Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Delete obsolete documentation and workflows; implement new agent management features in the agent home page; enhance biometric consent flow; update texture inspector functionality; improve model validation processes; refine build and deployment configurations.
nirholas1ac5e3f2571b
diff --git a/.claude/agents/browser-verifier.md b/.claude/agents/browser-verifier.mddeleted file mode 100644index 8c19e1650..000000000--- a/.claude/agents/browser-verifier.md+++ /dev/null@@ -1,40 +0,0 @@-----name: browser-verifier-description: Use after a UI change to confirm the page actually loads and the feature is reachable. Starts the dev server if not running, fetches the target route(s), checks HTTP status, scans returned HTML for the expected element/text markers, and reports pass/fail. Does not edit code.-tools: Bash, Read, Grep-model: sonnet------You verify that UI changes are actually live and reachable. You do not write code.--# Inputs the caller should give you--- Route(s) to verify (e.g. `/agent-detail.html?id=foo`).-- Markers to look for in the returned HTML (selector strings, ids, visible text).--If the caller did not specify, infer from `git diff --stat` which routes are affected and pick the obvious ones.--# Procedure--1. **Check dev server.**- `curl -sfI http://localhost:3000/ >/dev/null 2>&1 && echo UP || echo DOWN`-2. **Start if needed.**- ```- ( cd /workspaces/3D-Agent && nohup npm run dev > /tmp/3d-agent-dev.log 2>&1 & )- ```- Then poll for up to 30s: `until curl -sfI http://localhost:3000/ >/dev/null 2>&1; do sleep 1; done`.-3. **Fetch each route.** `curl -sS -o /tmp/page.html -w '%{http_code}\n' "http://localhost:3000<route>"`. Anything other than 200 is a fail.-4. **Marker scan.** `grep -F "<marker>" /tmp/page.html` for each marker. A miss is a fail.-5. **Console-error proxy.** Tail `/tmp/3d-agent-dev.log` for `error`, `ERR`, or stack traces produced during the fetch. Report any.-6. **Report.**--```-# Browser verifier-- Server: UP|started-- /route1 → 200, markers [a,b] OK-- /route2 → 500 FAIL-- Dev log errors: <list or none>-Verdict: PASS | FAIL-```--If FAIL, the calling agent must fix and re-run you. Do not soften failures.diff --git a/.claude/agents/completionist.md b/.claude/agents/completionist.mddeleted file mode 100644index b31cc7267..000000000--- a/.claude/agents/completionist.md+++ /dev/null@@ -1,61 +0,0 @@-----name: completionist-description: Use proactively before stopping any feature task. Audits recently changed files for laziness — mocks, fake data, TODOs, stubs, unhandled states, missing wiring, debug noise — runs build/tests, and returns a punch list of every item the implementing agent must fix before claiming done. Drops a freshness marker so the Stop hook accepts the audit. Do not call to plan or research; this agent only audits work-in-progress.-tools: Read, Grep, Glob, Bash-model: sonnet------You are the completionist auditor for the 3D-Agent workspace. Your only job is to verify a feature is genuinely shipped, not half-built.--# Inputs you must gather (parallel)--- `git status --short`-- `git diff --stat`-- `git diff` (full)--If the diff is empty, return: `No changes to audit.` and still drop the marker.--# What you check (every changed source file)--For each changed file under `src/`, `api/`, `workers/`, `sdk/`, `services/`, `chat/`, `avatar/`, `character-studio/`, `pump-fun-skills/`, or any root `.html`/`.js`/`.ts`/`.css`:--1. **Mocks / fakes / sample data** — `mockData`, `fakeUser`, `dummyAgents`, `sampleResponse`, hardcoded placeholder arrays, lorem ipsum.-2. **TODO / FIXME / HACK / XXX / "implement later" / "wire up later" / "for now," / "in a real implementation"** — any deferral comment.-3. **Stub functions** — empty bodies, `return null;` placeholder returns, `throw new Error("not implemented")`.-4. **Commented-out code** — multi-line `/* ... */` of disabled code, or 3+ consecutive `// code` lines.-5. **Fake async** — `setTimeout` simulating loading, fake progress, `await new Promise(r => setTimeout(...))` not tied to a real operation.-6. **Missing wiring** — every new export must be referenced. Use Grep to confirm: `grep -rn "<exportName>" src/ api/ chat/ avatar/ workers/ *.html 2>/dev/null`.-7. **Missing UI states** — for UI changes, confirm loading + empty + error states exist and are real (not faked).-8. **Console noise** — leftover `console.log` debug statements (not structured logging).-9. **Real API usage** — if the feature touches data, confirm an actual `fetch`/SDK call exists. No hardcoded responses.-10. **Hardcoded URLs / secrets** — no `localhost`, `127.0.0.1`, API keys baked into source.-11. **Test/build sanity** — run `npm test --silent 2>&1 | tail -30` and `npm run build 2>&1 | tail -40`. Report failures verbatim.--# Output format (single markdown report)--```-# Completionist audit--**Files changed:** N-**Verdict:** PASS | FAIL--## Punch list-- [file:line] <issue> — <what to do>--## Verification run-- npm test: <pass/fail/skipped + 1-line summary>-- npm run build: <pass/fail/skipped + 1-line summary>-- Wiring check: <each new export → where it's used, or NOT WIRED>-```--If verdict is PASS, the punch list is empty. If FAIL, every item is required, not optional. No softening language.--# After reporting--Always finish by dropping the freshness marker so the Stop hook accepts the audit:--```-mkdir -p /workspaces/3D-Agent/.claude/state && touch /workspaces/3D-Agent/.claude/state/completionist.lastrun-```--You do not edit code. You only audit, run checks, report, and mark.diff --git a/.claude/agents/implementer.md b/.claude/agents/implementer.mddeleted file mode 100644index 11a276183..000000000--- a/.claude/agents/implementer.md+++ /dev/null@@ -1,40 +0,0 @@-----name: implementer-description: Use this agent for feature work that needs to be shipped end-to-end. The implementer reads the task, locates the relevant code, writes the real implementation (no mocks, no TODOs, no stubs), wires it into the UI / API surface, runs build and tests, exercises the feature, then invokes the completionist subagent and clears its punch list before returning. Use whenever the user asks to "build", "implement", "wire up", "ship", "fix completely", or "finish" a feature.-tools: Read, Edit, Write, Bash, Grep, Glob-model: opus------You are the implementer for the 3D-Agent workspace. You ship complete features. Half-built work is a failure mode you do not produce.--# Operating rules (these override your defaults)--- **No clarifying questions.** Pick the highest-leverage interpretation and proceed.-- **No mocks, no fake data, no sample arrays, no TODOs, no `throw new Error("not implemented")`, no commented-out code, no `setTimeout` fake-loading, no hardcoded localhost URLs.**-- Real APIs only. Credentials live in `.env`, `vercel env`, or workers — find them, do not invent them.-- Every new export must be imported and reachable from the running app. Wiring is part of the task.-- Loading / empty / error states for any UI change. Real, not faked.-- Errors handled at boundaries (network, user input). Internal code trusts itself.--# Workflow (every task)--1. **Orient.** `git status`, read the relevant files end-to-end (not excerpts), understand the surface area.-2. **Plan in TodoWrite.** Break the task into concrete, verifiable steps.-3. **Implement.** Real code only. Wire it into the call graph. Update related call sites.-4. **Verify locally.**- - `npm run build 2>&1 | tail -40` must succeed.- - `npm test --silent 2>&1 | tail -40` must pass (when tests exist).- - For UI features: start `npm run dev` in the background, `curl -sf http://localhost:3000/<page>` to confirm the page renders, then kill the dev server.-5. **Audit.** Invoke the `completionist` subagent against your diff. Read its punch list.-6. **Clear punch list.** Fix every flagged item. Re-run completionist if you made non-trivial changes. Do not stop with a non-empty punch list.-7. **Report.** Two sentences: what shipped, what's wired. Then exit.--# Constraints on tools--- Use Edit/Write for code, Bash for verification only.-- Keep responses short. The user reads diffs, not narration.-- Never claim "done" without the completionist's PASS verdict in this same run.--# Style--Professional. No emojis. No filler. No "great question" energy. Ship the work.diff --git a/.claude/hooks/done-gate.sh b/.claude/hooks/done-gate.shdeleted file mode 100755index 6d114b6b5..000000000--- a/.claude/hooks/done-gate.sh+++ /dev/null@@ -1,146 +0,0 @@-#!/usr/bin/env bash-# Stop hook. Three checks before allowing the agent to stop:-# 1) No lazy patterns in modified/untracked source files.-# 2) `npm run build` passes (compile-level proof of correctness).-# 3) The completionist subagent has been run since the last source-file change-# (proof the agent actually audited its work).-#-# Any failure exits 2 with a short reason so the agent retries and fixes.--set -euo pipefail--REPO=/workspaces/3D-Agent-cd "$REPO"--LOG_DIR="$REPO/.claude/state"-mkdir -p "$LOG_DIR"-MARKER="$LOG_DIR/completionist.lastrun"-LAST_BUILD="$LOG_DIR/build.last"--fail() {- printf '\nStop blocked by done-gate. %s\n' "$1" >&2- exit 2-}--# Determine whether there is in-flight work at all. If not, allow stop.-changed=$(git ls-files --modified --others --exclude-standard 2>/dev/null \- | grep -Ev '(^|/)(node_modules|dist|dist-lib|public|\.claude/state)(/|$)' \- | grep -Ev '\.(lock|log|map)$' \- || true)--if [ -z "$changed" ]; then- exit 0-fi--# --- 1. Lazy-pattern scan on ADDED lines only ---------------------------------# We only care about laziness the agent introduced, not pre-existing tech debt.-# Parse `git diff` for added lines (prefixed with `+`, not `+++`), and grep-# those for the lazy patterns. Untracked files are wholly added.-LAZY_RE='(^|[^A-Za-z0-9_])(TODO|FIXME|HACK)([^A-Za-z0-9_]|$)|not[[:space:]]*implemented|throw[[:space:]]+new[[:space:]]+Error\([^)]*implement|(mockData|fakeData|dummyData|sampleData|placeholderData)|lorem[[:space:]]*ipsum|implement[[:space:]]+(this|me|later)|wire[[:space:]]+(this|it|up)[[:space:]]+later|in[[:space:]]+(a[[:space:]]+)?real[[:space:]]+implementation|(^|[^A-Za-z0-9_])debugger([^A-Za-z0-9_]|$)'--violations=()--# Tracked-file additions (vs HEAD). Header-aware: track current file from +++ b/<path>.-while IFS= read -r line; do- case "$line" in- '+++ b/'*) cur_file=${line#+++ b/} ;;- '+++ /dev/null') cur_file='' ;;- '+'*)- add=${line#+}- case "$add" in '++') continue ;; esac- # Skip diff headers that look like '+++'- [ -z "$cur_file" ] && continue- # Skip exempt paths/extensions- case "$cur_file" in- .claude/*|*/.claude/*) continue ;;- memory/*|*/memory/*) continue ;;- node_modules/*|*/node_modules/*) continue ;;- dist/*|*/dist/*|dist-lib/*|*/dist-lib/*|public/*|*/public/*) continue ;;- tests/*|*/tests/*|test/*|*/test/*|*.test.*|*.spec.*) continue ;;- specs/*|*/specs/*|docs/*|*/docs/*) continue ;;- *.md|*.json|*.lock|*.svg|*.png|*.jpg|*.jpeg|*.gif|*.webp|*.glb|*.gltf|*.wasm|*.ico|*.woff|*.woff2|*.ttf|*.map) continue ;;- esac- if printf '%s' "$add" | grep -Eqi "$LAZY_RE"; then- violations+=("$cur_file: + $add")- fi- ;;- esac-done < <(git diff --no-color HEAD 2>/dev/null || true)--# Untracked files: every line is "added".-while IFS= read -r f; do- [ -n "$f" ] || continue- [ -f "$f" ] || continue- case "$f" in- .claude/*|*/.claude/*) continue ;;- memory/*|*/memory/*) continue ;;- node_modules/*|*/node_modules/*) continue ;;- dist/*|*/dist/*|dist-lib/*|*/dist-lib/*|public/*|*/public/*) continue ;;- tests/*|*/tests/*|test/*|*/test/*|*.test.*|*.spec.*) continue ;;- specs/*|*/specs/*|docs/*|*/docs/*) continue ;;- *.md|*.json|*.lock|*.svg|*.png|*.jpg|*.jpeg|*.gif|*.webp|*.glb|*.gltf|*.wasm|*.ico|*.woff|*.woff2|*.ttf|*.map) continue ;;- esac- while IFS= read -r line; do- violations+=("$f: $line")- done < <(grep -nEi "$LAZY_RE" "$f" 2>/dev/null || true)-done < <(git ls-files --others --exclude-standard 2>/dev/null)--if [ ${#violations[@]} -gt 0 ]; then- {- printf 'Lazy patterns introduced in this work:\n'- for v in "${violations[@]}"; do printf ' %s\n' "$v"; done- printf '\nFix these (real implementations, no stubs), then stop.\n'- } >&2- exit 2-fi--# --- 2. Completionist freshness -----------------------------------------------# The completionist agent must have been invoked AFTER the most recent change to-# any tracked source file in this batch. Implementer agents drop the marker by-# touching the file as part of their wrap-up.-newest_change=0-while IFS= read -r f; do- [ -f "$f" ] || continue- ts=$(stat -c %Y "$f" 2>/dev/null || echo 0)- [ "$ts" -gt "$newest_change" ] && newest_change=$ts-done <<< "$changed"--marker_ts=0-[ -f "$MARKER" ] && marker_ts=$(stat -c %Y "$MARKER" 2>/dev/null || echo 0)--if [ "$marker_ts" -lt "$newest_change" ]; then- fail "Completionist audit not run since last source change.-Run the \`completionist\` subagent against the current diff, fix every punch-list item, then \`touch .claude/state/completionist.lastrun\` to record completion."-fi--# --- 3. Build must pass --------------------------------------------------------# Skip if package.json hasn't changed AND no JS/TS/CSS/HTML in changed source.-needs_build=0-if printf '%s\n' "$changed" | grep -Eq '\.(js|mjs|cjs|ts|tsx|jsx|css|html|json)$'; then- needs_build=1-fi--if [ "$needs_build" -eq 1 ]; then- # Clear stale dist so Vite's emptyOutDir doesn't hit ENOTEMPTY on sub-dirs- # that were populated by other scripts (e.g. build:animations, build:rider).- node -e "- const fs = require('fs');- const path = require('path');- const dist = path.join(process.cwd(), 'dist');- try { fs.rmSync(dist, { recursive: true, force: true }); } catch (_) {}- fs.mkdirSync(dist, { recursive: true });- " 2>/dev/null || true-- if ! out=$(timeout 240s npm run build --silent 2>&1); then- {- printf 'Build failed (npm run build):\n'- printf '%s\n' "$out" | tail -40- printf '\nFix the build, then stop.\n'- } >&2- printf '%s\n' "$out" > "$LAST_BUILD" || true- exit 2- fi- date -u +%FT%TZ > "$LAST_BUILD"-fi--exit 0diff --git a/.claude/hooks/no-shortcuts.sh b/.claude/hooks/no-shortcuts.shdeleted file mode 100755index 339ac295d..000000000--- a/.claude/hooks/no-shortcuts.sh+++ /dev/null@@ -1,90 +0,0 @@-#!/usr/bin/env bash-# PreToolUse hook: blocks Write/Edit that introduce mocks, fakes, TODOs, stubs,-# debug noise, or hardcoded secrets/dev URLs.-# Exits 2 with stderr message to block the tool call.--set -euo pipefail--input="$(cat)"--tool_name=$(printf '%s' "$input" | jq -r '.tool_name // empty')-file_path=$(printf '%s' "$input" | jq -r '.tool_input.file_path // empty')--case "$tool_name" in- Write|Edit|MultiEdit) ;;- *) exit 0 ;;-esac--# Skip the hook script itself, CLAUDE.md, memory files, docs, tests, configs.-case "$file_path" in- */.claude/hooks/*) exit 0 ;;- */.claude/agents/*) exit 0 ;;- */CLAUDE.md) exit 0 ;;- */memory/*) exit 0 ;;- *.md) exit 0 ;;- */tests/*|*/test/*|*.test.*|*.spec.*) exit 0 ;;- */node_modules/*) exit 0 ;;- */dist/*|*/dist-lib/*) exit 0 ;;- */vitest.config.*|*/vite.config.*) exit 0 ;;-esac--# Collect the candidate new content from any of the supported tool shapes.-content=$(printf '%s' "$input" | jq -r '- [- (.tool_input.content // empty),- (.tool_input.new_string // empty),- ((.tool_input.edits // []) | map(.new_string // "") | join("\n"))- ] | join("\n")-')--if [ -z "$content" ]; then- exit 0-fi--violations=()--check() {- local pattern="$1" label="$2"- if printf '%s' "$content" | grep -Eqi "$pattern"; then- violations+=("$label")- fi-}--# Lazy / placeholder patterns-check '(^|[^A-Za-z0-9_])TODO([^A-Za-z0-9_]|$)' 'TODO comment'-check '(^|[^A-Za-z0-9_])FIXME([^A-Za-z0-9_]|$)' 'FIXME comment'-check '(^|[^A-Za-z0-9_])XXX([^A-Za-z0-9_]|$)' 'XXX comment'-check '(^|[^A-Za-z0-9_])HACK([^A-Za-z0-9_]|$)' 'HACK comment'-check 'not[[:space:]]*implemented' 'not-implemented stub'-check 'throw[[:space:]]+new[[:space:]]+Error\([^)]*implement' 'throw not-implemented'-check '(mockData|fakeData|dummyData|sampleData|placeholderData)' 'mock/fake/dummy/sample/placeholder data identifier'-check 'lorem[[:space:]]*ipsum' 'lorem ipsum'-check 'implement[[:space:]]+(this|me|later)' '"implement this/me/later" comment'-check 'wire[[:space:]]+(this|it|up)[[:space:]]+later' '"wire up later" comment'-check 'in[[:space:]]+(a[[:space:]]+)?real[[:space:]]+implementation' '"in real implementation" comment'-check 'for[[:space:]]+now[[:space:]]*[,:]' '"for now" shortcut comment'-check 'placeholder[[:space:]]+(for|until|response|value)' '"placeholder for/until" comment'-check 'simulat(e|ed|ing)[[:space:]]+(api|response|fetch|loading|delay|network)' 'simulated API/response/loading'--# Debug noise that should not ship-check '(^|[^A-Za-z0-9_])debugger([^A-Za-z0-9_]|$)' 'debugger statement'-check 'console\.(log|debug|info)\([^)]*("|`)(DEBUG|TODO|TEST|XXX|HERE|wtf)' 'debug console.* call'--# Hardcoded secrets / dev URLs in source-check 'sk_test_[A-Za-z0-9]+' 'hardcoded Stripe test key'-check 'sk_live_[A-Za-z0-9]+' 'hardcoded Stripe live key'-check 'AKIA[0-9A-Z]{16}' 'hardcoded AWS access key id'-check 'AIza[0-9A-Za-z_-]{20,}' 'hardcoded Google API key'-check '(http|ws)s?://localhost(:[0-9]+)?' 'hardcoded localhost URL (use env/config)'-check '(http|ws)s?://127\.0\.0\.1(:[0-9]+)?' 'hardcoded 127.0.0.1 URL (use env/config)'--if [ ${#violations[@]} -gt 0 ]; then- printf 'Blocked by no-shortcuts hook (%s):\n' "$file_path" >&2- for v in "${violations[@]}"; do- printf ' - %s\n' "$v" >&2- done- printf 'Per CLAUDE.md: ship real, complete code. Implement it for real.\n' >&2- exit 2-fi--exit 0diff --git a/.claude/hooks/session-start.sh b/.claude/hooks/session-start.shdeleted file mode 100755index bf4611299..000000000--- a/.claude/hooks/session-start.sh+++ /dev/null@@ -1,16 +0,0 @@-#!/usr/bin/env bash-# SessionStart hook: prints the operating contract so every new session sees it.-set -euo pipefail--cat <<'EOF'-=== 3D-Agent operating contract (loaded) ===-1. Execute, never interview. No clarifying questions for execution tasks.-2. No mocks, no fake data, no TODOs, no stubs, no commented-out code, no placeholder fallback arrays.-3. Real APIs only. Implement features end-to-end, including loading/empty/error states.-4. Definition of done: code wired, dev server exercised, no console errors, tests pass.-5. Before Stop on any feature task: invoke the `completionist` subagent and clear its punch list.-6. Communication: short. State what you did, what's next. No trailing recaps, no emojis.--Hooks active: no-shortcuts (PreToolUse) | done-gate (Stop) | session-start | user-prompt-submit-Subagents available: completionist | implementer | browser-verifier-EOFdiff --git a/.claude/hooks/user-prompt-submit.sh b/.claude/hooks/user-prompt-submit.shdeleted file mode 100755index 819455ec9..000000000--- a/.claude/hooks/user-prompt-submit.sh+++ /dev/null@@ -1,23 +0,0 @@-#!/usr/bin/env bash-# UserPromptSubmit hook: when the user asks for execution work, inject a-# terse reminder so the agent does not regress to interview-mode.-set -euo pipefail--input="$(cat)"-prompt=$(printf '%s' "$input" | jq -r '.prompt // empty')--if [ -z "$prompt" ]; then- exit 0-fi--# Trigger only on execution-shaped requests.-if printf '%s' "$prompt" | grep -Eqi '\b(build|implement|wire|ship|fix|add|create|make|finish|complete|hook up|integrate|deploy|migrate|refactor)\b'; then- cat <<'EOF'-[contract reminder]-Execute. Do not ask clarifying questions — pick the highest-leverage path and ship.-No mocks, no fake data, no TODOs, no stubs. Real APIs only.-Before claiming done: run dev/build, verify wiring, invoke `completionist` subagent, clear punch list.-EOF-fi--exit 0diff --git a/.claude/output-styles/ship-mode.md b/.claude/output-styles/ship-mode.mddeleted file mode 100644index a3ac73bff..000000000--- a/.claude/output-styles/ship-mode.md+++ /dev/null@@ -1,30 +0,0 @@-----name: Ship Mode-description: Maximum-execution output style for the 3D-Agent workspace. Terse, no clarifying questions, complete features only.------You are operating in Ship Mode. The user wants completed work, not commentary.--# Rules--- **Never ask clarifying questions for execution requests.** Pick the highest-leverage interpretation and proceed. If something is genuinely ambiguous, ship the most reasonable version and note the assumption in one line at the end.-- **No mocks, no fake data, no TODO/FIXME/HACK comments, no stub functions, no `throw new Error("not implemented")`, no commented-out code, no hardcoded localhost URLs.** Real APIs and real implementations only.-- **Definition of done.** Code is written, wired into the call graph, build passes, tests pass, UI features are exercised in a real browser via the browser-verifier subagent, and the completionist subagent has issued a PASS verdict against the diff.-- **Subagents do the heavy lifting.** For any non-trivial feature, dispatch the `implementer` subagent. For UI verification, dispatch `browser-verifier`. Before stopping, always dispatch `completionist`.--# Tone--- One short sentence before each tool batch describing what you're about to do.-- No headers, bullet lists, or multi-paragraph recaps unless the user asks for one.-- End with one or two sentences: what shipped, what's next.-- No emojis. No "great question". No "I hope this helps". No filler.-- File references use `[name](path)` markdown links, never backticks.--# Forbidden phrases--- "Would you like me to…"-- "Should I also…"-- "Let me know if…"-- "Just to confirm…"-- "I'll go ahead and…" (just do it silently)-- "Here's a summary of what I did:" (the diff is the summary)diff --git a/.claude/settings.json b/.claude/settings.jsondeleted file mode 100644index 91da2c578..000000000--- a/.claude/settings.json+++ /dev/null@@ -1,290 +0,0 @@-{- "$schema": "https://json.schemastore.org/claude-code-settings.json",-- "permissions": {- "defaultMode": "acceptEdits",-- "allow": [- "Read",- "Glob",- "Grep",- "WebFetch",- "WebSearch",-- "Bash(npm *)",- "Bash(npx *)",- "Bash(pnpm *)",- "Bash(yarn *)",- "Bash(node *)",-- "Bash(prettier *)",- "Bash(vite *)",- "Bash(vitest *)",-- "Bash(forge build*)",- "Bash(forge test*)",- "Bash(forge fmt*)",- "Bash(forge install*)",- "Bash(forge update*)",- "Bash(forge snapshot*)",- "Bash(forge coverage*)",- "Bash(forge inspect*)",- "Bash(forge remappings*)",- "Bash(forge clean*)",- "Bash(cast *)",-- "Bash(vercel *)",-- "Bash(git status*)",- "Bash(git log*)",- "Bash(git diff*)",- "Bash(git show*)",- "Bash(git add*)",- "Bash(git commit*)",- "Bash(git push)",- "Bash(git push origin *)",- "Bash(git push -u origin *)",- "Bash(git push --set-upstream origin *)",- "Bash(git pull*)",- "Bash(git fetch*)",- "Bash(git checkout*)",- "Bash(git switch*)",- "Bash(git branch*)",- "Bash(git merge*)",- "Bash(git rebase*)",- "Bash(git stash*)",- "Bash(git restore*)",- "Bash(git reset)",- "Bash(git reset HEAD*)",- "Bash(git reset --soft*)",- "Bash(git reset --mixed*)",- "Bash(git remote*)",- "Bash(git tag*)",- "Bash(git ls-files*)",- "Bash(git ls-tree*)",- "Bash(git rev-parse*)",- "Bash(git rev-list*)",- "Bash(git describe*)",- "Bash(git blame*)",- "Bash(git worktree*)",- "Bash(git config --get*)",- "Bash(git config --list*)",-- "Bash(ls*)",- "Bash(pwd)",- "Bash(cd *)",- "Bash(cat *)",- "Bash(head *)",- "Bash(tail *)",- "Bash(wc *)",- "Bash(sort *)",- "Bash(uniq *)",- "Bash(diff *)",- "Bash(file *)",- "Bash(stat *)",- "Bash(du *)",- "Bash(tree *)",- "Bash(find *)",- "Bash(grep *)",- "Bash(rg *)",- "Bash(awk *)",- "Bash(sed *)",- "Bash(jq *)",- "Bash(which *)",- "Bash(whereis *)",- "Bash(command -v *)",- "Bash(env)",- "Bash(printenv*)",- "Bash(echo *)",- "Bash(true)",- "Bash(false)",- "Bash(date*)",- "Bash(basename *)",- "Bash(dirname *)",- "Bash(realpath *)",- "Bash(readlink *)",-- "Bash(mkdir *)",- "Bash(cp *)",- "Bash(mv *)",- "Bash(touch *)",- "Bash(ln -s *)",- "Bash(chmod *)",-- "Bash(curl -s *)",- "Bash(curl -I *)",- "Bash(curl --head *)",- "Bash(curl -o *)",- "Bash(curl -sSL *)",- "Bash(curl -sL *)",- "Bash(wget *)",-- "Bash(tar *)",- "Bash(unzip *)",- "Bash(zip *)",- "Bash(gzip *)",- "Bash(gunzip *)",-- "Bash(python *)",- "Bash(python3 *)",- "Bash(pip *)",- "Bash(pip3 *)",-- "Bash(ps *)",- "Bash(kill %*)",- "Bash(pgrep *)",- "Bash(lsof *)",- "Bash(netstat *)",- "Bash(host *)",- "Bash(dig *)",- "Bash(nslookup *)"- ],-- "deny": [- "Bash(rm -rf*)",- "Bash(rm -fr*)",- "Bash(rm -r *)",- "Bash(rm -R *)",- "Bash(rm --recursive*)",- "Bash(sudo*)",- "Bash(doas*)",- "Bash(su *)",- "Bash(su)",-- "Bash(git push --force*)",- "Bash(git push -f*)",- "Bash(git push --force-with-lease*)",- "Bash(git push --mirror*)",- "Bash(git push --delete*)",- "Bash(git push origin --delete*)",- "Bash(git push origin :*)",- "Bash(git push origin +*)",-- "Bash(git reset --hard*)",- "Bash(git clean -f*)",- "Bash(git clean -df*)",- "Bash(git clean -xf*)",- "Bash(git clean -xdf*)",- "Bash(git clean -fd*)",- "Bash(git clean -fx*)",- "Bash(git clean -fdx*)",- "Bash(git branch -D*)",- "Bash(git branch --delete --force*)",- "Bash(git checkout -- *)",- "Bash(git checkout . *)",- "Bash(git checkout .)",- "Bash(git restore --source=*)",- "Bash(git restore .)",- "Bash(git restore . *)",- "Bash(git update-ref -d*)",- "Bash(git filter-branch*)",- "Bash(git filter-repo*)",- "Bash(git reflog delete*)",- "Bash(git reflog expire*)",- "Bash(git gc --prune=now*)",-- "Bash(forge script * --broadcast*)",- "Bash(forge script *--broadcast*)",- "Bash(cast send *)",-- "Bash(vercel --prod*)",- "Bash(vercel deploy --prod*)",- "Bash(vercel rm*)",- "Bash(vercel remove*)",- "Bash(vercel alias rm*)",- "Bash(npm publish*)",- "Bash(yarn publish*)",- "Bash(pnpm publish*)",-- "Bash(curl * | sh*)",- "Bash(curl * | bash*)",- "Bash(curl *|sh*)",- "Bash(curl *|bash*)",- "Bash(wget * | sh*)",- "Bash(wget * | bash*)",- "Bash(wget *-O - | sh*)",- "Bash(wget *-O- | sh*)",-- "Bash(dd if=*)",- "Bash(dd of=*)",- "Bash(mkfs*)",- "Bash(fdisk*)",- "Bash(parted*)",- "Bash(shutdown*)",- "Bash(reboot*)",- "Bash(halt*)",- "Bash(poweroff*)",- "Bash(init *)",-- "Edit(.env)",- "Edit(.env.local)",- "Edit(.env.*.local)",- "Edit(.env.production)",- "Edit(.env.production.local)",- "Edit(**/.env)",- "Edit(**/.env.local)",- "Edit(**/.env.*.local)",- "Write(.env)",- "Write(.env.local)",- "Write(.env.*.local)",- "Write(**/.env)",- "Write(**/.env.local)",- "Write(**/.env.*.local)"- ]- },-- "includeCoAuthoredBy": true,- "respectGitignore": true,-- "outputStyle": "Ship Mode",-- "statusLine": {- "type": "command",- "command": "/workspaces/3D-Agent/.claude/statusline.sh",- "padding": 0- },-- "hooks": {- "SessionStart": [- {- "hooks": [- {- "type": "command",- "command": "/workspaces/3D-Agent/.claude/hooks/session-start.sh"- }- ]- }- ],- "UserPromptSubmit": [- {- "hooks": [- {- "type": "command",- "command": "/workspaces/3D-Agent/.claude/hooks/user-prompt-submit.sh"- }- ]- }- ],- "PreToolUse": [- {- "matcher": "Write|Edit|MultiEdit",- "hooks": [- {- "type": "command",- "command": "/workspaces/3D-Agent/.claude/hooks/no-shortcuts.sh"- }- ]- }- ],- "Stop": [- {- "hooks": [- {- "type": "command",- "command": "/workspaces/3D-Agent/.claude/hooks/done-gate.sh"- }- ]- }- ]- }-}diff --git a/.claude/state/build.last b/.claude/state/build.lastdeleted file mode 100644index 61cfa35df..000000000--- a/.claude/state/build.last+++ /dev/null@@ -1 +0,0 @@-2026-05-04T04:46:12Zdiff --git a/.claude/state/completionist.lastrun b/.claude/state/completionist.lastrundeleted file mode 100644index e69de29bb..000000000diff --git a/.claude/statusline.sh b/.claude/statusline.shdeleted file mode 100755index 511fb53a5..000000000--- a/.claude/statusline.sh+++ /dev/null@@ -1,49 +0,0 @@-#!/usr/bin/env bash-# Statusline: shows enforcement state at a glance.-set -euo pipefail--input="$(cat)"-model=$(printf '%s' "$input" | jq -r '.model.display_name // .model.id // "claude"')-cwd=$(printf '%s' "$input" | jq -r '.workspace.current_dir // .cwd // ""')--cd "${cwd:-/workspaces/3D-Agent}" 2>/dev/null || true--branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "-")-dirty=$(git status --porcelain 2>/dev/null | wc -l | tr -d ' ')--marker=/workspaces/3D-Agent/.claude/state/completionist.lastrun-if [ -f "$marker" ]; then- newest=0- while IFS= read -r f; do- [ -f "$f" ] || continue- ts=$(stat -c %Y "$f" 2>/dev/null || echo 0)- [ "$ts" -gt "$newest" ] && newest=$ts- done < <(git ls-files --modified --others --exclude-standard 2>/dev/null)- mts=$(stat -c %Y "$marker" 2>/dev/null || echo 0)- if [ "$mts" -ge "$newest" ]; then- audit="audit:OK"- else- audit="audit:STALE"- fi-else- audit="audit:none"-fi--build_log=/workspaces/3D-Agent/.claude/state/build.last-if [ -f "$build_log" ]; then- bts=$(date -d "$(cat "$build_log" 2>/dev/null)" +%s 2>/dev/null || echo 0)- if [ "$bts" -gt 0 ]; then- build="build:OK"- else- build="build:?"- fi-else- build="build:?"-fi--printf '%s | %s%s | ship-mode | %s | %s' \- "$model" \- "$branch" \- "$([ "$dirty" -gt 0 ] && printf ' *%s' "$dirty")" \- "$audit" \- "$build"diff --git a/.github/FUNDING.yml b/.github/FUNDING.ymldeleted file mode 100644index 2ccff69ee..000000000--- a/.github/FUNDING.yml+++ /dev/null@@ -1 +0,0 @@-github: [nirholas]diff --git a/.github/prompts/README.md b/.github/prompts/README.mddeleted file mode 100644index 0bd744b7e..000000000--- a/.github/prompts/README.md+++ /dev/null@@ -1,78 +0,0 @@-# Prompts--Task specs for agents working on three.ws. Each prompt is a self-contained brief: problem, implementation steps, validation, and what **not** to do.--Prompts are prioritized by the product stack from [memory/project_vision.md](../../.. /home/codespace/.claude/projects/-workspaces-3D/memory/project_vision.md). When in doubt, work the lowest-numbered unfinished `stack-*` prompt first.--## Priority stack prompts--### Layer 1 — Wallet auth 100%--- [stack-01-siwe-wallet-login.md](stack-01-siwe-wallet-login.md)-- [stack-02-privy-unified-auth.md](stack-02-privy-unified-auth.md)-- [stack-03-auth-session-recovery.md](stack-03-auth-session-recovery.md)-- [stack-04-auth-error-ux.md](stack-04-auth-error-ux.md)--### Layer 2 — Selfie → agent creation (the magic moment)--- [stack-05-selfie-capture.md](stack-05-selfie-capture.md)-- [stack-06-face-to-avatar-backend.md](stack-06-face-to-avatar-backend.md)-- [stack-07-avatar-creation-progress.md](stack-07-avatar-creation-progress.md)-- [stack-08-avatar-save-and-slug.md](stack-08-avatar-save-and-slug.md)-- [stack-28-first-run-tour.md](stack-28-first-run-tour.md) (onboarding)-- [stack-29-biometric-consent.md](stack-29-biometric-consent.md) (legal, ship with stack-05)--### Layer 3 — Edit avatar--- [stack-09-avatar-editor-shell.md](stack-09-avatar-editor-shell.md)-- [stack-10-avatar-identity-tab.md](stack-10-avatar-identity-tab.md)-- [stack-11-avatar-skills-tab.md](stack-11-avatar-skills-tab.md)-- [stack-12-avatar-memory-seed.md](stack-12-avatar-memory-seed.md)-- [stack-13-avatar-animation-tab.md](stack-13-avatar-animation-tab.md)-- [stack-14-avatar-mesh-replace.md](stack-14-avatar-mesh-replace.md)--### Layer 4 — View + embed--- [stack-15-agent-public-page.md](stack-15-agent-public-page.md)-- [stack-16-embed-code-generator.md](stack-16-embed-code-generator.md)-- [stack-17-kiosk-mode-polish.md](stack-17-kiosk-mode-polish.md)-- [stack-18-embed-telemetry.md](stack-18-embed-telemetry.md)-- [stack-27-agents-gallery.md](stack-27-agents-gallery.md) (discovery)--### Layer 5 — Embed in Claude.ai & LobeHub (the novel integration)--- [stack-19-artifacts-single-file.md](stack-19-artifacts-single-file.md)-- [stack-20-chat-plugin.md](stack-20-chat-plugin.md)-- [stack-21-host-chat-bridge.md](stack-21-host-chat-bridge.md)-- [stack-22-mcp-embodied-responses.md](stack-22-mcp-embodied-responses.md)--### Layer 6 — Onchain portable identity (the novel unlock)--- [stack-23-manifest-to-ipfs.md](stack-23-manifest-to-ipfs.md)-- [stack-24-onchain-identity-register.md](stack-24-onchain-identity-register.md)-- [stack-25-hydrate-from-chain.md](stack-25-hydrate-from-chain.md)-- [stack-26-signed-action-log.md](stack-26-signed-action-log.md)--## Side tasks (lower priority — do NOT rat-hole on these while stack is broken)--Existing viewer/feature prompts: ai-model-analysis, ar-quick-look, cli-tool, material-editor, measurement-tools, scene-graph-explorer, screenshot-video-export, side-by-side-diff, texture-inspector, file-format-expansion, add-tests, complete-mcp-tools.--## Stale — do not use--These describe work already done or targeting deleted files:--- ai-chat-agent.md (targets deleted src/avaturn-agent.js)-- cleanup-dead-code.md (already applied)-- create-agent-card.md (file now exists)-- fix-security-xss.md (already fixed)-- fix-validator-lightbox.md (already fixed)-- deploy-erc8004-contracts.md (contracts deployed)-- complete-openapi-spec.md (spec fully documented)-- update-docs.md (references deleted files)--## How to use a prompt--1. Read the prompt top to bottom.-2. Confirm against [CLAUDE.md](../../CLAUDE.md) — zero-dep, native DOM, tabs, reuse auth helpers.-3. Ship the prompt's scope and nothing more. "Do not do this" sections are load-bearing.-4. Verify via the prompt's Validation checklist before declaring done.diff --git a/.github/prompts/add-tests.md b/.github/prompts/add-tests.mddeleted file mode 100644index 17489f9d6..000000000--- a/.github/prompts/add-tests.md+++ /dev/null@@ -1,143 +0,0 @@-----mode: agent-description: 'Create test infrastructure with unit tests, integration tests, and CI'------# Add Test Infrastructure--## Problem--`package.json` defines `"test": "node test/gen_test.js"` but no `test/` directory exists. There are zero tests in the project.--## Implementation--### 1. Test Framework Setup--Install Vitest (matches the Vite build system):--```bash-npm install -D vitest @testing-library/dom jsdom-```--Update `package.json`:--```json-"scripts": {- "test": "vitest run",- "test:watch": "vitest",- "test:coverage": "vitest run --coverage"-}-```--Add Vitest config in `vite.config.js`:--```js-test: {- environment: 'jsdom',- globals: true,-}-```--### 2. Unit Tests--#### `test/environments.test.js`--- All environments have required fields (id, name)-- EXR environments have valid paths and `.exr` format-- No duplicate IDs or names--#### `test/validator.test.js`--- `escapeHTML()` escapes all dangerous characters-- `linkify()` converts URLs and emails to anchor tags-- `linkify()` does not create links from `javascript:` URIs-- `groupMessages()` correctly aggregates accessor messages-- `setResponse()` escapes `extras.title` (after XSS fix)--#### `test/ipfs.test.js`--- `resolveIpfsUrl()` correctly resolves `ipfs://` URIs-- `resolveIpfsUrl()` correctly resolves `ar://` URIs-- Fallback gateways are tried in order-- Non-IPFS URLs pass through unchanged--#### `test/erc8004/abi.test.js`--- ABI arrays are non-empty-- `agentRegistryId()` formats correctly: `eip155:{chainId}:{address}`-- All deployment entries have the three registry keys--#### `test/components/validator-report.test.js`--- Renders report with all severity levels-- Handles empty reports gracefully-- Renders extras (author, title, license) safely--### 3. Integration Tests--#### `test/viewer.test.js`--- Viewer constructor initializes without errors-- `updateBackground()` sets correct scene background-- `updateEnvironment()` handles all environment options-- Transparent background mode sets alpha correctly--#### `test/app.test.js`--- Hash parsing extracts model URL correctly-- IPFS URL detection works-- Arweave URL detection works--### 4. API Tests (if server is testable)--#### `test/api/mcp.test.js`--- JSON-RPC dispatch routes correctly-- `initialize` returns server info and protocol version-- `tools/list` returns the tool catalog-- Unknown methods return -32601 error-- Invalid JSON-RPC returns -32600 error--### 5. CI Integration--Create `.github/workflows/test.yml`:--```yaml-name: Test-on: [push, pull_request]-jobs:- test:- runs-on: ubuntu-latest- steps:- - uses: actions/checkout@v4- - uses: actions/setup-node@v4- with:- node-version: 20- - run: npm ci- - run: npm test- - run: npm run build-```--## File Structure--```-test/-├── environments.test.js-├── validator.test.js-├── ipfs.test.js-├── viewer.test.js-├── app.test.js-├── erc8004/-│ └── abi.test.js-├── components/-│ └── validator-report.test.js-└── api/- └── mcp.test.js-```--## Validation--- `npm test` runs all tests and passes-- `npm run test:coverage` generates coverage report-- CI workflow runs on push to main-- No test relies on network access (mock fetch where needed)diff --git a/.github/prompts/ai-chat-agent.md b/.github/prompts/ai-chat-agent.mddeleted file mode 100644index 123320f7a..000000000--- a/.github/prompts/ai-chat-agent.md+++ /dev/null@@ -1,130 +0,0 @@-----mode: agent-description: 'Upgrade the chat agent from pattern matching to real AI with LLM backend'------# AI-Powered Chat Agent--## Problem--`src/avaturn-agent.js` (NichAgent) uses hardcoded pattern matching with `if/else` chains — not actually AI-powered despite branding. It can answer ~15 predefined questions but falls apart on anything else.--## Implementation--### 1. LLM Backend (`api/chat.js`)--Create a server-side chat endpoint:--```-POST /api/chat-Body: { "message": "string", "context": { "model": "string", "validationReport": {} } }-Response: { "reply": "string", "actions": [] }-```--- Use OpenAI API (or compatible: Anthropic, Groq, local Ollama)-- System prompt includes:- - three.ws capabilities and feature knowledge- - Current loaded model info (name, stats, validation results)- - Available actions the agent can trigger in the viewer- - glTF format expertise for answering technical questions--### 2. Tool Use / Function Calling--The LLM can return structured actions that the frontend executes:--```json-{- "reply": "I've enabled wireframe mode and set the background to dark blue.",- "actions": [- { "type": "setWireframe", "value": true },- { "type": "setBgColor", "value": "#001133" },- { "type": "setAutoRotate", "value": true }- ]-}-```--Supported actions:--- `setWireframe`, `setSkeleton`, `setGrid` — display toggles-- `setBgColor`, `setTransparentBg` — background controls-- `setEnvironment` — change lighting environment-- `setAutoRotate` — toggle auto-rotation-- `takeScreenshot` — capture current view-- `loadModel` — load a model by URL-- `runValidation` — trigger validation-- `showMaterialEditor` — open editor panels--### 3. Context-Aware Responses--Pass model context to the LLM:--```js-const context = {- modelName: viewer.content?.name,- vertices: viewer.modelInfo?.vertices,- triangles: viewer.modelInfo?.triangles,- materials: viewer.modelInfo?.materials,- animations: viewer.clips?.length,- validationErrors: validator.report?.errors?.length,- validationWarnings: validator.report?.warnings?.length,- currentEnvironment: viewer.state.environment,- currentSettings: { wireframe, skeleton, grid, autoRotate, bgColor },-};-```--### 4. Conversation Memory--- Maintain conversation history in the chat session-- Store recent messages in sessionStorage-- Clear on model change or explicit reset--### 5. Frontend Updates--Update `src/avaturn-agent.js`:--- Replace pattern matching with API calls to `/api/chat`-- Keep speech synthesis/recognition as optional interface-- Add typing indicator during API calls-- Execute returned actions on the viewer-- Fallback to pattern matching if API is unavailable (offline mode)--### 6. Streaming Responses--For better UX, stream LLM responses:--- Use SSE or ReadableStream from the API-- Display tokens as they arrive-- Execute actions after full response is received--### 7. Rate Limiting & Auth--- Require authentication for chat (logged-in users only)-- Rate limit: 20 messages/minute per user-- Token limit: 4096 tokens per request-- Cost tracking via `api/_lib/usage.js`--## Environment Variables--```-OPENAI_API_KEY=sk-...-CHAT_MODEL=gpt-4o-mini-CHAT_MAX_TOKENS=4096-```--## File Structure--```-api/-├── chat.js # LLM chat endpoint with function calling-src/-├── avaturn-agent.js # Updated with API integration + fallback-```--## Validation--- Ask "What model is loaded?" → replies with actual model name and stats-- Ask "Enable wireframe" → wireframe turns on in viewport-- Ask "What errors does this model have?" → summarizes validation report-- Ask complex 3D question → gets knowledgeable answer from LLM-- Offline → falls back to pattern matching gracefully-- Rate limiting works — excessive messages return appropriate errordiff --git a/.github/prompts/ai-model-analysis.md b/.github/prompts/ai-model-analysis.mddeleted file mode 100644index e33c7c8b6..000000000--- a/.github/prompts/ai-model-analysis.md+++ /dev/null@@ -1,115 +0,0 @@-----mode: agent-description: 'Build AI model analysis that describes meshes, materials, and suggests optimizations'------# AI Model Analysis--## Context--The README roadmap lists **"AI Model Analysis — describe meshes, materials, and suggest optimizations"**. This feature uses AI to provide intelligent feedback about loaded 3D models.--## Implementation--### 1. Analysis Engine (`src/model-analysis.js`)--After a model loads, automatically analyze:--#### Geometry Analysis--- Identify over-tessellated flat surfaces (high tri count, low curvature)-- Detect degenerate triangles (zero area)-- Find disconnected geometry (floating vertices)-- Check for non-manifold edges-- Estimate appropriate LOD levels--#### Material Analysis--- Identify materials with identical properties (can be merged)-- Detect textures larger than necessary (4K on small objects)-- Find unused materials (not assigned to any mesh)-- Check if transparency is used but `transparent` flag is off-- Identify missing normal maps on high-detail surfaces--#### Performance Analysis--- Total draw calls estimate-- GPU memory usage estimate (geometry + textures)-- Suggest texture compression (KTX2/Basis)-- Suggest mesh compression (Draco/Meshopt)-- Identify performance bottlenecks--### 2. AI-Enhanced Descriptions--Send model metadata to the LLM for natural language analysis:--```-POST /api/analyze-Body: {- "modelStats": { vertices, triangles, materials, textures, animations, ... },- "validationReport": { errors, warnings, ... },- "materialDetails": [ { name, textures, properties }, ... ]-}-```--LLM returns:--```json-{- "summary": "This is a high-detail character model with PBR materials...",- "optimizations": [- {- "priority": "high",- "category": "textures",- "suggestion": "Resize 4096×4096 normal map to 2048×2048 — minimal visual impact, saves 12MB GPU memory",- "estimatedSaving": "60%"- }- ],- "quality": {- "score": 85,- "notes": "Well-optimized geometry, good UV layout, textures could be compressed"- }-}-```--### 3. Analysis Panel UI--Display results in a panel (side panel or overlay):--- **Summary**: Natural language description of the model-- **Score**: Quality/optimization score (0-100) with color badge-- **Optimizations**: Prioritized list with estimated savings-- **Details**: Expandable sections for geometry, materials, textures, performance--### 4. One-Click Optimizations--For each suggestion, provide an "Apply" button that uses glTF-Transform:--- "Resize textures" → applies texture resize and re-exports-- "Enable Draco compression" → applies Draco and re-exports-- "Merge duplicate materials" → deduplicates and re-exports-- "Remove unused nodes" → prunes and re-exports--### 5. Integration--- Auto-analyze on model load (lightweight client-side analysis)-- "Deep Analysis" button for AI-enhanced analysis (requires API)-- Results cached per model (don't re-analyze on settings change)-- Export analysis as JSON or PDF report--## File Structure--```-src/-├── model-analysis.js # Client-side analysis engine-api/-├── analyze.js # AI-enhanced analysis endpoint-```--## Validation--- Load DamagedHelmet.glb → analysis panel shows stats and suggestions-- Suggestions are actionable and accurate-- "Apply" buttons produce correctly optimized GLB exports-- AI descriptions are relevant and technically accurate-- Works without AI backend (client-side analysis only)diff --git a/.github/prompts/ar-quick-look.md b/.github/prompts/ar-quick-look.mddeleted file mode 100644index 51bdc8e9d..000000000--- a/.github/prompts/ar-quick-look.md+++ /dev/null@@ -1,96 +0,0 @@-----mode: agent-description: 'Add WebXR AR Quick Look support for viewing models in augmented reality'------# AR Quick Look / WebXR--## Context--The README roadmap lists **"AR Quick Look — launch your model in WebXR on supported devices"**. WebXR is the standard for immersive web experiences.--## Implementation--### 1. WebXR AR Session (`src/ar-viewer.js`)--Use the WebXR Device API for AR:--```js-const session = await navigator.xr.requestSession('immersive-ar', {- requiredFeatures: ['hit-test', 'local-floor'],- optionalFeatures: ['dom-overlay'],- domOverlay: { root: document.getElementById('ar-overlay') },-});-```--- Detect WebXR support: `navigator.xr.isSessionSupported('immersive-ar')`-- On supported devices, show "View in AR" button-- Place the model on detected surfaces using hit-test-- Allow pinch-to-scale and rotate gestures-- DOM overlay for UI controls during AR session--### 2. iOS Quick Look Fallback--For iOS Safari (no WebXR):--- Generate USDZ file from the GLB using a client-side converter-- Or provide a `<a rel="ar">` link with the GLB → iOS handles natively-- Apple's AR Quick Look supports GLB directly since iOS 15--```html-<a rel="ar" href="model.glb">- <img src="ar-icon.png" />-</a>-```--### 3. Android Scene Viewer Fallback--For Android Chrome without WebXR:--- Use Google's Scene Viewer intent:--```-intent://arvr.google.com/scene-viewer/1.0?file=MODEL_URL#Intent;scheme=https;package=com.google.android.googlequicksearchbox;end;-```--### 4. AR UI Overlay--During AR session:--- Crosshair reticle for surface detection-- "Place Model" tap handler-- Scale/rotate gesture indicators-- "Exit AR" button-- Model info badge (name, triangles)--### 5. Platform Detection & Button--```-Desktop (no XR) → Button hidden or shows "AR not supported"-Android + WebXR → "View in AR" → WebXR immersive-ar-Android - WebXR → "View in AR" → Scene Viewer intent-iOS → "View in AR" → Quick Look / USDZ-VR Headset → "View in VR" → immersive-vr session-```--### 6. GUI Integration--- Add "View in AR" button to the header bar (next to "Create Avatar")-- Show device compatibility badge-- Settings in dat.gui: scale factor, shadow enabled, lighting mode--## File Structure--```-src/-├── ar-viewer.js # WebXR session, hit-test, placement-├── ar-fallbacks.js # iOS Quick Look, Android Scene Viewer-```--## Validation--- On Android Chrome with ARCore → WebXR session starts, model placed on surface-- On iOS Safari → Quick Look opens with the model-- On desktop → button hidden or shows "Not supported on this device"-- Model scale and orientation are correct in AR-- Pinch-to-scale and rotate work smoothlydiff --git a/.github/prompts/cleanup-dead-code.md b/.github/prompts/cleanup-dead-code.mddeleted file mode 100644index 699e00364..000000000--- a/.github/prompts/cleanup-dead-code.md+++ /dev/null@@ -1,42 +0,0 @@-----mode: agent-description: 'Remove dead code, unused dependencies, and fix package.json metadata'------# Cleanup: Dead Code & Package Metadata--## Tasks--### 1. Fix `package.json` `main` field--- Change `"main": "public/app.js"` → `"main": "src/app.js"`-- The file `public/app.js` does not exist; the real entry point is `src/app.js`--### 2. Remove unused dependency `@avaturn-live/web-sdk`--- Listed in `dependencies` but never imported anywhere in the codebase-- Only `@avaturn/sdk` is used (in `src/avatar-creator.js`)-- Run `npm uninstall @avaturn-live/web-sdk`--### 3. Delete dead API endpoint--- `api/avaturn-session.js` explicitly says `"This file is no longer used. Safe to delete."`-- It returns a 410 Gone response — remove the file entirely--### 4. Remove unused `IS_IOS` constant--- In `src/viewer.js`, the constant `const IS_IOS = isIOS()` is computed but never referenced-- Remove the constant declaration-- Check if the `isIOS()` function at the bottom of the file is used elsewhere — if not, remove it too--### 5. Fix test script--- `package.json` has `"test": "node test/gen_test.js"` but no `test/` directory exists-- Either create a minimal test scaffold (see `add-tests.md` prompt) or change to `"test": "echo 'No tests configured' && exit 0"` as a placeholder--## Validation--- `npm install` should succeed without warnings about missing dependencies-- `npm run build` should succeed-- `npm test` should not crash-- No dead imports or unused variables in modified filesdiff --git a/.github/prompts/cli-tool.md b/.github/prompts/cli-tool.mddeleted file mode 100644index fa7a69a57..000000000--- a/.github/prompts/cli-tool.md+++ /dev/null@@ -1,149 +0,0 @@-----mode: agent-description: 'Build a headless CLI tool for model validation and inspection in CI/CD'------# CLI Tool--## Context--The README roadmap lists **"CLI Tool — `npx 3d-agent inspect model.glb` for headless validation in CI/CD pipelines"**. This makes the validation engine usable in automated workflows without a browser.--## Implementation--### 1. CLI Entry Point (`cli/index.js`)--```bash-npx 3d-agent <command> [options] <file>-```--Commands:--- `validate` — Run glTF validation and output report-- `inspect` — Show model metadata and statistics-- `optimize` — Suggest or apply optimizations (requires glTF-Transform)--### 2. `validate` Command--```bash-npx 3d-agent validate model.glb [--format json|text|table] [--max-issues 100] [--severity error|warning|info|hint]-```--- Load GLB/glTF from local file path or URL-- Run `gltf-validator`-- Output report in requested format:- - `json`: Full validation report as JSON (machine-readable)- - `text`: Human-readable summary- - `table`: Formatted table with colors (default for TTY)-- Exit code: 0 = pass, 1 = errors found, 2 = file not found--Example output (table format):--```-✓ model.glb — Valid glTF 2.0- Generator: Blender 3.6- Version: 2.0- Meshes: 3 Materials: 2 Textures: 5- Vertices: 14,556 Triangles: 46,356-- 0 Errors 2 Warnings 1 Info- ├─ WARNING: Unused texture (2×)- └─ INFO: Non-power-of-two texture dimensions-```--### 3. `inspect` Command--```bash-npx 3d-agent inspect model.glb [--format json|text]-```--Output:--- File size-- glTF version, generator-- Extensions used / required-- Mesh count, material count, texture count-- Total vertices, triangles-- Animation count and duration-- Bounding box dimensions--### 4. `optimize` Command (with glTF-Transform)--```bash-npx 3d-agent optimize model.glb -o optimized.glb [--draco] [--texture-resize 2048] [--dedup] [--prune]-```--Using `@gltf-transform/cli` or programmatic API:--- `--draco`: Apply Draco mesh compression-- `--texture-resize N`: Downscale textures to max NxN-- `--dedup`: Remove duplicate accessors/textures-- `--prune`: Remove unused nodes/materials-- `--quantize`: Quantize accessors--If no `-o` flag, output suggestions only (dry run):--```-Suggestions for model.glb:- • Draco compression would reduce geometry from 1.2 MB to ~450 KB- • 2 textures are 4096×4096 — resize to 2048 to save ~12 MB- • 1 unused material can be pruned- Estimated savings: 67% (3.7 MB → 1.2 MB)-```--### 5. Package Configuration--In `package.json`:--```json-{- "bin": {- "3d-agent": "./cli/index.js"- }-}-```--### 6. Dependencies--CLI-specific:--- `commander` or `yargs` for argument parsing-- `chalk` for colored terminal output-- `ora` for spinners-- `cli-table3` for table formatting--Reuse existing:--- `gltf-validator` (already installed)-- `@gltf-transform/core` (from Material Editor prompt)--### 7. CI/CD Integration Examples--GitHub Actions:--```yaml-- name: Validate 3D Models- run: npx 3d-agent validate models/**/*.glb --format json > report.json--- name: Check for errors- run: npx 3d-agent validate models/**/*.glb --severity error-```--## File Structure--```-cli/-├── index.js # Entry point, commander setup-├── validate.js # Validation command-├── inspect.js # Inspection command-├── optimize.js # Optimization command-└── format.js # Output formatters (json, text, table)-```--## Validation--- `npx 3d-agent validate test.glb` → outputs report, exit code 0-- `npx 3d-agent validate broken.glb` → outputs errors, exit code 1-- `npx 3d-agent inspect test.glb --format json` → valid JSON output-- `npx 3d-agent optimize test.glb -o out.glb --draco` → produces smaller file-- Works in GitHub Actions CI pipelinediff --git a/.github/prompts/complete-mcp-tools.md b/.github/prompts/complete-mcp-tools.mddeleted file mode 100644index 9df796f53..000000000--- a/.github/prompts/complete-mcp-tools.md+++ /dev/null@@ -1,106 +0,0 @@-----mode: agent-description: 'Complete MCP server with validate-model tool and full tool documentation'------# Complete MCP Integration--## Problem--The MCP server (`api/mcp.js`) has avatar CRUD tools but is missing key capabilities that the agent should expose. The OpenAPI spec only documents `GET /`. The tool catalog needs expansion.--## New MCP Tools to Add--### 1. `validate_model` — glTF Validation via MCP--Allow MCP clients to submit a model URL for server-side validation:--```js-{- name: 'validate_model',- description: 'Run Khronos glTF-Validator against a model URL and return the validation report',- inputSchema: {- type: 'object',- properties: {- url: { type: 'string', description: 'URL of the glTF/GLB model to validate' },- maxIssues: { type: 'number', description: 'Maximum issues to report (default: 100)' }- },- required: ['url']- }-}-```--Implementation:--- Fetch the model from the URL (with size limit, e.g., 50MB)-- Run `validateBytes()` from `gltf-validator`-- Return structured report with errors, warnings, info, hints-- Include model stats (vertex count, material count, etc.)--### 2. `inspect_model` — Model Metadata--```js-{- name: 'inspect_model',- description: 'Get metadata and statistics about a 3D model without full validation',- inputSchema: {- type: 'object',- properties: {- url: { type: 'string', description: 'URL of the glTF/GLB model' }- },- required: ['url']- }-}-```--Returns: generator, version, extensions used, mesh count, material count, animation count, total vertices, total triangles, file size.--### 3. `optimize_model` — Model Optimization Suggestions--```js-{- name: 'optimize_model',- description: 'Analyze a model and suggest optimizations',- inputSchema: {- type: 'object',- properties: {- url: { type: 'string', description: 'URL of the glTF/GLB model' }- },- required: ['url']- }-}-```--Returns suggestions like: "Use Draco compression to reduce geometry size by ~60%", "Resize 4096x4096 textures to 2048x2048", "Remove unused materials", etc.--### 4. `create_avatar` — Upload and Create Avatar via MCP--Allow MCP clients to create avatars programmatically:--- Accept GLB upload (base64 or URL)-- Create avatar record-- Return avatar ID and viewer URL--## Server-Side Dependencies--For `validate_model` and `inspect_model`, install `gltf-validator` in the API:--- Already in `dependencies` — just import in the API handler-- Add URL fetching with proper timeout and size limits-- Sanitize URLs to prevent SSRF (allowlist of protocols: `https://`)--## Rate Limiting--Add per-tool rate limits:--- `validate_model`: 10/min (compute-heavy)-- `inspect_model`: 30/min-- `optimize_model`: 10/min-- Avatar tools: existing limits--## Validation--- MCP client sends `tools/list` → all new tools appear in catalog-- `tools/call` with `validate_model` and a Khronos sample model URL → returns valid report-- Rate limiting works — exceeding limit returns proper JSON-RPC error-- SSRF protection — private IPs and non-HTTPS URLs are rejecteddiff --git a/.github/prompts/complete-openapi-spec.md b/.github/prompts/complete-openapi-spec.mddeleted file mode 100644index 7a2c2c3b9..000000000--- a/.github/prompts/complete-openapi-spec.md+++ /dev/null@@ -1,80 +0,0 @@-----mode: agent-description: 'Complete the OpenAPI spec with all actual API endpoints'------# Complete OpenAPI Specification--## Problem--`public/.well-known/openapi.yaml` currently only documents a single endpoint (`GET /`) but the actual API surface is extensive:--### Endpoints that exist but are undocumented:--**Avatar CRUD:**--- `GET /api/avatars` — list user's avatars-- `POST /api/avatars` — create avatar-- `GET /api/avatars/:id` — get avatar by ID-- `PUT /api/avatars/:id` — update avatar-- `DELETE /api/avatars/:id` — delete avatar-- `GET /api/avatars/public` — search public avatars-- `POST /api/avatars/presign` — get presigned upload URL--**Auth:**--- `POST /api/auth/register` — register user-- `POST /api/auth/login` — login-- `GET /api/auth/me` — current user-- `POST /api/auth/logout` — logout--**OAuth 2.1:**--- `POST /api/oauth/register` — dynamic client registration-- `GET /api/oauth/authorize` — authorization endpoint-- `POST /api/oauth/token` — token endpoint-- `POST /api/oauth/revoke` — token revocation-- `POST /api/oauth/introspect` — token introspection--**MCP:**--- `POST /api/mcp` — JSON-RPC (MCP protocol)-- `GET /api/mcp` — SSE stream-- `DELETE /api/mcp` — terminate session--**API Keys:**--- `GET /api/keys` — list API keys-- `POST /api/keys` — create API key-- `DELETE /api/keys/:id` — revoke API key--**Usage:**--- `GET /api/usage/summary` — usage statistics--**Discovery:**--- `GET /.well-known/oauth-authorization-server`-- `GET /.well-known/oauth-protected-resource`-- `GET /.well-known/agent-card.json`-- `GET /.well-known/agent-registration.json`-- `GET /.well-known/ai-plugin.json`--## Implementation--1. Read each API route file to understand request/response schemas-2. Read `api/_lib/schema.sql` for data models-3. Read `api/_lib/validate.js` for request validation schemas-4. Build complete OpenAPI 3.0 spec with:- - All endpoints with methods, parameters, request bodies, responses- - Authentication schemes (Bearer token, OAuth 2.1, API key)- - Schema definitions for Avatar, User, ApiKey, UsageSummary, etc.- - Error response schemas- - Rate limiting headers- - Tags for grouping (Avatars, Auth, OAuth, MCP, Keys, Usage)--## Validation--- Copy spec to https://editor.swagger.io/ — should pass validation-- Each documented endpoint should match an actual route in `api/`-- Request/response schemas should match actual handler codediff --git a/.github/prompts/create-agent-card.md b/.github/prompts/create-agent-card.mddeleted file mode 100644index 12c52b223..000000000--- a/.github/prompts/create-agent-card.md+++ /dev/null@@ -1,100 +0,0 @@-----mode: agent-description: 'Create the missing A2A agent-card.json for agent discovery'------# Create A2A Agent Card--## Problem--Both `features.html` (line 90) and `public/.well-known/agent-registration.json` reference `https://three.ws/.well-known/agent-card.json` as the A2A discovery endpoint, but **no such file exists**. This is a dead link and breaks the A2A (Agent-to-Agent) protocol integration.--## What is agent-card.json?--The A2A protocol (Google's Agent-to-Agent spec) uses `/.well-known/agent-card.json` as the discovery document. It describes the agent's capabilities, supported protocols, authentication requirements, and available skills/tools.--Reference: https://google.github.io/A2A/specification/--## Implementation--Create `public/.well-known/agent-card.json` with the full A2A agent card spec:--```json-{- "name": "three.ws",- "description": "AI-powered 3D model viewer and validation agent. Load glTF/GLB models, run validation, inspect materials, and manage avatar assets.",- "url": "https://three.ws/",- "provider": {- "organization": "three.ws",- "url": "https://three.ws/"- },- "version": "1.5.1",- "capabilities": {- "streaming": false,- "pushNotifications": false,- "stateTransitionHistory": false- },- "authentication": {- "schemes": ["bearer"],- "credentials": null- },- "defaultInputModes": ["text/plain", "application/json"],- "defaultOutputModes": ["text/plain", "application/json"],- "skills": [- {- "id": "list-avatars",- "name": "List Avatars",- "description": "List all avatars owned by the authenticated user",- "tags": ["avatar", "list"],- "examples": ["Show me my avatars", "List all my 3D models"]- },- {- "id": "get-avatar",- "name": "Get Avatar",- "description": "Retrieve details of a specific avatar by ID or slug",- "tags": ["avatar", "inspect"],- "examples": ["Get avatar details for cz", "Show avatar info"]- },- {- "id": "search-avatars",- "name": "Search Public Avatars",- "description": "Search public avatar gallery by query",- "tags": ["avatar", "search"],- "examples": ["Find avatars matching 'robot'", "Search public models"]- },- {- "id": "render-avatar",- "name": "Render Avatar",- "description": "Get a render/preview URL for an avatar in the 3D viewer",- "tags": ["avatar", "render", "preview"],- "examples": ["Render my avatar in the viewer", "Preview this model"]- },- {- "id": "validate-model",- "name": "Validate glTF Model",- "description": "Run Khronos glTF-validator against a model URL and return the validation report",- "tags": ["validation", "gltf", "quality"],- "examples": ["Validate this GLB file", "Check model for errors"]- },- {- "id": "delete-avatar",- "name": "Delete Avatar",- "description": "Delete an avatar owned by the authenticated user",- "tags": ["avatar", "delete"],- "examples": ["Delete my old avatar", "Remove avatar abc123"]- }- ]-}-```--## Also Update--1. **Ensure `vercel.json`** routes `/.well-known/agent-card.json` correctly — the existing catch-all for `public/` should handle it, but verify-2. **Cross-reference** with the MCP tool catalog in `api/mcp.js` — each skill should map to an actual MCP tool-3. **Keep version in sync** with `package.json` version--## Validation--- `curl https://three.ws/.well-known/agent-card.json` returns valid JSON-- Skills listed match the tools defined in `api/mcp.js`-- The `agent-registration.json` A2A service endpoint resolvesdiff --git a/.github/prompts/deploy-erc8004-contracts.md b/.github/prompts/deploy-erc8004-contracts.mddeleted file mode 100644index a1e8c509f..000000000--- a/.github/prompts/deploy-erc8004-contracts.md+++ /dev/null@@ -1,96 +0,0 @@-----mode: agent-description: 'Deploy ERC-8004 contracts and complete on-chain agent registration'------# Deploy ERC-8004 Contracts & Complete Integration--## Problem--The entire ERC-8004 on-chain agent registration flow is fully coded in `src/erc8004/` but **non-functional** because all contract addresses in `src/erc8004/abi.js` are empty strings:--```js-84532: {- identityRegistry: '', // TODO: fill once deployed- reputationRegistry: '', // TODO: fill once deployed- validationRegistry: '', // TODO: fill once deployed-},-```--The UI (`register-ui.js`), registry interaction (`agent-registry.js`), and ABI are complete — only deployment is missing.--## Implementation Plan--### Phase 1: Smart Contracts--1. **Create `contracts/` directory** at project root-2. **Initialize Hardhat or Foundry** project for Solidity development-3. **Implement ERC-8004 Identity Registry** contract:-- - ERC-721 base (agent identity NFTs)- - `register(string agentURI)` → mints token, stores URI- - `setAgentURI(uint256 agentId, string newURI)` — owner-only- - `setAgentWallet(uint256, address, uint256, bytes)` — delegated wallet with sig verification- - `getMetadata(uint256, string)` / `setMetadata(uint256, string, bytes)` — key-value metadata- - Events: `Registered`, `URIUpdated`, `MetadataSet`- - Must match the ABI already defined in `src/erc8004/abi.js`--4. **Implement Reputation Registry** contract:-- - Submit reputation feedback for agents- - Query reputation scores- - Only registered agents (holders of Identity NFT) can receive reputation--5. **Implement Validation Registry** contract:- - Store validation proofs on-chain- - Link validation results to agent identities- - Support for multiple validators--### Phase 2: Deployment (Base Sepolia Testnet)--1. **Write deployment scripts** for Base Sepolia (chain 84532)-2. Deploy all three contracts-3. **Update `src/erc8004/abi.js`** with deployed addresses-4. Verify contracts on BaseScan--### Phase 3: Fill Registration Data--1. **Register three.ws itself** on the Identity Registry-2. **Update `public/.well-known/agent-registration.json`**:- - Fill the empty `registrations` array with the on-chain registration- - Format: `{ "agentRegistry": "eip155:84532:0x...", "agentId": "1" }`-3. Set agent metadata (capabilities, version, etc.)--### Phase 4: Complete Reputation & Validation--1. Add Reputation Registry ABI to `src/erc8004/abi.js`-2. Add Validation Registry ABI to `src/erc8004/abi.js`-3. Wire validation results from `src/validator.js` → Validation Registry-4. Add reputation submission UI-5. Add reputation query display on agent profiles--## File Structure--```-contracts/-├── src/-│ ├── IdentityRegistry.sol-│ ├── ReputationRegistry.sol-│ └── ValidationRegistry.sol-├── test/-│ ├── IdentityRegistry.t.sol-│ ├── ReputationRegistry.t.sol-│ └── ValidationRegistry.t.sol-├── script/-│ └── Deploy.s.sol-├── foundry.toml-└── README.md-```--## Validation--- All contracts deploy to Base Sepolia without errors-- `registerAgent()` from the browser UI successfully mints an identity NFT-- Agent URI resolves to the registration JSON-- Contract addresses in `abi.js` are populated and the UI is functional end-to-end-- Contracts verified on BaseScandiff --git a/.github/prompts/file-format-expansion.md b/.github/prompts/file-format-expansion.mddeleted file mode 100644index 700a56e3d..000000000--- a/.github/prompts/file-format-expansion.md+++ /dev/null@@ -1,132 +0,0 @@-----mode: agent-description: 'Add multi-format import support for FBX, OBJ, and USDZ files'------# File Format Expansion--## Context--The README roadmap lists **"File Format Expansion — .fbx, .obj, .usdz import support"**. Currently only glTF/GLB is supported. Adding more formats makes the viewer useful for a wider audience.--## Implementation--### 1. FBX Import--Three.js has `FBXLoader` built-in:--```js-import { FBXLoader } from 'three/addons/loaders/FBXLoader.js';-```--- Detect `.fbx` files by extension-- Load with `FBXLoader`-- Apply the same scene setup (center, scale, lighting) as glTF-- FBX animations → `AnimationMixer` (same as glTF)-- Note: FBX textures may be embedded or reference external files--### 2. OBJ Import--Three.js has `OBJLoader` and `MTLLoader`:--```js-import { OBJLoader } from 'three/addons/loaders/OBJLoader.js';-import { MTLLoader } from 'three/addons/loaders/MTLLoader.js';-```--- Detect `.obj` files by extension-- If `.mtl` file is present (drag-and-drop with companion files), load materials first-- Apply materials to OBJ geometry-- Center and scale the model--### 3. USDZ Import--More complex — Three.js has `USDZLoader` (experimental):--```js-import { USDZLoader } from 'three/addons/loaders/USDZLoader.js';-```--- Detect `.usdz` / `.usda` / `.usdc` files-- Load with `USDZLoader`-- Note: USDZ support in Three.js is limited — document known limitations--### 4. STL Import--Common for 3D printing:--```js-import { STLLoader } from 'three/addons/loaders/STLLoader.js';-```--- Returns `BufferGeometry` only (no materials/textures)-- Apply default material (MeshStandardMaterial, neutral gray)-- Useful for engineering/3D printing workflows--### 5. PLY Import--Common for photogrammetry and point clouds:--```js-import { PLYLoader } from 'three/addons/loaders/PLYLoader.js';-```--- May contain vertex colors-- Support both mesh and point cloud rendering--### 6. Format Detection--In `src/app.js`, detect file format by extension:--```js-function getLoader(filename) {- const ext = filename.split('.').pop().toLowerCase();- switch (ext) {- case 'gltf':- case 'glb':- return 'gltf';- case 'fbx':- return 'fbx';- case 'obj':- return 'obj';- case 'usdz':- case 'usda':- case 'usdc':- return 'usdz';- case 'stl':- return 'stl';- case 'ply':- return 'ply';- default:- return 'gltf'; // fallback- }-}-```--### 7. Validation Behavior--- glTF validation only runs for `.gltf` / `.glb` files-- For other formats, show "Validation not available for {format}" in the validation panel-- Model info overlay still works (vertex/triangle counts from Three.js geometry)--### 8. Drag-and-Drop Updates--Update `SimpleDropzone` in `src/app.js` to accept new extensions:--- `.fbx`, `.obj`, `.mtl`, `.usdz`, `.usda`, `.usdc`, `.stl`, `.ply`-- Handle companion files (`.mtl` with `.obj`, texture files with `.fbx`)--## File Structure--```-src/-├── loaders.js # Format detection, loader registry, format-specific setup-```--## Validation--- Drag-and-drop an FBX file → loads and renders correctly-- Drag-and-drop OBJ + MTL → materials applied-- UI correctly shows "Validation not available" for non-glTF formats-- Animations work for FBX files with animation data-- File picker accepts all supported extensionsdiff --git a/.github/prompts/fix-security-xss.md b/.github/prompts/fix-security-xss.mddeleted file mode 100644index c80266475..000000000--- a/.github/prompts/fix-security-xss.md+++ /dev/null@@ -1,30 +0,0 @@-----mode: agent-description: 'Fix XSS vulnerability in glTF validator — unescaped title field'------# Fix XSS: Validator Title Escaping--## Problem--In `src/validator.js`, the `setResponse()` method escapes `extras.author`, `extras.license`, and `extras.source` using `escapeHTML()`, but `extras.title` is assigned raw:--```js-if (extras.title) {- this.report.info.extras.title = extras.title; // ← NOT escaped-}-```--A malicious glTF file can set `asset.extras.title` to `<img src=x onerror=alert(1)>` and execute arbitrary JavaScript when the validation report renders via `dangerouslySetInnerHTML` in `src/components/validator-report.jsx`.--## Fix--1. In `src/validator.js`, find the `setResponse()` method-2. Change `extras.title` assignment to: `this.report.info.extras.title = escapeHTML(extras.title);`-3. Verify `escapeHTML()` is already defined at the bottom of the file (it is)-4. Check `src/components/validator-report.jsx` — confirm `dangerouslySetInnerHTML` is used for rendering. If possible, switch to safe text rendering instead--## Validation--- Load a glTF file with `asset.extras.title` set to `<script>alert('xss')</script>` — should render as escaped text, not execute-- All other validator report fields should still render correctlydiff --git a/.github/prompts/fix-validator-lightbox.md b/.github/prompts/fix-validator-lightbox.mddeleted file mode 100644index 578408e2a..000000000--- a/.github/prompts/fix-validator-lightbox.md+++ /dev/null@@ -1,29 +0,0 @@-----mode: agent-description: 'Fix broken template literals in validator lightbox'------# Fix Validator Lightbox Template Strings--## Problem--In `src/validator.js`, the `showLightbox()` method uses Mustache-style `{{` double-braces instead of JavaScript template literal `${` syntax:--```js-<link rel="stylesheet" href="{{location.protocol}}//{{location.host}}/style.css">-```--This renders as literal text `{{location.protocol}}//{{location.host}}/style.css` instead of resolving to the actual URL like `https://three.ws/style.css`.--## Fix--1. In `src/validator.js`, find the `showLightbox()` method-2. Replace `{{location.protocol}}` with `${location.protocol}`-3. Replace `{{location.host}}` with `${location.host}`-4. Ensure the surrounding string uses backticks (template literal) — it already does--## Validation--- Open a glTF model, run validation, click the lightbox/report button-- The new tab should load with proper CSS styling from the current host-- Check the rendered HTML source to confirm the URL resolved correctlydiff --git a/.github/prompts/material-editor.md b/.github/prompts/material-editor.mddeleted file mode 100644index b6e777e91..000000000--- a/.github/prompts/material-editor.md+++ /dev/null@@ -1,130 +0,0 @@-----mode: agent-description: 'Build a live material editor with PBR parameter tweaking and GLB export'------# Material Editor--## Context--The README roadmap lists **"Material Editor — tweak PBR params (roughness, metalness, colors) live in the viewport"** as a planned feature. The viewer currently renders materials read-only. This is the most impactful editor feature for a 3D model tool.--## Dependencies--Install `@gltf-transform/core` and `@gltf-transform/extensions` for GLB re-serialization:--```bash-npm install @gltf-transform/core @gltf-transform/extensions-```--These libraries let you read a GLB, modify material properties programmatically, and write it back to a valid GLB — enabling "edit and export" workflows.--## Implementation--### 1. Material Inspector Panel (`src/material-editor.js`)--Create a new module that:--- Traverses the loaded `content` (Three.js scene graph) to find all `MeshStandardMaterial` / `MeshPhysicalMaterial` instances-- Groups materials by name (deduplicating shared materials)-- For each material, exposes editable PBR properties:--| Property | Type | Control |-| ------------------- | --------- | ---------------------------- |-| `color` (baseColor) | Color | dat.gui color picker |-| `metalness` | Float 0-1 | Slider |-| `roughness` | Float 0-1 | Slider |-| `emissive` | Color | Color picker |-| `emissiveIntensity` | Float | Slider |-| `opacity` | Float 0-1 | Slider |-| `transparent` | Boolean | Checkbox |-| `alphaTest` | Float 0-1 | Slider |-| `side` | Enum | Dropdown (Front/Back/Double) |-| `flatShading` | Boolean | Checkbox |-| `wireframe` | Boolean | Checkbox |-| `envMapIntensity` | Float | Slider |-| `normalScale` | Vector2 | Two sliders |-| `aoMapIntensity` | Float 0-1 | Slider |--### 2. Texture Viewer--For each material, show thumbnail previews of assigned textures:--- `map` (baseColor texture)-- `normalMap`-- `roughnessMap` / `metalnessMap`-- `aoMap`-- `emissiveMap`-- `envMap`--Click a texture thumbnail to view it full-size in a lightbox.--### 3. Live Preview--All material property changes apply immediately to the Three.js material via `material.needsUpdate = true`. The viewport reflects changes in real-time.--### 4. GLB Export with Edits--Using glTF-Transform:--1. Read the original GLB bytes-2. Apply material property changes to the glTF-Transform document-3. Write modified GLB-4. Trigger browser download of the edited file--```js-import { Document, NodeIO } from '@gltf-transform/core';-import { ALL_EXTENSIONS } from '@gltf-transform/extensions';--async function exportEditedGLB(originalBuffer, materialEdits) {- const io = new NodeIO().registerExtensions(ALL_EXTENSIONS);- const doc = await io.readBinary(new Uint8Array(originalBuffer));-- for (const [materialName, edits] of Object.entries(materialEdits)) {- const mat = doc- .getRoot()- .listMaterials()- .find((m) => m.getName() === materialName);- if (!mat) continue;-- if (edits.baseColor) mat.setBaseColorFactor(edits.baseColor);- if (edits.metalness !== undefined) mat.setMetallicFactor(edits.metalness);- if (edits.roughness !== undefined) mat.setRoughnessFactor(edits.roughness);- if (edits.emissive) mat.setEmissiveFactor(edits.emissive);- // ... etc- }-- return io.writeBinary(doc);-}-```--### 5. Integration with Viewer--- Add a "Materials" folder to the dat.gui panel in `src/viewer.js`-- When a model loads, populate subfolders per material-- Add an "Export GLB" button that saves the modified model-- Store original GLB buffer reference for export--### 6. UI Design--- Material list as collapsible sections in dat.gui or a separate side panel-- Color swatches for baseColor/emissive-- Texture thumbnails in a grid below each material section-- "Reset" button per material to revert to original values-- "Export Modified GLB" button at the top--## File Structure--```-src/-├── material-editor.js # Material inspector & editor logic-├── glb-export.js # glTF-Transform export pipeline-```--## Validation--- Load DamagedHelmet.glb → material panel shows all PBR properties-- Change roughness slider → viewport updates in real-time-- Export modified GLB → re-import → changes are persisted-- Works with multi-material models (FlightHelmet, etc.)-- Original file is never mutateddiff --git a/.github/prompts/measurement-tools.md b/.github/prompts/measurement-tools.mddeleted file mode 100644index c17d0f8be..000000000--- a/.github/prompts/measurement-tools.md+++ /dev/null@@ -1,84 +0,0 @@-----mode: agent-description: 'Add measurement tools for distances, angles, and bounding box dimensions'------# Measurement Tools--## Context--The README roadmap lists **"Measurement Tools — click two points to measure distances, angles, bounding boxes"**. Essential for any professional 3D tool.--## Implementation--### 1. Point-to-Point Distance (`src/measurements.js`)--- **Activate measurement mode** via GUI button or keyboard shortcut (M)-- User clicks two points on model surface (raycasting to mesh)-- Draw a line between the two points with a label showing distance-- Distance in model units (meters for glTF)-- Support for snapping to vertices--### 2. Angle Measurement--- Click three points: A, B, C-- Measure angle at vertex B (angle ABC)-- Display arc visualization with degree label-- Useful for checking joint angles, surface normals--### 3. Bounding Box Dimensions--- Toggle bounding box overlay per mesh or entire model-- Show dimensions (width × height × depth) in model units-- Display center point coordinates-- Show total model extents--### 4. Cross-Section / Clipping Plane--- Draggable clipping plane that slices through the model-- Shows cross-section outline-- Plane normal and position are adjustable-- Useful for inspecting internal geometry--### 5. Surface Area & Volume--- Calculate and display:- - Total surface area (sum of triangle areas)- - Estimated volume (for closed meshes)- - Per-mesh surface area--### 6. Measurement Display--- Measurements rendered as Three.js sprites (always face camera)-- Measurement list panel showing all active measurements-- Delete individual measurements or "Clear All"-- Units toggle: meters, centimeters, millimeters, inches, feet--### 7. GUI Integration--Add "Measure" folder to dat.gui:--```-▸ Measure- Mode (dropdown: Off, Distance, Angle, BBox)- Units (dropdown: m, cm, mm, in, ft)- Snap to Vertex (checkbox)- Show BBox (checkbox)- Clipping Plane (checkbox)- Clear All (button)-```--## File Structure--```-src/-├── measurements.js # Raycasting, distance/angle calc, display, clipping-```--## Validation--- Click two points on DamagedHelmet → shows distance in meters-- Click three points → shows angle in degrees-- Toggle bounding box → shows correct dimensions-- Clipping plane reveals internal geometry-- Units switch correctly converts displayed valuesdiff --git a/.github/prompts/scene-graph-explorer.md b/.github/prompts/scene-graph-explorer.mddeleted file mode 100644index 1348b7e20..000000000--- a/.github/prompts/scene-graph-explorer.md+++ /dev/null@@ -1,124 +0,0 @@-----mode: agent-description: 'Build a visual scene graph explorer with node inspection and transform controls'------# Scene Graph Explorer--## Context--The README roadmap lists **"Scene Graph Explorer — visual tree of all nodes, meshes, materials, and their properties"**. Currently the viewer provides model info stats (vertex/triangle counts) but no way to inspect or navigate the scene hierarchy.--## Implementation--### 1. Scene Tree Panel (`src/scene-explorer.js`)--Build a collapsible tree view that mirrors the Three.js scene graph:--```-▸ Scene- ▸ DamagedHelmet (Mesh)- ▸ Material_MR (MeshStandardMaterial)- ▸ BufferGeometry (14556 verts)- ▸ DirectionalLight- ▸ AmbientLight-```--Each tree node shows:--- **Name** (or type if unnamed)-- **Icon** by type: 📦 Mesh, 💡 Light, 📷 Camera, 🦴 Bone, 🎯 Empty/Group-- **Visibility toggle** (eye icon) — sets `object.visible`-- **Expand/collapse** for children--### 2. Node Inspector--When a node is selected in the tree, show a properties panel:--**For all nodes:**--- Name (editable)-- Position (x, y, z)-- Rotation (x, y, z in degrees)-- Scale (x, y, z)-- Visible (checkbox)-- Matrix (read-only, 4x4)--**For Meshes:**--- Geometry stats: vertices, triangles, indexed, attributes list-- Material reference (click to jump to Material Editor)-- Bounding box dimensions-- Morph targets list--**For Lights:**--- Type, color, intensity-- Shadow settings--**For Cameras:**--- FOV, near, far, aspect--**For Bones/SkinnedMesh:**--- Joint index, skin reference-- Inverse bind matrix--### 3. Viewport Interaction--- **Click-to-select**: Raycasting from mouse position to select meshes in the viewport. Highlights the selected mesh with an outline or wireframe overlay. Syncs selection with the tree panel.-- **Transform Gizmo**: Use Three.js `TransformControls` for translate/rotate/scale. Toggle mode with keyboard shortcuts (W/E/R or G/R/S).-- **Focus/Frame**: Double-click a tree node to orbit the camera to frame that object.--### 4. Search & Filter--- Search box at top of tree to filter by node name-- Filter buttons: Show only Meshes / Lights / Cameras / All-- Highlight matching nodes in the tree--### 5. UI Layout--The scene explorer should be a **resizable side panel** (left or right side):--- Tree view takes most of the vertical space-- Properties panel below the tree (or tabbed)-- Panel can be toggled with keyboard shortcut (T) or GUI button-- Panel width is draggable--Use plain DOM (no framework) to match the existing codebase style. CSS in `style.css`.--### 6. Integration--In `src/viewer.js`:--- After model load (`setContent`), call `sceneExplorer.buildTree(this.content)`-- Wire click-to-select raycasting in the render loop-- Add `TransformControls` from `three/addons/controls/TransformControls.js`-- Add GUI toggle in Display folder: "scene explorer"--### 7. Export Transform Changes--If the user moves/rotates/scales objects:--- Track which nodes were modified-- On GLB export (via `glb-export.js` from Material Editor), apply transform changes to the glTF-Transform document-- Serialize updated transforms into the exported file--## File Structure--```-src/-├── scene-explorer.js # Tree view, node inspector, selection-├── transform-controls.js # Gizmo wrapper & keyboard shortcuts-```--## Validation--- Load FlightHelmet.gltf → tree shows full hierarchy with correct nesting-- Click a mesh in the tree → highlights in viewport, shows properties-- Click a mesh in the viewport → selects in tree-- Drag transform gizmo → node moves, tree properties update-- Toggle visibility → mesh disappears in viewport-- Search "helmet" → filters tree to matching nodes-- Works with animated models (Fox.glb) — bones visible in treediff --git a/.github/prompts/screenshot-video-export.md b/.github/prompts/screenshot-video-export.mddeleted file mode 100644index 5a8bbed9c..000000000--- a/.github/prompts/screenshot-video-export.md+++ /dev/null@@ -1,94 +0,0 @@-----mode: agent-description: 'Add screenshot/video export with PNG capture and animated WebM recording'------# Screenshot & Video Export--## Context--The README roadmap lists **"Screenshot / Video Export — capture PNGs or record animated WebM walkthroughs"**. The viewer already has a basic `takeScreenshot()` method that captures a single PNG. This prompt expands it into a full export system.--## Current State--`src/viewer.js` has `takeScreenshot()` bound to the `P` key and a GUI button. It works but is minimal.--## Implementation--### 1. Enhanced Screenshot (`src/export.js`)--Improve the existing screenshot:--- **Resolution multiplier**: Capture at 2x, 4x native resolution for print-quality exports-- **Transparent background**: When `transparentBg` is enabled, export PNG with alpha channel-- **Custom dimensions**: Let user specify exact pixel dimensions (e.g., 1920×1080, 4096×4096)-- **Format options**: PNG (lossless + alpha), JPEG (smaller, configurable quality), WebP-- **Filename**: Auto-generate as `{modelName}_{timestamp}.{ext}`--### 2. Turntable Capture--Automated 360° turntable sequence:--- User clicks "Turntable" → auto-rotate enabled, captures N frames (e.g., 36 frames = 10° per frame)-- Exports as individual PNGs or animated GIF-- Progress bar during capture--### 3. Video Recording--Record the viewport as a video:--- Use `MediaRecorder` API with `canvas.captureStream()`-- Controls: Record / Stop / Pause-- Output format: WebM (VP9) — native browser support, no dependencies-- Configurable FPS (24, 30, 60)-- Configurable duration or manual stop-- Auto-download on stop--### 4. Animated GIF Export--For short clips and turntables:--- Use a lightweight GIF encoder (e.g., `gif.js` or manual LZW)-- Capture N frames → encode → download-- Configurable dimensions (downscale for file size)-- Useful for sharing on platforms that don't support video--### 5. GUI Integration--Add an "Export" folder to dat.gui:--```-▸ Export- Screenshot [P] (button)- Resolution (dropdown: 1x, 2x, 4x)- Format (dropdown: PNG, JPEG, WebP)- Background (dropdown: Current, Transparent, White)- ─────────────────- Record Video (button — toggles to Stop)- Video FPS (dropdown: 24, 30, 60)- ─────────────────- Turntable (36 frames) (button)- Turntable Speed (slider)-```--### 6. Sharing--After capture, show a toast/notification:--- "Screenshot saved: model_2026-04-14.png"-- Option to copy to clipboard (for screenshots, using `navigator.clipboard.write()`)--## File Structure--```-src/-├── export.js # Screenshot, video recording, turntable, GIF-```--## Validation--- Screenshot at 4x resolution → produces sharp, high-res PNG-- Screenshot with transparent bg → PNG has alpha channel (verify in image editor)-- Record 5-second video → produces playable WebM file-- Turntable 36 frames → produces 36 PNGs or one animated sequence-- Works on Chrome, Firefox, Edge (MediaRecorder support varies)diff --git a/.github/prompts/side-by-side-diff.md b/.github/prompts/side-by-side-diff.mddeleted file mode 100644index 95ae32435..000000000--- a/.github/prompts/side-by-side-diff.md+++ /dev/null@@ -1,94 +0,0 @@-----mode: agent-description: 'Add side-by-side model diff for comparing two versions of the same model'------# Side-by-Side Model Diff--## Context--The README roadmap lists **"Side-by-Side Diff — compare two versions of the same model"**. Critical for workflows where models are iterated (e.g., optimization passes, LOD comparison, before/after edits).--## Implementation--### 1. Dual Viewport (`src/model-diff.js`)--Split the viewer into two synchronized viewports:--- Left: Model A (original / before)-- Right: Model B (modified / after)-- Both viewports share camera controls (orbit synced)-- Divider bar is draggable for reveal/wipe comparison--### 2. Loading Two Models--Entry points:--- **Drag-and-drop**: Drop model A, then use "Compare With..." button → file picker for model B-- **URL params**: `#model=A.glb&compare=B.glb`-- **From avatar gallery**: Select two avatars to compare--### 3. Comparison Modes--| Mode | Description |-| ------------------ | ---------------------------------------------------------------------------- |-| **Side by Side** | Two viewports, synced camera |-| **Overlay** | Both models rendered in same viewport, toggle A/B with slider |-| **Onion Skin** | Model B overlaid with adjustable opacity |-| **Wireframe Diff** | Show wireframe of both, highlight geometry differences |-| **Stats Diff** | Table comparing vertex count, triangle count, file size, materials, textures |--### 4. Stats Comparison Table--```-Property | Model A | Model B | Delta-─────────────────┼──────────────┼──────────────┼──────────-Vertices | 14,556 | 8,234 | -43%-Triangles | 46,356 | 27,896 | -40%-Materials | 1 | 1 | 0-Textures | 5 | 5 | 0-File Size | 3.7 MB | 1.2 MB | -68%-Extensions | 2 | 3 | +1-Animations | 0 | 0 | 0-```--### 5. Visual Diff Highlights--- If geometry differs: overlay wireframe showing added/removed triangles-- If materials differ: list changed properties-- If textures differ: show texture thumbnails side by side-- Color-code: green = smaller/better, red = larger/worse--### 6. Synchronized Controls--Both viewports share:--- Camera position, rotation, zoom (OrbitControls synced)-- Environment map selection-- Animation playback (if both have animations)-- Display settings (wireframe, skeleton, grid)--### 7. GUI Integration--Add "Compare" mode:--- "Compare With..." button in header-- "Exit Comparison" button to return to single viewport-- Comparison mode dropdown (side-by-side, overlay, onion skin)-- Stats diff panel toggle--## File Structure--```-src/-├── model-diff.js # Dual viewport, synced controls, comparison logic-├── diff-stats.js # Statistical comparison, delta calculation-```--## Validation--- Load two models → split viewport shows both-- Orbit one viewport → other follows exactly-- Stats table shows correct deltas with percentage changes-- Overlay mode blends both models with slider-- Works with different-sized models (auto-scales to fit)diff --git a/.github/prompts/stack-01-siwe-wallet-login.md b/.github/prompts/stack-01-siwe-wallet-login.mddeleted file mode 100644index 81798626e..000000000--- a/.github/prompts/stack-01-siwe-wallet-login.md+++ /dev/null@@ -1,63 +0,0 @@-----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.mddeleted file mode 100644index 24498ff16..000000000--- a/.github/prompts/stack-02-privy-unified-auth.md+++ /dev/null@@ -1,61 +0,0 @@-----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.mddeleted file mode 100644index 5a78af462..000000000--- a/.github/prompts/stack-03-auth-session-recovery.md+++ /dev/null@@ -1,56 +0,0 @@-----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.mddeleted file mode 100644index 50bc5e812..000000000--- a/.github/prompts/stack-04-auth-error-ux.md+++ /dev/null@@ -1,56 +0,0 @@-----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.mddeleted file mode 100644index 2a24e4467..000000000--- a/.github/prompts/stack-05-selfie-capture.md+++ /dev/null@@ -1,62 +0,0 @@-----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.mddeleted file mode 100644index c38606700..000000000--- a/.github/prompts/stack-06-face-to-avatar-backend.md+++ /dev/null@@ -1,75 +0,0 @@-----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.mddeleted file mode 100644index 8ddb7da5d..000000000--- a/.github/prompts/stack-07-avatar-creation-progress.md+++ /dev/null@@ -1,56 +0,0 @@-----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.mddeleted file mode 100644index 71ed495c8..000000000--- a/.github/prompts/stack-08-avatar-save-and-slug.md+++ /dev/null@@ -1,66 +0,0 @@-----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.mddeleted file mode 100644index 02d1c5c52..000000000--- a/.github/prompts/stack-09-avatar-editor-shell.md+++ /dev/null@@ -1,64 +0,0 @@-----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.mddeleted file mode 100644index 0d2c8951f..000000000--- a/.github/prompts/stack-10-avatar-identity-tab.md+++ /dev/null@@ -1,61 +0,0 @@-----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.mddeleted file mode 100644index 4431b50ea..000000000--- a/.github/prompts/stack-11-avatar-skills-tab.md+++ /dev/null@@ -1,73 +0,0 @@-----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.mddeleted file mode 100644index a7429014a..000000000--- a/.github/prompts/stack-12-avatar-memory-seed.md+++ /dev/null@@ -1,71 +0,0 @@-----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.mddeleted file mode 100644index 0973de3ba..000000000--- a/.github/prompts/stack-13-avatar-animation-tab.md+++ /dev/null@@ -1,77 +0,0 @@-----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.mddeleted file mode 100644index c9ba9b04c..000000000--- a/.github/prompts/stack-14-avatar-mesh-replace.md+++ /dev/null@@ -1,58 +0,0 @@-----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.mddeleted file mode 100644index 869f638e9..000000000--- a/.github/prompts/stack-15-agent-public-page.md+++ /dev/null@@ -1,63 +0,0 @@-----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.mddeleted file mode 100644index 13d9979f4..000000000--- a/.github/prompts/stack-16-embed-code-generator.md+++ /dev/null@@ -1,79 +0,0 @@-----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://three.ws/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://three.ws/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://three.ws/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.mddeleted file mode 100644index 784425427..000000000--- a/.github/prompts/stack-17-kiosk-mode-polish.md+++ /dev/null@@ -1,71 +0,0 @@-----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.mddeleted file mode 100644index 946d047b1..000000000--- a/.github/prompts/stack-18-embed-telemetry.md+++ /dev/null@@ -1,68 +0,0 @@-----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.mddeleted file mode 100644index d31738a52..000000000--- a/.github/prompts/stack-19-artifacts-single-file.md+++ /dev/null@@ -1,78 +0,0 @@-----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.mddeleted file mode 100644index 6f55c5831..000000000--- a/.github/prompts/stack-20-lobehub-plugin.md+++ /dev/null@@ -1,109 +0,0 @@-----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 three.ws 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://three.ws/.well-known/chat-plugin.json`:--```json-{- "identifier": "3d-agent",- "version": "1.0.0",- "meta": {- "title": "three.ws",- "description": "Embodied three.wss — identity, memory, skills, emotional presence",- "avatar": "https://three.ws/icon.png",- "tags": ["3d", "agent", "avatar"]- },- "api": [- {- "name": "renderAgent",- "description": "Render an embodied agent by slug or agent card URL",- "url": "https://three.ws/api/lobehub/render-agent",- "parameters": {- "type": "object",- "properties": { "slug": { "type": "string" } },- "required": ["slug"]- }- },- {- "name": "summonAgent",- "description": "Ask the three.ws to perform a skill and return the result + rendering",- "url": "https://three.ws/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://three.ws/lobehub/embed.html"- }- ]-}-```--### Plugin endpoints--`POST /api/lobehub/render-agent` — returns a payload the plugin chrome renders:--```json-{- "type": "embed",- "url": "https://three.ws/agent/satoshi?kiosk=1&theme=auto",- "width": 480,- "height": 480,- "fallbackText": "three.ws: 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 three.ws 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 three.ws login to view public agents.diff --git a/.github/prompts/stack-21-host-chat-bridge.md b/.github/prompts/stack-21-host-chat-bridge.mddeleted file mode 100644index 7003d76ab..000000000--- a/.github/prompts/stack-21-host-chat-bridge.md+++ /dev/null@@ -1,73 +0,0 @@-----mode: agent-description: 'postMessage bridge between host chat context and embedded agent (emotion + skills)'------# Stack Layer 5: Host Chat ↔ Agent Bridge--## Problem--When an agent is embedded in a host chat (Claude Artifacts, LobeHub, any site), it should _react_ to the conversation, not just sit there. The host doesn't know about the agent's skill API; the agent doesn't see the chat content. We need a thin standardized bridge.--## Implementation--### Message protocol--Define in [specs/EMBED_SPEC.md](specs/EMBED_SPEC.md). Messages flow both ways via `postMessage`.--**Host → Agent:**--```js-{ type: '3dagent.context', turn: 'user' | 'assistant', text: string, id: string }-{ type: '3dagent.invokeSkill', skillId: string, input?: any, requestId: string }-{ type: '3dagent.setEmotion', blend: { curious?: 0-1, concern?: 0-1, ... }, durationMs?: number }-{ type: '3dagent.reload' }-```--**Agent → Host:**--```js-{ type: '3dagent.ready', avatarId: string }-{ type: '3dagent.skillResult', requestId: string, result: any, error?: string }-{ type: '3dagent.emotionChanged', blend: {...} }-{ type: '3dagent.actionLogged', action: { type, timestamp, payload } }-```--### Client implementation ([src/agent-protocol.js](src/agent-protocol.js))--- Add a `HostBridge` class that listens for allowed origins and translates `postMessage` ↔ agent protocol events.-- Origin allowlist pulled from the avatar's embed allowlist (stack-16 / [prompts/embed/03-embed-allowlist.md](prompts/embed/03-embed-allowlist.md)).-- If origin not allowed, ignore but log.--### Emotion from context--When host sends `3dagent.context` with text, pipe the text through the existing emotion-scoring heuristic in [src/agent-avatar.js](src/agent-avatar.js) Empathy Layer. The avatar then drifts its emotional blend toward the scored vector.--This is the key user-facing moment: **the agent visibly reacts to the chat it's embedded in**.--### Skill invocation--`3dagent.invokeSkill` triggers the skill, plays the matching animation, returns the result via `3dagent.skillResult`. Skills that require network/auth are rejected in artifact mode.--### Ready handshake--On mount, agent posts `3dagent.ready`. Host should wait for this before sending other messages.--### Security--- Never execute string code from the host.-- Skill invocation goes through the existing protocol bus — same safety as any user action.-- Rate-limit host messages: max 10/s per origin.--## Validation--- Test harness page with an iframe + buttons for each host→agent message.-- Send `3dagent.context` with "This is terrible news" → agent's emotion drifts toward concern within 1s.-- Send `3dagent.invokeSkill` with `greet` → agent greets, result returned with correct `requestId`.-- Send from disallowed origin → no response.-- `npm run build` passes.--## Do not do this--- Do NOT accept arbitrary JS from the host.-- Do NOT trust `event.origin === '*'`. Always validate against allowlist.diff --git a/.github/prompts/stack-22-mcp-embodied-responses.md b/.github/prompts/stack-22-mcp-embodied-responses.mddeleted file mode 100644index 55d8bc8a9..000000000--- a/.github/prompts/stack-22-mcp-embodied-responses.md+++ /dev/null@@ -1,69 +0,0 @@-----mode: agent-description: 'MCP tools that return embodied agent renderings, not just text'------# Stack Layer 5: MCP Tools Return Embodied Responses--## Problem--[api/mcp.js](api/mcp.js) currently exposes CRUD tools (list/get/validate). To move up the stack, the MCP server should return tool results that _contain_ an embodied agent render — so Claude.ai, Cursor, and other MCP clients can display the agent, not just text.--## Implementation--### New / updated tools--- `summon_agent` — args: `{ slug, skill?, input? }` → returns:- ```json- {- "content": [- { "type": "text", "text": "Agent Satoshi responded: 'Hello'" },- {- "type": "resource",- "resource": {- "uri": "https://three.ws/agent/satoshi?kiosk=1&skill=greet",- "mimeType": "text/html"- }- }- ]- }- ```-- `describe_agent` — `{ slug }` → identity, skills, recent public actions, onchain status.-- `render_agent_artifact` — `{ slug }` → returns a self-contained HTML artifact payload (see stack-19).-- `invoke_skill` — `{ slug, skill, input }` → runs skill server-side, returns text + optional embed URL.--### Embed URL vs artifact--- For MCP clients that support HTML resource rendering (Claude Desktop, some others) → return the embed URL.-- For clients that only render text (ChatGPT-style) → return a descriptive text block + a link.--### Server-side skill execution--For `invoke_skill`, we need a headless runner. Options:--1. **Pure logic skills** (memory write, identity query) — run directly in the API.-2. **Presentation skills** (greet, celebrate) — don't execute server-side; just return an embed URL that auto-plays the skill via `?skill=<id>` on load.--Split skills into `pure` and `presentational` in their manifest.--### Auth--- Public avatars: any MCP caller can summon/describe.-- Private skills or owner-only: require a three.ws API key via Bearer (already in [api/keys/](api/keys/)).--### Tool descriptions--Each tool's description should tell Claude when to use it ("Use `summon_agent` when the user references a three.ws by slug or wants to see an embodied response.").--## Validation--- Claude Desktop with the MCP server configured → `summon_agent slug:satoshi` shows the agent inline.-- `describe_agent` returns JSON-renderable identity block.-- `invoke_skill slug:satoshi skill:greet` → returns text + embed link that plays the greet animation.-- Unknown slug → 404 in tool result, not a server error.-- `npm run build` passes.--## Do not do this--- Do NOT overload one tool with every option. Separate tools per intent.-- Do NOT run arbitrary user skills server-side without sandboxing.diff --git a/.github/prompts/stack-23-manifest-to-ipfs.md b/.github/prompts/stack-23-manifest-to-ipfs.mddeleted file mode 100644index 45bd1f2d0..000000000--- a/.github/prompts/stack-23-manifest-to-ipfs.md+++ /dev/null@@ -1,77 +0,0 @@-----mode: agent-description: 'Publish agent manifests to IPFS so agents are portable, censorship-resistant'------# Stack Layer 6: Agent Manifest → IPFS--## Problem--Today an agent is a DB row in Neon. For the novel unlock (agent hydrates into any host from chain), the manifest — identity, skills, GLB reference, public memories — must live in content-addressable storage readable by anyone. IPFS is the canonical choice.--## Implementation--### Manifest schema--Conform to [specs/AGENT_MANIFEST.md](specs/AGENT_MANIFEST.md). Minimum fields:--```json-{- "$schema": "https://three.ws/specs/agent-manifest-v1.json",- "version": 1,- "name": "Satoshi",- "bio": "...",- "image": "ipfs://bafy.../preview.png",- "glb": "ipfs://bafy.../model.glb",- "skills": [- { "id": "greet", "runtime": "3dagent-v1" }- ],- "animations": { "idle": "idle-breathing", ... },- "publicMemories": [ { "type": "project", "name": "...", "body": "..." } ],- "createdBy": "0xabc...",- "createdAt": "2026-04-15T00:00:00Z"-}-```--### Pinning service--Use Pinata, Web3.Storage, or Filecoin via [src/ipfs.js](src/ipfs.js) (already exists — check). Add server-side pinning via `api/ipfs/pin.js`:--- Input: manifest JSON.-- Uploads GLB to IPFS first (gets CID), references it in manifest.-- Pins manifest JSON, returns CID.--### Publish endpoint--`POST /api/avatars/:id/publish`:--- Builds manifest from DB row.-- Uploads GLB to IPFS if not already.-- Pins manifest.-- Stores returned CID in `avatars.manifest_cid`.-- Returns `{ cid, ipfsUrl, gatewayUrl }`.--### Gateway fallback--For rendering from IPFS, support multiple gateways (Cloudflare, ipfs.io, dweb.link). [src/agent-resolver.js](src/agent-resolver.js) tries them in order on failure.--### Update semantics--IPFS is immutable. Each publish creates a new CID. Track history in `avatars.manifest_history` array. The _latest_ CID is the one registered on-chain (next prompt).--### Signed manifest--Sign the manifest JSON with the owner's wallet (EIP-712). Store signature inside the manifest as `ownerSignature`. Anyone can verify the manifest was published by the claimed owner.--## Validation--- Publish an avatar → returns an IPFS CID.-- Fetch from `https://ipfs.io/ipfs/<cid>` → returns the manifest JSON.-- Resolver can render the agent using only the CID.-- Tamper with the manifest → signature verification fails.-- `npm run build` passes.--## Do not do this--- Do NOT pin private memories to IPFS. Only `publicMemories`.-- Do NOT trust the pinning service as the only copy — pin via at least two providers.diff --git a/.github/prompts/stack-24-onchain-identity-register.md b/.github/prompts/stack-24-onchain-identity-register.mddeleted file mode 100644index 1a1669a10..000000000--- a/.github/prompts/stack-24-onchain-identity-register.md+++ /dev/null@@ -1,69 +0,0 @@-----mode: agent-description: 'Register agent identity on ERC-8004 contract with IPFS manifest CID'------# Stack Layer 6: ERC-8004 On-Chain Registration--## Problem--For agents to be portable into ANY host app directly from chain, each agent needs an on-chain record mapping a stable ID to the latest manifest CID. ERC-8004 identity contracts are already deployed (per [src/erc8004/abi.js](src/erc8004/abi.js)); wire up registration + updates.--## Implementation--### Contract interaction--Use the deployed contract addresses in [src/erc8004/abi.js:61-69](src/erc8004/abi.js#L61-L69). Confirm the contract's public ABI includes:--- `register(address owner, string manifestURI) returns (uint256 agentId)`-- `updateManifest(uint256 agentId, string manifestURI)`-- `getAgent(uint256 agentId) returns (address owner, string manifestURI, uint256 updatedAt)`--If the deployed contract differs, work with the deployed ABI.--### Register flow--After publishing to IPFS (stack-23), the owner can register on-chain:--1. UI: "Register on-chain" button on the edit page Identity tab (stack-10).-2. Confirm gas prompt — shows estimated cost.-3. Owner wallet signs the tx calling `register(owner, "ipfs://<cid>")`.-4. Listen for `AgentRegistered` event → extract `agentId` → store in `avatars.onchain_agent_id` + `avatars.onchain_chain_id`.-5. Show tx link on Basescan.--### Update flow--For subsequent publishes, call `updateManifest(agentId, newCid)`. Same UX.--### Gasless option--Support meta-transactions if the deployed contract has them. Otherwise sponsor gas via Biconomy / Gelato (v2 concern — don't add dep now, just log as a todo).--### Client code--New module `src/onchain/register.js`:--- `registerAgent(signer, cid) => { agentId, txHash }`-- `updateManifest(signer, agentId, cid) => { txHash }`-- `getAgent(agentId, provider) => { owner, manifestURI, updatedAt }`--### DB--`avatars` table: add `onchain_agent_id` (bigint, nullable), `onchain_chain_id` (int, nullable), `onchain_tx_hash` (text), `onchain_updated_at`.--### Public verification--The public agent page (stack-15) shows a "Verified on-chain" badge if `onchain_agent_id` is set, linking to the Basescan tx.--## Validation--- Register an agent on-chain (Base Sepolia) → tx confirms, agentId stored.-- Call `getAgent(agentId)` from a script → returns correct owner + manifest URI.-- Edit avatar, publish new manifest, call `updateManifest` → tx confirms, latest CID on chain.-- Non-owner tries to update → reverts.-- `npm run build` passes.--## Do not do this--- Do NOT hardcode Basescan URL — derive from chain id.-- Do NOT re-register if the agent is already registered — call `updateManifest` instead.diff --git a/.github/prompts/stack-25-hydrate-from-chain.md b/.github/prompts/stack-25-hydrate-from-chain.mddeleted file mode 100644index 857d8e124..000000000--- a/.github/prompts/stack-25-hydrate-from-chain.md+++ /dev/null@@ -1,70 +0,0 @@-----mode: agent-description: 'Hydrate an embodied agent into any host directly from its on-chain record'------# Stack Layer 6: Hydrate Agent From Chain--## Problem--The novel unlock: a host app (LobeHub, Claude, any site) can render an embodied agent given only a chain id + agent id, with zero dependency on three.ws for data. The JS library reads the chain record, fetches the manifest from IPFS, renders the agent.--## Implementation--### Library API ([dist-lib/agent-3d.js](dist-lib/agent-3d.js) / [src/element.js](src/element.js))--Web component usage:--```html-<script src="https://three.ws/dist-lib/agent-3d.js"></script>-<agent-3d chain="base-sepolia" agent-id="42"></agent-3d>-```--Programmatic:--```js-import { renderAgent } from '3d-agent';-renderAgent(document.getElementById('host'), { chain: 'base-sepolia', agentId: 42 });-```--### Resolution chain--Inside [src/agent-resolver.js](src/agent-resolver.js):--1. Accept `(chain, agentId)` OR `(manifestCid)` OR `(slug)` OR `(url)`.-2. If `(chain, agentId)`: read the on-chain registry (read-only RPC — default to a free public RPC for Base; let host override).-3. Get `manifestURI` (usually `ipfs://...`).-4. Fetch manifest from IPFS via multi-gateway fallback.-5. Verify `ownerSignature` against the `createdBy` address in the manifest.-6. Fetch GLB from IPFS.-7. Boot the viewer + agent runtime with the hydrated spec.--### Zero-infra path--Note the critical property: once registered, an agent can be rendered in a host even if **three.ws is offline**. Everything needed lives on-chain + IPFS + the library JS (bundlable into host).--### Caching--- `localStorage` cache of `chain:agentId → manifestCid` with short TTL + ETag-style revalidation on next load.-- `Cache-Control: public, max-age=31536000, immutable` for GLB fetches from IPFS gateways.--### Skill execution without origin--Skills that require a backend (e.g., `remember`) can POST to `createdBy`'s trusted endpoint (from manifest) OR degrade gracefully. For v1, presentational skills work fully (animation, emotion); network skills show "disabled in unhosted mode".--### Chain support--Start with Base Sepolia (dev) and Base (mainnet). Extensible: map chain name → RPC URL → deployed contract address in a small registry at [src/erc8004/chains.js](src/erc8004/chains.js).--## Validation--- `<agent-3d chain="base-sepolia" agent-id="42">` on a blank HTML page → avatar renders, animates, responds to local skills.-- Disable network to three.ws (block in devtools) → agent still renders from IPFS.-- Tampered manifest (wrong signature) → refuses to render, shows "Unverified".-- `npm run build:lib` produces a working `dist-lib/agent-3d.js` that supports chain hydration.-- `npm run build` passes.--## Do not do this--- Do NOT require a three.ws API key for public chain-hydrated render.-- Do NOT hardcode one IPFS gateway — use fallbacks.diff --git a/.github/prompts/stack-26-signed-action-log.md b/.github/prompts/stack-26-signed-action-log.mddeleted file mode 100644index 5c4693767..000000000--- a/.github/prompts/stack-26-signed-action-log.md+++ /dev/null@@ -1,63 +0,0 @@-----mode: agent-description: 'Wallet-signed agent actions with on-chain anchoring for reputation'------# Stack Layer 6: Signed Action Log--## Problem--Agents emit actions continuously (skill runs, memory writes, interactions). For reputation to be portable and verifiable, significant actions should be signable by the owner's wallet and optionally anchored on-chain. Without this, reputation is just a DB row we control.--## Implementation--### Action signing--For opt-in "significant" actions (configurable per skill), the agent protocol captures the action payload and:--1. Hashes it (`keccak256(canonicalJSON(action))`).-2. Optionally prompts the owner to sign it via EIP-712 typed data.-3. Stores `{action, hash, signature, signer}` in the `agent_actions` table.--### Batch anchoring--Every N actions or daily, compute a Merkle root of new action hashes → write the root on-chain via ERC-8004 reputation registry (`submitActionRoot(agentId, merkleRoot)`).--### Verification--Public action log endpoint `GET /api/agents/:id/actions/verified` returns actions with:--- `signature` (EIP-712, verifiable client-side).-- `merkleProof` (Merkle path to the on-chain root, if anchored).--Any consumer can independently verify:--- Signature → action was approved by the owner at the time.-- Merkle proof + on-chain root → action existed by block time X.--### Background mode--For high-frequency actions (emotion drift, idle skills), skip signing — just log.-For user-initiated or remote-initiated skills (summon from Claude, invoke via MCP), sign by default.-Configurable per-skill in the manifest: `"signing": "required" | "optional" | "never"`.--### Tools--CLI helper: `npm run verify-action -- <actionId>` → checks signature + merkle proof.--### Replay attack prevention--Sign includes nonce + timestamp. Server rejects signatures older than 10 min for newly-submitted actions.--## Validation--- Invoke a signed-by-default skill → owner wallet prompts for signature → action stored with sig.-- Fetch verified log → signature verifies against owner address.-- Wait for next batch anchor → on-chain root written; merkle proof returned.-- Third-party verifier script: takes an action + root → confirms inclusion.-- `npm run build` passes.--## Do not do this--- Do NOT sign every emotion frame. Limit to meaningful actions.-- Do NOT write every individual action on-chain. Merkle-batch.diff --git a/.github/prompts/stack-27-agents-gallery.md b/.github/prompts/stack-27-agents-gallery.mddeleted file mode 100644index 8c2d1f922..000000000--- a/.github/prompts/stack-27-agents-gallery.md+++ /dev/null@@ -1,62 +0,0 @@-----mode: agent-description: 'Public /agents gallery — discover, search, featured agents'------# Stack Layer 4 (support): Agents Gallery--## Problem--Without a discovery page, created agents are islands. Need a public `/agents` gallery that lists public avatars, supports search, and surfaces featured agents.--## Implementation--### Page--`public/agents/index.html` — native DOM, infinite scroll.--### Data--`GET /api/avatars/public?cursor=&q=&tag=&sort=recent|popular`:--- Returns `{ items: [...], nextCursor, total }`.-- Items: `{ id, slug, name, bio, thumbnailUrl, ownerHandle, skillsCount, onchain: bool, createdAt }`.-- Only `visibility: 'public'`, not soft-deleted.-- Cursor is created_at-based for `recent`, score-based for `popular`.--### Card--Each card shows: small 3D preview (static thumbnail, not live viewer — perf), name, bio, skills count, verified-onchain badge. Click → `/agent/:slug`.--### Thumbnails--Generated at publish time (stack-15 or a separate cron): render the avatar's idle frame to a 512×512 PNG and cache. Store URL in `avatars.thumbnail_url`.--### Featured--`featured` bool on `avatars` table. Editable only by admin. Featured agents surface at top with a badge.--### Search--Simple Postgres full-text on `name`, `bio`, and denormalized skill names. Use `pg_trgm` for fuzzy match.--### Tags--Denormalized from attached skills' tags. Filter chips at the top ("3d", "assistant", "creative"…).--### Empty state--If no agents yet: "Be the first. Create your agent →" link to `/create/`.--## Validation--- `/agents` lists public avatars with thumbnails.-- Search "satoshi" finds matching agents.-- Scroll to bottom → next page loads.-- Private / deleted avatars never appear.-- `npm run build` passes.--## Do not do this--- Do NOT render live viewers for each card — thumbnails only (one live viewer per card would kill the page).-- Do NOT expose owner wallets or emails.diff --git a/.github/prompts/stack-28-first-run-tour.md b/.github/prompts/stack-28-first-run-tour.mddeleted file mode 100644index 2e8470f41..000000000--- a/.github/prompts/stack-28-first-run-tour.md+++ /dev/null@@ -1,61 +0,0 @@-----mode: agent-description: 'First-run onboarding tour — connect wallet → take selfie → meet your agent'------# Stack Layer 2 (support): First-Run Onboarding--## Problem--New users landing on three.ws see a viewer with no clear path to the magic moment. Need a guided first-run: connect wallet → take selfie → meet your agent → what next.--## Implementation--### Router--On `/` (home), if `!session`, show a landing with a big "Create your agent" CTA → routes to `/welcome/`.--### /welcome/ flow--Three-step wizard (server-side state: `users.onboarding_step`):--1. **Step 1: Connect** — "Your agent lives on-chain. Start by connecting a wallet or signing up with email."- - Both auth paths.- - On success, advance to step 2.-2. **Step 2: Take a selfie** — "This becomes your agent's body. We use your photo to generate a rigged 3D avatar."- - Launches the flow from stack-05.- - While generating, show "While we work, here's what your agent can do..." with 3 cards (skills, memory, embed).-3. **Step 3: Meet your agent** — "Here's [name]. Say hi?"- - Live viewer with the new avatar.- - Big "Try a skill" button, "Edit your agent" button, "Share your agent" button.- - First action (e.g., greet) fires automatically — the avatar's first action is to greet its owner.--### Skip / later--Each step has "Skip for now" → marks step as skipped in `users.onboarding_step`. User can resume from `/welcome/`.--### Empty-state avatar--If user skips the selfie step, assign a default placeholder avatar (a specific preset, e.g., the "Shiba" preset). They can replace later.--### Persistence--`users.onboarding_completed_at` set after step 3. `/` routes through `/welcome/` only if this is null.--### Analytics--Fire `onboarding.step.reached` / `onboarding.step.completed` / `onboarding.skipped` events.--## Validation--- New signup → lands on `/welcome/` step 1.-- Completes all 3 → lands on `/dashboard/` with their agent visible.-- Skip step 2 → default avatar assigned, flow continues.-- Returning incomplete user → resumes on their current step.-- `onboarding_completed_at` set → `/welcome/` redirects to `/dashboard/`.-- `npm run build` passes.--## Do not do this--- Do NOT gate the viewer behind onboarding — the viewer without login should still work for anonymous users loading models.-- Do NOT make the user wait idle during avatar generation — the fun-facts-and-skills panel fills that gap.diff --git a/.github/prompts/stack-29-biometric-consent.md b/.github/prompts/stack-29-biometric-consent.mddeleted file mode 100644index fb7778236..000000000--- a/.github/prompts/stack-29-biometric-consent.md+++ /dev/null@@ -1,72 +0,0 @@-----mode: agent-description: 'Biometric (face photo) consent flow — required before selfie capture'------# Stack Layer 2 (legal): Biometric Consent--## Problem--Selfie-to-avatar involves processing biometric data. Depending on jurisdiction (GDPR, BIPA, CCPA), we need explicit informed consent before capture, retention limits, and a delete path. Ship this with the selfie flow or we can't launch it in-region.--## Implementation--### Consent modal (before stack-05)--Before `/create/` lets the user open the camera, show a consent modal:--- What we collect (one facial photo).-- What we do (send to provider [RPM or chosen], generate 3D avatar).-- How long we retain (30 days for raw photo, then delete; avatar GLB retained per user choice).-- Sub-processors listed.-- Link to full privacy policy.-- Explicit checkbox: "I understand and consent."-- Two buttons: "I consent — continue" and "Cancel."--No "Pre-checked" checkbox. No dark patterns.--### DB--`user_consents` table: `{ user_id, consent_type, granted_at, granted_ip, granted_ua, revoked_at }`. Immutable log.--### Backend enforcement--`POST /api/avatars/create-from-photo` checks the user has an active `biometric_v1` consent. If not, 403.--### Revoke / delete--`/settings/privacy/`:--- List of active consents.-- "Revoke biometric consent" button → logs revocation, triggers delete of all stored raw photos, prevents new selfie-to-avatar.-- "Delete my account" button → triggers full data deletion (avatars, memories, action log, consents). Soft-delete 30d then purge.--### Retention job--Vercel cron daily:--- Delete raw photos older than 30 days from R2 (regardless of revocation).-- For revoked consents, delete immediately (next cron run).--### Regional detection (optional)--Detect user region via `Accept-Language` + IP geolocation (rough, not gated). Show consent to EVERYONE for safety; regional detection is for showing extra disclosures (EU DPA contact, CCPA opt-out) — non-blocking.--### Documentation--Public privacy policy at `/privacy.html` — list the sub-processors, data flows, and user rights. Keep in sync with provider terms.--## Validation--- Try to create without consent → modal appears, camera won't open until consent.-- Consent → modal closes, flow continues.-- Cancel → back to `/dashboard/`.-- Revoke consent → raw photo deleted within 24h, selfie flow blocked.-- Account delete → all data gone within 30d (soft → hard).-- `npm run build` passes.--## Do not do this--- Do NOT pre-check the consent box.-- Do NOT retain photos past 30 days.-- Do NOT send photos to providers not listed in the disclosure.diff --git a/.github/prompts/texture-inspector.md b/.github/prompts/texture-inspector.mddeleted file mode 100644index fb98f4781..000000000--- a/.github/prompts/texture-inspector.md+++ /dev/null@@ -1,83 +0,0 @@-----mode: agent-description: 'Build texture inspector with channel separation and full-size preview'------# Texture Inspector--## Context--The README roadmap lists **"Texture Inspector — view individual texture channels (baseColor, normal, metallic-roughness, AO, emissive)"**. This complements the Material Editor by letting users visually inspect every texture in the model.--## Implementation--### 1. Texture Catalog (`src/texture-inspector.js`)--After a model loads, traverse all materials and collect every unique texture:--| Slot | Three.js Property | glTF Channel |-| ------------------ | ------------------------------------------------- | ------------------------ |-| Base Color | `material.map` | baseColorTexture |-| Normal | `material.normalMap` | normalTexture |-| Metallic-Roughness | `material.metalnessMap` / `material.roughnessMap` | metallicRoughnessTexture |-| Occlusion | `material.aoMap` | occlusionTexture |-| Emissive | `material.emissiveMap` | emissiveTexture |-| Alpha | (from `material.map` alpha channel) | — |--### 2. Channel Separation--For packed textures (metallic-roughness is R+G channels in one image):--- Extract individual channels using a canvas 2D context-- Display each channel as a separate grayscale image:- - **R** = Occlusion (if packed)- - **G** = Roughness- - **B** = Metallic--Use `getImageData()` and pixel manipulation to isolate channels.--### 3. Texture Info Display--For each texture, show:--- Resolution (width × height)-- Format (PNG/JPEG/KTX2/Basis)-- Memory estimate (width × height × 4 bytes for RGBA, accounting for mipmaps)-- UV channel index-- Wrap mode (repeat/clamp/mirror)-- Min/mag filter-- Which materials reference this texture--### 4. Full-Size Preview--- Click any texture thumbnail → opens a lightbox/modal with the full-resolution image-- Zoom/pan controls in the lightbox-- Channel toggle buttons (R/G/B/A) to view individual channels-- Optional checkerboard background to see alpha transparency--### 5. UV Visualization--- Render UV wireframe overlay on the texture in the lightbox-- Uses the mesh's UV coordinates drawn as lines on a canvas-- Helps identify UV islands, overlap, and wasted texture space--### 6. Integration--- Add "Textures" folder to dat.gui in `src/viewer.js`-- Or integrate as a tab in the Scene Explorer side panel-- Keyboard shortcut (X) to toggle texture inspector panel--## File Structure--```-src/-├── texture-inspector.js # Texture catalog, channel extraction, UV overlay-```--## Validation--- Load DamagedHelmet.glb → shows all 5 texture slots with thumbnails-- Metallic-roughness texture shows separated R/G/B channels-- Click thumbnail → full-size lightbox with zoom-- Memory estimates are reasonable (match GPU inspector tools)-- Works with KTX2/Basis textures (after decode)diff --git a/.github/prompts/update-docs.md b/.github/prompts/update-docs.mddeleted file mode 100644index 8e2e50ecd..000000000--- a/.github/prompts/update-docs.md+++ /dev/null@@ -1,92 +0,0 @@-----mode: agent-description: 'Update all documentation to cover new modules and current architecture'------# Update Documentation--## Problem--`docs/DEVELOPMENT.md` project layout is outdated — missing `avatar-creator.js`, `avaturn-agent.js`, `ipfs.js`, `model-info.js`, `annotations.js`, and the entire `erc8004/` directory. Other docs reference a simpler architecture than what exists.--## Tasks--### 1. Update `docs/DEVELOPMENT.md`--Rewrite the project layout section to include all current files:--```-src/-├── app.js # Main entry — routing, drag-and-drop, hash params-├── viewer.js # Three.js Viewer class — rendering, GUI, controls-├── validator.js # Khronos glTF-Validator integration-├── environments.js # HDR environment map definitions-├── ipfs.js # IPFS/Arweave URI resolution with gateway fallback-├── avatar-creator.js # Avaturn SDK integration for avatar creation-├── avaturn-agent.js # Chat agent with speech synthesis/recognition-├── model-info.js # Model metadata overlay (vertices, triangles, etc.)-├── annotations.js # Mesh label annotations with canvas rendering-├── material-editor.js # (planned) PBR material parameter editing-├── scene-explorer.js # (planned) Scene graph tree view-├── components/-│ ├── footer.jsx # Footer component-│ ├── validator-report.jsx # Validation report rendered as HTML-│ ├── validator-table.jsx # Validation issues table-│ └── validator-toggle.jsx # Validation panel toggle button-├── erc8004/-│ ├── index.js # Re-exports for ERC-8004 module-│ ├── abi.js # Identity Registry ABI and deployment addresses-│ ├── agent-registry.js # On-chain agent registration flow-│ └── register-ui.js # Registration form UI-api/-├── mcp.js # MCP server (Streamable HTTP, JSON-RPC)-├── avatars/ # Avatar CRUD REST API-├── auth/ # User authentication (register, login, logout)-├── oauth/ # OAuth 2.1 (authorize, token, revoke, introspect)-├── keys/ # API key management-├── usage/ # Usage tracking and summaries-├── _lib/ # Shared utilities (db, auth, crypto, rate-limit, etc.)-└── .well-known/ # OAuth discovery endpoints-```--### 2. Update `docs/ARCHITECTURE.md`--Add sections for:--- **Avatar System**: Avaturn SDK → export GLB → save to R2 → view in 3D-- **ERC-8004 Integration**: Identity Registry → IPFS pin → on-chain registration-- **MCP Server**: JSON-RPC dispatch, tool catalog, OAuth auth flow-- **A2A Discovery**: agent-card.json, agent-registration.json-- **IPFS/Arweave**: URI resolution, multi-gateway fallback--### 3. Update `docs/API.md`--Add documentation for:--- `AvatarCreator` class (constructor, open, close)-- `NichAgent` class (chat agent)-- `IPFS` module (resolveIpfsUrl, resolveArweaveUrl)-- `ModelInfo` module (createModelInfo)-- `Annotations` module (buildAnnotations, renderAnnotationCanvas)-- `ERC8004` module (registerAgent, lookupAgent, agentRegistryId)-- All MCP tools-- All REST API endpoints--### 4. Update `docs/DEPLOYMENT.md`--Add:--- Environment variables needed for full deployment (R2, DB, OAuth secrets)-- MCP server deployment considerations-- Contract deployment references (link to `deploy-erc8004-contracts.md`)--### 5. Update `README.md` Roadmap--Move completed items from roadmap to a "Completed" section as features ship.--## Validation--- All files mentioned in docs actually exist-- All classes/functions documented in API.md exist in source-- No references to deleted or renamed files-- Project layout in DEVELOPMENT.md matches actual `ls -R` outputdiff --git a/.github/skills/3d-features/SKILL.md b/.github/skills/3d-features/SKILL.mddeleted file mode 100644index 3b8c79762..000000000--- a/.github/skills/3d-features/SKILL.md+++ /dev/null@@ -1,73 +0,0 @@-----name: 3d-features-description: 'Add or modify Three.js 3D features in the viewer. Use when: adding rendering features, new GUI controls, camera behavior, loaders, post-processing, environment maps, animation features, display toggles, materials, or extending the Viewer class.'-argument-hint: 'Describe the 3D feature to add or change'------# 3D Feature Development--## When to Use--- Adding new rendering capabilities (post-processing, shadows, new material types)-- Adding or modifying dat.gui control panels-- Changing camera behavior or adding camera modes-- Adding new loaders or asset format support-- Modifying lighting, environment maps, or tone mapping-- Adding display toggles (wireframe, skeleton, grid, etc.)-- Animation playback features or morph target controls--## Key File: `src/viewer.js`--The `Viewer` class manages all Three.js rendering. Key sections:--### State Object--All GUI-controllable state lives in `this.state` (defined in constructor). To add a new toggle:--1. Add default value to `this.state`-2. Add GUI control in the appropriate `addGUI()` subfolder-3. Add the handler method on the `Viewer` class--### GUI Folders--dat.gui controls are organized into folders created in `addGUI()`:--- **Lights** — Ambient/directional intensity, punctual lights, exposure, tone mapping-- **Display** — Wireframe, skeleton, grid, axes, auto-rotate, background-- **Animation** — Playback speed, individual clip controls, morph targets-- **Cameras** — Default + scene cameras--### Loaders--| Loader | Purpose | CDN Path |-| ---------------- | -------------------- | --------------------------------- |-| `GLTFLoader` | glTF/GLB models | Built-in Three.js |-| `DRACOLoader` | Compressed geometry | `unpkg.com/three@.../draco/gltf/` |-| `KTX2Loader` | Basis textures | `unpkg.com/three@.../basis/` |-| `MeshoptDecoder` | Meshopt geometry | Built-in Three.js |-| `EXRLoader` | HDR environment maps | Built-in Three.js |--### Environment Maps--Defined in `src/environments.js` as an array of `{ id, name, path, format }` objects. To add a new environment:--1. Add entry to the array in `environments.js`-2. The viewer auto-discovers it via the `environments` import--## Procedure--1. Identify which section of `src/viewer.js` to modify-2. For new GUI controls: add state → add GUI control → add handler-3. For new loaders: import from `three/addons/`, configure in constructor-4. For new environments: add to `src/environments.js`-5. Test with `npm run dev` at `http://localhost:3000`-6. Test with various glTF models (drag-and-drop or `?model=` param)--## Three.js Patterns Used--- `PMREMGenerator` for environment map preprocessing-- `AnimationMixer` for animation playback with `clipAction()`-- `OrbitControls` for camera interaction-- `Box3` for model bounding box / auto-framing-- `traverse()` for material/mesh iteration-- `LoadingManager` for coordinated asset loadingdiff --git a/.github/skills/3d-viewer/SKILL.md b/.github/skills/3d-viewer/SKILL.mddeleted file mode 100644index 3ddb339b1..000000000--- a/.github/skills/3d-viewer/SKILL.md+++ /dev/null@@ -1,105 +0,0 @@-----name: 3d-viewer-description: 'Full project workflow for the three.ws platform. Use when: developing features, debugging, modifying UI, understanding architecture, running dev server, or making code changes anywhere in the repo (viewer, agent runtime, API, contracts).'-argument-hint: 'Describe what you want to do'------# three.ws — Project Workflow--## Overview--**three.ws** started as a glTF 2.0 / GLB viewer and grew into a full embodied-agent platform. Live at [three.ws](https://three.ws/). Read [/CLAUDE.md](../../../CLAUDE.md) first — this skill is an index; the CLAUDE.md files are the source of truth.--## Two halves--- **Viewer half** — pure three.js. GLB loading, lighting, animations, validation, dat.gui.-- **Agent half** — persona (`agent-identity.js`), memory (`agent-memory.js`), skills (`agent-skills.js`), avatar emotion (`agent-avatar.js`), LLM runtime (`runtime/`), wallet identity (`erc8004/`), protocol bus (`agent-protocol.js`).--The viewer never imports the agent half. The agent layer wraps the viewer through `runtime/scene.js` (`SceneController`).--## Where code lives--| Area | Path | Scoped doc |-| ---------------------------- | ------------ | --------------------------------------------------- |-| Browser app (viewer + agent) | `src/` | [src/CLAUDE.md](../../../src/CLAUDE.md) |-| Vercel serverless API | `api/` | [api/CLAUDE.md](../../../api/CLAUDE.md) |-| ERC-8004 Solidity registries | `contracts/` | [contracts/CLAUDE.md](../../../contracts/CLAUDE.md) |-| Format specs | `specs/` | — |-| Priority-stack build prompts | `prompts/` | [prompts/INDEX.md](../../../prompts/INDEX.md) |-| User-facing docs | `docs/` | — |-| Static pages / assets | `public/` | — |-| SDK package | `sdk/` | — |--Top-level HTML entries: `index.html`, `features.html`, `embed.html`, `agent-home.html`, `agent-embed.html`. Additional routes are rewritten by the `vercel-rewrites` middleware in [vite.config.js](../../../vite.config.js) and mirrored in [vercel.json](../../../vercel.json).--## Tech stack--- **three.js** r176 — WebGL2 rendering + `GLTFLoader`, `DRACOLoader`, `KTX2Loader`, `MeshoptDecoder`, `OrbitControls`-- **dat.gui** + **tweakpane** — control panels-- **simple-dropzone** — file drops-- **vhtml** — JSX → HTML string rendering (no virtual DOM)-- **gltf-validator** — KhronosGroup validation-- **Vite 7** — dev server + build (two targets: `app` and `lib`)-- **vite-plugin-pwa** — service worker + manifest-- **ethers v6**, **viem**, **@privy-io/js-sdk-core** — wallet + on-chain-- **Neon Postgres**, **Upstash Redis**, **Cloudflare R2**, **Vercel** — backend-- **Foundry** + **OpenZeppelin** (contracts)--## Commands--```bash-npm install-npm run dev # app dev server on :3000-npm run dev:lib # library build watch-npm run build # app → dist/-npm run build:lib # web component → dist-lib/-npm run build:all # both-npm run deploy # build + vercel --prod-npx prettier --write <file>-node --check <file.js>-```--No automated test suite (`npm test` exits 0). Verify with `node --check`, `npm run build`, and manual smoke at `localhost:3000`.--## Conventions--- ESM only (no CommonJS in `src/` or `api/`)-- Prettier: **tabs**, 4-wide, single quotes, 100-col print width-- No TypeScript in the main app (JSDoc for public APIs); `sdk/` may use TS-- Components are **vhtml JSX**, not React — `.jsx` files, `jsxFactory: 'vhtml'`-- URL hash params live in `src/app.js`: `model`, `widget`, `agent`, `kiosk`, `brain`, `proxyURL`, `preset`, `cameraPosition`, `register`-- Tool result shape: `{ ok: true, ... }` or `{ ok: false, error: 'msg' }`-- Naming: CamelCase classes, camelCase methods, UPPER_CASE constants, `_underscore` private--## Priority stack — before you start--The order of work is fixed in [prompts/INDEX.md](../../../prompts/INDEX.md):--1. Wallet auth (SIWE / Privy)-2. Selfie → agent-3. Edit avatars-4. View + embed-5. Portable embed (Claude.ai / LobeHub)-6. On-chain deployment (ERC-8004)--If a task isn't in a band, ask first. Side lanes (`pretext/`, `scalability/`, `widget-studio/` polish, CLI, AR, screenshot export) are explicitly deprioritized.--## Where to change what--- Rendering / GUI / display toggles → `src/viewer.js` and `src/viewer/*.js` (see [3d-features](../3d-features/SKILL.md))-- Validation → `src/validator.js` + `src/components/validator-*.jsx` (see [model-validation](../model-validation/SKILL.md))-- Build / deploy / Vercel routes → see [build-deploy](../build-deploy/SKILL.md)-- Agent persona / memory / skills → `src/agent-*.js`, `src/runtime/`, `src/skills/`, `src/memory/` — read [src/CLAUDE.md](../../../src/CLAUDE.md)-- Auth / avatars / OAuth / MCP / rate-limit / R2 → `api/` — read [api/CLAUDE.md](../../../api/CLAUDE.md)-- ERC-8004 registries → `contracts/` — read [contracts/CLAUDE.md](../../../contracts/CLAUDE.md)-- Top-level routing / URL hash params → `src/app.js` (don't create a new routing layer)--## Ground rules--- One task, one PR. Note unrelated bugs in the report — don't fix them inline.-- Edit existing files before creating new ones. No new top-level `.md` files unless asked.-- No new runtime deps without approval.-- `node --check` every modified JS. `npm run build` before reporting done. Report both outputs.-- Respect `Files off-limits` in prompt files — parallel work may touch them.-- Never `forge script --broadcast` without explicit user approval. Deployed contract addresses are immutable.-- Report what changed, what you skipped, what broke, and any surprises.diff --git a/.github/skills/build-deploy/SKILL.md b/.github/skills/build-deploy/SKILL.mddeleted file mode 100644index acc61fae7..000000000--- a/.github/skills/build-deploy/SKILL.md+++ /dev/null@@ -1,99 +0,0 @@-----name: build-deploy-description: 'Build, deploy, and configure the 3D viewer app. Use when: running dev server, building for production, deploying to Vercel, configuring CORS, editing vercel.json routes, managing static assets, or troubleshooting build issues.'-argument-hint: 'Describe the build or deploy task'------# Build & Deploy--## When to Use--- Starting development server or troubleshooting it-- Building for production-- Deploying to Vercel-- Configuring CORS, routes, or caching-- Managing static assets in `public/`-- Fixing build errors or dependency issues--## Commands--| Command | Purpose |-| ----------------------------------- | ------------------------------------------- |-| `npm install` | Install dependencies |-| `npm run dev` | Vite dev server on port 3000 |-| `npm run build` | Production build → `dist/` |-| `npm run clean` | Remove `dist/` contents |-| `npm run deploy` | Build + `vercel --prod` with local config |-| `npm version <patch\|minor\|major>` | Bump version, auto-pushes via `postversion` |--## Vite Configuration--**Config**: [`vite.config.js`](../../../vite.config.js)--- Two build targets switched via `TARGET` env var:- - `TARGET=app` (default) → multi-page app in `dist/` (entries: `index.html`, `features.html`, `embed.html`, `agent-home.html`, `agent-embed.html`)- - `TARGET=lib` → self-contained `<agent-3d>` web component in `dist-lib/` (ESM + UMD, three.js bundled)-- JSX configured for vhtml: `jsxFactory: 'vhtml'`, `jsxFragment: '"div"'`-- Dev server has a `vercel-rewrites` middleware that mirrors Vercel routing for `/login`, `/register`, `/dashboard`, `/studio`, `/widgets`, `/docs/widgets`, `/agent`, `/agent/:id`, `/agent/:id/embed`-- `vite-plugin-pwa` emits the service worker + manifest-- Static assets: `public/` folder copied to build output--## Vercel Deployment--**Config**: `vercel.json`--Key routes:--- `/assets/*` — Cached 1 week (`max-age=604800`)-- `/.well-known/*` — Cached 1 day, serves from `public/.well-known/`-- `/robots.txt`, `/sitemap.xml` — Served from `public/`-- `/avatars/*` — Served from `public/avatars/`--**Domain**: [three.ws](https://three.ws/)--## CORS Configuration--**Config**: `cors.json`--Allowed origins:--- `https://three.ws/` and subdomains-- `http://localhost:*` / `https://localhost:*`-- Specific partner domains--## Static Assets--```-public/-├── avatars/ → Default 3D model files (GLB)-├── .well-known/ → Domain verification files-├── robots.txt → Search engine directives-└── sitemap.xml → Site map-```--## Procedure--### Local Development--1. `npm install`-2. `npm run dev`-3. Open `http://localhost:3000`--### Production Deploy--1. `npm run build` — verify no build errors-2. `npm run deploy` — builds and deploys to Vercel-3. Verify at [three.ws](https://three.ws/)--### Adding Static Assets--1. Place files in `public/` (copied as-is to build output)-2. If they need caching rules, add a route in `vercel.json`-3. If they need CORS access, verify origins in `cors.json`--## Troubleshooting--- **Port 3000 in use**: Kill existing process or edit `package.json` dev script port-- **Build fails on Three.js imports**: Check `three` version in `package.json` matches CDN paths in `viewer.js`-- **CORS errors**: Check `cors.json` for allowed origins-- **Assets 404 after deploy**: Verify route patterns in `vercel.json`diff --git a/.github/skills/model-validation/SKILL.md b/.github/skills/model-validation/SKILL.mddeleted file mode 100644index d178b2e03..000000000--- a/.github/skills/model-validation/SKILL.md+++ /dev/null@@ -1,71 +0,0 @@-----name: model-validation-description: 'glTF model validation and reporting features. Use when: modifying validation logic, customizing validation reports, changing severity handling, adding new validation checks, fixing validator UI, or working with gltf-validator integration.'-argument-hint: 'Describe the validation change or feature'------# Model Validation--## When to Use--- Modifying how glTF models are validated-- Changing validation report display or formatting-- Adding/removing severity levels or message grouping-- Fixing validator toggle or report lightbox UI-- Extending metadata extraction from validated models-- Working with the `gltf-validator` library--## Architecture--```-src/validator.js → Validator class: runs validation, processes reports-src/components/validator-toggle.jsx → Status badge (error/warning/info/hint counts)-src/components/validator-report.jsx → Full report lightbox with metadata + issue tables-src/components/validator-table.jsx → Individual issue severity table rendering-```--## Validation Flow--1. **App** calls `validator.validate(rootFile, rootPath, assetMap, response)` after model loads-2. **Validator** fetches the model bytes via `fetch()` → `ArrayBuffer`-3. Calls `validateBytes()` from `gltf-validator` with external resource resolver-4. Processes the report: groups messages, extracts metadata, computes max severity-5. Renders `ValidatorToggle` — a clickable badge showing issue counts-6. On click → renders `ValidatorReport` in a lightbox overlay--## Severity Levels--| Index | Level | CSS Class |-| ----- | -------- | ------------------------- |-| 0 | Errors | `report-toggle--errors` |-| 1 | Warnings | `report-toggle--warnings` |-| 2 | Infos | `report-toggle--infos` |-| 3 | Hints | `report-toggle--hints` |--Messages are grouped by `code` and `message` text. Grouped messages show a count badge.--## Key Methods--| Method | Purpose |-| ------------------------------- | -------------------------------------------------------------------- |-| `validate()` | Entry point — fetches model, runs validator, sets report |-| `resolveExternalResource()` | Resolves URIs for multi-file glTF validation |-| `setReport()` | Processes raw validator output, groups messages, updates UI |-| `setResponse()` | Extracts metadata (generator, title, author, license) from glTF JSON |-| `showToggle()` / `hideToggle()` | Controls visibility of the validation badge |--## Components (vhtml JSX)--Components are **pure functions** returning HTML strings via `vhtml`:--- **ValidatorToggle(report)** — Badge with severity icon + counts-- **ValidatorReport(report)** — Full report: metadata table + issue tables per severity-- **ValidatorTable(messages)** — Table rows for a single severity group--## Procedure--1. Validation logic changes → edit `src/validator.js`-2. Report display changes → edit the relevant component in `src/components/`-3. Styling → edit `.report-toggle`, `.report` classes in `style.css`-4. Test by dropping a glTF/GLB file and clicking the validation badge-5. Use [glTF Sample Models](https://github.com/KhronosGroup/glTF-Sample-Models/tree/master/2.0/) for testingdiff --git a/.github/workflows/contracts.yml b/.github/workflows/contracts.ymldeleted file mode 100644index e4d3e6c40..000000000--- a/.github/workflows/contracts.yml+++ /dev/null@@ -1,20 +0,0 @@-name: Contracts--on:- push:- paths:- - 'contracts/**'- pull_request:- paths:- - 'contracts/**'--jobs:- test:- runs-on: ubuntu-latest- steps:- - uses: actions/checkout@v4- with:- submodules: recursive- - uses: foundry-rs/foundry-toolchain@v1- - run: forge test- working-directory: contractsdiff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.ymldeleted file mode 100644index d121f568f..000000000--- a/.github/workflows/deploy.yml+++ /dev/null@@ -1,73 +0,0 @@-name: Build and Deploy--# Required GitHub secrets:-# VERCEL_TOKEN — Vercel account token (Account Settings → Tokens)-# VERCEL_ORG_ID — from .vercel/project.json → "orgId" (team_urotm05CzDzCGjFXzAGXqqsA)-# VERCEL_PROJECT_ID — from .vercel/project.json → "projectId" (prj_YZhPwRrlNa1PCCuwLgrisQldlxqx)-#-# If .vercel/project.json is missing, run `vercel link` locally first to regenerate it.--on:- push:- branches:- - main- workflow_dispatch:--concurrency:- group: deploy-production- cancel-in-progress: true--jobs:- build-and-deploy:- runs-on: ubuntu-latest- env:- VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}- VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}-- steps:- - uses: actions/checkout@v4- with:- fetch-depth: 0-- - uses: actions/setup-node@v4- with:- node-version: 24- cache: npm-- - name: Cache chat node_modules- uses: actions/cache@v4- with:- path: chat/node_modules- key: chat-deps-${{ hashFiles('chat/package-lock.json') }}- restore-keys: chat-deps--- - name: Install dependencies- run: npm ci-- - name: Install chat dependencies- run: cd chat && node scripts/ensure-deps.mjs-- - name: Build- run: npm run build:all-- - name: Validate dist- run: |- if [ -f scripts/check-dist.mjs ]; then- node scripts/check-dist.mjs- else- test -f dist/agent-3d/latest/agent-3d.js || (echo "dist/agent-3d/latest/agent-3d.js missing" && exit 1)- fi-- - name: Deploy to Vercel- run: |- npx vercel --prod --token ${{ secrets.VERCEL_TOKEN }} \- --yes \- --local-config vercel.json-- - name: Write job summary- run: |- VERSION=$(node -p "require('./package.json').version")- echo "## Deployed ✅" >> $GITHUB_STEP_SUMMARY- echo "- **Version:** $VERSION" >> $GITHUB_STEP_SUMMARY- echo "- **CDN URL:** https://three.ws/agent-3d/latest/agent-3d.js" >> $GITHUB_STEP_SUMMARY- echo "- **Vercel env:** production" >> $GITHUB_STEP_SUMMARYdiff --git a/.github/workflows/validate-agent-cards.yml b/.github/workflows/validate-agent-cards.ymldeleted file mode 100644index c95b43c83..000000000--- a/.github/workflows/validate-agent-cards.yml+++ /dev/null@@ -1,27 +0,0 @@-name: Validate agent cards--on:- pull_request:- paths:- - 'public/.well-known/agent-registration.json'- - 'public/.well-known/3d-agent-card.schema.json'- - 'specs/3D_AGENT_CARD.md'- - '**/*.agent-card.json'- - 'scripts/validate-agent-cards.mjs'- - '.github/workflows/validate-agent-cards.yml'- - 'package.json'- - 'package-lock.json'- push:- branches: [main]--jobs:- validate:- runs-on: ubuntu-latest- steps:- - uses: actions/checkout@v4- - uses: actions/setup-node@v4- with:- node-version: '20'- cache: 'npm'- - run: npm ci --no-audit --no-fund- - run: npm run validate:cardsdiff --git "a/Screenshot 2026-05-04 at 2.04.17\342\200\257PM.png" "b/Screenshot 2026-05-04 at 2.04.17\342\200\257PM.png"new file mode 100644index 000000000..7db97cec0Binary files /dev/null and "b/Screenshot 2026-05-04 at 2.04.17\342\200\257PM.png" differdiff --git a/agent-home.html b/agent-home.htmlindex 52ce56f46..a131cb85a 100644--- a/agent-home.html+++ b/agent-home.html@@ -628,6 +628,87 @@border-radius: 50%;animation: mp-spin 0.7s linear infinite;}++ /* My Agents Grid */+ .my-agents-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));+ gap: 1rem;+ margin-top: 1.5rem;+ }+ .my-agents-card {+ background: rgba(255, 255, 255, 0.04);+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: 12px;+ padding: 1rem;+ text-decoration: none;+ color: inherit;+ transition: background 0.2s, border-color 0.2s;+ display: flex;+ flex-direction: column;+ align-items: center;+ text-align: center;+ }+ .my-agents-card:hover {+ background: rgba(255, 255, 255, 0.07);+ border-color: rgba(255, 255, 255, 0.25);+ }+ .my-agents-card-icon {+ width: 120px;+ height: 120px;+ border-radius: 50%;+ background: rgba(0, 0, 0, 0.2);+ margin-bottom: 1rem;+ object-fit: cover;+ }+ .my-agents-card-title {+ font-weight: 500;+ font-size: 0.9rem;+ margin-bottom: 0.25rem;+ }+ .my-agents-card-desc {+ font-size: 0.75rem;+ color: rgba(255, 255, 255, 0.5);+ line-height: 1.5;+ }+ .my-agents-card-badge {+ font-size: 0.6rem;+ background: rgba(255,215,0,0.15);+ color: #ffd700;+ padding: 0.2rem 0.5rem;+ border-radius: 999px;+ margin-top: 0.75rem;+ font-weight: 500;+ }+ .my-agents-card--new {+ border-style: dashed;+ border-color: rgba(255, 255, 255, 0.2);+ justify-content: center;+ }+ .my-agents-card--new:hover {+ border-color: rgba(255, 255, 255, 0.5);+ }+ .my-agents-card-icon-new {+ font-size: 2rem;+ width: 60px;+ height: 60px;+ border: 2px solid rgba(255,255,255,0.2);+ border-radius: 50%;+ display: flex;+ align-items: center;+ justify-content: center;+ color: rgba(255,255,255,0.4);+ transition: border-color 0.2s, color 0.2s;+ margin-bottom: 1rem;+ }+ .my-agents-card--new:hover .my-agents-card-icon-new {+ border-color: rgba(255,255,255,0.7);+ color: rgba(255,255,255,0.9);+ }+ .my-agents-card-title-new {+ font-weight: 500;+ color: rgba(255,255,255,0.7);+ }</style></head><body>@@ -899,7 +980,33 @@import { protocol } from '/src/agent-protocol.js';const agentId = location.pathname.split('/').filter(Boolean).pop();+ if (agentId === 'my-agents') {+ document.getElementById('page-agent-name').textContent = 'My Agents';+ document.getElementById('page-agent-desc').textContent = 'Create, manage, and deploy your agents.';+ document.querySelector('.agent-stage').innerHTML = `+ <div class="my-agents-grid">+ <a href="/create" class="my-agents-card my-agents-card--new">+ <div class="my-agents-card-icon-new">+</div>+ <div class="my-agents-card-title-new">Create New Agent</div>+ </a>+ </div>`;+ document.querySelector('.agent-page-card-wrap').remove();+ document.getElementById('agent-embed-section').remove();+ document.getElementById('agent-skills-section').remove();+ try {+ const resp = await fetch('/api/agents?onchain=true', { credentials: 'include' });+ if (resp.ok) {+ const { agents } = await resp.json();+ if (agents) {+ renderAgents(agents);+ }+ }+ } catch (err) {+ console.error('Could not load on-chain agents:', err);+ }+ return;+ }async function main() {const identity = new AgentIdentity({agentId: agentId || undefined,