Skip to content

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

miday

nirholasd44e9513bf83
diff --git a/.github/prompts/README.md b/.github/prompts/README.md
index 4a3462a50..e047269d7 100644
--- a/.github/prompts/README.md
+++ b/.github/prompts/README.md
@@ -7,12 +7,14 @@ Prompts are prioritized by the product stack from [memory/project_vision.md](../
## 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)
@@ -21,6 +23,7 @@ Prompts are prioritized by the product stack from [memory/project_vision.md](../
- [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)
@@ -29,6 +32,7 @@ Prompts are prioritized by the product stack from [memory/project_vision.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)
@@ -36,12 +40,14 @@ Prompts are prioritized by the product stack from [memory/project_vision.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-lobehub-plugin.md](stack-20-lobehub-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)
@@ -54,6 +60,7 @@ Existing viewer/feature prompts: ai-model-analysis, ar-quick-look, cli-tool, mat
## 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)
diff --git a/.github/prompts/add-tests.md b/.github/prompts/add-tests.md
index 171cacdd4..17489f9d6 100644
--- a/.github/prompts/add-tests.md
+++ b/.github/prompts/add-tests.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Create test infrastructure with unit tests, integration tests, and CI"
+description: 'Create test infrastructure with unit tests, integration tests, and CI'
---
# Add Test Infrastructure
@@ -20,6 +20,7 @@ npm install -D vitest @testing-library/dom jsdom
```
Update `package.json`:
+
```json
"scripts": {
"test": "vitest run",
@@ -29,6 +30,7 @@ Update `package.json`:
```
Add Vitest config in `vite.config.js`:
+
```js
test: {
environment: 'jsdom',
@@ -39,11 +41,13 @@ test: {
### 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
@@ -51,17 +55,20 @@ test: {
- `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
@@ -69,12 +76,14 @@ test: {
### 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
@@ -82,6 +91,7 @@ test: {
### 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
@@ -91,20 +101,21 @@ test: {
### 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
+ 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
diff --git a/.github/prompts/ai-chat-agent.md b/.github/prompts/ai-chat-agent.md
index 0509dd569..752a912db 100644
--- a/.github/prompts/ai-chat-agent.md
+++ b/.github/prompts/ai-chat-agent.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Upgrade the chat agent from pattern matching to real AI with LLM backend"
+description: 'Upgrade the chat agent from pattern matching to real AI with LLM backend'
---
# AI-Powered Chat Agent
@@ -23,10 +23,10 @@ Response: { "reply": "string", "actions": [] }
- Use OpenAI API (or compatible: Anthropic, Groq, local Ollama)
- System prompt includes:
- - 3D Agent 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
+ - 3D Agent 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
@@ -34,16 +34,17 @@ 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 }
- ]
+ "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
@@ -56,17 +57,18 @@ Supported actions:
### 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 }
+ 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 },
};
```
@@ -79,6 +81,7 @@ const context = {
### 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
@@ -88,6 +91,7 @@ Update `src/avaturn-agent.js`:
### 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
diff --git a/.github/prompts/ai-model-analysis.md b/.github/prompts/ai-model-analysis.md
index 33d179fd9..e33c7c8b6 100644
--- a/.github/prompts/ai-model-analysis.md
+++ b/.github/prompts/ai-model-analysis.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Build AI model analysis that describes meshes, materials, and suggests optimizations"
+description: 'Build AI model analysis that describes meshes, materials, and suggests optimizations'
---
# AI Model Analysis
@@ -16,6 +16,7 @@ The README roadmap lists **"AI Model Analysis — describe meshes, materials, an
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)
@@ -23,6 +24,7 @@ After a model loads, automatically analyze:
- 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)
@@ -30,6 +32,7 @@ After a model loads, automatically analyze:
- 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)
@@ -50,27 +53,29 @@ Body: {
```
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"
- }
+ "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
@@ -79,6 +84,7 @@ Display results in a panel (side panel or overlay):
### 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
diff --git a/.github/prompts/ar-quick-look.md b/.github/prompts/ar-quick-look.md
index 4c04d6656..51bdc8e9d 100644
--- a/.github/prompts/ar-quick-look.md
+++ b/.github/prompts/ar-quick-look.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Add WebXR AR Quick Look support for viewing models in augmented reality"
+description: 'Add WebXR AR Quick Look support for viewing models in augmented reality'
---
# AR Quick Look / WebXR
@@ -17,9 +17,9 @@ 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') }
+ requiredFeatures: ['hit-test', 'local-floor'],
+ optionalFeatures: ['dom-overlay'],
+ domOverlay: { root: document.getElementById('ar-overlay') },
});
```
@@ -32,20 +32,23 @@ const session = await navigator.xr.requestSession('immersive-ar', {
### 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">
+ <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;
```
@@ -53,6 +56,7 @@ intent://arvr.google.com/scene-viewer/1.0?file=MODEL_URL#Intent;scheme=https;pac
### 4. AR UI Overlay
During AR session:
+
- Crosshair reticle for surface detection
- "Place Model" tap handler
- Scale/rotate gesture indicators
diff --git a/.github/prompts/cleanup-dead-code.md b/.github/prompts/cleanup-dead-code.md
index 658bd774a..699e00364 100644
--- a/.github/prompts/cleanup-dead-code.md
+++ b/.github/prompts/cleanup-dead-code.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Remove dead code, unused dependencies, and fix package.json metadata"
+description: 'Remove dead code, unused dependencies, and fix package.json metadata'
---
# Cleanup: Dead Code & Package Metadata
@@ -8,24 +8,29 @@ description: "Remove dead code, unused dependencies, and fix package.json metada
## 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
diff --git a/.github/prompts/cli-tool.md b/.github/prompts/cli-tool.md
index 80155ea18..fa7a69a57 100644
--- a/.github/prompts/cli-tool.md
+++ b/.github/prompts/cli-tool.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Build a headless CLI tool for model validation and inspection in CI/CD"
+description: 'Build a headless CLI tool for model validation and inspection in CI/CD'
---
# CLI Tool
@@ -18,6 +18,7 @@ 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)
@@ -31,12 +32,13 @@ npx 3d-agent validate model.glb [--format json|text|table] [--max-issues 100] [-
- 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)
+ - `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
@@ -56,6 +58,7 @@ npx 3d-agent inspect model.glb [--format json|text]
```
Output:
+
- File size
- glTF version, generator
- Extensions used / required
@@ -71,6 +74,7 @@ npx 3d-agent optimize model.glb -o optimized.glb [--draco] [--texture-resize 204
```
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
@@ -78,6 +82,7 @@ Using `@gltf-transform/cli` or programmatic API:
- `--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
@@ -89,29 +94,33 @@ Suggestions for model.glb:
### 5. Package Configuration
In `package.json`:
+
```json
{
- "bin": {
- "3d-agent": "./cli/index.js"
- }
+ "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
diff --git a/.github/prompts/complete-mcp-tools.md b/.github/prompts/complete-mcp-tools.md
index 120ff106e..9df796f53 100644
--- a/.github/prompts/complete-mcp-tools.md
+++ b/.github/prompts/complete-mcp-tools.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Complete MCP server with validate-model tool and full tool documentation"
+description: 'Complete MCP server with validate-model tool and full tool documentation'
---
# Complete MCP Integration
@@ -31,6 +31,7 @@ Allow MCP clients to submit a model URL for server-side validation:
```
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
@@ -75,6 +76,7 @@ Returns suggestions like: "Use Draco compression to reduce geometry size by ~60%
### 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
@@ -82,6 +84,7 @@ Allow MCP clients to create avatars programmatically:
## 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://`)
@@ -89,6 +92,7 @@ For `validate_model` and `inspect_model`, install `gltf-validator` in the API:
## Rate Limiting
Add per-tool rate limits:
+
- `validate_model`: 10/min (compute-heavy)
- `inspect_model`: 30/min
- `optimize_model`: 10/min
diff --git a/.github/prompts/complete-openapi-spec.md b/.github/prompts/complete-openapi-spec.md
index f77adc756..7a2c2c3b9 100644
--- a/.github/prompts/complete-openapi-spec.md
+++ b/.github/prompts/complete-openapi-spec.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Complete the OpenAPI spec with all actual API endpoints"
+description: 'Complete the OpenAPI spec with all actual API endpoints'
---
# Complete OpenAPI Specification
@@ -12,6 +12,7 @@ description: "Complete the OpenAPI spec with all actual API endpoints"
### 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
@@ -21,12 +22,14 @@ description: "Complete the OpenAPI spec with all actual API endpoints"
- `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
@@ -34,19 +37,23 @@ description: "Complete the OpenAPI spec with all actual API endpoints"
- `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`
@@ -59,12 +66,12 @@ description: "Complete the OpenAPI spec with all actual API endpoints"
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)
+ - 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
diff --git a/.github/prompts/create-agent-card.md b/.github/prompts/create-agent-card.md
index f53330d3d..3f32ffc98 100644
--- a/.github/prompts/create-agent-card.md
+++ b/.github/prompts/create-agent-card.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Create the missing A2A agent-card.json for agent discovery"
+description: 'Create the missing A2A agent-card.json for agent discovery'
---
# Create A2A Agent Card
@@ -21,69 +21,69 @@ Create `public/.well-known/agent-card.json` with the full A2A agent card spec:
```json
{
- "name": "3D Agent",
- "description": "AI-powered 3D model viewer and validation agent. Load glTF/GLB models, run validation, inspect materials, and manage avatar assets.",
- "url": "https://3dagent.vercel.app",
- "provider": {
- "organization": "3D Agent",
- "url": "https://3dagent.vercel.app"
- },
- "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"]
- }
- ]
+ "name": "3D Agent",
+ "description": "AI-powered 3D model viewer and validation agent. Load glTF/GLB models, run validation, inspect materials, and manage avatar assets.",
+ "url": "https://3dagent.vercel.app",
+ "provider": {
+ "organization": "3D Agent",
+ "url": "https://3dagent.vercel.app"
+ },
+ "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"]
+ }
+ ]
}
```
diff --git a/.github/prompts/deploy-erc8004-contracts.md b/.github/prompts/deploy-erc8004-contracts.md
index 8404bf9a8..646c6d64d 100644
--- a/.github/prompts/deploy-erc8004-contracts.md
+++ b/.github/prompts/deploy-erc8004-contracts.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Deploy ERC-8004 contracts and complete on-chain agent registration"
+description: 'Deploy ERC-8004 contracts and complete on-chain agent registration'
---
# Deploy ERC-8004 Contracts & Complete Integration
@@ -26,23 +26,25 @@ The UI (`register-ui.js`), registry interaction (`agent-registry.js`), and ABI a
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`
+
+ - 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
+
+ - 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
+ - Store validation proofs on-chain
+ - Link validation results to agent identities
+ - Support for multiple validators
### Phase 2: Deployment (Base Sepolia Testnet)
@@ -55,8 +57,8 @@ The UI (`register-ui.js`), registry interaction (`agent-registry.js`), and ABI a
1. **Register 3D Agent 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" }`
+ - 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
diff --git a/.github/prompts/file-format-expansion.md b/.github/prompts/file-format-expansion.md
index b01dfd137..700a56e3d 100644
--- a/.github/prompts/file-format-expansion.md
+++ b/.github/prompts/file-format-expansion.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Add multi-format import support for FBX, OBJ, and USDZ files"
+description: 'Add multi-format import support for FBX, OBJ, and USDZ files'
---
# File Format Expansion
@@ -80,16 +80,26 @@ 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
- }
+ 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
+ }
}
```
@@ -102,6 +112,7 @@ function getLoader(filename) {
### 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`)
diff --git a/.github/prompts/fix-security-xss.md b/.github/prompts/fix-security-xss.md
index 863c25585..c80266475 100644
--- a/.github/prompts/fix-security-xss.md
+++ b/.github/prompts/fix-security-xss.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Fix XSS vulnerability in glTF validator — unescaped title field"
+description: 'Fix XSS vulnerability in glTF validator — unescaped title field'
---
# Fix XSS: Validator Title Escaping
@@ -11,7 +11,7 @@ In `src/validator.js`, the `setResponse()` method escapes `extras.author`, `extr
```js
if (extras.title) {
- this.report.info.extras.title = extras.title; // ← NOT escaped
+ this.report.info.extras.title = extras.title; // ← NOT escaped
}
```
diff --git a/.github/prompts/fix-validator-lightbox.md b/.github/prompts/fix-validator-lightbox.md
index e86253371..d238f5fdc 100644
--- a/.github/prompts/fix-validator-lightbox.md
+++ b/.github/prompts/fix-validator-lightbox.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Fix broken template literals in validator lightbox"
+description: 'Fix broken template literals in validator lightbox'
---
# Fix Validator Lightbox Template Strings
diff --git a/.github/prompts/material-editor.md b/.github/prompts/material-editor.md
index 9b297d254..b6e777e91 100644
--- a/.github/prompts/material-editor.md
+++ b/.github/prompts/material-editor.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Build a live material editor with PBR parameter tweaking and GLB export"
+description: 'Build a live material editor with PBR parameter tweaking and GLB export'
---
# Material Editor
@@ -24,30 +24,32 @@ These libraries let you read a GLB, modify material properties programmatically,
### 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 |
+| 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`
@@ -64,6 +66,7 @@ All material property changes apply immediately to the Three.js material via `ma
### 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
@@ -74,22 +77,24 @@ 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);
+ 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);
}
```
diff --git a/.github/prompts/measurement-tools.md b/.github/prompts/measurement-tools.md
index 42ee2b2ba..c17d0f8be 100644
--- a/.github/prompts/measurement-tools.md
+++ b/.github/prompts/measurement-tools.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Add measurement tools for distances, angles, and bounding box dimensions"
+description: 'Add measurement tools for distances, angles, and bounding box dimensions'
---
# Measurement Tools
@@ -43,9 +43,9 @@ The README roadmap lists **"Measurement Tools — click two points to measure di
### 5. Surface Area & Volume
- Calculate and display:
- - Total surface area (sum of triangle areas)
- - Estimated volume (for closed meshes)
- - Per-mesh surface area
+ - Total surface area (sum of triangle areas)
+ - Estimated volume (for closed meshes)
+ - Per-mesh surface area
### 6. Measurement Display
@@ -57,6 +57,7 @@ The README roadmap lists **"Measurement Tools — click two points to measure di
### 7. GUI Integration
Add "Measure" folder to dat.gui:
+
```
▸ Measure
Mode (dropdown: Off, Distance, Angle, BBox)
diff --git a/.github/prompts/scene-graph-explorer.md b/.github/prompts/scene-graph-explorer.md
index b06bfd251..1348b7e20 100644
--- a/.github/prompts/scene-graph-explorer.md
+++ b/.github/prompts/scene-graph-explorer.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Build a visual scene graph explorer with node inspection and transform controls"
+description: 'Build a visual scene graph explorer with node inspection and transform controls'
---
# Scene Graph Explorer
@@ -25,6 +25,7 @@ Build a collapsible tree view that mirrors the Three.js scene graph:
```
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`
@@ -35,6 +36,7 @@ Each tree node shows:
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)
@@ -43,19 +45,23 @@ When a node is selected in the tree, show a properties panel:
- 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
@@ -74,6 +80,7 @@ When a node is selected in the tree, show a properties panel:
### 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
@@ -84,6 +91,7 @@ Use plain DOM (no framework) to match the existing codebase style. CSS in `style
### 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`
@@ -92,6 +100,7 @@ In `src/viewer.js`:
### 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
diff --git a/.github/prompts/screenshot-video-export.md b/.github/prompts/screenshot-video-export.md
index cf03b896a..5a8bbed9c 100644
--- a/.github/prompts/screenshot-video-export.md
+++ b/.github/prompts/screenshot-video-export.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Add screenshot/video export with PNG capture and animated WebM recording"
+description: 'Add screenshot/video export with PNG capture and animated WebM recording'
---
# Screenshot & Video Export
@@ -18,6 +18,7 @@ The README roadmap lists **"Screenshot / Video Export — capture PNGs or record
### 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)
@@ -27,6 +28,7 @@ Improve the existing screenshot:
### 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
@@ -34,6 +36,7 @@ Automated 360° turntable sequence:
### 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
@@ -44,6 +47,7 @@ Record the viewport as a video:
### 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)
@@ -70,6 +74,7 @@ Add an "Export" folder to dat.gui:
### 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()`)
diff --git a/.github/prompts/side-by-side-diff.md b/.github/prompts/side-by-side-diff.md
index ce53ba298..95ae32435 100644
--- a/.github/prompts/side-by-side-diff.md
+++ b/.github/prompts/side-by-side-diff.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Add side-by-side model diff for comparing two versions of the same model"
+description: 'Add side-by-side model diff for comparing two versions of the same model'
---
# Side-by-Side Model Diff
@@ -14,6 +14,7 @@ The README roadmap lists **"Side-by-Side Diff — compare two versions of the sa
### 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)
@@ -22,19 +23,20 @@ Split the viewer into two synchronized viewports:
### 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 |
+| 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
@@ -60,6 +62,7 @@ Animations | 0 | 0 | 0
### 6. Synchronized Controls
Both viewports share:
+
- Camera position, rotation, zoom (OrbitControls synced)
- Environment map selection
- Animation playback (if both have animations)
@@ -68,6 +71,7 @@ Both viewports share:
### 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)
diff --git a/.github/prompts/stack-01-siwe-wallet-login.md b/.github/prompts/stack-01-siwe-wallet-login.md
index 05d6b86ee..81798626e 100644
--- a/.github/prompts/stack-01-siwe-wallet-login.md
+++ b/.github/prompts/stack-01-siwe-wallet-login.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Complete SIWE wallet login end-to-end — nonce, verify, session, error states"
+description: 'Complete SIWE wallet login end-to-end — nonce, verify, session, error states'
---
# Stack Layer 1: SIWE Wallet Login End-to-End
@@ -16,26 +16,26 @@ This is priority stack layer 1 (wallet auth 100%). Nothing else on the stack can
### 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.
+ - 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 } }`.
+ - 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/`.
+ - 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
@@ -44,7 +44,7 @@ This is priority stack layer 1 (wallet auth 100%). Nothing else on the stack can
### Session
-Reuse `requireAuth()` from [api/_lib/](api/_lib/) — no new JWT code. Verify it accepts wallet-authed users (no email required).
+Reuse `requireAuth()` from [api/\_lib/](api/_lib/) — no new JWT code. Verify it accepts wallet-authed users (no email required).
## Validation
diff --git a/.github/prompts/stack-02-privy-unified-auth.md b/.github/prompts/stack-02-privy-unified-auth.md
index acd762f97..24498ff16 100644
--- a/.github/prompts/stack-02-privy-unified-auth.md
+++ b/.github/prompts/stack-02-privy-unified-auth.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Unify Privy + SIWE so one user row handles both email+wallet auth paths"
+description: 'Unify Privy + SIWE so one user row handles both email+wallet auth paths'
---
# Stack Layer 1: Unified Privy + SIWE Auth
@@ -14,6 +14,7 @@ Privy is integrated (per recent commit `e4bc161`) and SIWE is being added. Witho
### 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)
@@ -21,9 +22,10 @@ Privy is integrated (per recent commit `e4bc161`) and SIWE is being added. Witho
- `handle` (nullable)
- `created_at`, `updated_at`
-### Server resolution logic ([api/_lib/](api/_lib/))
+### 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.
diff --git a/.github/prompts/stack-03-auth-session-recovery.md b/.github/prompts/stack-03-auth-session-recovery.md
index 14aeaf2a0..5a78af462 100644
--- a/.github/prompts/stack-03-auth-session-recovery.md
+++ b/.github/prompts/stack-03-auth-session-recovery.md
@@ -1,13 +1,14 @@
---
mode: agent
-description: "Make auth sessions survive refresh, new tab, wallet disconnect, token near-expiry"
+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:
+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)
@@ -17,6 +18,7 @@ Wallet auth must *stay* authenticated across page refresh, new tabs, wallet disc
### 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.
diff --git a/.github/prompts/stack-04-auth-error-ux.md b/.github/prompts/stack-04-auth-error-ux.md
index b39fb8e7c..50bc5e812 100644
--- a/.github/prompts/stack-04-auth-error-ux.md
+++ b/.github/prompts/stack-04-auth-error-ux.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Turn every auth failure into a clear, recoverable user-facing message"
+description: 'Turn every auth failure into a clear, recoverable user-facing message'
---
# Stack Layer 1: Auth Error UX
@@ -14,6 +14,7 @@ Today auth errors bubble up as generic "Login failed" with no indication of caus
### 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
@@ -29,6 +30,7 @@ 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".
diff --git a/.github/prompts/stack-05-selfie-capture.md b/.github/prompts/stack-05-selfie-capture.md
index 0a97d8fed..2a24e4467 100644
--- a/.github/prompts/stack-05-selfie-capture.md
+++ b/.github/prompts/stack-05-selfie-capture.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Camera + upload UI that captures a selfie and hands it to the avatar pipeline"
+description: 'Camera + upload UI that captures a selfie and hands it to the avatar pipeline'
---
# Stack Layer 2: Selfie Capture UI
@@ -20,11 +20,11 @@ The magic moment of the product is "photo becomes your agent." We need the captu
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)`.
+ - 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.
+ - 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).
diff --git a/.github/prompts/stack-06-face-to-avatar-backend.md b/.github/prompts/stack-06-face-to-avatar-backend.md
index 3f37a3ba0..c38606700 100644
--- a/.github/prompts/stack-06-face-to-avatar-backend.md
+++ b/.github/prompts/stack-06-face-to-avatar-backend.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Backend pipeline that turns an uploaded selfie into a riggable GLB avatar"
+description: 'Backend pipeline that turns an uploaded selfie into a riggable GLB avatar'
---
# Stack Layer 2: Selfie → GLB Avatar Pipeline
@@ -16,11 +16,13 @@ We need a server endpoint that accepts a selfie and returns a GLB avatar (riggab
`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" }
```
@@ -29,11 +31,11 @@ Response (202 Accepted):
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 |
+| 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).
diff --git a/.github/prompts/stack-07-avatar-creation-progress.md b/.github/prompts/stack-07-avatar-creation-progress.md
index 786bee451..8ddb7da5d 100644
--- a/.github/prompts/stack-07-avatar-creation-progress.md
+++ b/.github/prompts/stack-07-avatar-creation-progress.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Progress UI for the 30-90s avatar generation — live status, cancel, preview"
+description: 'Progress UI for the 30-90s avatar generation — live status, cancel, preview'
---
# Stack Layer 2: Avatar Creation Progress UI
diff --git a/.github/prompts/stack-08-avatar-save-and-slug.md b/.github/prompts/stack-08-avatar-save-and-slug.md
index e7f0c18ac..71ed495c8 100644
--- a/.github/prompts/stack-08-avatar-save-and-slug.md
+++ b/.github/prompts/stack-08-avatar-save-and-slug.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Persist created avatars with a user-chosen slug and route /agent/:slug to the viewer"
+description: 'Persist created avatars with a user-chosen slug and route /agent/:slug to the viewer'
---
# Stack Layer 2: Avatar Persistence + Slug Routing
@@ -16,6 +16,7 @@ Once an avatar is generated we need: (1) a stable, shareable URL, (2) a slug cho
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" }
```
@@ -35,6 +36,7 @@ Server returns 409 if slug is taken, 400 if invalid, 200 with the updated row on
### 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" }
```
diff --git a/.github/prompts/stack-09-avatar-editor-shell.md b/.github/prompts/stack-09-avatar-editor-shell.md
index bc93c81e4..02d1c5c52 100644
--- a/.github/prompts/stack-09-avatar-editor-shell.md
+++ b/.github/prompts/stack-09-avatar-editor-shell.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Edit-avatar page shell — auth-gated, tabbed, lives at /edit/:slug"
+description: 'Edit-avatar page shell — auth-gated, tabbed, lives at /edit/:slug'
---
# Stack Layer 3: Avatar Editor Shell
@@ -26,10 +26,12 @@ Users need a page to edit an avatar after creation. Today there is no edit surfa
`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)
diff --git a/.github/prompts/stack-10-avatar-identity-tab.md b/.github/prompts/stack-10-avatar-identity-tab.md
index ea48dca2d..0d2c8951f 100644
--- a/.github/prompts/stack-10-avatar-identity-tab.md
+++ b/.github/prompts/stack-10-avatar-identity-tab.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Identity tab of avatar editor — edit name, bio, visibility; delete avatar"
+description: 'Identity tab of avatar editor — edit name, bio, visibility; delete avatar'
---
# Stack Layer 3: Identity Tab
@@ -21,6 +21,7 @@ Users need to edit an avatar's public identity after creation: name, bio, visibi
### Save
`PATCH /api/avatars/:id`:
+
```json
{ "name": "...", "bio": "...", "visibility": "public" }
```
@@ -32,6 +33,7 @@ Use `zod` to validate on the server. Reject unknowns. Only owner can edit.
"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.
diff --git a/.github/prompts/stack-11-avatar-skills-tab.md b/.github/prompts/stack-11-avatar-skills-tab.md
index 38cae2e03..4431b50ea 100644
--- a/.github/prompts/stack-11-avatar-skills-tab.md
+++ b/.github/prompts/stack-11-avatar-skills-tab.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Skills tab — attach/detach skills to an avatar from a catalog"
+description: 'Skills tab — attach/detach skills to an avatar from a catalog'
---
# Stack Layer 3: Skills Tab
@@ -14,10 +14,16 @@ An avatar's capabilities are defined by which skills are attached. Today skills
### 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"] }
+ {
+ "id": "greet",
+ "name": "Greet",
+ "description": "Say hello with presence",
+ "tags": ["default"]
+ },
+ { "id": "validate-model", "name": "Validate glTF", "tags": ["3d"] }
]
```
@@ -30,6 +36,7 @@ Expose via `GET /api/skills/catalog` (public, cached).
### 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.
diff --git a/.github/prompts/stack-12-avatar-memory-seed.md b/.github/prompts/stack-12-avatar-memory-seed.md
index 27745f9d1..a7429014a 100644
--- a/.github/prompts/stack-12-avatar-memory-seed.md
+++ b/.github/prompts/stack-12-avatar-memory-seed.md
@@ -7,28 +7,31 @@ description: "Memory tab — seed initial facts/feedback/references into an avat
## 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.
+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.
+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.
@@ -40,6 +43,7 @@ Each subsection:
### Validation
Server-side zod schema:
+
```js
{
type: z.enum(['user', 'feedback', 'project', 'reference']),
diff --git a/.github/prompts/stack-13-avatar-animation-tab.md b/.github/prompts/stack-13-avatar-animation-tab.md
index 3bad8731e..0973de3ba 100644
--- a/.github/prompts/stack-13-avatar-animation-tab.md
+++ b/.github/prompts/stack-13-avatar-animation-tab.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Animation tab — pick idle + gesture animations from Mixamo bundle"
+description: 'Animation tab — pick idle + gesture animations from Mixamo bundle'
---
# Stack Layer 3: Animation Tab
@@ -16,6 +16,7 @@ Avatars ship with a skeleton but no default animations. We need a UI to pick: (1
[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" },
@@ -42,8 +43,14 @@ Picker shows animation name + a looping preview. If GIF previews don't exist, re
### Persistence
`avatars.animations` jsonb column:
+
```json
-{ "idle": "idle-breathing", "greet": "waving", "think": "thinking-scratch", "celebrate": "fist-pump" }
+{
+ "idle": "idle-breathing",
+ "greet": "waving",
+ "think": "thinking-scratch",
+ "celebrate": "fist-pump"
+}
```
`PATCH /api/avatars/:id/animations` endpoint.
diff --git a/.github/prompts/stack-14-avatar-mesh-replace.md b/.github/prompts/stack-14-avatar-mesh-replace.md
index b24a019fb..c9ba9b04c 100644
--- a/.github/prompts/stack-14-avatar-mesh-replace.md
+++ b/.github/prompts/stack-14-avatar-mesh-replace.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Mesh tab — replace underlying GLB (rerun selfie, upload GLB, or pick preset)"
+description: 'Mesh tab — replace underlying GLB (rerun selfie, upload GLB, or pick preset)'
---
# Stack Layer 3: Mesh Replacement Tab
@@ -20,6 +20,7 @@ Users may want to change the underlying 3D mesh of an existing avatar while keep
### 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.
diff --git a/.github/prompts/stack-15-agent-public-page.md b/.github/prompts/stack-15-agent-public-page.md
index 66deaded7..869f638e9 100644
--- a/.github/prompts/stack-15-agent-public-page.md
+++ b/.github/prompts/stack-15-agent-public-page.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Polish the public /agent/:slug page — hero, identity card, presence, CTAs"
+description: 'Polish the public /agent/:slug page — hero, identity card, presence, CTAs'
---
# Stack Layer 4: Public Agent Page
diff --git a/.github/prompts/stack-16-embed-code-generator.md b/.github/prompts/stack-16-embed-code-generator.md
index 1eafa78c6..07f8271e3 100644
--- a/.github/prompts/stack-16-embed-code-generator.md
+++ b/.github/prompts/stack-16-embed-code-generator.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Embed code generator — copy-paste snippets for iframe, web component, React"
+description: 'Embed code generator — copy-paste snippets for iframe, web component, React'
---
# Stack Layer 4: Embed Code Generator
@@ -29,19 +29,26 @@ For the agent to appear in third-party sites, the owner needs one-click copy-pas
Live-update three snippets in tabs as settings change:
**iframe**:
+
```html
-<iframe src="https://3dagent.vercel.app/agent/satoshi?kiosk=1&theme=dark"
- width="600" height="600" style="border:0"
- allow="camera; microphone; xr-spatial-tracking"></iframe>
+<iframe
+ src="https://3dagent.vercel.app/agent/satoshi?kiosk=1&theme=dark"
+ width="600"
+ height="600"
+ style="border:0"
+ allow="camera; microphone; xr-spatial-tracking"
+></iframe>
```
**Web component** (using [src/element.js](src/element.js)):
+
```html
<script src="https://3dagent.vercel.app/dist-lib/agent-3d.js"></script>
<agent-3d slug="satoshi" theme="dark" mode="kiosk"></agent-3d>
```
**React** (thin wrapper note — the lib is framework-agnostic):
+
```jsx
<iframe src="https://3dagent.vercel.app/agent/satoshi?kiosk=1" width={600} height={600} />
```
diff --git a/.github/prompts/stack-17-kiosk-mode-polish.md b/.github/prompts/stack-17-kiosk-mode-polish.md
index e940f03a5..784425427 100644
--- a/.github/prompts/stack-17-kiosk-mode-polish.md
+++ b/.github/prompts/stack-17-kiosk-mode-polish.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Kiosk mode polish — minimal chrome, responsive to parent sizing, fast first paint"
+description: 'Kiosk mode polish — minimal chrome, responsive to parent sizing, fast first paint'
---
# Stack Layer 4: Kiosk Mode Polish
@@ -40,11 +40,13 @@ description: "Kiosk mode polish — minimal chrome, responsive to parent sizing,
### 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.
diff --git a/.github/prompts/stack-18-embed-telemetry.md b/.github/prompts/stack-18-embed-telemetry.md
index bd70cbed7..946d047b1 100644
--- a/.github/prompts/stack-18-embed-telemetry.md
+++ b/.github/prompts/stack-18-embed-telemetry.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Track embed views, skill invocations, and session duration — without tracking users"
+description: 'Track embed views, skill invocations, and session duration — without tracking users'
---
# Stack Layer 4: Embed Telemetry
@@ -14,6 +14,7 @@ We need to know which agents are being embedded, where, how often they're intera
### 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 }`
@@ -27,6 +28,7 @@ POST to `/api/telemetry` (batched, fire-and-forget from client):
### Storage
`agent_telemetry` table in Neon:
+
```sql
avatar_id, event, parent_origin, kiosk bool, theme, ua_bucket, occurred_at
```
@@ -36,6 +38,7 @@ 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.
diff --git a/.github/prompts/stack-19-artifacts-single-file.md b/.github/prompts/stack-19-artifacts-single-file.md
index 9a4c84dbb..d31738a52 100644
--- a/.github/prompts/stack-19-artifacts-single-file.md
+++ b/.github/prompts/stack-19-artifacts-single-file.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Self-contained HTML build for Claude.ai Artifacts — one file, no external fetches"
+description: 'Self-contained HTML build for Claude.ai Artifacts — one file, no external fetches'
---
# Stack Layer 5: Claude Artifacts Single-File Embed
@@ -14,6 +14,7 @@ Claude.ai Artifacts run user-supplied HTML in a sandboxed iframe with restricted
### 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).
@@ -25,13 +26,17 @@ Vite config: new entry `src/artifact-entry.js`, `viteStaticCopy` or `rollup-plug
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>
+<script type="application/json" id="agent-spec">
+ {...full spec...}
+</script>
```
On load, read spec, boot viewer + agent runtime, render.
@@ -39,6 +44,7 @@ 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.
@@ -48,6 +54,7 @@ For v1: support inline base64 AND allow a passthrough URL. Document which works
### No auth / no writes
Artifact mode is read-only:
+
- No login UI.
- No memory writes.
- Skills that need the network are disabled (grayed out).
diff --git a/.github/prompts/stack-20-lobehub-plugin.md b/.github/prompts/stack-20-lobehub-plugin.md
index 5f2feae70..5a14513df 100644
--- a/.github/prompts/stack-20-lobehub-plugin.md
+++ b/.github/prompts/stack-20-lobehub-plugin.md
@@ -14,49 +14,63 @@ User maintains a LobeHub fork. Per priority stack, an agent from 3dagent.vercel.
### Plugin manifest
Host at `https://3dagent.vercel.app/.well-known/lobehub-plugin.json`:
+
```json
{
- "identifier": "3d-agent",
- "version": "1.0.0",
- "meta": {
- "title": "3D Agent",
- "description": "Embodied 3D agents — identity, memory, skills, emotional presence",
- "avatar": "https://3dagent.vercel.app/icon.png",
- "tags": ["3d", "agent", "avatar"]
- },
- "api": [
- {
- "name": "renderAgent",
- "description": "Render an embodied agent by slug or agent card URL",
- "url": "https://3dagent.vercel.app/api/lobehub/render-agent",
- "parameters": { "type": "object", "properties": { "slug": { "type": "string" } }, "required": ["slug"] }
- },
- {
- "name": "summonAgent",
- "description": "Ask the 3D agent to perform a skill and return the result + rendering",
- "url": "https://3dagent.vercel.app/api/lobehub/summon-agent",
- "parameters": { "type": "object", "properties": { "slug": { "type": "string" }, "skill": { "type": "string" }, "input": { "type": "string" } }, "required": ["slug", "skill"] }
- }
- ],
- "ui": [
- {
- "name": "agent-embed",
- "url": "https://3dagent.vercel.app/lobehub/embed.html"
- }
- ]
+ "identifier": "3d-agent",
+ "version": "1.0.0",
+ "meta": {
+ "title": "3D Agent",
+ "description": "Embodied 3D agents — identity, memory, skills, emotional presence",
+ "avatar": "https://3dagent.vercel.app/icon.png",
+ "tags": ["3d", "agent", "avatar"]
+ },
+ "api": [
+ {
+ "name": "renderAgent",
+ "description": "Render an embodied agent by slug or agent card URL",
+ "url": "https://3dagent.vercel.app/api/lobehub/render-agent",
+ "parameters": {
+ "type": "object",
+ "properties": { "slug": { "type": "string" } },
+ "required": ["slug"]
+ }
+ },
+ {
+ "name": "summonAgent",
+ "description": "Ask the 3D agent to perform a skill and return the result + rendering",
+ "url": "https://3dagent.vercel.app/api/lobehub/summon-agent",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "slug": { "type": "string" },
+ "skill": { "type": "string" },
+ "input": { "type": "string" }
+ },
+ "required": ["slug", "skill"]
+ }
+ }
+ ],
+ "ui": [
+ {
+ "name": "agent-embed",
+ "url": "https://3dagent.vercel.app/lobehub/embed.html"
+ }
+ ]
}
```
### Plugin endpoints
`POST /api/lobehub/render-agent` — returns a payload the plugin chrome renders:
+
```json
{
- "type": "embed",
- "url": "https://3dagent.vercel.app/agent/satoshi?kiosk=1&theme=auto",
- "width": 480,
- "height": 480,
- "fallbackText": "3D Agent: Satoshi — open in browser to interact"
+ "type": "embed",
+ "url": "https://3dagent.vercel.app/agent/satoshi?kiosk=1&theme=auto",
+ "width": 480,
+ "height": 480,
+ "fallbackText": "3D Agent: Satoshi — open in browser to interact"
}
```
@@ -65,6 +79,7 @@ Host at `https://3dagent.vercel.app/.well-known/lobehub-plugin.json`:
### 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).
@@ -72,12 +87,13 @@ Host at `https://3dagent.vercel.app/.well-known/lobehub-plugin.json`:
### Install flow
Document in repo: how the user installs the plugin in their fork. Either:
+
- Official LobeHub plugin marketplace submission (later), OR
- Direct manifest URL install (immediate).
### Auth
-Plugin does NOT require auth to render public avatars. If the LobeHub user wants their *own* agents listed, they pass a 3D Agent API key (see [api/keys/](api/keys/)) in a settings field.
+Plugin does NOT require auth to render public avatars. If the LobeHub user wants their _own_ agents listed, they pass a 3D Agent API key (see [api/keys/](api/keys/)) in a settings field.
## Validation
diff --git a/.github/prompts/stack-21-host-chat-bridge.md b/.github/prompts/stack-21-host-chat-bridge.md
index 323b3b3b9..7003d76ab 100644
--- a/.github/prompts/stack-21-host-chat-bridge.md
+++ b/.github/prompts/stack-21-host-chat-bridge.md
@@ -1,13 +1,13 @@
---
mode: agent
-description: "postMessage bridge between host chat context and embedded agent (emotion + skills)"
+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.
+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
@@ -16,6 +16,7 @@ When an agent is embedded in a host chat (Claude Artifacts, LobeHub, any site),
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 }
@@ -24,6 +25,7 @@ Define in [specs/EMBED_SPEC.md](specs/EMBED_SPEC.md). Messages flow both ways vi
```
**Agent → Host:**
+
```js
{ type: '3dagent.ready', avatarId: string }
{ type: '3dagent.skillResult', requestId: string, result: any, error?: string }
diff --git a/.github/prompts/stack-22-mcp-embodied-responses.md b/.github/prompts/stack-22-mcp-embodied-responses.md
index 0e1adf527..33e522e41 100644
--- a/.github/prompts/stack-22-mcp-embodied-responses.md
+++ b/.github/prompts/stack-22-mcp-embodied-responses.md
@@ -1,27 +1,33 @@
---
mode: agent
-description: "MCP tools that return embodied agent renderings, not just text"
+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.
+[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://3dagent.vercel.app/agent/satoshi?kiosk=1&skill=greet", "mimeType": "text/html" } }
- ]
- }
- ```
+ ```json
+ {
+ "content": [
+ { "type": "text", "text": "Agent Satoshi responded: 'Hello'" },
+ {
+ "type": "resource",
+ "resource": {
+ "uri": "https://3dagent.vercel.app/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.
@@ -34,6 +40,7 @@ description: "MCP tools that return embodied agent renderings, not just text"
### 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.
diff --git a/.github/prompts/stack-23-manifest-to-ipfs.md b/.github/prompts/stack-23-manifest-to-ipfs.md
index 77e4f579a..25be49053 100644
--- a/.github/prompts/stack-23-manifest-to-ipfs.md
+++ b/.github/prompts/stack-23-manifest-to-ipfs.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Publish agent manifests to IPFS so agents are portable, censorship-resistant"
+description: 'Publish agent manifests to IPFS so agents are portable, censorship-resistant'
---
# Stack Layer 6: Agent Manifest → IPFS
@@ -14,6 +14,7 @@ Today an agent is a DB row in Neon. For the novel unlock (agent hydrates into an
### Manifest schema
Conform to [specs/AGENT_MANIFEST.md](specs/AGENT_MANIFEST.md). Minimum fields:
+
```json
{
"$schema": "https://3dagent.vercel.app/specs/agent-manifest-v1.json",
@@ -35,6 +36,7 @@ Conform to [specs/AGENT_MANIFEST.md](specs/AGENT_MANIFEST.md). Minimum fields:
### 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.
@@ -42,6 +44,7 @@ Use Pinata, Web3.Storage, or Filecoin via [src/ipfs.js](src/ipfs.js) (already ex
### Publish endpoint
`POST /api/avatars/:id/publish`:
+
- Builds manifest from DB row.
- Uploads GLB to IPFS if not already.
- Pins manifest.
@@ -54,7 +57,7 @@ For rendering from IPFS, support multiple gateways (Cloudflare, ipfs.io, dweb.li
### 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).
+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
diff --git a/.github/prompts/stack-24-onchain-identity-register.md b/.github/prompts/stack-24-onchain-identity-register.md
index 227bf5ea5..1a1669a10 100644
--- a/.github/prompts/stack-24-onchain-identity-register.md
+++ b/.github/prompts/stack-24-onchain-identity-register.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Register agent identity on ERC-8004 contract with IPFS manifest CID"
+description: 'Register agent identity on ERC-8004 contract with IPFS manifest CID'
---
# Stack Layer 6: ERC-8004 On-Chain Registration
@@ -14,6 +14,7 @@ For agents to be portable into ANY host app directly from chain, each agent need
### 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)`
@@ -41,6 +42,7 @@ Support meta-transactions if the deployed contract has them. Otherwise sponsor g
### Client code
New module `src/onchain/register.js`:
+
- `registerAgent(signer, cid) => { agentId, txHash }`
- `updateManifest(signer, agentId, cid) => { txHash }`
- `getAgent(agentId, provider) => { owner, manifestURI, updatedAt }`
diff --git a/.github/prompts/stack-25-hydrate-from-chain.md b/.github/prompts/stack-25-hydrate-from-chain.md
index 3d9d8606d..03f8d50bc 100644
--- a/.github/prompts/stack-25-hydrate-from-chain.md
+++ b/.github/prompts/stack-25-hydrate-from-chain.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Hydrate an embodied agent into any host directly from its on-chain record"
+description: 'Hydrate an embodied agent into any host directly from its on-chain record'
---
# Stack Layer 6: Hydrate Agent From Chain
@@ -14,12 +14,14 @@ The novel unlock: a host app (LobeHub, Claude, any site) can render an embodied
### 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://3dagent.vercel.app/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 });
@@ -28,6 +30,7 @@ renderAgent(document.getElementById('host'), { chain: 'base-sepolia', agentId: 4
### 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://...`).
diff --git a/.github/prompts/stack-26-signed-action-log.md b/.github/prompts/stack-26-signed-action-log.md
index 859b375ed..5c4693767 100644
--- a/.github/prompts/stack-26-signed-action-log.md
+++ b/.github/prompts/stack-26-signed-action-log.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Wallet-signed agent actions with on-chain anchoring for reputation"
+description: 'Wallet-signed agent actions with on-chain anchoring for reputation'
---
# Stack Layer 6: Signed Action Log
@@ -14,6 +14,7 @@ Agents emit actions continuously (skill runs, memory writes, interactions). For
### 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.
@@ -25,10 +26,12 @@ Every N actions or daily, compute a Merkle root of new action hashes → write t
### 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.
diff --git a/.github/prompts/stack-27-agents-gallery.md b/.github/prompts/stack-27-agents-gallery.md
index d13d73b99..8c2d1f922 100644
--- a/.github/prompts/stack-27-agents-gallery.md
+++ b/.github/prompts/stack-27-agents-gallery.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Public /agents gallery — discover, search, featured agents"
+description: 'Public /agents gallery — discover, search, featured agents'
---
# Stack Layer 4 (support): Agents Gallery
@@ -18,6 +18,7 @@ Without a discovery page, created agents are islands. Need a public `/agents` ga
### 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.
diff --git a/.github/prompts/stack-28-first-run-tour.md b/.github/prompts/stack-28-first-run-tour.md
index 3dcdd27d1..18f1e42cf 100644
--- a/.github/prompts/stack-28-first-run-tour.md
+++ b/.github/prompts/stack-28-first-run-tour.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "First-run onboarding tour — connect wallet → take selfie → meet your agent"
+description: 'First-run onboarding tour — connect wallet → take selfie → meet your agent'
---
# Stack Layer 2 (support): First-Run Onboarding
@@ -20,15 +20,15 @@ On `/` (home), if `!session`, show a landing with a big "Create your agent" CTA
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.
+ - 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).
+ - 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.
+ - 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
diff --git a/.github/prompts/stack-29-biometric-consent.md b/.github/prompts/stack-29-biometric-consent.md
index 2fb760fb9..fb7778236 100644
--- a/.github/prompts/stack-29-biometric-consent.md
+++ b/.github/prompts/stack-29-biometric-consent.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Biometric (face photo) consent flow — required before selfie capture"
+description: 'Biometric (face photo) consent flow — required before selfie capture'
---
# Stack Layer 2 (legal): Biometric Consent
@@ -14,6 +14,7 @@ Selfie-to-avatar involves processing biometric data. Depending on jurisdiction (
### 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).
@@ -35,6 +36,7 @@ No "Pre-checked" checkbox. No dark patterns.
### 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.
@@ -42,6 +44,7 @@ No "Pre-checked" checkbox. No dark patterns.
### 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).
diff --git a/.github/prompts/texture-inspector.md b/.github/prompts/texture-inspector.md
index 64b1bf152..fb98f4781 100644
--- a/.github/prompts/texture-inspector.md
+++ b/.github/prompts/texture-inspector.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Build texture inspector with channel separation and full-size preview"
+description: 'Build texture inspector with channel separation and full-size preview'
---
# Texture Inspector
@@ -15,29 +15,31 @@ The README roadmap lists **"Texture Inspector — view individual texture channe
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 |
+| 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) | — |
+| 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
+ - **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)
diff --git a/.github/prompts/update-docs.md b/.github/prompts/update-docs.md
index ed639bbf9..8e2e50ecd 100644
--- a/.github/prompts/update-docs.md
+++ b/.github/prompts/update-docs.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Update all documentation to cover new modules and current architecture"
+description: 'Update all documentation to cover new modules and current architecture'
---
# Update Documentation
@@ -52,6 +52,7 @@ api/
### 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
@@ -61,6 +62,7 @@ Add sections for:
### 3. Update `docs/API.md`
Add documentation for:
+
- `AvatarCreator` class (constructor, open, close)
- `NichAgent` class (chat agent)
- `IPFS` module (resolveIpfsUrl, resolveArweaveUrl)
@@ -73,6 +75,7 @@ Add documentation for:
### 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`)
diff --git a/.github/skills/3d-features/SKILL.md b/.github/skills/3d-features/SKILL.md
index b3f5953ff..3b8c79762 100644
--- a/.github/skills/3d-features/SKILL.md
+++ b/.github/skills/3d-features/SKILL.md
@@ -1,7 +1,7 @@
---
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"
+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
@@ -23,6 +23,7 @@ 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
@@ -30,6 +31,7 @@ All GUI-controllable state lives in `this.state` (defined in constructor). To ad
### 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
@@ -37,17 +39,18 @@ dat.gui controls are organized into folders created in `addGUI()`:
### 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 |
+| 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
diff --git a/.github/skills/3d-viewer/SKILL.md b/.github/skills/3d-viewer/SKILL.md
index b7476abed..9882dc89a 100644
--- a/.github/skills/3d-viewer/SKILL.md
+++ b/.github/skills/3d-viewer/SKILL.md
@@ -1,7 +1,7 @@
---
name: 3d-viewer
-description: "Full project workflow for the 3D Agent 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"
+description: 'Full project workflow for the 3D Agent 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'
---
# 3D Agent — Project Workflow
@@ -19,16 +19,16 @@ The viewer never imports the agent half. The agent layer wraps the viewer throug
## 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) |
+| 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/` | — |
+| 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).
diff --git a/.github/skills/build-deploy/SKILL.md b/.github/skills/build-deploy/SKILL.md
index 3087fd71e..dab21528f 100644
--- a/.github/skills/build-deploy/SKILL.md
+++ b/.github/skills/build-deploy/SKILL.md
@@ -1,7 +1,7 @@
---
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"
+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
@@ -17,13 +17,13 @@ argument-hint: "Describe the build or deploy task"
## 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 |
+| 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
@@ -31,8 +31,8 @@ argument-hint: "Describe the build or deploy task"
**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)
+ - `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
@@ -43,6 +43,7 @@ argument-hint: "Describe the build or deploy task"
**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/`
@@ -55,6 +56,7 @@ Key routes:
**Config**: `cors.json`
Allowed origins:
+
- `https://3dagent.vercel.app` and subdomains
- `http://localhost:*` / `https://localhost:*`
- Specific partner domains
@@ -72,16 +74,19 @@ public/
## 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 [3dagent.vercel.app](https://3dagent.vercel.app/)
### 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`
diff --git a/.github/skills/model-validation/SKILL.md b/.github/skills/model-validation/SKILL.md
index 4e7c9bc2a..d178b2e03 100644
--- a/.github/skills/model-validation/SKILL.md
+++ b/.github/skills/model-validation/SKILL.md
@@ -1,7 +1,7 @@
---
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"
+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
@@ -35,24 +35,24 @@ src/components/validator-table.jsx → Individual issue severity table renderin
## 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` |
+| 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 |
+| 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)
diff --git a/.prettierignore b/.prettierignore
new file mode 100644
index 000000000..aa4e98a30
--- /dev/null
+++ b/.prettierignore
@@ -0,0 +1,16 @@
+# Dependencies and generated files
+node_modules/
+dist/
+dist-lib/
+dist-artifact/
+
+# Vendored / external library code
+contracts/lib/
+character-studio/
+
+# Build artifacts
+*.min.js
+public/embed-sdk.js
+public/embed.js
+public/wallet-login.js
+public/artifact.js
diff --git a/CLAUDE.md b/CLAUDE.md
index b40112650..fdc2c9fc9 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -27,19 +27,19 @@ Live at <https://3dagent.vercel.app>. Backend is Vercel serverless (`api/`) + Ne
## Directory map — where things live
-| Path | What it is | Scoped doc |
-|---|---|---|
-| [src/](src/) | Browser app — viewer + agent runtime + web component | [src/CLAUDE.md](src/CLAUDE.md) |
-| [api/](api/) | Vercel serverless endpoints (auth, avatars, OAuth, MCP, agents) | [api/CLAUDE.md](api/CLAUDE.md) |
-| [contracts/](contracts/) | Foundry project — ERC-8004 registries (Solidity) | [contracts/CLAUDE.md](contracts/CLAUDE.md) |
-| [specs/](specs/) | Format specs: `AGENT_MANIFEST.md`, `SKILL_SPEC.md`, `EMBED_SPEC.md`, `MEMORY_SPEC.md` | — |
-| [docs/](docs/) | User-facing docs: `ARCHITECTURE.md`, `API.md`, `DEPLOYMENT.md`, `DEVELOPMENT.md`, `WIDGETS.md`, `MCP.md` | — |
-| [prompts/](prompts/) | Build prompts organized by priority band — see [prompts/INDEX.md](prompts/INDEX.md) | — |
-| [public/](public/) | Static assets, separate HTML pages (`login.html`, `dashboard/`, `studio/`, `widgets-gallery/`) | — |
-| [sdk/](sdk/) | `@3dagent/sdk` — public TS client (separate npm package) | — |
-| [scripts/](scripts/) | One-off node scripts (schema apply, icon gen, animation fetchers) | — |
-| [.github/skills/](.github/skills/) | GitHub Copilot `SKILL.md` bundles (viewer, features, validation, deploy) | — |
-| [.github/prompts/](.github/prompts/) | Copilot prompt library for one-shot features | — |
+| Path | What it is | Scoped doc |
+| ------------------------------------ | -------------------------------------------------------------------------------------------------------- | ------------------------------------------ |
+| [src/](src/) | Browser app — viewer + agent runtime + web component | [src/CLAUDE.md](src/CLAUDE.md) |
+| [api/](api/) | Vercel serverless endpoints (auth, avatars, OAuth, MCP, agents) | [api/CLAUDE.md](api/CLAUDE.md) |
+| [contracts/](contracts/) | Foundry project — ERC-8004 registries (Solidity) | [contracts/CLAUDE.md](contracts/CLAUDE.md) |
+| [specs/](specs/) | Format specs: `AGENT_MANIFEST.md`, `SKILL_SPEC.md`, `EMBED_SPEC.md`, `MEMORY_SPEC.md` | — |
+| [docs/](docs/) | User-facing docs: `ARCHITECTURE.md`, `API.md`, `DEPLOYMENT.md`, `DEVELOPMENT.md`, `WIDGETS.md`, `MCP.md` | — |
+| [prompts/](prompts/) | Build prompts organized by priority band — see [prompts/INDEX.md](prompts/INDEX.md) | — |
+| [public/](public/) | Static assets, separate HTML pages (`login.html`, `dashboard/`, `studio/`, `widgets-gallery/`) | — |
+| [sdk/](sdk/) | `@3dagent/sdk` — public TS client (separate npm package) | — |
+| [scripts/](scripts/) | One-off node scripts (schema apply, icon gen, animation fetchers) | — |
+| [.github/skills/](.github/skills/) | GitHub Copilot `SKILL.md` bundles (viewer, features, validation, deploy) | — |
+| [.github/prompts/](.github/prompts/) | Copilot prompt library for one-shot features | — |
Top-level HTML entry points: `index.html` (app), `features.html`, `embed.html`, `agent-home.html`, `agent-embed.html`. Additional routes served from `public/` — wiring is in [vite.config.js](vite.config.js) `vercel-rewrites` plugin, mirrored in [vercel.json](vercel.json).
@@ -86,19 +86,19 @@ No test suite is configured (`npm test` exits 0). Verification = `node --check`
## Conventions
-| Topic | Rule |
-|---|---|
-| Modules | **ESM only.** No CommonJS in `src/` or `api/`. |
-| Formatting | Prettier: **tabs**, 4-wide, single quotes, 100-col print width, `bracketSpacing`. Run `npx prettier --write` before committing. |
-| Typing | **No TypeScript** in the main app. JSDoc for public APIs. (SDK in `sdk/` may use TS — check locally.) |
-| Templating | **vhtml JSX** — string-based, no virtual DOM. Files end in `.jsx`. `jsxFactory: 'vhtml'`. |
-| Naming | CamelCase classes, camelCase methods, UPPER_CASE constants, `_underscore` for private. |
-| State | Classes over factories where there's state. `EventTarget` for buses. |
-| SQL | Always tagged-template via `sql\`...\`` from [api/_lib/db.js](api/_lib/db.js). Never concat. |
-| HTTP responses | Use `json()` / `error()` / `wrap()` from [api/_lib/http.js](api/_lib/http.js). Never `res.end(JSON.stringify(...))`. |
-| Auth | Use `getSessionUser` / `authenticateBearer` from [api/_lib/auth.js](api/_lib/auth.js). Never hand-roll JWT. |
-| Tool result shape | `{ ok: true, ... }` or `{ ok: false, error: 'msg' }`. |
-| Errors | `error(res, status, code, message)` — OAuth-style string codes. See `api/CLAUDE.md`. |
+| Topic | Rule |
+| ----------------- | ------------------------------------------------------------------------------------------------------------------------------- |
+| Modules | **ESM only.** No CommonJS in `src/` or `api/`. |
+| Formatting | Prettier: **tabs**, 4-wide, single quotes, 100-col print width, `bracketSpacing`. Run `npx prettier --write` before committing. |
+| Typing | **No TypeScript** in the main app. JSDoc for public APIs. (SDK in `sdk/` may use TS — check locally.) |
+| Templating | **vhtml JSX** — string-based, no virtual DOM. Files end in `.jsx`. `jsxFactory: 'vhtml'`. |
+| Naming | CamelCase classes, camelCase methods, UPPER_CASE constants, `_underscore` for private. |
+| State | Classes over factories where there's state. `EventTarget` for buses. |
+| SQL | Always tagged-template via `sql\`...\`` from [api/\_lib/db.js](api/_lib/db.js). Never concat. |
+| HTTP responses | Use `json()` / `error()` / `wrap()` from [api/\_lib/http.js](api/_lib/http.js). Never `res.end(JSON.stringify(...))`. |
+| Auth | Use `getSessionUser` / `authenticateBearer` from [api/\_lib/auth.js](api/_lib/auth.js). Never hand-roll JWT. |
+| Tool result shape | `{ ok: true, ... }` or `{ ok: false, error: 'msg' }`. |
+| Errors | `error(res, status, code, message)` — OAuth-style string codes. See `api/CLAUDE.md`. |
---
@@ -143,7 +143,7 @@ No test suite is configured (`npm test` exits 0). Verification = `node --check`
- Adding TypeScript to the main app.
- Importing agent modules from the viewer half.
- Writing a new routing layer instead of extending the URL-hash params in [src/app.js](src/app.js).
-- Long multi-paragraph comments / docstrings explaining *what* code does. Keep it tight.
+- Long multi-paragraph comments / docstrings explaining _what_ code does. Keep it tight.
---
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 4ddd493b1..b8bfee0f9 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -23,15 +23,16 @@ Open [http://localhost:3000](http://localhost:3000) and verify the default model
1. Check [existing issues](https://github.com/nirholas/3d-agent/issues) to avoid duplicates
2. Open a [new issue](https://github.com/nirholas/3d-agent/issues/new) with:
- - Browser and OS
- - Steps to reproduce
- - Expected vs. actual behavior
- - Console errors (if any)
- - The model file (if possible) or a link to a public glTF sample that triggers the issue
+ - Browser and OS
+ - Steps to reproduce
+ - Expected vs. actual behavior
+ - Console errors (if any)
+ - The model file (if possible) or a link to a public glTF sample that triggers the issue
### Suggest a Feature
Open an issue with the **Feature Request** label. Describe:
+
- The use case (what problem does it solve?)
- Proposed behavior
- Any UI mockups or examples from other tools
@@ -40,19 +41,19 @@ Open an issue with the **Feature Request** label. Describe:
1. Fork the repository
2. Create a feature branch from `main`:
- ```bash
- git checkout -b feat/my-feature
- ```
+ ```bash
+ git checkout -b feat/my-feature
+ ```
3. Make your changes
4. Format your code:
- ```bash
- npx prettier --write .
- ```
+ ```bash
+ npx prettier --write .
+ ```
5. Test locally with `npm run dev`
6. Commit with a clear message:
- ```bash
- git commit -m "feat: add opacity slider to display controls"
- ```
+ ```bash
+ git commit -m "feat: add opacity slider to display controls"
+ ```
7. Push and open a PR against `main`
---
@@ -61,15 +62,15 @@ Open an issue with the **Feature Request** label. Describe:
Use clear, descriptive commit messages. Conventional format is preferred:
-| Prefix | Use |
-|--------|-----|
-| `feat:` | New feature |
-| `fix:` | Bug fix |
-| `docs:` | Documentation only |
-| `style:` | Formatting, no logic change |
-| `refactor:` | Code restructuring |
-| `perf:` | Performance improvement |
-| `chore:` | Build, tooling, dependency updates |
+| Prefix | Use |
+| ----------- | ---------------------------------- |
+| `feat:` | New feature |
+| `fix:` | Bug fix |
+| `docs:` | Documentation only |
+| `style:` | Formatting, no logic change |
+| `refactor:` | Code restructuring |
+| `perf:` | Performance improvement |
+| `chore:` | Build, tooling, dependency updates |
---
@@ -119,13 +120,13 @@ Before submitting a PR, verify:
Use the [Khronos glTF Sample Assets](https://github.com/KhronosGroup/glTF-Sample-Assets):
-| Model | Tests |
-|-------|-------|
+| Model | Tests |
+| -------------- | ---------------------------------- |
| Damaged Helmet | PBR materials, environment mapping |
-| Fox | Skinned mesh, animation |
-| Flight Helmet | Multi-texture, display controls |
-| Box | Minimal model, basic rendering |
-| Animated Cube | Animation playback |
+| Fox | Skinned mesh, animation |
+| Flight Helmet | Multi-texture, display controls |
+| Box | Minimal model, basic rendering |
+| Animated Cube | Animation playback |
---
diff --git a/README.md b/README.md
index fe17535ad..47966c992 100644
--- a/README.md
+++ b/README.md
@@ -1,8 +1,8 @@
---
title: 3D Agent
-description: 3D Agent is an open-source, browser-native 3D model viewer built on three.js. It renders glTF 2.0 and GLB files directly in WebGL. No plugins, no server uploads, no installs. Create your own models and agents or just open the site, drop a file, and inspect your model instantly.
+description: 3D Agent is an open-source, browser-native 3D model viewer built on three.js. It renders glTF 2.0 and GLB files directly in WebGL. No plugins, no server uploads, no installs. Create your own models and agents or just open the site, drop a file, and inspect your model instantly.
---
-
+
<video width="100%" height="auto" autoplay loop muted playsinline>
<source src="https://github.com/nirholas/3D-Agent/raw/refs/heads/main/public/skills.mp4" type="video/mp4">
Your browser does not support the video tag.
@@ -19,7 +19,7 @@ description: 3D Agent is an open-source, browser-native 3D model viewer built on
---
-## 🧠 What is 3D Agent?
+## 🧠 What is 3D Agent?
**3D Agent** is an open-source, browser-native 3D model viewer built on [three.js](https://threejs.org/) (r176). It renders **glTF 2.0** and **GLB** files directly in WebGL — no plugins, no server uploads, no installs. Just open [3dagent.vercel.app](https://3dagent.vercel.app), drop a file, and inspect your model instantly.
@@ -36,7 +36,12 @@ It's built for **3D artists** previewing exports, **game developers** debugging
Save any avatar as a **widget** — a configured, shareable view that any site can drop in with one line of HTML. Five types: **Turntable** (auto-rotate hero banner), **Animation Gallery** (clip browser), **Talking Agent** (embodied chat), **ERC-8004 Passport** (on-chain identity card), **Hotspot Tour** (annotated 3D scene).
```html
-<iframe src="https://3dagent.vercel.app/#widget=wdgt_abc123" width="600" height="600" style="border:0"></iframe>
+<iframe
+ src="https://3dagent.vercel.app/#widget=wdgt_abc123"
+ width="600"
+ height="600"
+ style="border:0"
+></iframe>
```
- **[Open the Studio →](https://3dagent.vercel.app/studio)** — pick avatar, pick type, generate embed.
@@ -63,19 +68,19 @@ Widget URLs (`/w/<id>`) get rich Open Graph cards in Slack/Discord/X and auto-em
### Full Feature Breakdown
-| Category | What You Get |
-|:---------|:-------------|
-| **File Support** | `.glTF` and `.GLB` (glTF 2.0), with multi-file drag-and-drop (textures, bins) |
-| **Compression** | Draco mesh compression, KTX2 texture compression, Meshopt decoder |
-| **Lighting** | Ambient + directional lights, HDR environment maps (Venice Sunset, Footprint Court), neutral room environment, exposure & tone mapping (Linear / ACES Filmic) |
-| **Display** | Wireframe overlay, skeleton visualization, grid + axes helpers, background color picker, auto-rotate, point size control |
-| **Animation** | Full clip playback with per-clip toggle, playback speed control, play-all |
-| **Morph Targets** | Real-time slider control for every morph target on every mesh |
-| **Cameras** | Switch between default orbit camera and any cameras embedded in the glTF |
-| **Validation** | Integrated [glTF-Validator](https://github.com/KhronosGroup/gltf-validator) — errors, warnings, hints, and info-level messages in a structured report |
-| **Performance** | Live FPS/MS/MB stats panel via `stats.js` |
-| **Deep Linking** | Load models via URL hash: `#model=url&preset=...&cameraPosition=x,y,z` |
-| **Privacy** | 100% client-side — your files never leave your browser |
+| Category | What You Get |
+| :---------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| **File Support** | `.glTF` and `.GLB` (glTF 2.0), with multi-file drag-and-drop (textures, bins) |
+| **Compression** | Draco mesh compression, KTX2 texture compression, Meshopt decoder |
+| **Lighting** | Ambient + directional lights, HDR environment maps (Venice Sunset, Footprint Court), neutral room environment, exposure & tone mapping (Linear / ACES Filmic) |
+| **Display** | Wireframe overlay, skeleton visualization, grid + axes helpers, background color picker, auto-rotate, point size control |
+| **Animation** | Full clip playback with per-clip toggle, playback speed control, play-all |
+| **Morph Targets** | Real-time slider control for every morph target on every mesh |
+| **Cameras** | Switch between default orbit camera and any cameras embedded in the glTF |
+| **Validation** | Integrated [glTF-Validator](https://github.com/KhronosGroup/gltf-validator) — errors, warnings, hints, and info-level messages in a structured report |
+| **Performance** | Live FPS/MS/MB stats panel via `stats.js` |
+| **Deep Linking** | Load models via URL hash: `#model=url&preset=...&cameraPosition=x,y,z` |
+| **Privacy** | 100% client-side — your files never leave your browser |
<br/>
@@ -104,12 +109,12 @@ Open **http://localhost:3000** and drop any `.glb` or `.gltf` file onto the page
### Available Scripts
-| Command | What It Does |
-|:--------|:-------------|
-| `npm run dev` | Starts Vite dev server on port 3000 with hot reload |
-| `npm run build` | Production build to `dist/` |
-| `npm run deploy` | Build + deploy to Vercel |
-| `npm run clean` | Wipe the `dist/` directory |
+| Command | What It Does |
+| :--------------- | :-------------------------------------------------- |
+| `npm run dev` | Starts Vite dev server on port 3000 with hot reload |
+| `npm run build` | Production build to `dist/` |
+| `npm run deploy` | Build + deploy to Vercel |
+| `npm run clean` | Wipe the `dist/` directory |
<br/>
@@ -148,17 +153,17 @@ Open **http://localhost:3000** and drop any `.glb` or `.gltf` file onto the page
### Tech Stack
-| Layer | Technology |
-|:------|:-----------|
-| **Rendering** | [three.js](https://threejs.org/) r176 — WebGL 2.0 |
-| **Model Loading** | `GLTFLoader` + `DRACOLoader` + `KTX2Loader` + `MeshoptDecoder` |
-| **Controls** | `OrbitControls` — pan, zoom, rotate |
-| **GUI** | [dat.gui](https://github.com/dataarts/dat.gui) — real-time parameter tweaking |
-| **Validation** | [gltf-validator](https://github.com/KhronosGroup/gltf-validator) — Khronos spec compliance |
-| **Templating** | [vhtml](https://github.com/developit/vhtml) — JSX → HTML string rendering |
-| **Drag & Drop** | [simple-dropzone](https://github.com/donmccurdy/simple-dropzone) |
-| **Build** | [Vite](https://vitejs.dev/) 8 — sub-second HMR |
-| **Hosting** | [Vercel](https://vercel.com/) — edge CDN |
+| Layer | Technology |
+| :---------------- | :----------------------------------------------------------------------------------------- |
+| **Rendering** | [three.js](https://threejs.org/) r176 — WebGL 2.0 |
+| **Model Loading** | `GLTFLoader` + `DRACOLoader` + `KTX2Loader` + `MeshoptDecoder` |
+| **Controls** | `OrbitControls` — pan, zoom, rotate |
+| **GUI** | [dat.gui](https://github.com/dataarts/dat.gui) — real-time parameter tweaking |
+| **Validation** | [gltf-validator](https://github.com/KhronosGroup/gltf-validator) — Khronos spec compliance |
+| **Templating** | [vhtml](https://github.com/developit/vhtml) — JSX → HTML string rendering |
+| **Drag & Drop** | [simple-dropzone](https://github.com/donmccurdy/simple-dropzone) |
+| **Build** | [Vite](https://vitejs.dev/) 8 — sub-second HMR |
+| **Hosting** | [Vercel](https://vercel.com/) — edge CDN |
<br/>
@@ -174,14 +179,15 @@ Load models and configure the viewer directly via URL hash parameters. This is u
https://3dagent.vercel.app/#model=URL&kiosk=true&preset=assetgenerator&cameraPosition=1,2,3
```
-| Parameter | Type | Description |
-|:----------|:-----|:------------|
-| `model` | `string` | URL to a `.glb` or `.gltf` file to load on page open |
-| `kiosk` | `boolean` | Hides the header and validation UI for clean embedding |
-| `preset` | `string` | Set to `assetgenerator` for glTF asset generator testing mode |
-| `cameraPosition` | `x,y,z` | Initial camera position as comma-separated floats |
+| Parameter | Type | Description |
+| :--------------- | :-------- | :------------------------------------------------------------ |
+| `model` | `string` | URL to a `.glb` or `.gltf` file to load on page open |
+| `kiosk` | `boolean` | Hides the header and validation UI for clean embedding |
+| `preset` | `string` | Set to `assetgenerator` for glTF asset generator testing mode |
+| `cameraPosition` | `x,y,z` | Initial camera position as comma-separated floats |
**Example — embed a model in kiosk mode:**
+
```
https://3dagent.vercel.app/#model=https://example.com/model.glb&kiosk=true
```
@@ -258,11 +264,11 @@ Use an `<iframe>` with kiosk mode for clean embedding:
```html
<iframe
- src="https://3dagent.vercel.app/#model=https://your-cdn.com/model.glb&kiosk=true"
- width="800"
- height="600"
- frameborder="0"
- allow="autoplay; fullscreen"
+ src="https://3dagent.vercel.app/#model=https://your-cdn.com/model.glb&kiosk=true"
+ width="800"
+ height="600"
+ frameborder="0"
+ allow="autoplay; fullscreen"
></iframe>
```
@@ -333,9 +339,9 @@ console.log(window.VIEWER.scene);
// Traverse all meshes
window.VIEWER.scene.traverse((node) => {
- if (node.isMesh) {
- console.log(node.name, node.geometry.attributes);
- }
+ if (node.isMesh) {
+ console.log(node.name, node.geometry.attributes);
+ }
});
```
@@ -381,13 +387,13 @@ See [CONTRIBUTING.md](CONTRIBUTING.md) for the full guide.
For deeper technical detail, see the `docs/` directory:
-| Document | Description |
-|:---------|:------------|
-| **[Architecture](docs/ARCHITECTURE.md)** | Data flow, module responsibilities, Three.js setup, validation pipeline, GUI structure, styling architecture, and security considerations |
-| **[API Reference](docs/API.md)** | Complete reference for all classes (`App`, `Viewer`, `Validator`), methods, properties, state objects, components, and the `window.VIEWER` debugging API |
-| **[Deployment](docs/DEPLOYMENT.md)** | Build pipeline, Vercel deploy, routing, CORS config, custom domains, iframe embedding, self-hosting (nginx, Docker), CDN strategy, and troubleshooting |
-| **[Development](docs/DEVELOPMENT.md)** | Local setup, code style, how-things-work guide, common tasks (new GUI controls, components, environments), debugging techniques, browser compatibility, and performance notes |
-| **[Contributing](CONTRIBUTING.md)** | Bug reporting, feature requests, PR workflow, commit conventions, code guidelines, and testing checklist |
+| Document | Description |
+| :--------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| **[Architecture](docs/ARCHITECTURE.md)** | Data flow, module responsibilities, Three.js setup, validation pipeline, GUI structure, styling architecture, and security considerations |
+| **[API Reference](docs/API.md)** | Complete reference for all classes (`App`, `Viewer`, `Validator`), methods, properties, state objects, components, and the `window.VIEWER` debugging API |
+| **[Deployment](docs/DEPLOYMENT.md)** | Build pipeline, Vercel deploy, routing, CORS config, custom domains, iframe embedding, self-hosting (nginx, Docker), CDN strategy, and troubleshooting |
+| **[Development](docs/DEVELOPMENT.md)** | Local setup, code style, how-things-work guide, common tasks (new GUI controls, components, environments), debugging techniques, browser compatibility, and performance notes |
+| **[Contributing](CONTRIBUTING.md)** | Bug reporting, feature requests, PR workflow, commit conventions, code guidelines, and testing checklist |
<br/>
@@ -397,16 +403,16 @@ For deeper technical detail, see the `docs/` directory:
## 📚 Resources
-| Resource | Link |
-|:---------|:-----|
-| **glTF 2.0 Spec** | [registry.khronos.org/glTF](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html) |
-| **Sample Models** | [KhronosGroup/glTF-Sample-Assets](https://github.com/KhronosGroup/glTF-Sample-Assets) |
-| **three.js Docs** | [threejs.org/docs](https://threejs.org/docs/) |
-| **GLTFLoader** | [three.js GLTFLoader](https://threejs.org/docs/#examples/en/loaders/GLTFLoader) |
-| **glTF Validator** | [KhronosGroup/gltf-validator](https://github.com/KhronosGroup/gltf-validator) |
-| **Sketchfab** | [sketchfab.com](https://sketchfab.com/) — download free glTF models |
-| **Mixamo** | [mixamo.com](https://www.mixamo.com/) — free rigged & animated characters |
-| **Poly Haven** | [polyhaven.com](https://polyhaven.com/) — free HDRIs, textures, and 3D models |
+| Resource | Link |
+| :----------------- | :------------------------------------------------------------------------------------- |
+| **glTF 2.0 Spec** | [registry.khronos.org/glTF](https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html) |
+| **Sample Models** | [KhronosGroup/glTF-Sample-Assets](https://github.com/KhronosGroup/glTF-Sample-Assets) |
+| **three.js Docs** | [threejs.org/docs](https://threejs.org/docs/) |
+| **GLTFLoader** | [three.js GLTFLoader](https://threejs.org/docs/#examples/en/loaders/GLTFLoader) |
+| **glTF Validator** | [KhronosGroup/gltf-validator](https://github.com/KhronosGroup/gltf-validator) |
+| **Sketchfab** | [sketchfab.com](https://sketchfab.com/) — download free glTF models |
+| **Mixamo** | [mixamo.com](https://www.mixamo.com/) — free rigged & animated characters |
+| **Poly Haven** | [polyhaven.com](https://polyhaven.com/) — free HDRIs, textures, and 3D models |
<br/>
diff --git a/agent-edit.html b/agent-edit.html
index d5036018f..44f4db7da 100644
--- a/agent-edit.html
+++ b/agent-edit.html
@@ -1,488 +1,568 @@
<!doctype html>
<html lang="en">
-<head>
- <meta charset="utf-8" />
- <title>Edit Agent — 3D Agent</title>
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <meta name="theme-color" content="#000000" />
- <link rel="shortcut icon" href="/favicon.ico" />
- <link rel="preconnect" href="https://fonts.googleapis.com" />
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
- <link rel="stylesheet" href="/style.css" />
- <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500&display=swap" rel="stylesheet" />
-
- <style>
- body { overflow: auto; display: flex; flex-direction: column; min-height: 100vh; }
-
- .edit-header {
- display: flex;
- align-items: center;
- gap: 1rem;
- padding: 0.875rem 1.618rem;
- border-bottom: 1px solid rgba(255,255,255,0.06);
- flex-shrink: 0;
- }
- .edit-header a {
- color: rgba(255,255,255,0.4);
- text-decoration: none;
- font-size: 0.764rem;
- }
- .edit-header a:hover { color: rgba(255,255,255,0.8); }
- .edit-header-title {
- flex: 1;
- font-size: 0.875rem;
- font-weight: 500;
- color: rgba(255,255,255,0.75);
- }
-
- .edit-tabs {
- display: flex;
- gap: 0;
- padding: 0 1.618rem;
- border-bottom: 1px solid rgba(255,255,255,0.06);
- flex-shrink: 0;
- }
- .edit-tab {
- background: transparent;
- border: 0;
- border-bottom: 2px solid transparent;
- color: rgba(255,255,255,0.4);
- font-size: 0.764rem;
- font-family: inherit;
- padding: 0.75rem 1rem;
- cursor: pointer;
- margin-bottom: -1px;
- transition: color 0.15s, border-color 0.15s;
- }
- .edit-tab:hover { color: rgba(255,255,255,0.7); }
- .edit-tab.active {
- color: rgba(255,255,255,0.9);
- border-bottom-color: #3b82f6;
- }
-
- .edit-panel { display: none; flex: 1; }
- .edit-panel.active { display: flex; }
-
- /* ── Persona tab ── */
- .persona-panel {
- max-width: 560px;
- margin: 2rem auto;
- padding: 0 1rem;
- flex-direction: column;
- gap: 1rem;
- width: 100%;
- }
- .form-group { display: flex; flex-direction: column; gap: 0.5rem; }
- .form-label {
- font-size: 0.764rem;
- color: rgba(255,255,255,0.5);
- font-weight: 500;
- }
- .form-input, .form-textarea {
- background: rgba(255,255,255,0.04);
- border: 1px solid rgba(255,255,255,0.1);
- border-radius: 8px;
- color: rgba(255,255,255,0.9);
- font: 0.875rem/1.5 inherit;
- padding: 0.618rem 0.875rem;
- width: 100%;
- box-sizing: border-box;
- outline: none;
- transition: border-color 0.15s;
- }
- .form-input:focus, .form-textarea:focus { border-color: rgba(59,130,246,0.5); }
- .form-textarea { resize: vertical; min-height: 90px; }
- .form-actions { display: flex; align-items: center; gap: 1rem; margin-top: 0.5rem; }
- .btn-primary {
- background: #3b82f6;
- border: 0;
- border-radius: 8px;
- color: #fff;
- cursor: pointer;
- font: 0.875rem/1 inherit;
- padding: 0.618rem 1.25rem;
- font-weight: 500;
- }
- .btn-primary:hover { background: #2563eb; }
- .btn-primary:disabled { opacity: 0.5; cursor: default; }
- .form-status {
- font-size: 0.764rem;
- color: rgba(255,255,255,0.4);
- }
- .form-status.ok { color: #86efac; }
- .form-status.err { color: #fca5a5; }
-
- /* ── Outfit tab ── */
- .outfit-panel {
- display: grid;
- grid-template-columns: 380px 1fr;
- gap: 0;
- flex: 1;
- min-height: 0;
- }
- @media (max-width: 800px) {
- .outfit-panel { grid-template-columns: 1fr; }
- .outfit-preview { height: 300px; }
- }
- .outfit-preview {
- position: sticky;
- top: 0;
- height: 100vh;
- background: #0a0a12;
- border-right: 1px solid rgba(255,255,255,0.06);
- overflow: hidden;
- }
- .outfit-preview agent-3d {
- width: 100%;
- height: 100%;
- }
- .outfit-controls {
- padding: 1.5rem;
- overflow-y: auto;
- }
- .outfit-header {
- display: flex;
- align-items: center;
- justify-content: space-between;
- margin-bottom: 1.25rem;
- }
- .outfit-title {
- font-size: 0.764rem;
- color: rgba(255,255,255,0.35);
- text-transform: uppercase;
- letter-spacing: 0.08em;
- }
- .btn-reset-all {
- background: transparent;
- border: 1px solid rgba(255,255,255,0.12);
- border-radius: 6px;
- color: rgba(255,255,255,0.4);
- cursor: pointer;
- font: 0.618rem/1 inherit;
- padding: 0.382rem 0.75rem;
- }
- .btn-reset-all:hover { color: rgba(255,255,255,0.8); border-color: rgba(255,255,255,0.25); }
-
- .mat-card {
- background: rgba(255,255,255,0.03);
- border: 1px solid rgba(255,255,255,0.07);
- border-radius: 10px;
- margin-bottom: 0.75rem;
- overflow: hidden;
- }
- .mat-card-header {
- display: flex;
- align-items: center;
- gap: 0.75rem;
- padding: 0.75rem 1rem;
- cursor: pointer;
- user-select: none;
- }
- .mat-card-header:hover { background: rgba(255,255,255,0.03); }
- .mat-card-chevron {
- color: rgba(255,255,255,0.25);
- font-size: 0.618rem;
- transition: transform 0.2s;
- margin-left: auto;
- }
- .mat-card.open .mat-card-chevron { transform: rotate(90deg); }
- .mat-card-name {
- font-size: 0.875rem;
- color: rgba(255,255,255,0.8);
- font-weight: 500;
- }
- .mat-card-swatch {
- width: 16px;
- height: 16px;
- border-radius: 4px;
- border: 1px solid rgba(255,255,255,0.15);
- flex-shrink: 0;
- }
- .mat-card-modified {
- font-size: 0.618rem;
- color: #93c5fd;
- margin-left: 0;
- }
- .mat-card-body { display: none; padding: 0 1rem 1rem; }
- .mat-card.open .mat-card-body { display: block; }
-
- .mat-row {
- display: grid;
- grid-template-columns: 100px 1fr auto;
- align-items: center;
- gap: 0.75rem;
- margin-bottom: 0.618rem;
- }
- .mat-row-label {
- font-size: 0.764rem;
- color: rgba(255,255,255,0.4);
- }
- .mat-row input[type="color"] {
- -webkit-appearance: none;
- width: 100%;
- height: 28px;
- border-radius: 6px;
- border: 1px solid rgba(255,255,255,0.12);
- padding: 0;
- cursor: pointer;
- background: transparent;
- }
- .mat-row input[type="color"]::-webkit-color-swatch-wrapper { padding: 2px; }
- .mat-row input[type="color"]::-webkit-color-swatch { border-radius: 4px; border: none; }
- .mat-row input[type="range"] {
- width: 100%;
- accent-color: #3b82f6;
- }
- .mat-row-val {
- font-size: 0.618rem;
- color: rgba(255,255,255,0.35);
- min-width: 30px;
- text-align: right;
- }
- .mat-card-footer {
- display: flex;
- justify-content: flex-end;
- padding-top: 0.5rem;
- }
- .btn-reset-mat {
- background: transparent;
- border: 0;
- color: rgba(255,255,255,0.3);
- cursor: pointer;
- font: 0.618rem/1 inherit;
- padding: 0.25rem 0;
- }
- .btn-reset-mat:hover { color: rgba(255,255,255,0.7); }
-
- .outfit-status {
- position: fixed;
- bottom: 1rem;
- right: 1.5rem;
- font-size: 0.618rem;
- color: rgba(255,255,255,0.25);
- pointer-events: none;
- }
- .outfit-status.saving { color: rgba(255,255,255,0.4); }
- .outfit-status.saved { color: #86efac; }
- .outfit-status.err { color: #fca5a5; }
-
- .loading-msg, .error-msg {
- flex: 1;
- display: flex;
- align-items: center;
- justify-content: center;
- color: rgba(255,255,255,0.3);
- font-size: 0.875rem;
- }
- .error-msg { color: #fca5a5; }
- .no-avatar-msg {
- padding: 2rem;
- color: rgba(255,255,255,0.3);
- font-size: 0.764rem;
- text-align: center;
- }
- .no-named-mats {
- color: rgba(255,255,255,0.3);
- font-size: 0.764rem;
- padding: 1rem 0;
- }
- </style>
-</head>
-<body>
- <header class="edit-header">
- <a id="back-link" href="/">← Agent</a>
- <div class="edit-header-title" id="agent-title">Edit Agent</div>
- </header>
-
- <div class="edit-tabs" role="tablist">
- <button class="edit-tab active" data-tab="persona">Persona</button>
- <button class="edit-tab" data-tab="outfit">Outfit</button>
- </div>
-
- <div id="loading" class="loading-msg">Loading…</div>
- <div id="error" class="error-msg" style="display:none"></div>
-
- <!-- Persona tab -->
- <div class="edit-panel persona-panel" id="panel-persona">
- <div class="form-group">
- <label class="form-label" for="f-name">Name</label>
- <input class="form-input" id="f-name" type="text" maxlength="100" />
- </div>
- <div class="form-group">
- <label class="form-label" for="f-desc">Description</label>
- <textarea class="form-textarea" id="f-desc" rows="4" maxlength="500"></textarea>
- </div>
- <div class="form-actions">
- <button class="btn-primary" id="persona-save">Save</button>
- <span class="form-status" id="persona-status"></span>
+ <head>
+ <meta charset="utf-8" />
+ <title>Edit Agent — 3D Agent</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta name="theme-color" content="#000000" />
+ <link rel="shortcut icon" href="/favicon.ico" />
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
+ <link rel="stylesheet" href="/style.css" />
+ <link
+ href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500&display=swap"
+ rel="stylesheet"
+ />
+
+ <style>
+ body {
+ overflow: auto;
+ display: flex;
+ flex-direction: column;
+ min-height: 100vh;
+ }
+
+ .edit-header {
+ display: flex;
+ align-items: center;
+ gap: 1rem;
+ padding: 0.875rem 1.618rem;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);
+ flex-shrink: 0;
+ }
+ .edit-header a {
+ color: rgba(255, 255, 255, 0.4);
+ text-decoration: none;
+ font-size: 0.764rem;
+ }
+ .edit-header a:hover {
+ color: rgba(255, 255, 255, 0.8);
+ }
+ .edit-header-title {
+ flex: 1;
+ font-size: 0.875rem;
+ font-weight: 500;
+ color: rgba(255, 255, 255, 0.75);
+ }
+
+ .edit-tabs {
+ display: flex;
+ gap: 0;
+ padding: 0 1.618rem;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);
+ flex-shrink: 0;
+ }
+ .edit-tab {
+ background: transparent;
+ border: 0;
+ border-bottom: 2px solid transparent;
+ color: rgba(255, 255, 255, 0.4);
+ font-size: 0.764rem;
+ font-family: inherit;
+ padding: 0.75rem 1rem;
+ cursor: pointer;
+ margin-bottom: -1px;
+ transition:
+ color 0.15s,
+ border-color 0.15s;
+ }
+ .edit-tab:hover {
+ color: rgba(255, 255, 255, 0.7);
+ }
+ .edit-tab.active {
+ color: rgba(255, 255, 255, 0.9);
+ border-bottom-color: #3b82f6;
+ }
+
+ .edit-panel {
+ display: none;
+ flex: 1;
+ }
+ .edit-panel.active {
+ display: flex;
+ }
+
+ /* ── Persona tab ── */
+ .persona-panel {
+ max-width: 560px;
+ margin: 2rem auto;
+ padding: 0 1rem;
+ flex-direction: column;
+ gap: 1rem;
+ width: 100%;
+ }
+ .form-group {
+ display: flex;
+ flex-direction: column;
+ gap: 0.5rem;
+ }
+ .form-label {
+ font-size: 0.764rem;
+ color: rgba(255, 255, 255, 0.5);
+ font-weight: 500;
+ }
+ .form-input,
+ .form-textarea {
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ border-radius: 8px;
+ color: rgba(255, 255, 255, 0.9);
+ font: 0.875rem/1.5 inherit;
+ padding: 0.618rem 0.875rem;
+ width: 100%;
+ box-sizing: border-box;
+ outline: none;
+ transition: border-color 0.15s;
+ }
+ .form-input:focus,
+ .form-textarea:focus {
+ border-color: rgba(59, 130, 246, 0.5);
+ }
+ .form-textarea {
+ resize: vertical;
+ min-height: 90px;
+ }
+ .form-actions {
+ display: flex;
+ align-items: center;
+ gap: 1rem;
+ margin-top: 0.5rem;
+ }
+ .btn-primary {
+ background: #3b82f6;
+ border: 0;
+ border-radius: 8px;
+ color: #fff;
+ cursor: pointer;
+ font: 0.875rem/1 inherit;
+ padding: 0.618rem 1.25rem;
+ font-weight: 500;
+ }
+ .btn-primary:hover {
+ background: #2563eb;
+ }
+ .btn-primary:disabled {
+ opacity: 0.5;
+ cursor: default;
+ }
+ .form-status {
+ font-size: 0.764rem;
+ color: rgba(255, 255, 255, 0.4);
+ }
+ .form-status.ok {
+ color: #86efac;
+ }
+ .form-status.err {
+ color: #fca5a5;
+ }
+
+ /* ── Outfit tab ── */
+ .outfit-panel {
+ display: grid;
+ grid-template-columns: 380px 1fr;
+ gap: 0;
+ flex: 1;
+ min-height: 0;
+ }
+ @media (max-width: 800px) {
+ .outfit-panel {
+ grid-template-columns: 1fr;
+ }
+ .outfit-preview {
+ height: 300px;
+ }
+ }
+ .outfit-preview {
+ position: sticky;
+ top: 0;
+ height: 100vh;
+ background: #0a0a12;
+ border-right: 1px solid rgba(255, 255, 255, 0.06);
+ overflow: hidden;
+ }
+ .outfit-preview agent-3d {
+ width: 100%;
+ height: 100%;
+ }
+ .outfit-controls {
+ padding: 1.5rem;
+ overflow-y: auto;
+ }
+ .outfit-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 1.25rem;
+ }
+ .outfit-title {
+ font-size: 0.764rem;
+ color: rgba(255, 255, 255, 0.35);
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ }
+ .btn-reset-all {
+ background: transparent;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ border-radius: 6px;
+ color: rgba(255, 255, 255, 0.4);
+ cursor: pointer;
+ font: 0.618rem/1 inherit;
+ padding: 0.382rem 0.75rem;
+ }
+ .btn-reset-all:hover {
+ color: rgba(255, 255, 255, 0.8);
+ border-color: rgba(255, 255, 255, 0.25);
+ }
+
+ .mat-card {
+ background: rgba(255, 255, 255, 0.03);
+ border: 1px solid rgba(255, 255, 255, 0.07);
+ border-radius: 10px;
+ margin-bottom: 0.75rem;
+ overflow: hidden;
+ }
+ .mat-card-header {
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+ padding: 0.75rem 1rem;
+ cursor: pointer;
+ user-select: none;
+ }
+ .mat-card-header:hover {
+ background: rgba(255, 255, 255, 0.03);
+ }
+ .mat-card-chevron {
+ color: rgba(255, 255, 255, 0.25);
+ font-size: 0.618rem;
+ transition: transform 0.2s;
+ margin-left: auto;
+ }
+ .mat-card.open .mat-card-chevron {
+ transform: rotate(90deg);
+ }
+ .mat-card-name {
+ font-size: 0.875rem;
+ color: rgba(255, 255, 255, 0.8);
+ font-weight: 500;
+ }
+ .mat-card-swatch {
+ width: 16px;
+ height: 16px;
+ border-radius: 4px;
+ border: 1px solid rgba(255, 255, 255, 0.15);
+ flex-shrink: 0;
+ }
+ .mat-card-modified {
+ font-size: 0.618rem;
+ color: #93c5fd;
+ margin-left: 0;
+ }
+ .mat-card-body {
+ display: none;
+ padding: 0 1rem 1rem;
+ }
+ .mat-card.open .mat-card-body {
+ display: block;
+ }
+
+ .mat-row {
+ display: grid;
+ grid-template-columns: 100px 1fr auto;
+ align-items: center;
+ gap: 0.75rem;
+ margin-bottom: 0.618rem;
+ }
+ .mat-row-label {
+ font-size: 0.764rem;
+ color: rgba(255, 255, 255, 0.4);
+ }
+ .mat-row input[type='color'] {
+ -webkit-appearance: none;
+ width: 100%;
+ height: 28px;
+ border-radius: 6px;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ padding: 0;
+ cursor: pointer;
+ background: transparent;
+ }
+ .mat-row input[type='color']::-webkit-color-swatch-wrapper {
+ padding: 2px;
+ }
+ .mat-row input[type='color']::-webkit-color-swatch {
+ border-radius: 4px;
+ border: none;
+ }
+ .mat-row input[type='range'] {
+ width: 100%;
+ accent-color: #3b82f6;
+ }
+ .mat-row-val {
+ font-size: 0.618rem;
+ color: rgba(255, 255, 255, 0.35);
+ min-width: 30px;
+ text-align: right;
+ }
+ .mat-card-footer {
+ display: flex;
+ justify-content: flex-end;
+ padding-top: 0.5rem;
+ }
+ .btn-reset-mat {
+ background: transparent;
+ border: 0;
+ color: rgba(255, 255, 255, 0.3);
+ cursor: pointer;
+ font: 0.618rem/1 inherit;
+ padding: 0.25rem 0;
+ }
+ .btn-reset-mat:hover {
+ color: rgba(255, 255, 255, 0.7);
+ }
+
+ .outfit-status {
+ position: fixed;
+ bottom: 1rem;
+ right: 1.5rem;
+ font-size: 0.618rem;
+ color: rgba(255, 255, 255, 0.25);
+ pointer-events: none;
+ }
+ .outfit-status.saving {
+ color: rgba(255, 255, 255, 0.4);
+ }
+ .outfit-status.saved {
+ color: #86efac;
+ }
+ .outfit-status.err {
+ color: #fca5a5;
+ }
+
+ .loading-msg,
+ .error-msg {
+ flex: 1;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: rgba(255, 255, 255, 0.3);
+ font-size: 0.875rem;
+ }
+ .error-msg {
+ color: #fca5a5;
+ }
+ .no-avatar-msg {
+ padding: 2rem;
+ color: rgba(255, 255, 255, 0.3);
+ font-size: 0.764rem;
+ text-align: center;
+ }
+ .no-named-mats {
+ color: rgba(255, 255, 255, 0.3);
+ font-size: 0.764rem;
+ padding: 1rem 0;
+ }
+ </style>
+ </head>
+ <body>
+ <header class="edit-header">
+ <a id="back-link" href="/">← Agent</a>
+ <div class="edit-header-title" id="agent-title">Edit Agent</div>
+ </header>
+
+ <div class="edit-tabs" role="tablist">
+ <button class="edit-tab active" data-tab="persona">Persona</button>
+ <button class="edit-tab" data-tab="outfit">Outfit</button>
</div>
- </div>
- <!-- Outfit tab -->
- <div class="edit-panel outfit-panel" id="panel-outfit">
- <div class="outfit-preview" id="outfit-preview">
- <!-- agent-3d inserted here once avatar is confirmed -->
+ <div id="loading" class="loading-msg">Loading…</div>
+ <div id="error" class="error-msg" style="display: none"></div>
+
+ <!-- Persona tab -->
+ <div class="edit-panel persona-panel" id="panel-persona">
+ <div class="form-group">
+ <label class="form-label" for="f-name">Name</label>
+ <input class="form-input" id="f-name" type="text" maxlength="100" />
+ </div>
+ <div class="form-group">
+ <label class="form-label" for="f-desc">Description</label>
+ <textarea class="form-textarea" id="f-desc" rows="4" maxlength="500"></textarea>
+ </div>
+ <div class="form-actions">
+ <button class="btn-primary" id="persona-save">Save</button>
+ <span class="form-status" id="persona-status"></span>
+ </div>
</div>
- <div class="outfit-controls" id="outfit-controls">
- <div class="outfit-header">
- <span class="outfit-title">Materials</span>
- <button class="btn-reset-all" id="btn-reset-all">Reset all</button>
+
+ <!-- Outfit tab -->
+ <div class="edit-panel outfit-panel" id="panel-outfit">
+ <div class="outfit-preview" id="outfit-preview">
+ <!-- agent-3d inserted here once avatar is confirmed -->
</div>
- <div id="mat-list">
- <div class="no-named-mats">Loading preview…</div>
+ <div class="outfit-controls" id="outfit-controls">
+ <div class="outfit-header">
+ <span class="outfit-title">Materials</span>
+ <button class="btn-reset-all" id="btn-reset-all">Reset all</button>
+ </div>
+ <div id="mat-list">
+ <div class="no-named-mats">Loading preview…</div>
+ </div>
</div>
</div>
- </div>
- <div class="outfit-status" id="outfit-status"></div>
+ <div class="outfit-status" id="outfit-status"></div>
- <script type="module">
- import './src/element.js'; // registers <agent-3d>
+ <script type="module">
+ import './src/element.js'; // registers <agent-3d>
- // ── Bootstrap ─────────────────────────────────────────────────────────────
- const agentId = location.pathname.split('/').filter(Boolean)[1]; // /agent/:id/edit
- if (!agentId) { showError('No agent ID in URL.'); throw new Error(); }
+ // ── Bootstrap ─────────────────────────────────────────────────────────────
+ const agentId = location.pathname.split('/').filter(Boolean)[1]; // /agent/:id/edit
+ if (!agentId) {
+ showError('No agent ID in URL.');
+ throw new Error();
+ }
- document.getElementById('back-link').href = `/agent/${agentId}`;
+ document.getElementById('back-link').href = `/agent/${agentId}`;
- let agent = null;
- let overridesMap = {}; // { materialName: { color, metalness, roughness, emissive } }
- let agentEl = null; // the <agent-3d> element once created
- let saveTimer = null;
+ let agent = null;
+ let overridesMap = {}; // { materialName: { color, metalness, roughness, emissive } }
+ let agentEl = null; // the <agent-3d> element once created
+ let saveTimer = null;
- async function init() {
- const res = await fetch(`/api/agents/${agentId}`, { credentials: 'include' });
- if (!res.ok) {
- const err = await res.json().catch(() => ({}));
- throw new Error(err.error_description || `HTTP ${res.status}`);
- }
- const { agent: a } = await res.json();
- if (!a) throw new Error('Agent not found');
- if (!a.user_id) {
- // Not the owner — redirect to public page
- location.href = `/agent/${agentId}`;
- return;
- }
- agent = a;
- overridesMap = (agent.meta?.edits?.materials) || {};
+ async function init() {
+ const res = await fetch(`/api/agents/${agentId}`, { credentials: 'include' });
+ if (!res.ok) {
+ const err = await res.json().catch(() => ({}));
+ throw new Error(err.error_description || `HTTP ${res.status}`);
+ }
+ const { agent: a } = await res.json();
+ if (!a) throw new Error('Agent not found');
+ if (!a.user_id) {
+ // Not the owner — redirect to public page
+ location.href = `/agent/${agentId}`;
+ return;
+ }
+ agent = a;
+ overridesMap = agent.meta?.edits?.materials || {};
- document.getElementById('agent-title').textContent = `Edit — ${agent.name}`;
- document.getElementById('loading').style.display = 'none';
+ document.getElementById('agent-title').textContent = `Edit — ${agent.name}`;
+ document.getElementById('loading').style.display = 'none';
- initPersonaTab();
- activateTab('persona');
- }
+ initPersonaTab();
+ activateTab('persona');
+ }
- init().catch((err) => showError(err.message || String(err)));
+ init().catch((err) => showError(err.message || String(err)));
+
+ // ── Tab switching ─────────────────────────────────────────────────────────
+ function activateTab(name) {
+ document.querySelectorAll('.edit-tab').forEach((btn) => {
+ btn.classList.toggle('active', btn.dataset.tab === name);
+ });
+ document.querySelectorAll('.edit-panel').forEach((p) => {
+ p.classList.toggle('active', p.id === `panel-${name}`);
+ });
+ if (name === 'outfit') initOutfitTab();
+ }
- // ── Tab switching ─────────────────────────────────────────────────────────
- function activateTab(name) {
document.querySelectorAll('.edit-tab').forEach((btn) => {
- btn.classList.toggle('active', btn.dataset.tab === name);
+ btn.addEventListener('click', () => activateTab(btn.dataset.tab));
});
- document.querySelectorAll('.edit-panel').forEach((p) => {
- p.classList.toggle('active', p.id === `panel-${name}`);
- });
- if (name === 'outfit') initOutfitTab();
- }
-
- document.querySelectorAll('.edit-tab').forEach((btn) => {
- btn.addEventListener('click', () => activateTab(btn.dataset.tab));
- });
-
- // ── Persona tab ───────────────────────────────────────────────────────────
- function initPersonaTab() {
- document.getElementById('f-name').value = agent.name || '';
- document.getElementById('f-desc').value = agent.description || '';
- }
-
- document.getElementById('persona-save').addEventListener('click', async () => {
- const btn = document.getElementById('persona-save');
- const status = document.getElementById('persona-status');
- btn.disabled = true;
- status.textContent = 'Saving…';
- status.className = 'form-status';
- try {
- const res = await fetch(`/api/agents/${agentId}`, {
- method: 'PUT',
- credentials: 'include',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({
- name: document.getElementById('f-name').value.trim() || agent.name,
- description: document.getElementById('f-desc').value.trim() || null,
- }),
- });
- if (!res.ok) {
- const err = await res.json().catch(() => ({}));
- throw new Error(err.error_description || `HTTP ${res.status}`);
+
+ // ── Persona tab ───────────────────────────────────────────────────────────
+ function initPersonaTab() {
+ document.getElementById('f-name').value = agent.name || '';
+ document.getElementById('f-desc').value = agent.description || '';
+ }
+
+ document.getElementById('persona-save').addEventListener('click', async () => {
+ const btn = document.getElementById('persona-save');
+ const status = document.getElementById('persona-status');
+ btn.disabled = true;
+ status.textContent = 'Saving…';
+ status.className = 'form-status';
+ try {
+ const res = await fetch(`/api/agents/${agentId}`, {
+ method: 'PUT',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ name: document.getElementById('f-name').value.trim() || agent.name,
+ description: document.getElementById('f-desc').value.trim() || null,
+ }),
+ });
+ if (!res.ok) {
+ const err = await res.json().catch(() => ({}));
+ throw new Error(err.error_description || `HTTP ${res.status}`);
+ }
+ const { agent: updated } = await res.json();
+ agent = updated;
+ document.getElementById('agent-title').textContent = `Edit — ${agent.name}`;
+ status.textContent = 'Saved.';
+ status.className = 'form-status ok';
+ } catch (err) {
+ status.textContent = err.message;
+ status.className = 'form-status err';
+ } finally {
+ btn.disabled = false;
}
- const { agent: updated } = await res.json();
- agent = updated;
- document.getElementById('agent-title').textContent = `Edit — ${agent.name}`;
- status.textContent = 'Saved.';
- status.className = 'form-status ok';
- } catch (err) {
- status.textContent = err.message;
- status.className = 'form-status err';
- } finally {
- btn.disabled = false;
- }
- });
-
- // ── Outfit tab ────────────────────────────────────────────────────────────
- let outfitInitialized = false;
-
- function initOutfitTab() {
- if (outfitInitialized) return;
- outfitInitialized = true;
-
- if (!agent.avatar_id) {
- document.getElementById('mat-list').innerHTML =
- '<div class="no-avatar-msg">No avatar attached to this agent.<br>Attach an avatar from the Dashboard first.</div>';
- return;
- }
-
- // Create <agent-3d> in the preview panel
- agentEl = document.createElement('agent-3d');
- agentEl.setAttribute('agent-id', agentId);
- agentEl.setAttribute('kiosk', '');
- agentEl.setAttribute('eager', '');
- agentEl.style.width = '100%';
- agentEl.style.height = '100%';
- document.getElementById('outfit-preview').appendChild(agentEl);
-
- agentEl.addEventListener('agent:ready', () => buildMatUI());
- agentEl.addEventListener('agent:error', (e) => {
- document.getElementById('mat-list').innerHTML =
- `<div class="no-avatar-msg">Preview error: ${esc(e.detail?.error?.message || 'unknown')}</div>`;
});
- }
- function buildMatUI() {
- const mats = agentEl.getMaterials();
- const named = mats.filter((m) => m.name);
- const list = document.getElementById('mat-list');
+ // ── Outfit tab ────────────────────────────────────────────────────────────
+ let outfitInitialized = false;
+
+ function initOutfitTab() {
+ if (outfitInitialized) return;
+ outfitInitialized = true;
- if (!named.length) {
- list.innerHTML = '<div class="no-named-mats">No named materials found in this model.</div>';
- return;
+ if (!agent.avatar_id) {
+ document.getElementById('mat-list').innerHTML =
+ '<div class="no-avatar-msg">No avatar attached to this agent.<br>Attach an avatar from the Dashboard first.</div>';
+ return;
+ }
+
+ // Create <agent-3d> in the preview panel
+ agentEl = document.createElement('agent-3d');
+ agentEl.setAttribute('agent-id', agentId);
+ agentEl.setAttribute('kiosk', '');
+ agentEl.setAttribute('eager', '');
+ agentEl.style.width = '100%';
+ agentEl.style.height = '100%';
+ document.getElementById('outfit-preview').appendChild(agentEl);
+
+ agentEl.addEventListener('agent:ready', () => buildMatUI());
+ agentEl.addEventListener('agent:error', (e) => {
+ document.getElementById('mat-list').innerHTML =
+ `<div class="no-avatar-msg">Preview error: ${esc(e.detail?.error?.message || 'unknown')}</div>`;
+ });
}
- list.innerHTML = '';
- for (const mat of named) {
- list.appendChild(buildMatCard(mat));
+ function buildMatUI() {
+ const mats = agentEl.getMaterials();
+ const named = mats.filter((m) => m.name);
+ const list = document.getElementById('mat-list');
+
+ if (!named.length) {
+ list.innerHTML =
+ '<div class="no-named-mats">No named materials found in this model.</div>';
+ return;
+ }
+
+ list.innerHTML = '';
+ for (const mat of named) {
+ list.appendChild(buildMatCard(mat));
+ }
}
- }
- function buildMatCard(mat) {
- const override = overridesMap[mat.name] || {};
- const card = document.createElement('div');
- card.className = 'mat-card';
- card.dataset.mat = mat.name;
+ function buildMatCard(mat) {
+ const override = overridesMap[mat.name] || {};
+ const card = document.createElement('div');
+ card.className = 'mat-card';
+ card.dataset.mat = mat.name;
- const isModified = !!overridesMap[mat.name];
+ const isModified = !!overridesMap[mat.name];
- card.innerHTML = `
+ card.innerHTML = `
<div class="mat-card-header">
<span class="mat-card-swatch" style="background:${esc(override.color || mat.color)}"></span>
<span class="mat-card-name">${esc(mat.name)}</span>
@@ -518,117 +598,128 @@
</div>
`;
- // Toggle open/close
- card.querySelector('.mat-card-header').addEventListener('click', () => {
- card.classList.toggle('open');
- });
-
- // Field changes
- card.querySelectorAll('input').forEach((inp) => {
- inp.addEventListener('input', () => {
- const field = inp.dataset.field;
- const val = inp.type === 'range' ? parseFloat(inp.value) : inp.value;
-
- // Update range display value
- const row = inp.closest('.mat-row');
- if (inp.type === 'range') row.querySelector('.mat-row-val').textContent = fmtN(val);
-
- // Update swatch if color
- if (field === 'color') card.querySelector('.mat-card-swatch').style.background = val;
+ // Toggle open/close
+ card.querySelector('.mat-card-header').addEventListener('click', () => {
+ card.classList.toggle('open');
+ });
- // Merge into overrides
- overridesMap[mat.name] = { ...(overridesMap[mat.name] || {}), [field]: val };
- markModified(card, true);
+ // Field changes
+ card.querySelectorAll('input').forEach((inp) => {
+ inp.addEventListener('input', () => {
+ const field = inp.dataset.field;
+ const val = inp.type === 'range' ? parseFloat(inp.value) : inp.value;
+
+ // Update range display value
+ const row = inp.closest('.mat-row');
+ if (inp.type === 'range')
+ row.querySelector('.mat-row-val').textContent = fmtN(val);
+
+ // Update swatch if color
+ if (field === 'color')
+ card.querySelector('.mat-card-swatch').style.background = val;
+
+ // Merge into overrides
+ overridesMap[mat.name] = {
+ ...(overridesMap[mat.name] || {}),
+ [field]: val,
+ };
+ markModified(card, true);
+
+ agentEl.applyOverrides(overridesMap);
+ scheduleSave();
+ });
+ });
+ // Reset this material
+ card.querySelector('.btn-reset-mat').addEventListener('click', (e) => {
+ e.stopPropagation();
+ delete overridesMap[mat.name];
+ // Rebuild this card using GLB defaults (from getMaterials which reads live state after applyOverrides)
agentEl.applyOverrides(overridesMap);
+ const mats = agentEl.getMaterials();
+ const fresh = mats.find((m) => m.name === mat.name);
+ if (fresh) {
+ const newCard = buildMatCard(fresh);
+ card.replaceWith(newCard);
+ }
scheduleSave();
});
- });
- // Reset this material
- card.querySelector('.btn-reset-mat').addEventListener('click', (e) => {
- e.stopPropagation();
- delete overridesMap[mat.name];
- // Rebuild this card using GLB defaults (from getMaterials which reads live state after applyOverrides)
- agentEl.applyOverrides(overridesMap);
- const mats = agentEl.getMaterials();
- const fresh = mats.find((m) => m.name === mat.name);
- if (fresh) {
- const newCard = buildMatCard(fresh);
- card.replaceWith(newCard);
+ return card;
+ }
+
+ function markModified(card, modified) {
+ let dot = card.querySelector('.mat-card-modified');
+ if (modified && !dot) {
+ dot = document.createElement('span');
+ dot.className = 'mat-card-modified';
+ dot.textContent = '●';
+ card.querySelector('.mat-card-name').after(dot);
+ } else if (!modified && dot) {
+ dot.remove();
+ }
+ }
+
+ document.getElementById('btn-reset-all').addEventListener('click', () => {
+ overridesMap = {};
+ if (agentEl) {
+ agentEl.applyOverrides({});
+ buildMatUI();
}
scheduleSave();
});
- return card;
- }
-
- function markModified(card, modified) {
- let dot = card.querySelector('.mat-card-modified');
- if (modified && !dot) {
- dot = document.createElement('span');
- dot.className = 'mat-card-modified';
- dot.textContent = '●';
- card.querySelector('.mat-card-name').after(dot);
- } else if (!modified && dot) {
- dot.remove();
- }
- }
-
- document.getElementById('btn-reset-all').addEventListener('click', () => {
- overridesMap = {};
- if (agentEl) {
- agentEl.applyOverrides({});
- buildMatUI();
- }
- scheduleSave();
- });
-
- // ── Debounced save ────────────────────────────────────────────────────────
- function scheduleSave() {
- clearTimeout(saveTimer);
- setOutfitStatus('saving', '● unsaved');
- saveTimer = setTimeout(saveEdits, 1000);
- }
-
- async function saveEdits() {
- setOutfitStatus('saving', 'Saving…');
- try {
- const res = await fetch(`/api/agents/${agentId}`, {
- method: 'PATCH',
- credentials: 'include',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ edits: { materials: overridesMap } }),
- });
- if (!res.ok) {
- const err = await res.json().catch(() => ({}));
- throw new Error(err.error_description || `HTTP ${res.status}`);
+ // ── Debounced save ────────────────────────────────────────────────────────
+ function scheduleSave() {
+ clearTimeout(saveTimer);
+ setOutfitStatus('saving', '● unsaved');
+ saveTimer = setTimeout(saveEdits, 1000);
+ }
+
+ async function saveEdits() {
+ setOutfitStatus('saving', 'Saving…');
+ try {
+ const res = await fetch(`/api/agents/${agentId}`, {
+ method: 'PATCH',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ edits: { materials: overridesMap } }),
+ });
+ if (!res.ok) {
+ const err = await res.json().catch(() => ({}));
+ throw new Error(err.error_description || `HTTP ${res.status}`);
+ }
+ setOutfitStatus('saved', 'Saved ✓');
+ setTimeout(() => setOutfitStatus('', ''), 2000);
+ } catch (err) {
+ setOutfitStatus('err', `Save failed: ${err.message}`);
}
- setOutfitStatus('saved', 'Saved ✓');
- setTimeout(() => setOutfitStatus('', ''), 2000);
- } catch (err) {
- setOutfitStatus('err', `Save failed: ${err.message}`);
- }
- }
-
- function setOutfitStatus(cls, text) {
- const el = document.getElementById('outfit-status');
- el.className = `outfit-status ${cls}`;
- el.textContent = text;
- }
-
- // ── Helpers ───────────────────────────────────────────────────────────────
- function esc(s) {
- return String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
- }
- function fmtN(n) { return Number(n).toFixed(2); }
-
- function showError(msg) {
- document.getElementById('loading').style.display = 'none';
- const el = document.getElementById('error');
- el.style.display = 'flex';
- el.textContent = msg;
- }
- </script>
-</body>
+ }
+
+ function setOutfitStatus(cls, text) {
+ const el = document.getElementById('outfit-status');
+ el.className = `outfit-status ${cls}`;
+ el.textContent = text;
+ }
+
+ // ── Helpers ───────────────────────────────────────────────────────────────
+ function esc(s) {
+ return String(s ?? '')
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;');
+ }
+ function fmtN(n) {
+ return Number(n).toFixed(2);
+ }
+
+ function showError(msg) {
+ document.getElementById('loading').style.display = 'none';
+ const el = document.getElementById('error');
+ el.style.display = 'flex';
+ el.textContent = msg;
+ }
+ </script>
+ </body>
</html>
diff --git a/api/CLAUDE.md b/api/CLAUDE.md
index 0617a161f..68ef06ec7 100644
--- a/api/CLAUDE.md
+++ b/api/CLAUDE.md
@@ -26,7 +26,8 @@ export default wrap(async (req, res) => {
const session = await getSessionUser(req);
const bearer = session ? null : await authenticateBearer(extractBearer(req));
if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
- if (bearer && !hasScope(bearer.scope, 'avatars:read')) return error(res, 403, 'insufficient_scope', '...');
+ if (bearer && !hasScope(bearer.scope, 'avatars:read'))
+ return error(res, 403, 'insufficient_scope', '...');
const userId = session?.id ?? bearer.userId;
// Rate limit
@@ -38,7 +39,8 @@ export default wrap(async (req, res) => {
// ... do work
}
- const rows = await sql`select id, name from avatars where owner_id = ${userId} and deleted_at is null`;
+ const rows =
+ await sql`select id, name from avatars where owner_id = ${userId} and deleted_at is null`;
return json(res, 200, { data: rows });
});
```
@@ -47,18 +49,18 @@ Never `res.end(JSON.stringify(...))`. Never read/verify JWTs yourself. Never int
---
-## Helpers in [_lib/](./_lib/)
+## Helpers in [\_lib/](./_lib/)
-| File | Exports | Use for |
-|---|---|---|
-| [_lib/auth.js](_lib/auth.js) | `getSessionUser`, `authenticateBearer`, `extractBearer`, `hasScope`, `createSession`, `sessionCookie`, `destroySession`, `csrfTokenFor`, `verifyCsrfToken`, `isSameSiteOrigin` | All auth. Never roll your own. |
-| [_lib/db.js](_lib/db.js) | `sql` | Tagged-template Postgres via `@neondatabase/serverless`. Import; don't instantiate a new Pool. |
-| [_lib/http.js](_lib/http.js) | `cors`, `json`, `text`, `redirect`, `error`, `wrap`, `method`, `readJson` | Every response. `wrap()` catches async errors → 500. |
-| [_lib/validate.js](_lib/validate.js) | `parse`, `email`, `password`, `displayName`, `slug`, `avatarVisibility`, `avatarContentType`, `registerBody`, `loginBody`, `createAvatarBody`, `presignUploadBody` | zod wrappers. `parse()` throws `{status:400, code:'validation_error'}`. |
-| [_lib/rate-limit.js](_lib/rate-limit.js) | `limits.*`, `clientIp` | Preset Upstash limiters. |
-| [_lib/r2.js](_lib/r2.js) | `presignUpload`, `presignGet`, `headObject`, `deleteObject`, `publicUrl` | R2 / S3 ops. |
-| [_lib/env.js](_lib/env.js) | `env`, `env.ISSUER`, `env.MCP_RESOURCE` | Env vars. Throws if required ones missing. |
-| [_lib/avatars.js](_lib/avatars.js) | `stripOwnerFor`, avatar URL resolution | Hides R2 path prefixes from unauthenticated callers. |
+| File | Exports | Use for |
+| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------- |
+| [\_lib/auth.js](_lib/auth.js) | `getSessionUser`, `authenticateBearer`, `extractBearer`, `hasScope`, `createSession`, `sessionCookie`, `destroySession`, `csrfTokenFor`, `verifyCsrfToken`, `isSameSiteOrigin` | All auth. Never roll your own. |
+| [\_lib/db.js](_lib/db.js) | `sql` | Tagged-template Postgres via `@neondatabase/serverless`. Import; don't instantiate a new Pool. |
+| [\_lib/http.js](_lib/http.js) | `cors`, `json`, `text`, `redirect`, `error`, `wrap`, `method`, `readJson` | Every response. `wrap()` catches async errors → 500. |
+| [\_lib/validate.js](_lib/validate.js) | `parse`, `email`, `password`, `displayName`, `slug`, `avatarVisibility`, `avatarContentType`, `registerBody`, `loginBody`, `createAvatarBody`, `presignUploadBody` | zod wrappers. `parse()` throws `{status:400, code:'validation_error'}`. |
+| [\_lib/rate-limit.js](_lib/rate-limit.js) | `limits.*`, `clientIp` | Preset Upstash limiters. |
+| [\_lib/r2.js](_lib/r2.js) | `presignUpload`, `presignGet`, `headObject`, `deleteObject`, `publicUrl` | R2 / S3 ops. |
+| [\_lib/env.js](_lib/env.js) | `env`, `env.ISSUER`, `env.MCP_RESOURCE` | Env vars. Throws if required ones missing. |
+| [\_lib/avatars.js](_lib/avatars.js) | `stripOwnerFor`, avatar URL resolution | Hides R2 path prefixes from unauthenticated callers. |
---
@@ -73,11 +75,11 @@ Never `res.end(JSON.stringify(...))`. Never read/verify JWTs yourself. Never int
## Auth modes
-| Mode | Helper | When |
-|---|---|---|
-| Session cookie | `getSessionUser(req)` | Browser apps in [public/](../public/) — `credentials: 'include'` |
-| Bearer JWT (OAuth) | `authenticateBearer(extractBearer(req))` → `{ userId, scope, source: 'oauth', clientId }` | MCP clients, third-party apps |
-| Bearer API key | `authenticateBearer(...)` → `{ userId, scope, source: 'apikey', apiKeyId }` | Server-to-server from user scripts |
+| Mode | Helper | When |
+| ------------------ | ----------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
+| Session cookie | `getSessionUser(req)` | Browser apps in [public/](../public/) — `credentials: 'include'` |
+| Bearer JWT (OAuth) | `authenticateBearer(extractBearer(req))` → `{ userId, scope, source: 'oauth', clientId }` | MCP clients, third-party apps |
+| Bearer API key | `authenticateBearer(...)` → `{ userId, scope, source: 'apikey', apiKeyId }` | Server-to-server from user scripts |
**Scopes:** `avatars:read`, `avatars:write`, `avatars:delete`, `profile`, `offline_access`. Check via `hasScope(bearer.scope, 'avatars:write')`.
@@ -121,16 +123,16 @@ For public/unlisted avatars use `publicUrl(key)` (CDN-cached). For private, `pre
Use the named preset that matches the endpoint. Don't invent new ones inline.
```js
-limits.authIp(ip) // 30 / 10 min — login/register
-limits.registerIp(ip) // 5 / 1 h
-limits.oauthRegisterIp(ip) // 10 / 1 h — dynamic client reg
-limits.mcpUser(userId) // 1200 / 1 min
-limits.mcpIp(ip) // 600 / 1 min
-limits.mcpValidate(key) // 10 / 1 min
-limits.mcpInspect(key) // 30 / 1 min
-limits.mcpOptimize(key) // 10 / 1 min
-limits.oauthToken(clientId)// 120 / 1 min
-limits.upload(userId) // 60 / 1 h
+limits.authIp(ip); // 30 / 10 min — login/register
+limits.registerIp(ip); // 5 / 1 h
+limits.oauthRegisterIp(ip); // 10 / 1 h — dynamic client reg
+limits.mcpUser(userId); // 1200 / 1 min
+limits.mcpIp(ip); // 600 / 1 min
+limits.mcpValidate(key); // 10 / 1 min
+limits.mcpInspect(key); // 30 / 1 min
+limits.mcpOptimize(key); // 10 / 1 min
+limits.oauthToken(clientId); // 120 / 1 min
+limits.upload(userId); // 60 / 1 h
```
`clientIp(req)` reads `x-vercel-forwarded-for` → `x-real-ip` → socket.
@@ -149,7 +151,7 @@ When adding a tool: bump rate-limit bucket if heavy, declare scope via `hasScope
## OAuth provider
-We *issue* tokens (not consume). Endpoints:
+We _issue_ tokens (not consume). Endpoints:
- `/api/oauth/authorize` (GET consent render, POST consent submit) — PKCE S256 mandatory, no implicit/password grants
- `/api/oauth/token` — `authorization_code` + `refresh_token` grants → JWT access + opaque refresh
@@ -167,7 +169,7 @@ Token JWT: `{ sub, client_id, scope, aud, exp, iat, jti, kid: env.JWT_KID }`.
- Hand-rolled JWT / bearer extraction → use `authenticateBearer()`
- Inline SQL concat → always tagged-template `sql\`... ${x} ...\``
- `res.end(JSON.stringify(...))` → `json(res, ...)`
-- Instantiating a new `Pool` or `neon()` → import `sql` from [_lib/db.js](_lib/db.js)
+- Instantiating a new `Pool` or `neon()` → import `sql` from [\_lib/db.js](_lib/db.js)
- Missing rate-limit on public endpoint
- Hardcoded origins → `env.ISSUER` or `env.APP_ORIGIN`
- Registering a file in `avatars` without `headObject()` size check
diff --git a/api/_lib/accessories.js b/api/_lib/accessories.js
index 777c7fea1..162a57054 100644
--- a/api/_lib/accessories.js
+++ b/api/_lib/accessories.js
@@ -23,12 +23,14 @@ export function validateAppearance(appearance) {
if (!appearance) return null;
if (appearance.outfit !== undefined && appearance.outfit !== null) {
- if (typeof appearance.outfit !== 'string') return 'appearance.outfit must be a string or null';
+ if (typeof appearance.outfit !== 'string')
+ return 'appearance.outfit must be a string or null';
if (!isValidPresetId(appearance.outfit)) return `unknown preset id: ${appearance.outfit}`;
}
if (appearance.accessories !== undefined) {
- if (!Array.isArray(appearance.accessories)) return 'appearance.accessories must be an array';
+ if (!Array.isArray(appearance.accessories))
+ return 'appearance.accessories must be an array';
if (appearance.accessories.length > 8) return 'appearance.accessories max length is 8';
for (const id of appearance.accessories) {
if (typeof id !== 'string') return 'appearance.accessories entries must be strings';
diff --git a/api/_lib/agent-wallet.js b/api/_lib/agent-wallet.js
index bb49311cc..873c2a72b 100644
--- a/api/_lib/agent-wallet.js
+++ b/api/_lib/agent-wallet.js
@@ -5,7 +5,7 @@
import { webcrypto } from 'node:crypto';
import { env } from './env.js';
-const subtle = (globalThis.crypto?.subtle) || webcrypto.subtle;
+const subtle = globalThis.crypto?.subtle || webcrypto.subtle;
const randomBytes = (n) => {
const b = new Uint8Array(n);
(globalThis.crypto || webcrypto).getRandomValues(b);
@@ -18,7 +18,12 @@ async function deriveKey() {
const raw = new TextEncoder().encode(env.JWT_SECRET);
const base = await subtle.importKey('raw', raw, 'HKDF', false, ['deriveKey']);
return subtle.deriveKey(
- { name: 'HKDF', hash: 'SHA-256', salt: new TextEncoder().encode('agent-wallet-v1'), info: new Uint8Array(0) },
+ {
+ name: 'HKDF',
+ hash: 'SHA-256',
+ salt: new TextEncoder().encode('agent-wallet-v1'),
+ info: new Uint8Array(0),
+ },
base,
{ name: 'AES-GCM', length: 256 },
false,
diff --git a/api/_lib/auth.js b/api/_lib/auth.js
index 815fbf801..2d6113352 100644
--- a/api/_lib/auth.js
+++ b/api/_lib/auth.js
@@ -6,9 +6,9 @@ import { env } from './env.js';
import { sql } from './db.js';
import { randomToken, sha256, hmacSha256, constantTimeEquals } from './crypto.js';
-const ACCESS_TTL_SEC = 60 * 60; // 1h access tokens
-const REFRESH_TTL_SEC = 60 * 60 * 24 * 30; // 30d refresh tokens
-const SESSION_TTL_SEC = 60 * 60 * 24 * 30; // 30d browser sessions
+const ACCESS_TTL_SEC = 60 * 60; // 1h access tokens
+const REFRESH_TTL_SEC = 60 * 60 * 24 * 30; // 30d refresh tokens
+const SESSION_TTL_SEC = 60 * 60 * 24 * 30; // 30d browser sessions
// Lazy: env.JWT_SECRET throws if unset, so defer encoding until first use.
let _jwtKey;
@@ -75,7 +75,10 @@ export async function rotateRefreshToken({ oldSecret, clientId, narrowScope }) {
// Reuse detected — revoke whole chain for this user+client.
await sql`update oauth_refresh_tokens set revoked_at = now()
where user_id = ${row.user_id} and client_id = ${clientId} and revoked_at is null`;
- throw Object.assign(new Error('invalid_grant'), { status: 400, code: 'refresh_reuse_detected' });
+ throw Object.assign(new Error('invalid_grant'), {
+ status: 400,
+ code: 'refresh_reuse_detected',
+ });
}
if (new Date(row.expires_at) < new Date()) {
throw Object.assign(new Error('invalid_grant'), { status: 400, code: 'refresh_expired' });
@@ -84,7 +87,12 @@ export async function rotateRefreshToken({ oldSecret, clientId, narrowScope }) {
// subset). Without this, a caller could re-widen back to the full scope on
// the next rotation by omitting `scope`.
const effectiveScope = typeof narrowScope === 'function' ? narrowScope(row.scope) : row.scope;
- const next = await issueRefreshToken({ userId: row.user_id, clientId, scope: effectiveScope, resource: row.resource });
+ const next = await issueRefreshToken({
+ userId: row.user_id,
+ clientId,
+ scope: effectiveScope,
+ resource: row.resource,
+ });
await sql`update oauth_refresh_tokens set revoked_at = now(), replaced_by = ${next.id}, last_used_at = now()
where id = ${row.id}`;
return { next, userId: row.user_id, scope: effectiveScope, resource: row.resource };
@@ -106,8 +114,7 @@ const LEGACY_COOKIE = 'sid';
function readSessionCookie(req) {
const cookie = req.headers.cookie || '';
- const m = cookie.match(/(?:^|;\s*)__Host-sid=([^;]+)/)
- || cookie.match(/(?:^|;\s*)sid=([^;]+)/);
+ const m = cookie.match(/(?:^|;\s*)__Host-sid=([^;]+)/) || cookie.match(/(?:^|;\s*)sid=([^;]+)/);
return m ? decodeURIComponent(m[1]) : null;
}
@@ -178,7 +185,11 @@ export function isSameSiteOrigin(req) {
if (origin) return origin === env.APP_ORIGIN;
const referer = req.headers.referer;
if (!referer) return false;
- try { return new URL(referer).origin === env.APP_ORIGIN; } catch { return false; }
+ try {
+ return new URL(referer).origin === env.APP_ORIGIN;
+ } catch {
+ return false;
+ }
}
// ── bearer extraction (OAuth access tokens OR API keys) ─────────────────────
diff --git a/api/_lib/crypto.js b/api/_lib/crypto.js
index aa5a6b60b..a36531aa2 100644
--- a/api/_lib/crypto.js
+++ b/api/_lib/crypto.js
@@ -2,7 +2,7 @@
import { webcrypto } from 'node:crypto';
-const subtle = (globalThis.crypto?.subtle) || webcrypto.subtle;
+const subtle = globalThis.crypto?.subtle || webcrypto.subtle;
const randomBytes = (n) => {
const b = new Uint8Array(n);
(globalThis.crypto || webcrypto).getRandomValues(b);
diff --git a/api/_lib/db.js b/api/_lib/db.js
index 4faa466b5..0c89e4143 100644
--- a/api/_lib/db.js
+++ b/api/_lib/db.js
@@ -13,8 +13,12 @@ function getSql() {
return _sql;
}
export const sql = new Proxy(function () {}, {
- apply(_t, _this, args) { return getSql()(...args); },
- get(_t, prop) { return getSql()[prop]; },
+ apply(_t, _this, args) {
+ return getSql()(...args);
+ },
+ get(_t, prop) {
+ return getSql()[prop];
+ },
});
// Simple retry for transient network errors — Neon drops idle HTTPS quickly.
diff --git a/api/_lib/erc8004-chains.js b/api/_lib/erc8004-chains.js
index 6a4481afe..970a3b36f 100644
--- a/api/_lib/erc8004-chains.js
+++ b/api/_lib/erc8004-chains.js
@@ -15,28 +15,160 @@ export const IDENTITY_REGISTRY_TESTNET = '0x8004A818BFB912233c491871b3d84c89A494
* active chains are crawled first when the cron has a time budget.
*/
export const CHAINS = [
- { id: 8453, name: 'Base', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://basescan.org' },
- { id: 42161, name: 'Arbitrum One', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://arbiscan.io' },
- { id: 56, name: 'BNB Chain', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://bscscan.com' },
- { id: 1, name: 'Ethereum', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://etherscan.io' },
- { id: 10, name: 'Optimism', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://optimistic.etherscan.io' },
- { id: 137, name: 'Polygon', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://polygonscan.com' },
- { id: 43114, name: 'Avalanche', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://snowtrace.io' },
- { id: 100, name: 'Gnosis', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://gnosisscan.io' },
- { id: 250, name: 'Fantom', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://ftmscan.com' },
- { id: 42220, name: 'Celo', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://celoscan.io' },
- { id: 59144, name: 'Linea', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://lineascan.build' },
- { id: 534352, name: 'Scroll', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://scrollscan.com' },
- { id: 5000, name: 'Mantle', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://explorer.mantle.xyz' },
- { id: 324, name: 'zkSync Era', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://explorer.zksync.io' },
- { id: 1284, name: 'Moonbeam', testnet: false, registry: IDENTITY_REGISTRY_MAINNET, explorer: 'https://moonbeam.moonscan.io' },
- { id: 97, name: 'BSC Testnet', testnet: true, registry: IDENTITY_REGISTRY_TESTNET, explorer: 'https://testnet.bscscan.com' },
- { id: 84532, name: 'Base Sepolia', testnet: true, registry: IDENTITY_REGISTRY_TESTNET, explorer: 'https://sepolia.basescan.org' },
- { id: 421614, name: 'Arbitrum Sepolia', testnet: true, registry: IDENTITY_REGISTRY_TESTNET, explorer: 'https://sepolia.arbiscan.io' },
- { id: 11155111, name: 'Ethereum Sepolia', testnet: true, registry: IDENTITY_REGISTRY_TESTNET, explorer: 'https://sepolia.etherscan.io' },
- { id: 11155420, name: 'Optimism Sepolia', testnet: true, registry: IDENTITY_REGISTRY_TESTNET, explorer: 'https://sepolia-optimism.etherscan.io' },
- { id: 80002, name: 'Polygon Amoy', testnet: true, registry: IDENTITY_REGISTRY_TESTNET, explorer: 'https://amoy.polygonscan.com' },
- { id: 43113, name: 'Avalanche Fuji', testnet: true, registry: IDENTITY_REGISTRY_TESTNET, explorer: 'https://testnet.snowtrace.io' },
+ {
+ id: 8453,
+ name: 'Base',
+ testnet: false,
+ registry: IDENTITY_REGISTRY_MAINNET,
+ explorer: 'https://basescan.org',
+ },
+ {
+ id: 42161,
+ name: 'Arbitrum One',
+ testnet: false,
+ registry: IDENTITY_REGISTRY_MAINNET,
+ explorer: 'https://arbiscan.io',
+ },
+ {
+ id: 56,
+ name: 'BNB Chain',
+ testnet: false,
+ registry: IDENTITY_REGISTRY_MAINNET,
+ explorer: 'https://bscscan.com',
+ },
+ {
+ id: 1,
+ name: 'Ethereum',
+ testnet: false,
+ registry: IDENTITY_REGISTRY_MAINNET,
+ explorer: 'https://etherscan.io',
+ },
+ {
+ id: 10,
+ name: 'Optimism',
+ testnet: false,
+ registry: IDENTITY_REGISTRY_MAINNET,
+ explorer: 'https://optimistic.etherscan.io',
+ },
+ {
+ id: 137,
+ name: 'Polygon',
+ testnet: false,
+ registry: IDENTITY_REGISTRY_MAINNET,
+ explorer: 'https://polygonscan.com',
+ },
+ {
+ id: 43114,
+ name: 'Avalanche',
+ testnet: false,
+ registry: IDENTITY_REGISTRY_MAINNET,
+ explorer: 'https://snowtrace.io',
+ },
+ {
+ id: 100,
+ name: 'Gnosis',
+ testnet: false,
+ registry: IDENTITY_REGISTRY_MAINNET,
+ explorer: 'https://gnosisscan.io',
+ },
+ {
+ id: 250,
+ name: 'Fantom',
+ testnet: false,
+ registry: IDENTITY_REGISTRY_MAINNET,
+ explorer: 'https://ftmscan.com',
+ },
+ {
+ id: 42220,
+ name: 'Celo',
+ testnet: false,
+ registry: IDENTITY_REGISTRY_MAINNET,
+ explorer: 'https://celoscan.io',
+ },
+ {
+ id: 59144,
+ name: 'Linea',
+ testnet: false,
+ registry: IDENTITY_REGISTRY_MAINNET,
+ explorer: 'https://lineascan.build',
+ },
+ {
+ id: 534352,
+ name: 'Scroll',
+ testnet: false,
+ registry: IDENTITY_REGISTRY_MAINNET,
+ explorer: 'https://scrollscan.com',
+ },
+ {
+ id: 5000,
+ name: 'Mantle',
+ testnet: false,
+ registry: IDENTITY_REGISTRY_MAINNET,
+ explorer: 'https://explorer.mantle.xyz',
+ },
+ {
+ id: 324,
+ name: 'zkSync Era',
+ testnet: false,
+ registry: IDENTITY_REGISTRY_MAINNET,
+ explorer: 'https://explorer.zksync.io',
+ },
+ {
+ id: 1284,
+ name: 'Moonbeam',
+ testnet: false,
+ registry: IDENTITY_REGISTRY_MAINNET,
+ explorer: 'https://moonbeam.moonscan.io',
+ },
+ {
+ id: 97,
+ name: 'BSC Testnet',
+ testnet: true,
+ registry: IDENTITY_REGISTRY_TESTNET,
+ explorer: 'https://testnet.bscscan.com',
+ },
+ {
+ id: 84532,
+ name: 'Base Sepolia',
+ testnet: true,
+ registry: IDENTITY_REGISTRY_TESTNET,
+ explorer: 'https://sepolia.basescan.org',
+ },
+ {
+ id: 421614,
+ name: 'Arbitrum Sepolia',
+ testnet: true,
+ registry: IDENTITY_REGISTRY_TESTNET,
+ explorer: 'https://sepolia.arbiscan.io',
+ },
+ {
+ id: 11155111,
+ name: 'Ethereum Sepolia',
+ testnet: true,
+ registry: IDENTITY_REGISTRY_TESTNET,
+ explorer: 'https://sepolia.etherscan.io',
+ },
+ {
+ id: 11155420,
+ name: 'Optimism Sepolia',
+ testnet: true,
+ registry: IDENTITY_REGISTRY_TESTNET,
+ explorer: 'https://sepolia-optimism.etherscan.io',
+ },
+ {
+ id: 80002,
+ name: 'Polygon Amoy',
+ testnet: true,
+ registry: IDENTITY_REGISTRY_TESTNET,
+ explorer: 'https://amoy.polygonscan.com',
+ },
+ {
+ id: 43113,
+ name: 'Avalanche Fuji',
+ testnet: true,
+ registry: IDENTITY_REGISTRY_TESTNET,
+ explorer: 'https://testnet.snowtrace.io',
+ },
];
export const CHAIN_BY_ID = Object.fromEntries(CHAINS.map((c) => [c.id, c]));
diff --git a/api/_lib/fetch-model.js b/api/_lib/fetch-model.js
index 3f4d22daa..5a94ec34a 100644
--- a/api/_lib/fetch-model.js
+++ b/api/_lib/fetch-model.js
@@ -69,10 +69,16 @@ async function assertPublicHost(host) {
const addrs = Array.isArray(resolved) ? resolved : [resolved];
for (const { address, family } of addrs) {
if (family === 4 && isPrivateIPv4(address)) {
- throw new FetchModelError(`host resolves to private address: ${address}`, 'private_address');
+ throw new FetchModelError(
+ `host resolves to private address: ${address}`,
+ 'private_address',
+ );
}
if (family === 6 && isPrivateIPv6(address)) {
- throw new FetchModelError(`host resolves to private address: ${address}`, 'private_address');
+ throw new FetchModelError(
+ `host resolves to private address: ${address}`,
+ 'private_address',
+ );
}
}
}
diff --git a/api/_lib/http.js b/api/_lib/http.js
index c0d3bee33..dce51c4ef 100644
--- a/api/_lib/http.js
+++ b/api/_lib/http.js
@@ -69,7 +69,11 @@ function readBody(req, limit) {
});
}
-export function cors(req, res, { origins = null, methods = 'GET,POST,OPTIONS', credentials = false } = {}) {
+export function cors(
+ req,
+ res,
+ { origins = null, methods = 'GET,POST,OPTIONS', credentials = false } = {},
+) {
const origin = req.headers.origin;
if (origin && isAllowedOrigin(origin, origins)) {
res.setHeader('access-control-allow-origin', origin);
@@ -77,7 +81,10 @@ export function cors(req, res, { origins = null, methods = 'GET,POST,OPTIONS', c
if (credentials) res.setHeader('access-control-allow-credentials', 'true');
}
res.setHeader('access-control-allow-methods', methods);
- res.setHeader('access-control-allow-headers', 'authorization, content-type, mcp-session-id, mcp-protocol-version');
+ res.setHeader(
+ 'access-control-allow-headers',
+ 'authorization, content-type, mcp-session-id, mcp-protocol-version',
+ );
res.setHeader('access-control-max-age', '86400');
if (req.method === 'OPTIONS') {
res.statusCode = 204;
@@ -101,7 +108,12 @@ export function wrap(handler) {
const status = err.status || 500;
if (status >= 500) console.error('[api] unhandled', err);
if (!res.writableEnded) {
- error(res, status, err.code || (status >= 500 ? 'internal_error' : 'bad_request'), err.message || 'error');
+ error(
+ res,
+ status,
+ err.code || (status >= 500 ? 'internal_error' : 'bad_request'),
+ err.message || 'error',
+ );
}
}
};
diff --git a/api/_lib/model-inspect.js b/api/_lib/model-inspect.js
index 3299e6f52..37597b0f3 100644
--- a/api/_lib/model-inspect.js
+++ b/api/_lib/model-inspect.js
@@ -11,11 +11,7 @@ const GLB_MAGIC = 0x46546c67; // "glTF"
function isGLB(bytes) {
if (!bytes || bytes.byteLength < 4) return false;
- const view = new DataView(
- bytes.buffer,
- bytes.byteOffset,
- Math.min(4, bytes.byteLength),
- );
+ const view = new DataView(bytes.buffer, bytes.byteOffset, Math.min(4, bytes.byteLength));
return view.getUint32(0, true) === GLB_MAGIC;
}
@@ -158,13 +154,12 @@ export function suggestOptimizations(info) {
out.push({
id: 'meshopt',
severity: 'info',
- message: 'Meshopt compression can reduce vertex+index size with faster decode than Draco.',
+ message:
+ 'Meshopt compression can reduce vertex+index size with faster decode than Draco.',
});
}
- const bigTextures = info.textures.filter(
- (t) => Math.max(t.width, t.height) >= 4096,
- );
+ const bigTextures = info.textures.filter((t) => Math.max(t.width, t.height) >= 4096);
if (bigTextures.length > 0) {
out.push({
id: 'texture_oversized',
@@ -178,7 +173,8 @@ export function suggestOptimizations(info) {
out.push({
id: 'texture_basisu',
severity: 'info',
- message: 'Transcode PNG textures to KTX2 (Basis Universal) for GPU-direct upload and smaller download.',
+ message:
+ 'Transcode PNG textures to KTX2 (Basis Universal) for GPU-direct upload and smaller download.',
});
}
diff --git a/api/_lib/onchain.js b/api/_lib/onchain.js
index b79937fa4..9894549e6 100644
--- a/api/_lib/onchain.js
+++ b/api/_lib/onchain.js
@@ -25,30 +25,184 @@ const TESTNET = '0x8004A818BFB912233c491871b3d84c89A494BD9e';
// global edges; no API keys required.
export const SERVER_CHAIN_META = {
// Mainnets
- 1: { name: 'Ethereum', short: 'ETH', rpc: 'https://eth.llamarpc.com', explorer: 'https://etherscan.io', registry: MAINNET, testnet: false },
- 10: { name: 'Optimism', short: 'OP', rpc: 'https://mainnet.optimism.io', explorer: 'https://optimistic.etherscan.io', registry: MAINNET, testnet: false },
- 56: { name: 'BNB Chain', short: 'BSC', rpc: 'https://bsc-dataseed.bnbchain.org', explorer: 'https://bscscan.com', registry: MAINNET, testnet: false },
- 100: { name: 'Gnosis', short: 'GNO', rpc: 'https://rpc.gnosischain.com', explorer: 'https://gnosisscan.io', registry: MAINNET, testnet: false },
- 137: { name: 'Polygon', short: 'MATIC', rpc: 'https://polygon-rpc.com', explorer: 'https://polygonscan.com', registry: MAINNET, testnet: false },
- 250: { name: 'Fantom', short: 'FTM', rpc: 'https://rpc.ftm.tools', explorer: 'https://ftmscan.com', registry: MAINNET, testnet: false },
- 324: { name: 'zkSync Era', short: 'zkSync', rpc: 'https://mainnet.era.zksync.io', explorer: 'https://explorer.zksync.io', registry: MAINNET, testnet: false },
- 1284: { name: 'Moonbeam', short: 'GLMR', rpc: 'https://rpc.api.moonbeam.network', explorer: 'https://moonscan.io', registry: MAINNET, testnet: false },
- 5000: { name: 'Mantle', short: 'MNT', rpc: 'https://rpc.mantle.xyz', explorer: 'https://explorer.mantle.xyz', registry: MAINNET, testnet: false },
- 8453: { name: 'Base', short: 'BASE', rpc: 'https://mainnet.base.org', explorer: 'https://basescan.org', registry: MAINNET, testnet: false },
- 42161: { name: 'Arbitrum One', short: 'ARB', rpc: 'https://arb1.arbitrum.io/rpc', explorer: 'https://arbiscan.io', registry: MAINNET, testnet: false },
- 42220: { name: 'Celo', short: 'CELO', rpc: 'https://forno.celo.org', explorer: 'https://celoscan.io', registry: MAINNET, testnet: false },
- 43114: { name: 'Avalanche', short: 'AVAX', rpc: 'https://api.avax.network/ext/bc/C/rpc', explorer: 'https://snowtrace.io', registry: MAINNET, testnet: false },
- 59144: { name: 'Linea', short: 'LINEA', rpc: 'https://rpc.linea.build', explorer: 'https://lineascan.build', registry: MAINNET, testnet: false },
- 534352: { name: 'Scroll', short: 'SCR', rpc: 'https://rpc.scroll.io', explorer: 'https://scrollscan.com', registry: MAINNET, testnet: false },
+ 1: {
+ name: 'Ethereum',
+ short: 'ETH',
+ rpc: 'https://eth.llamarpc.com',
+ explorer: 'https://etherscan.io',
+ registry: MAINNET,
+ testnet: false,
+ },
+ 10: {
+ name: 'Optimism',
+ short: 'OP',
+ rpc: 'https://mainnet.optimism.io',
+ explorer: 'https://optimistic.etherscan.io',
+ registry: MAINNET,
+ testnet: false,
+ },
+ 56: {
+ name: 'BNB Chain',
+ short: 'BSC',
+ rpc: 'https://bsc-dataseed.bnbchain.org',
+ explorer: 'https://bscscan.com',
+ registry: MAINNET,
+ testnet: false,
+ },
+ 100: {
+ name: 'Gnosis',
+ short: 'GNO',
+ rpc: 'https://rpc.gnosischain.com',
+ explorer: 'https://gnosisscan.io',
+ registry: MAINNET,
+ testnet: false,
+ },
+ 137: {
+ name: 'Polygon',
+ short: 'MATIC',
+ rpc: 'https://polygon-rpc.com',
+ explorer: 'https://polygonscan.com',
+ registry: MAINNET,
+ testnet: false,
+ },
+ 250: {
+ name: 'Fantom',
+ short: 'FTM',
+ rpc: 'https://rpc.ftm.tools',
+ explorer: 'https://ftmscan.com',
+ registry: MAINNET,
+ testnet: false,
+ },
+ 324: {
+ name: 'zkSync Era',
+ short: 'zkSync',
+ rpc: 'https://mainnet.era.zksync.io',
+ explorer: 'https://explorer.zksync.io',
+ registry: MAINNET,
+ testnet: false,
+ },
+ 1284: {
+ name: 'Moonbeam',
+ short: 'GLMR',
+ rpc: 'https://rpc.api.moonbeam.network',
+ explorer: 'https://moonscan.io',
+ registry: MAINNET,
+ testnet: false,
+ },
+ 5000: {
+ name: 'Mantle',
+ short: 'MNT',
+ rpc: 'https://rpc.mantle.xyz',
+ explorer: 'https://explorer.mantle.xyz',
+ registry: MAINNET,
+ testnet: false,
+ },
+ 8453: {
+ name: 'Base',
+ short: 'BASE',
+ rpc: 'https://mainnet.base.org',
+ explorer: 'https://basescan.org',
+ registry: MAINNET,
+ testnet: false,
+ },
+ 42161: {
+ name: 'Arbitrum One',
+ short: 'ARB',
+ rpc: 'https://arb1.arbitrum.io/rpc',
+ explorer: 'https://arbiscan.io',
+ registry: MAINNET,
+ testnet: false,
+ },
+ 42220: {
+ name: 'Celo',
+ short: 'CELO',
+ rpc: 'https://forno.celo.org',
+ explorer: 'https://celoscan.io',
+ registry: MAINNET,
+ testnet: false,
+ },
+ 43114: {
+ name: 'Avalanche',
+ short: 'AVAX',
+ rpc: 'https://api.avax.network/ext/bc/C/rpc',
+ explorer: 'https://snowtrace.io',
+ registry: MAINNET,
+ testnet: false,
+ },
+ 59144: {
+ name: 'Linea',
+ short: 'LINEA',
+ rpc: 'https://rpc.linea.build',
+ explorer: 'https://lineascan.build',
+ registry: MAINNET,
+ testnet: false,
+ },
+ 534352: {
+ name: 'Scroll',
+ short: 'SCR',
+ rpc: 'https://rpc.scroll.io',
+ explorer: 'https://scrollscan.com',
+ registry: MAINNET,
+ testnet: false,
+ },
// Testnets
- 97: { name: 'BSC Testnet', short: 'tBSC', rpc: 'https://data-seed-prebsc-1-s1.bnbchain.org:8545', explorer: 'https://testnet.bscscan.com', registry: TESTNET, testnet: true },
- 11155111: { name: 'Ethereum Sepolia', short: 'SEP', rpc: 'https://rpc.sepolia.org', explorer: 'https://sepolia.etherscan.io', registry: TESTNET, testnet: true },
- 84532: { name: 'Base Sepolia', short: 'baseSep', rpc: 'https://sepolia.base.org', explorer: 'https://sepolia.basescan.org', registry: TESTNET, testnet: true },
- 421614: { name: 'Arbitrum Sepolia', short: 'arbSep', rpc: 'https://sepolia-rollup.arbitrum.io/rpc', explorer: 'https://sepolia.arbiscan.io', registry: TESTNET, testnet: true },
- 11155420: { name: 'Optimism Sepolia', short: 'opSep', rpc: 'https://sepolia.optimism.io', explorer: 'https://sepolia-optimism.etherscan.io', registry: TESTNET, testnet: true },
- 80002: { name: 'Polygon Amoy', short: 'Amoy', rpc: 'https://rpc-amoy.polygon.technology', explorer: 'https://amoy.polygonscan.com', registry: TESTNET, testnet: true },
- 43113: { name: 'Avalanche Fuji', short: 'Fuji', rpc: 'https://api.avax-test.network/ext/bc/C/rpc', explorer: 'https://testnet.snowtrace.io', registry: TESTNET, testnet: true },
+ 97: {
+ name: 'BSC Testnet',
+ short: 'tBSC',
+ rpc: 'https://data-seed-prebsc-1-s1.bnbchain.org:8545',
+ explorer: 'https://testnet.bscscan.com',
+ registry: TESTNET,
+ testnet: true,
+ },
+ 11155111: {
+ name: 'Ethereum Sepolia',
+ short: 'SEP',
+ rpc: 'https://rpc.sepolia.org',
+ explorer: 'https://sepolia.etherscan.io',
+ registry: TESTNET,
+ testnet: true,
+ },
+ 84532: {
+ name: 'Base Sepolia',
+ short: 'baseSep',
+ rpc: 'https://sepolia.base.org',
+ explorer: 'https://sepolia.basescan.org',
+ registry: TESTNET,
+ testnet: true,
+ },
+ 421614: {
+ name: 'Arbitrum Sepolia',
+ short: 'arbSep',
+ rpc: 'https://sepolia-rollup.arbitrum.io/rpc',
+ explorer: 'https://sepolia.arbiscan.io',
+ registry: TESTNET,
+ testnet: true,
+ },
+ 11155420: {
+ name: 'Optimism Sepolia',
+ short: 'opSep',
+ rpc: 'https://sepolia.optimism.io',
+ explorer: 'https://sepolia-optimism.etherscan.io',
+ registry: TESTNET,
+ testnet: true,
+ },
+ 80002: {
+ name: 'Polygon Amoy',
+ short: 'Amoy',
+ rpc: 'https://rpc-amoy.polygon.technology',
+ explorer: 'https://amoy.polygonscan.com',
+ registry: TESTNET,
+ testnet: true,
+ },
+ 43113: {
+ name: 'Avalanche Fuji',
+ short: 'Fuji',
+ rpc: 'https://api.avax-test.network/ext/bc/C/rpc',
+ explorer: 'https://testnet.snowtrace.io',
+ registry: TESTNET,
+ testnet: true,
+ },
};
const IPFS_GATEWAY = 'https://ipfs.io/ipfs/';
@@ -128,7 +282,10 @@ export async function resolveOnChainAgent({
try {
const [uri, owner] = await Promise.all([
_withTimeout(registry.tokenURI(idBig), timeoutMs),
- _withTimeout(registry.ownerOf(idBig).catch(() => null), timeoutMs),
+ _withTimeout(
+ registry.ownerOf(idBig).catch(() => null),
+ timeoutMs,
+ ),
]);
base.tokenURI = uri || null;
base.tokenURIResolved = uri ? resolveURI(uri) : null;
diff --git a/api/_lib/r2.js b/api/_lib/r2.js
index 66f8f8eb5..6f5801e76 100644
--- a/api/_lib/r2.js
+++ b/api/_lib/r2.js
@@ -1,6 +1,12 @@
// S3-compatible storage client (works with AWS S3, Cloudflare R2, Backblaze B2, etc.)
-import { S3Client, PutObjectCommand, GetObjectCommand, DeleteObjectCommand, HeadObjectCommand } from '@aws-sdk/client-s3';
+import {
+ S3Client,
+ PutObjectCommand,
+ GetObjectCommand,
+ DeleteObjectCommand,
+ HeadObjectCommand,
+} from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { env } from './env.js';
@@ -16,13 +22,23 @@ function getR2() {
accessKeyId: env.S3_ACCESS_KEY_ID,
secretAccessKey: env.S3_SECRET_ACCESS_KEY,
},
+ // AWS SDK v3 ≥ 3.730 adds CRC32 to every PutObject by default.
+ // Browsers can't compute/send that header, so presigned PUT URLs
+ // would be rejected by R2. Opt out until we add client-side CRC32.
+ requestChecksumCalculation: 'WHEN_REQUIRED',
+ responseChecksumValidation: 'WHEN_REQUIRED',
});
}
return _r2;
}
-export const r2 = new Proxy({}, {
- get(_t, prop) { return getR2()[prop]; },
-});
+export const r2 = new Proxy(
+ {},
+ {
+ get(_t, prop) {
+ return getR2()[prop];
+ },
+ },
+);
// Short-lived signed URL for direct browser upload (PUT).
export async function presignUpload({ key, contentType, contentLength, checksumSha256 }) {
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 4c49e403f..983af633d 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -95,7 +95,8 @@ export const limits = {
}).limit(agentId),
pinUser: (userId) => getLimiter('pin:user', { limit: 30, window: '1 h' }).limit(userId),
pinStatusIp: (ip) => getLimiter('pin:status:ip', { limit: 60, window: '1 m' }).limit(ip),
- agentByAddress: (ip) => getLimiter('agents:by-address', { limit: 120, window: '1 m' }).limit(ip),
+ agentByAddress: (ip) =>
+ getLimiter('agents:by-address', { limit: 120, window: '1 m' }).limit(ip),
walletLink: (userId) => getLimiter('wallet:link', { limit: 10, window: '10 m' }).limit(userId),
agentSuggest: (ip) => getLimiter('agents:suggest', { limit: 120, window: '1 m' }).limit(ip),
};
diff --git a/api/_lib/validate.js b/api/_lib/validate.js
index 5cc8ec934..fda30971d 100644
--- a/api/_lib/validate.js
+++ b/api/_lib/validate.js
@@ -17,10 +17,7 @@ export const avatarVisibility = z.enum(['private', 'unlisted', 'public']);
// Avatars are GLB/GLTF models. Lock the content-type allowlist here so both
// the presign URL and the stored object can only ever be model binaries —
// prevents an attacker uploading HTML/SVG to the public CDN for stored XSS.
-export const avatarContentType = z.enum([
- 'model/gltf-binary',
- 'model/gltf+json',
-]);
+export const avatarContentType = z.enum(['model/gltf-binary', 'model/gltf+json']);
export const username = z
.string()
@@ -55,20 +52,36 @@ export const createAvatarBody = z.object({
parent_avatar_id: z.string().uuid().optional(),
source_meta: z.record(z.any()).default({}),
content_type: avatarContentType.default('model/gltf-binary'),
- size_bytes: z.number().int().positive().max(500 * 1024 * 1024),
- checksum_sha256: z.string().regex(/^[a-f0-9]{64}$/).optional(),
+ size_bytes: z
+ .number()
+ .int()
+ .positive()
+ .max(500 * 1024 * 1024),
+ checksum_sha256: z
+ .string()
+ .regex(/^[a-f0-9]{64}$/)
+ .optional(),
});
export const presignUploadBody = z.object({
- size_bytes: z.number().int().positive().max(500 * 1024 * 1024),
+ size_bytes: z
+ .number()
+ .int()
+ .positive()
+ .max(500 * 1024 * 1024),
content_type: avatarContentType.default('model/gltf-binary'),
- checksum_sha256: z.string().regex(/^[a-f0-9]{64}$/).optional(),
+ checksum_sha256: z
+ .string()
+ .regex(/^[a-f0-9]{64}$/)
+ .optional(),
});
export function parse(schema, input) {
const res = schema.safeParse(input);
if (!res.success) {
- const err = new Error(res.error.issues.map((i) => `${i.path.join('.') || 'body'}: ${i.message}`).join('; '));
+ const err = new Error(
+ res.error.issues.map((i) => `${i.path.join('.') || 'body'}: ${i.message}`).join('; '),
+ );
err.status = 400;
err.code = 'validation_error';
throw err;
diff --git a/api/agent-actions.js b/api/agent-actions.js
index 595c53742..979e22d8c 100644
--- a/api/agent-actions.js
+++ b/api/agent-actions.js
@@ -10,14 +10,14 @@
*/
import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';
-import { sql } from './_lib/db.js';
+import { sql } from './_lib/db.js';
import { cors, json, method, readJson, wrap, error } from './_lib/http.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET', 'POST'])) return;
- if (req.method === 'GET') return handleList(req, res);
+ if (req.method === 'GET') return handleList(req, res);
return handleAppend(req, res);
});
@@ -27,10 +27,10 @@ async function handleList(req, res) {
const auth = await resolveAuth(req);
if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
- const url = new URL(req.url, 'http://x');
- const agentId = url.searchParams.get('agent_id');
- const limit = Math.min(Number(url.searchParams.get('limit')) || 50, 200);
- const cursor = url.searchParams.get('cursor'); // bigserial id cursor
+ const url = new URL(req.url, 'http://x');
+ const agentId = url.searchParams.get('agent_id');
+ const limit = Math.min(Number(url.searchParams.get('limit')) || 50, 200);
+ const cursor = url.searchParams.get('cursor'); // bigserial id cursor
if (!agentId) return error(res, 400, 'validation_error', 'agent_id is required');
@@ -39,8 +39,8 @@ async function handleList(req, res) {
SELECT user_id FROM agent_identities
WHERE id = ${agentId} AND deleted_at IS NULL
`;
- if (!agentRow) return error(res, 404, 'not_found', 'agent not found');
- if (agentRow.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
+ if (!agentRow) return error(res, 404, 'not_found', 'agent not found');
+ if (agentRow.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
const rows = cursor
? await sql`
@@ -56,8 +56,8 @@ async function handleList(req, res) {
LIMIT ${limit + 1}
`;
- const hasMore = rows.length > limit;
- const actions = hasMore ? rows.slice(0, limit) : rows;
+ const hasMore = rows.length > limit;
+ const actions = hasMore ? rows.slice(0, limit) : rows;
const nextCursor = hasMore ? String(actions[actions.length - 1].id) : null;
return json(res, 200, { actions: actions.map(decorate), next_cursor: nextCursor });
@@ -72,14 +72,14 @@ async function handleAppend(req, res) {
const body = await readJson(req);
if (!body.agent_id) return error(res, 400, 'validation_error', 'agent_id required');
- if (!body.type) return error(res, 400, 'validation_error', 'type required');
+ if (!body.type) return error(res, 400, 'validation_error', 'type required');
// Verify ownership
const [agentRow] = await sql`
SELECT user_id FROM agent_identities
WHERE id = ${body.agent_id} AND deleted_at IS NULL
`;
- if (!agentRow) return error(res, 404, 'not_found', 'agent not found');
+ if (!agentRow) return error(res, 404, 'not_found', 'agent not found');
if (agentRow.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
const [action] = await sql`
@@ -88,8 +88,8 @@ async function handleAppend(req, res) {
${body.agent_id},
${String(body.type).slice(0, 64)},
${JSON.stringify(body.payload || {})}::jsonb,
- ${body.source_skill || null},
- ${body.signature || null},
+ ${body.source_skill || null},
+ ${body.signature || null},
${body.signer_address || null}
)
RETURNING *
@@ -103,20 +103,20 @@ async function handleAppend(req, res) {
async function resolveAuth(req) {
const session = await getSessionUser(req);
if (session) return { userId: session.id };
- const bearer = await authenticateBearer(extractBearer(req));
- if (bearer) return { userId: bearer.userId };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
return null;
}
function decorate(row) {
return {
- id: String(row.id),
- agent_id: row.agent_id,
- type: row.type,
- payload: row.payload,
- source_skill: row.source_skill,
- signature: row.signature,
+ id: String(row.id),
+ agent_id: row.agent_id,
+ type: row.type,
+ payload: row.payload,
+ source_skill: row.source_skill,
+ signature: row.signature,
signer_address: row.signer_address,
- created_at: row.created_at,
+ created_at: row.created_at,
};
}
diff --git a/api/agent-memory.js b/api/agent-memory.js
index 427e63ef4..2956e6c1d 100644
--- a/api/agent-memory.js
+++ b/api/agent-memory.js
@@ -10,14 +10,14 @@
*/
import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';
-import { sql } from './_lib/db.js';
+import { sql } from './_lib/db.js';
import { cors, json, method, readJson, wrap, error } from './_lib/http.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;
- const url = new URL(req.url, 'http://x');
- const pathId = url.pathname.split('/').pop(); // /api/agent-memory/:id
+ const url = new URL(req.url, 'http://x');
+ const pathId = url.pathname.split('/').pop(); // /api/agent-memory/:id
// DELETE /api/agent-memory/:id
if (req.method === 'DELETE' && pathId && pathId !== 'agent-memory') {
@@ -25,7 +25,7 @@ export default wrap(async (req, res) => {
}
if (!method(req, res, ['GET', 'POST'])) return;
- if (req.method === 'GET') return handleList(req, res);
+ if (req.method === 'GET') return handleList(req, res);
return handleUpsert(req, res);
});
@@ -35,11 +35,11 @@ async function handleList(req, res) {
const auth = await resolveAuth(req);
if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
- const url = new URL(req.url, 'http://x');
+ const url = new URL(req.url, 'http://x');
const agentId = url.searchParams.get('agentId') || url.searchParams.get('agent_id');
- const type = url.searchParams.get('type');
- const since = Number(url.searchParams.get('since')) || 0;
- const limit = Math.min(Number(url.searchParams.get('limit')) || 200, 500);
+ const type = url.searchParams.get('type');
+ const since = Number(url.searchParams.get('since')) || 0;
+ const limit = Math.min(Number(url.searchParams.get('limit')) || 200, 500);
if (!agentId) return error(res, 400, 'validation_error', 'agentId required');
@@ -47,7 +47,7 @@ async function handleList(req, res) {
const [agentRow] = await sql`
SELECT user_id FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL
`;
- if (!agentRow) return error(res, 404, 'not_found', 'agent not found');
+ if (!agentRow) return error(res, 404, 'not_found', 'agent not found');
if (agentRow.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
const rows = type
@@ -78,22 +78,22 @@ async function handleUpsert(req, res) {
const auth = await resolveAuth(req);
if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
- const body = await readJson(req);
+ const body = await readJson(req);
const agentId = body.agentId || body.agent_id;
- const entry = body.entry;
+ const entry = body.entry;
if (!agentId) return error(res, 400, 'validation_error', 'agentId required');
- if (!entry) return error(res, 400, 'validation_error', 'entry required');
+ if (!entry) return error(res, 400, 'validation_error', 'entry required');
// Verify ownership
const [agentRow] = await sql`
SELECT user_id FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL
`;
- if (!agentRow) return error(res, 404, 'not_found', 'agent not found');
+ if (!agentRow) return error(res, 404, 'not_found', 'agent not found');
if (agentRow.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
const validTypes = ['user', 'feedback', 'project', 'reference'];
- const memType = validTypes.includes(entry.type) ? entry.type : 'project';
+ const memType = validTypes.includes(entry.type) ? entry.type : 'project';
// Upsert by id (idempotent — local storage may resync the same entry).
// The WHERE clause on ON CONFLICT is critical: IDs come from the client,
@@ -108,7 +108,7 @@ async function handleUpsert(req, res) {
${agentId},
${memType},
${String(entry.content || '').slice(0, 10000)},
- ${entry.tags || []},
+ ${entry.tags || []},
${JSON.stringify(entry.context || {})}::jsonb,
${entry.salience || 0.5},
${entry.createdAt ? new Date(entry.createdAt).toISOString() : new Date().toISOString()},
@@ -127,7 +127,7 @@ async function handleUpsert(req, res) {
${agentId},
${memType},
${String(entry.content || '').slice(0, 10000)},
- ${entry.tags || []},
+ ${entry.tags || []},
${JSON.stringify(entry.context || {})}::jsonb,
${entry.salience || 0.5},
${entry.expiresAt ? new Date(entry.expiresAt).toISOString() : null}
@@ -156,7 +156,7 @@ async function handleDelete(req, res, memoryId) {
WHERE m.id = ${memoryId}
`;
- if (!row) return error(res, 404, 'not_found', 'memory not found');
+ if (!row) return error(res, 404, 'not_found', 'memory not found');
if (row.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your memory');
await sql`DELETE FROM agent_memories WHERE id = ${memoryId}`;
@@ -168,21 +168,21 @@ async function handleDelete(req, res, memoryId) {
async function resolveAuth(req) {
const session = await getSessionUser(req);
if (session) return { userId: session.id };
- const bearer = await authenticateBearer(extractBearer(req));
- if (bearer) return { userId: bearer.userId };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
return null;
}
function decorateMemory(row) {
return {
- id: row.id,
- agent_id: row.agent_id,
- type: row.type,
- content: row.content,
- tags: row.tags || [],
- context: row.context || {},
- salience: row.salience,
- createdAt: row.created_at ? new Date(row.created_at).getTime() : Date.now(),
- expiresAt: row.expires_at ? new Date(row.expires_at).getTime() : null,
+ id: row.id,
+ agent_id: row.agent_id,
+ type: row.type,
+ content: row.content,
+ tags: row.tags || [],
+ context: row.context || {},
+ salience: row.salience,
+ createdAt: row.created_at ? new Date(row.created_at).getTime() : Date.now(),
+ expiresAt: row.expires_at ? new Date(row.expires_at).getTime() : null,
};
}
diff --git a/api/agent-oembed.js b/api/agent-oembed.js
index 13635783b..f21e14218 100644
--- a/api/agent-oembed.js
+++ b/api/agent-oembed.js
@@ -8,22 +8,22 @@
* Discord, etc.) can render the agent inline.
*/
-import { sql } from './_lib/db.js';
-import { env } from './_lib/env.js';
+import { sql } from './_lib/db.js';
+import { env } from './_lib/env.js';
import { cors, wrap, error } from './_lib/http.js';
import { resolveOnChainAgent, SERVER_CHAIN_META } from './_lib/onchain.js';
-const WIDTH = 420;
-const HEIGHT = 520;
-const THUMB_WIDTH = 1200;
+const WIDTH = 420;
+const HEIGHT = 520;
+const THUMB_WIDTH = 1200;
const THUMB_HEIGHT = 630;
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
- const url = new URL(req.url, 'http://x');
- const target = url.searchParams.get('url');
- const format = (url.searchParams.get('format') || 'json').toLowerCase();
+ const url = new URL(req.url, 'http://x');
+ const target = url.searchParams.get('url');
+ const format = (url.searchParams.get('format') || 'json').toLowerCase();
if (!target) return error(res, 400, 'invalid_request', 'url parameter required');
@@ -41,28 +41,28 @@ export default wrap(async (req, res) => {
`;
if (!agent) return error(res, 404, 'not_found', 'agent not found');
- const origin = env.APP_ORIGIN;
+ const origin = env.APP_ORIGIN;
const embedUrl = `${origin}/agent/${agent.id}/embed`;
const agentUrl = `${origin}/agent/${agent.id}`;
const thumbUrl = `${origin}/api/agent/${agent.id}/og`;
- const title = agent.name || 'Agent';
+ const title = agent.name || 'Agent';
const iframe = `<iframe src="${escapeAttr(embedUrl)}" width="${WIDTH}" height="${HEIGHT}" style="border:0;border-radius:12px" allow="autoplay; xr-spatial-tracking" sandbox="allow-scripts allow-same-origin allow-popups"></iframe>`;
const payload = {
- type: 'rich',
- version: '1.0',
- provider_name: '3D Agent',
- provider_url: origin,
+ type: 'rich',
+ version: '1.0',
+ provider_name: '3D Agent',
+ provider_url: origin,
title,
- author_name: title,
- author_url: agentUrl,
- html: iframe,
- width: WIDTH,
- height: HEIGHT,
- thumbnail_url: thumbUrl,
- thumbnail_width: THUMB_WIDTH,
- thumbnail_height: THUMB_HEIGHT,
+ author_name: title,
+ author_url: agentUrl,
+ html: iframe,
+ width: WIDTH,
+ height: HEIGHT,
+ thumbnail_url: thumbUrl,
+ thumbnail_width: THUMB_WIDTH,
+ thumbnail_height: THUMB_HEIGHT,
};
res.setHeader('cache-control', 'public, max-age=900');
@@ -81,11 +81,15 @@ export default wrap(async (req, res) => {
function extractAgentId(target) {
let parsed;
- try { parsed = new URL(target); } catch { return null; }
+ try {
+ parsed = new URL(target);
+ } catch {
+ return null;
+ }
const originStr = `${parsed.protocol}//${parsed.host}`;
- const okOrigin = originStr === env.APP_ORIGIN
- || /^https?:\/\/localhost(:\d+)?$/.test(originStr);
+ const okOrigin =
+ originStr === env.APP_ORIGIN || /^https?:\/\/localhost(:\d+)?$/.test(originStr);
if (!okOrigin) return null;
const match = parsed.pathname.match(/^\/agent\/([A-Za-z0-9_-]+)\/?$/);
@@ -94,11 +98,15 @@ function extractAgentId(target) {
function extractOnChain(target) {
let parsed;
- try { parsed = new URL(target); } catch { return null; }
+ try {
+ parsed = new URL(target);
+ } catch {
+ return null;
+ }
const originStr = `${parsed.protocol}//${parsed.host}`;
- const okOrigin = originStr === env.APP_ORIGIN
- || /^https?:\/\/localhost(:\d+)?$/.test(originStr);
+ const okOrigin =
+ originStr === env.APP_ORIGIN || /^https?:\/\/localhost(:\d+)?$/.test(originStr);
if (!okOrigin) return null;
const match = parsed.pathname.match(/^\/a\/(\d+)\/(\d+)\/?$/);
@@ -115,28 +123,28 @@ async function sendOnChain(res, format, { chainId, agentId }) {
return error(res, 404, 'not_found', `agent #${agentId} not found on chain ${chainId}`);
}
- const origin = env.APP_ORIGIN;
- const pageUrl = `${origin}/a/${chainId}/${agentId}`;
+ const origin = env.APP_ORIGIN;
+ const pageUrl = `${origin}/a/${chainId}/${agentId}`;
const embedUrl = `${origin}/a/${chainId}/${agentId}/embed`;
const thumbUrl = `${origin}/api/a-og?chain=${chainId}&id=${encodeURIComponent(agentId)}`;
- const title = agent.name || `Agent #${agentId}`;
+ const title = agent.name || `Agent #${agentId}`;
const iframe = `<iframe src="${escapeAttr(embedUrl)}" width="${WIDTH}" height="${HEIGHT}" style="border:0;border-radius:12px" allow="autoplay; xr-spatial-tracking" sandbox="allow-scripts allow-same-origin allow-popups"></iframe>`;
const payload = {
- type: 'rich',
- version: '1.0',
- provider_name: '3D Agent',
- provider_url: origin,
+ type: 'rich',
+ version: '1.0',
+ provider_name: '3D Agent',
+ provider_url: origin,
title,
- author_name: title,
- author_url: pageUrl,
- html: iframe,
- width: WIDTH,
- height: HEIGHT,
- thumbnail_url: thumbUrl,
- thumbnail_width: THUMB_WIDTH,
- thumbnail_height: THUMB_HEIGHT,
+ author_name: title,
+ author_url: pageUrl,
+ html: iframe,
+ width: WIDTH,
+ height: HEIGHT,
+ thumbnail_url: thumbUrl,
+ thumbnail_width: THUMB_WIDTH,
+ thumbnail_height: THUMB_HEIGHT,
};
res.setHeader('cache-control', 'public, max-age=900');
@@ -153,25 +161,23 @@ async function sendOnChain(res, format, { chainId, agentId }) {
}
function toXml(payload) {
- const lines = Object.entries(payload).map(([k, v]) =>
- ` <${k}>${escapeXml(String(v))}</${k}>`
- );
+ const lines = Object.entries(payload).map(([k, v]) => ` <${k}>${escapeXml(String(v))}</${k}>`);
return `<?xml version="1.0" encoding="utf-8" standalone="yes"?>\n<oembed>\n${lines.join('\n')}\n</oembed>`;
}
function escapeXml(s) {
return String(s)
- .replace(/&/g, '&amp;')
- .replace(/</g, '&lt;')
- .replace(/>/g, '&gt;')
- .replace(/"/g, '&quot;')
- .replace(/'/g, '&apos;');
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+ .replace(/'/g, '&apos;');
}
function escapeAttr(s) {
return String(s)
- .replace(/&/g, '&amp;')
- .replace(/"/g, '&quot;')
- .replace(/</g, '&lt;')
- .replace(/>/g, '&gt;');
+ .replace(/&/g, '&amp;')
+ .replace(/"/g, '&quot;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;');
}
diff --git a/api/agent-og.js b/api/agent-og.js
index b16be746e..db61f0e19 100644
--- a/api/agent-og.js
+++ b/api/agent-og.js
@@ -9,17 +9,17 @@
* pulling in canvas/imagemagick on the serverless side.
*/
-import { sql } from './_lib/db.js';
+import { sql } from './_lib/db.js';
import { getAvatar } from './_lib/avatars.js';
import { cors, wrap } from './_lib/http.js';
-const CACHE_CARD = 'public, max-age=3600, s-maxage=86400';
+const CACHE_CARD = 'public, max-age=3600, s-maxage=86400';
const CACHE_REDIR = 'public, max-age=3600';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
- const url = new URL(req.url, 'http://x');
+ const url = new URL(req.url, 'http://x');
const agentId = url.searchParams.get('id');
if (!agentId) return sendNotFound(res);
@@ -44,14 +44,14 @@ export default wrap(async (req, res) => {
}
sendCardSvg(res, 200, CACHE_CARD, {
- name: agent.name || 'Agent',
+ name: agent.name || 'Agent',
description: agent.description || 'An embodied 3D agent.',
});
});
function sendNotFound(res) {
sendCardSvg(res, 404, 'public, max-age=60', {
- name: 'Agent not found',
+ name: 'Agent not found',
description: '',
});
}
@@ -83,9 +83,9 @@ function truncate(s, n) {
function escapeXml(s) {
return String(s)
- .replace(/&/g, '&amp;')
- .replace(/</g, '&lt;')
- .replace(/>/g, '&gt;')
- .replace(/"/g, '&quot;')
- .replace(/'/g, '&apos;');
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+ .replace(/'/g, '&apos;');
}
diff --git a/api/agents.js b/api/agents.js
index 59893a11f..0b4904b2e 100644
--- a/api/agents.js
+++ b/api/agents.js
@@ -12,21 +12,26 @@
*/
import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';
-import { sql } from './_lib/db.js';
+import { sql } from './_lib/db.js';
import { cors, json, method, readJson, wrap, error } from './_lib/http.js';
import { generateAgentWallet } from './_lib/agent-wallet.js';
import { z } from 'zod';
const animationEntrySchema = z.object({
- name: z.string().trim().min(1).max(60),
- url: z.string().trim().min(1).max(2048).refine(
- (u) => /^(https?|ipfs|ar):\/\//.test(u) || u.startsWith('/'),
- 'url must be http, https, ipfs, ar, or a root-relative path',
- ),
- loop: z.boolean().default(true),
+ name: z.string().trim().min(1).max(60),
+ url: z
+ .string()
+ .trim()
+ .min(1)
+ .max(2048)
+ .refine(
+ (u) => /^(https?|ipfs|ar):\/\//.test(u) || u.startsWith('/'),
+ 'url must be http, https, ipfs, ar, or a root-relative path',
+ ),
+ loop: z.boolean().default(true),
clipName: z.string().trim().max(120).optional(),
- source: z.enum(['mixamo', 'preset', 'custom']),
- addedAt: z.string().optional(),
+ source: z.enum(['mixamo', 'preset', 'custom']),
+ addedAt: z.string().optional(),
});
const animationsSchema = z.array(animationEntrySchema).max(30);
@@ -42,9 +47,9 @@ export default wrap(async (req, res) => {
// ── List ───────────────────────────────────────────────────────────────────
async function handleList(req, res) {
- const url = new URL(req.url, 'http://x');
- const isMe = url.pathname.endsWith('/me');
- const auth = await resolveAuth(req);
+ const url = new URL(req.url, 'http://x');
+ const isMe = url.pathname.endsWith('/me');
+ const auth = await resolveAuth(req);
// /api/agents/me is the identity bootstrap endpoint — the client calls it
// on every page load, including for anonymous visitors. Return null instead
@@ -105,7 +110,7 @@ async function handleGetOrCreateMe(req, res, auth) {
// should not brick the client — surface null and let the UI fall back to
// local-only identity.
const code = err?.code || '';
- const msg = String(err?.message || '');
+ const msg = String(err?.message || '');
const missing = code === '42P01' || /relation.*does not exist/i.test(msg);
const warning = missing ? 'agents_table_missing' : 'agent_init_failed';
console.error(`[agents/me] ${warning}`, err);
@@ -120,7 +125,9 @@ async function handleCreate(req, res) {
if (!auth) return error(res, 401, 'unauthorized', 'sign in or provide a bearer token');
const body = await readJson(req);
- const name = String(body.name || 'Agent').trim().slice(0, 100);
+ const name = String(body.name || 'Agent')
+ .trim()
+ .slice(0, 100);
if (!name) return error(res, 400, 'validation_error', 'name is required');
@@ -150,7 +157,7 @@ export async function handleGetOne(req, res, id) {
if (!method(req, res, ['GET', 'PUT', 'PATCH', 'DELETE'])) return;
if (req.method === 'GET') {
- const auth = await resolveAuth(req);
+ const auth = await resolveAuth(req);
const [row] = await sql`
SELECT * FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL
`;
@@ -186,18 +193,18 @@ async function handleUpdate(req, res, id, auth) {
const [existing] = await sql`
SELECT id, user_id FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL
`;
- if (!existing) return error(res, 404, 'not_found', 'agent not found');
+ if (!existing) return error(res, 404, 'not_found', 'agent not found');
if (existing.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
const body = await readJson(req);
const [updated] = await sql`
UPDATE agent_identities SET
- name = COALESCE(${body.name || null}, name),
+ name = COALESCE(${body.name || null}, name),
description = COALESCE(${body.description || null}, description),
- avatar_id = COALESCE(${body.avatar_id || null}, avatar_id),
- skills = COALESCE(${body.skills || null}, skills),
- meta = COALESCE(${body.meta ? JSON.stringify(body.meta) : null}::jsonb, meta),
- home_url = COALESCE(${body.home_url || null}, home_url)
+ avatar_id = COALESCE(${body.avatar_id || null}, avatar_id),
+ skills = COALESCE(${body.skills || null}, skills),
+ meta = COALESCE(${body.meta ? JSON.stringify(body.meta) : null}::jsonb, meta),
+ home_url = COALESCE(${body.home_url || null}, home_url)
WHERE id = ${id}
RETURNING *
`;
@@ -216,7 +223,7 @@ async function handleDelete(req, res, id, auth) {
const [existing] = await sql`
SELECT id, user_id FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL
`;
- if (!existing) return error(res, 404, 'not_found', 'agent not found');
+ if (!existing) return error(res, 404, 'not_found', 'agent not found');
if (existing.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
await sql`UPDATE agent_identities SET deleted_at = now() WHERE id = ${id}`;
@@ -234,7 +241,7 @@ export async function handleWallet(req, res, id) {
const [existing] = await sql`
SELECT id, user_id FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL
`;
- if (!existing) return error(res, 404, 'not_found', 'agent not found');
+ if (!existing) return error(res, 404, 'not_found', 'agent not found');
if (existing.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
if (req.method === 'DELETE') {
@@ -247,9 +254,9 @@ export async function handleWallet(req, res, id) {
}
if (!method(req, res, ['POST'])) return;
- const body = await readJson(req);
+ const body = await readJson(req);
const address = String(body.wallet_address || '').trim();
- const chainId = Number(body.chain_id) || null;
+ const chainId = Number(body.chain_id) || null;
// Optional: post-mint, the client can patch in the minted ERC-8004 agent id.
const erc8004 = body.erc8004_agent_id != null ? BigInt(body.erc8004_agent_id).toString() : null;
if (!address) return error(res, 400, 'validation_error', 'wallet_address required');
@@ -271,7 +278,7 @@ async function resolveAuth(req) {
const session = await getSessionUser(req);
if (session) return { userId: session.id, source: 'session' };
const bearer = await authenticateBearer(extractBearer(req));
- if (bearer) return { userId: bearer.userId, source: 'bearer' };
+ if (bearer) return { userId: bearer.userId, source: 'bearer' };
return null;
}
@@ -281,23 +288,23 @@ function decorate(row, isOwner = true) {
delete meta.encrypted_wallet_key;
const base = {
- id: row.id,
- name: row.name,
- description: row.description,
- avatar_id: row.avatar_id,
- home_url: row.home_url || `/agent/${row.id}`,
- skills: row.skills || [],
+ id: row.id,
+ name: row.name,
+ description: row.description,
+ avatar_id: row.avatar_id,
+ home_url: row.home_url || `/agent/${row.id}`,
+ skills: row.skills || [],
meta,
is_registered: Boolean(row.erc8004_agent_id),
- created_at: row.created_at,
+ created_at: row.created_at,
};
if (isOwner) {
base.wallet_address = row.wallet_address;
- base.chain_id = row.chain_id;
- base.user_id = row.user_id;
- base.erc8004_agent_id = row.erc8004_agent_id;
- base.erc8004_registry = row.erc8004_registry;
- base.registration_cid = row.registration_cid;
+ base.chain_id = row.chain_id;
+ base.user_id = row.user_id;
+ base.erc8004_agent_id = row.erc8004_agent_id;
+ base.erc8004_registry = row.erc8004_registry;
+ base.registration_cid = row.registration_cid;
}
return base;
}
diff --git a/api/agents/REGISTER_FLOW.md b/api/agents/REGISTER_FLOW.md
index eced6ae71..ac3f7c00a 100644
--- a/api/agents/REGISTER_FLOW.md
+++ b/api/agents/REGISTER_FLOW.md
@@ -80,23 +80,25 @@ The server-side prep endpoint eliminates the need for users to manage IPFS pinni
**Rate limit:** `limits.authIp` (per-user, 30 per 10 min).
**Request body:**
+
```json
{
- "name": "Coach Leo",
- "description": "A football coach who reviews your form.",
- "avatarId": "<uuid of owned avatar>",
- "brain": {
- "provider": "anthropic",
- "model": "claude-opus-4-6",
- "instructions": "instructions.md"
- },
- "skills": ["wave", "dance"],
- "embedPolicy": {},
- "demoSlug": "coach-leo"
+ "name": "Coach Leo",
+ "description": "A football coach who reviews your form.",
+ "avatarId": "<uuid of owned avatar>",
+ "brain": {
+ "provider": "anthropic",
+ "model": "claude-opus-4-6",
+ "instructions": "instructions.md"
+ },
+ "skills": ["wave", "dance"],
+ "embedPolicy": {},
+ "demoSlug": "coach-leo"
}
```
**Validation:**
+
- `name`: 1–60 chars.
- `description`: ≤ 280 chars.
- `avatarId`: Must belong to the authed user (404 if not).
@@ -104,20 +106,23 @@ The server-side prep endpoint eliminates the need for users to manage IPFS pinni
- `brain`, `embedPolicy`, `demoSlug`: Optional.
**Response (200 OK):**
+
```json
{
- "ok": true,
- "cid": "bafkreigenerated...",
- "metadataURI": "ipfs://bafkreigenerated...",
- "prepId": "<uuid>"
+ "ok": true,
+ "cid": "bafkreigenerated...",
+ "metadataURI": "ipfs://bafkreigenerated...",
+ "prepId": "<uuid>"
}
```
**Pinning strategy:**
+
- If `WEB3_STORAGE_TOKEN` is set: pins to web3.storage, returns real CID.
- Otherwise: stores to R2, generates stub CID from content hash.
**Error responses:**
+
- 401: Not authenticated.
- 404: Avatar not found or doesn't belong to user.
- 429: Rate limited.
@@ -133,16 +138,18 @@ The server-side prep endpoint eliminates the need for users to manage IPFS pinni
**Rate limit:** `limits.authIp` (per-user, 30 per 10 min).
**Request body:**
+
```json
{
- "prepId": "<uuid from register-prep>",
- "chainId": 8453,
- "agentId": "1234",
- "txHash": "0x..."
+ "prepId": "<uuid from register-prep>",
+ "chainId": 8453,
+ "agentId": "1234",
+ "txHash": "0x..."
}
```
**Verification steps:**
+
1. Prep record exists, belongs to authed user, not expired (> now).
2. TX receipt fetched from the chain's RPC (status = 1, success).
3. Registered event parsed from logs.
@@ -150,18 +157,21 @@ The server-side prep endpoint eliminates the need for users to manage IPFS pinni
5. Agent record upserted to `agent_identities` table.
**Response (200 OK):**
+
```json
{
- "ok": true,
- "agentId": "<agent_identities.id>"
+ "ok": true,
+ "agentId": "<agent_identities.id>"
}
```
**Side effects:**
+
- Prep record is deleted (consumed), preventing reuse.
- Agent identity row is inserted or updated.
**Error responses:**
+
- 400: Chain unsupported, TX not found, TX failed, event parse failed, CID mismatch.
- 401: Not authenticated.
- 404: Prep not found or expired.
@@ -192,6 +202,7 @@ The server-side prep endpoint eliminates the need for users to manage IPFS pinni
### Database schema
**agent_registrations_pending:**
+
- `id` (uuid, PK)
- `user_id` (uuid, FK to users)
- `cid` (text) — IPFS CID
@@ -200,6 +211,7 @@ The server-side prep endpoint eliminates the need for users to manage IPFS pinni
- `created_at`, `expires_at` (timestamptz)
**agent_identities** (updated by confirm):
+
- `user_id`, `name`, `description`, `avatar_id`
- `chain_id`, `erc8004_agent_id`, `erc8004_registry`, `registration_cid`
diff --git a/api/agents/[id].js b/api/agents/[id].js
index bf09b96a4..976b5b215 100644
--- a/api/agents/[id].js
+++ b/api/agents/[id].js
@@ -6,10 +6,10 @@ import { handleGetOne, handleWallet } from '../agents.js';
import { cors, error, wrap } from '../_lib/http.js';
export default wrap(async function handler(req, res) {
- const url = new URL(req.url, 'http://x');
+ const url = new URL(req.url, 'http://x');
const parts = url.pathname.split('/').filter(Boolean);
// parts: ['api', 'agents', ':id'] or ['api', 'agents', ':id', 'wallet']
- const id = parts[2];
+ const id = parts[2];
const sub = parts[3];
if (!id) {
@@ -19,4 +19,4 @@ export default wrap(async function handler(req, res) {
if (sub === 'wallet') return handleWallet(req, res, id);
return handleGetOne(req, res, id);
-})
+});
diff --git a/api/agents/[id]/sign.js b/api/agents/[id]/sign.js
index 8dc016ef6..3c6962f9a 100644
--- a/api/agents/[id]/sign.js
+++ b/api/agents/[id]/sign.js
@@ -66,6 +66,6 @@ async function resolveAuth(req) {
const session = await getSessionUser(req);
if (session) return { userId: session.id };
const bearer = await authenticateBearer(extractBearer(req));
- if (bearer) return { userId: bearer.userId };
+ if (bearer) return { userId: bearer.userId };
return null;
}
diff --git a/api/agents/ens/[name].js b/api/agents/ens/[name].js
index e6944bedc..a16392123 100644
--- a/api/agents/ens/[name].js
+++ b/api/agents/ens/[name].js
@@ -93,7 +93,8 @@ export default wrap(async (req, res) => {
return error(res, 503, 'ens_error', 'ENS resolution failed');
}
- if (!resolved) return error(res, 404, 'not_found', `${name} does not resolve to an address`);
+ if (!resolved)
+ return error(res, 404, 'not_found', `${name} does not resolve to an address`);
address = resolved.toLowerCase();
setCached(name, address);
diff --git a/api/agents/register-confirm.js b/api/agents/register-confirm.js
index 46f445b51..8e34f5402 100644
--- a/api/agents/register-confirm.js
+++ b/api/agents/register-confirm.js
@@ -25,7 +25,8 @@ const bodySchema = z.object({
});
// ERC-721 Transfer event (emitted when token is minted)
-const REGISTERED_EVENT_ABI = 'event Registered(uint256 indexed agentId, string agentURI, address indexed owner)';
+const REGISTERED_EVENT_ABI =
+ 'event Registered(uint256 indexed agentId, string agentURI, address indexed owner)';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
@@ -76,7 +77,12 @@ export default wrap(async (req, res) => {
// Verify metadataURI matches prep record
if (agentURI !== prep.metadata_uri) {
- return error(res, 409, 'conflict', `metadata URI mismatch: expected ${prep.metadata_uri} got ${agentURI}`);
+ return error(
+ res,
+ 409,
+ 'conflict',
+ `metadata URI mismatch: expected ${prep.metadata_uri} got ${agentURI}`,
+ );
}
// Upsert agent_identities
@@ -156,10 +162,7 @@ function parseRegisteredEvent(logs, registryAddress) {
for (const log of logs) {
// Match registry address and Registered event topic
- if (
- getAddress(log.address) === registryAddr &&
- log.topics[0] === topic0
- ) {
+ if (getAddress(log.address) === registryAddr && log.topics[0] === topic0) {
// Decode the data field which contains the string agentURI
// For Registered(uint256 indexed agentId, string agentURI, address indexed owner),
// the data field contains (agentURI). The string is ABI-encoded as offset + length + data.
diff --git a/api/agents/register-prep.js b/api/agents/register-prep.js
index 8662990c7..9d7872a2a 100644
--- a/api/agents/register-prep.js
+++ b/api/agents/register-prep.js
@@ -24,12 +24,17 @@ const bodySchema = z.object({
name: z.string().trim().min(1).max(60),
description: z.string().trim().max(280),
avatarId: z.string().uuid(),
- brain: z.object({
- provider: z.string().optional(),
- model: z.string().optional(),
- instructions: z.string().optional(),
- }).optional(),
- skills: z.array(z.string().regex(/^[a-z0-9-]{1,40}$/i)).max(16).optional(),
+ brain: z
+ .object({
+ provider: z.string().optional(),
+ model: z.string().optional(),
+ instructions: z.string().optional(),
+ })
+ .optional(),
+ skills: z
+ .array(z.string().regex(/^[a-z0-9-]{1,40}$/i))
+ .max(16)
+ .optional(),
embedPolicy: z.record(z.any()).optional(),
demoSlug: z.string().optional(),
});
@@ -128,12 +133,14 @@ async function pinRegistrationJson(json) {
const stubCid = `bafkreigenerated${contentHash.slice(0, 40)}`; // mock bafk-prefixed CID
const key = `agent-registrations/${Date.now()}-${Math.random().toString(36).slice(2)}.json`;
- await r2.send(new PutObjectCommand({
- Bucket: env.S3_BUCKET,
- Key: key,
- Body: jsonBytes,
- ContentType: 'application/json',
- }));
+ await r2.send(
+ new PutObjectCommand({
+ Bucket: env.S3_BUCKET,
+ Key: key,
+ Body: jsonBytes,
+ ContentType: 'application/json',
+ }),
+ );
return { cid: stubCid, metadataURI: `ipfs://${stubCid}` };
}
diff --git a/api/animations/presign.js b/api/animations/presign.js
index b3d081238..f2a1f80d3 100644
--- a/api/animations/presign.js
+++ b/api/animations/presign.js
@@ -10,9 +10,16 @@ import { limits, clientIp } from '../_lib/rate-limit.js';
import { z } from 'zod';
const bodySchema = z.object({
- size_bytes: z.number().int().positive().max(100 * 1024 * 1024), // 100 MB cap for animation clips
+ size_bytes: z
+ .number()
+ .int()
+ .positive()
+ .max(100 * 1024 * 1024), // 100 MB cap for animation clips
content_type: z.enum(['model/gltf-binary', 'model/gltf+json']).default('model/gltf-binary'),
- checksum_sha256: z.string().regex(/^[a-f0-9]{64}$/).optional(),
+ checksum_sha256: z
+ .string()
+ .regex(/^[a-f0-9]{64}$/)
+ .optional(),
slug: z
.string()
.trim()
@@ -35,7 +42,9 @@ export default wrap(async (req, res) => {
const raw = await readJson(req);
const parsed = bodySchema.safeParse(raw);
if (!parsed.success) {
- const msg = parsed.error.issues.map((i) => `${i.path.join('.') || 'body'}: ${i.message}`).join('; ');
+ const msg = parsed.error.issues
+ .map((i) => `${i.path.join('.') || 'body'}: ${i.message}`)
+ .join('; ');
return error(res, 400, 'validation_error', msg);
}
const body = parsed.data;
diff --git a/api/auth/privy/verify.js b/api/auth/privy/verify.js
index d42d613ce..daf28f0b6 100644
--- a/api/auth/privy/verify.js
+++ b/api/auth/privy/verify.js
@@ -63,7 +63,12 @@ export default wrap(async (req, res) => {
}
if (!hasPrivyUserIdColumn) {
- return error(res, 501, 'schema_migration_required', 'user_wallets.privy_user_id column missing');
+ return error(
+ res,
+ 501,
+ 'schema_migration_required',
+ 'user_wallets.privy_user_id column missing',
+ );
}
// 4. Find or create the user and wallet.
diff --git a/api/auth/register.js b/api/auth/register.js
index 052c37cdb..7b3c6093c 100644
--- a/api/auth/register.js
+++ b/api/auth/register.js
@@ -23,7 +23,8 @@ export default wrap(async (req, res) => {
displayName = body.username;
password = body.password;
- const existing = await sql`select id from users where display_name ilike ${body.username} and deleted_at is null limit 1`;
+ const existing =
+ await sql`select id from users where display_name ilike ${body.username} and deleted_at is null limit 1`;
if (existing[0]) return error(res, 409, 'username_taken', 'that username is already taken');
} else {
const body = parse(registerBody, raw);
@@ -31,8 +32,10 @@ export default wrap(async (req, res) => {
displayName = body.display_name ?? null;
password = body.password;
- const existing = await sql`select id from users where email = ${email} and deleted_at is null limit 1`;
- if (existing[0]) return error(res, 409, 'email_taken', 'an account with this email already exists');
+ const existing =
+ await sql`select id from users where email = ${email} and deleted_at is null limit 1`;
+ if (existing[0])
+ return error(res, 409, 'email_taken', 'an account with this email already exists');
}
const hash = await hashPassword(password);
diff --git a/api/auth/session/list.js b/api/auth/session/list.js
index 5e89e709b..a0a8a0623 100644
--- a/api/auth/session/list.js
+++ b/api/auth/session/list.js
@@ -6,9 +6,7 @@ import { cors, json, error, method, wrap } from '../../_lib/http.js';
// Reads __Host-sid (or legacy sid) from the cookie header.
function readCookieToken(req) {
const cookie = req.headers.cookie || '';
- const m =
- cookie.match(/(?:^|;\s*)__Host-sid=([^;]+)/) ||
- cookie.match(/(?:^|;\s*)sid=([^;]+)/);
+ const m = cookie.match(/(?:^|;\s*)__Host-sid=([^;]+)/) || cookie.match(/(?:^|;\s*)sid=([^;]+)/);
return m ? decodeURIComponent(m[1]) : null;
}
diff --git a/api/auth/session/refresh.js b/api/auth/session/refresh.js
index fb277ff4b..e7e88f7c6 100644
--- a/api/auth/session/refresh.js
+++ b/api/auth/session/refresh.js
@@ -7,9 +7,7 @@ import { clientIp } from '../../_lib/rate-limit.js';
// Reads __Host-sid (or legacy sid) from the cookie header.
function readCookieToken(req) {
const cookie = req.headers.cookie || '';
- const m =
- cookie.match(/(?:^|;\s*)__Host-sid=([^;]+)/) ||
- cookie.match(/(?:^|;\s*)sid=([^;]+)/);
+ const m = cookie.match(/(?:^|;\s*)__Host-sid=([^;]+)/) || cookie.match(/(?:^|;\s*)sid=([^;]+)/);
return m ? decodeURIComponent(m[1]) : null;
}
diff --git a/api/auth/siwe/nonce.js b/api/auth/siwe/nonce.js
index 43c40c23f..1d1f85136 100644
--- a/api/auth/siwe/nonce.js
+++ b/api/auth/siwe/nonce.js
@@ -35,7 +35,10 @@ export default wrap(async (req, res) => {
// Issue a CSRF token tied to a temporary cookie (not session-based).
const csrfRaw = randomToken(32);
const csrf = await hmacSha256(env.JWT_SECRET, `csrf-siwe:${csrfRaw}`);
- res.setHeader('set-cookie', `${CSRF_COOKIE}=${csrfRaw}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${NONCE_TTL_SEC}`);
+ res.setHeader(
+ 'set-cookie',
+ `${CSRF_COOKIE}=${csrfRaw}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${NONCE_TTL_SEC}`,
+ );
const issuedAt = new Date().toISOString();
const expiresAt = new Date(Date.now() + NONCE_TTL_SEC * 1000).toISOString();
diff --git a/api/auth/siwe/verify.js b/api/auth/siwe/verify.js
index f6cb85ab0..d6e70ed93 100644
--- a/api/auth/siwe/verify.js
+++ b/api/auth/siwe/verify.js
@@ -12,7 +12,7 @@ import { parse } from '../../_lib/validate.js';
import { hmacSha256, constantTimeEquals } from '../../_lib/crypto.js';
const verifyBody = z.object({
- message: z.string().min(64).max(4000),
+ message: z.string().min(64).max(4000),
signature: z.string().regex(/^0x[a-fA-F0-9]+$/),
});
@@ -51,7 +51,7 @@ export default wrap(async (req, res) => {
// VERCEL_URL is the deployment-specific hostname Vercel injects automatically
// (e.g. "3dagent-git-main-moomsi.vercel.app") — allows preview deployments.
const appOrigin = env.APP_ORIGIN;
- const appHost = new URL(appOrigin).host;
+ const appHost = new URL(appOrigin).host;
const vercelHost = process.env.VERCEL_URL || null;
const allowedHosts = new Set([appHost, vercelHost].filter(Boolean));
if (!allowedHosts.has(fields.domain)) {
@@ -59,8 +59,11 @@ export default wrap(async (req, res) => {
}
try {
const u = new URL(fields.uri);
- const allowedOrigins = new Set([appOrigin, vercelHost ? `https://${vercelHost}` : null].filter(Boolean));
- if (!allowedOrigins.has(u.origin)) return error(res, 400, 'invalid_uri', 'uri origin mismatch');
+ const allowedOrigins = new Set(
+ [appOrigin, vercelHost ? `https://${vercelHost}` : null].filter(Boolean),
+ );
+ if (!allowedOrigins.has(u.origin))
+ return error(res, 400, 'invalid_uri', 'uri origin mismatch');
} catch {
return error(res, 400, 'invalid_uri', 'uri not a valid URL');
}
@@ -115,7 +118,7 @@ export default wrap(async (req, res) => {
// 6. Find or create user. Wallet address is the primary key into the user record.
const addrLower = claimed.toLowerCase();
- const chainId = fields.chainId || null;
+ const chainId = fields.chainId || null;
let [wallet] = await sql`
select user_id from user_wallets where address = ${addrLower} limit 1
@@ -187,14 +190,30 @@ function parseSiweMessage(msg) {
const key = kv[1].trim();
const val = kv[2].trim();
switch (key) {
- case 'URI': out.uri = val; break;
- case 'Version': out.version = val; break;
- case 'Chain ID': out.chainId = parseInt(val, 10) || null; break;
- case 'Nonce': out.nonce = val; break;
- case 'Issued At': out.issuedAt = val; break;
- case 'Expiration Time': out.expirationTime = val; break;
- case 'Not Before': out.notBefore = val; break;
- case 'Request ID': out.requestId = val; break;
+ case 'URI':
+ out.uri = val;
+ break;
+ case 'Version':
+ out.version = val;
+ break;
+ case 'Chain ID':
+ out.chainId = parseInt(val, 10) || null;
+ break;
+ case 'Nonce':
+ out.nonce = val;
+ break;
+ case 'Issued At':
+ out.issuedAt = val;
+ break;
+ case 'Expiration Time':
+ out.expirationTime = val;
+ break;
+ case 'Not Before':
+ out.notBefore = val;
+ break;
+ case 'Request ID':
+ out.requestId = val;
+ break;
}
}
if (!out.uri || !out.nonce || !out.version) return null;
diff --git a/api/avatars/REGENERATE.md b/api/avatars/REGENERATE.md
index 8ea85e7e6..a30c8bdba 100644
--- a/api/avatars/REGENERATE.md
+++ b/api/avatars/REGENERATE.md
@@ -11,29 +11,32 @@ Initiate an avatar regeneration job.
**Authentication:** Session cookie or `avatars:write` bearer token required.
**Request body:**
+
```json
{
- "sourceAvatarId": "avatar-uuid",
- "mode": "remesh|retex|rerig|restyle",
- "params": {
- "custom": "values"
- }
+ "sourceAvatarId": "avatar-uuid",
+ "mode": "remesh|retex|rerig|restyle",
+ "params": {
+ "custom": "values"
+ }
}
```
**Mode definitions:**
+
- `remesh` — regenerate mesh topology from source material or reference
- `retex` — regenerate textures and materials
- `rerig` — regenerate skeleton/rig bindings
- `restyle` — regenerate styling/appearance from description
**Success response (202):**
+
```json
{
- "ok": true,
- "jobId": "string",
- "status": "queued",
- "eta": null
+ "ok": true,
+ "jobId": "string",
+ "status": "queued",
+ "eta": null
}
```
@@ -41,12 +44,12 @@ Initiate an avatar regeneration job.
- **404 not_found** — source avatar not found or not owned
- **501 regen_unconfigured** — `AVATAR_REGEN_PROVIDER` env var not set
- ```json
- {
- "error": "regen_unconfigured",
- "error_description": "Avatar regeneration is not yet wired to an ML backend. Set AVATAR_REGEN_PROVIDER env var."
- }
- ```
+ ```json
+ {
+ "error": "regen_unconfigured",
+ "error_description": "Avatar regeneration is not yet wired to an ML backend. Set AVATAR_REGEN_PROVIDER env var."
+ }
+ ```
- **429 rate_limited** — user has exceeded upload quota
### `GET /api/avatars/regenerate-status?jobId=<id>`
@@ -56,20 +59,23 @@ Poll the status of a regeneration job.
**Authentication:** Session cookie or `avatars:read` bearer token required.
**Query parameters:**
+
- `jobId` (required) — job ID from regenerate endpoint
**Success response (200):**
+
```json
{
- "ok": true,
- "jobId": "string",
- "status": "queued|running|done|failed",
- "resultAvatarId": "avatar-uuid",
- "error": "optional error message"
+ "ok": true,
+ "jobId": "string",
+ "status": "queued|running|done|failed",
+ "resultAvatarId": "avatar-uuid",
+ "error": "optional error message"
}
```
**Status values:**
+
- `queued` — job waiting for processing
- `running` — actively processing
- `done` — completed successfully
@@ -84,50 +90,53 @@ Providers are swapped via the `AVATAR_REGEN_PROVIDER` env var (e.g., `meshy`, `c
```typescript
// Each provider exports an async factory function
export async function createRegenProvider(config) {
- return {
- // Accept regeneration request, return job handle
- submit: async (request) => {
- // request shape:
- // {
- // userId: string,
- // sourceAvatarId: string,
- // mode: 'remesh' | 'retex' | 'rerig' | 'restyle',
- // params: Record<string, unknown>,
- // sourceStorageKey: string, // R2 path to source GLB
- // }
-
- // return shape:
- // { jobId: string, eta?: number }
- return { jobId: 'ext-' + Date.now(), eta: 30 };
- },
-
- // Poll job status
- status: async (jobId) => {
- // return shape:
- // {
- // status: 'queued' | 'running' | 'done' | 'failed',
- // resultGlbUrl?: string, // temporary signed URL or CDN URL
- // textureUrls?: string[], // optional pre-resolved texture URLs
- // error?: string,
- // }
- return { status: 'done', resultGlbUrl: 'https://...' };
- },
- };
+ return {
+ // Accept regeneration request, return job handle
+ submit: async (request) => {
+ // request shape:
+ // {
+ // userId: string,
+ // sourceAvatarId: string,
+ // mode: 'remesh' | 'retex' | 'rerig' | 'restyle',
+ // params: Record<string, unknown>,
+ // sourceStorageKey: string, // R2 path to source GLB
+ // }
+
+ // return shape:
+ // { jobId: string, eta?: number }
+ return { jobId: 'ext-' + Date.now(), eta: 30 };
+ },
+
+ // Poll job status
+ status: async (jobId) => {
+ // return shape:
+ // {
+ // status: 'queued' | 'running' | 'done' | 'failed',
+ // resultGlbUrl?: string, // temporary signed URL or CDN URL
+ // textureUrls?: string[], // optional pre-resolved texture URLs
+ // error?: string,
+ // }
+ return { status: 'done', resultGlbUrl: 'https://...' };
+ },
+ };
}
```
### Output requirements
When `status` returns `done`:
+
- **resultGlbUrl** (required) — HTTP(S) URL to the regenerated GLB file. If temporary signed URL, provider must guarantee it stays valid for at least 24 hours.
- **textureUrls** (optional) — Array of HTTP(S) URLs to texture files if they differ from those embedded in the GLB.
Provider is responsible for:
+
1. Storing intermediate results (probably temporary S3 / R2 bucket)
2. Persisting temporary URLs long enough for the client to register the avatar
3. Handling cleanup of stale jobs after X days
The client will:
+
1. Fetch the GLB from `resultGlbUrl` and store it in `avatars` R2 bucket
2. Register the new avatar via `POST /api/avatars` with `parent_avatar_id = sourceAvatarId`
3. Delete or archive the old avatar (user decision)
@@ -136,13 +145,13 @@ The client will:
Research-stage notes (costs and integration effort unknown):
-| Provider | Specialization | Notes |
-| ---------- | ---------------------- | ----------------------------------------------------- |
-| **Meshy** | 3D generation | Text/image → mesh. API available; evaluate cost/time. |
-| **CSM** | Custom avatar builder | Photo → avatar. Avalready integrated for `POST /api/onboarding/avaturn-session`. |
-| **Rodin** | Avatar generation | Competitors of Meshy; check pricing. |
-| **TripoSR** | Text-to-3D models | Open-source model; would need self-hosted inference. |
-| **Kaedim** | Automated mesh cleanup | Specifically optimized remeshing for game assets. |
+| Provider | Specialization | Notes |
+| ----------- | ---------------------- | -------------------------------------------------------------------------------- |
+| **Meshy** | 3D generation | Text/image → mesh. API available; evaluate cost/time. |
+| **CSM** | Custom avatar builder | Photo → avatar. Avalready integrated for `POST /api/onboarding/avaturn-session`. |
+| **Rodin** | Avatar generation | Competitors of Meshy; check pricing. |
+| **TripoSR** | Text-to-3D models | Open-source model; would need self-hosted inference. |
+| **Kaedim** | Automated mesh cleanup | Specifically optimized remeshing for game assets. |
Picking a provider is a separate decision and out of scope for this contract. When chosen, create `api/_providers/<name>.js` implementing the shape above, then set `AVATAR_REGEN_PROVIDER=<name>` in Vercel env.
diff --git a/api/avatars/[id].js b/api/avatars/[id].js
index 7cc21e8e5..ab161bd1d 100644
--- a/api/avatars/[id].js
+++ b/api/avatars/[id].js
@@ -3,7 +3,13 @@
// DELETE /api/avatars/:id — soft-delete (owner only)
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
-import { getAvatar, updateAvatar, deleteAvatar, resolveAvatarUrl, stripOwnerFor } from '../_lib/avatars.js';
+import {
+ getAvatar,
+ updateAvatar,
+ deleteAvatar,
+ resolveAvatarUrl,
+ stripOwnerFor,
+} from '../_lib/avatars.js';
import { sql } from '../_lib/db.js';
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
import { headObject } from '../_lib/r2.js';
@@ -32,7 +38,13 @@ export default wrap(async (req, res) => {
const avatar = await getAvatar({ id, requesterId: auth?.userId });
if (!avatar) return error(res, 404, 'not_found', 'avatar not found');
const urlInfo = await resolveAvatarUrl(avatar);
- recordEvent({ userId: auth?.userId, clientId: auth?.clientId, apiKeyId: auth?.apiKeyId, avatarId: id, kind: 'avatar_fetch' });
+ recordEvent({
+ userId: auth?.userId,
+ clientId: auth?.clientId,
+ apiKeyId: auth?.apiKeyId,
+ avatarId: id,
+ kind: 'avatar_fetch',
+ });
return json(res, 200, { avatar: stripOwnerFor({ ...avatar, ...urlInfo }, auth?.userId) });
}
@@ -40,7 +52,8 @@ export default wrap(async (req, res) => {
if (req.method === 'PATCH') {
if (auth.source === 'oauth' || auth.source === 'apikey') {
- if (!hasScope(auth.scope, 'avatars:write')) return error(res, 403, 'insufficient_scope', 'avatars:write required');
+ if (!hasScope(auth.scope, 'avatars:write'))
+ return error(res, 403, 'insufficient_scope', 'avatars:write required');
}
const body = await readJson(req);
if (body && typeof body.glbUrl === 'string') {
@@ -54,7 +67,8 @@ export default wrap(async (req, res) => {
// DELETE
if (auth.source === 'oauth' || auth.source === 'apikey') {
- if (!hasScope(auth.scope, 'avatars:delete')) return error(res, 403, 'insufficient_scope', 'avatars:delete required');
+ if (!hasScope(auth.scope, 'avatars:delete'))
+ return error(res, 403, 'insufficient_scope', 'avatars:delete required');
}
const ok = await deleteAvatar({ id, userId: auth.userId });
if (!ok) return error(res, 404, 'not_found', 'avatar not found or not yours');
@@ -69,7 +83,12 @@ async function handleGlbPatch(res, auth, id, glbUrl) {
if (!rl.success) return error(res, 429, 'rate_limited', 'too many patch requests');
if (!/^u\/[^/]+\/.+\.glb$/.test(glbUrl)) {
- return error(res, 400, 'invalid_request', 'glbUrl must be a valid R2 storage key (u/{userId}/...)');
+ return error(
+ res,
+ 400,
+ 'invalid_request',
+ 'glbUrl must be a valid R2 storage key (u/{userId}/...)',
+ );
}
if (!glbUrl.startsWith(`u/${auth.userId}/`)) {
return error(res, 403, 'forbidden', 'key does not belong to your storage namespace');
@@ -81,13 +100,20 @@ async function handleGlbPatch(res, auth, id, glbUrl) {
return error(res, 413, 'payload_too_large', 'glb exceeds 25 MB limit');
}
if (!VALID_GLB_TYPES.has(head.ContentType)) {
- return error(res, 415, 'unsupported_media_type', 'content-type must be model/gltf-binary or application/octet-stream');
+ return error(
+ res,
+ 415,
+ 'unsupported_media_type',
+ 'content-type must be model/gltf-binary or application/octet-stream',
+ );
}
- const rows = await sql`select id, owner_id from avatars where id = ${id} and deleted_at is null limit 1`;
+ const rows =
+ await sql`select id, owner_id from avatars where id = ${id} and deleted_at is null limit 1`;
const avatar = rows[0];
if (!avatar) return error(res, 404, 'not_found', 'avatar not found');
- if (avatar.owner_id !== auth.userId) return error(res, 403, 'forbidden', 'you do not own this avatar');
+ if (avatar.owner_id !== auth.userId)
+ return error(res, 403, 'forbidden', 'you do not own this avatar');
try {
await sql`insert into avatar_versions (avatar_id, storage_key, created_by) values (${id}, ${glbUrl}, ${auth.userId})`;
@@ -107,13 +133,22 @@ async function handleGlbPatch(res, auth, id, glbUrl) {
return json(res, 200, {
ok: true,
- avatar: { id: updated.id, currentGlbUrl: updated.storage_key, updatedAt: updated.updated_at },
+ avatar: {
+ id: updated.id,
+ currentGlbUrl: updated.storage_key,
+ updatedAt: updated.updated_at,
+ },
});
}
async function resolveAuth(req) {
const session = await getSessionUser(req);
- if (session) return { userId: session.id, source: 'session', scope: 'avatars:read avatars:write avatars:delete' };
+ if (session)
+ return {
+ userId: session.id,
+ source: 'session',
+ scope: 'avatars:read avatars:write avatars:delete',
+ };
const bearer = await authenticateBearer(extractBearer(req));
return bearer;
}
diff --git a/api/avatars/[id]/session.js b/api/avatars/[id]/session.js
index 548e0d20b..b069e17aa 100644
--- a/api/avatars/[id]/session.js
+++ b/api/avatars/[id]/session.js
@@ -38,7 +38,12 @@ export default wrap(async (req, res) => {
}
if (!env.AVATURN_API_KEY) {
- return error(res, 501, 'not_configured', 'Avaturn is not configured on this deployment. Set AVATURN_API_KEY.');
+ return error(
+ res,
+ 501,
+ 'not_configured',
+ 'Avaturn is not configured on this deployment. Set AVATURN_API_KEY.',
+ );
}
// Resolve a time-limited URL the Avaturn upstream can fetch (works for private too).
diff --git a/api/avatars/presign.js b/api/avatars/presign.js
index 16badd1e3..9a71efa88 100644
--- a/api/avatars/presign.js
+++ b/api/avatars/presign.js
@@ -20,7 +20,9 @@ export default wrap(async (req, res) => {
const body = parse(presignUploadBody, await readJson(req));
const bodyAny = body;
- const slug = bodyAny.slug ? slugSchema.parse(bodyAny.slug) : `draft-${Math.random().toString(36).slice(2, 8)}`;
+ const slug = bodyAny.slug
+ ? slugSchema.parse(bodyAny.slug)
+ : `draft-${Math.random().toString(36).slice(2, 8)}`;
const key = storageKeyFor({ userId, slug });
const url = await presignUpload({
diff --git a/api/chat.js b/api/chat.js
index ef2594a8e..8a72c7ef5 100644
--- a/api/chat.js
+++ b/api/chat.js
@@ -18,52 +18,76 @@ const DEFAULT_MODEL = 'claude-sonnet-4-6';
const DEFAULT_MAX_TOKENS = 1024;
const HARD_MAX_TOKENS = 4096;
-const contextSchema = z.object({
- modelName: z.string().max(200).optional(),
- vertices: z.number().int().nonnegative().optional(),
- triangles: z.number().int().nonnegative().optional(),
- materials: z.number().int().nonnegative().optional(),
- animations: z.number().int().nonnegative().optional(),
- validationErrors: z.number().int().nonnegative().optional(),
- validationWarnings: z.number().int().nonnegative().optional(),
- currentEnvironment: z.string().max(80).optional(),
- wireframe: z.boolean().optional(),
- skeleton: z.boolean().optional(),
- grid: z.boolean().optional(),
- autoRotate: z.boolean().optional(),
- transparentBg: z.boolean().optional(),
- bgColor: z.string().max(20).optional(),
-}).partial().default({});
+const contextSchema = z
+ .object({
+ modelName: z.string().max(200).optional(),
+ vertices: z.number().int().nonnegative().optional(),
+ triangles: z.number().int().nonnegative().optional(),
+ materials: z.number().int().nonnegative().optional(),
+ animations: z.number().int().nonnegative().optional(),
+ validationErrors: z.number().int().nonnegative().optional(),
+ validationWarnings: z.number().int().nonnegative().optional(),
+ currentEnvironment: z.string().max(80).optional(),
+ wireframe: z.boolean().optional(),
+ skeleton: z.boolean().optional(),
+ grid: z.boolean().optional(),
+ autoRotate: z.boolean().optional(),
+ transparentBg: z.boolean().optional(),
+ bgColor: z.string().max(20).optional(),
+ })
+ .partial()
+ .default({});
const chatBody = z.object({
message: z.string().trim().min(1).max(4000),
context: contextSchema,
- history: z.array(z.object({
- role: z.enum(['user', 'assistant']),
- content: z.string().min(1).max(4000),
- })).max(20).default([]),
+ history: z
+ .array(
+ z.object({
+ role: z.enum(['user', 'assistant']),
+ content: z.string().min(1).max(4000),
+ }),
+ )
+ .max(20)
+ .default([]),
});
const ACTION_TOOLS = [
{
name: 'setWireframe',
description: 'Toggle wireframe mode on the currently loaded model.',
- input_schema: { type: 'object', properties: { value: { type: 'boolean' } }, required: ['value'] },
+ input_schema: {
+ type: 'object',
+ properties: { value: { type: 'boolean' } },
+ required: ['value'],
+ },
},
{
name: 'setSkeleton',
description: 'Toggle the skeleton helper visualization for rigged models.',
- input_schema: { type: 'object', properties: { value: { type: 'boolean' } }, required: ['value'] },
+ input_schema: {
+ type: 'object',
+ properties: { value: { type: 'boolean' } },
+ required: ['value'],
+ },
},
{
name: 'setGrid',
description: 'Toggle the reference grid and axes helper.',
- input_schema: { type: 'object', properties: { value: { type: 'boolean' } }, required: ['value'] },
+ input_schema: {
+ type: 'object',
+ properties: { value: { type: 'boolean' } },
+ required: ['value'],
+ },
},
{
name: 'setAutoRotate',
description: 'Toggle auto-rotation of the camera around the model.',
- input_schema: { type: 'object', properties: { value: { type: 'boolean' } }, required: ['value'] },
+ input_schema: {
+ type: 'object',
+ properties: { value: { type: 'boolean' } },
+ required: ['value'],
+ },
},
{
name: 'setBgColor',
@@ -77,12 +101,21 @@ const ACTION_TOOLS = [
{
name: 'setTransparentBg',
description: 'Toggle transparent background (for compositing screenshots).',
- input_schema: { type: 'object', properties: { value: { type: 'boolean' } }, required: ['value'] },
+ input_schema: {
+ type: 'object',
+ properties: { value: { type: 'boolean' } },
+ required: ['value'],
+ },
},
{
name: 'setEnvironment',
- description: 'Change the HDRI lighting environment. Known names: "None", "Neutral", "Venice Sunset", "Footprint Court (HDR Labs)".',
- input_schema: { type: 'object', properties: { value: { type: 'string' } }, required: ['value'] },
+ description:
+ 'Change the HDRI lighting environment. Known names: "None", "Neutral", "Venice Sunset", "Footprint Court (HDR Labs)".',
+ input_schema: {
+ type: 'object',
+ properties: { value: { type: 'string' } },
+ required: ['value'],
+ },
},
{
name: 'takeScreenshot',
@@ -100,7 +133,8 @@ const ACTION_TOOLS = [
},
{
name: 'runValidation',
- description: 'Run glTF validation on the currently loaded model and report errors/warnings.',
+ description:
+ 'Run glTF validation on the currently loaded model and report errors/warnings.',
input_schema: { type: 'object', properties: {} },
},
{
@@ -128,7 +162,9 @@ export default wrap(async (req, res) => {
if (!rl.success) {
const retryAfter = Math.max(1, Math.ceil((rl.reset - Date.now()) / 1000));
res.setHeader('retry-after', String(retryAfter));
- return error(res, 429, 'rate_limited', 'too many messages — slow down', { retry_after: retryAfter });
+ return error(res, 429, 'rate_limited', 'too many messages — slow down', {
+ retry_after: retryAfter,
+ });
}
const body = parse(chatBody, await readJson(req));
@@ -150,16 +186,16 @@ export default wrap(async (req, res) => {
upstream = await fetch(ANTHROPIC_URL, {
method: 'POST',
headers: {
- 'x-api-key': apiKey,
+ 'x-api-key': apiKey,
'anthropic-version': '2023-06-01',
- 'content-type': 'application/json',
+ 'content-type': 'application/json',
},
body: JSON.stringify({
model,
max_tokens: maxTokens,
- system: buildSystemPrompt(body.context),
+ system: buildSystemPrompt(body.context),
messages,
- tools: ACTION_TOOLS,
+ tools: ACTION_TOOLS,
}),
});
} catch (err) {
@@ -179,17 +215,17 @@ export default wrap(async (req, res) => {
const latencyMs = Date.now() - started;
recordEvent({
- userId: auth.userId,
+ userId: auth.userId,
apiKeyId: auth.apiKeyId,
clientId: auth.clientId,
- kind: 'chat',
- tool: model,
+ kind: 'chat',
+ tool: model,
latencyMs,
meta: {
- input_tokens: data.usage?.input_tokens,
+ input_tokens: data.usage?.input_tokens,
output_tokens: data.usage?.output_tokens,
- actions: actions.map((a) => a.type),
- has_context: Boolean(body.context?.modelName),
+ actions: actions.map((a) => a.type),
+ has_context: Boolean(body.context?.modelName),
},
});
@@ -200,9 +236,10 @@ function buildSystemPrompt(ctx = {}) {
const loaded = ctx.modelName
? `A model named "${ctx.modelName}" is loaded. Stats: ${fmt(ctx.vertices)} vertices, ${fmt(ctx.triangles)} triangles, ${fmt(ctx.materials)} materials, ${ctx.animations ?? 0} animations.`
: 'No model is currently loaded in the viewer.';
- const validation = ctx.validationErrors != null
- ? `Validation has been run: ${ctx.validationErrors} errors, ${ctx.validationWarnings ?? 0} warnings.`
- : 'glTF validation has not been run yet for this model.';
+ const validation =
+ ctx.validationErrors != null
+ ? `Validation has been run: ${ctx.validationErrors} errors, ${ctx.validationWarnings ?? 0} warnings.`
+ : 'glTF validation has not been run yet for this model.';
const settings = `Viewer settings — wireframe:${fmtBool(ctx.wireframe)}, skeleton:${fmtBool(ctx.skeleton)}, grid:${fmtBool(ctx.grid)}, autoRotate:${fmtBool(ctx.autoRotate)}, transparentBg:${fmtBool(ctx.transparentBg)}, bgColor:${ctx.bgColor || '?'}, environment:${ctx.currentEnvironment || '?'}.`;
return [
@@ -239,6 +276,12 @@ async function resolveAuth(req) {
return null;
}
-function fmt(n) { return typeof n === 'number' ? n.toLocaleString('en-US') : '?'; }
-function fmtBool(v) { return typeof v === 'boolean' ? (v ? 'on' : 'off') : '?'; }
-function clampInt(n, min, max) { return Math.min(max, Math.max(min, n)); }
+function fmt(n) {
+ return typeof n === 'number' ? n.toLocaleString('en-US') : '?';
+}
+function fmtBool(v) {
+ return typeof v === 'boolean' ? (v ? 'on' : 'off') : '?';
+}
+function clampInt(n, min, max) {
+ return Math.min(max, Math.max(min, n));
+}
diff --git a/api/cron/erc8004-crawl.js b/api/cron/erc8004-crawl.js
index d21dc4aef..994dbe4de 100644
--- a/api/cron/erc8004-crawl.js
+++ b/api/cron/erc8004-crawl.js
@@ -100,7 +100,9 @@ async function crawlChain(chain) {
return { inserted: 0, lastBlock: fromBlock - 1, fromBlock };
}
if (body.status !== '1' || !Array.isArray(body.result)) {
- throw new Error(`etherscan ${chain.id}: ${body.message || 'unknown'} — ${String(body.result).slice(0, 120)}`);
+ throw new Error(
+ `etherscan ${chain.id}: ${body.message || 'unknown'} — ${String(body.result).slice(0, 120)}`,
+ );
}
let lastBlock = fromBlock - 1;
diff --git a/api/erc8004/pin.js b/api/erc8004/pin.js
index 553abfe33..3670c921c 100644
--- a/api/erc8004/pin.js
+++ b/api/erc8004/pin.js
@@ -28,8 +28,9 @@ export default wrap(async (req, res) => {
const rl = await limits.authIp(ip);
if (!rl.success) return error(res, 429, 'rate_limited', 'too many uploads');
- const ct = (req.headers['content-type'] || 'application/octet-stream').split(';')[0].trim();
- if (!ALLOWED.has(ct)) return error(res, 415, 'unsupported_media_type', 'unsupported content-type');
+ const ct = (req.headers['content-type'] || 'application/octet-stream').split(';')[0].trim();
+ if (!ALLOWED.has(ct))
+ return error(res, 415, 'unsupported_media_type', 'unsupported content-type');
const body = await readRaw(req, MAX_SIZE);
@@ -52,12 +53,14 @@ export default wrap(async (req, res) => {
// Fallback to R2 with warning
const key = `erc8004/${Date.now()}-${Math.random().toString(36).slice(2)}.${ext}`;
- await r2.send(new PutObjectCommand({
- Bucket: env.S3_BUCKET,
- Key: key,
- Body: body,
- ContentType: ct,
- }));
+ await r2.send(
+ new PutObjectCommand({
+ Bucket: env.S3_BUCKET,
+ Key: key,
+ Body: body,
+ ContentType: ct,
+ }),
+ );
const url = publicUrl(key);
return json(res, 200, {
@@ -70,12 +73,18 @@ export default wrap(async (req, res) => {
function getExt(ct) {
switch (ct) {
- case 'application/json': return 'json';
- case 'model/gltf-binary': return 'glb';
- case 'image/png': return 'png';
- case 'image/jpeg': return 'jpg';
- case 'image/webp': return 'webp';
- default: return 'bin';
+ case 'application/json':
+ return 'json';
+ case 'model/gltf-binary':
+ return 'glb';
+ case 'image/png':
+ return 'png';
+ case 'image/jpeg':
+ return 'jpg';
+ case 'image/webp':
+ return 'webp';
+ default:
+ return 'bin';
}
}
@@ -88,7 +97,7 @@ async function uploadToWeb3Storage(token, ext, body, ct) {
const response = await fetch('https://api.web3.storage/upload', {
method: 'POST',
headers: {
- 'Authorization': `Bearer ${token}`,
+ Authorization: `Bearer ${token}`,
},
body: formData,
});
@@ -117,7 +126,7 @@ async function uploadToNftStorage(token, ext, body, ct) {
const response = await fetch('https://api.nft.storage/upload', {
method: 'POST',
headers: {
- 'Authorization': `Bearer ${token}`,
+ Authorization: `Bearer ${token}`,
},
body: formData,
});
diff --git a/api/explore.js b/api/explore.js
index 5d7ebe697..caf47ce2a 100644
--- a/api/explore.js
+++ b/api/explore.js
@@ -70,9 +70,7 @@ export default wrap(async (req, res) => {
registeredAt: r.registered_at,
tokenExplorerUrl: tokenExplorerUrl(r.chain_id, r.agent_id),
ownerExplorerUrl: addressExplorerUrl(r.chain_id, r.owner),
- viewerUrl: r.glb_url
- ? `/#model=${encodeURIComponent(r.glb_url)}`
- : null,
+ viewerUrl: r.glb_url ? `/#model=${encodeURIComponent(r.glb_url)}` : null,
services: (r.services || []).map((s) => ({
name: s?.name || null,
endpoint: s?.endpoint || null,
diff --git a/api/oauth/authorize.js b/api/oauth/authorize.js
index bbd2a2bd0..8b420addd 100644
--- a/api/oauth/authorize.js
+++ b/api/oauth/authorize.js
@@ -28,11 +28,14 @@ export default wrap(async (req, res) => {
resource,
} = params;
- if (response_type !== 'code') return error(res, 400, 'unsupported_response_type', 'only response_type=code supported');
+ if (response_type !== 'code')
+ return error(res, 400, 'unsupported_response_type', 'only response_type=code supported');
if (!client_id) return error(res, 400, 'invalid_request', 'client_id required');
if (!redirect_uri) return error(res, 400, 'invalid_request', 'redirect_uri required');
- if (!code_challenge) return error(res, 400, 'invalid_request', 'code_challenge required (PKCE)');
- if ((code_challenge_method ?? 'S256') !== 'S256') return error(res, 400, 'invalid_request', 'code_challenge_method must be S256');
+ if (!code_challenge)
+ return error(res, 400, 'invalid_request', 'code_challenge required (PKCE)');
+ if ((code_challenge_method ?? 'S256') !== 'S256')
+ return error(res, 400, 'invalid_request', 'code_challenge_method must be S256');
const rows = await sql`select * from oauth_clients where client_id = ${client_id} limit 1`;
const client = rows[0];
@@ -57,7 +60,8 @@ export default wrap(async (req, res) => {
// POST — user confirmed consent. Reject cross-site POSTs (Origin check) and
// forged submissions (CSRF token bound to the session cookie).
if (!isSameSiteOrigin(req)) return error(res, 403, 'forbidden', 'cross-site request blocked');
- if (!(await verifyCsrfToken(req, params.csrf))) return error(res, 403, 'forbidden', 'invalid csrf token');
+ if (!(await verifyCsrfToken(req, params.csrf)))
+ return error(res, 403, 'forbidden', 'invalid csrf token');
if (params.decision !== 'allow') {
const denied = new URL(redirect_uri);
@@ -87,7 +91,12 @@ function parseQuery(url) {
function intersectScopes(requested, allowed) {
const a = new Set(allowed.split(/\s+/).filter(Boolean));
- return requested.split(/\s+/).filter((s) => a.has(s)).join(' ') || allowed;
+ return (
+ requested
+ .split(/\s+/)
+ .filter((s) => a.has(s))
+ .join(' ') || allowed
+ );
}
function renderConsent(res, { client, user, params, csrf }) {
@@ -97,7 +106,10 @@ function renderConsent(res, { client, user, params, csrf }) {
// Harden the consent page against clickjacking, mixed content, and
// extension/CDN script injection. form-action restricts where the form
// can POST; frame-ancestors blocks iframing of the consent UI.
- res.setHeader('content-security-policy', "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'");
+ res.setHeader(
+ 'content-security-policy',
+ "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'",
+ );
res.setHeader('x-frame-options', 'DENY');
res.setHeader('x-content-type-options', 'nosniff');
res.setHeader('referrer-policy', 'strict-origin-when-cross-origin');
@@ -134,7 +146,10 @@ function renderConsent(res, { client, user, params, csrf }) {
<p style="margin:0 0 4px"><b>${esc(client.name)}</b> will be able to:</p>
<ul>${scopeList.map((s) => `<li>${scopeLabel(s)}</li>`).join('')}</ul>
<input type="hidden" name="csrf" value="${esc(csrf || '')}">
- ${Object.entries(params).filter(([k]) => k !== 'csrf' && k !== 'decision').map(([k, v]) => `<input type="hidden" name="${esc(k)}" value="${esc(v)}">`).join('')}
+ ${Object.entries(params)
+ .filter(([k]) => k !== 'csrf' && k !== 'decision')
+ .map(([k, v]) => `<input type="hidden" name="${esc(k)}" value="${esc(v)}">`)
+ .join('')}
<div class="actions">
<button class="deny" type="submit" name="decision" value="deny">Cancel</button>
<button class="allow" type="submit" name="decision" value="allow">Authorize</button>
@@ -155,5 +170,8 @@ function scopeLabel(s) {
}
function esc(s) {
- return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+ return String(s).replace(
+ /[&<>"']/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
+ );
}
diff --git a/api/oauth/introspect.js b/api/oauth/introspect.js
index ca17f24a5..438e2d949 100644
--- a/api/oauth/introspect.js
+++ b/api/oauth/introspect.js
@@ -12,7 +12,8 @@ export default wrap(async (req, res) => {
const form = await readForm(req);
const { token, client_id, client_secret } = form;
- if (!token || !client_id) return error(res, 400, 'invalid_request', 'token and client_id required');
+ if (!token || !client_id)
+ return error(res, 400, 'invalid_request', 'token and client_id required');
const rows = await sql`select * from oauth_clients where client_id = ${client_id} limit 1`;
const client = rows[0];
diff --git a/api/oauth/register.js b/api/oauth/register.js
index 0ce8aea58..770f469a3 100644
--- a/api/oauth/register.js
+++ b/api/oauth/register.js
@@ -16,7 +16,9 @@ const registerSchema = z.object({
scope: z.string().max(500).optional(),
grant_types: z.array(z.string()).optional(),
response_types: z.array(z.string()).optional(),
- token_endpoint_auth_method: z.enum(['none', 'client_secret_basic', 'client_secret_post']).optional(),
+ token_endpoint_auth_method: z
+ .enum(['none', 'client_secret_basic', 'client_secret_post'])
+ .optional(),
software_id: z.string().max(120).optional(),
software_version: z.string().max(60).optional(),
});
@@ -36,7 +38,12 @@ export default wrap(async (req, res) => {
for (const uri of body.redirect_uris) {
const u = new URL(uri);
if (u.protocol === 'http:' && !/^localhost$|^127\.0\.0\.1$/.test(u.hostname)) {
- return error(res, 400, 'invalid_redirect_uri', 'non-https redirect URIs only allowed for localhost');
+ return error(
+ res,
+ 400,
+ 'invalid_redirect_uri',
+ 'non-https redirect URIs only allowed for localhost',
+ );
}
}
diff --git a/api/oauth/revoke.js b/api/oauth/revoke.js
index 13204bf0c..b004d6df8 100644
--- a/api/oauth/revoke.js
+++ b/api/oauth/revoke.js
@@ -11,7 +11,8 @@ export default wrap(async (req, res) => {
const form = await readForm(req);
const { token, token_type_hint, client_id, client_secret } = form;
- if (!token || !client_id) return error(res, 400, 'invalid_request', 'token and client_id required');
+ if (!token || !client_id)
+ return error(res, 400, 'invalid_request', 'token and client_id required');
const rows = await sql`select * from oauth_clients where client_id = ${client_id} limit 1`;
const client = rows[0];
diff --git a/api/oauth/token.js b/api/oauth/token.js
index 66398eeb2..4c67a19ac 100644
--- a/api/oauth/token.js
+++ b/api/oauth/token.js
@@ -28,7 +28,10 @@ export default wrap(async (req, res) => {
if (client.client_type === 'confidential') {
const secret = form.client_secret || basicAuthPass(req) || '';
const providedHash = await sha256(secret);
- if (!client.client_secret_hash || !constantTimeEquals(providedHash, client.client_secret_hash)) {
+ if (
+ !client.client_secret_hash ||
+ !constantTimeEquals(providedHash, client.client_secret_hash)
+ ) {
return error(res, 401, 'invalid_client', 'bad client credentials');
}
}
@@ -55,12 +58,16 @@ async function handleAuthCode(res, client, form) {
where user_id = ${row.user_id} and client_id = ${client.client_id} and revoked_at is null`;
return error(res, 400, 'invalid_grant', 'authorization code already used');
}
- if (new Date(row.expires_at) < new Date()) return error(res, 400, 'invalid_grant', 'code expired');
- if (row.client_id !== client.client_id) return error(res, 400, 'invalid_grant', 'client mismatch');
- if (row.redirect_uri !== redirect_uri) return error(res, 400, 'invalid_grant', 'redirect_uri mismatch');
+ if (new Date(row.expires_at) < new Date())
+ return error(res, 400, 'invalid_grant', 'code expired');
+ if (row.client_id !== client.client_id)
+ return error(res, 400, 'invalid_grant', 'client mismatch');
+ if (row.redirect_uri !== redirect_uri)
+ return error(res, 400, 'invalid_grant', 'redirect_uri mismatch');
const computed = await sha256Base64Url(code_verifier);
- if (computed !== row.code_challenge) return error(res, 400, 'invalid_grant', 'PKCE verification failed');
+ if (computed !== row.code_challenge)
+ return error(res, 400, 'invalid_grant', 'PKCE verification failed');
await sql`update oauth_auth_codes set consumed_at = now() where code = ${code}`;
@@ -73,7 +80,12 @@ async function handleAuthCode(res, client, form) {
const wantsRefresh = client.grant_types.includes('refresh_token');
const refresh = wantsRefresh
- ? await issueRefreshToken({ userId: row.user_id, clientId: client.client_id, scope: row.scope, resource: row.resource })
+ ? await issueRefreshToken({
+ userId: row.user_id,
+ clientId: client.client_id,
+ scope: row.scope,
+ resource: row.resource,
+ })
: null;
return json(res, 200, {
@@ -120,7 +132,12 @@ async function handleRefresh(res, client, form) {
function intersect(a, b) {
const set = new Set(b.split(/\s+/).filter(Boolean));
- return a.split(/\s+/).filter((s) => set.has(s)).join(' ') || b;
+ return (
+ a
+ .split(/\s+/)
+ .filter((s) => set.has(s))
+ .join(' ') || b
+ );
}
function basicAuthUser(req) {
@@ -129,7 +146,9 @@ function basicAuthUser(req) {
try {
const decoded = Buffer.from(h.slice(6), 'base64').toString('utf8');
return decoded.split(':')[0];
- } catch { return null; }
+ } catch {
+ return null;
+ }
}
function basicAuthPass(req) {
@@ -138,5 +157,7 @@ function basicAuthPass(req) {
try {
const decoded = Buffer.from(h.slice(6), 'base64').toString('utf8');
return decoded.split(':').slice(1).join(':');
- } catch { return null; }
+ } catch {
+ return null;
+ }
}
diff --git a/api/onboarding/avaturn-session.js b/api/onboarding/avaturn-session.js
index d61940add..dd36ed44a 100644
--- a/api/onboarding/avaturn-session.js
+++ b/api/onboarding/avaturn-session.js
@@ -44,16 +44,18 @@ export default wrap(async (req, res) => {
// Rate-limit on the same bucket as other uploads — 60/hour/user is plenty
// for onboarding and bounds abuse cost on the Avaturn API.
const rlUser = await limits.upload(userId);
- if (!rlUser.success) return error(res, 429, 'rate_limited', 'too many avatar attempts, try again later');
+ if (!rlUser.success)
+ return error(res, 429, 'rate_limited', 'too many avatar attempts, try again later');
const rlIp = await limits.authIp(clientIp(req));
- if (!rlIp.success) return error(res, 429, 'rate_limited', 'too many requests from this network');
+ if (!rlIp.success)
+ return error(res, 429, 'rate_limited', 'too many requests from this network');
if (!env.AVATURN_API_KEY) {
return error(
res,
501,
'not_configured',
- 'Avaturn is not configured on this deployment. Set AVATURN_API_KEY.'
+ 'Avaturn is not configured on this deployment. Set AVATURN_API_KEY.',
);
}
diff --git a/api/showcase.js b/api/showcase.js
index f78ec0b38..bf3b338ca 100644
--- a/api/showcase.js
+++ b/api/showcase.js
@@ -105,7 +105,10 @@ function parseParams(sp) {
const chainParam = sp.get('chain') || '';
const explicitChains = [];
if (chainParam) {
- for (const p of chainParam.split(',').map((s) => s.trim()).filter(Boolean)) {
+ for (const p of chainParam
+ .split(',')
+ .map((s) => s.trim())
+ .filter(Boolean)) {
const n = Number(p);
if (!Number.isInteger(n) || !CHAIN_BY_ID[n]) {
return { error: `unknown chain: ${p}` };
diff --git a/api/tts/eleven.js b/api/tts/eleven.js
index 26420d843..1dec9c26b 100644
--- a/api/tts/eleven.js
+++ b/api/tts/eleven.js
@@ -17,13 +17,13 @@ import { env } from '../_lib/env.js';
import { headObject, getObjectBuffer, putObject } from '../_lib/r2.js';
const CHARS_PER_HOUR = 1000;
-const ELEVEN_BASE = 'https://api.elevenlabs.io/v1';
+const ELEVEN_BASE = 'https://api.elevenlabs.io/v1';
// Only instantiate if Upstash is configured (mirrors the pattern in rate-limit.js).
let redis = null;
if (process.env.UPSTASH_REDIS_REST_URL && process.env.UPSTASH_REDIS_REST_TOKEN) {
redis = new Redis({
- url: process.env.UPSTASH_REDIS_REST_URL,
+ url: process.env.UPSTASH_REDIS_REST_URL,
token: process.env.UPSTASH_REDIS_REST_TOKEN,
});
}
@@ -33,44 +33,54 @@ export default wrap(async (req, res) => {
if (!method(req, res, ['POST'])) return;
const apiKey = env.ELEVENLABS_API_KEY;
- if (!apiKey) return error(res, 503, 'not_configured', 'ElevenLabs is not configured on this server');
+ if (!apiKey)
+ return error(res, 503, 'not_configured', 'ElevenLabs is not configured on this server');
const session = await getSessionUser(req);
- const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
const userId = session?.id ?? bearer.userId;
- const body = await readJson(req);
+ const body = await readJson(req);
const voiceId = String(body.voiceId || '').trim();
- const text = String(body.text || '').trim();
+ const text = String(body.text || '').trim();
const modelId = String(body.modelId || 'eleven_turbo_v2_5').trim();
if (!voiceId) return error(res, 400, 'validation_error', 'voiceId is required');
- if (!text) return error(res, 400, 'validation_error', 'text is required');
- if (text.length > 500) return error(res, 400, 'validation_error', 'text exceeds 500 chars per request');
+ if (!text) return error(res, 400, 'validation_error', 'text is required');
+ if (text.length > 500)
+ return error(res, 400, 'validation_error', 'text exceeds 500 chars per request');
// ── Char-based rate limit ─────────────────────────────────────────────────
if (redis) {
const hourBucket = Math.floor(Date.now() / 3_600_000);
const rKey = `tts:chars:${userId}:${hourBucket}`;
- const used = Number(await redis.get(rKey) || 0);
+ const used = Number((await redis.get(rKey)) || 0);
if (used + text.length > CHARS_PER_HOUR) {
- return error(res, 429, 'rate_limited',
- `TTS character limit (${CHARS_PER_HOUR}/hr) reached. Try again next hour.`);
+ return error(
+ res,
+ 429,
+ 'rate_limited',
+ `TTS character limit (${CHARS_PER_HOUR}/hr) reached. Try again next hour.`,
+ );
}
// Increment before synthesis to prevent parallel races from blowing past limit.
const newTotal = await redis.incrby(rKey, text.length);
await redis.expire(rKey, 7200);
if (newTotal > CHARS_PER_HOUR) {
await redis.decrby(rKey, text.length).catch(() => {});
- return error(res, 429, 'rate_limited',
- `TTS character limit (${CHARS_PER_HOUR}/hr) reached. Try again next hour.`);
+ return error(
+ res,
+ 429,
+ 'rate_limited',
+ `TTS character limit (${CHARS_PER_HOUR}/hr) reached. Try again next hour.`,
+ );
}
}
// ── R2 cache lookup ───────────────────────────────────────────────────────
const cacheHash = await sha256(`${voiceId}\x00${text}\x00${modelId}`);
- const cacheKey = `tts/cache/${cacheHash}.mp3`;
+ const cacheKey = `tts/cache/${cacheHash}.mp3`;
const cached = await headObject(cacheKey).catch(() => null);
if (cached) {
@@ -98,16 +108,16 @@ export default wrap(async (req, res) => {
method: 'POST',
headers: {
'content-type': 'application/json',
- 'accept': 'audio/mpeg',
- 'xi-api-key': apiKey,
+ accept: 'audio/mpeg',
+ 'xi-api-key': apiKey,
},
body: JSON.stringify({
text,
model_id: modelId,
voice_settings: {
- stability: 0.5,
- similarity_boost: 0.75,
- style: styleVal,
+ stability: 0.5,
+ similarity_boost: 0.75,
+ style: styleVal,
use_speaker_boost: true,
},
}),
@@ -129,10 +139,10 @@ export default wrap(async (req, res) => {
// Store in R2 (fire-and-forget — cache miss on failure is acceptable).
putObject({
- key: cacheKey,
- body: audioBuffer,
+ key: cacheKey,
+ body: audioBuffer,
contentType: 'audio/mpeg',
- metadata: { 'created-at': new Date().toISOString() },
+ metadata: { 'created-at': new Date().toISOString() },
}).catch((e) => console.warn('[tts/eleven] R2 cache write failed:', e.message));
res.setHeader('content-type', 'audio/mpeg');
diff --git a/api/tts/eleven/voices.js b/api/tts/eleven/voices.js
index 7a591f53f..af9750479 100644
--- a/api/tts/eleven/voices.js
+++ b/api/tts/eleven/voices.js
@@ -15,7 +15,7 @@ export default wrap(async (req, res) => {
if (!method(req, res, ['GET'])) return;
const session = await getSessionUser(req);
- const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
const apiKey = env.ELEVENLABS_API_KEY;
@@ -37,10 +37,10 @@ export default wrap(async (req, res) => {
}
const voices = (data.voices || []).map((v) => ({
- voice_id: v.voice_id,
- name: v.name,
- category: v.category,
- labels: v.labels || {},
+ voice_id: v.voice_id,
+ name: v.name,
+ category: v.category,
+ labels: v.labels || {},
preview_url: v.preview_url || null,
}));
diff --git a/api/widgets/[id].js b/api/widgets/[id].js
index 8bb099d26..3badadfd9 100644
--- a/api/widgets/[id].js
+++ b/api/widgets/[id].js
@@ -13,21 +13,27 @@
import { z } from 'zod';
-import { sql } from '../_lib/db.js';
+import { sql } from '../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
-import { parse } from '../_lib/validate.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-import { decorate } from './index.js';
-
-const WIDGET_TYPES = ['turntable', 'animation-gallery', 'talking-agent', 'passport', 'hotspot-tour'];
+import { parse } from '../_lib/validate.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { decorate } from './index.js';
+
+const WIDGET_TYPES = [
+ 'turntable',
+ 'animation-gallery',
+ 'talking-agent',
+ 'passport',
+ 'hotspot-tour',
+];
const patchSchema = z.object({
- name: z.string().trim().min(1).max(120).optional(),
- config: z.record(z.any()).optional(),
+ name: z.string().trim().min(1).max(120).optional(),
+ config: z.record(z.any()).optional(),
is_public: z.boolean().optional(),
avatar_id: z.string().uuid().nullable().optional(),
- type: z.enum(WIDGET_TYPES).optional(),
+ type: z.enum(WIDGET_TYPES).optional(),
});
export default wrap(async (req, res) => {
@@ -70,7 +76,8 @@ export default wrap(async (req, res) => {
if (!auth?.userId) return error(res, 401, 'unauthorized', 'authentication required');
if (auth.source === 'oauth' || auth.source === 'apikey') {
const need = req.method === 'DELETE' ? 'avatars:delete' : 'avatars:write';
- if (!hasScope(auth.scope, need)) return error(res, 403, 'insufficient_scope', `${need} required`);
+ if (!hasScope(auth.scope, need))
+ return error(res, 403, 'insufficient_scope', `${need} required`);
}
const rl = await limits.widgetWrite(auth.userId);
@@ -83,7 +90,13 @@ export default wrap(async (req, res) => {
const owns = await sql`
select 1 from avatars where id = ${patch.avatar_id} and owner_id = ${auth.userId} and deleted_at is null limit 1
`;
- if (!owns[0]) return error(res, 400, 'invalid_avatar', 'avatar_id not found or not owned by caller');
+ if (!owns[0])
+ return error(
+ res,
+ 400,
+ 'invalid_avatar',
+ 'avatar_id not found or not owned by caller',
+ );
}
const [row] = await sql`
@@ -120,6 +133,11 @@ function idFromReq(req) {
async function resolveAuth(req) {
const session = await getSessionUser(req);
- if (session) return { userId: session.id, source: 'session', scope: 'avatars:read avatars:write avatars:delete' };
+ if (session)
+ return {
+ userId: session.id,
+ source: 'session',
+ scope: 'avatars:read avatars:write avatars:delete',
+ };
return await authenticateBearer(extractBearer(req));
}
diff --git a/api/widgets/[id]/chat.js b/api/widgets/[id]/chat.js
index 702ed93f3..780b515e7 100644
--- a/api/widgets/[id]/chat.js
+++ b/api/widgets/[id]/chat.js
@@ -21,14 +21,14 @@
import { z } from 'zod';
-import { sql } from '../../_lib/db.js';
-import { getSessionUser } from '../../_lib/auth.js';
+import { sql } from '../../_lib/db.js';
+import { getSessionUser } from '../../_lib/auth.js';
import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
-import { parse } from '../../_lib/validate.js';
-import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { parse } from '../../_lib/validate.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
-const ANTHROPIC_URL = 'https://api.anthropic.com/v1/messages';
-const DEFAULT_MODEL = 'claude-sonnet-4-6';
+const ANTHROPIC_URL = 'https://api.anthropic.com/v1/messages';
+const DEFAULT_MODEL = 'claude-sonnet-4-6';
const DEFAULT_MAX_TOKENS = 1024;
const HARD_MAX_TOKENS = 4096;
@@ -36,10 +36,15 @@ const SAFE_SKILLS = new Set(['speak', 'wave', 'lookAt', 'playClip', 'remember'])
const chatBody = z.object({
message: z.string().trim().min(1).max(4000),
- history: z.array(z.object({
- role: z.enum(['user', 'assistant']),
- content: z.string().min(1).max(4000),
- })).max(40).default([]),
+ history: z
+ .array(
+ z.object({
+ role: z.enum(['user', 'assistant']),
+ content: z.string().min(1).max(4000),
+ }),
+ )
+ .max(40)
+ .default([]),
});
const SKILL_TOOLS = [
@@ -110,7 +115,9 @@ export default wrap(async (req, res) => {
if (!rl.success) {
const retryAfter = Math.max(1, Math.ceil((rl.reset - Date.now()) / 1000));
res.setHeader('retry-after', String(retryAfter));
- return error(res, 429, 'rate_limited', 'too many messages — slow down', { retry_after: retryAfter });
+ return error(res, 429, 'rate_limited', 'too many messages — slow down', {
+ retry_after: retryAfter,
+ });
}
}
@@ -136,17 +143,17 @@ export default wrap(async (req, res) => {
result = await callCustomProxy(cfg.proxyURL, body, cfg, allowedSkills);
} else {
result = await callAnthropic({
- message: body.message,
- history: body.history,
+ message: body.message,
+ history: body.history,
systemPrompt: buildSystemPrompt(cfg, widget),
- temperature: Number(cfg.temperature) || 0.7,
- maxTurns: Math.min(20, Math.max(1, Number(cfg.maxTurns) || 20)),
+ temperature: Number(cfg.temperature) || 0.7,
+ maxTurns: Math.min(20, Math.max(1, Number(cfg.maxTurns) || 20)),
allowedSkills,
});
}
writeSse(res, 'message', { reply: result.reply || '', actions: result.actions || [] });
- writeSse(res, 'done', {});
+ writeSse(res, 'done', {});
} catch (err) {
console.warn('[widget-chat] dispatch failed', err?.message);
writeSse(res, 'error', { message: 'chat backend unavailable' });
@@ -160,16 +167,27 @@ export default wrap(async (req, res) => {
// ── Brain dispatchers ──────────────────────────────────────────────────────
-async function callAnthropic({ message, history, systemPrompt, temperature, maxTurns, allowedSkills }) {
+async function callAnthropic({
+ message,
+ history,
+ systemPrompt,
+ temperature,
+ maxTurns,
+ allowedSkills,
+}) {
const apiKey = process.env.ANTHROPIC_API_KEY;
if (!apiKey) {
return {
- reply: "I'm not configured to answer just yet — the owner needs to set ANTHROPIC_API_KEY.",
+ reply: "I'm not configured to answer just yet — the owner needs to set ANTHROPIC_API_KEY.",
actions: [],
};
}
- const model = process.env.CHAT_MODEL || DEFAULT_MODEL;
- const maxTokens = clampInt(parseInt(process.env.CHAT_MAX_TOKENS || '', 10) || DEFAULT_MAX_TOKENS, 128, HARD_MAX_TOKENS);
+ const model = process.env.CHAT_MODEL || DEFAULT_MODEL;
+ const maxTokens = clampInt(
+ parseInt(process.env.CHAT_MAX_TOKENS || '', 10) || DEFAULT_MAX_TOKENS,
+ 128,
+ HARD_MAX_TOKENS,
+ );
// Truncate history to maxTurns (each turn = one user + one assistant message).
const trimmed = history.slice(-(maxTurns * 2));
@@ -181,24 +199,27 @@ async function callAnthropic({ message, history, systemPrompt, temperature, maxT
model,
max_tokens: maxTokens,
temperature,
- system: systemPrompt,
+ system: systemPrompt,
messages,
};
if (tools.length) payload.tools = tools;
const upstream = await fetch(ANTHROPIC_URL, {
- method: 'POST',
+ method: 'POST',
headers: {
- 'x-api-key': apiKey,
+ 'x-api-key': apiKey,
'anthropic-version': '2023-06-01',
- 'content-type': 'application/json',
+ 'content-type': 'application/json',
},
body: JSON.stringify(payload),
});
if (!upstream.ok) {
const text = await upstream.text().catch(() => '');
console.warn('[widget-chat] anthropic', upstream.status, text.slice(0, 400));
- return { reply: 'I had trouble thinking of a response. Try again in a moment.', actions: [] };
+ return {
+ reply: 'I had trouble thinking of a response. Try again in a moment.',
+ actions: [],
+ };
}
const data = await upstream.json();
return normalizeAnthropic(data, allowedSkills);
@@ -206,16 +227,16 @@ async function callAnthropic({ message, history, systemPrompt, temperature, maxT
async function callCustomProxy(proxyURL, body, cfg, allowedSkills) {
if (!/^https:\/\//i.test(proxyURL || '')) {
- return { reply: "Custom brain misconfigured — proxyURL must be HTTPS.", actions: [] };
+ return { reply: 'Custom brain misconfigured — proxyURL must be HTTPS.', actions: [] };
}
const upstream = await fetch(proxyURL, {
- method: 'POST',
+ method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
- message: body.message,
- history: body.history,
+ message: body.message,
+ history: body.history,
systemPrompt: buildSystemPromptForCustom(cfg),
- temperature: Number(cfg.temperature) || 0.7,
+ temperature: Number(cfg.temperature) || 0.7,
}),
});
if (!upstream.ok) {
@@ -327,4 +348,6 @@ function idFromReq(req) {
return m ? decodeURIComponent(m[1]) : null;
}
-function clampInt(n, min, max) { return Math.min(max, Math.max(min, n)); }
+function clampInt(n, min, max) {
+ return Math.min(max, Math.max(min, n));
+}
diff --git a/api/widgets/[id]/duplicate.js b/api/widgets/[id]/duplicate.js
index 2f8957d0b..e8ad64778 100644
--- a/api/widgets/[id]/duplicate.js
+++ b/api/widgets/[id]/duplicate.js
@@ -8,11 +8,11 @@
import crypto from 'node:crypto';
-import { sql } from '../../_lib/db.js';
+import { sql } from '../../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../../_lib/auth.js';
import { cors, json, method, wrap, error } from '../../_lib/http.js';
-import { limits } from '../../_lib/rate-limit.js';
-import { decorate } from '../index.js';
+import { limits } from '../../_lib/rate-limit.js';
+import { decorate } from '../index.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
@@ -24,7 +24,8 @@ export default wrap(async (req, res) => {
const auth = await resolveAuth(req);
if (!auth?.userId) return error(res, 401, 'unauthorized', 'authentication required');
if (auth.source === 'oauth' || auth.source === 'apikey') {
- if (!hasScope(auth.scope, 'avatars:write')) return error(res, 403, 'insufficient_scope', 'avatars:write required');
+ if (!hasScope(auth.scope, 'avatars:write'))
+ return error(res, 403, 'insufficient_scope', 'avatars:write required');
}
const rl = await limits.widgetWrite(auth.userId);
@@ -38,7 +39,7 @@ export default wrap(async (req, res) => {
`;
if (!src) return error(res, 404, 'not_found', 'widget not found or not yours');
- const newId = 'wdgt_' + crypto.randomBytes(9).toString('base64url');
+ const newId = 'wdgt_' + crypto.randomBytes(9).toString('base64url');
const newName = trim(`${src.name} (copy)`, 120);
const [row] = await sql`
@@ -65,6 +66,7 @@ function idFromReq(req) {
async function resolveAuth(req) {
const session = await getSessionUser(req);
- if (session) return { userId: session.id, source: 'session', scope: 'avatars:read avatars:write' };
+ if (session)
+ return { userId: session.id, source: 'session', scope: 'avatars:read avatars:write' };
return await authenticateBearer(extractBearer(req));
}
diff --git a/api/widgets/[id]/stats.js b/api/widgets/[id]/stats.js
index b826631c4..d1059206d 100644
--- a/api/widgets/[id]/stats.js
+++ b/api/widgets/[id]/stats.js
@@ -16,7 +16,7 @@
* "all-zero" state without special casing.
*/
-import { sql } from '../../_lib/db.js';
+import { sql } from '../../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../../_lib/auth.js';
import { cors, json, method, wrap, error } from '../../_lib/http.js';
@@ -30,7 +30,8 @@ export default wrap(async (req, res) => {
const auth = await resolveAuth(req);
if (!auth?.userId) return error(res, 401, 'unauthorized', 'authentication required');
if (auth.source === 'oauth' || auth.source === 'apikey') {
- if (!hasScope(auth.scope, 'avatars:read')) return error(res, 403, 'insufficient_scope', 'avatars:read required');
+ if (!hasScope(auth.scope, 'avatars:read'))
+ return error(res, 403, 'insufficient_scope', 'avatars:read required');
}
// Ownership check — never 404 vs 403 leak: collapse to 404 either way.
@@ -53,12 +54,12 @@ export default wrap(async (req, res) => {
res.setHeader('cache-control', 'private, max-age=30');
return json(res, 200, {
stats: {
- view_count: Number(w.view_count || 0),
- last_viewed_at: lastViewed,
+ view_count: Number(w.view_count || 0),
+ last_viewed_at: lastViewed,
recent_views_7d: recentViews,
- top_referers: topReferers,
- top_countries: topCountries,
- chat_count: chatCount,
+ top_referers: topReferers,
+ top_countries: topCountries,
+ chat_count: chatCount,
},
});
});
@@ -99,7 +100,10 @@ async function topAggregates(id, column) {
group by 1 order by count desc limit 5`,
[id],
);
- return rows.map((r) => ({ [column === 'referer_host' ? 'host' : 'country']: r.key, count: Number(r.count) }));
+ return rows.map((r) => ({
+ [column === 'referer_host' ? 'host' : 'country']: r.key,
+ count: Number(r.count),
+ }));
} catch (err) {
if (/relation .* does not exist/i.test(err?.message || '')) return [];
throw err;
@@ -108,7 +112,8 @@ async function topAggregates(id, column) {
async function lastViewedAt(id) {
try {
- const rows = await sql`select max(created_at) as t from widget_views where widget_id = ${id}`;
+ const rows =
+ await sql`select max(created_at) as t from widget_views where widget_id = ${id}`;
return rows[0]?.t || null;
} catch (err) {
if (/relation .* does not exist/i.test(err?.message || '')) return null;
@@ -138,6 +143,7 @@ function idFromReq(req) {
async function resolveAuth(req) {
const session = await getSessionUser(req);
- if (session) return { userId: session.id, source: 'session', scope: 'avatars:read avatars:write' };
+ if (session)
+ return { userId: session.id, source: 'session', scope: 'avatars:read avatars:write' };
return await authenticateBearer(extractBearer(req));
}
diff --git a/api/widgets/index.js b/api/widgets/index.js
index ca847d9e1..1d4b3026a 100644
--- a/api/widgets/index.js
+++ b/api/widgets/index.js
@@ -11,20 +11,26 @@
import crypto from 'node:crypto';
import { z } from 'zod';
-import { sql } from '../_lib/db.js';
+import { sql } from '../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
-import { parse } from '../_lib/validate.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-import { publicUrl } from '../_lib/r2.js';
-
-const WIDGET_TYPES = ['turntable', 'animation-gallery', 'talking-agent', 'passport', 'hotspot-tour'];
+import { parse } from '../_lib/validate.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { publicUrl } from '../_lib/r2.js';
+
+const WIDGET_TYPES = [
+ 'turntable',
+ 'animation-gallery',
+ 'talking-agent',
+ 'passport',
+ 'hotspot-tour',
+];
const createBody = z.object({
- type: z.enum(WIDGET_TYPES),
- name: z.string().trim().min(1).max(120),
+ type: z.enum(WIDGET_TYPES),
+ name: z.string().trim().min(1).max(120),
avatar_id: z.string().uuid().nullable().optional(),
- config: z.record(z.any()).default({}),
+ config: z.record(z.any()).default({}),
is_public: z.boolean().default(true),
});
@@ -63,7 +69,8 @@ export default wrap(async (req, res) => {
const owns = await sql`
select 1 from avatars where id = ${body.avatar_id} and owner_id = ${auth.userId} and deleted_at is null limit 1
`;
- if (!owns[0]) return error(res, 400, 'invalid_avatar', 'avatar_id not found or not owned by caller');
+ if (!owns[0])
+ return error(res, 400, 'invalid_avatar', 'avatar_id not found or not owned by caller');
}
const id = newWidgetId();
@@ -103,19 +110,27 @@ export function decorate(row) {
updated_at: row.updated_at,
};
if (row.avatar_name !== undefined) {
- out.avatar = row.avatar_id ? {
- id: row.avatar_id,
- name: row.avatar_name,
- thumbnail_url: safePublicUrl(row.avatar_thumbnail_key),
- model_url: (row.avatar_visibility === 'public' || row.avatar_visibility === 'unlisted')
- ? safePublicUrl(row.avatar_storage_key) : null,
- visibility: row.avatar_visibility,
- } : null;
+ out.avatar = row.avatar_id
+ ? {
+ id: row.avatar_id,
+ name: row.avatar_name,
+ thumbnail_url: safePublicUrl(row.avatar_thumbnail_key),
+ model_url:
+ row.avatar_visibility === 'public' || row.avatar_visibility === 'unlisted'
+ ? safePublicUrl(row.avatar_storage_key)
+ : null,
+ visibility: row.avatar_visibility,
+ }
+ : null;
}
return out;
}
function safePublicUrl(key) {
if (!key) return null;
- try { return publicUrl(key); } catch { return null; }
+ try {
+ return publicUrl(key);
+ } catch {
+ return null;
+ }
}
diff --git a/api/widgets/view.js b/api/widgets/view.js
index 29d5bbc67..d11878626 100644
--- a/api/widgets/view.js
+++ b/api/widgets/view.js
@@ -12,18 +12,18 @@
* the dashboard does.
*/
-import { sql } from '../_lib/db.js';
-import { cors, wrap, error } from '../_lib/http.js';
+import { sql } from '../_lib/db.js';
+import { cors, wrap, error } from '../_lib/http.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
if (req.method !== 'POST') return error(res, 405, 'method_not_allowed', 'POST only');
- const url = new URL(req.url, 'http://x');
+ const url = new URL(req.url, 'http://x');
const widgetId = url.searchParams.get('id');
if (!widgetId) return error(res, 400, 'invalid_request', 'id required');
- const country = headerOnce(req, 'x-vercel-ip-country') || null;
+ const country = headerOnce(req, 'x-vercel-ip-country') || null;
const refererHost = parseRefererHost(req.headers.referer);
try {
@@ -53,5 +53,9 @@ function headerOnce(req, name) {
function parseRefererHost(referer) {
if (!referer) return null;
- try { return new URL(referer).hostname || null; } catch { return null; }
+ try {
+ return new URL(referer).hostname || null;
+ } catch {
+ return null;
+ }
}
diff --git a/api/wk-oauth-authorization-server.js b/api/wk-oauth-authorization-server.js
index 28c8d85d8..2bd0b73fb 100644
--- a/api/wk-oauth-authorization-server.js
+++ b/api/wk-oauth-authorization-server.js
@@ -12,27 +12,36 @@ export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
if (!method(req, res, ['GET'])) return;
const base = env.APP_ORIGIN;
- return json(res, 200, {
- issuer: base,
- authorization_endpoint: `${base}/oauth/authorize`,
- token_endpoint: `${base}/api/oauth/token`,
- registration_endpoint: `${base}/api/oauth/register`,
- revocation_endpoint: `${base}/api/oauth/revoke`,
- introspection_endpoint: `${base}/api/oauth/introspect`,
- response_types_supported: ['code'],
- grant_types_supported: ['authorization_code', 'refresh_token'],
- code_challenge_methods_supported: ['S256'],
- token_endpoint_auth_methods_supported: ['none', 'client_secret_basic', 'client_secret_post'],
- scopes_supported: [
- 'avatars:read',
- 'avatars:write',
- 'avatars:delete',
- 'profile',
- 'offline_access',
- ],
- service_documentation: `${base}/docs/mcp`,
- ui_locales_supported: ['en'],
- }, {
- 'cache-control': 'public, max-age=300',
- });
+ return json(
+ res,
+ 200,
+ {
+ issuer: base,
+ authorization_endpoint: `${base}/oauth/authorize`,
+ token_endpoint: `${base}/api/oauth/token`,
+ registration_endpoint: `${base}/api/oauth/register`,
+ revocation_endpoint: `${base}/api/oauth/revoke`,
+ introspection_endpoint: `${base}/api/oauth/introspect`,
+ response_types_supported: ['code'],
+ grant_types_supported: ['authorization_code', 'refresh_token'],
+ code_challenge_methods_supported: ['S256'],
+ token_endpoint_auth_methods_supported: [
+ 'none',
+ 'client_secret_basic',
+ 'client_secret_post',
+ ],
+ scopes_supported: [
+ 'avatars:read',
+ 'avatars:write',
+ 'avatars:delete',
+ 'profile',
+ 'offline_access',
+ ],
+ service_documentation: `${base}/docs/mcp`,
+ ui_locales_supported: ['en'],
+ },
+ {
+ 'cache-control': 'public, max-age=300',
+ },
+ );
});
diff --git a/api/wk-oauth-protected-resource.js b/api/wk-oauth-protected-resource.js
index 668fcda92..97425c6a4 100644
--- a/api/wk-oauth-protected-resource.js
+++ b/api/wk-oauth-protected-resource.js
@@ -10,13 +10,18 @@ import { cors, json, method, wrap } from './_lib/http.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
if (!method(req, res, ['GET'])) return;
- return json(res, 200, {
- resource: env.MCP_RESOURCE,
- authorization_servers: [env.APP_ORIGIN],
- bearer_methods_supported: ['header'],
- resource_documentation: `${env.APP_ORIGIN}/docs/mcp`,
- scopes_supported: ['avatars:read', 'avatars:write', 'avatars:delete', 'profile'],
- }, {
- 'cache-control': 'public, max-age=300',
- });
+ return json(
+ res,
+ 200,
+ {
+ resource: env.MCP_RESOURCE,
+ authorization_servers: [env.APP_ORIGIN],
+ bearer_methods_supported: ['header'],
+ resource_documentation: `${env.APP_ORIGIN}/docs/mcp`,
+ scopes_supported: ['avatars:read', 'avatars:write', 'avatars:delete', 'profile'],
+ },
+ {
+ 'cache-control': 'public, max-age=300',
+ },
+ );
});
diff --git a/contracts/CLAUDE.md b/contracts/CLAUDE.md
index 8911b9de7..abe524b41 100644
--- a/contracts/CLAUDE.md
+++ b/contracts/CLAUDE.md
@@ -10,11 +10,11 @@ Scoped guidance for the Foundry project implementing ERC-8004. Read [/CLAUDE.md]
All Solidity 0.8.24, optimizer 200 runs, OpenZeppelin-based.
-| Contract | File | Purpose |
-|---|---|---|
-| **IdentityRegistry** | [src/IdentityRegistry.sol](src/IdentityRegistry.sol) | ERC-721 agents. `register()`, `register(agentURI)`, `register(agentURI, MetadataEntry[])`, `setAgentURI()`, `tokenURI()`, `setAgentWallet()` (EIP-712 delegated), `getAgentWallet()`, `unsetAgentWallet()`, `setMetadata()`, `getMetadata()`, `isAgent()`, `ownerOf()`. |
-| **ReputationRegistry** | [src/ReputationRegistry.sol](src/ReputationRegistry.sol) | Signed feedback −100..+100, one review per address per agent. `submitFeedback(agentId, score, uri)`, `getReputation()` → `(avgX100, count)`, `getFeedback()`, `getFeedbackRange()`, `getFeedbackCount()`. |
-| **ValidationRegistry** | [src/ValidationRegistry.sol](src/ValidationRegistry.sol) | Allow-listed validators attest off-chain proofs. `recordValidation(agentId, passed, proofHash, proofURI, kind)` (validator-only), `getValidation()`, `getLatestByKind()`, `getValidationRange()`, `addValidator()`, `removeValidator()`, `transferOwnership()`. |
+| Contract | File | Purpose |
+| ---------------------- | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| **IdentityRegistry** | [src/IdentityRegistry.sol](src/IdentityRegistry.sol) | ERC-721 agents. `register()`, `register(agentURI)`, `register(agentURI, MetadataEntry[])`, `setAgentURI()`, `tokenURI()`, `setAgentWallet()` (EIP-712 delegated), `getAgentWallet()`, `unsetAgentWallet()`, `setMetadata()`, `getMetadata()`, `isAgent()`, `ownerOf()`. |
+| **ReputationRegistry** | [src/ReputationRegistry.sol](src/ReputationRegistry.sol) | Signed feedback −100..+100, one review per address per agent. `submitFeedback(agentId, score, uri)`, `getReputation()` → `(avgX100, count)`, `getFeedback()`, `getFeedbackRange()`, `getFeedbackCount()`. |
+| **ValidationRegistry** | [src/ValidationRegistry.sol](src/ValidationRegistry.sol) | Allow-listed validators attest off-chain proofs. `recordValidation(agentId, passed, proofHash, proofURI, kind)` (validator-only), `getValidation()`, `getLatestByKind()`, `getValidationRange()`, `addValidator()`, `removeValidator()`, `transferOwnership()`. |
---
@@ -23,12 +23,14 @@ All Solidity 0.8.24, optimizer 200 runs, OpenZeppelin-based.
Same address on every EVM chain (CREATE2 deterministic). Mirrored in [src/erc8004/abi.js](../src/erc8004/abi.js) `REGISTRY_DEPLOYMENTS`.
### Mainnet (chainIds: 1, 10, 56, 100, 137, 250, 324, 1284, 5000, 8453, 42161, 42220, 43114, 59144, 534352)
-- IdentityRegistry: `0x8004A169FB4a3325136EB29fA0ceB6D2e539a432`
+
+- IdentityRegistry: `0x8004A169FB4a3325136EB29fA0ceB6D2e539a432`
- ReputationRegistry: `0x8004BAa17C55a88189AE136b182e5fdA19dE9b63`
-- ValidationRegistry: *(not yet deployed on mainnet)*
+- ValidationRegistry: _(not yet deployed on mainnet)_
### Testnet (chainIds: 97, 11155111, 84532, 421614, 11155420, 80002, 43113)
-- IdentityRegistry: `0x8004A818BFB912233c491871b3d84c89A494BD9e`
+
+- IdentityRegistry: `0x8004A818BFB912233c491871b3d84c89A494BD9e`
- ReputationRegistry: `0x8004B663056A597Dffe9eCcC1965A193B7388713`
- ValidationRegistry: `0x8004Cb1BF31DAf7788923b405b754f57acEB4272`
@@ -68,11 +70,12 @@ Configured RPC aliases (from [foundry.toml](foundry.toml)): `base_sepolia`, `bas
ABIs are **hardcoded** in [src/erc8004/abi.js](../src/erc8004/abi.js) as ethers v6 human-readable strings (not JSON):
```js
-'function register(string agentURI) external returns (uint256 agentId)'
-'function tokenURI(uint256 tokenId) external view returns (string)'
+'function register(string agentURI) external returns (uint256 agentId)';
+'function tokenURI(uint256 tokenId) external view returns (string)';
```
No generation step. When you add/change a function signature in Solidity:
+
1. Change the `.sol`
2. Update the string in `abi.js` to match exactly
3. Update any callers in `src/erc8004/*.js`
diff --git a/contracts/README.md b/contracts/README.md
index f5c5ab952..8a8fbaf07 100644
--- a/contracts/README.md
+++ b/contracts/README.md
@@ -27,27 +27,30 @@ forge test -vv
## Deploy to Base Sepolia
1. Install Foundry if you haven't:
- ```bash
- curl -L https://foundry.paradigm.xyz | bash && foundryup
- ```
+
+ ```bash
+ curl -L https://foundry.paradigm.xyz | bash && foundryup
+ ```
2. Fund a deployer wallet with Base Sepolia ETH: https://www.alchemy.com/faucets/base-sepolia
3. Configure environment:
- ```bash
- cp .env.example .env
- # Fill in DEPLOYER_PK and BASESCAN_API_KEY
- ```
+
+ ```bash
+ cp .env.example .env
+ # Fill in DEPLOYER_PK and BASESCAN_API_KEY
+ ```
4. Deploy + verify:
- ```bash
- source .env
- forge script script/Deploy.s.sol:Deploy \
- --rpc-url $BASE_SEPOLIA_RPC_URL \
- --private-key $DEPLOYER_PK \
- --broadcast \
- --verify
- ```
+
+ ```bash
+ source .env
+ forge script script/Deploy.s.sol:Deploy \
+ --rpc-url $BASE_SEPOLIA_RPC_URL \
+ --private-key $DEPLOYER_PK \
+ --broadcast \
+ --verify
+ ```
5. Copy the three addresses from the console output into [`../src/erc8004/abi.js`](../src/erc8004/abi.js) under the `84532` entry of `REGISTRY_DEPLOYMENTS`.
diff --git a/cors.json b/cors.json
index 7dccb0ae4..0c1bc55a3 100644
--- a/cors.json
+++ b/cors.json
@@ -1,7 +1,14 @@
[
{
"method": ["GET"],
- "origin": ["https://3dagent.vercel.app", "https://chat.sperax.io", "https://sperax-jam2emun9-moomsi.vercel.app", "https://sperax-iota.vercel.app", "http://localhost:*", "https://localhost:*"],
+ "origin": [
+ "https://3dagent.vercel.app",
+ "https://chat.sperax.io",
+ "https://sperax-jam2emun9-moomsi.vercel.app",
+ "https://sperax-iota.vercel.app",
+ "http://localhost:*",
+ "https://localhost:*"
+ ],
"responseHeader": ["Content-Type"],
"maxAgeSeconds": 3600
}
diff --git a/create.html b/create.html
index 9cb6c3aa5..9bc0b4743 100644
--- a/create.html
+++ b/create.html
@@ -311,8 +311,12 @@
animation: avatar-creator-fadein 0.25s ease;
}
@keyframes avatar-creator-fadein {
- from { opacity: 0; }
- to { opacity: 1; }
+ from {
+ opacity: 0;
+ }
+ to {
+ opacity: 1;
+ }
}
.avatar-creator-modal {
width: 95vw;
@@ -350,7 +354,9 @@
line-height: 1;
transition: color 0.2s ease;
}
- .avatar-creator-close:hover { color: #fff; }
+ .avatar-creator-close:hover {
+ color: #fff;
+ }
.avatar-creator-body {
flex: 1;
position: relative;
@@ -388,7 +394,9 @@
animation: spin 0.75s linear infinite;
}
@keyframes spin {
- to { transform: rotate(360deg); }
+ to {
+ transform: rotate(360deg);
+ }
}
@media screen and (max-width: 700px) {
.avatar-creator-modal {
diff --git a/docs/API.md b/docs/API.md
index 75a9e9ac2..b0fc7c6f7 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -27,33 +27,33 @@ The top-level application controller. Manages user interaction (drag-and-drop, f
new App(el: Element, location: Location)
```
-| Parameter | Type | Description |
-|-----------|------|-------------|
-| `el` | `Element` | Root DOM element (typically `document.body`) |
+| Parameter | Type | Description |
+| ---------- | ---------- | -------------------------------------------------- |
+| `el` | `Element` | Root DOM element (typically `document.body`) |
| `location` | `Location` | Browser location object for hash parameter parsing |
Parses the following URL hash parameters via `query-string`:
-| Hash Param | Type | Default | Description |
-|------------|------|---------|-------------|
-| `model` | `string` | `'/avatars/cz.glb'` | URL of a glTF/GLB model to load |
-| `kiosk` | `boolean` | `false` | Hides header; intended for iframe embedding |
-| `preset` | `string` | `''` | `'assetgenerator'` activates asset generator mode |
-| `cameraPosition` | `string` | `null` | Comma-separated `x,y,z` camera coordinates |
+| Hash Param | Type | Default | Description |
+| ---------------- | --------- | ------------------- | ------------------------------------------------- |
+| `model` | `string` | `'/avatars/cz.glb'` | URL of a glTF/GLB model to load |
+| `kiosk` | `boolean` | `false` | Hides header; intended for iframe embedding |
+| `preset` | `string` | `''` | `'assetgenerator'` activates asset generator mode |
+| `cameraPosition` | `string` | `null` | Comma-separated `x,y,z` camera coordinates |
### Properties
-| Property | Type | Description |
-|----------|------|-------------|
-| `el` | `Element` | Root DOM element |
-| `viewer` | `Viewer \| null` | Viewer instance (created on first model load) |
-| `viewerEl` | `Element \| null` | Viewer container element |
-| `spinnerEl` | `Element` | Loading spinner element |
-| `dropEl` | `Element` | Drop target element (`.wrap`) |
-| `inputEl` | `Element` | Hidden file input element |
-| `viewerContainerEl` | `Element` | Container for the 3D viewport |
-| `validator` | `Validator` | Validator instance |
-| `options` | `object` | Parsed URL hash options |
+| Property | Type | Description |
+| ------------------- | ----------------- | --------------------------------------------- |
+| `el` | `Element` | Root DOM element |
+| `viewer` | `Viewer \| null` | Viewer instance (created on first model load) |
+| `viewerEl` | `Element \| null` | Viewer container element |
+| `spinnerEl` | `Element` | Loading spinner element |
+| `dropEl` | `Element` | Drop target element (`.wrap`) |
+| `inputEl` | `Element` | Hidden file input element |
+| `viewerContainerEl` | `Element` | Container for the 3D viewport |
+| `validator` | `Validator` | Validator instance |
+| `options` | `object` | Parsed URL hash options |
### Methods
@@ -82,13 +82,14 @@ Processes a fileset from a drag-and-drop or file input event.
Loads a model into the viewer and runs validation.
-| Parameter | Type | Description |
-|-----------|------|-------------|
-| `rootFile` | `File \| string` | The root glTF/GLB file object or URL string |
-| `rootPath` | `string` | Directory prefix for resolving relative URIs |
-| `fileMap` | `Map<string, File>` | All files from the drop (for multi-file glTF) |
+| Parameter | Type | Description |
+| ---------- | ------------------- | --------------------------------------------- |
+| `rootFile` | `File \| string` | The root glTF/GLB file object or URL string |
+| `rootPath` | `string` | Directory prefix for resolving relative URIs |
+| `fileMap` | `Map<string, File>` | All files from the drop (for multi-file glTF) |
Flow:
+
1. Clears any existing scene from the viewer
2. Creates a blob URL if `rootFile` is a `File` object
3. Calls `Viewer.load()` to render the model
@@ -99,11 +100,11 @@ Flow:
Normalizes and displays an error message via `window.alert()`. Special case handling:
-| Pattern | Displayed Message |
-|---------|-------------------|
-| Contains `ProgressEvent` | "Unable to retrieve this file..." |
-| Contains `Unexpected token` | "Unable to parse file content..." |
-| `error.target instanceof Image` | "Missing texture: {filename}" |
+| Pattern | Displayed Message |
+| ------------------------------- | --------------------------------- |
+| Contains `ProgressEvent` | "Unable to retrieve this file..." |
+| Contains `Unexpected token` | "Unable to parse file content..." |
+| `error.target instanceof Image` | "Missing texture: {filename}" |
#### `showSpinner()` / `hideSpinner()`
@@ -123,12 +124,13 @@ The Three.js rendering engine. Manages the WebGL scene, camera, renderer, contro
new Viewer(el: Element, options: object)
```
-| Parameter | Type | Description |
-|-----------|------|-------------|
-| `el` | `Element` | Container element for the WebGL canvas |
-| `options` | `object` | Options from `App` (kiosk, preset, cameraPosition) |
+| Parameter | Type | Description |
+| --------- | --------- | -------------------------------------------------- |
+| `el` | `Element` | Container element for the WebGL canvas |
+| `options` | `object` | Options from `App` (kiosk, preset, cameraPosition) |
The constructor:
+
1. Creates `WebGLRenderer`, `PerspectiveCamera`, `Scene`, `OrbitControls`
2. Initializes `PMREMGenerator` for environment map processing
3. Creates the neutral environment from `THREE.RoomEnvironment`
@@ -139,32 +141,32 @@ The constructor:
### Properties
-| Property | Type | Description |
-|----------|------|-------------|
-| `el` | `Element` | Container element |
-| `options` | `object` | Configuration options |
-| `scene` | `THREE.Scene` | The Three.js scene |
-| `defaultCamera` | `THREE.PerspectiveCamera` | Default orbit camera |
-| `activeCamera` | `THREE.Camera` | Currently active camera (default or embedded) |
-| `renderer` | `THREE.WebGLRenderer` | WebGL renderer (also on `window.renderer`) |
-| `controls` | `OrbitControls` | Orbit controls instance |
-| `content` | `THREE.Object3D \| null` | Currently loaded model root |
-| `mixer` | `THREE.AnimationMixer \| null` | Animation mixer |
-| `clips` | `THREE.AnimationClip[]` | Animation clips from the loaded model |
-| `lights` | `THREE.Light[]` | App-provided lights (ambient + directional) |
-| `gui` | `GUI` | dat.gui instance |
-| `state` | `object` | Current GUI state (see [State Object](#state-object) below) |
-| `stats` | `Stats` | stats.js performance monitor |
-| `backgroundColor` | `THREE.Color` | Current background color |
-| `pmremGenerator` | `THREE.PMREMGenerator` | Environment map processor |
-| `neutralEnvironment` | `THREE.Texture` | Pre-computed neutral environment |
-| `skeletonHelpers` | `THREE.SkeletonHelper[]` | Active skeleton overlays |
-| `gridHelper` | `THREE.GridHelper \| null` | Grid overlay |
-| `axesHelper` | `THREE.AxesHelper \| null` | Axes overlay in main scene |
-| `axesScene` | `THREE.Scene` | Mini axes viewport scene |
-| `axesCamera` | `THREE.PerspectiveCamera` | Mini axes viewport camera |
-| `axesRenderer` | `THREE.WebGLRenderer` | Mini axes viewport renderer |
-| `axesCorner` | `THREE.AxesHelper` | Axes object in mini viewport |
+| Property | Type | Description |
+| -------------------- | ------------------------------ | ----------------------------------------------------------- |
+| `el` | `Element` | Container element |
+| `options` | `object` | Configuration options |
+| `scene` | `THREE.Scene` | The Three.js scene |
+| `defaultCamera` | `THREE.PerspectiveCamera` | Default orbit camera |
+| `activeCamera` | `THREE.Camera` | Currently active camera (default or embedded) |
+| `renderer` | `THREE.WebGLRenderer` | WebGL renderer (also on `window.renderer`) |
+| `controls` | `OrbitControls` | Orbit controls instance |
+| `content` | `THREE.Object3D \| null` | Currently loaded model root |
+| `mixer` | `THREE.AnimationMixer \| null` | Animation mixer |
+| `clips` | `THREE.AnimationClip[]` | Animation clips from the loaded model |
+| `lights` | `THREE.Light[]` | App-provided lights (ambient + directional) |
+| `gui` | `GUI` | dat.gui instance |
+| `state` | `object` | Current GUI state (see [State Object](#state-object) below) |
+| `stats` | `Stats` | stats.js performance monitor |
+| `backgroundColor` | `THREE.Color` | Current background color |
+| `pmremGenerator` | `THREE.PMREMGenerator` | Environment map processor |
+| `neutralEnvironment` | `THREE.Texture` | Pre-computed neutral environment |
+| `skeletonHelpers` | `THREE.SkeletonHelper[]` | Active skeleton overlays |
+| `gridHelper` | `THREE.GridHelper \| null` | Grid overlay |
+| `axesHelper` | `THREE.AxesHelper \| null` | Axes overlay in main scene |
+| `axesScene` | `THREE.Scene` | Mini axes viewport scene |
+| `axesCamera` | `THREE.PerspectiveCamera` | Mini axes viewport camera |
+| `axesRenderer` | `THREE.WebGLRenderer` | Mini axes viewport renderer |
+| `axesCorner` | `THREE.AxesHelper` | Axes object in mini viewport |
### State Object
@@ -219,11 +221,11 @@ Handles window resize. Updates camera aspect ratio, renderer size, and axes rend
Loads a glTF/GLB model.
-| Parameter | Type | Description |
-|-----------|------|-------------|
-| `url` | `string` | URL to the model file (or blob URL) |
-| `rootPath` | `string` | Directory prefix for resolving relative URIs |
-| `assetMap` | `Map<string, File>` | Dropped files for local resource resolution |
+| Parameter | Type | Description |
+| ---------- | ------------------- | -------------------------------------------- |
+| `url` | `string` | URL to the model file (or blob URL) |
+| `rootPath` | `string` | Directory prefix for resolving relative URIs |
+| `assetMap` | `Map<string, File>` | Dropped files for local resource resolution |
Returns a Promise that resolves with the parsed glTF object. The method:
@@ -259,9 +261,9 @@ Plays all animation clips simultaneously by calling `mixer.clipAction(clip).rese
Switches the active camera.
-| Value | Behavior |
-|-------|----------|
-| `'[default]'` | Activates the orbit camera; enables OrbitControls |
+| Value | Behavior |
+| ---------------- | ---------------------------------------------------------------------------------- |
+| `'[default]'` | Activates the orbit camera; enables OrbitControls |
| Any other string | Traverses the scene for a camera with `node.name === name`; disables OrbitControls |
#### `updateLights()`
@@ -288,15 +290,16 @@ Loads the selected environment map and applies it to `scene.environment`. If `st
Processes an environment definition into a usable environment map:
-| Environment ID | Processing |
-|----------------|-----------|
-| `'neutral'` | Returns pre-computed `RoomEnvironment` texture |
-| `''` | Returns `null` (no environment) |
-| Any other | Loads `.exr` via `EXRLoader`, processes through `PMREMGenerator` |
+| Environment ID | Processing |
+| -------------- | ---------------------------------------------------------------- |
+| `'neutral'` | Returns pre-computed `RoomEnvironment` texture |
+| `''` | Returns `null` (no environment) |
+| Any other | Loads `.exr` via `EXRLoader`, processes through `PMREMGenerator` |
#### `updateDisplay()`
Applies display state changes:
+
- Wireframe mode on all materials
- Point size for `PointsMaterial`
- Skeleton helpers on skinned meshes
@@ -310,6 +313,7 @@ Updates `backgroundColor` from `state.bgColor`.
#### `addAxesHelper()`
Creates the mini axes viewport:
+
- 100×100 px `<div>` in the bottom-left corner
- Separate `WebGLRenderer` with transparent background
- `AxesHelper(5)` scaled to match the loaded model
@@ -332,6 +336,7 @@ Rebuilds the dynamic GUI folders (Animation, Morph Targets, Cameras) based on th
#### `clear()`
Removes the current model from the scene and disposes all resources:
+
- Disposes all geometries
- Disposes all textures (except `envMap`)
- Disposes all materials
@@ -354,17 +359,17 @@ Integrates the [Khronos glTF-Validator](https://github.com/KhronosGroup/glTF-Val
new Validator(el: Element)
```
-| Parameter | Type | Description |
-|-----------|------|-------------|
-| `el` | `Element` | Root DOM element for appending the toggle bar |
+| Parameter | Type | Description |
+| --------- | --------- | --------------------------------------------- |
+| `el` | `Element` | Root DOM element for appending the toggle bar |
### Properties
-| Property | Type | Description |
-|----------|------|-------------|
-| `el` | `Element` | Root DOM element |
-| `report` | `object \| null` | Last validation report |
-| `toggleEl` | `Element` | Container for the toggle bar |
+| Property | Type | Description |
+| ---------- | ---------------- | ---------------------------- |
+| `el` | `Element` | Root DOM element |
+| `report` | `object \| null` | Last validation report |
+| `toggleEl` | `Element` | Container for the toggle bar |
### Methods
@@ -372,14 +377,15 @@ new Validator(el: Element)
Runs the glTF validator against a loaded model.
-| Parameter | Type | Description |
-|-----------|------|-------------|
-| `rootFile` | `string` | URL of the model file |
-| `rootPath` | `string` | Directory prefix for resolving relative URIs |
-| `assetMap` | `Map<string, File>` | Dropped files for local resource resolution |
-| `response` | `object` | The parsed GLTF object from GLTFLoader |
+| Parameter | Type | Description |
+| ---------- | ------------------- | -------------------------------------------- |
+| `rootFile` | `string` | URL of the model file |
+| `rootPath` | `string` | Directory prefix for resolving relative URIs |
+| `assetMap` | `Map<string, File>` | Dropped files for local resource resolution |
+| `response` | `object` | The parsed GLTF object from GLTFLoader |
Flow:
+
1. Fetches the model URL as an `ArrayBuffer`
2. Calls `validateBytes()` from `gltf-validator`
3. Provides `externalResourceFunction` for resolving external resources
@@ -409,12 +415,12 @@ Processes the raw validator report:
Extracts metadata from the glTF `asset.extras` field:
-| Extra | Processing |
-|-------|-----------|
-| `author` | HTML-escaped then linkified |
+| Extra | Processing |
+| --------- | --------------------------- |
+| `author` | HTML-escaped then linkified |
| `license` | HTML-escaped then linkified |
-| `source` | HTML-escaped then linkified |
-| `title` | Stored as-is |
+| `source` | HTML-escaped then linkified |
+| `title` | Stored as-is |
#### `setReportException(e: Error)`
@@ -443,6 +449,7 @@ All components are pure functions that return HTML strings via [vhtml](https://g
**File:** `src/components/footer.jsx`
Returns a `<footer>` with:
+
- X (Twitter) link to [@nichxbt](https://x.com/nichxbt)
- "help & feedback" link to GitHub issues
- GitHub repository link
@@ -456,12 +463,13 @@ Returns a `<footer>` with:
Renders the validation status bar.
-| Prop | Type | Description |
-|------|------|-------------|
-| `issues` | `object \| undefined` | Validation issues summary |
-| `reportError` | `Error \| undefined` | Error if validation failed to run |
+| Prop | Type | Description |
+| ------------- | --------------------- | --------------------------------- |
+| `issues` | `object \| undefined` | Validation issues summary |
+| `reportError` | `Error \| undefined` | Error if validation failed to run |
Message logic:
+
- `numErrors > 0` → "X errors."
- `numWarnings > 0` → "X warnings."
- `numHints > 0` → "X hints."
@@ -476,17 +484,18 @@ CSS class `level-{maxSeverity}` controls the color (0 = red, 1 = yellow).
Renders the full validation report.
-| Prop | Type | Description |
-|------|------|-------------|
-| `info` | `object` | Model info (version, generator, counts, extensions, extras) |
-| `validatorVersion` | `string` | glTF-Validator version |
-| `issues` | `object` | Issues summary with counts |
-| `errors` | `array` | Error messages |
-| `warnings` | `array` | Warning messages |
-| `hints` | `array` | Hint messages |
-| `infos` | `array` | Info messages |
+| Prop | Type | Description |
+| ------------------ | -------- | ----------------------------------------------------------- |
+| `info` | `object` | Model info (version, generator, counts, extensions, extras) |
+| `validatorVersion` | `string` | glTF-Validator version |
+| `issues` | `object` | Issues summary with counts |
+| `errors` | `array` | Error messages |
+| `warnings` | `array` | Warning messages |
+| `hints` | `array` | Hint messages |
+| `infos` | `array` | Info messages |
Displays:
+
- Format version and generator
- Metadata from `asset.extras` (title, author, license, source)
- Stats: draw calls, animations, materials, vertices, triangles
@@ -499,11 +508,11 @@ Displays:
Renders a color-coded table of validation issues.
-| Prop | Type | Description |
-|------|------|-------------|
-| `title` | `string` | Severity title ("Error", "Warning", "Hint", "Info") |
-| `color` | `string` | Header background color (CSS color string) |
-| `messages` | `array` | Array of `{ code, message, pointer }` objects |
+| Prop | Type | Description |
+| ---------- | -------- | --------------------------------------------------- |
+| `title` | `string` | Severity title ("Error", "Warning", "Hint", "Info") |
+| `color` | `string` | Header background color (CSS color string) |
+| `messages` | `array` | Array of `{ code, message, pointer }` objects |
Columns: Code, Message, Pointer (JSON pointer into the glTF).
@@ -519,21 +528,21 @@ Exports `environments` — an array of environment map definitions.
```typescript
interface Environment {
- id: string; // Unique identifier ('' for none, 'neutral' for RoomEnvironment)
- name: string; // Display name in the GUI dropdown
- path: string | null; // URL to the EXR file (null for procedural/none)
- format?: string; // File format (e.g., '.exr')
+ id: string; // Unique identifier ('' for none, 'neutral' for RoomEnvironment)
+ name: string; // Display name in the GUI dropdown
+ path: string | null; // URL to the EXR file (null for procedural/none)
+ format?: string; // File format (e.g., '.exr')
}
```
### Default Environments
-| ID | Name | Source |
-|----|------|--------|
-| `''` | None | No environment map |
-| `neutral` | Neutral | `THREE.RoomEnvironment` (procedural) |
-| `venice-sunset` | Venice Sunset | `venice_sunset_1k.exr` from GCS |
-| `footprint-court` | Footprint Court (HDR Labs) | `footprint_court_2k.exr` from GCS |
+| ID | Name | Source |
+| ----------------- | -------------------------- | ------------------------------------ |
+| `''` | None | No environment map |
+| `neutral` | Neutral | `THREE.RoomEnvironment` (procedural) |
+| `venice-sunset` | Venice Sunset | `venice_sunset_1k.exr` from GCS |
+| `footprint-court` | Footprint Court (HDR Labs) | `footprint_court_2k.exr` from GCS |
### Adding Custom Environments
@@ -549,6 +558,7 @@ Append to the `environments` array in `src/environments.js`:
```
Requirements:
+
- Must be an equirectangular HDR image in `.exr` format
- 1K resolution (1024×512) is recommended for web delivery
- Must be served with CORS headers allowing the app's origin
@@ -559,11 +569,11 @@ Requirements:
The app exports debugging state to `window.VIEWER`:
-| Property | Type | Set By | Description |
-|----------|------|--------|-------------|
-| `window.VIEWER.app` | `App` | `app.js` at DOMContentLoaded | Full App instance |
-| `window.VIEWER.scene` | `THREE.Object3D` | `Viewer.setContent()` | Current model scene graph |
-| `window.VIEWER.json` | `GLTF` | `Viewer.load()` | Raw parsed glTF object from GLTFLoader |
+| Property | Type | Set By | Description |
+| --------------------- | ---------------- | ---------------------------- | -------------------------------------- |
+| `window.VIEWER.app` | `App` | `app.js` at DOMContentLoaded | Full App instance |
+| `window.VIEWER.scene` | `THREE.Object3D` | `Viewer.setContent()` | Current model scene graph |
+| `window.VIEWER.json` | `GLTF` | `Viewer.load()` | Raw parsed glTF object from GLTFLoader |
The WebGL renderer is also available at `window.renderer`.
@@ -571,7 +581,7 @@ The WebGL renderer is also available at `window.renderer`.
```javascript
// List all meshes
-window.VIEWER.scene.traverse(n => n.isMesh && console.log(n.name, n));
+window.VIEWER.scene.traverse((n) => n.isMesh && console.log(n.name, n));
// Get renderer stats
window.VIEWER.app.viewer.renderer.info;
@@ -580,9 +590,7 @@ window.VIEWER.app.viewer.renderer.info;
window.VIEWER.app.viewer.defaultCamera.position.toArray();
// Force play animation clip by index
-window.VIEWER.app.viewer.mixer.clipAction(
- window.VIEWER.app.viewer.clips[0]
-).play();
+window.VIEWER.app.viewer.mixer.clipAction(window.VIEWER.app.viewer.clips[0]).play();
// Change background color programmatically
window.VIEWER.app.viewer.state.bgColor = '#ff0000';
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 96afb65f5..cea26afd7 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -87,16 +87,18 @@ When a user drops a multi-file glTF (e.g., `scene.gltf` + `scene.bin` + textures
```javascript
MANAGER.setURLModifier((url, path) => {
- const normalizedURL = rootPath + decodeURI(url)
- .replace(baseURL, '')
- .replace(/^(\.?\/)/, '');
-
- if (assetMap.has(normalizedURL)) {
- const blob = assetMap.get(normalizedURL);
- return URL.createObjectURL(blob); // Serve from local blob
- }
-
- return (path || '') + url; // Fall back to network fetch
+ const normalizedURL =
+ rootPath +
+ decodeURI(url)
+ .replace(baseURL, '')
+ .replace(/^(\.?\/)/, '');
+
+ if (assetMap.has(normalizedURL)) {
+ const blob = assetMap.get(normalizedURL);
+ return URL.createObjectURL(blob); // Serve from local blob
+ }
+
+ return (path || '') + url; // Fall back to network fetch
});
```
@@ -123,15 +125,15 @@ requestAnimationFrame(this.animate)
The application controller. Creates the dropzone, viewer, and validator. Routes user interactions.
-| Method | Description |
-|--------|-------------|
-| `constructor(el, location)` | Parses hash params, sets up dropzone, loads initial model |
-| `createDropzone()` | Binds SimpleDropzone to `.wrap` element and `#file-input` |
-| `createViewer()` | Instantiates `Viewer` on first model load |
-| `load(fileMap)` | Finds root glTF/GLB in a dropped fileset and calls `view()` |
-| `view(rootFile, rootPath, fileMap)` | Passes model to `Viewer.load()` and `Validator.validate()` |
-| `onError(error)` | Normalizes error messages and shows `window.alert()` |
-| `showSpinner()` / `hideSpinner()` | Toggle loading indicator visibility |
+| Method | Description |
+| ----------------------------------- | ----------------------------------------------------------- |
+| `constructor(el, location)` | Parses hash params, sets up dropzone, loads initial model |
+| `createDropzone()` | Binds SimpleDropzone to `.wrap` element and `#file-input` |
+| `createViewer()` | Instantiates `Viewer` on first model load |
+| `load(fileMap)` | Finds root glTF/GLB in a dropped fileset and calls `view()` |
+| `view(rootFile, rootPath, fileMap)` | Passes model to `Viewer.load()` and `Validator.validate()` |
+| `onError(error)` | Normalizes error messages and shows `window.alert()` |
+| `showSpinner()` / `hideSpinner()` | Toggle loading indicator visibility |
### `Viewer` — `src/viewer.js`
@@ -151,11 +153,11 @@ Exports a flat array of environment map definitions:
```javascript
[
- { id: '', name: 'None', path: null },
- { id: 'neutral', name: 'Neutral', path: null },
- { id: 'venice-sunset', name: 'Venice Sunset', path: '...1k.exr' },
- { id: 'footprint-court', name: 'Footprint Court', path: '...2k.exr' },
-]
+ { id: '', name: 'None', path: null },
+ { id: 'neutral', name: 'Neutral', path: null },
+ { id: 'venice-sunset', name: 'Venice Sunset', path: '...1k.exr' },
+ { id: 'footprint-court', name: 'Footprint Court', path: '...2k.exr' },
+];
```
- `id: ''` — no environment map applied
@@ -166,12 +168,12 @@ Exports a flat array of environment map definitions:
All components use [vhtml](https://github.com/developit/vhtml) — a JSX-compatible library that outputs plain HTML strings (no virtual DOM, no reactivity).
-| Component | File | Description |
-|-----------|------|-------------|
-| `Footer` | `footer.jsx` | Social links (X/Twitter, GitHub) and feedback link |
-| `ValidatorToggle` | `validator-toggle.jsx` | Status bar with severity color and dismiss button |
+| Component | File | Description |
+| ----------------- | ---------------------- | ---------------------------------------------------------- |
+| `Footer` | `footer.jsx` | Social links (X/Twitter, GitHub) and feedback link |
+| `ValidatorToggle` | `validator-toggle.jsx` | Status bar with severity color and dismiss button |
| `ValidatorReport` | `validator-report.jsx` | Full report with metadata, stats, extensions, issue tables |
-| `ValidatorTable` | `validator-table.jsx` | Color-coded table of issues (code, message, JSON pointer) |
+| `ValidatorTable` | `validator-table.jsx` | Color-coded table of issues (code, message, JSON pointer) |
---
@@ -181,9 +183,9 @@ All components use [vhtml](https://github.com/developit/vhtml) — a JSX-compati
```javascript
new WebGLRenderer({ antialias: true })
- .setClearColor(0xcccccc)
- .setPixelRatio(window.devicePixelRatio)
- .setSize(el.clientWidth, el.clientHeight)
+ .setClearColor(0xcccccc)
+ .setPixelRatio(window.devicePixelRatio)
+ .setSize(el.clientWidth, el.clientHeight);
```
### Camera
@@ -197,10 +199,10 @@ new WebGLRenderer({ antialias: true })
When the model does **not** contain embedded lights (`state.punctualLights = true`):
-| Light | Type | Default Intensity | Position |
-|-------|------|------------------|----------|
-| Ambient | `AmbientLight` | 0.3 | Attached to camera |
-| Directional | `DirectionalLight` | 0.8π ≈ 2.51 | `(0.5, 0, 0.866)` on camera |
+| Light | Type | Default Intensity | Position |
+| ----------- | ------------------ | ----------------- | --------------------------- |
+| Ambient | `AmbientLight` | 0.3 | Attached to camera |
+| Directional | `DirectionalLight` | 0.8π ≈ 2.51 | `(0.5, 0, 0.866)` on camera |
When the model **does** contain lights, punctual lights are disabled and the model's own lights are used.
@@ -208,12 +210,12 @@ Asset generator preset uses a single `HemisphereLight` instead.
### Loaders
-| Loader | CDN Source | Purpose |
-|--------|-----------|---------|
-| `GLTFLoader` | Bundled (three.js) | Core glTF 2.0 parser |
-| `DRACOLoader` | `unpkg.com/three@0.{REVISION}.x/examples/jsm/libs/draco/gltf/` | Draco mesh decompression |
-| `KTX2Loader` | `unpkg.com/three@0.{REVISION}.x/examples/jsm/libs/basis/` | KTX2/Basis Universal texture transcoding |
-| `MeshoptDecoder` | Bundled (three.js) | Meshopt compression decoding |
+| Loader | CDN Source | Purpose |
+| ---------------- | -------------------------------------------------------------- | ---------------------------------------- |
+| `GLTFLoader` | Bundled (three.js) | Core glTF 2.0 parser |
+| `DRACOLoader` | `unpkg.com/three@0.{REVISION}.x/examples/jsm/libs/draco/gltf/` | Draco mesh decompression |
+| `KTX2Loader` | `unpkg.com/three@0.{REVISION}.x/examples/jsm/libs/basis/` | KTX2/Basis Universal texture transcoding |
+| `MeshoptDecoder` | Bundled (three.js) | Meshopt compression decoding |
All loaders are shared singleton instances to avoid redundant initialization.
@@ -249,12 +251,12 @@ Validator.validate(fileURL, rootPath, assetMap, gltfResponse)
### Severity Levels
-| Level | Color | CSS Class | Meaning |
-|-------|-------|-----------|---------|
-| 0 | Red | `level-0` | Errors — spec violations |
-| 1 | Yellow | `level-1` | Warnings — potential issues |
-| 2 | Blue | — | Informational notes |
-| 3 | Green | — | Optimization hints |
+| Level | Color | CSS Class | Meaning |
+| ----- | ------ | --------- | --------------------------- |
+| 0 | Red | `level-0` | Errors — spec violations |
+| 1 | Yellow | `level-1` | Warnings — potential issues |
+| 2 | Blue | — | Informational notes |
+| 3 | Green | — | Optimization hints |
### Message Aggregation
@@ -311,20 +313,20 @@ Dynamic folders (Animation, Morph Targets, Cameras) have their controls rebuilt
All styles live in a single `style.css` file with clearly delineated sections:
-| Section | Description |
-|---------|-------------|
-| Base reset | `html, body` reset, dark background, Inter font |
-| Layout | Flexbox column: header → main (viewer + dropzone) |
-| Viewer | Full-bleed canvas container |
-| Axes | Fixed 100×100 px overlay, bottom-left, `pointer-events: none` |
-| Header | Sticky top bar, blur backdrop, 3.5rem height |
-| GUI wrap | Absolute positioning, right side, `pointer-events: none` on wrapper |
-| dat.gui overrides | Dark theme: `#0a0a0a` backgrounds, subtle borders |
-| Responsive (≤700px) | Collapsed header, hidden drop hint, 65vw max GUI width |
-| Footer | Absolute bottom-right, monospace, low opacity |
-| Upload button | Custom file input styling |
-| Validation report | Tables, toggle bar, severity colors |
-| Spinner | CSS-only pulsing circle animation |
+| Section | Description |
+| ------------------- | ------------------------------------------------------------------- |
+| Base reset | `html, body` reset, dark background, Inter font |
+| Layout | Flexbox column: header → main (viewer + dropzone) |
+| Viewer | Full-bleed canvas container |
+| Axes | Fixed 100×100 px overlay, bottom-left, `pointer-events: none` |
+| Header | Sticky top bar, blur backdrop, 3.5rem height |
+| GUI wrap | Absolute positioning, right side, `pointer-events: none` on wrapper |
+| dat.gui overrides | Dark theme: `#0a0a0a` backgrounds, subtle borders |
+| Responsive (≤700px) | Collapsed header, hidden drop hint, 65vw max GUI width |
+| Footer | Absolute bottom-right, monospace, low opacity |
+| Upload button | Custom file input styling |
+| Validation report | Tables, toggle bar, severity colors |
+| Spinner | CSS-only pulsing circle animation |
### Safe Area Support
diff --git a/docs/CZ_DEMO_FAILURE_MODES.md b/docs/CZ_DEMO_FAILURE_MODES.md
index bad8a3b83..ff4081e44 100644
--- a/docs/CZ_DEMO_FAILURE_MODES.md
+++ b/docs/CZ_DEMO_FAILURE_MODES.md
@@ -6,34 +6,35 @@ A comprehensive table of conceivable failures during the live CZ demo, their sym
## Failure Mode Reference Table
-| # | Failure Mode | Symptom | Likely Root Cause | Recovery Path | Time Cost | Severity |
-|---|---|---|---|---|---|---|
-| 1 | Avatar won't render | Black screen or loading spinner infinite | GLB 404, CORS error, or slow CDN | Check DevTools Network; if 404, restart server; if CORS, verify origin config; wait 30s or switch to `/cz/offline/` | 30-90s | HIGH |
-| 2 | MetaMask popup blocked | Click claim button; nothing happens | Browser popup blocker enabled | Allow popups in browser settings; click MetaMask extension icon | 20s | MEDIUM |
-| 3 | MetaMask not installed | No response to claim click; no wallet in toolbar | Fresh browser profile without MetaMask | Install MetaMask extension OR switch to `/cz?rehearsal=1` | 2m | MEDIUM |
-| 4 | Base Sepolia RPC congestion | Claim modal stuck on "Waiting for confirmation…" for > 45s | Network overload or node sync lag | Continue narrating feature; check Basescan for tx; if > 2 min, switch to `/cz?rehearsal=1` | 2-3m | MEDIUM |
-| 5 | Transaction fails (out of gas) | MetaMask shows "Transaction failed" or modal shows error | CZ's wallet has < required gas (e.g., < 0.01 ETH) | Acknowledge "we ran out of gas—this is why we fund wallets beforehand"; would auto-refuel on mainnet. Switch to `/cz?rehearsal=1` | 1m | HIGH |
-| 6 | Agent already claimed | Modal says "Already owned by 0x..." | Staging state carries over from previous rehearsal or live event | This is actually safe—just narrate "this agent is already claimed, but on mainnet this would be transferable." Continue. | 0s | LOW |
-| 7 | `/api/cz/identity` returns 404 | Footer shows "Not yet onchain" | Agent not yet registered on Base Sepolia (pre-onchain state) | Narrate: "Registration is coming this week. Let me show you the code." Skip Basescan step; focus on local demo | 0s | LOW |
-| 8 | Basescan / block explorer slow or down | Click to see agent registration; page hangs or 503 | Block explorer RPC congestion or outage | Close tab; continue narration without showing on-chain proof. Say "We'll check that after." Return to avatar demo. | 30-60s | MEDIUM |
-| 9 | Confetti library fails to load | Claim succeeds but no confetti animation | CDN down for confetti.js or bundle load fails | Visually confirm modal says "Claim successful" without animation; narrate "success confirmed"; not critical for messaging | 0s | LOW |
-| 10 | LobeHub iframe blank or unresponsive | Open LobeHub tab; shows white space or "Loading…" forever | postMessage origin mismatch, LobeHub build stale, or iframe blocked by CORS | Close LobeHub tab; skip step 7 (live chat). Narrate feature conceptually. Move to Q&A. | 1m | MEDIUM |
-| 11 | Venue wifi drops mid-demo | Network tab shows all requests failing; avatar frozen | WiFi router disconnects or signal lost | Switch to phone hotspot; wait 5s for DNS. If still down, open `/cz/offline/index.html` | 10-20s | MEDIUM |
-| 12 | Laptop overheating / GPU throttle | Avatar animation stutters, drops FPS, or becomes choppy | Sustained 100% GPU load (avatar morph targets on old hardware) | Reduce avatar animation loop, or show `/cz/offline/` (lighter load) instead | 30s | LOW |
-| 13 | MetaMask shows wrong chain | Approve signature in MetaMask; modal doesn't respond | Chain ID mismatch (MetaMask on Mainnet instead of Base Sepolia) | Click MetaMask icon; switch network to Base Sepolia. Re-try claim. | 30s | MEDIUM |
-| 14 | IPFS gateway timeout (if used for metadata) | Claim confirms but agent metadata never loads | IPFS node unreachable or rate-limited | This would affect only post-claim metadata fetch; doesn't block claim itself. Continue; metadata updates eventually. | 0s | LOW |
-| 15 | Browser tab crash | Demo tab goes white; full reload needed | Out-of-memory (large model), JavaScript exception, or OS kill | Force-reload tab (Ctrl+R or Cmd+R). Re-enter from bookmarks or history. | 20-30s | MEDIUM |
-| 16 | Console errors visible to audience | Audience sees red X icon in DevTools or hears beep | JavaScript error thrown (e.g., undefined variable, failed fetch) | Close DevTools before demo starts. If opened during: minimize it or explain "these are debug logs, not errors." | 0s | LOW |
-| 17 | Staging URL is down (502 / 503) | All requests to staging fail, page never loads | Vercel build failure, database connection error, or deployment rollback | Switch to production URL (if CZ is registered there). Narrate: "We're switching to the live instance." | 1-2m | HIGH |
-| 18 | JWT/session token expired | API calls return 401 Unauthorized | Session cookie or OAuth token expired (rare in 1-hour window; usually from T-24h to demo time) | Clear cookies: Ctrl+Shift+Delete → Clear site data. Reload. Re-authenticate if prompted. | 30s | LOW |
-| 19 | Avatar file too large / slow download | Avatar load time > 20s | GLB file oversized (should be < 5MB), CDN cache miss, or slow network | Wait. If > 30s: download pre-cached version from `/cz/offline/index.html` or restart server to clear CDN. | 30s | MEDIUM |
-| 20 | Claim button visually broken | Button text corrupted, styling off, or not clickable | CSS injection, missing stylesheet, or browser rendering bug | Reload page. If persists, check DevTools for CSS errors. Try incognito mode. | 20s | LOW |
+| # | Failure Mode | Symptom | Likely Root Cause | Recovery Path | Time Cost | Severity |
+| --- | ------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | --------- | -------- |
+| 1 | Avatar won't render | Black screen or loading spinner infinite | GLB 404, CORS error, or slow CDN | Check DevTools Network; if 404, restart server; if CORS, verify origin config; wait 30s or switch to `/cz/offline/` | 30-90s | HIGH |
+| 2 | MetaMask popup blocked | Click claim button; nothing happens | Browser popup blocker enabled | Allow popups in browser settings; click MetaMask extension icon | 20s | MEDIUM |
+| 3 | MetaMask not installed | No response to claim click; no wallet in toolbar | Fresh browser profile without MetaMask | Install MetaMask extension OR switch to `/cz?rehearsal=1` | 2m | MEDIUM |
+| 4 | Base Sepolia RPC congestion | Claim modal stuck on "Waiting for confirmation…" for > 45s | Network overload or node sync lag | Continue narrating feature; check Basescan for tx; if > 2 min, switch to `/cz?rehearsal=1` | 2-3m | MEDIUM |
+| 5 | Transaction fails (out of gas) | MetaMask shows "Transaction failed" or modal shows error | CZ's wallet has < required gas (e.g., < 0.01 ETH) | Acknowledge "we ran out of gas—this is why we fund wallets beforehand"; would auto-refuel on mainnet. Switch to `/cz?rehearsal=1` | 1m | HIGH |
+| 6 | Agent already claimed | Modal says "Already owned by 0x..." | Staging state carries over from previous rehearsal or live event | This is actually safe—just narrate "this agent is already claimed, but on mainnet this would be transferable." Continue. | 0s | LOW |
+| 7 | `/api/cz/identity` returns 404 | Footer shows "Not yet onchain" | Agent not yet registered on Base Sepolia (pre-onchain state) | Narrate: "Registration is coming this week. Let me show you the code." Skip Basescan step; focus on local demo | 0s | LOW |
+| 8 | Basescan / block explorer slow or down | Click to see agent registration; page hangs or 503 | Block explorer RPC congestion or outage | Close tab; continue narration without showing on-chain proof. Say "We'll check that after." Return to avatar demo. | 30-60s | MEDIUM |
+| 9 | Confetti library fails to load | Claim succeeds but no confetti animation | CDN down for confetti.js or bundle load fails | Visually confirm modal says "Claim successful" without animation; narrate "success confirmed"; not critical for messaging | 0s | LOW |
+| 10 | LobeHub iframe blank or unresponsive | Open LobeHub tab; shows white space or "Loading…" forever | postMessage origin mismatch, LobeHub build stale, or iframe blocked by CORS | Close LobeHub tab; skip step 7 (live chat). Narrate feature conceptually. Move to Q&A. | 1m | MEDIUM |
+| 11 | Venue wifi drops mid-demo | Network tab shows all requests failing; avatar frozen | WiFi router disconnects or signal lost | Switch to phone hotspot; wait 5s for DNS. If still down, open `/cz/offline/index.html` | 10-20s | MEDIUM |
+| 12 | Laptop overheating / GPU throttle | Avatar animation stutters, drops FPS, or becomes choppy | Sustained 100% GPU load (avatar morph targets on old hardware) | Reduce avatar animation loop, or show `/cz/offline/` (lighter load) instead | 30s | LOW |
+| 13 | MetaMask shows wrong chain | Approve signature in MetaMask; modal doesn't respond | Chain ID mismatch (MetaMask on Mainnet instead of Base Sepolia) | Click MetaMask icon; switch network to Base Sepolia. Re-try claim. | 30s | MEDIUM |
+| 14 | IPFS gateway timeout (if used for metadata) | Claim confirms but agent metadata never loads | IPFS node unreachable or rate-limited | This would affect only post-claim metadata fetch; doesn't block claim itself. Continue; metadata updates eventually. | 0s | LOW |
+| 15 | Browser tab crash | Demo tab goes white; full reload needed | Out-of-memory (large model), JavaScript exception, or OS kill | Force-reload tab (Ctrl+R or Cmd+R). Re-enter from bookmarks or history. | 20-30s | MEDIUM |
+| 16 | Console errors visible to audience | Audience sees red X icon in DevTools or hears beep | JavaScript error thrown (e.g., undefined variable, failed fetch) | Close DevTools before demo starts. If opened during: minimize it or explain "these are debug logs, not errors." | 0s | LOW |
+| 17 | Staging URL is down (502 / 503) | All requests to staging fail, page never loads | Vercel build failure, database connection error, or deployment rollback | Switch to production URL (if CZ is registered there). Narrate: "We're switching to the live instance." | 1-2m | HIGH |
+| 18 | JWT/session token expired | API calls return 401 Unauthorized | Session cookie or OAuth token expired (rare in 1-hour window; usually from T-24h to demo time) | Clear cookies: Ctrl+Shift+Delete → Clear site data. Reload. Re-authenticate if prompted. | 30s | LOW |
+| 19 | Avatar file too large / slow download | Avatar load time > 20s | GLB file oversized (should be < 5MB), CDN cache miss, or slow network | Wait. If > 30s: download pre-cached version from `/cz/offline/index.html` or restart server to clear CDN. | 30s | MEDIUM |
+| 20 | Claim button visually broken | Button text corrupted, styling off, or not clickable | CSS injection, missing stylesheet, or browser rendering bug | Reload page. If persists, check DevTools for CSS errors. Try incognito mode. | 20s | LOW |
---
## Mitigation Strategy by Severity
### HIGH (5 failures)
+
**Plan B required.** These block the demo or lose audience attention > 1 minute.
- **#1 Avatar won't render:** Pre-load `/cz/offline/index.html` in a second browser window as a hot-swap.
@@ -41,6 +42,7 @@ A comprehensive table of conceivable failures during the live CZ demo, their sym
- **#17 Staging down:** Know the production URL as a backup (if agent is onchain there).
### MEDIUM (10 failures)
+
**Workarounds exist.** These cost 10–90 seconds but don't kill the demo.
- **#2, #3 MetaMask issues:** Have `/cz?rehearsal=1` bookmarked. Rehearsal mode fakes the claim.
@@ -54,6 +56,7 @@ A comprehensive table of conceivable failures during the live CZ demo, their sym
- **#19 Avatar slow:** Pre-cache by loading `/cz` 30 minutes before.
### LOW (5 failures)
+
**Audience won't notice.** These are transparent or don't affect the demo flow.
- **#6, #7 Pre-onchain state:** Expected. Narrate accordingly.
@@ -110,6 +113,7 @@ If something fails during the actual demo, fill this out immediately after (for
```
Example:
+
```markdown
**Failure:** #4 — RPC Congestion
**Time in demo:** Step 5 (claim confirmation)
@@ -129,11 +133,11 @@ Example:
1. **Load staging 10 times** — warm cache, observe timing
2. **Claim with throwaway wallet** — succeed or fail intentionally
3. **Simulate each of failures #1–5** (highest severity):
- - Unplug wifi → open `/cz/offline/`
- - Clear MetaMask → observe what happens
- - Set gas to 0 in MetaMask → watch transaction fail
- - Stop the dev server → see 502 and fallback to production
- - Disable JavaScript in DevTools → avatar still renders (graceful degradation)
+ - Unplug wifi → open `/cz/offline/`
+ - Clear MetaMask → observe what happens
+ - Set gas to 0 in MetaMask → watch transaction fail
+ - Stop the dev server → see 502 and fallback to production
+ - Disable JavaScript in DevTools → avatar still renders (graceful degradation)
4. **Time the full demo** with stopwatch; hit < 5 minutes
5. **Record the run on your phone** — watch it back for UX gotchas
6. **Reset state** — delete cookies, seed phrases, etc. before handing off to the live operator
diff --git a/docs/CZ_DEMO_RUNBOOK.md b/docs/CZ_DEMO_RUNBOOK.md
index 8c58d30e1..76e374394 100644
--- a/docs/CZ_DEMO_RUNBOOK.md
+++ b/docs/CZ_DEMO_RUNBOOK.md
@@ -16,8 +16,8 @@ Live event runbook for the CZ agent demo. This is the operator's edge — when t
- [ ] Console clean on `/cz` load: `window.VIEWER.agent_protocol.history` shows no errors
- [ ] VPN / proxy disabled; public internet only
- [ ] Backup RPC endpoints saved locally:
- - Primary: Base Sepolia public RPC (e.g., `https://sepolia.base.org/`)
- - Secondary: Alchemy / Infura Base Sepolia endpoint (check rate limits)
+ - Primary: Base Sepolia public RPC (e.g., `https://sepolia.base.org/`)
+ - Secondary: Alchemy / Infura Base Sepolia endpoint (check rate limits)
---
@@ -29,10 +29,10 @@ Live event runbook for the CZ agent demo. This is the operator's edge — when t
- [ ] Hotspot phone ready (venue wifi fallback)
- [ ] `/cz` preloaded and avatar fully rendered; camera responds
- [ ] Dry-run entire demo flow with a throwaway wallet:
- 1. Load `/cz`
- 2. Click claim button (may fail; that's ok for this run)
- 3. Observe modal and any error state
- 4. Return to home state
+ 1. Load `/cz`
+ 2. Click claim button (may fail; that's ok for this run)
+ 3. Observe modal and any error state
+ 4. Return to home state
- [ ] Reset `/cz/state.json` to `pre-onchain` after dry-run
- [ ] Check browser DevTools for any JavaScript errors or failed network requests
- [ ] Stopwatch ready for timing each demo step
@@ -42,6 +42,7 @@ Live event runbook for the CZ agent demo. This is the operator's edge — when t
## Demo Sequence (9 steps, ≤ 5 minutes total)
### Step 1: Landing (15 seconds)
+
**Speaker:** "This is CZ. It's an agent. And it's onchain."
- Open browser to `https://staging-url.vercel.app/cz/`
@@ -50,15 +51,17 @@ Live event runbook for the CZ agent demo. This is the operator's edge — when t
- **Expected screen:** Full-screen avatar with claim button visible, footer shows chain/agent ID (if onchain)
### Step 2: Passport (30 seconds)
+
**Speaker:** "Every agent has a passport—an onchain registration. Let me show you."
- Click the agent address chip / footer link (if onchain)
- Basescan or Sepolia block explorer opens in new tab
- Show `AgentRegistered` event or registry entry
- **Expected screen:** Block explorer showing agent's ERC-8004 registration
-- *If pre-onchain:* Skip this step; say "Registration is coming this week."
+- _If pre-onchain:_ Skip this step; say "Registration is coming this week."
### Step 3: Claim Flow Begins (10 seconds)
+
**Speaker:** "CZ, can you claim this? Let's see."
- Back to CZ tab
@@ -67,6 +70,7 @@ Live event runbook for the CZ agent demo. This is the operator's edge — when t
- **Expected screen:** MetaMask signature request
### Step 4: Signature (15 seconds)
+
**Speaker:** "Signing the claim..."
- In MetaMask, approve the signature (not a tx, just a message signature)
@@ -75,6 +79,7 @@ Live event runbook for the CZ agent demo. This is the operator's edge — when t
- **Expected screen:** Spinning modal with confirmation text
### Step 5: Confirmation (30 seconds)
+
**Speaker:** "And it's confirmed. Confetti."
- Confetti animation plays
@@ -84,12 +89,14 @@ Live event runbook for the CZ agent demo. This is the operator's edge — when t
- **Expected screen:** Success state with tx hash and confetti
### Step 6: Close Modal (5 seconds)
+
**Speaker:** "Close."
- Click close button or tap outside modal
- **Expected screen:** Back to `/cz` main page with updated owner state
### Step 7: Live in LobeHub (60 seconds)
+
**Speaker:** "Now watch this in LobeHub, our plugin partner."
- Open second tab to LobeHub instance (pre-loaded, or navigate to hosted instance)
@@ -99,6 +106,7 @@ Live event runbook for the CZ agent demo. This is the operator's edge — when t
- **Expected screen:** LobeHub chat with agent, avatar responding
### Step 8: Empathy Layer (30 seconds)
+
**Speaker:** "Notice the avatar's expression. It reads emotion—that's the empathy layer."
- Observe subtle emotion shifts in avatar face as agent responds
@@ -106,6 +114,7 @@ Live event runbook for the CZ agent demo. This is the operator's edge — when t
- **Expected screen:** Avatar with visible emotion feedback
### Step 9: Close (10 seconds)
+
**Speaker:** "That's CZ. Questions?"
- Close tabs
@@ -119,9 +128,11 @@ Live event runbook for the CZ agent demo. This is the operator's edge — when t
## Fallbacks
### Fallback 1: Avatar Won't Render
+
**Symptom:** Avatar displays as blank or black, or loading spinner never stops.
**Likely cause:** GLB file 404, CORS error, or slow network.
**Response:**
+
1. Check DevTools Network tab for 404 on `/avatars/cz.glb`
2. If 404: Confirm file exists in `public/avatars/cz.glb`; restart dev server or redeploy
3. If CORS: Check that origin is in `ALLOWED_ORIGINS`
@@ -129,40 +140,48 @@ Live event runbook for the CZ agent demo. This is the operator's edge — when t
5. **Last resort:** Open `/cz/offline/index.html` in the same browser window; avatar is pre-bundled
### Fallback 2: Claim Transaction Pending > 45 Seconds
+
**Symptom:** Modal says "Waiting for confirmation…" and doesn't update.
**Likely cause:** Base Sepolia RPC congestion or node sync lag.
**Response:**
+
1. Continue narrating the feature while waiting (talk about onchain identity, wallets, etc.)
2. Check Basescan in a side window: search for the tx hash from MetaMask (if visible)
3. If tx is confirmed on-chain: Refresh the `/cz` page; state should update
4. If tx is still pending after 2 minutes:
- - Switch to fallback mode: Open `/cz?rehearsal=1` in a new tab
- - This shows a fake "already claimed" state without hitting the chain
- - Say: "We've pre-claimed this in rehearsal mode to keep the demo flowing."
+ - Switch to fallback mode: Open `/cz?rehearsal=1` in a new tab
+ - This shows a fake "already claimed" state without hitting the chain
+ - Say: "We've pre-claimed this in rehearsal mode to keep the demo flowing."
5. **Root cause investigation (later):** Check Vercel logs and Base Sepolia RPC status
### Fallback 3: MetaMask Popup Blocked
+
**Symptom:** User clicks claim button; nothing happens.
**Likely cause:** Browser popup blocker, or MetaMask extension not installed.
**Response:**
+
1. Check address bar for popup-blocker icon; allow popups for this origin
2. Reload the page and try claim again
3. If still blocked: Click the MetaMask extension icon in the toolbar directly; wallet should open
4. If MetaMask not installed: Say "MetaMask isn't installed on this profile. We'll skip the live signing." Switch to `/cz?rehearsal=1`
### Fallback 4: Internet Drops Mid-Demo
+
**Symptom:** Page loads fine, then network goes dead. Avatar frozen. Claim button unresponsive.
**Likely cause:** Venue wifi failed, or hotspot disconnected.
**Response:**
+
1. Switch to hotspot (phone tethering) if available; wait 5 seconds for DNS to stabilize
2. Reload `/cz` page
3. If still offline: Open `/cz/offline/index.html` (served from browser cache); avatar and state are fully pre-rendered
4. Say: "We're offline now, but the agent still renders thanks to our offline cache."
### Fallback 5: LobeHub Embed Blank or Unresponsive
+
**Symptom:** LobeHub iframe loads but shows blank white space, or chat doesn't respond.
**Likely cause:** `postMessage` origin mismatch, or LobeHub build is stale.
**Response:**
+
1. Check DevTools Console for `postMessage` security warnings (frame origin mismatch)
2. Close the LobeHub tab and skip to Q&A (Step 9)
3. Say: "LobeHub integration is still rolling out; let's focus on the agent itself."
@@ -205,6 +224,7 @@ If the demo hits a hard blocker (venue wifi down, RPC completely unavailable, la
## Demo Environment Setup (for the operator)
### Local / Staging Setup
+
```bash
# Ensure staging is deployed and healthy
npm run deploy
@@ -220,13 +240,15 @@ curl -s https://staging-url/api/cz/identity | jq .agentId
```
### Browser Setup
+
- Fresh profile (no extensions except MetaMask)
- MetaMask: CZ's seed imported, Base Sepolia selected
- Two tabs pre-loaded:
- 1. `https://staging-url/cz/`
- 2. `https://lobehub-instance/` (or bookmark ready to click)
+ 1. `https://staging-url/cz/`
+ 2. `https://lobehub-instance/` (or bookmark ready to click)
### Network Backup
+
```bash
# Save these endpoints locally for manual testing
PRIMARY_RPC="https://sepolia.base.org/"
@@ -242,18 +264,18 @@ curl -s -X POST $PRIMARY_RPC \
## Timing Reference
-| Step | Speaker Script | Duration | Expected State |
-|---|---|---|---|
-| 1 | Landing pitch | 15s | Avatar loaded, idle |
-| 2 | Passport / onchain | 30s | Block explorer or "coming soon" |
-| 3 | Claim begins | 10s | MetaMask popup |
-| 4 | Signing | 15s | Waiting for confirmation modal |
-| 5 | Success / confetti | 30s | Success modal + updated footer |
-| 6 | Close modal | 5s | Back to main page |
-| 7 | LobeHub live | 60s | Chat with avatar response |
-| 8 | Empathy layer | 30s | Avatar expressions visible |
-| 9 | Close / Q&A | 10s | Ready for questions |
-| **Total** | | **4m 45s** | |
+| Step | Speaker Script | Duration | Expected State |
+| --------- | ------------------ | ---------- | ------------------------------- |
+| 1 | Landing pitch | 15s | Avatar loaded, idle |
+| 2 | Passport / onchain | 30s | Block explorer or "coming soon" |
+| 3 | Claim begins | 10s | MetaMask popup |
+| 4 | Signing | 15s | Waiting for confirmation modal |
+| 5 | Success / confetti | 30s | Success modal + updated footer |
+| 6 | Close modal | 5s | Back to main page |
+| 7 | LobeHub live | 60s | Chat with avatar response |
+| 8 | Empathy layer | 30s | Avatar expressions visible |
+| 9 | Close / Q&A | 10s | Ready for questions |
+| **Total** | | **4m 45s** | |
---
diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md
index 00f49835f..d6d6c7a97 100644
--- a/docs/DEPLOYMENT.md
+++ b/docs/DEPLOYMENT.md
@@ -87,27 +87,27 @@ vercel --prod
```json
{
- "public": true,
- "routes": [
- {
- "src": "/assets/(.*)",
- "headers": { "cache-control": "max-age=604800, public" },
- "dest": "/assets/$1"
- },
- {
- "src": "/(.*)",
- "dest": "/public/$1"
- }
- ]
+ "public": true,
+ "routes": [
+ {
+ "src": "/assets/(.*)",
+ "headers": { "cache-control": "max-age=604800, public" },
+ "dest": "/assets/$1"
+ },
+ {
+ "src": "/(.*)",
+ "dest": "/public/$1"
+ }
+ ]
}
```
### Route Breakdown
-| Route | Behavior |
-|-------|----------|
+| Route | Behavior |
+| ----------- | ------------------------------------------------------- |
| `/assets/*` | Static assets served with 7-day cache (604,800 seconds) |
-| `/*` | Everything else rewrites to `/public/*` |
+| `/*` | Everything else rewrites to `/public/*` |
The `public: true` flag allows listing of the deployment.
@@ -119,24 +119,25 @@ The `public: true` flag allows listing of the deployment.
```json
[
- {
- "method": ["GET"],
- "origin": [
- "https://3dagent.vercel.app",
- "https://*.3dagent.vercel.app",
- "https://chat.sperax.io",
- "https://sperax-jam2emun9-moomsi.vercel.app",
- "https://sperax-iota.vercel.app",
- "http://localhost:*",
- "https://localhost:*"
- ],
- "responseHeader": ["Content-Type"],
- "maxAgeSeconds": 3600
- }
+ {
+ "method": ["GET"],
+ "origin": [
+ "https://3dagent.vercel.app",
+ "https://*.3dagent.vercel.app",
+ "https://chat.sperax.io",
+ "https://sperax-jam2emun9-moomsi.vercel.app",
+ "https://sperax-iota.vercel.app",
+ "http://localhost:*",
+ "https://localhost:*"
+ ],
+ "responseHeader": ["Content-Type"],
+ "maxAgeSeconds": 3600
+ }
]
```
This allows:
+
- The production domain and all subdomains
- Partner domains (Sperax)
- Local development on any port
@@ -158,8 +159,8 @@ The production deployment uses `3dagent.vercel.app`. To use a custom domain:
1. Add the domain in the Vercel dashboard under **Settings → Domains**
2. Configure DNS:
- - **A record:** `76.76.21.21`
- - **CNAME:** `cname.vercel-dns.com`
+ - **A record:** `76.76.21.21`
+ - **CNAME:** `cname.vercel-dns.com`
3. Vercel automatically provisions an SSL certificate
---
@@ -170,18 +171,19 @@ The production deployment uses `3dagent.vercel.app`. To use a custom domain:
```html
<iframe
- src="https://3dagent.vercel.app/#model=https://your-cdn.com/model.glb&kiosk=true"
- width="100%"
- height="600"
- frameborder="0"
- allow="autoplay; fullscreen"
- style="border: none;"
+ src="https://3dagent.vercel.app/#model=https://your-cdn.com/model.glb&kiosk=true"
+ width="100%"
+ height="600"
+ frameborder="0"
+ allow="autoplay; fullscreen"
+ style="border: none;"
></iframe>
```
### Kiosk Mode
Add `kiosk=true` to the hash to:
+
- Hide the top header bar
- Auto-close the dat.gui panel
- Hide the validation toggle
@@ -275,10 +277,10 @@ docker run -p 8080:80 3d-agent
The app loads decoder libraries from unpkg at runtime:
-| Library | CDN URL Pattern |
-|---------|----------------|
-| Draco decoder | `https://unpkg.com/three@0.{REVISION}.x/examples/jsm/libs/draco/gltf/` |
-| KTX2/Basis transcoder | `https://unpkg.com/three@0.{REVISION}.x/examples/jsm/libs/basis/` |
+| Library | CDN URL Pattern |
+| --------------------- | ---------------------------------------------------------------------- |
+| Draco decoder | `https://unpkg.com/three@0.{REVISION}.x/examples/jsm/libs/draco/gltf/` |
+| KTX2/Basis transcoder | `https://unpkg.com/three@0.{REVISION}.x/examples/jsm/libs/basis/` |
These are versioned to the installed three.js revision, so they automatically match.
@@ -286,27 +288,28 @@ These are versioned to the installed three.js revision, so they automatically ma
Environment maps are loaded from Google Cloud Storage:
-| Map | URL |
-|-----|-----|
-| Venice Sunset | `https://storage.googleapis.com/donmccurdy-static/venice_sunset_1k.exr` |
+| Map | URL |
+| --------------- | ------------------------------------------------------------------------- |
+| Venice Sunset | `https://storage.googleapis.com/donmccurdy-static/venice_sunset_1k.exr` |
| Footprint Court | `https://storage.googleapis.com/donmccurdy-static/footprint_court_2k.exr` |
For self-hosting, download these files and update the paths in `src/environments.js`.
### Caching Strategy
-| Resource | Cache Duration |
-|----------|---------------|
-| `/assets/*` | 7 days (`max-age=604800`) |
-| Decoder libraries (unpkg) | CDN-controlled |
-| HDR maps (GCS) | CDN-controlled |
-| Application bundles | Content-hashed by Vite |
+| Resource | Cache Duration |
+| ------------------------- | ------------------------- |
+| `/assets/*` | 7 days (`max-age=604800`) |
+| Decoder libraries (unpkg) | CDN-controlled |
+| HDR maps (GCS) | CDN-controlled |
+| Application bundles | Content-hashed by Vite |
---
## Environment Variables
3D Agent does not require any environment variables. All configuration is done via:
+
- URL hash parameters (runtime)
- `src/environments.js` (build-time)
- `vercel.json` (deployment)
@@ -325,6 +328,7 @@ NODE_OPTIONS=--max-old-space-size=4096 npm run build
### Model doesn't load (CORS error)
Check the browser console for CORS errors. The model URL must either:
+
- Be on the same domain as the app
- Include proper `Access-Control-Allow-Origin` headers
@@ -335,6 +339,7 @@ Verify that `vercel.json` routing is correct. The `/(.*) → /public/$1` rewrite
### Draco models fail to load
Draco decoders are loaded from unpkg. If the CDN is down or blocked:
+
1. Download the Draco decoder files
2. Serve them locally
3. Update the `DRACO_LOADER.setDecoderPath()` call in `src/viewer.js`
@@ -342,6 +347,7 @@ Draco decoders are loaded from unpkg. If the CDN is down or blocked:
### Environment maps don't appear
EXR files are large. Check:
+
- Network tab for failed requests
- Console for `EXRLoader` errors
- That the GCS URLs are accessible from your deployment
diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md
index c4cd60f91..0f2329b73 100644
--- a/docs/DEVELOPMENT.md
+++ b/docs/DEVELOPMENT.md
@@ -28,6 +28,7 @@ npm install
```
**Requirements:**
+
- Node.js ≥ 18
- A browser with WebGL 2.0 support (Chrome, Firefox, Edge)
@@ -80,14 +81,14 @@ Open [http://localhost:3000](http://localhost:3000).
### Available Scripts
-| Script | Command | Description |
-|--------|---------|-------------|
-| `dev` | `vite --port 3000` | Dev server with HMR |
-| `build` | `vite build` | Production build to `dist/` |
-| `clean` | `rm -rf dist/* \|\| true` | Remove build output |
-| `test` | `node test/gen_test.js` | Run test suite |
-| `deploy` | `npm run build && vercel --prod` | Build and deploy |
-| `postversion` | `git push && git push --tags` | Auto-push after version bump |
+| Script | Command | Description |
+| ------------- | -------------------------------- | ---------------------------- |
+| `dev` | `vite --port 3000` | Dev server with HMR |
+| `build` | `vite build` | Production build to `dist/` |
+| `clean` | `rm -rf dist/* \|\| true` | Remove build output |
+| `test` | `node test/gen_test.js` | Run test suite |
+| `deploy` | `npm run build && vercel --prod` | Build and deploy |
+| `postversion` | `git push && git push --tags` | Auto-push after version bump |
---
@@ -124,6 +125,7 @@ npx prettier --check .
```
On `DOMContentLoaded`, `app.js` instantiates the `App` class, which:
+
1. Parses URL hash parameters
2. Sets up drag-and-drop
3. Loads the default or specified model
@@ -219,8 +221,8 @@ The `Validator` class runs independently of the viewer. When a model loads:
```javascript
this.state = {
- // ... existing state
- opacity: 1.0,
+ // ... existing state
+ opacity: 1.0,
};
```
@@ -235,8 +237,8 @@ opacityCtrl.onChange(() => this.updateDisplay());
```javascript
traverseMaterials(this.content, (material) => {
- material.opacity = this.state.opacity;
- material.transparent = this.state.opacity < 1;
+ material.opacity = this.state.opacity;
+ material.transparent = this.state.opacity < 1;
});
```
@@ -249,14 +251,16 @@ import vhtml from 'vhtml';
/** @jsx vhtml */
export function MyComponent({ title, items }) {
- return (
- <div class="my-component">
- <h2>{title}</h2>
- <ul>
- {items.map(item => <li>{item}</li>)}
- </ul>
- </div>
- );
+ return (
+ <div class="my-component">
+ <h2>{title}</h2>
+ <ul>
+ {items.map((item) => (
+ <li>{item}</li>
+ ))}
+ </ul>
+ </div>
+ );
}
```
@@ -286,8 +290,8 @@ Replace `/avatars/cz.glb` with the path to your model. Place the file in `public
```javascript
const hash = location.hash ? queryString.parse(location.hash) : {};
this.options = {
- // ... existing options
- myParam: hash.myParam || 'default',
+ // ... existing options
+ myParam: hash.myParam || 'default',
};
```
@@ -302,9 +306,9 @@ this.options = {
The app exports state to `window.VIEWER` for console debugging:
```javascript
-window.VIEWER.app // App instance (access viewer, validator, options)
-window.VIEWER.scene // Current THREE.Object3D scene graph
-window.VIEWER.json // Raw glTF JSON from GLTFLoader
+window.VIEWER.app; // App instance (access viewer, validator, options)
+window.VIEWER.scene; // Current THREE.Object3D scene graph
+window.VIEWER.json; // Raw glTF JSON from GLTFLoader
```
### Scene Graph Logging
@@ -312,7 +316,7 @@ window.VIEWER.json // Raw glTF JSON from GLTFLoader
Every model load prints the scene graph to the console:
```
-▼ <Scene>
+▼ <Scene>
▼ <Group> MyModel
▼ <Mesh> Body
▼ <Mesh> Head
@@ -333,7 +337,7 @@ console.table(window.VIEWER.app.viewer.renderer.info.memory);
const v = window.VIEWER.app.viewer;
// List all clips
-v.clips.forEach(c => console.log(c.name, c.duration + 's'));
+v.clips.forEach((c) => console.log(c.name, c.duration + 's'));
// Play a specific clip
v.mixer.clipAction(v.clips[0]).play();
@@ -345,27 +349,27 @@ v.mixer.setTime(1.5);
### Morph Target Debugging
```javascript
-window.VIEWER.scene.traverse(node => {
- if (node.morphTargetInfluences) {
- console.log(node.name, node.morphTargetDictionary);
- }
+window.VIEWER.scene.traverse((node) => {
+ if (node.morphTargetInfluences) {
+ console.log(node.name, node.morphTargetDictionary);
+ }
});
```
### Material Inspection
```javascript
-window.VIEWER.scene.traverse(node => {
- if (node.isMesh) {
- const mat = node.material;
- console.log(node.name, {
- type: mat.type,
- color: mat.color?.getHexString(),
- roughness: mat.roughness,
- metalness: mat.metalness,
- map: mat.map?.name,
- });
- }
+window.VIEWER.scene.traverse((node) => {
+ if (node.isMesh) {
+ const mat = node.material;
+ console.log(node.name, {
+ type: mat.type,
+ color: mat.color?.getHexString(),
+ roughness: mat.roughness,
+ metalness: mat.metalness,
+ map: mat.map?.name,
+ });
+ }
});
```
@@ -375,23 +379,23 @@ window.VIEWER.scene.traverse(node => {
### Requirements
-| Feature | Minimum |
-|---------|---------|
-| WebGL 2.0 | Required |
-| File API | Required (`File`, `FileReader`, `FileList`, `Blob`) |
-| ES Modules | Required (`<script type="module">`) |
+| Feature | Minimum |
+| ----------- | --------------------------------------------------- |
+| WebGL 2.0 | Required |
+| File API | Required (`File`, `FileReader`, `FileList`, `Blob`) |
+| ES Modules | Required (`<script type="module">`) |
| CSS `env()` | Needed for safe-area support (graceful degradation) |
### Tested Browsers
-| Browser | Status |
-|---------|--------|
-| Chrome 90+ | Fully supported |
-| Firefox 90+ | Fully supported |
-| Edge (Chromium) 90+ | Fully supported |
-| Safari 15+ | Mostly works; drag-and-drop has known limitations |
-| Mobile Chrome (Android) | Works; GUI auto-collapses |
-| Mobile Safari (iOS) | Works with limitations; iOS detection via `isIOS()` |
+| Browser | Status |
+| ----------------------- | --------------------------------------------------- |
+| Chrome 90+ | Fully supported |
+| Firefox 90+ | Fully supported |
+| Edge (Chromium) 90+ | Fully supported |
+| Safari 15+ | Mostly works; drag-and-drop has known limitations |
+| Mobile Chrome (Android) | Works; GUI auto-collapses |
+| Mobile Safari (iOS) | Works with limitations; iOS detection via `isIOS()` |
### Known Limitations
@@ -406,6 +410,7 @@ window.VIEWER.scene.traverse(node => {
### Memory Management
The `Viewer.clear()` method properly disposes:
+
- All geometries (`geometry.dispose()`)
- All textures (`texture.dispose()`, except `envMap`)
- All materials (`material.dispose()`)
diff --git a/docs/MCP.md b/docs/MCP.md
index ebc645eb7..26c1bbbd8 100644
--- a/docs/MCP.md
+++ b/docs/MCP.md
@@ -11,13 +11,13 @@ MCP-compatible app — list, render, and manage a user's 3D avatars.
## Tools
-| Name | Scope | Description |
-| --- | --- | --- |
-| `list_my_avatars` | `avatars:read` | Paginated list of the caller's avatars. |
-| `get_avatar` | `avatars:read` | Fetch one avatar by `id` or `slug`. |
-| `search_public_avatars` | — | Discover public avatars (no auth needed for read). |
+| Name | Scope | Description |
+| ----------------------- | ---------------- | ----------------------------------------------------------------------- |
+| `list_my_avatars` | `avatars:read` | Paginated list of the caller's avatars. |
+| `get_avatar` | `avatars:read` | Fetch one avatar by `id` or `slug`. |
+| `search_public_avatars` | — | Discover public avatars (no auth needed for read). |
| `render_avatar` | `avatars:read` | Returns ready-to-embed `<model-viewer>` HTML. Use as a Claude artifact. |
-| `delete_avatar` | `avatars:delete` | Soft-delete an avatar you own. |
+| `delete_avatar` | `avatars:delete` | Soft-delete an avatar you own. |
## Auth: OAuth 2.1
@@ -31,7 +31,7 @@ Claude handles the handshake automatically via dynamic client registration:
Metadata discovery:
- Authorization Server: `GET /.well-known/oauth-authorization-server`
-- Protected Resource: `GET /.well-known/oauth-protected-resource`
+- Protected Resource: `GET /.well-known/oauth-protected-resource`
On a 401 from `/api/mcp`, the `WWW-Authenticate` header points clients at the
protected-resource metadata URL, per RFC 9728.
@@ -39,7 +39,7 @@ protected-resource metadata URL, per RFC 9728.
## Auth: API key
For server-to-server usage (scripts, agents, CI), create a key in the dashboard
-under *API keys* and pass it as a bearer token:
+under _API keys_ and pass it as a bearer token:
```bash
curl -X POST https://3dagent.vercel.app/api/mcp \
@@ -62,12 +62,12 @@ and emit the returned HTML as an inline artifact.
## Plans & quotas
-| Plan | Avatars | Size / file | Total storage | MCP calls / day |
-| --- | --- | --- | --- | --- |
-| Free | 10 | 25 MB | 250 MB | 1 000 |
-| Pro | 500 | 50 MB | 25 GB | 50 000 |
-| Team | 5 000 | 100 MB | 500 GB | 500 000 |
-| Enterprise | 100 000| 500 MB | 10 TB | 10 000 000|
+| Plan | Avatars | Size / file | Total storage | MCP calls / day |
+| ---------- | ------- | ----------- | ------------- | --------------- |
+| Free | 10 | 25 MB | 250 MB | 1 000 |
+| Pro | 500 | 50 MB | 25 GB | 50 000 |
+| Team | 5 000 | 100 MB | 500 GB | 500 000 |
+| Enterprise | 100 000 | 500 MB | 10 TB | 10 000 000 |
## Credits
diff --git a/docs/SETUP.md b/docs/SETUP.md
index 1dfb357de..2263f458a 100644
--- a/docs/SETUP.md
+++ b/docs/SETUP.md
@@ -69,7 +69,7 @@ npm run deploy
storage + requests, both cheap.
- **Database:** Neon autoscales; for very high traffic, switch `sql` to the
pooled connection string or consider branching for heavy tenants.
-- **Rate limits:** Defaults in [api/_lib/rate-limit.js](../api/_lib/rate-limit.js) —
+- **Rate limits:** Defaults in [api/\_lib/rate-limit.js](../api/_lib/rate-limit.js) —
tune once real traffic patterns emerge. Per-plan daily caps are enforced from
the `plan_quotas` table.
- **Observability:** Every tool call writes to `usage_events`. Build dashboards
diff --git a/docs/VALIDATION_DEPLOY.md b/docs/VALIDATION_DEPLOY.md
index 11b849e9e..da6917ce5 100644
--- a/docs/VALIDATION_DEPLOY.md
+++ b/docs/VALIDATION_DEPLOY.md
@@ -8,13 +8,13 @@ Deploys `ValidationRegistry` to 15 mainnet chains via CREATE2 (deterministic add
## Deployment Overview
-| Property | Value |
-|---|---|
-| **Script** | `contracts/script/DeployValidationMainnet.s.sol` |
-| **Constructor args** | `(identityRegistry: 0x8004A169FB4a3325136EB29fA0ceB6D2e539a432, owner: msg.sender)` |
-| **CREATE2 salt** | `keccak256(abi.encodePacked("ValidationRegistry", uint256(1)))` |
-| **Expected address** | See "Expected Addresses" section below |
-| **Time to deploy all chains** | ~2–4 hours (wait for block finality between chains) |
+| Property | Value |
+| ----------------------------- | ----------------------------------------------------------------------------------- |
+| **Script** | `contracts/script/DeployValidationMainnet.s.sol` |
+| **Constructor args** | `(identityRegistry: 0x8004A169FB4a3325136EB29fA0ceB6D2e539a432, owner: msg.sender)` |
+| **CREATE2 salt** | `keccak256(abi.encodePacked("ValidationRegistry", uint256(1)))` |
+| **Expected address** | See "Expected Addresses" section below |
+| **Time to deploy all chains** | ~2–4 hours (wait for block finality between chains) |
---
@@ -37,6 +37,7 @@ forge test
```
Output should show all tests passing:
+
```
...
Test result: ok. X passed; 0 failed; 0 skipped
@@ -80,6 +81,7 @@ forge script script/DeployValidationMainnet.s.sol:DeployValidationMainnet \
```
Expected output:
+
```
Expected ValidationRegistry: 0x...
IdentityRegistry: 0x8004A169FB4a3325136EB29fA0ceB6D2e539a432
@@ -296,23 +298,23 @@ Expected address: **identical to all others**.
## Reference: RPC Endpoints & Etherscan Keys
-| Chain | Chain ID | RPC Endpoint | Etherscan URL | API Key Env Var |
-|---|---|---|---|---|
-| Ethereum | 1 | https://ethereum-rpc.publicnode.com | https://etherscan.io | `ETHEREUM_ETHERSCAN_API_KEY` |
-| Base | 8453 | https://base-rpc.publicnode.com | https://basescan.org | `BASE_ETHERSCAN_API_KEY` |
-| Optimism | 10 | https://optimism-rpc.publicnode.com | https://optimistic.etherscan.io | `OPTIMISM_ETHERSCAN_API_KEY` |
-| Arbitrum One | 42161 | https://arbitrum-rpc.publicnode.com | https://arbiscan.io | `ARBITRUM_ETHERSCAN_API_KEY` |
-| Polygon | 137 | https://polygon-rpc.publicnode.com | https://polygonscan.com | `POLYGON_ETHERSCAN_API_KEY` |
-| BNB Chain | 56 | https://bsc-rpc.publicnode.com | https://bscscan.com | `BSC_ETHERSCAN_API_KEY` |
-| Avalanche C-Chain | 43114 | https://avalanche-c-chain-rpc.publicnode.com | https://snowtrace.io | `AVALANCHE_ETHERSCAN_API_KEY` |
-| Gnosis | 100 | https://gnosis-rpc.publicnode.com | https://gnosisscan.io | `GNOSIS_ETHERSCAN_API_KEY` |
-| Linea | 59144 | https://linea-rpc.publicnode.com | https://lineascan.build | `LINEA_ETHERSCAN_API_KEY` |
-| Scroll | 534352 | https://scroll-rpc.publicnode.com | https://scrollscan.com | `SCROLL_ETHERSCAN_API_KEY` |
-| zkSync Era | 324 | https://zksync-mainnet-rpc.publicnode.com | https://explorer.zksync.io | `ZKSYNC_ETHERSCAN_API_KEY` |
-| Mantle | 5000 | https://mantle-rpc.publicnode.com | https://mantlescan.xyz | `MANTLE_ETHERSCAN_API_KEY` |
-| Celo | 42220 | https://celo-mainnet-rpc.publicnode.com | https://celoscan.io | `CELO_ETHERSCAN_API_KEY` |
-| Ink | TBD | https://ink-mainnet-rpc.publicnode.com | TBD | `INK_ETHERSCAN_API_KEY` |
-| Unichain | TBD | https://unichain-mainnet-rpc.publicnode.com | TBD | `UNICHAIN_ETHERSCAN_API_KEY` |
+| Chain | Chain ID | RPC Endpoint | Etherscan URL | API Key Env Var |
+| ----------------- | -------- | -------------------------------------------- | ------------------------------- | ----------------------------- |
+| Ethereum | 1 | https://ethereum-rpc.publicnode.com | https://etherscan.io | `ETHEREUM_ETHERSCAN_API_KEY` |
+| Base | 8453 | https://base-rpc.publicnode.com | https://basescan.org | `BASE_ETHERSCAN_API_KEY` |
+| Optimism | 10 | https://optimism-rpc.publicnode.com | https://optimistic.etherscan.io | `OPTIMISM_ETHERSCAN_API_KEY` |
+| Arbitrum One | 42161 | https://arbitrum-rpc.publicnode.com | https://arbiscan.io | `ARBITRUM_ETHERSCAN_API_KEY` |
+| Polygon | 137 | https://polygon-rpc.publicnode.com | https://polygonscan.com | `POLYGON_ETHERSCAN_API_KEY` |
+| BNB Chain | 56 | https://bsc-rpc.publicnode.com | https://bscscan.com | `BSC_ETHERSCAN_API_KEY` |
+| Avalanche C-Chain | 43114 | https://avalanche-c-chain-rpc.publicnode.com | https://snowtrace.io | `AVALANCHE_ETHERSCAN_API_KEY` |
+| Gnosis | 100 | https://gnosis-rpc.publicnode.com | https://gnosisscan.io | `GNOSIS_ETHERSCAN_API_KEY` |
+| Linea | 59144 | https://linea-rpc.publicnode.com | https://lineascan.build | `LINEA_ETHERSCAN_API_KEY` |
+| Scroll | 534352 | https://scroll-rpc.publicnode.com | https://scrollscan.com | `SCROLL_ETHERSCAN_API_KEY` |
+| zkSync Era | 324 | https://zksync-mainnet-rpc.publicnode.com | https://explorer.zksync.io | `ZKSYNC_ETHERSCAN_API_KEY` |
+| Mantle | 5000 | https://mantle-rpc.publicnode.com | https://mantlescan.xyz | `MANTLE_ETHERSCAN_API_KEY` |
+| Celo | 42220 | https://celo-mainnet-rpc.publicnode.com | https://celoscan.io | `CELO_ETHERSCAN_API_KEY` |
+| Ink | TBD | https://ink-mainnet-rpc.publicnode.com | TBD | `INK_ETHERSCAN_API_KEY` |
+| Unichain | TBD | https://unichain-mainnet-rpc.publicnode.com | TBD | `UNICHAIN_ETHERSCAN_API_KEY` |
---
@@ -381,9 +383,9 @@ Once deployed and verified on all 15 chains, update [src/erc8004/abi.js](../src/
```javascript
const MAINNET = {
- identityRegistry: '0x8004A169FB4a3325136EB29fA0ceB6D2e539a432',
- reputationRegistry: '0x8004BAa17C55a88189AE136b182e5fdA19dE9b63',
- validationRegistry: '0x8004Cb1BF31DAf7788923b405b754f57acEB42ab', // <- ADD THIS LINE
+ identityRegistry: '0x8004A169FB4a3325136EB29fA0ceB6D2e539a432',
+ reputationRegistry: '0x8004BAa17C55a88189AE136b182e5fdA19dE9b63',
+ validationRegistry: '0x8004Cb1BF31DAf7788923b405b754f57acEB42ab', // <- ADD THIS LINE
};
```
@@ -401,6 +403,7 @@ Update `REGISTRY_DEPLOYMENTS` object—it should already have entries for all 15
4. **Update frontend** to the new address.
**Cost of rollback:** Extra gas on failed chains. Avoid by:
+
- Dry-running thoroughly
- Testing with a throwaway wallet first
- Deploying during low-gas hours on L1s
@@ -409,24 +412,24 @@ Update `REGISTRY_DEPLOYMENTS` object—it should already have entries for all 15
## Total Gas Cost Estimate
-| Chain | Est. Gas (ETH) | Notes |
-|---|---|---|
-| Ethereum | 0.5 | L1, highly variable (gwei) |
-| Base | 0.01 | L2, very cheap |
-| Optimism | 0.01 | L2, very cheap |
-| Arbitrum One | 0.01 | L2, very cheap |
-| Polygon | 0.001 | Sidechain, cheap |
-| BNB Chain | 0.002 | Cheap |
-| Avalanche | 0.005 | Moderate |
-| Gnosis | 0.002 | Cheap |
-| Linea | 0.005 | L2, moderate |
-| Scroll | 0.005 | L2, moderate |
-| zkSync Era | 0.005 | L2, moderate |
-| Mantle | 0.005 | L2, moderate |
-| Celo | 0.001 | Cheap |
-| Ink | 0.01 | L2, moderate |
-| Unichain | 0.01 | L2, moderate |
-| **TOTAL** | **≈ 0.6–0.8 ETH** | Varies by network congestion |
+| Chain | Est. Gas (ETH) | Notes |
+| ------------ | ----------------- | ---------------------------- |
+| Ethereum | 0.5 | L1, highly variable (gwei) |
+| Base | 0.01 | L2, very cheap |
+| Optimism | 0.01 | L2, very cheap |
+| Arbitrum One | 0.01 | L2, very cheap |
+| Polygon | 0.001 | Sidechain, cheap |
+| BNB Chain | 0.002 | Cheap |
+| Avalanche | 0.005 | Moderate |
+| Gnosis | 0.002 | Cheap |
+| Linea | 0.005 | L2, moderate |
+| Scroll | 0.005 | L2, moderate |
+| zkSync Era | 0.005 | L2, moderate |
+| Mantle | 0.005 | L2, moderate |
+| Celo | 0.001 | Cheap |
+| Ink | 0.01 | L2, moderate |
+| Unichain | 0.01 | L2, moderate |
+| **TOTAL** | **≈ 0.6–0.8 ETH** | Varies by network congestion |
(Etherscan verification is usually free; if using a paid RPC, factor in API costs.)
@@ -435,20 +438,24 @@ Update `REGISTRY_DEPLOYMENTS` object—it should already have entries for all 15
## Troubleshooting
### "Address already exists"
+
- Chain was already deployed. Use `cast call` to verify the address has the correct `identityRegistry`.
- If already correct, update frontend and move on.
- If incorrect, use rollback procedure above.
### "Private key insufficient gas"
+
- Deployer wallet is out of gas on that chain.
- Bridge more ETH and retry.
### "Etherscan verification failed"
+
- API key is wrong or rate-limited.
- Verify manually by checking constructor args on Etherscan UI.
- Retry later.
### "Constructor arg mismatch"
+
- The `identityRegistry` or `owner` address in the script doesn't match what you passed.
- Check [contracts/script/DeployValidationMainnet.s.sol](../contracts/script/DeployValidationMainnet.s.sol) for hardcoded addresses.
- Do not change them without user approval.
diff --git a/docs/WIDGETS.md b/docs/WIDGETS.md
index 843192b6f..0075cb68d 100644
--- a/docs/WIDGETS.md
+++ b/docs/WIDGETS.md
@@ -31,13 +31,13 @@ A widget is a saved bundle of: an avatar (GLB stored in R2), a widget type (turn
## Widget types
-| Type | Best for | Default size |
-|---|---|---|
-| `turntable` | Hero banners, product showcases. Auto-rotate, no UI. | 600 × 600 |
-| `animation-gallery` | Showcasing a rigged avatar's animation library. | 720 × 720 |
-| `talking-agent` | Embodied chat — your agent on your site. | 420 × 600 |
-| `passport` | On-chain identity card backed by ERC-8004. | 480 × 560 |
-| `hotspot-tour` | Annotated 3D scenes with clickable POIs. | 800 × 600 |
+| Type | Best for | Default size |
+| ------------------- | ---------------------------------------------------- | ------------ |
+| `turntable` | Hero banners, product showcases. Auto-rotate, no UI. | 600 × 600 |
+| `animation-gallery` | Showcasing a rigged avatar's animation library. | 720 × 720 |
+| `talking-agent` | Embodied chat — your agent on your site. | 420 × 600 |
+| `passport` | On-chain identity card backed by ERC-8004. | 480 × 560 |
+| `hotspot-tour` | Annotated 3D scenes with clickable POIs. | 800 × 600 |
---
@@ -45,11 +45,11 @@ A widget is a saved bundle of: an avatar (GLB stored in R2), a widget type (turn
Every widget has three canonical URLs.
-| URL | Use it for |
-|---|---|
-| `https://3dagent.vercel.app/w/<id>` | Sharing in Slack/Discord/X — server-rendered with rich OG card. |
-| `https://3dagent.vercel.app/#widget=<id>` | The SPA viewer with the widget config applied. |
-| `https://3dagent.vercel.app/api/widgets/<id>/og` | The 1200×630 preview image. |
+| URL | Use it for |
+| ------------------------------------------------ | --------------------------------------------------------------- |
+| `https://3dagent.vercel.app/w/<id>` | Sharing in Slack/Discord/X — server-rendered with rich OG card. |
+| `https://3dagent.vercel.app/#widget=<id>` | The SPA viewer with the widget config applied. |
+| `https://3dagent.vercel.app/api/widgets/<id>/og` | The 1200×630 preview image. |
`/w/<id>` is the recommended share URL — bots get an OG preview, browsers fall through to the SPA.
@@ -57,13 +57,13 @@ Every widget has three canonical URLs.
The viewer supports the following hash params (combine with `&`):
-| Param | Type | Description |
-|---|---|---|
-| `widget` | `string` | Loads a saved widget by id. |
-| `model` | `string` | Loads a raw GLB by URL (mutually exclusive with `widget`). |
-| `kiosk` | `boolean` | Hides the header chrome for clean iframe embeds. |
-| `cameraPosition` | `x,y,z` | Comma-separated camera position override. |
-| `preset` | `string` | HDR environment preset name. |
+| Param | Type | Description |
+| ---------------- | --------- | ---------------------------------------------------------- |
+| `widget` | `string` | Loads a saved widget by id. |
+| `model` | `string` | Loads a raw GLB by URL (mutually exclusive with `widget`). |
+| `kiosk` | `boolean` | Hides the header chrome for clean iframe embeds. |
+| `cameraPosition` | `x,y,z` | Comma-separated camera position override. |
+| `preset` | `string` | HDR environment preset name. |
---
@@ -78,10 +78,12 @@ The viewer supports the following hash params (combine with `&`):
height="600"
style="border:0;border-radius:12px;max-width:100%"
allow="autoplay; xr-spatial-tracking; clipboard-write"
- loading="lazy"></iframe>
+ loading="lazy"
+></iframe>
```
**Size guidance:**
+
- Turntable / hotspot-tour: 1:1 or 4:3 — let the user breathe.
- Talking-agent: 7:10 portrait — chat needs vertical space.
- Passport: anything ≥ 360 × 480.
@@ -106,14 +108,14 @@ Widgets communicate with the parent page via `window.postMessage`. **Always chec
### iframe → parent
-| Event | Payload | When |
-|---|---|---|
-| `widget:ready` | `{ id, type }` | Widget runtime has booted. |
-| `widget:load` | `{ id, model_url }` | Underlying GLB loaded successfully. |
-| `widget:load:error` | `{ id, error }` | GLB or config failed to load. |
-| `widget:chat:message` | `{ role, content }` | Talking-agent only — a new chat turn. |
-| `widget:hotspot:open` | `{ id, label }` | Hotspot-tour only — visitor opened a POI. |
-| `widget:resize` | `{ width, height }` | Widget reports its preferred size. |
+| Event | Payload | When |
+| --------------------- | ------------------- | ----------------------------------------- |
+| `widget:ready` | `{ id, type }` | Widget runtime has booted. |
+| `widget:load` | `{ id, model_url }` | Underlying GLB loaded successfully. |
+| `widget:load:error` | `{ id, error }` | GLB or config failed to load. |
+| `widget:chat:message` | `{ role, content }` | Talking-agent only — a new chat turn. |
+| `widget:hotspot:open` | `{ id, label }` | Hotspot-tour only — visitor opened a POI. |
+| `widget:resize` | `{ width, height }` | Widget reports its preferred size. |
```js
window.addEventListener('message', (e) => {
@@ -126,16 +128,16 @@ window.addEventListener('message', (e) => {
### parent → iframe
-| Event | Payload | Effect |
-|---|---|---|
-| `widget:config` | `{ background, accent, autoRotate, ... }` | Live-update brand config (used by the Studio preview). |
-| `widget:command` | `{ command, args }` | Trigger a runtime action (e.g. `play_clip`, `wave`). |
+| Event | Payload | Effect |
+| ---------------- | ----------------------------------------- | ------------------------------------------------------ |
+| `widget:config` | `{ background, accent, autoRotate, ... }` | Live-update brand config (used by the Studio preview). |
+| `widget:command` | `{ command, args }` | Trigger a runtime action (e.g. `play_clip`, `wave`). |
```js
const iframe = document.querySelector('iframe');
iframe.contentWindow.postMessage(
{ type: 'widget:config', config: { background: '#ff00aa' } },
- 'https://3dagent.vercel.app'
+ 'https://3dagent.vercel.app',
);
```
@@ -150,11 +152,15 @@ Every widget URL serves rich-preview metadata.
`/w/<id>` returns a server-rendered HTML page with:
```html
-<meta property="og:title" content="…">
-<meta property="og:description" content="…">
-<meta property="og:image" content="https://3dagent.vercel.app/api/widgets/<id>/og">
-<meta name="twitter:card" content="summary_large_image">
-<link rel="alternate" type="application/json+oembed" href="https://3dagent.vercel.app/api/widgets/oembed?url=…">
+<meta property="og:title" content="…" />
+<meta property="og:description" content="…" />
+<meta property="og:image" content="https://3dagent.vercel.app/api/widgets/<id>/og" />
+<meta name="twitter:card" content="summary_large_image" />
+<link
+ rel="alternate"
+ type="application/json+oembed"
+ href="https://3dagent.vercel.app/api/widgets/oembed?url=…"
+/>
```
### oEmbed endpoint
@@ -208,15 +214,16 @@ The widget iframe makes outbound requests to `3dagent.vercel.app` and (for some
We log a minimal first-party event per widget load:
-| Field | Source |
-|---|---|
-| `widget_id` | the widget being loaded |
-| `type` | the widget type |
-| `country` | Vercel edge header (`x-vercel-ip-country`) |
+| Field | Source |
+| -------------- | -------------------------------------------------- |
+| `widget_id` | the widget being loaded |
+| `type` | the widget type |
+| `country` | Vercel edge header (`x-vercel-ip-country`) |
| `referer_host` | hostname of the embedding page (no path, no query) |
-| `created_at` | timestamp |
+| `created_at` | timestamp |
We **do not** log:
+
- IP addresses
- User agent strings
- Cookies (we don't set any on the embed)
@@ -247,4 +254,4 @@ The widget owner can see aggregated counts in their [Dashboard](https://3dagent.
- iOS Safari may require a user gesture before `speechSynthesis.getVoices()` returns voices for the talking-agent widget.
- Some browser extensions (uBlock + strict mode) will block the analytics POST. The widget itself still works.
-- Embedding inside a parent iframe that's *also* sandboxed can break WebGL initialization. Add `allow-scripts allow-same-origin` to the parent sandbox.
+- Embedding inside a parent iframe that's _also_ sandboxed can break WebGL initialization. Add `allow-scripts allow-same-origin` to the parent sandbox.
diff --git a/docs/avaturn-docs.md b/docs/avaturn-docs.md
index 26858cd1d..28934194c 100644
--- a/docs/avaturn-docs.md
+++ b/docs/avaturn-docs.md
@@ -27,6 +27,7 @@ Users can register at developer.avaturn.me to begin using Avaturn at no cost wit
Straightforward instructions for importing Avaturn avatars into Blender, leveraging the software's native support for GLTF 2.0 format.
Three-Step Import Process:
+
1. Initiate Import: Access Blender's import function to load your GLB file
2. Configure Settings: When the import dialog appears, set the bone direction parameter to "Blender" before finalizing the import process
3. Completion: Your avatar assets are now ready for use within your Blender project
@@ -40,6 +41,7 @@ If the imported avatar appears gray or you're uncertain whether textures have lo
Avaturn exports avatars in GLB format, which Unity doesn't natively support. The documentation recommends using the "GLTFast" package to load GLB files either during editing or while the application runs.
Key Recommendations:
+
- Apply an environment map to prevent metallic clothing from appearing black
- GLTFast version 5.2 was tested, though other versions should work
@@ -54,12 +56,13 @@ Two distinct import processes depending on your Unreal Engine version.
For UE 5.1 and newer: The procedure is streamlined since these versions natively support GLB files. Users simply need to drag and drop it onto the content manager to complete the import.
For UE 5.0 and earlier: Since native GLB support is unavailable, the workflow requires additional steps:
+
1. Download a GLB avatar from Avaturn
2. Convert the file to FBX format using Avaturn's dedicated converter tool, ensuring "Unreal" is selected in the converter settings
3. Import the FBX into the content browser with specific settings:
- - Normals import method set to "Import Normals"
- - Import uniform scale at 100.0 (adjustable based on asset scale)
- - Enable "Invert normal maps"
+ - Normals import method set to "Import Normals"
+ - Import uniform scale at 100.0 (adjustable based on asset scale)
+ - Enable "Invert normal maps"
4. Finalize the process, with occasional manual transparency corrections needed for eyewear elements
### 2.4 Meta Spark Studio
@@ -75,6 +78,7 @@ Brief documentation page with reference to a video tutorial contributed by Max G
Avaturn exports 3D avatars in GLTF 2.0 format to ensure compatibility across different engines. For legacy workflows that require FBX files, Avaturn provides a conversion tool that outputs FBX files with separate texture maps, though materials may require manual adjustment.
Why GLTF 2.0 is Preferred:
+
- Open standard developed by the Khronos Group (versus Autodesk's proprietary FBX)
- JSON-based structure for readability and easier debugging
- Optimized for real-time rendering in web and VR applications
@@ -84,6 +88,7 @@ Why GLTF 2.0 is Preferred:
- Extensible architecture for custom metadata
Engine-Specific Guidance:
+
- Unity: Strongly recommends using GLTFast package to load GLB directly, avoiding conversion
- Unreal Engine: Versions 5.1+ support native GLB importing. Older versions requiring FBX need specific import settings: Import Normals method, 100.0 uniform scale, and inverted normal maps enabled
@@ -100,6 +105,7 @@ Avaturn exports in GLTF 2.0 format to ensure the 3D model looks well in every en
While Avaturn exports models in GLB format, Mixamo cannot directly read this format. Converting GLB to FBX may cause issues, so the guide recommends an alternative approach:
Recommended Process:
+
1. Download a pre-tested Avaturn avatar in FBX format from their assets
2. Import that model into Mixamo and select desired animations
3. Export the animated avatar, choosing "without skin" for Blender or "with skin" for Unity
@@ -118,6 +124,7 @@ The key insight is that instead of converting your exported avatar, users should
Avaturn functions as an integrable plugin for applications, games, and metaverse platforms. The workflow is straightforward: users trigger an avatar configurator within a game, customize their avatar, and the game then receives the completed avatar file.
Available SDKs and Integration Options:
+
- Unity integration
- Unreal Engine support
- HTML and JavaScript implementation
@@ -132,10 +139,12 @@ Basic integration follows published tutorials at no cost. Developers seeking adv
**URL:** https://docs.avaturn.me/docs/integration/bodies/
Avatar Types:
+
- **T1 Avatars:** Static faces that provide the most realistic avatar. Cannot use face bones or blendshapes for facial animation.
- **T2 Avatars:** Feature separate eyeballs and mouthhole structures, enabling facial animation through ARKit blendshapes and visemes. Slightly reduced recognizability compared to T1 models.
Body Shape Types: Two body presets are available: v2023 and v2024.
+
- **v2023:** The original body design iteration with unique skeletons per body shape that vary significantly from each other.
- **v2024:** An improved version with nearly identical skeletons across body shapes. "Skeletons are identical everywhere, but have a bit of stretch/compression of the shoulder joints. Legs, arm length, head bone is the same!" This design makes animation work easier while maintaining shape variety.
@@ -148,10 +157,12 @@ Both versions come in Female and Male configurations.
Instructions for integrating the Avaturn avatar creation tool into web applications.
Quick Start:
+
1. Add a div element with the ID `avaturn-sdk-container` to your HTML markup.
2. Include a module script that imports the AvaturnSDK from a CDN. Initialize the SDK with your custom subdomain and set up an event listener for the export event.
Key Configuration Details:
+
- **Subdomain Setup:** Create a project and obtain your own subdomain through developer.avaturn.me rather than using the limited "demo" subdomain.
- **Export Callback:** The SDK triggers an "export" event when users click the "Next" button, returning the generated avatar data for processing.
- **Styling Options:** CSS can be applied to the container element, with optional custom class names for the internal iframe.
@@ -173,11 +184,13 @@ Required Configuration: Replace the demo subdomain with your own, created throug
**URL:** https://docs.avaturn.me/docs/integration/web/sdk/introduction/
Key Features:
+
- Receive callbacks on user actions (garment change, body change, export)
- Customize the list of assets available for a particular user
- Create custom UI for the avatar editor through programmatic asset switching
Prerequisites and Installation:
+
- Create a project at the developer portal and activate API access
- Install via npm: `npm install @avaturn/sdk`
@@ -190,6 +203,7 @@ Basic Implementation: Obtain a session link from the `/v1/sessions/new` API endp
**URL:** https://docs.avaturn.me/docs/integration/web/sdk/callbacks/
The Avaturn Web SDK enables developers to implement callbacks that respond to user interactions:
+
- Asset changed
- Body changed
- Avatar exported
@@ -198,9 +212,9 @@ Implementation: Obtain a URL using the `/v1/sessions/new` API request, then pass
```js
const scene = await sdk.init(container, {
- url: '<URL_RETURNED_BY_AVATURN_API>',
- iframeClassName: '<CSS_CLASS_NAME_FOR_IFRAME>',
- disableUi: false,
+ url: '<URL_RETURNED_BY_AVATURN_API>',
+ iframeClassName: '<CSS_CLASS_NAME_FOR_IFRAME>',
+ disableUi: false,
});
```
@@ -223,6 +237,7 @@ Once disabled, the SDK provides access to asset and body data through specific m
Supported Platforms: WebGL and Android/iOS integrations. Windows/Mac Standalone apps possible but require contacting the company directly.
Available Resources:
+
- Integration tutorial explaining how to add Avaturn to games
- SDK and sample code available on GitHub, supporting Android, iOS, and WebGL
- WebGL demo showcasing runtime avatar replacement
@@ -233,6 +248,7 @@ Available Resources:
**URL:** https://docs.avaturn.me/docs/integration/unreal/
Introduction to Avaturn integration for Unreal Engine 5.0 and later. Two SDK options:
+
1. Web-view based SDK — a browser-integrated approach
2. Native SDK — a direct integration method (newer)
@@ -249,6 +265,7 @@ Key Resources: Google Drive folder containing the SDK, demo project source code,
The framework builds upon the Ready Player Me Unreal framework. Copy necessary files from the downloaded demo project into your own projects.
Troubleshooting:
+
- Material loading failures in packaged builds: solved via cooking plugin directories
- Multiplayer functionality requiring proper httpURL configuration in developer settings
@@ -277,6 +294,7 @@ Update the URL initialization in `WebViewController.swift` from the demo domain
**URL:** https://docs.avaturn.me/docs/integration/api/introduction/
Key Capabilities:
+
- Integrate Avaturn while bypassing the sign-in interface (use your own authentication method)
- Customize user workflows
- Upload selfies directly rather than requiring users to scan through the UI
@@ -285,6 +303,7 @@ Key Capabilities:
- Utilize native SDKs for Unreal and Unity
Getting Started:
+
1. Create a project at the developer portal
2. Generate an API authentication token
3. Maintain a paid subscription plan — **the API is not available on the free plan**
@@ -300,6 +319,7 @@ Getting Started:
"Avaturn can be easily customized and extended with additional content."
Key Features:
+
- Upload personalized looks and accessories
- Adjust UI color schemes
- Modify the avatar's environment setting
@@ -322,6 +342,7 @@ Avatar Resources: Two downloadable template avatars — male body template and f
**URL:** https://docs.avaturn.me/docs/ux_customization/assets/clothing/
Key Requirements:
+
- Create an alpha mask for the avatar to hide parts covered by clothing (prevents visibility issues from deformations)
- Asset must share the same skeleton as the avatar with correct skinning weights (manual painting recommended)
- The mesh and avatar require proper alignment with identity global transforms
@@ -340,6 +361,7 @@ Pipeline is the same as for clothing. Key distinction: footwear textures are com
**URL:** https://docs.avaturn.me/docs/ux_customization/assets/eyewear/
Guidelines:
+
- "The lower polycount the better" for mesh optimization
- Glasses typically consist of two parts: frame and lens
- Lens uses translucent material; frame uses another material type
diff --git a/embed.html b/embed.html
index a8c79bb14..b5f320190 100644
--- a/embed.html
+++ b/embed.html
@@ -1,26 +1,36 @@
<!doctype html>
<html lang="en">
-<head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <title>Embed editor — 3D Agent</title>
- <style>
- html, body { margin: 0; padding: 0; height: 100%; background: #0b0d10; color: #fff; font-family: system-ui, sans-serif; }
- #root { height: 100vh; }
- </style>
-</head>
-<body>
- <div id="root"></div>
- <script type="module">
- import { mountEmbedEditor } from './src/editor/embed-editor.js';
- const url = new URL(location.href);
- mountEmbedEditor(document.getElementById('root'), {
- src: url.searchParams.get('src') || '',
- mode: url.searchParams.get('mode') || 'floating',
- position: url.searchParams.get('position') || 'bottom-right',
- width: url.searchParams.get('width') || '320px',
- height: url.searchParams.get('height') || '420px',
- });
- </script>
-</body>
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Embed editor — 3D Agent</title>
+ <style>
+ html,
+ body {
+ margin: 0;
+ padding: 0;
+ height: 100%;
+ background: #0b0d10;
+ color: #fff;
+ font-family: system-ui, sans-serif;
+ }
+ #root {
+ height: 100vh;
+ }
+ </style>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module">
+ import { mountEmbedEditor } from './src/editor/embed-editor.js';
+ const url = new URL(location.href);
+ mountEmbedEditor(document.getElementById('root'), {
+ src: url.searchParams.get('src') || '',
+ mode: url.searchParams.get('mode') || 'floating',
+ position: url.searchParams.get('position') || 'bottom-right',
+ width: url.searchParams.get('width') || '320px',
+ height: url.searchParams.get('height') || '420px',
+ });
+ </script>
+ </body>
</html>
diff --git a/examples/coach-leo/manifest.json b/examples/coach-leo/manifest.json
index 53d90aeeb..ee4c18fe6 100644
--- a/examples/coach-leo/manifest.json
+++ b/examples/coach-leo/manifest.json
@@ -22,9 +22,7 @@
"tts": { "provider": "browser", "rate": 1.05 },
"stt": { "provider": "browser", "language": "en-US" }
},
- "skills": [
- { "uri": "../skills/wave/", "version": "0.1.0" }
- ],
+ "skills": [{ "uri": "../skills/wave/", "version": "0.1.0" }],
"memory": {
"mode": "local",
"index": "memory/MEMORY.md",
diff --git a/examples/minimal.html b/examples/minimal.html
index 75d2167c4..c986b3a83 100644
--- a/examples/minimal.html
+++ b/examples/minimal.html
@@ -1,65 +1,101 @@
<!doctype html>
<html lang="en">
-<head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <title>Minimal embed — 3D Agent</title>
- <style>
- body { margin: 0; font: 16px/1.5 system-ui, sans-serif; background: #fafafa; color: #111; }
- main { max-width: 720px; margin: 0 auto; padding: 64px 32px; }
- h1 { font-size: 40px; margin: 0 0 16px; }
- p { color: #4b5563; }
- .two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 24px; margin: 48px 0; }
- .card { background: white; border: 1px solid #e5e7eb; border-radius: 16px; padding: 24px; }
- .card h2 { margin-top: 0; font-size: 18px; }
- pre { background: #0a0d12; color: #a7f3d0; padding: 16px; border-radius: 8px; overflow-x: auto; font-size: 13px; }
- </style>
-</head>
-<body>
- <main>
- <h1>Hello from the page</h1>
- <p>
- This is a plain HTML page. The floating agent in the corner was added
- with a single <code>&lt;agent-3d&gt;</code> tag — no build step, no framework.
- </p>
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Minimal embed — 3D Agent</title>
+ <style>
+ body {
+ margin: 0;
+ font:
+ 16px/1.5 system-ui,
+ sans-serif;
+ background: #fafafa;
+ color: #111;
+ }
+ main {
+ max-width: 720px;
+ margin: 0 auto;
+ padding: 64px 32px;
+ }
+ h1 {
+ font-size: 40px;
+ margin: 0 0 16px;
+ }
+ p {
+ color: #4b5563;
+ }
+ .two-col {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 24px;
+ margin: 48px 0;
+ }
+ .card {
+ background: white;
+ border: 1px solid #e5e7eb;
+ border-radius: 16px;
+ padding: 24px;
+ }
+ .card h2 {
+ margin-top: 0;
+ font-size: 18px;
+ }
+ pre {
+ background: #0a0d12;
+ color: #a7f3d0;
+ padding: 16px;
+ border-radius: 8px;
+ overflow-x: auto;
+ font-size: 13px;
+ }
+ </style>
+ </head>
+ <body>
+ <main>
+ <h1>Hello from the page</h1>
+ <p>
+ This is a plain HTML page. The floating agent in the corner was added with a single
+ <code>&lt;agent-3d&gt;</code> tag — no build step, no framework.
+ </p>
- <div class="two-col">
- <div class="card">
- <h2>Inline embed</h2>
- <p>The agent below is embedded inline, flowing with the page content.</p>
- <agent-3d
- body="/avatars/cz.glb"
- instructions="You are a friendly 3D guide."
- width="100%"
- height="320px"
- brain="claude-opus-4-6"
- ></agent-3d>
- </div>
- <div class="card">
- <h2>The snippet</h2>
- <pre>&lt;agent-3d
+ <div class="two-col">
+ <div class="card">
+ <h2>Inline embed</h2>
+ <p>The agent below is embedded inline, flowing with the page content.</p>
+ <agent-3d
+ body="/avatars/cz.glb"
+ instructions="You are a friendly 3D guide."
+ width="100%"
+ height="320px"
+ brain="claude-opus-4-6"
+ ></agent-3d>
+ </div>
+ <div class="card">
+ <h2>The snippet</h2>
+ <pre>
+&lt;agent-3d
body="/avatars/cz.glb"
width="100%"
height="320px"
-&gt;&lt;/agent-3d&gt;</pre>
+&gt;&lt;/agent-3d&gt;</pre
+ >
+ </div>
</div>
- </div>
- <p>
- Floating bubble in the corner ↘ — like a chatbot, but embodied.
- </p>
- </main>
+ <p>Floating bubble in the corner ↘ — like a chatbot, but embodied.</p>
+ </main>
- <!-- Floating bubble — bottom-right of the viewport -->
- <agent-3d
- body="/avatars/cz.glb"
- instructions="You are a cheerful 3D greeter. Wave when users say hi."
- mode="floating"
- position="bottom-right"
- width="320px"
- height="420px"
- ></agent-3d>
+ <!-- Floating bubble — bottom-right of the viewport -->
+ <agent-3d
+ body="/avatars/cz.glb"
+ instructions="You are a cheerful 3D greeter. Wave when users say hi."
+ mode="floating"
+ position="bottom-right"
+ width="320px"
+ height="420px"
+ ></agent-3d>
- <script type="module" src="../src/element.js"></script>
-</body>
+ <script type="module" src="../src/element.js"></script>
+ </body>
</html>
diff --git a/examples/skills/wave/SKILL.md b/examples/skills/wave/SKILL.md
index 9af24dcc6..44fb8dd22 100644
--- a/examples/skills/wave/SKILL.md
+++ b/examples/skills/wave/SKILL.md
@@ -2,9 +2,9 @@
name: wave
description: Wave at the user with context-appropriate enthusiasm.
triggers:
- - user_greeting
- - user_farewell
- - introduction
+ - user_greeting
+ - user_farewell
+ - introduction
cost: low
---
diff --git a/examples/two-agents.html b/examples/two-agents.html
index a6fc29962..7b65e6004 100644
--- a/examples/two-agents.html
+++ b/examples/two-agents.html
@@ -5,19 +5,73 @@
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>&lt;agent-stage&gt; — two agents, one scene</title>
<style>
- body { margin: 0; font-family: system-ui, sans-serif; background: #0f0f0f; color: #e9e9e9; padding: 24px; }
- h1 { margin: 0 0 8px; font-weight: 500; }
- p { color: #b0b0b0; margin: 4px 0 16px; }
- agent-stage { display: block; width: 100%; height: 540px; background: #1a1a1a; border-radius: 8px; overflow: hidden; }
- .row { display: flex; gap: 8px; margin-top: 16px; }
- .row input { flex: 1; padding: 10px 14px; border-radius: 999px; border: 1px solid #333; background: #111; color: #eee; font: 14px system-ui; }
- .row button { padding: 10px 18px; border-radius: 999px; border: 0; background: #3b82f6; color: white; font: 14px system-ui; cursor: pointer; }
- .log { font: 12px/1.5 ui-monospace, Menlo, monospace; color: #8fd4a4; background: #111; border-radius: 6px; padding: 12px; margin-top: 16px; max-height: 180px; overflow-y: auto; }
+ body {
+ margin: 0;
+ font-family: system-ui, sans-serif;
+ background: #0f0f0f;
+ color: #e9e9e9;
+ padding: 24px;
+ }
+ h1 {
+ margin: 0 0 8px;
+ font-weight: 500;
+ }
+ p {
+ color: #b0b0b0;
+ margin: 4px 0 16px;
+ }
+ agent-stage {
+ display: block;
+ width: 100%;
+ height: 540px;
+ background: #1a1a1a;
+ border-radius: 8px;
+ overflow: hidden;
+ }
+ .row {
+ display: flex;
+ gap: 8px;
+ margin-top: 16px;
+ }
+ .row input {
+ flex: 1;
+ padding: 10px 14px;
+ border-radius: 999px;
+ border: 1px solid #333;
+ background: #111;
+ color: #eee;
+ font: 14px system-ui;
+ }
+ .row button {
+ padding: 10px 18px;
+ border-radius: 999px;
+ border: 0;
+ background: #3b82f6;
+ color: white;
+ font: 14px system-ui;
+ cursor: pointer;
+ }
+ .log {
+ font:
+ 12px/1.5 ui-monospace,
+ Menlo,
+ monospace;
+ color: #8fd4a4;
+ background: #111;
+ border-radius: 6px;
+ padding: 12px;
+ margin-top: 16px;
+ max-height: 180px;
+ overflow-y: auto;
+ }
</style>
</head>
<body>
<h1>&lt;agent-stage&gt; demo — two agents, one canvas</h1>
- <p>Both agents render in a single WebGL context. Each keeps its own brain, memory, and chat chrome.</p>
+ <p>
+ Both agents render in a single WebGL context. Each keeps its own brain, memory, and chat
+ chrome.
+ </p>
<agent-stage id="stage" formation="row">
<agent-3d
@@ -38,7 +92,11 @@
</agent-stage>
<div class="row">
- <input id="prompt" placeholder="Ask Leo to say hi to Mira..." value="Say hi to Mira and ask her how she's doing." />
+ <input
+ id="prompt"
+ placeholder="Ask Leo to say hi to Mira..."
+ value="Say hi to Mira and ask her how she's doing."
+ />
<button id="send">Send to Leo</button>
<button id="broadcast">Broadcast</button>
</div>
@@ -59,12 +117,22 @@
log.scrollTop = log.scrollHeight;
};
- stage.addEventListener('stage:agent-joined', (e) => line(`joined: ${e.detail.agentId}`));
+ stage.addEventListener('stage:agent-joined', (e) =>
+ line(`joined: ${e.detail.agentId}`),
+ );
stage.addEventListener('stage:agent-left', (e) => line(`left: ${e.detail.agentId}`));
- stage.addEventListener('stage:message', (e) => line(`stage msg from ${e.detail.from}: ${JSON.stringify(e.detail.event)}`));
+ stage.addEventListener('stage:message', (e) =>
+ line(`stage msg from ${e.detail.from}: ${JSON.stringify(e.detail.event)}`),
+ );
for (const el of [leo, mira]) {
- el.addEventListener('brain:message', (e) => line(`[${el.id}/${e.detail.role}] ${e.detail.content || ''}`));
- el.addEventListener('skill:tool-called', (e) => line(`[${el.id}] tool ${e.detail.tool}(${JSON.stringify(e.detail.args)}) -> ${JSON.stringify(e.detail.result)}`));
+ el.addEventListener('brain:message', (e) =>
+ line(`[${el.id}/${e.detail.role}] ${e.detail.content || ''}`),
+ );
+ el.addEventListener('skill:tool-called', (e) =>
+ line(
+ `[${el.id}] tool ${e.detail.tool}(${JSON.stringify(e.detail.args)}) -> ${JSON.stringify(e.detail.result)}`,
+ ),
+ );
}
document.getElementById('send').addEventListener('click', () => {
diff --git a/examples/web-component.html b/examples/web-component.html
index e208f2634..9d8972581 100644
--- a/examples/web-component.html
+++ b/examples/web-component.html
@@ -5,12 +5,42 @@
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>&lt;mv-viewer&gt; Custom Element demo</title>
<style>
- body { margin: 0; font-family: system-ui, sans-serif; background: #0f0f0f; color: #e9e9e9; padding: 24px; }
- h1 { margin: 0 0 8px; font-weight: 500; }
- h2 { margin: 24px 0 8px; font-size: 14px; font-weight: 500; color: #9a9a9a; text-transform: uppercase; letter-spacing: 0.05em; }
- .grid { display: grid; gap: 16px; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); }
- .log { font-family: ui-monospace, Menlo, monospace; font-size: 12px; color: #8fd4a4; background: #1a1a1a; border-radius: 4px; padding: 8px 12px; min-height: 24px; }
- mv-viewer { border-radius: 8px; }
+ body {
+ margin: 0;
+ font-family: system-ui, sans-serif;
+ background: #0f0f0f;
+ color: #e9e9e9;
+ padding: 24px;
+ }
+ h1 {
+ margin: 0 0 8px;
+ font-weight: 500;
+ }
+ h2 {
+ margin: 24px 0 8px;
+ font-size: 14px;
+ font-weight: 500;
+ color: #9a9a9a;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ }
+ .grid {
+ display: grid;
+ gap: 16px;
+ grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
+ }
+ .log {
+ font-family: ui-monospace, Menlo, monospace;
+ font-size: 12px;
+ color: #8fd4a4;
+ background: #1a1a1a;
+ border-radius: 4px;
+ padding: 8px 12px;
+ min-height: 24px;
+ }
+ mv-viewer {
+ border-radius: 8px;
+ }
</style>
</head>
<body>
@@ -22,7 +52,12 @@
<div class="log" id="log1"></div>
<h2>Auto-rotate</h2>
- <mv-viewer id="v2" src="/avatars/cz.glb" auto-rotate environment="Venice Sunset"></mv-viewer>
+ <mv-viewer
+ id="v2"
+ src="/avatars/cz.glb"
+ auto-rotate
+ environment="Venice Sunset"
+ ></mv-viewer>
<h2>Poster &amp; reveal on interaction (click to load)</h2>
<mv-viewer
diff --git a/features.html b/features.html
index 32378e484..44002d6f2 100644
--- a/features.html
+++ b/features.html
@@ -1,141 +1,177 @@
<!doctype html>
<html lang="en">
-<head>
- <meta charset="utf-8" />
- <meta http-equiv="X-UA-Compatible" content="IE=edge" />
- <title>Features — 3D Agent</title>
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <meta name="author" content="nirholas" />
- <meta name="description" content="3D Agent features: ERC-8004 trustless identity, on-chain agent discovery, 3D model validation, and AI-powered rendering." />
- <meta name="theme-color" content="#000000" />
+ <head>
+ <meta charset="utf-8" />
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+ <title>Features — 3D Agent</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta name="author" content="nirholas" />
+ <meta
+ name="description"
+ content="3D Agent features: ERC-8004 trustless identity, on-chain agent discovery, 3D model validation, and AI-powered rendering."
+ />
+ <meta name="theme-color" content="#000000" />
- <meta property="og:type" content="website" />
- <meta property="og:title" content="Features — 3D Agent" />
- <meta property="og:description" content="ERC-8004 trustless identity, on-chain agent discovery, 3D model validation, and AI-powered rendering." />
- <meta property="og:url" content="https://3dagent.vercel.app/features" />
+ <meta property="og:type" content="website" />
+ <meta property="og:title" content="Features — 3D Agent" />
+ <meta
+ property="og:description"
+ content="ERC-8004 trustless identity, on-chain agent discovery, 3D model validation, and AI-powered rendering."
+ />
+ <meta property="og:url" content="https://3dagent.vercel.app/features" />
- <link rel="canonical" href="https://3dagent.vercel.app/features" />
- <link rel="shortcut icon" href="/favicon.ico" />
- <link rel="preconnect" href="https://fonts.googleapis.com" />
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
- <link rel="stylesheet" href="/style.css" />
- <link rel="stylesheet" href="/features.css" />
- <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&family=JetBrains+Mono:wght@400&display=swap" rel="stylesheet" />
- <script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>
-</head>
-<body class="features-page">
- <header>
- <h1><a href="/">3D Agent</a></h1>
- <nav class="features-nav">
- <a href="/app">Viewer</a>
- <a href="/explore">Explore</a>
- <a href="/features" class="active">Features</a>
- </nav>
- </header>
+ <link rel="canonical" href="https://3dagent.vercel.app/features" />
+ <link rel="shortcut icon" href="/favicon.ico" />
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/features.css" />
+ <link
+ href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&family=JetBrains+Mono:wght@400&display=swap"
+ rel="stylesheet"
+ />
+ <script
+ type="module"
+ src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"
+ ></script>
+ </head>
+ <body class="features-page">
+ <header>
+ <h1><a href="/">3D Agent</a></h1>
+ <nav class="features-nav">
+ <a href="/app">Viewer</a>
+ <a href="/explore">Explore</a>
+ <a href="/features" class="active">Features</a>
+ </nav>
+ </header>
- <main class="features-main">
- <!-- Hero -->
- <section class="hero" id="hero">
- <div class="hero-bg" aria-hidden="true">
- <div class="hero-mesh"></div>
- <div class="hero-grid"></div>
- <div class="hero-glow hero-glow-gold"></div>
- <div class="hero-glow hero-glow-cyan"></div>
- </div>
- <div class="hero-content">
- <div class="hero-chip scroll-reveal">
- <span class="hero-chip-dot"></span>
- <span>Live on Ethereum</span>
- <span class="hero-chip-divider"></span>
- <span class="hero-chip-spec">ERC-8004</span>
+ <main class="features-main">
+ <!-- Hero -->
+ <section class="hero" id="hero">
+ <div class="hero-bg" aria-hidden="true">
+ <div class="hero-mesh"></div>
+ <div class="hero-grid"></div>
+ <div class="hero-glow hero-glow-gold"></div>
+ <div class="hero-glow hero-glow-cyan"></div>
</div>
- <h2 class="hero-title scroll-reveal">
- Every agent<br/>
- deserves a <em>passport</em>.
- </h2>
- <p class="hero-subtitle scroll-reveal">A verifiable, portable identity for every AI avatar — discoverable by any agent, on any chain, anywhere.</p>
- <div class="hero-cta scroll-reveal">
- <a href="/" class="btn-primary">
- <span>Launch Viewer</span>
- <span class="btn-arrow">→</span>
- </a>
- <a href="https://eips.ethereum.org/EIPS/eip-8004" target="_blank" rel="noopener" class="btn-ghost">Read the spec</a>
- </div>
- <ul class="hero-proof scroll-reveal" aria-label="Supported standards">
- <li>ERC-721</li>
- <li>A2A</li>
- <li>MCP</li>
- <li>ENS</li>
- <li>zkML</li>
- </ul>
- </div>
- <div class="hero-avatar scroll-reveal" aria-hidden="true">
- <div class="hero-avatar-ring"></div>
- <div class="hero-avatar-pulse"></div>
- <model-viewer
- class="hero-avatar-viewer"
- src="/avatars/cz.glb"
- alt="3D Agent avatar"
- camera-controls
- disable-zoom
- auto-rotate
- auto-rotate-delay="0"
- rotation-per-second="18deg"
- interaction-prompt="none"
- shadow-intensity="0.8"
- shadow-softness="1"
- exposure="1.05"
- tone-mapping="aces"
- environment-image="neutral"
- camera-orbit="20deg 68deg 3.4m"
- field-of-view="28deg"
- loading="eager"
- ></model-viewer>
- <div class="hero-avatar-tag" aria-hidden="true">
- <span class="hero-avatar-tag-label">agentId</span>
- <span class="hero-avatar-tag-value">0x3d…a9f</span>
- </div>
- </div>
- <div class="hero-scroll-hint scroll-reveal" aria-hidden="true">
- <span>scroll</span>
- <span class="hero-scroll-line"></span>
- </div>
- </section>
-
- <!-- How it works -->
- <section class="section" id="how-it-works">
- <h3 class="section-label scroll-reveal">How It Works</h3>
- <div class="steps">
- <div class="step scroll-reveal">
- <div class="step-num">01</div>
- <h4>Register</h4>
- <p>Mint an ERC-721 token on any EVM chain. The <code>tokenURI</code> points to your agent's JSON registration file — name, description, endpoints, and trust preferences.</p>
+ <div class="hero-content">
+ <div class="hero-chip scroll-reveal">
+ <span class="hero-chip-dot"></span>
+ <span>Live on Ethereum</span>
+ <span class="hero-chip-divider"></span>
+ <span class="hero-chip-spec">ERC-8004</span>
+ </div>
+ <h2 class="hero-title scroll-reveal">
+ Every agent<br />
+ deserves a <em>passport</em>.
+ </h2>
+ <p class="hero-subtitle scroll-reveal">
+ A verifiable, portable identity for every AI avatar — discoverable by any
+ agent, on any chain, anywhere.
+ </p>
+ <div class="hero-cta scroll-reveal">
+ <a href="/" class="btn-primary">
+ <span>Launch Viewer</span>
+ <span class="btn-arrow">→</span>
+ </a>
+ <a
+ href="https://eips.ethereum.org/EIPS/eip-8004"
+ target="_blank"
+ rel="noopener"
+ class="btn-ghost"
+ >Read the spec</a
+ >
+ </div>
+ <ul class="hero-proof scroll-reveal" aria-label="Supported standards">
+ <li>ERC-721</li>
+ <li>A2A</li>
+ <li>MCP</li>
+ <li>ENS</li>
+ <li>zkML</li>
+ </ul>
</div>
- <div class="step scroll-reveal">
- <div class="step-num">02</div>
- <h4>Discover</h4>
- <p>Other agents and clients query the Identity Registry to find your agent. Service endpoints expose A2A, MCP, web interfaces, ENS names, and wallet addresses.</p>
+ <div class="hero-avatar scroll-reveal" aria-hidden="true">
+ <div class="hero-avatar-ring"></div>
+ <div class="hero-avatar-pulse"></div>
+ <model-viewer
+ class="hero-avatar-viewer"
+ src="/avatars/cz.glb"
+ alt="3D Agent avatar"
+ camera-controls
+ disable-zoom
+ auto-rotate
+ auto-rotate-delay="0"
+ rotation-per-second="18deg"
+ interaction-prompt="none"
+ shadow-intensity="0.8"
+ shadow-softness="1"
+ exposure="1.05"
+ tone-mapping="aces"
+ environment-image="neutral"
+ camera-orbit="20deg 68deg 3.4m"
+ field-of-view="28deg"
+ loading="eager"
+ ></model-viewer>
+ <div class="hero-avatar-tag" aria-hidden="true">
+ <span class="hero-avatar-tag-label">agentId</span>
+ <span class="hero-avatar-tag-value">0x3d…a9f</span>
+ </div>
</div>
- <div class="step scroll-reveal">
- <div class="step-num">03</div>
- <h4>Trust</h4>
- <p>Reputation feedback, validation registries, and cryptographic proofs build trust proportional to value at risk — from ordering pizza to medical diagnosis.</p>
+ <div class="hero-scroll-hint scroll-reveal" aria-hidden="true">
+ <span>scroll</span>
+ <span class="hero-scroll-line"></span>
</div>
- </div>
- </section>
+ </section>
- <!-- Registration JSON -->
- <section class="section section-dark" id="registration">
- <h3 class="section-label scroll-reveal">Agent Registration File</h3>
- <p class="section-desc scroll-reveal">Every 3D avatar is a JSON file — the same format ERC-8004 uses for agent identity. Your avatar's metadata becomes its on-chain passport.</p>
- <div class="code-block scroll-reveal">
- <div class="code-header">
- <span class="code-dot red"></span>
- <span class="code-dot yellow"></span>
- <span class="code-dot green"></span>
- <span class="code-filename">agent-registration.json</span>
+ <!-- How it works -->
+ <section class="section" id="how-it-works">
+ <h3 class="section-label scroll-reveal">How It Works</h3>
+ <div class="steps">
+ <div class="step scroll-reveal">
+ <div class="step-num">01</div>
+ <h4>Register</h4>
+ <p>
+ Mint an ERC-721 token on any EVM chain. The <code>tokenURI</code> points
+ to your agent's JSON registration file — name, description, endpoints,
+ and trust preferences.
+ </p>
+ </div>
+ <div class="step scroll-reveal">
+ <div class="step-num">02</div>
+ <h4>Discover</h4>
+ <p>
+ Other agents and clients query the Identity Registry to find your agent.
+ Service endpoints expose A2A, MCP, web interfaces, ENS names, and wallet
+ addresses.
+ </p>
+ </div>
+ <div class="step scroll-reveal">
+ <div class="step-num">03</div>
+ <h4>Trust</h4>
+ <p>
+ Reputation feedback, validation registries, and cryptographic proofs
+ build trust proportional to value at risk — from ordering pizza to
+ medical diagnosis.
+ </p>
+ </div>
</div>
-<pre class="code-body"><code>{
+ </section>
+
+ <!-- Registration JSON -->
+ <section class="section section-dark" id="registration">
+ <h3 class="section-label scroll-reveal">Agent Registration File</h3>
+ <p class="section-desc scroll-reveal">
+ Every 3D avatar is a JSON file — the same format ERC-8004 uses for agent
+ identity. Your avatar's metadata becomes its on-chain passport.
+ </p>
+ <div class="code-block scroll-reveal">
+ <div class="code-header">
+ <span class="code-dot red"></span>
+ <span class="code-dot yellow"></span>
+ <span class="code-dot green"></span>
+ <span class="code-filename">agent-registration.json</span>
+ </div>
+ <pre class="code-body"><code>{
<span class="json-key">"type"</span>: <span class="json-str">"https://eips.ethereum.org/EIPS/eip-8004#registration-v1"</span>,
<span class="json-key">"name"</span>: <span class="json-str">"3D Agent"</span>,
<span class="json-key">"description"</span>: <span class="json-str">"AI-powered 3D model viewer and validation agent"</span>,
@@ -148,134 +184,173 @@
],
<span class="json-key">"supportedTrust"</span>: [<span class="json-str">"reputation"</span>]
}</code></pre>
- </div>
- </section>
-
- <!-- Three Registries -->
- <section class="section" id="registries">
- <h3 class="section-label scroll-reveal">Three Registries</h3>
- <div class="registry-grid">
- <div class="registry-card scroll-reveal">
- <div class="registry-icon">🪪</div>
- <h4>Identity Registry</h4>
- <p>ERC-721 based. Every agent gets a unique <code>agentId</code> and a URI that resolves to its registration file. Transferable, composable, browsable with any NFT app.</p>
- <ul class="registry-details">
- <li><code>register(agentURI)</code></li>
- <li><code>setAgentURI()</code></li>
- <li><code>setMetadata()</code></li>
- </ul>
- </div>
- <div class="registry-card scroll-reveal">
- <div class="registry-icon">⭐</div>
- <h4>Reputation Registry</h4>
- <p>Any client can leave signed feedback — quality scores, uptime, response time. On-chain composability meets off-chain aggregation.</p>
- <ul class="registry-details">
- <li><code>giveFeedback(agentId, value)</code></li>
- <li><code>getSummary(agentId)</code></li>
- <li><code>revokeFeedback()</code></li>
- </ul>
- </div>
- <div class="registry-card scroll-reveal">
- <div class="registry-icon">🔐</div>
- <h4>Validation Registry</h4>
- <p>Request independent verification: stake-secured re-execution, zkML proofs, TEE attestations. Trust proportional to value at risk.</p>
- <ul class="registry-details">
- <li><code>validationRequest()</code></li>
- <li><code>validationResponse()</code></li>
- <li><code>getValidationStatus()</code></li>
- </ul>
</div>
- </div>
- </section>
+ </section>
- <!-- 3D + ERC-8004 -->
- <section class="section section-dark" id="integration">
- <h3 class="section-label scroll-reveal">3D Avatars Meet Web3 Identity</h3>
- <div class="integration-grid">
- <div class="integration-item scroll-reveal">
- <h4>GLB → On-Chain</h4>
- <p>Your 3D avatar's GLB file becomes the <code>"image"</code> field in the registration JSON. Render it in any viewer, verify it on-chain.</p>
- </div>
- <div class="integration-item scroll-reveal">
- <h4>Validation Built-In</h4>
- <p>glTF validation results feed the Reputation Registry — model quality scores become on-chain reputation signals.</p>
+ <!-- Three Registries -->
+ <section class="section" id="registries">
+ <h3 class="section-label scroll-reveal">Three Registries</h3>
+ <div class="registry-grid">
+ <div class="registry-card scroll-reveal">
+ <div class="registry-icon">🪪</div>
+ <h4>Identity Registry</h4>
+ <p>
+ ERC-721 based. Every agent gets a unique <code>agentId</code> and a URI
+ that resolves to its registration file. Transferable, composable,
+ browsable with any NFT app.
+ </p>
+ <ul class="registry-details">
+ <li><code>register(agentURI)</code></li>
+ <li><code>setAgentURI()</code></li>
+ <li><code>setMetadata()</code></li>
+ </ul>
+ </div>
+ <div class="registry-card scroll-reveal">
+ <div class="registry-icon">⭐</div>
+ <h4>Reputation Registry</h4>
+ <p>
+ Any client can leave signed feedback — quality scores, uptime, response
+ time. On-chain composability meets off-chain aggregation.
+ </p>
+ <ul class="registry-details">
+ <li><code>giveFeedback(agentId, value)</code></li>
+ <li><code>getSummary(agentId)</code></li>
+ <li><code>revokeFeedback()</code></li>
+ </ul>
+ </div>
+ <div class="registry-card scroll-reveal">
+ <div class="registry-icon">🔐</div>
+ <h4>Validation Registry</h4>
+ <p>
+ Request independent verification: stake-secured re-execution, zkML
+ proofs, TEE attestations. Trust proportional to value at risk.
+ </p>
+ <ul class="registry-details">
+ <li><code>validationRequest()</code></li>
+ <li><code>validationResponse()</code></li>
+ <li><code>getValidationStatus()</code></li>
+ </ul>
+ </div>
</div>
- <div class="integration-item scroll-reveal">
- <h4>Agent Discovery</h4>
- <p>Any A2A or MCP client can discover your 3D Agent via the Identity Registry and interact through standard endpoints.</p>
- </div>
- <div class="integration-item scroll-reveal">
- <h4>Portable & Composable</h4>
- <p>Your agent identity is an NFT — transfer it, delegate it, list it. Works across any EVM chain.</p>
+ </section>
+
+ <!-- 3D + ERC-8004 -->
+ <section class="section section-dark" id="integration">
+ <h3 class="section-label scroll-reveal">3D Avatars Meet Web3 Identity</h3>
+ <div class="integration-grid">
+ <div class="integration-item scroll-reveal">
+ <h4>GLB → On-Chain</h4>
+ <p>
+ Your 3D avatar's GLB file becomes the <code>"image"</code> field in the
+ registration JSON. Render it in any viewer, verify it on-chain.
+ </p>
+ </div>
+ <div class="integration-item scroll-reveal">
+ <h4>Validation Built-In</h4>
+ <p>
+ glTF validation results feed the Reputation Registry — model quality
+ scores become on-chain reputation signals.
+ </p>
+ </div>
+ <div class="integration-item scroll-reveal">
+ <h4>Agent Discovery</h4>
+ <p>
+ Any A2A or MCP client can discover your 3D Agent via the Identity
+ Registry and interact through standard endpoints.
+ </p>
+ </div>
+ <div class="integration-item scroll-reveal">
+ <h4>Portable & Composable</h4>
+ <p>
+ Your agent identity is an NFT — transfer it, delegate it, list it. Works
+ across any EVM chain.
+ </p>
+ </div>
</div>
- </div>
- </section>
+ </section>
- <!-- CTA -->
- <section class="section cta-section" id="cta">
- <div class="cta-content scroll-reveal">
- <h3>Ready to give your AI agent an identity?</h3>
- <p>Drop a 3D model into the viewer, or explore the ERC-8004 spec.</p>
- <div class="hero-cta">
- <a href="/" class="btn-primary">Launch Viewer</a>
- <a href="https://ethereum-magicians.org/t/erc-8004-trustless-agents/25098" target="_blank" rel="noopener" class="btn-ghost">Join the Discussion →</a>
+ <!-- CTA -->
+ <section class="section cta-section" id="cta">
+ <div class="cta-content scroll-reveal">
+ <h3>Ready to give your AI agent an identity?</h3>
+ <p>Drop a 3D model into the viewer, or explore the ERC-8004 spec.</p>
+ <div class="hero-cta">
+ <a href="/" class="btn-primary">Launch Viewer</a>
+ <a
+ href="https://ethereum-magicians.org/t/erc-8004-trustless-agents/25098"
+ target="_blank"
+ rel="noopener"
+ class="btn-ghost"
+ >Join the Discussion →</a
+ >
+ </div>
</div>
- </div>
- </section>
+ </section>
- <footer class="features-footer">
- <p>3D Agent · <a href="https://github.com/nirholas/3D" target="_blank" rel="noopener">GitHub</a> · Built on <a href="https://eips.ethereum.org/EIPS/eip-8004" target="_blank" rel="noopener">ERC-8004</a></p>
- </footer>
- </main>
+ <footer class="features-footer">
+ <p>
+ 3D Agent ·
+ <a href="https://github.com/nirholas/3D" target="_blank" rel="noopener"
+ >GitHub</a
+ >
+ · Built on
+ <a href="https://eips.ethereum.org/EIPS/eip-8004" target="_blank" rel="noopener"
+ >ERC-8004</a
+ >
+ </p>
+ </footer>
+ </main>
- <script>
- // Scroll-triggered reveal animations using IntersectionObserver
- (function () {
- const reveals = document.querySelectorAll('.scroll-reveal');
+ <script>
+ // Scroll-triggered reveal animations using IntersectionObserver
+ (function () {
+ const reveals = document.querySelectorAll('.scroll-reveal');
- const observer = new IntersectionObserver(
- (entries) => {
- entries.forEach((entry) => {
- if (entry.isIntersecting) {
- entry.target.classList.add('revealed');
- observer.unobserve(entry.target);
- }
- });
- },
- {
- threshold: 0.15,
- rootMargin: '0px 0px -60px 0px',
- }
- );
+ const observer = new IntersectionObserver(
+ (entries) => {
+ entries.forEach((entry) => {
+ if (entry.isIntersecting) {
+ entry.target.classList.add('revealed');
+ observer.unobserve(entry.target);
+ }
+ });
+ },
+ {
+ threshold: 0.15,
+ rootMargin: '0px 0px -60px 0px',
+ },
+ );
- reveals.forEach((el, i) => {
- // Stagger siblings inside the same parent
- const siblings = Array.from(el.parentElement.querySelectorAll('.scroll-reveal'));
- const idx = siblings.indexOf(el);
- el.style.transitionDelay = (idx * 0.1) + 's';
- observer.observe(el);
- });
- })();
- </script>
+ reveals.forEach((el, i) => {
+ // Stagger siblings inside the same parent
+ const siblings = Array.from(
+ el.parentElement.querySelectorAll('.scroll-reveal'),
+ );
+ const idx = siblings.indexOf(el);
+ el.style.transitionDelay = idx * 0.1 + 's';
+ observer.observe(el);
+ });
+ })();
+ </script>
- <script type="module">
- // ?pretext=N opts into experimental hero behaviours. Default visitors see no change.
- (async function () {
- try {
- const flag = new URLSearchParams(location.search).get('pretext');
- if (!['1', '2', '3', '4'].includes(flag)) return;
+ <script type="module">
+ // ?pretext=N opts into experimental hero behaviours. Default visitors see no change.
+ (async function () {
+ try {
+ const flag = new URLSearchParams(location.search).get('pretext');
+ if (!['1', '2', '3', '4'].includes(flag)) return;
- const hero = document.querySelector('.hero');
- if (!hero) return;
+ const hero = document.querySelector('.hero');
+ if (!hero) return;
- const { default: PretextHero } = await import('/src/features/hero-pretext.js');
- const instance = new PretextHero(hero, { flag });
- await instance.init();
- window.__pretextHero = instance;
- } catch (err) {
- console.warn('[pretext-hero] init failed:', err);
- }
- })();
- </script>
-</body>
+ const { default: PretextHero } = await import('/src/features/hero-pretext.js');
+ const instance = new PretextHero(hero, { flag });
+ await instance.init();
+ window.__pretextHero = instance;
+ } catch (err) {
+ console.warn('[pretext-hero] init failed:', err);
+ }
+ })();
+ </script>
+ </body>
</html>
diff --git a/home.css b/home.css
index 04ae4dbd6..5d564d310 100644
--- a/home.css
+++ b/home.css
@@ -1,854 +1,910 @@
/* ── Home page marketing styles ── */
.home-page {
- overflow-y: auto;
- overflow-x: hidden;
- height: 100%;
- scroll-behavior: smooth;
+ overflow-y: auto;
+ overflow-x: hidden;
+ height: 100%;
+ scroll-behavior: smooth;
}
.home-main {
- width: 100%;
+ width: 100%;
}
/* ── Nav ── */
.home-nav {
- margin-left: auto;
- display: flex;
- align-items: center;
- gap: var(--space-lg);
- -webkit-app-region: no-drag;
+ margin-left: auto;
+ display: flex;
+ align-items: center;
+ gap: var(--space-lg);
+ -webkit-app-region: no-drag;
}
.home-nav a {
- color: rgba(255, 255, 255, 0.4);
- text-decoration: none;
- font-size: var(--text-sm);
- font-weight: 400;
- letter-spacing: 0.04em;
- transition: color 0.2s ease;
+ color: rgba(255, 255, 255, 0.4);
+ text-decoration: none;
+ font-size: var(--text-sm);
+ font-weight: 400;
+ letter-spacing: 0.04em;
+ transition: color 0.2s ease;
}
.home-nav a:hover {
- color: #fff;
+ color: #fff;
}
.home-nav .nav-cta {
- padding: 0.42rem 1.1rem;
- background: #fff;
- color: #000;
- border-radius: var(--radius-lg);
- font-weight: 500;
- font-size: var(--text-sm);
- transition: background 0.2s ease, transform 0.2s ease;
+ padding: 0.42rem 1.1rem;
+ background: #fff;
+ color: #000;
+ border-radius: var(--radius-lg);
+ font-weight: 500;
+ font-size: var(--text-sm);
+ transition:
+ background 0.2s ease,
+ transform 0.2s ease;
}
.home-nav .nav-cta:hover {
- background: rgba(255, 255, 255, 0.88);
- color: #000;
- transform: translateY(-1px);
+ background: rgba(255, 255, 255, 0.88);
+ color: #000;
+ transform: translateY(-1px);
}
/* ── Scroll reveal ── */
.h-reveal {
- opacity: 0;
- transform: translateY(20px);
- transition:
- opacity 0.65s cubic-bezier(0.16, 1, 0.3, 1),
- transform 0.65s cubic-bezier(0.16, 1, 0.3, 1);
+ opacity: 0;
+ transform: translateY(20px);
+ transition:
+ opacity 0.65s cubic-bezier(0.16, 1, 0.3, 1),
+ transform 0.65s cubic-bezier(0.16, 1, 0.3, 1);
}
.h-reveal.revealed {
- opacity: 1;
- transform: translateY(0);
+ opacity: 1;
+ transform: translateY(0);
}
/* ── Hero ── */
.h-hero {
- position: relative;
- display: grid;
- grid-template-columns: minmax(0, 1fr) minmax(0, 1.05fr);
- align-items: center;
- gap: var(--space-2xl);
- min-height: 100vh;
- max-width: 1280px;
- margin: 0 auto;
- padding: calc(var(--space-2xl) + 2rem) var(--space-lg) var(--space-2xl);
- overflow: hidden;
- isolation: isolate;
+ position: relative;
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) minmax(0, 1.05fr);
+ align-items: center;
+ gap: var(--space-2xl);
+ min-height: 100vh;
+ max-width: 1280px;
+ margin: 0 auto;
+ padding: calc(var(--space-2xl) + 2rem) var(--space-lg) var(--space-2xl);
+ overflow: hidden;
+ isolation: isolate;
}
.h-hero-bg {
- position: absolute;
- inset: 0;
- pointer-events: none;
- z-index: 0;
- overflow: hidden;
+ position: absolute;
+ inset: 0;
+ pointer-events: none;
+ z-index: 0;
+ overflow: hidden;
}
.h-hero-grid {
- position: absolute;
- inset: -1px;
- background-image:
- linear-gradient(to right, rgba(255, 255, 255, 0.03) 1px, transparent 1px),
- linear-gradient(to bottom, rgba(255, 255, 255, 0.03) 1px, transparent 1px);
- background-size: 64px 64px;
- mask-image: radial-gradient(ellipse at 50% 40%, #000 20%, transparent 75%);
- -webkit-mask-image: radial-gradient(ellipse at 50% 40%, #000 20%, transparent 75%);
+ position: absolute;
+ inset: -1px;
+ background-image:
+ linear-gradient(to right, rgba(255, 255, 255, 0.03) 1px, transparent 1px),
+ linear-gradient(to bottom, rgba(255, 255, 255, 0.03) 1px, transparent 1px);
+ background-size: 64px 64px;
+ mask-image: radial-gradient(ellipse at 50% 40%, #000 20%, transparent 75%);
+ -webkit-mask-image: radial-gradient(ellipse at 50% 40%, #000 20%, transparent 75%);
}
.h-hero-mesh {
- position: absolute;
- inset: -20%;
- background:
- radial-gradient(40% 50% at 72% 38%, rgba(255, 200, 60, 0.13) 0%, transparent 60%),
- radial-gradient(35% 45% at 20% 72%, rgba(80, 200, 255, 0.08) 0%, transparent 65%),
- radial-gradient(55% 40% at 50% 100%, rgba(120, 80, 255, 0.05) 0%, transparent 60%);
- filter: blur(40px);
- animation: hMeshDrift 20s ease-in-out infinite alternate;
+ position: absolute;
+ inset: -20%;
+ background:
+ radial-gradient(40% 50% at 72% 38%, rgba(255, 200, 60, 0.13) 0%, transparent 60%),
+ radial-gradient(35% 45% at 20% 72%, rgba(80, 200, 255, 0.08) 0%, transparent 65%),
+ radial-gradient(55% 40% at 50% 100%, rgba(120, 80, 255, 0.05) 0%, transparent 60%);
+ filter: blur(40px);
+ animation: hMeshDrift 20s ease-in-out infinite alternate;
}
@keyframes hMeshDrift {
- 0% { transform: translate3d(0, 0, 0) scale(1); }
- 50% { transform: translate3d(-2%, 1.5%, 0) scale(1.04); }
- 100% { transform: translate3d(2%, -1%, 0) scale(1.02); }
+ 0% {
+ transform: translate3d(0, 0, 0) scale(1);
+ }
+ 50% {
+ transform: translate3d(-2%, 1.5%, 0) scale(1.04);
+ }
+ 100% {
+ transform: translate3d(2%, -1%, 0) scale(1.02);
+ }
}
.h-hero-glow-a {
- position: absolute;
- width: 700px;
- height: 700px;
- border-radius: 50%;
- background: radial-gradient(circle, rgba(255, 200, 60, 0.11) 0%, transparent 65%);
- top: 38%;
- right: -6%;
- transform: translateY(-50%);
- filter: blur(18px);
- animation: hBreath 6s ease-in-out infinite;
+ position: absolute;
+ width: 700px;
+ height: 700px;
+ border-radius: 50%;
+ background: radial-gradient(circle, rgba(255, 200, 60, 0.11) 0%, transparent 65%);
+ top: 38%;
+ right: -6%;
+ transform: translateY(-50%);
+ filter: blur(18px);
+ animation: hBreath 6s ease-in-out infinite;
}
.h-hero-glow-b {
- position: absolute;
- width: 400px;
- height: 400px;
- border-radius: 50%;
- background: radial-gradient(circle, rgba(80, 220, 255, 0.07) 0%, transparent 65%);
- bottom: -8%;
- left: -2%;
- filter: blur(18px);
- animation: hBreathB 9s ease-in-out infinite;
+ position: absolute;
+ width: 400px;
+ height: 400px;
+ border-radius: 50%;
+ background: radial-gradient(circle, rgba(80, 220, 255, 0.07) 0%, transparent 65%);
+ bottom: -8%;
+ left: -2%;
+ filter: blur(18px);
+ animation: hBreathB 9s ease-in-out infinite;
}
@keyframes hBreath {
- 0%, 100% { opacity: 0.85; transform: translateY(-50%) scale(1); }
- 50% { opacity: 1; transform: translateY(-50%) scale(1.06); }
+ 0%,
+ 100% {
+ opacity: 0.85;
+ transform: translateY(-50%) scale(1);
+ }
+ 50% {
+ opacity: 1;
+ transform: translateY(-50%) scale(1.06);
+ }
}
@keyframes hBreathB {
- 0%, 100% { opacity: 0.7; transform: scale(1); }
- 50% { opacity: 1; transform: scale(1.09); }
+ 0%,
+ 100% {
+ opacity: 0.7;
+ transform: scale(1);
+ }
+ 50% {
+ opacity: 1;
+ transform: scale(1.09);
+ }
}
/* ── Hero content ── */
.h-hero-content {
- position: relative;
- z-index: 2;
+ position: relative;
+ z-index: 2;
}
.h-eyebrow {
- display: inline-flex;
- align-items: center;
- gap: var(--space-sm);
- padding: 0.38rem 0.9rem;
- background: rgba(255, 255, 255, 0.035);
- border: 1px solid rgba(255, 255, 255, 0.08);
- border-radius: 999px;
- font-size: 0.68rem;
- color: rgba(255, 255, 255, 0.6);
- letter-spacing: 0.09em;
- text-transform: uppercase;
- margin-bottom: var(--space-lg);
- backdrop-filter: blur(12px);
- -webkit-backdrop-filter: blur(12px);
- font-family: 'JetBrains Mono', monospace;
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-sm);
+ padding: 0.38rem 0.9rem;
+ background: rgba(255, 255, 255, 0.035);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 999px;
+ font-size: 0.68rem;
+ color: rgba(255, 255, 255, 0.6);
+ letter-spacing: 0.09em;
+ text-transform: uppercase;
+ margin-bottom: var(--space-lg);
+ backdrop-filter: blur(12px);
+ -webkit-backdrop-filter: blur(12px);
+ font-family: 'JetBrains Mono', monospace;
}
.h-eyebrow-dot {
- width: 6px;
- height: 6px;
- border-radius: 50%;
- background: #4ade80;
- box-shadow: 0 0 0 0 rgba(74, 222, 128, 0.6);
- animation: hDotPulse 2.4s ease-out infinite;
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: #4ade80;
+ box-shadow: 0 0 0 0 rgba(74, 222, 128, 0.6);
+ animation: hDotPulse 2.4s ease-out infinite;
}
@keyframes hDotPulse {
- 0% { box-shadow: 0 0 0 0 rgba(74, 222, 128, 0.55); }
- 70% { box-shadow: 0 0 0 8px rgba(74, 222, 128, 0); }
- 100% { box-shadow: 0 0 0 0 rgba(74, 222, 128, 0); }
+ 0% {
+ box-shadow: 0 0 0 0 rgba(74, 222, 128, 0.55);
+ }
+ 70% {
+ box-shadow: 0 0 0 8px rgba(74, 222, 128, 0);
+ }
+ 100% {
+ box-shadow: 0 0 0 0 rgba(74, 222, 128, 0);
+ }
}
.h-title {
- font-size: clamp(2.8rem, 7vw, 5.2rem);
- font-weight: 600;
- color: #fff;
- line-height: 1.03;
- margin: 0 0 var(--space-lg);
- letter-spacing: -0.035em;
+ font-size: clamp(2.8rem, 7vw, 5.2rem);
+ font-weight: 600;
+ color: #fff;
+ line-height: 1.03;
+ margin: 0 0 var(--space-lg);
+ letter-spacing: -0.035em;
}
.h-title em {
- font-style: normal;
- background: linear-gradient(100deg, #ffd76a 0%, #ffb347 35%, #7df9ff 75%, #9d8cff 100%);
- background-size: 200% 100%;
- -webkit-background-clip: text;
- background-clip: text;
- color: transparent;
- animation: hTitleShimmer 9s ease-in-out infinite;
+ font-style: normal;
+ background: linear-gradient(100deg, #ffd76a 0%, #ffb347 35%, #7df9ff 75%, #9d8cff 100%);
+ background-size: 200% 100%;
+ -webkit-background-clip: text;
+ background-clip: text;
+ color: transparent;
+ animation: hTitleShimmer 9s ease-in-out infinite;
}
@keyframes hTitleShimmer {
- 0%, 100% { background-position: 0% 50%; }
- 50% { background-position: 100% 50%; }
+ 0%,
+ 100% {
+ background-position: 0% 50%;
+ }
+ 50% {
+ background-position: 100% 50%;
+ }
}
.h-subtitle {
- font-size: clamp(1rem, 1.3vw, 1.2rem);
- color: rgba(255, 255, 255, 0.52);
- font-weight: 300;
- line-height: 1.55;
- max-width: 30em;
- margin: 0 0 var(--space-xl);
+ font-size: clamp(1rem, 1.3vw, 1.2rem);
+ color: rgba(255, 255, 255, 0.52);
+ font-weight: 300;
+ line-height: 1.55;
+ max-width: 30em;
+ margin: 0 0 var(--space-xl);
}
.h-cta-row {
- display: flex;
- gap: var(--space-md);
- flex-wrap: wrap;
- margin-bottom: var(--space-xl);
+ display: flex;
+ gap: var(--space-md);
+ flex-wrap: wrap;
+ margin-bottom: var(--space-xl);
}
.h-btn-primary {
- display: inline-flex;
- align-items: center;
- gap: 0.5em;
- padding: 0.7rem 1.6rem;
- background: #fff;
- color: #000;
- font-size: var(--text-sm);
- font-weight: 500;
- border-radius: var(--radius-lg);
- text-decoration: none;
- letter-spacing: 0.02em;
- transition: all 0.25s ease;
+ display: inline-flex;
+ align-items: center;
+ gap: 0.5em;
+ padding: 0.7rem 1.6rem;
+ background: #fff;
+ color: #000;
+ font-size: var(--text-sm);
+ font-weight: 500;
+ border-radius: var(--radius-lg);
+ text-decoration: none;
+ letter-spacing: 0.02em;
+ transition: all 0.25s ease;
}
.h-btn-primary:hover {
- background: rgba(255, 255, 255, 0.88);
- transform: translateY(-1px);
- box-shadow: 0 4px 20px rgba(255, 255, 255, 0.14);
+ background: rgba(255, 255, 255, 0.88);
+ transform: translateY(-1px);
+ box-shadow: 0 4px 20px rgba(255, 255, 255, 0.14);
}
.h-btn-primary .arrow {
- transition: transform 0.25s ease;
+ transition: transform 0.25s ease;
}
.h-btn-primary:hover .arrow {
- transform: translateX(3px);
+ transform: translateX(3px);
}
.h-btn-ghost {
- display: inline-flex;
- align-items: center;
- padding: 0.7rem 1.6rem;
- color: rgba(255, 255, 255, 0.5);
- font-size: var(--text-sm);
- font-weight: 400;
- text-decoration: none;
- letter-spacing: 0.02em;
- border: 1px solid rgba(255, 255, 255, 0.1);
- border-radius: var(--radius-lg);
- transition: all 0.25s ease;
+ display: inline-flex;
+ align-items: center;
+ padding: 0.7rem 1.6rem;
+ color: rgba(255, 255, 255, 0.5);
+ font-size: var(--text-sm);
+ font-weight: 400;
+ text-decoration: none;
+ letter-spacing: 0.02em;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ border-radius: var(--radius-lg);
+ transition: all 0.25s ease;
}
.h-btn-ghost:hover {
- color: #fff;
- border-color: rgba(255, 255, 255, 0.28);
- background: rgba(255, 255, 255, 0.04);
+ color: #fff;
+ border-color: rgba(255, 255, 255, 0.28);
+ background: rgba(255, 255, 255, 0.04);
}
.h-standards {
- list-style: none;
- padding: 0;
- margin: 0;
- display: flex;
- flex-wrap: wrap;
- gap: var(--space-md) var(--space-lg);
- font-family: 'JetBrains Mono', monospace;
- font-size: 0.68rem;
- color: rgba(255, 255, 255, 0.3);
- letter-spacing: 0.14em;
- text-transform: uppercase;
+ list-style: none;
+ padding: 0;
+ margin: 0;
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-md) var(--space-lg);
+ font-family: 'JetBrains Mono', monospace;
+ font-size: 0.68rem;
+ color: rgba(255, 255, 255, 0.3);
+ letter-spacing: 0.14em;
+ text-transform: uppercase;
}
.h-standards li {
- position: relative;
+ position: relative;
}
.h-standards li + li::before {
- content: '';
- position: absolute;
- left: calc(var(--space-lg) * -0.5);
- top: 50%;
- width: 2px;
- height: 2px;
- border-radius: 50%;
- background: rgba(255, 255, 255, 0.2);
- transform: translateY(-50%);
+ content: '';
+ position: absolute;
+ left: calc(var(--space-lg) * -0.5);
+ top: 50%;
+ width: 2px;
+ height: 2px;
+ border-radius: 50%;
+ background: rgba(255, 255, 255, 0.2);
+ transform: translateY(-50%);
}
/* ── Hero avatar column ── */
.h-hero-visual {
- position: relative;
- z-index: 1;
- width: 100%;
- aspect-ratio: 1 / 1;
- max-width: 600px;
- justify-self: end;
- display: flex;
- align-items: center;
- justify-content: center;
+ position: relative;
+ z-index: 1;
+ width: 100%;
+ aspect-ratio: 1 / 1;
+ max-width: 600px;
+ justify-self: end;
+ display: flex;
+ align-items: center;
+ justify-content: center;
}
.h-avatar-viewer {
- width: 100%;
- height: 100%;
- background: transparent;
- --poster-color: transparent;
- border-radius: 50%;
- outline: none;
- position: relative;
- z-index: 2;
+ width: 100%;
+ height: 100%;
+ background: transparent;
+ --poster-color: transparent;
+ border-radius: 50%;
+ outline: none;
+ position: relative;
+ z-index: 2;
}
.h-avatar-ring {
- position: absolute;
- inset: 4%;
- border-radius: 50%;
- background: conic-gradient(
- from 140deg,
- rgba(255, 200, 60, 0.0) 0deg,
- rgba(255, 200, 60, 0.22) 60deg,
- rgba(125, 249, 255, 0.15) 180deg,
- rgba(157, 140, 255, 0.1) 260deg,
- rgba(255, 200, 60, 0.0) 360deg
- );
- filter: blur(1px);
- opacity: 0.65;
- animation: hRingSpin 30s linear infinite;
- mask: radial-gradient(circle, transparent 58%, #000 59%, #000 63%, transparent 64%);
- -webkit-mask: radial-gradient(circle, transparent 58%, #000 59%, #000 63%, transparent 64%);
- pointer-events: none;
- z-index: 1;
+ position: absolute;
+ inset: 4%;
+ border-radius: 50%;
+ background: conic-gradient(
+ from 140deg,
+ rgba(255, 200, 60, 0) 0deg,
+ rgba(255, 200, 60, 0.22) 60deg,
+ rgba(125, 249, 255, 0.15) 180deg,
+ rgba(157, 140, 255, 0.1) 260deg,
+ rgba(255, 200, 60, 0) 360deg
+ );
+ filter: blur(1px);
+ opacity: 0.65;
+ animation: hRingSpin 30s linear infinite;
+ mask: radial-gradient(circle, transparent 58%, #000 59%, #000 63%, transparent 64%);
+ -webkit-mask: radial-gradient(circle, transparent 58%, #000 59%, #000 63%, transparent 64%);
+ pointer-events: none;
+ z-index: 1;
}
@keyframes hRingSpin {
- to { transform: rotate(360deg); }
+ to {
+ transform: rotate(360deg);
+ }
}
.h-avatar-glow {
- position: absolute;
- inset: 8%;
- border-radius: 50%;
- background:
- radial-gradient(circle at 50% 50%, rgba(255, 200, 60, 0.12) 0%, transparent 60%),
- radial-gradient(circle at 40% 70%, rgba(125, 249, 255, 0.07) 0%, transparent 55%);
- box-shadow: 0 40px 120px -20px rgba(255, 200, 60, 0.16);
- animation: hBreath 5s ease-in-out infinite;
- pointer-events: none;
- z-index: 0;
+ position: absolute;
+ inset: 8%;
+ border-radius: 50%;
+ background:
+ radial-gradient(circle at 50% 50%, rgba(255, 200, 60, 0.12) 0%, transparent 60%),
+ radial-gradient(circle at 40% 70%, rgba(125, 249, 255, 0.07) 0%, transparent 55%);
+ box-shadow: 0 40px 120px -20px rgba(255, 200, 60, 0.16);
+ animation: hBreath 5s ease-in-out infinite;
+ pointer-events: none;
+ z-index: 0;
}
.h-avatar-badge {
- position: absolute;
- bottom: 9%;
- right: 0;
- display: inline-flex;
- align-items: center;
- gap: 0.6em;
- padding: 0.5rem 0.9rem;
- background: rgba(10, 10, 14, 0.72);
- border: 1px solid rgba(255, 255, 255, 0.07);
- border-radius: var(--radius-lg);
- font-family: 'JetBrains Mono', monospace;
- font-size: 0.68rem;
- color: rgba(255, 255, 255, 0.75);
- backdrop-filter: blur(12px);
- -webkit-backdrop-filter: blur(12px);
- z-index: 3;
- box-shadow: 0 8px 24px -8px rgba(0, 0, 0, 0.6);
+ position: absolute;
+ bottom: 9%;
+ right: 0;
+ display: inline-flex;
+ align-items: center;
+ gap: 0.6em;
+ padding: 0.5rem 0.9rem;
+ background: rgba(10, 10, 14, 0.72);
+ border: 1px solid rgba(255, 255, 255, 0.07);
+ border-radius: var(--radius-lg);
+ font-family: 'JetBrains Mono', monospace;
+ font-size: 0.68rem;
+ color: rgba(255, 255, 255, 0.75);
+ backdrop-filter: blur(12px);
+ -webkit-backdrop-filter: blur(12px);
+ z-index: 3;
+ box-shadow: 0 8px 24px -8px rgba(0, 0, 0, 0.6);
}
.h-avatar-badge-label {
- color: rgba(255, 215, 0, 0.65);
- letter-spacing: 0.08em;
- text-transform: uppercase;
- font-size: 0.58rem;
+ color: rgba(255, 215, 0, 0.65);
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ font-size: 0.58rem;
}
.h-scroll-hint {
- position: absolute;
- bottom: var(--space-lg);
- left: 50%;
- transform: translateX(-50%);
- display: flex;
- flex-direction: column;
- align-items: center;
- gap: 0.5rem;
- font-family: 'JetBrains Mono', monospace;
- font-size: 0.58rem;
- color: rgba(255, 255, 255, 0.22);
- letter-spacing: 0.25em;
- text-transform: uppercase;
- z-index: 2;
- pointer-events: none;
+ position: absolute;
+ bottom: var(--space-lg);
+ left: 50%;
+ transform: translateX(-50%);
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 0.5rem;
+ font-family: 'JetBrains Mono', monospace;
+ font-size: 0.58rem;
+ color: rgba(255, 255, 255, 0.22);
+ letter-spacing: 0.25em;
+ text-transform: uppercase;
+ z-index: 2;
+ pointer-events: none;
}
.h-scroll-line {
- width: 1px;
- height: 32px;
- background: linear-gradient(to bottom, rgba(255, 255, 255, 0.28), transparent);
- animation: hScrollLine 2.2s ease-in-out infinite;
- transform-origin: top;
+ width: 1px;
+ height: 32px;
+ background: linear-gradient(to bottom, rgba(255, 255, 255, 0.28), transparent);
+ animation: hScrollLine 2.2s ease-in-out infinite;
+ transform-origin: top;
}
@keyframes hScrollLine {
- 0% { transform: scaleY(0); opacity: 0; }
- 40% { opacity: 1; }
- 100% { transform: scaleY(1); opacity: 0; }
+ 0% {
+ transform: scaleY(0);
+ opacity: 0;
+ }
+ 40% {
+ opacity: 1;
+ }
+ 100% {
+ transform: scaleY(1);
+ opacity: 0;
+ }
}
/* ── Section base ── */
.h-section {
- padding: var(--space-2xl) var(--space-lg);
- max-width: 1080px;
- margin: 0 auto;
+ padding: var(--space-2xl) var(--space-lg);
+ max-width: 1080px;
+ margin: 0 auto;
}
.h-section-dark {
- max-width: none;
- background: rgba(255, 255, 255, 0.018);
- border-top: 1px solid rgba(255, 255, 255, 0.04);
- border-bottom: 1px solid rgba(255, 255, 255, 0.04);
- padding: var(--space-2xl) var(--space-lg);
+ max-width: none;
+ background: rgba(255, 255, 255, 0.018);
+ border-top: 1px solid rgba(255, 255, 255, 0.04);
+ border-bottom: 1px solid rgba(255, 255, 255, 0.04);
+ padding: var(--space-2xl) var(--space-lg);
}
.h-section-dark > .h-section-inner {
- max-width: 1080px;
- margin: 0 auto;
+ max-width: 1080px;
+ margin: 0 auto;
}
.h-section-label {
- font-family: 'JetBrains Mono', monospace;
- font-size: var(--text-xs);
- color: rgba(255, 215, 0, 0.55);
- letter-spacing: 0.15em;
- text-transform: uppercase;
- margin: 0 0 var(--space-xl);
- text-align: center;
+ font-family: 'JetBrains Mono', monospace;
+ font-size: var(--text-xs);
+ color: rgba(255, 215, 0, 0.55);
+ letter-spacing: 0.15em;
+ text-transform: uppercase;
+ margin: 0 0 var(--space-xl);
+ text-align: center;
}
.h-section-title {
- font-size: clamp(1.8rem, 3.5vw, 2.8rem);
- font-weight: 600;
- color: #fff;
- line-height: 1.1;
- margin: 0 0 var(--space-md);
- text-align: center;
- letter-spacing: -0.025em;
+ font-size: clamp(1.8rem, 3.5vw, 2.8rem);
+ font-weight: 600;
+ color: #fff;
+ line-height: 1.1;
+ margin: 0 0 var(--space-md);
+ text-align: center;
+ letter-spacing: -0.025em;
}
.h-section-sub {
- font-size: var(--text-base);
- color: rgba(255, 255, 255, 0.4);
- font-weight: 300;
- text-align: center;
- max-width: 36em;
- margin: 0 auto var(--space-2xl);
- line-height: var(--leading-normal);
+ font-size: var(--text-base);
+ color: rgba(255, 255, 255, 0.4);
+ font-weight: 300;
+ text-align: center;
+ max-width: 36em;
+ margin: 0 auto var(--space-2xl);
+ line-height: var(--leading-normal);
}
/* ── Steps ── */
.h-steps {
- display: grid;
- grid-template-columns: repeat(3, 1fr);
- gap: var(--space-xl);
- position: relative;
+ display: grid;
+ grid-template-columns: repeat(3, 1fr);
+ gap: var(--space-xl);
+ position: relative;
}
.h-steps::before {
- content: '';
- position: absolute;
- top: 1.8rem;
- left: calc(33.333% + 1rem);
- right: calc(33.333% + 1rem);
- height: 1px;
- background: linear-gradient(to right, rgba(255,215,0,0.15), rgba(255,215,0,0.08));
+ content: '';
+ position: absolute;
+ top: 1.8rem;
+ left: calc(33.333% + 1rem);
+ right: calc(33.333% + 1rem);
+ height: 1px;
+ background: linear-gradient(to right, rgba(255, 215, 0, 0.15), rgba(255, 215, 0, 0.08));
}
.h-step {
- padding: var(--space-lg);
- border: 1px solid rgba(255, 255, 255, 0.06);
- border-radius: var(--radius-lg);
- transition: border-color 0.3s ease, transform 0.3s ease;
- position: relative;
+ padding: var(--space-lg);
+ border: 1px solid rgba(255, 255, 255, 0.06);
+ border-radius: var(--radius-lg);
+ transition:
+ border-color 0.3s ease,
+ transform 0.3s ease;
+ position: relative;
}
.h-step:hover {
- border-color: rgba(255, 255, 255, 0.12);
- transform: translateY(-2px);
+ border-color: rgba(255, 255, 255, 0.12);
+ transform: translateY(-2px);
}
.h-step-num {
- font-family: 'JetBrains Mono', monospace;
- font-size: var(--text-2xl);
- font-weight: 600;
- color: rgba(255, 215, 0, 0.13);
- line-height: 1;
- margin-bottom: var(--space-sm);
+ font-family: 'JetBrains Mono', monospace;
+ font-size: var(--text-2xl);
+ font-weight: 600;
+ color: rgba(255, 215, 0, 0.13);
+ line-height: 1;
+ margin-bottom: var(--space-sm);
}
.h-step h4 {
- color: #fff;
- font-size: var(--text-lg);
- font-weight: 500;
- margin: 0 0 var(--space-xs);
+ color: #fff;
+ font-size: var(--text-lg);
+ font-weight: 500;
+ margin: 0 0 var(--space-xs);
}
.h-step p {
- color: rgba(255, 255, 255, 0.42);
- font-size: var(--text-sm);
- line-height: var(--leading-normal);
- margin: 0;
+ color: rgba(255, 255, 255, 0.42);
+ font-size: var(--text-sm);
+ line-height: var(--leading-normal);
+ margin: 0;
}
/* ── Feature rows (alternating, Avaturn-style) ── */
.h-feature {
- display: grid;
- grid-template-columns: 1fr 1fr;
- gap: var(--space-2xl);
- align-items: center;
- padding: var(--space-2xl) var(--space-lg);
- max-width: 1080px;
- margin: 0 auto;
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: var(--space-2xl);
+ align-items: center;
+ padding: var(--space-2xl) var(--space-lg);
+ max-width: 1080px;
+ margin: 0 auto;
}
.h-feature.h-feature-flip {
- direction: rtl;
+ direction: rtl;
}
.h-feature.h-feature-flip > * {
- direction: ltr;
+ direction: ltr;
}
.h-feature-text h3 {
- font-size: clamp(1.5rem, 2.5vw, 2.2rem);
- font-weight: 600;
- color: #fff;
- line-height: 1.1;
- margin: 0 0 var(--space-md);
- letter-spacing: -0.02em;
+ font-size: clamp(1.5rem, 2.5vw, 2.2rem);
+ font-weight: 600;
+ color: #fff;
+ line-height: 1.1;
+ margin: 0 0 var(--space-md);
+ letter-spacing: -0.02em;
}
.h-feature-text p {
- font-size: var(--text-base);
- color: rgba(255, 255, 255, 0.45);
- font-weight: 300;
- line-height: var(--leading-normal);
- margin: 0 0 var(--space-lg);
+ font-size: var(--text-base);
+ color: rgba(255, 255, 255, 0.45);
+ font-weight: 300;
+ line-height: var(--leading-normal);
+ margin: 0 0 var(--space-lg);
}
.h-feature-link {
- display: inline-flex;
- align-items: center;
- gap: 0.4em;
- font-size: var(--text-sm);
- color: rgba(255, 215, 0, 0.75);
- text-decoration: none;
- letter-spacing: 0.02em;
- transition: color 0.2s ease, gap 0.2s ease;
+ display: inline-flex;
+ align-items: center;
+ gap: 0.4em;
+ font-size: var(--text-sm);
+ color: rgba(255, 215, 0, 0.75);
+ text-decoration: none;
+ letter-spacing: 0.02em;
+ transition:
+ color 0.2s ease,
+ gap 0.2s ease;
}
.h-feature-link:hover {
- color: #ffd76a;
- gap: 0.7em;
+ color: #ffd76a;
+ gap: 0.7em;
}
.h-feature-visual {
- border-radius: var(--radius-lg);
- background: rgba(255, 255, 255, 0.02);
- border: 1px solid rgba(255, 255, 255, 0.06);
- overflow: hidden;
- display: flex;
- align-items: center;
- justify-content: center;
- min-height: 280px;
- position: relative;
+ border-radius: var(--radius-lg);
+ background: rgba(255, 255, 255, 0.02);
+ border: 1px solid rgba(255, 255, 255, 0.06);
+ overflow: hidden;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ min-height: 280px;
+ position: relative;
}
.h-feature-visual model-viewer {
- width: 100%;
- height: 320px;
- background: transparent;
- --poster-color: transparent;
+ width: 100%;
+ height: 320px;
+ background: transparent;
+ --poster-color: transparent;
}
/* Widget preview card */
.h-widget-preview {
- padding: var(--space-lg);
- width: 100%;
+ padding: var(--space-lg);
+ width: 100%;
}
.h-widget-card {
- background: rgba(255, 255, 255, 0.03);
- border: 1px solid rgba(255, 255, 255, 0.07);
- border-radius: var(--radius-lg);
- padding: var(--space-md);
- margin-bottom: var(--space-sm);
+ background: rgba(255, 255, 255, 0.03);
+ border: 1px solid rgba(255, 255, 255, 0.07);
+ border-radius: var(--radius-lg);
+ padding: var(--space-md);
+ margin-bottom: var(--space-sm);
}
.h-widget-card-label {
- font-family: 'JetBrains Mono', monospace;
- font-size: 0.65rem;
- color: rgba(255, 215, 0, 0.6);
- letter-spacing: 0.12em;
- text-transform: uppercase;
- margin-bottom: var(--space-xs);
+ font-family: 'JetBrains Mono', monospace;
+ font-size: 0.65rem;
+ color: rgba(255, 215, 0, 0.6);
+ letter-spacing: 0.12em;
+ text-transform: uppercase;
+ margin-bottom: var(--space-xs);
}
.h-widget-card-title {
- color: #fff;
- font-size: var(--text-sm);
- font-weight: 500;
- margin-bottom: var(--space-xs);
+ color: #fff;
+ font-size: var(--text-sm);
+ font-weight: 500;
+ margin-bottom: var(--space-xs);
}
.h-widget-card-desc {
- color: rgba(255, 255, 255, 0.35);
- font-size: 0.75rem;
+ color: rgba(255, 255, 255, 0.35);
+ font-size: 0.75rem;
}
.h-embed-code {
- background: #0a0a0a;
- border: 1px solid rgba(255, 255, 255, 0.05);
- border-radius: var(--radius-sm);
- padding: var(--space-sm) var(--space-md);
- font-family: 'JetBrains Mono', monospace;
- font-size: 0.68rem;
- color: rgba(255, 255, 255, 0.45);
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- margin-top: var(--space-sm);
-}
-
-.h-embed-code .tag { color: rgba(125, 200, 255, 0.8); }
-.h-embed-code .attr { color: rgba(168, 204, 140, 0.8); }
+ background: #0a0a0a;
+ border: 1px solid rgba(255, 255, 255, 0.05);
+ border-radius: var(--radius-sm);
+ padding: var(--space-sm) var(--space-md);
+ font-family: 'JetBrains Mono', monospace;
+ font-size: 0.68rem;
+ color: rgba(255, 255, 255, 0.45);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ margin-top: var(--space-sm);
+}
+
+.h-embed-code .tag {
+ color: rgba(125, 200, 255, 0.8);
+}
+.h-embed-code .attr {
+ color: rgba(168, 204, 140, 0.8);
+}
/* Identity card */
.h-identity-card {
- padding: var(--space-lg);
- width: 100%;
+ padding: var(--space-lg);
+ width: 100%;
}
.h-id-header {
- display: flex;
- align-items: center;
- gap: var(--space-sm);
- margin-bottom: var(--space-md);
+ display: flex;
+ align-items: center;
+ gap: var(--space-sm);
+ margin-bottom: var(--space-md);
}
.h-id-dot {
- width: 8px;
- height: 8px;
- border-radius: 50%;
- background: #4ade80;
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background: #4ade80;
}
.h-id-title {
- font-family: 'JetBrains Mono', monospace;
- font-size: 0.7rem;
- color: rgba(255, 255, 255, 0.5);
- letter-spacing: 0.08em;
+ font-family: 'JetBrains Mono', monospace;
+ font-size: 0.7rem;
+ color: rgba(255, 255, 255, 0.5);
+ letter-spacing: 0.08em;
}
.h-id-row {
- display: flex;
- justify-content: space-between;
- align-items: center;
- padding: var(--space-xs) 0;
- border-bottom: 1px solid rgba(255, 255, 255, 0.04);
- font-size: 0.75rem;
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: var(--space-xs) 0;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.04);
+ font-size: 0.75rem;
}
.h-id-row:last-child {
- border-bottom: none;
+ border-bottom: none;
}
.h-id-key {
- font-family: 'JetBrains Mono', monospace;
- color: rgba(255, 255, 255, 0.3);
- letter-spacing: 0.05em;
+ font-family: 'JetBrains Mono', monospace;
+ color: rgba(255, 255, 255, 0.3);
+ letter-spacing: 0.05em;
}
.h-id-val {
- color: rgba(255, 255, 255, 0.65);
- font-family: 'JetBrains Mono', monospace;
- font-size: 0.7rem;
+ color: rgba(255, 255, 255, 0.65);
+ font-family: 'JetBrains Mono', monospace;
+ font-size: 0.7rem;
}
.h-id-val.gold {
- color: rgba(255, 215, 0, 0.7);
+ color: rgba(255, 215, 0, 0.7);
}
/* ── Final CTA ── */
.h-cta-section {
- text-align: center;
- padding: var(--space-2xl) var(--space-lg);
+ text-align: center;
+ padding: var(--space-2xl) var(--space-lg);
}
.h-cta-section h2 {
- font-size: clamp(1.8rem, 4vw, 3rem);
- font-weight: 600;
- color: #fff;
- line-height: 1.1;
- margin: 0 0 var(--space-md);
- letter-spacing: -0.025em;
+ font-size: clamp(1.8rem, 4vw, 3rem);
+ font-weight: 600;
+ color: #fff;
+ line-height: 1.1;
+ margin: 0 0 var(--space-md);
+ letter-spacing: -0.025em;
}
.h-cta-section p {
- font-size: var(--text-base);
- color: rgba(255, 255, 255, 0.4);
- margin: 0 0 var(--space-xl);
+ font-size: var(--text-base);
+ color: rgba(255, 255, 255, 0.4);
+ margin: 0 0 var(--space-xl);
}
.h-cta-row-center {
- display: flex;
- gap: var(--space-md);
- justify-content: center;
- flex-wrap: wrap;
+ display: flex;
+ gap: var(--space-md);
+ justify-content: center;
+ flex-wrap: wrap;
}
/* ── Footer ── */
.h-footer {
- text-align: center;
- padding: var(--space-xl) var(--space-lg);
- border-top: 1px solid rgba(255, 255, 255, 0.04);
+ text-align: center;
+ padding: var(--space-xl) var(--space-lg);
+ border-top: 1px solid rgba(255, 255, 255, 0.04);
}
.h-footer p {
- color: rgba(255, 255, 255, 0.22);
- font-size: var(--text-xs);
- font-family: 'JetBrains Mono', monospace;
- margin: 0;
+ color: rgba(255, 255, 255, 0.22);
+ font-size: var(--text-xs);
+ font-family: 'JetBrains Mono', monospace;
+ margin: 0;
}
.h-footer a {
- color: rgba(255, 255, 255, 0.32);
- text-decoration: none;
- transition: color 0.2s ease;
+ color: rgba(255, 255, 255, 0.32);
+ text-decoration: none;
+ transition: color 0.2s ease;
}
.h-footer a:hover {
- color: #fff;
+ color: #fff;
}
/* ── Responsive ── */
@media (prefers-reduced-motion: reduce) {
- .h-hero-mesh, .h-hero-glow-a, .h-hero-glow-b,
- .h-avatar-ring, .h-avatar-glow, .h-eyebrow-dot,
- .h-title em, .h-scroll-line {
- animation: none !important;
- }
+ .h-hero-mesh,
+ .h-hero-glow-a,
+ .h-hero-glow-b,
+ .h-avatar-ring,
+ .h-avatar-glow,
+ .h-eyebrow-dot,
+ .h-title em,
+ .h-scroll-line {
+ animation: none !important;
+ }
}
@media screen and (max-width: 1024px) {
- .h-hero {
- grid-template-columns: 1fr 1fr;
- gap: var(--space-xl);
- }
+ .h-hero {
+ grid-template-columns: 1fr 1fr;
+ gap: var(--space-xl);
+ }
- .h-hero-visual {
- max-width: 400px;
- }
+ .h-hero-visual {
+ max-width: 400px;
+ }
}
@media screen and (max-width: 768px) {
- .h-hero {
- grid-template-columns: 1fr;
- min-height: auto;
- padding: calc(var(--space-xl) + 1rem) var(--space-md) var(--space-xl);
- text-align: center;
- }
-
- .h-hero-content {
- order: 2;
- }
-
- .h-hero-visual {
- order: 1;
- max-width: 320px;
- margin: 0 auto;
- justify-self: center;
- }
-
- .h-cta-row {
- justify-content: center;
- }
-
- .h-standards {
- justify-content: center;
- }
-
- .h-steps {
- grid-template-columns: 1fr;
- gap: var(--space-md);
- }
-
- .h-steps::before {
- display: none;
- }
-
- .h-feature {
- grid-template-columns: 1fr;
- gap: var(--space-lg);
- padding: var(--space-xl) var(--space-md);
- }
-
- .h-feature.h-feature-flip {
- direction: ltr;
- }
-
- .h-section {
- padding: var(--space-xl) var(--space-md);
- }
-
- .h-section-dark {
- padding: var(--space-xl) var(--space-md);
- }
-
- .h-scroll-hint {
- display: none;
- }
+ .h-hero {
+ grid-template-columns: 1fr;
+ min-height: auto;
+ padding: calc(var(--space-xl) + 1rem) var(--space-md) var(--space-xl);
+ text-align: center;
+ }
+
+ .h-hero-content {
+ order: 2;
+ }
+
+ .h-hero-visual {
+ order: 1;
+ max-width: 320px;
+ margin: 0 auto;
+ justify-self: center;
+ }
+
+ .h-cta-row {
+ justify-content: center;
+ }
+
+ .h-standards {
+ justify-content: center;
+ }
+
+ .h-steps {
+ grid-template-columns: 1fr;
+ gap: var(--space-md);
+ }
+
+ .h-steps::before {
+ display: none;
+ }
+
+ .h-feature {
+ grid-template-columns: 1fr;
+ gap: var(--space-lg);
+ padding: var(--space-xl) var(--space-md);
+ }
+
+ .h-feature.h-feature-flip {
+ direction: ltr;
+ }
+
+ .h-section {
+ padding: var(--space-xl) var(--space-md);
+ }
+
+ .h-section-dark {
+ padding: var(--space-xl) var(--space-md);
+ }
+
+ .h-scroll-hint {
+ display: none;
+ }
}
diff --git a/home.html b/home.html
index 3bc8e3cf6..ab08dc62d 100644
--- a/home.html
+++ b/home.html
@@ -1,294 +1,342 @@
<!doctype html>
<html lang="en">
-<head>
- <meta charset="utf-8" />
- <meta http-equiv="X-UA-Compatible" content="IE=edge" />
- <title>3D Agent — Give Your AI a Body</title>
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <meta name="author" content="nirholas" />
- <meta name="description" content="Drop any GLB model into 3D Agent — view it, animate it, embed it anywhere, and give it a verifiable on-chain identity." />
- <meta name="theme-color" content="#000000" />
+ <head>
+ <meta charset="utf-8" />
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+ <title>3D Agent — Give Your AI a Body</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta name="author" content="nirholas" />
+ <meta
+ name="description"
+ content="Drop any GLB model into 3D Agent — view it, animate it, embed it anywhere, and give it a verifiable on-chain identity."
+ />
+ <meta name="theme-color" content="#000000" />
- <meta property="og:type" content="website" />
- <meta property="og:title" content="3D Agent — Give Your AI a Body" />
- <meta property="og:description" content="Drop any GLB model into 3D Agent — view it, animate it, embed it anywhere." />
- <meta property="og:url" content="https://3dagent.vercel.app/home" />
+ <meta property="og:type" content="website" />
+ <meta property="og:title" content="3D Agent — Give Your AI a Body" />
+ <meta
+ property="og:description"
+ content="Drop any GLB model into 3D Agent — view it, animate it, embed it anywhere."
+ />
+ <meta property="og:url" content="https://3dagent.vercel.app/home" />
- <link rel="canonical" href="https://3dagent.vercel.app/home" />
- <link rel="shortcut icon" href="/favicon.ico" />
- <link rel="apple-touch-icon" href="/pwa-192x192.png" />
- <link rel="preconnect" href="https://fonts.googleapis.com" />
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
- <link rel="stylesheet" href="/style.css" />
- <link rel="stylesheet" href="/home.css" />
- <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400&display=swap" rel="stylesheet" />
- <script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>
-</head>
-<body class="home-page">
- <header>
- <h1><a href="/"><span class="wordmark-dot" aria-hidden="true"></span>3D Agent</a></h1>
- <nav class="home-nav">
- <a href="/app">Viewer</a>
- <a href="/studio">Studio</a>
- <a href="/widgets">Widgets</a>
- <a href="/features">Docs</a>
- <a href="/login" class="nav-cta" id="home-nav-cta">Get started</a>
- </nav>
- </header>
+ <link rel="canonical" href="https://3dagent.vercel.app/home" />
+ <link rel="shortcut icon" href="/favicon.ico" />
+ <link rel="apple-touch-icon" href="/pwa-192x192.png" />
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/home.css" />
+ <link
+ href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400&display=swap"
+ rel="stylesheet"
+ />
+ <script
+ type="module"
+ src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"
+ ></script>
+ </head>
+ <body class="home-page">
+ <header>
+ <h1>
+ <a href="/"><span class="wordmark-dot" aria-hidden="true"></span>3D Agent</a>
+ </h1>
+ <nav class="home-nav">
+ <a href="/app">Viewer</a>
+ <a href="/studio">Studio</a>
+ <a href="/widgets">Widgets</a>
+ <a href="/features">Docs</a>
+ <a href="/login" class="nav-cta" id="home-nav-cta">Get started</a>
+ </nav>
+ </header>
- <main class="home-main">
-
- <!-- ── Hero ── -->
- <section class="h-hero">
- <div class="h-hero-bg" aria-hidden="true">
- <div class="h-hero-mesh"></div>
- <div class="h-hero-grid"></div>
- <div class="h-hero-glow-a"></div>
- <div class="h-hero-glow-b"></div>
- </div>
-
- <div class="h-hero-content">
- <div class="h-eyebrow h-reveal">
- <span class="h-eyebrow-dot"></span>
- <span>Browser-native · No install</span>
+ <main class="home-main">
+ <!-- ── Hero ── -->
+ <section class="h-hero">
+ <div class="h-hero-bg" aria-hidden="true">
+ <div class="h-hero-mesh"></div>
+ <div class="h-hero-grid"></div>
+ <div class="h-hero-glow-a"></div>
+ <div class="h-hero-glow-b"></div>
</div>
- <h2 class="h-title h-reveal">
- Give your AI<br/>agent a <em>body</em>.
- </h2>
- <p class="h-subtitle h-reveal">
- Drop any GLB model into 3D Agent — view it, animate it,
- embed it anywhere, and give it a verifiable on-chain identity.
- No plugins. No server uploads. Just open and go.
- </p>
- <div class="h-cta-row h-reveal">
- <a href="/" class="h-btn-primary">
- <span>Launch Viewer</span>
- <span class="arrow">→</span>
- </a>
- <a href="/widgets" class="h-btn-ghost">Explore Widgets</a>
- </div>
- <ul class="h-standards h-reveal" aria-label="Supported formats and standards">
- <li>glTF 2.0</li>
- <li>GLB</li>
- <li>ERC-8004</li>
- <li>A2A</li>
- <li>MCP</li>
- </ul>
- </div>
- <div class="h-hero-visual h-reveal" aria-hidden="true">
- <div class="h-avatar-ring"></div>
- <div class="h-avatar-glow"></div>
- <model-viewer
- class="h-avatar-viewer"
- src="/avatars/cz.glb"
- alt="3D Agent avatar"
- camera-controls
- disable-zoom
- auto-rotate
- auto-rotate-delay="0"
- rotation-per-second="18deg"
- interaction-prompt="none"
- shadow-intensity="0.8"
- shadow-softness="1"
- exposure="1.05"
- tone-mapping="aces"
- environment-image="neutral"
- camera-orbit="20deg 68deg 3.4m"
- field-of-view="28deg"
- loading="eager"
- ></model-viewer>
- <div class="h-avatar-badge">
- <span class="h-avatar-badge-label">agent</span>
- <span>0x3d…a9f</span>
- </div>
- </div>
-
- <div class="h-scroll-hint" aria-hidden="true">
- <span>scroll</span>
- <span class="h-scroll-line"></span>
- </div>
- </section>
-
- <!-- ── How it works ── -->
- <section class="h-section">
- <p class="h-section-label h-reveal">How It Works</p>
- <h2 class="h-section-title h-reveal">From file to deployed agent<br/>in three steps.</h2>
- <p class="h-section-sub h-reveal">No account required to start. Drop a model, explore the viewer, then sign in when you're ready to save and share.</p>
- <div class="h-steps">
- <div class="h-step h-reveal">
- <div class="h-step-num">01</div>
- <h4>Drop your model</h4>
- <p>Drag a GLB or glTF 2.0 file directly into the browser. Instant WebGL rendering — no upload, no install, no waiting.</p>
- </div>
- <div class="h-step h-reveal">
- <div class="h-step-num">02</div>
- <h4>Animate &amp; configure</h4>
- <p>Pick animations, add an AI chat agent, adjust lighting and camera. Save your avatar to your account for reuse.</p>
- </div>
- <div class="h-step h-reveal">
- <div class="h-step-num">03</div>
- <h4>Embed anywhere</h4>
- <p>Generate a widget — one iframe, any site. Turntable, talking agent, animation gallery. Works in Notion, Ghost, WordPress.</p>
+ <div class="h-hero-content">
+ <div class="h-eyebrow h-reveal">
+ <span class="h-eyebrow-dot"></span>
+ <span>Browser-native · No install</span>
+ </div>
+ <h2 class="h-title h-reveal">Give your AI<br />agent a <em>body</em>.</h2>
+ <p class="h-subtitle h-reveal">
+ Drop any GLB model into 3D Agent — view it, animate it, embed it anywhere,
+ and give it a verifiable on-chain identity. No plugins. No server uploads.
+ Just open and go.
+ </p>
+ <div class="h-cta-row h-reveal">
+ <a href="/" class="h-btn-primary">
+ <span>Launch Viewer</span>
+ <span class="arrow">→</span>
+ </a>
+ <a href="/widgets" class="h-btn-ghost">Explore Widgets</a>
+ </div>
+ <ul class="h-standards h-reveal" aria-label="Supported formats and standards">
+ <li>glTF 2.0</li>
+ <li>GLB</li>
+ <li>ERC-8004</li>
+ <li>A2A</li>
+ <li>MCP</li>
+ </ul>
</div>
- </div>
- </section>
- <!-- ── Feature: Viewer ── -->
- <div class="h-section-dark">
- <div class="h-feature h-section-inner">
- <div class="h-feature-text h-reveal">
- <h3>Instant 3D viewer,<br/>no install.</h3>
- <p>Built on three.js r176. Drag a GLB file onto the page and see it rendered in WebGL with full lighting, animations, and material inspection — on any device, any browser.</p>
- <a href="/" class="h-feature-link">Open the viewer →</a>
- </div>
- <div class="h-feature-visual h-reveal">
+ <div class="h-hero-visual h-reveal" aria-hidden="true">
+ <div class="h-avatar-ring"></div>
+ <div class="h-avatar-glow"></div>
<model-viewer
+ class="h-avatar-viewer"
src="/avatars/cz.glb"
- alt="3D model preview"
+ alt="3D Agent avatar"
camera-controls
+ disable-zoom
auto-rotate
auto-rotate-delay="0"
- rotation-per-second="12deg"
+ rotation-per-second="18deg"
interaction-prompt="none"
- shadow-intensity="0.6"
- exposure="1.0"
+ shadow-intensity="0.8"
+ shadow-softness="1"
+ exposure="1.05"
tone-mapping="aces"
environment-image="neutral"
- camera-orbit="0deg 75deg 2.8m"
- field-of-view="30deg"
- loading="lazy"
+ camera-orbit="20deg 68deg 3.4m"
+ field-of-view="28deg"
+ loading="eager"
></model-viewer>
+ <div class="h-avatar-badge">
+ <span class="h-avatar-badge-label">agent</span>
+ <span>0x3d…a9f</span>
+ </div>
</div>
- </div>
- </div>
- <!-- ── Feature: Widget Studio ── -->
- <div class="h-feature h-reveal" style="max-width:1080px; margin: 0 auto;">
- <div class="h-feature-text">
- <h3>Embeddable widgets.<br/>One line of HTML.</h3>
- <p>Save any avatar as a widget — a configured, shareable view that any site can drop in with a single iframe. Five types: Turntable, Animation Gallery, Talking Agent, ERC-8004 Passport, Hotspot Tour.</p>
- <a href="/studio" class="h-feature-link">Open Widget Studio →</a>
- </div>
- <div class="h-feature-visual">
- <div class="h-widget-preview">
- <div class="h-widget-card h-reveal">
- <div class="h-widget-card-label">Turntable</div>
- <div class="h-widget-card-title">Auto-rotating hero banner</div>
- <div class="h-widget-card-desc">360° display, configurable speed and background.</div>
+ <div class="h-scroll-hint" aria-hidden="true">
+ <span>scroll</span>
+ <span class="h-scroll-line"></span>
+ </div>
+ </section>
+
+ <!-- ── How it works ── -->
+ <section class="h-section">
+ <p class="h-section-label h-reveal">How It Works</p>
+ <h2 class="h-section-title h-reveal">
+ From file to deployed agent<br />in three steps.
+ </h2>
+ <p class="h-section-sub h-reveal">
+ No account required to start. Drop a model, explore the viewer, then sign in
+ when you're ready to save and share.
+ </p>
+ <div class="h-steps">
+ <div class="h-step h-reveal">
+ <div class="h-step-num">01</div>
+ <h4>Drop your model</h4>
+ <p>
+ Drag a GLB or glTF 2.0 file directly into the browser. Instant WebGL
+ rendering — no upload, no install, no waiting.
+ </p>
+ </div>
+ <div class="h-step h-reveal">
+ <div class="h-step-num">02</div>
+ <h4>Animate &amp; configure</h4>
+ <p>
+ Pick animations, add an AI chat agent, adjust lighting and camera. Save
+ your avatar to your account for reuse.
+ </p>
+ </div>
+ <div class="h-step h-reveal">
+ <div class="h-step-num">03</div>
+ <h4>Embed anywhere</h4>
+ <p>
+ Generate a widget — one iframe, any site. Turntable, talking agent,
+ animation gallery. Works in Notion, Ghost, WordPress.
+ </p>
</div>
- <div class="h-widget-card h-reveal">
- <div class="h-widget-card-label">Talking Agent</div>
- <div class="h-widget-card-title">Embodied AI chat</div>
- <div class="h-widget-card-desc">Your 3D avatar speaks. Powered by your LLM of choice.</div>
+ </div>
+ </section>
+
+ <!-- ── Feature: Viewer ── -->
+ <div class="h-section-dark">
+ <div class="h-feature h-section-inner">
+ <div class="h-feature-text h-reveal">
+ <h3>Instant 3D viewer,<br />no install.</h3>
+ <p>
+ Built on three.js r176. Drag a GLB file onto the page and see it
+ rendered in WebGL with full lighting, animations, and material
+ inspection — on any device, any browser.
+ </p>
+ <a href="/" class="h-feature-link">Open the viewer →</a>
</div>
- <div class="h-embed-code h-reveal">
- <span class="tag">&lt;iframe</span>
- <span class="attr"> src</span>=<span class="attr">"https://3dagent.vercel.app/#widget=wdgt_abc123"</span>
- <span class="tag">/&gt;</span>
+ <div class="h-feature-visual h-reveal">
+ <model-viewer
+ src="/avatars/cz.glb"
+ alt="3D model preview"
+ camera-controls
+ auto-rotate
+ auto-rotate-delay="0"
+ rotation-per-second="12deg"
+ interaction-prompt="none"
+ shadow-intensity="0.6"
+ exposure="1.0"
+ tone-mapping="aces"
+ environment-image="neutral"
+ camera-orbit="0deg 75deg 2.8m"
+ field-of-view="30deg"
+ loading="lazy"
+ ></model-viewer>
</div>
</div>
</div>
- </div>
- <!-- ── Feature: Agent Identity ── -->
- <div class="h-section-dark">
- <div class="h-feature h-feature-flip h-section-inner">
- <div class="h-feature-text h-reveal">
- <h3>On-chain identity<br/>for every agent.</h3>
- <p>Register your avatar on Ethereum via ERC-8004 — a verifiable, portable identity discoverable by any A2A or MCP client. Your 3D model becomes your agent's on-chain passport.</p>
- <a href="/features" class="h-feature-link">Read the spec →</a>
+ <!-- ── Feature: Widget Studio ── -->
+ <div class="h-feature h-reveal" style="max-width: 1080px; margin: 0 auto">
+ <div class="h-feature-text">
+ <h3>Embeddable widgets.<br />One line of HTML.</h3>
+ <p>
+ Save any avatar as a widget — a configured, shareable view that any site can
+ drop in with a single iframe. Five types: Turntable, Animation Gallery,
+ Talking Agent, ERC-8004 Passport, Hotspot Tour.
+ </p>
+ <a href="/studio" class="h-feature-link">Open Widget Studio →</a>
</div>
- <div class="h-feature-visual h-reveal">
- <div class="h-identity-card">
- <div class="h-id-header">
- <div class="h-id-dot"></div>
- <span class="h-id-title">agent-registration.json</span>
- </div>
- <div class="h-id-row">
- <span class="h-id-key">name</span>
- <span class="h-id-val">"3D Agent"</span>
+ <div class="h-feature-visual">
+ <div class="h-widget-preview">
+ <div class="h-widget-card h-reveal">
+ <div class="h-widget-card-label">Turntable</div>
+ <div class="h-widget-card-title">Auto-rotating hero banner</div>
+ <div class="h-widget-card-desc">
+ 360° display, configurable speed and background.
+ </div>
</div>
- <div class="h-id-row">
- <span class="h-id-key">agentId</span>
- <span class="h-id-val gold">0x3d…a9f</span>
+ <div class="h-widget-card h-reveal">
+ <div class="h-widget-card-label">Talking Agent</div>
+ <div class="h-widget-card-title">Embodied AI chat</div>
+ <div class="h-widget-card-desc">
+ Your 3D avatar speaks. Powered by your LLM of choice.
+ </div>
</div>
- <div class="h-id-row">
- <span class="h-id-key">type</span>
- <span class="h-id-val">ERC-8004</span>
- </div>
- <div class="h-id-row">
- <span class="h-id-key">services</span>
- <span class="h-id-val">A2A · MCP · web</span>
- </div>
- <div class="h-id-row">
- <span class="h-id-key">active</span>
- <span class="h-id-val gold">true</span>
+ <div class="h-embed-code h-reveal">
+ <span class="tag">&lt;iframe</span>
+ <span class="attr"> src</span>=<span class="attr"
+ >"https://3dagent.vercel.app/#widget=wdgt_abc123"</span
+ >
+ <span class="tag">/&gt;</span>
</div>
</div>
</div>
</div>
- </div>
- <!-- ── Final CTA ── -->
- <section class="h-cta-section h-reveal">
- <h2>Ready to give your<br/>agent a presence?</h2>
- <p>Drop a 3D model. Add AI. Ship in minutes.</p>
- <div class="h-cta-row-center">
- <a href="/" class="h-btn-primary">
- <span>Launch Viewer</span>
- <span class="arrow">→</span>
- </a>
- <a href="/register" class="h-btn-ghost">Create account</a>
+ <!-- ── Feature: Agent Identity ── -->
+ <div class="h-section-dark">
+ <div class="h-feature h-feature-flip h-section-inner">
+ <div class="h-feature-text h-reveal">
+ <h3>On-chain identity<br />for every agent.</h3>
+ <p>
+ Register your avatar on Ethereum via ERC-8004 — a verifiable, portable
+ identity discoverable by any A2A or MCP client. Your 3D model becomes
+ your agent's on-chain passport.
+ </p>
+ <a href="/features" class="h-feature-link">Read the spec →</a>
+ </div>
+ <div class="h-feature-visual h-reveal">
+ <div class="h-identity-card">
+ <div class="h-id-header">
+ <div class="h-id-dot"></div>
+ <span class="h-id-title">agent-registration.json</span>
+ </div>
+ <div class="h-id-row">
+ <span class="h-id-key">name</span>
+ <span class="h-id-val">"3D Agent"</span>
+ </div>
+ <div class="h-id-row">
+ <span class="h-id-key">agentId</span>
+ <span class="h-id-val gold">0x3d…a9f</span>
+ </div>
+ <div class="h-id-row">
+ <span class="h-id-key">type</span>
+ <span class="h-id-val">ERC-8004</span>
+ </div>
+ <div class="h-id-row">
+ <span class="h-id-key">services</span>
+ <span class="h-id-val">A2A · MCP · web</span>
+ </div>
+ <div class="h-id-row">
+ <span class="h-id-key">active</span>
+ <span class="h-id-val gold">true</span>
+ </div>
+ </div>
+ </div>
+ </div>
</div>
- </section>
- <footer class="h-footer">
- <p>
- 3D Agent ·
- <a href="https://github.com/nirholas/3D" target="_blank" rel="noopener">GitHub</a> ·
- <a href="/features">Docs</a> ·
- <a href="https://eips.ethereum.org/EIPS/eip-8004" target="_blank" rel="noopener">ERC-8004</a>
- </p>
- </footer>
- </main>
+ <!-- ── Final CTA ── -->
+ <section class="h-cta-section h-reveal">
+ <h2>Ready to give your<br />agent a presence?</h2>
+ <p>Drop a 3D model. Add AI. Ship in minutes.</p>
+ <div class="h-cta-row-center">
+ <a href="/" class="h-btn-primary">
+ <span>Launch Viewer</span>
+ <span class="arrow">→</span>
+ </a>
+ <a href="/register" class="h-btn-ghost">Create account</a>
+ </div>
+ </section>
+
+ <footer class="h-footer">
+ <p>
+ 3D Agent ·
+ <a href="https://github.com/nirholas/3D" target="_blank" rel="noopener"
+ >GitHub</a
+ >
+ · <a href="/features">Docs</a> ·
+ <a href="https://eips.ethereum.org/EIPS/eip-8004" target="_blank" rel="noopener"
+ >ERC-8004</a
+ >
+ </p>
+ </footer>
+ </main>
- <script>
- // Auth-aware nav CTA
- (function () {
- try {
- const token = localStorage.getItem('auth_token') || sessionStorage.getItem('auth_token');
- if (token) {
- const cta = document.getElementById('home-nav-cta');
- if (cta) {
- cta.textContent = 'Dashboard';
- cta.href = '/dashboard';
+ <script>
+ // Auth-aware nav CTA
+ (function () {
+ try {
+ const token =
+ localStorage.getItem('auth_token') || sessionStorage.getItem('auth_token');
+ if (token) {
+ const cta = document.getElementById('home-nav-cta');
+ if (cta) {
+ cta.textContent = 'Dashboard';
+ cta.href = '/dashboard';
+ }
}
- }
- } catch (_) {}
- })();
+ } catch (_) {}
+ })();
- // Scroll reveal
- (function () {
- const els = document.querySelectorAll('.h-reveal');
- const observer = new IntersectionObserver(
- (entries) => {
- entries.forEach((entry) => {
- if (entry.isIntersecting) {
- entry.target.classList.add('revealed');
- observer.unobserve(entry.target);
- }
- });
- },
- { threshold: 0.12, rootMargin: '0px 0px -50px 0px' }
- );
- els.forEach((el, i) => {
- const siblings = Array.from(el.parentElement.querySelectorAll('.h-reveal'));
- const idx = siblings.indexOf(el);
- el.style.transitionDelay = (idx * 0.09) + 's';
- observer.observe(el);
- });
- })();
- </script>
-</body>
+ // Scroll reveal
+ (function () {
+ const els = document.querySelectorAll('.h-reveal');
+ const observer = new IntersectionObserver(
+ (entries) => {
+ entries.forEach((entry) => {
+ if (entry.isIntersecting) {
+ entry.target.classList.add('revealed');
+ observer.unobserve(entry.target);
+ }
+ });
+ },
+ { threshold: 0.12, rootMargin: '0px 0px -50px 0px' },
+ );
+ els.forEach((el, i) => {
+ const siblings = Array.from(el.parentElement.querySelectorAll('.h-reveal'));
+ const idx = siblings.indexOf(el);
+ el.style.transitionDelay = idx * 0.09 + 's';
+ observer.observe(el);
+ });
+ })();
+ </script>
+ </body>
</html>
diff --git a/index.html b/index.html
index a9359f50f..dec52c25c 100644
--- a/index.html
+++ b/index.html
@@ -500,7 +500,7 @@
<a href="/widgets">Widgets</a>
<a href="/dashboard" class="nav-dashboard">Dashboard</a>
<a href="/login" class="nav-sign-in" id="nav-sign-in">Sign in</a>
- <button id="btn-wallet-signin" style="cursor:pointer;">Sign in with wallet</button>
+ <button id="btn-wallet-signin" style="cursor: pointer">Sign in with wallet</button>
</nav>
</header>
@@ -718,7 +718,6 @@
<p class="journey-step-desc">
Generate a widget — one iframe, any site. Works in Notion, Ghost,
WordPress, and more.
-
</p>
<a href="/studio" class="journey-step-cta">Open Widget Studio →</a>
</div>
diff --git a/lobehub-plugin/LICENSE b/lobehub-plugin/LICENSE
new file mode 100644
index 000000000..d237cbd54
--- /dev/null
+++ b/lobehub-plugin/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 3D Agent
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/lobehub-plugin/README.md b/lobehub-plugin/README.md
index 9a0ad6f93..468f11592 100644
--- a/lobehub-plugin/README.md
+++ b/lobehub-plugin/README.md
@@ -1,152 +1,144 @@
# @3dagent/lobehub-plugin
-A LobeHub plugin that renders a 3D agent avatar in the chat sidebar, reacting to assistant messages via the agent bridge protocol.
+Render an embodied 3D avatar in the LobeChat sidebar. The avatar reacts to the LLM's tool calls — speaking, gesturing, and emoting — in real time.
-## Features
+> **Icon/screenshot note:** `assets/icon-256.svg` is a placeholder. Replace with a designed 256×256 PNG before submitting to the LobeHub plugin registry.
-- **Embedded 3D Avatar** — Renders a glTF-based agent in a fixed 320×420 pane
-- **Message Reaction** — Avatar speaks when the LLM generates responses
-- **Zero Dependencies** — No external 3D libraries; uses the 3D Agent embed endpoint
-- **Configurable** — Plugin settings for agent ID and API origin
+---
-## Installation
+## One-click install (LobeChat ≥ 1.x)
-1. Clone this directory into your LobeHub fork at `plugins/@3dagent/lobehub-plugin/`
-2. Install dependencies:
- ```bash
- cd lobehub-plugin
- npm install
+1. In LobeChat, open **Plugins → Plugin Store → Custom plugins**.
+2. Paste the manifest URL:
```
-3. Build:
- ```bash
- npm run build
+ https://3dagent.vercel.app/.well-known/lobehub-plugin.json
```
-4. Reference the plugin manifest in your LobeHub fork's plugin registry.
+3. Click **Install**. LobeChat will show the plugin settings dialog.
+4. Enter your **Agent ID** (UUID from the 3D Agent dashboard at `https://3dagent.vercel.app/dashboard`).
+5. Click **Save**. The 3D avatar appears in the right sidebar.
-## Usage
+---
-In LobeHub's plugin settings, configure:
+## Configuration
-- **Agent ID** (required): The UUID or identifier of the agent you want to embed (e.g., `agent-xyz-123`)
-- **API Origin** (optional): The base URL of your 3D Agent server (defaults to `https://3dagent.vercel.app`)
+| Setting | Type | Required | Default | Description |
+|---|---|---|---|---|
+| `agentId` | `string` | Yes | — | Agent UUID from the 3D Agent dashboard |
+| `apiOrigin` | `string` | No | `https://3dagent.vercel.app` | Override for self-hosted instances |
-The plugin will render an iframe pointing to `${apiOrigin}/agent/${agentId}/embed` and listen for chat messages.
+---
-## Configuration
+## How it works
-Plugin settings are defined in [`src/config-schema.ts`](src/config-schema.ts) and exposed via the [`manifest.json`](manifest.json) schema section.
+```
+LobeChat host
+ │ postMessage({ type: 'LobePlugin.renderPlugin', payload: { apiName, arguments } })
+ ▼
+AgentPane (React sidebar component)
+ │ v1 bridge request: { v:1, source:'agent-host', kind:'request', op:'speak', payload }
+ ▼
+/lobehub/iframe/ (boot.js)
+ │ el.say(text, { sentiment })
+ ▼
+<agent-3d> web component — avatar speaks
+```
-## Bridge Protocol
+When the LLM calls one of the plugin's tools (`speak`, `gesture`, `emote`, `render_agent`), LobeChat sends the tool args as a postMessage to the plugin iframe. `AgentPane` receives it, translates it into a bridge request, and the iframe's `boot.js` dispatches it to the `<agent-3d>` element.
-The plugin uses the **v1 bridge protocol** (FROZEN) from `public/agent/embed.html`:
+### LobeChat message format
-### Host → Iframe
+LobeChat (and `@lobehub/chat-plugin-sdk` internally) sends:
```json
{
- "type": "agent:hello",
- "agentId": "agent-id",
- "host": "optional-origin"
-}
-```
-
-```json
-{
- "type": "agent:action",
- "agentId": "agent-id",
- "action": {
- "type": "speak",
- "payload": { "text": "Hello, world!" }
+ "type": "LobePlugin.renderPlugin",
+ "payload": {
+ "apiName": "speak",
+ "arguments": "{\"text\":\"Hello!\",\"sentiment\":0.5}",
+ "identifier": "3d-agent"
}
}
```
-### Iframe → Host
+`AgentPane` listens for this on `window.addEventListener('message', ...)`. When `@lobehub/chat-plugin-sdk` ships a stable `usePluginStore` / `useWatchPluginMessage` hook that is directly callable for sidebar plugins, replace the listener with that hook so the React render cycle drives the effect.
-```json
-{
- "type": "agent:ready",
- "agentId": "agent-id",
- "version": "1",
- "capabilities": ["speak", "gesture", "look-at", "emote", "present-model"],
- "name": "Agent Name"
-}
-```
+### Wire protocol (v1)
+
+Bridge envelope:
```json
{
- "type": "agent:resize",
- "agentId": "agent-id",
- "height": 500
+ "v": 1,
+ "source": "agent-host",
+ "id": "<uuid>",
+ "inReplyTo": "<request-id>",
+ "kind": "request | response | event",
+ "op": "speak | gesture | emote | look | setAgent | ping | subscribe",
+ "payload": {}
}
```
-## Lobe Hook Integration
+Full spec: [`01-embed-bridges.md`](../prompts/final-integration/01-embed-bridges.md).
-### Current Status
+---
-The plugin currently **mocks** the Lobe hook API with a custom event emitter. To integrate with a real LobeHub fork, you must:
+## Available tool ops
-1. **Find the actual SDK**: Check `@lobehub/ui@latest` or `lobehub-plugin-sdk` for the real `usePluginStore` and `onAssistantMessage` hooks.
-2. **Update `src/AgentPane.tsx`**: Replace the `lobe:assistantMessage` custom event listener with the real hook:
+| Op | Payload | Description |
+|---|---|---|
+| `render_agent` | `{ agentId }` | Swap the agent in the sidebar |
+| `speak` | `{ text, sentiment? [-1,1] }` | Avatar speaks with emotional valence |
+| `gesture` | `{ name: wave\|nod\|point\|shrug }` | Trigger a named gesture |
+| `emote` | `{ trigger, weight? [0,1] }` | Inject emotion into the Empathy Layer |
-```typescript
-// Example (adjust based on actual SDK):
-import { usePluginStore } from '@lobehub/ui';
+---
-export const AgentPane: React.FC<AgentPaneProps> = ({ settings }) => {
- // ... existing code ...
+## Dev harness
- const { onAssistantMessage } = usePluginStore();
+To test the plugin without running LobeChat:
- useEffect(() => {
- if (onAssistantMessage) {
- const unsubscribe = onAssistantMessage((msg) => {
- if (msg.content && bridgeRef.current) {
- bridgeRef.current.speak(msg.content);
- }
- });
- return unsubscribe;
- }
- }, [onAssistantMessage]);
+```bash
+# From repo root:
+npm run build:lib # produces dist-lib/agent-3d.js (the <agent-3d> web component)
+npm --prefix lobehub-plugin install
+npm --prefix lobehub-plugin run build
+
+# Serve the repo root:
+python3 -m http.server 8080
- // ... rest of component ...
-};
+# Open in browser:
+open http://localhost:8080/lobehub-plugin/dev/?agent=<your-agent-id>
```
-### Placeholder Implementation
+The harness shows the agent iframe on the left and a control panel on the right. Click **Inject speak** to fire a fake assistant message and verify the avatar reacts.
-If the Lobe SDK is not available, you can emit a custom event from your LobeHub fork:
+---
-```javascript
-// In your chat message handler:
-window.dispatchEvent(new CustomEvent('lobe:assistantMessage', {
- detail: { content: 'Assistant message text' }
-}));
-```
-
-## Development
+## Build
```bash
+cd lobehub-plugin
npm install
-npm run dev # Watch build (tsc + esbuild)
-npm run type-check # Check TypeScript without emitting
-npm run build # Production bundle
+npm run build # → dist/bundle.js
+npm run type-check # TypeScript strict check
```
-The build outputs to `dist/bundle.js` (ESM module).
+Output: `dist/bundle.js` — tree-shaken, browser-targeted. React and react-dom are external (provided by LobeChat at runtime).
-## Structure
+---
-```
-src/
-├── index.ts # Entry point (exports AgentPane, AgentBridge, settingsSchema)
-├── AgentPane.tsx # Main React component with iframe and hooks
-├── bridge.ts # PostMessage bridge (v1 protocol implementation)
-├── config-schema.ts # Settings schema and defaults
-manifest.json # LobeHub plugin manifest
-```
+## Troubleshooting
+
+| Symptom | Likely cause | Fix |
+|---|---|---|
+| Avatar never appears | Wrong `agentId` | Copy UUID from dashboard; ensure agent has an avatar |
+| "Loading agent…" stuck | Bridge handshake failed | Check browser console for `[3d-agent]` messages; verify `apiOrigin` is reachable |
+| `speak` does nothing | LobeChat hasn't installed the plugin | Confirm plugin is active in LobeChat Plugin Store |
+| CORS error | Self-hosted origin not allowed | Add origin to `CORS_ORIGINS` in your 3D Agent deployment |
+| Timeout errors | Network latency | The bridge has a 10 s timeout; the iframe may still be loading the web component |
+
+---
## License
-MIT
+MIT — see [LICENSE](LICENSE).
diff --git a/lobehub-plugin/assets/icon-256.svg b/lobehub-plugin/assets/icon-256.svg
new file mode 100644
index 000000000..9f69d2ba9
--- /dev/null
+++ b/lobehub-plugin/assets/icon-256.svg
@@ -0,0 +1,24 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256" viewBox="0 0 256 256">
+ <defs>
+ <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0%" stop-color="#0f0f10"/>
+ <stop offset="100%" stop-color="#1a1a2e"/>
+ </linearGradient>
+ <linearGradient id="glow" x1="0" y1="0" x2="0" y2="1">
+ <stop offset="0%" stop-color="#60a5fa"/>
+ <stop offset="100%" stop-color="#818cf8"/>
+ </linearGradient>
+ </defs>
+ <!-- Background -->
+ <rect width="256" height="256" rx="48" fill="url(#bg)"/>
+ <!-- Stylised 3D cube wireframe representing the 3D agent -->
+ <!-- Front face -->
+ <polygon points="88,96 168,96 168,168 88,168" fill="none" stroke="url(#glow)" stroke-width="5" stroke-linejoin="round"/>
+ <!-- Top face (parallelogram) -->
+ <polygon points="88,96 128,72 208,72 168,96" fill="none" stroke="url(#glow)" stroke-width="5" stroke-linejoin="round"/>
+ <!-- Right face -->
+ <polygon points="168,96 208,72 208,144 168,168" fill="none" stroke="url(#glow)" stroke-width="5" stroke-linejoin="round"/>
+ <!-- Inner glow dot — the "agent" -->
+ <circle cx="128" cy="132" r="16" fill="#818cf8" opacity="0.85"/>
+ <circle cx="128" cy="132" r="8" fill="#e0e7ff"/>
+</svg>
diff --git a/lobehub-plugin/assets/screenshots/README.txt b/lobehub-plugin/assets/screenshots/README.txt
new file mode 100644
index 000000000..28b5dfd93
--- /dev/null
+++ b/lobehub-plugin/assets/screenshots/README.txt
@@ -0,0 +1 @@
+Screenshots placeholder — replace with actual captures before publishing to LobeHub registry.
diff --git a/lobehub-plugin/dev/index.html b/lobehub-plugin/dev/index.html
new file mode 100644
index 000000000..77993a6cb
--- /dev/null
+++ b/lobehub-plugin/dev/index.html
@@ -0,0 +1,388 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <title>3D Agent — LobeHub Plugin Dev Harness</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <style>
+ *,
+ *::before,
+ *::after {
+ box-sizing: border-box;
+ }
+ body {
+ margin: 0;
+ font:
+ 14px/1.5 system-ui,
+ sans-serif;
+ background: #0f0f10;
+ color: #e0e0e0;
+ display: flex;
+ height: 100vh;
+ overflow: hidden;
+ }
+
+ /* ── Left: simulated LobeChat sidebar ── */
+ #sidebar {
+ width: 420px;
+ flex-shrink: 0;
+ background: #151618;
+ border-right: 1px solid #2a2a2e;
+ display: flex;
+ flex-direction: column;
+ }
+ #sidebar-header {
+ padding: 12px 16px;
+ border-bottom: 1px solid #2a2a2e;
+ font-size: 12px;
+ color: #888;
+ letter-spacing: 0.05em;
+ text-transform: uppercase;
+ }
+ #agent-frame {
+ flex: 1;
+ border: none;
+ width: 100%;
+ }
+
+ /* ── Right: control panel ── */
+ #controls {
+ flex: 1;
+ padding: 24px;
+ overflow-y: auto;
+ display: flex;
+ flex-direction: column;
+ gap: 20px;
+ }
+ h1 {
+ margin: 0 0 4px;
+ font-size: 18px;
+ font-weight: 600;
+ }
+ .subtitle {
+ color: #888;
+ font-size: 13px;
+ margin: 0 0 8px;
+ }
+ .section {
+ background: #151618;
+ border: 1px solid #2a2a2e;
+ border-radius: 8px;
+ padding: 16px;
+ }
+ .section h2 {
+ margin: 0 0 12px;
+ font-size: 13px;
+ font-weight: 600;
+ color: #aaa;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ }
+ .row {
+ display: flex;
+ gap: 8px;
+ align-items: center;
+ margin-bottom: 8px;
+ }
+ input[type='text'],
+ select {
+ flex: 1;
+ background: #0f0f10;
+ border: 1px solid #333;
+ border-radius: 6px;
+ color: #e0e0e0;
+ padding: 6px 10px;
+ font: inherit;
+ }
+ input[type='range'] {
+ flex: 1;
+ }
+ button {
+ background: #2563eb;
+ border: none;
+ border-radius: 6px;
+ color: #fff;
+ cursor: pointer;
+ font: inherit;
+ font-size: 13px;
+ padding: 6px 14px;
+ white-space: nowrap;
+ transition: background 0.15s;
+ }
+ button:hover {
+ background: #1d4ed8;
+ }
+ button.secondary {
+ background: #2a2a2e;
+ color: #ccc;
+ }
+ button.secondary:hover {
+ background: #333;
+ }
+ #log {
+ font: 12px/1.6 monospace;
+ color: #6ee7b7;
+ background: #0a0a0c;
+ border: 1px solid #1e3a2a;
+ border-radius: 6px;
+ padding: 10px;
+ max-height: 220px;
+ overflow-y: auto;
+ white-space: pre-wrap;
+ word-break: break-all;
+ }
+ .status-dot {
+ display: inline-block;
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background: #ef4444;
+ margin-right: 6px;
+ }
+ .status-dot.ready {
+ background: #22c55e;
+ }
+ label {
+ font-size: 12px;
+ color: #888;
+ }
+ </style>
+ </head>
+ <body>
+ <div id="sidebar">
+ <div id="sidebar-header">
+ <span id="status-dot" class="status-dot"></span>
+ 3D Agent sidebar
+ </div>
+ <iframe id="agent-frame" title="Agent embed"></iframe>
+ </div>
+
+ <div id="controls">
+ <div>
+ <h1>LobeHub Plugin Dev Harness</h1>
+ <p class="subtitle">
+ Simulates the LobeChat host. Use the controls below to verify the plugin without
+ running LobeChat.
+ </p>
+ </div>
+
+ <!-- Agent config -->
+ <div class="section">
+ <h2>Config</h2>
+ <div class="row">
+ <label style="width: 80px">Agent ID</label>
+ <input type="text" id="agent-id-input" placeholder="agent-xyz-123" />
+ </div>
+ <div class="row">
+ <label style="width: 80px">API Origin</label>
+ <input type="text" id="origin-input" value="https://3dagent.vercel.app" />
+ </div>
+ <div class="row">
+ <button id="load-btn">Load agent</button>
+ <button class="secondary" id="ping-btn">Ping</button>
+ </div>
+ </div>
+
+ <!-- Tool call simulation -->
+ <div class="section">
+ <h2>Inject tool call (simulates LobeChat calling the plugin API)</h2>
+ <div class="row">
+ <label style="width: 60px">Text</label>
+ <input type="text" id="speak-text" value="Hello! I am your 3D agent." />
+ </div>
+ <div class="row">
+ <label style="width: 60px">Sentiment</label>
+ <input type="range" id="sentiment" min="-1" max="1" step="0.1" value="0.3" />
+ <span id="sentiment-label">0.3</span>
+ </div>
+ <div class="row">
+ <button id="speak-btn">Inject speak</button>
+ </div>
+ <div class="row" style="margin-top: 8px">
+ <label style="width: 60px">Gesture</label>
+ <select id="gesture-select">
+ <option value="wave">wave</option>
+ <option value="nod">nod</option>
+ <option value="point">point</option>
+ <option value="shrug">shrug</option>
+ </select>
+ <button id="gesture-btn">Inject gesture</button>
+ </div>
+ <div class="row" style="margin-top: 8px">
+ <label style="width: 60px">Emote</label>
+ <select id="emote-select">
+ <option value="celebration">celebration</option>
+ <option value="curiosity">curiosity</option>
+ <option value="concern">concern</option>
+ <option value="patience">patience</option>
+ <option value="empathy">empathy</option>
+ </select>
+ <button id="emote-btn">Inject emote</button>
+ </div>
+ </div>
+
+ <!-- Log -->
+ <div class="section">
+ <h2>PostMessage log</h2>
+ <div id="log">Waiting for messages…</div>
+ </div>
+ </div>
+
+ <script>
+ // ── State ──────────────────────────────────────────────────────────────────
+
+ const frame = document.getElementById('agent-frame');
+ const log = document.getElementById('log');
+ const statusDot = document.getElementById('status-dot');
+ let agentId = '';
+ let apiOrigin = 'https://3dagent.vercel.app';
+ let pendingRequests = new Map();
+ let isReady = false;
+
+ function appendLog(msg) {
+ log.textContent += '\n' + new Date().toISOString().slice(11, 23) + ' ' + msg;
+ log.scrollTop = log.scrollHeight;
+ }
+
+ function newId() {
+ return crypto?.randomUUID?.() || Math.random().toString(36).slice(2);
+ }
+
+ // ── Iframe load ────────────────────────────────────────────────────────────
+
+ function loadAgent() {
+ agentId = document.getElementById('agent-id-input').value.trim();
+ apiOrigin = document.getElementById('origin-input').value.trim();
+ if (!agentId) {
+ alert('Enter an Agent ID first.');
+ return;
+ }
+ isReady = false;
+ statusDot.className = 'status-dot';
+ const url = `${apiOrigin}/lobehub/iframe/?agent=${encodeURIComponent(agentId)}&host=${encodeURIComponent(location.origin)}`;
+ frame.src = url;
+ appendLog(`→ Loading ${url}`);
+ }
+
+ document.getElementById('load-btn').addEventListener('click', loadAgent);
+
+ // ── Bridge (host side) ─────────────────────────────────────────────────────
+
+ function sendToFrame(envelope) {
+ if (!frame.contentWindow) return;
+ appendLog('→ ' + JSON.stringify(envelope));
+ frame.contentWindow.postMessage(envelope, '*');
+ }
+
+ function request(op, payload) {
+ return new Promise((resolve, reject) => {
+ const id = newId();
+ const timer = setTimeout(() => {
+ pendingRequests.delete(id);
+ reject(new Error(`Timeout: ${op}`));
+ }, 10000);
+ pendingRequests.set(id, { resolve, reject, timer });
+ sendToFrame({
+ v: 1,
+ source: 'agent-host',
+ id,
+ kind: 'request',
+ op,
+ payload: payload || {},
+ });
+ });
+ }
+
+ window.addEventListener('message', (ev) => {
+ const d = ev.data;
+ if (!d || typeof d !== 'object') return;
+ appendLog('← ' + JSON.stringify(d));
+
+ // v1 spec envelope
+ if (d.v === 1 && d.source === 'agent-3d') {
+ if (d.kind === 'event' && d.op === 'ready') {
+ isReady = true;
+ statusDot.className = 'status-dot ready';
+ // Complete handshake
+ request('ping', {})
+ .then(() => appendLog('✓ Handshake complete'))
+ .catch((e) => appendLog('✗ Ping failed: ' + e.message));
+ }
+ if (d.kind === 'response' && d.inReplyTo) {
+ const entry = pendingRequests.get(d.inReplyTo);
+ if (entry) {
+ clearTimeout(entry.timer);
+ pendingRequests.delete(d.inReplyTo);
+ entry.resolve(d.payload);
+ }
+ }
+ }
+ });
+
+ // ── Control buttons ────────────────────────────────────────────────────────
+
+ document.getElementById('ping-btn').addEventListener('click', () => {
+ request('ping', {})
+ .then(() => appendLog('✓ pong'))
+ .catch((e) => appendLog('✗ ' + e.message));
+ });
+
+ document.getElementById('speak-btn').addEventListener('click', () => {
+ const text = document.getElementById('speak-text').value.trim();
+ const sentiment = parseFloat(document.getElementById('sentiment').value);
+ if (!text) return;
+
+ // Simulate LobeChat sending a tool call via postMessage
+ // (this is what @lobehub/chat-plugin-sdk sends from the host page)
+ const lobeMsg = {
+ type: 'LobePlugin.renderPlugin',
+ payload: {
+ apiName: 'speak',
+ arguments: JSON.stringify({ text, sentiment }),
+ identifier: '3d-agent',
+ },
+ };
+ appendLog('→ [LobeChat sim] ' + JSON.stringify(lobeMsg));
+ // Post to the AgentPane's window context (simulates LobeChat → plugin iframe).
+ // In real LobeChat, this goes to the React plugin's window, not directly to the
+ // agent iframe. The AgentPane then uses the bridge to forward it.
+ // Here we send directly to the agent iframe for simplicity.
+ request('speak', { text, sentiment })
+ .then(() => appendLog('✓ speak dispatched'))
+ .catch((e) => appendLog('✗ ' + e.message));
+ });
+
+ document.getElementById('gesture-btn').addEventListener('click', () => {
+ const name = document.getElementById('gesture-select').value;
+ request('gesture', { name })
+ .then(() => appendLog('✓ gesture dispatched'))
+ .catch((e) => appendLog('✗ ' + e.message));
+ });
+
+ document.getElementById('emote-btn').addEventListener('click', () => {
+ const trigger = document.getElementById('emote-select').value;
+ request('emote', { trigger, weight: 1 })
+ .then(() => appendLog('✓ emote dispatched'))
+ .catch((e) => appendLog('✗ ' + e.message));
+ });
+
+ // ── Sentiment slider label ─────────────────────────────────────────────────
+
+ document.getElementById('sentiment').addEventListener('input', (e) => {
+ document.getElementById('sentiment-label').textContent = parseFloat(
+ e.target.value,
+ ).toFixed(1);
+ });
+
+ // ── Auto-load from query params ────────────────────────────────────────────
+
+ const qp = new URLSearchParams(location.search);
+ if (qp.get('agent')) {
+ document.getElementById('agent-id-input').value = qp.get('agent');
+ if (qp.get('origin'))
+ document.getElementById('origin-input').value = qp.get('origin');
+ loadAgent();
+ }
+ </script>
+ </body>
+</html>
diff --git a/lobehub-plugin/manifest.json b/lobehub-plugin/manifest.json
index 94b4d60ad..5ac5fd9ae 100644
--- a/lobehub-plugin/manifest.json
+++ b/lobehub-plugin/manifest.json
@@ -13,6 +13,11 @@
},
"settings": [
{ "name": "agentId", "type": "string", "required": true, "title": "Agent ID" },
- { "name": "apiOrigin", "type": "string", "default": "https://3dagent.vercel.app", "title": "API Origin" }
+ {
+ "name": "apiOrigin",
+ "type": "string",
+ "default": "https://3dagent.vercel.app",
+ "title": "API Origin"
+ }
]
}
diff --git a/lobehub-plugin/package-lock.json b/lobehub-plugin/package-lock.json
index 2762af1b2..6c42f5522 100644
--- a/lobehub-plugin/package-lock.json
+++ b/lobehub-plugin/package-lock.json
@@ -8,6 +8,9 @@
"name": "@3dagent/lobehub-plugin",
"version": "1.0.0",
"license": "MIT",
+ "dependencies": {
+ "@lobehub/chat-plugin-sdk": "^1.0.0"
+ },
"devDependencies": {
"@types/react": "^18.2.0",
"@types/react-dom": "^18.2.0",
@@ -19,6 +22,77 @@
"react-dom": "^18.0.0"
}
},
+ "node_modules/@apidevtools/json-schema-ref-parser": {
+ "version": "11.7.2",
+ "resolved": "https://registry.npmjs.org/@apidevtools/json-schema-ref-parser/-/json-schema-ref-parser-11.7.2.tgz",
+ "integrity": "sha512-4gY54eEGEstClvEkGnwVkTkrx0sqwemEFG5OSRRn3tD91XH0+Q8XIkYIfo7IwEWPpJZwILb9GUXeShtplRc/eA==",
+ "license": "MIT",
+ "dependencies": {
+ "@jsdevtools/ono": "^7.1.3",
+ "@types/json-schema": "^7.0.15",
+ "js-yaml": "^4.1.0"
+ },
+ "engines": {
+ "node": ">= 16"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/philsturgeon"
+ }
+ },
+ "node_modules/@apidevtools/openapi-schemas": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/@apidevtools/openapi-schemas/-/openapi-schemas-2.1.0.tgz",
+ "integrity": "sha512-Zc1AlqrJlX3SlpupFGpiLi2EbteyP7fXmUOGup6/DnkRgjP9bgMM/ag+n91rsv0U1Gpz0H3VILA/o3bW7Ua6BQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/@apidevtools/swagger-methods": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/@apidevtools/swagger-methods/-/swagger-methods-3.0.2.tgz",
+ "integrity": "sha512-QAkD5kK2b1WfjDS/UQn/qQkbwF31uqRjPTrsCs5ZG9BQGAkjwvqGFjjPqAuzac/IYzpPtRzjCP1WrTuAIjMrXg==",
+ "license": "MIT"
+ },
+ "node_modules/@apidevtools/swagger-parser": {
+ "version": "10.1.1",
+ "resolved": "https://registry.npmjs.org/@apidevtools/swagger-parser/-/swagger-parser-10.1.1.tgz",
+ "integrity": "sha512-u/kozRnsPO/x8QtKYJOqoGtC4kH6yg1lfYkB9Au0WhYB0FNLpyFusttQtvhlwjtG3rOwiRz4D8DnnXa8iEpIKA==",
+ "license": "MIT",
+ "dependencies": {
+ "@apidevtools/json-schema-ref-parser": "11.7.2",
+ "@apidevtools/openapi-schemas": "^2.1.0",
+ "@apidevtools/swagger-methods": "^3.0.2",
+ "@jsdevtools/ono": "^7.1.3",
+ "ajv": "^8.17.1",
+ "ajv-draft-04": "^1.0.0",
+ "call-me-maybe": "^1.0.2"
+ },
+ "peerDependencies": {
+ "openapi-types": ">=7"
+ }
+ },
+ "node_modules/@babel/runtime": {
+ "version": "7.29.2",
+ "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.2.tgz",
+ "integrity": "sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/runtime-corejs3": {
+ "version": "7.29.2",
+ "resolved": "https://registry.npmjs.org/@babel/runtime-corejs3/-/runtime-corejs3-7.29.2.tgz",
+ "integrity": "sha512-Lc94FOD5+0aXhdb0Tdg3RUtqT6yWbI/BbFWvlaSJ3gAb9Ks+99nHRDKADVqC37er4eCB0fHyWT+y+K3QOvJKbw==",
+ "license": "MIT",
+ "dependencies": {
+ "core-js-pure": "^3.48.0"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
"node_modules/@esbuild/aix-ppc64": {
"version": "0.21.5",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",
@@ -410,6 +484,703 @@
"node": ">=12"
}
},
+ "node_modules/@jsdevtools/ono": {
+ "version": "7.1.3",
+ "resolved": "https://registry.npmjs.org/@jsdevtools/ono/-/ono-7.1.3.tgz",
+ "integrity": "sha512-4JQNk+3mVzK3xh2rqd6RB4J46qUR19azEHBneZyTZM+c456qOrbbM/5xcR8huNCCcbVt7+UmizG6GuUvPvKUYg==",
+ "license": "MIT"
+ },
+ "node_modules/@lobehub/chat-plugin-sdk": {
+ "version": "1.32.4",
+ "resolved": "https://registry.npmjs.org/@lobehub/chat-plugin-sdk/-/chat-plugin-sdk-1.32.4.tgz",
+ "integrity": "sha512-dEYNqFr+FzMIRsBLjPC7VPSueX5U9zDKvI9oT9xWrzKGRiTE4oFznf8Z4VGb44h2a2r2nkZ0EzNvOZ+XV2qcUg==",
+ "license": "MIT",
+ "dependencies": {
+ "@apidevtools/swagger-parser": "^10.1.0",
+ "@babel/runtime": "^7.23.2",
+ "@types/json-schema": "^7.0.14",
+ "openapi-jsonschema-parameters": "^12.1.3",
+ "openapi-types": "^12.1.3",
+ "swagger-client": "^3.24.6",
+ "zod": "^3.22.4"
+ },
+ "peerDependencies": {
+ "react": ">=18",
+ "react-dom": ">=18"
+ }
+ },
+ "node_modules/@scarf/scarf": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/@scarf/scarf/-/scarf-1.4.0.tgz",
+ "integrity": "sha512-xxeapPiUXdZAE3che6f3xogoJPeZgig6omHEy1rIY5WVsB3H2BHNnZH+gHG6x91SCWyQCzWGsuL2Hh3ClO5/qQ==",
+ "hasInstallScript": true,
+ "license": "Apache-2.0"
+ },
+ "node_modules/@swagger-api/apidom-ast": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ast/-/apidom-ast-1.10.2.tgz",
+ "integrity": "sha512-vTl8gWyeZaj887/NSWYs3as4K8wXHar5wY/606XRBjR2UgmJBokBgKjq7S23LW9tsYjsT4MjQKC8idjgw17xvg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-error": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0",
+ "unraw": "^3.0.0"
+ }
+ },
+ "node_modules/@swagger-api/apidom-core": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-core/-/apidom-core-1.10.2.tgz",
+ "integrity": "sha512-qryNBGHNWDvSRyK1w5rox0UOrHrVBjZOHgeXFpGHF+oBO7ntSc/H7BSiYMDR+KQESkzMcAxn4tZMLYItaBt06w==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-ast": "^1.10.2",
+ "@swagger-api/apidom-error": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "minim": "~0.23.8",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0",
+ "short-unique-id": "^5.3.2",
+ "ts-mixer": "^6.0.3"
+ }
+ },
+ "node_modules/@swagger-api/apidom-error": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-error/-/apidom-error-1.10.2.tgz",
+ "integrity": "sha512-SWyPyL5xwTUsDzPi0A5zwTFwqPezvlwj4opEqruqjESNTYupUA7+vt4Mdj7IlDaRYRG1qyCWQgKhIBXznVUD4w==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.20.7"
+ }
+ },
+ "node_modules/@swagger-api/apidom-json-pointer": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-json-pointer/-/apidom-json-pointer-1.10.2.tgz",
+ "integrity": "sha512-zySHPqIXF4HZ3VWbHwTxO+H1e9dJw7mGHzoX+tZjx5wVyLQO3kZDCAAXzz3c3/TIY21Y2Zkpkez3q9hjFyuLvQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-error": "^1.10.2",
+ "@swaggerexpert/json-pointer": "^2.10.1"
+ }
+ },
+ "node_modules/@swagger-api/apidom-ns-api-design-systems": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-api-design-systems/-/apidom-ns-api-design-systems-1.10.2.tgz",
+ "integrity": "sha512-MsZ4GWmWN7wkWv7G9Pwk8sHU1j0bwk7xoGeaZmNCylbTfYvGkg6jJGMHdAdQNCQXbbpfLeKt1O+3YCN//JUQ7w==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-error": "^1.10.2",
+ "@swagger-api/apidom-ns-openapi-3-1": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0",
+ "ts-mixer": "^6.0.3"
+ }
+ },
+ "node_modules/@swagger-api/apidom-ns-arazzo-1": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-arazzo-1/-/apidom-ns-arazzo-1-1.10.2.tgz",
+ "integrity": "sha512-fQSwDlIR85tbnLXAjtV/ypSGUBfrzFcZ4NbH6BL1DSTR4uEunVxAULdD4wlhCt9gGNDl/zxZD3vQtlYDkXDFmw==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-ns-json-schema-2020-12": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0",
+ "ts-mixer": "^6.0.3"
+ }
+ },
+ "node_modules/@swagger-api/apidom-ns-asyncapi-2": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-asyncapi-2/-/apidom-ns-asyncapi-2-1.10.2.tgz",
+ "integrity": "sha512-obWHe3pyAj65Nf9ISwnbtJ4C5mZ15C6mtQXxzHVW5maVZqlqt3s/YbPY87EqK9ArdNOwOZHkQt2Uth02GMmjxA==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-ns-json-schema-draft-7": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0",
+ "ts-mixer": "^6.0.3"
+ }
+ },
+ "node_modules/@swagger-api/apidom-ns-asyncapi-3": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-asyncapi-3/-/apidom-ns-asyncapi-3-1.10.2.tgz",
+ "integrity": "sha512-yqNmXeObF2OLAusgGEapXz2CrGjXwkcfG3DYcQDtOvgRytvGZxC2EkCUR+wEXCVNYhoJ7QpVzzTJOHs3jOvptg==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-ns-asyncapi-2": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0",
+ "ts-mixer": "^6.0.3"
+ }
+ },
+ "node_modules/@swagger-api/apidom-ns-json-schema-2019-09": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-json-schema-2019-09/-/apidom-ns-json-schema-2019-09-1.10.2.tgz",
+ "integrity": "sha512-I1FaBoDFMjybF4QVsesIYl8OilkwycZ0mQ0jf1P++zfTRG27uIePB8M+Iuj6iqMsE3qpkjjJJ6ZLnrLPdKvmRw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-error": "^1.10.2",
+ "@swagger-api/apidom-ns-json-schema-draft-7": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0",
+ "ts-mixer": "^6.0.4"
+ }
+ },
+ "node_modules/@swagger-api/apidom-ns-json-schema-2020-12": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-json-schema-2020-12/-/apidom-ns-json-schema-2020-12-1.10.2.tgz",
+ "integrity": "sha512-lg9XfRlJRNoBa2EDGpEFc7HvFV39G6RG0/SbjQY0BE/WZer10wmfTCU7l3RUNJXRFGKH6/O/nsYgP7AFjTanXQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-error": "^1.10.2",
+ "@swagger-api/apidom-ns-json-schema-2019-09": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0",
+ "ts-mixer": "^6.0.4"
+ }
+ },
+ "node_modules/@swagger-api/apidom-ns-json-schema-draft-4": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-json-schema-draft-4/-/apidom-ns-json-schema-draft-4-1.10.2.tgz",
+ "integrity": "sha512-C50KnSKynrmHky/oOB6+hHyZVpwng78Fz5aZjay3h8X5C/PJHmm3sDJFvF3/9wkYHO3N9sPp7cpu4Xm9VJ4/wQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-ast": "^1.10.2",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0",
+ "ts-mixer": "^6.0.4"
+ }
+ },
+ "node_modules/@swagger-api/apidom-ns-json-schema-draft-6": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-json-schema-draft-6/-/apidom-ns-json-schema-draft-6-1.10.2.tgz",
+ "integrity": "sha512-/wiP8+2lF8UJRrkoQ9HvKnMbnqijk2uY/hAg+/Bo73T9NGKkEa29jYVUKYNYj7gJBw4hhkUHfHFWuZUpxPC4ZA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-error": "^1.10.2",
+ "@swagger-api/apidom-ns-json-schema-draft-4": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0",
+ "ts-mixer": "^6.0.4"
+ }
+ },
+ "node_modules/@swagger-api/apidom-ns-json-schema-draft-7": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-json-schema-draft-7/-/apidom-ns-json-schema-draft-7-1.10.2.tgz",
+ "integrity": "sha512-firN/uvnVxQgACqcyzV3NU9qjbMvNMJkpmm3wOat3URmaFMaFBT3qjbU1pFHBGbnXI3+I9pQJZHmJSwqNzfUbQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-error": "^1.10.2",
+ "@swagger-api/apidom-ns-json-schema-draft-6": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0",
+ "ts-mixer": "^6.0.4"
+ }
+ },
+ "node_modules/@swagger-api/apidom-ns-openapi-2": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-openapi-2/-/apidom-ns-openapi-2-1.10.2.tgz",
+ "integrity": "sha512-FK5kYvo/1uwAByumRVRsynBlnKxUUImfsjPEFgRCW6yhbCGRqN47NaZ7GYFHpbhjC3OmMN5/etYj6B0jnZx7Gg==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-error": "^1.10.2",
+ "@swagger-api/apidom-ns-json-schema-draft-4": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0",
+ "ts-mixer": "^6.0.3"
+ }
+ },
+ "node_modules/@swagger-api/apidom-ns-openapi-3-0": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-openapi-3-0/-/apidom-ns-openapi-3-0-1.10.2.tgz",
+ "integrity": "sha512-ziyv85QbJYHRdc9oTEFBy3pxwxg7BW/a9GrwH01/SmuXVQPjLjwzRb+SjCxLogJppm0yjxOkDFI2VWPp2RADFg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-error": "^1.10.2",
+ "@swagger-api/apidom-ns-json-schema-draft-4": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0",
+ "ts-mixer": "^6.0.3"
+ }
+ },
+ "node_modules/@swagger-api/apidom-ns-openapi-3-1": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-openapi-3-1/-/apidom-ns-openapi-3-1-1.10.2.tgz",
+ "integrity": "sha512-ngcmO4dH77JT5hZB04OJdyTzgKnt2lNhAZQ+4wXjum/xhszjUmDhOeYfXdHw3Lm7MxsEsTesWzLYQ5LKADc41A==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-ast": "^1.10.2",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-json-pointer": "^1.10.2",
+ "@swagger-api/apidom-ns-json-schema-2020-12": "^1.10.2",
+ "@swagger-api/apidom-ns-openapi-3-0": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0",
+ "ts-mixer": "^6.0.3"
+ }
+ },
+ "node_modules/@swagger-api/apidom-ns-openapi-3-2": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-ns-openapi-3-2/-/apidom-ns-openapi-3-2-1.10.2.tgz",
+ "integrity": "sha512-3SWJ5ipWwn+w11HTUESWex/522jy2aGLzBqqMgH36sy+Wdwx+9Mw2bgSDqkxmNC5+jpzOGUOIWoQAMuCpS/Gzg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-ast": "^1.10.2",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-json-pointer": "^1.10.2",
+ "@swagger-api/apidom-ns-json-schema-2020-12": "^1.10.2",
+ "@swagger-api/apidom-ns-openapi-3-0": "^1.10.2",
+ "@swagger-api/apidom-ns-openapi-3-1": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0",
+ "ts-mixer": "^6.0.3"
+ }
+ },
+ "node_modules/@swagger-api/apidom-parser-adapter-api-design-systems-json": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-api-design-systems-json/-/apidom-parser-adapter-api-design-systems-json-1.10.2.tgz",
+ "integrity": "sha512-kzhJUGzsJ38Uohj5xRQDkQC08rqNhatbqgD30LZ0/UWryJ9nAsjqK2ovuP9t+5WKcDE4iwcYeGSt1NA2XgEZwg==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-ns-api-design-systems": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-json": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0"
+ }
+ },
+ "node_modules/@swagger-api/apidom-parser-adapter-api-design-systems-yaml": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-api-design-systems-yaml/-/apidom-parser-adapter-api-design-systems-yaml-1.10.2.tgz",
+ "integrity": "sha512-i3CmSxJ/iG67ybRDAJ9xpuMrOMFvC/obX2lI36E0VZzBTb+llw4Zd5qFmBqNnImLpwdmk11Z1V7i+5HM+J7ijQ==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-ns-api-design-systems": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0"
+ }
+ },
+ "node_modules/@swagger-api/apidom-parser-adapter-arazzo-json-1": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-arazzo-json-1/-/apidom-parser-adapter-arazzo-json-1-1.10.2.tgz",
+ "integrity": "sha512-HwiUkwvo5i2hV2SS6KWrdj62BdceZGfhuXhr1il8akWekpU4jXPtr5pv4gOnKKJN7VgjAmwt/DlcCSRo1+9jVA==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-ns-arazzo-1": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-json": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0"
+ }
+ },
+ "node_modules/@swagger-api/apidom-parser-adapter-arazzo-yaml-1": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-arazzo-yaml-1/-/apidom-parser-adapter-arazzo-yaml-1-1.10.2.tgz",
+ "integrity": "sha512-w8VTVuE7GPbRqWxvMgRoTb726JRsMhFPMfTBf8+MJ4pQThjk78dSXPV2Zlse71b2DWBuQy2sr6zGyLUNs/3ePQ==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-ns-arazzo-1": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0"
+ }
+ },
+ "node_modules/@swagger-api/apidom-parser-adapter-asyncapi-json-2": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-asyncapi-json-2/-/apidom-parser-adapter-asyncapi-json-2-1.10.2.tgz",
+ "integrity": "sha512-FDNjqmn2vV1jFoVVwQDO0XPPm8R5xzmcyY/6yBLFmKZADin3smSKVZ+njYHmfRjpspXwN0AwI0drdvuH0FZLJg==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-ns-asyncapi-2": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-json": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0"
+ }
+ },
+ "node_modules/@swagger-api/apidom-parser-adapter-asyncapi-json-3": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-asyncapi-json-3/-/apidom-parser-adapter-asyncapi-json-3-1.10.2.tgz",
+ "integrity": "sha512-x/0vM2nDDzYzFnXr69+so/KSH+2py2TiZd1K49pWcX8cHsPV1Y4Ppih7GVOMymd8m/IOCjLYlV7qt4eWDwdldg==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-ns-asyncapi-3": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-json": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0"
+ }
+ },
+ "node_modules/@swagger-api/apidom-parser-adapter-asyncapi-yaml-2": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-asyncapi-yaml-2/-/apidom-parser-adapter-asyncapi-yaml-2-1.10.2.tgz",
+ "integrity": "sha512-2bVACmU9ZmAVVnqQWSc3Bs+xG0HHLU1tfZbYL8xNgSi8kw4HcnejF5mWtN+MLFzTaBmWCi2In7P7BYNR8+2Dyg==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-ns-asyncapi-2": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0"
+ }
+ },
+ "node_modules/@swagger-api/apidom-parser-adapter-asyncapi-yaml-3": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-asyncapi-yaml-3/-/apidom-parser-adapter-asyncapi-yaml-3-1.10.2.tgz",
+ "integrity": "sha512-oHpbf+iqBcDS3qtsipMpgCwAeckKMxg0qFKYTCRZyJdctRgupJTxVeir6t/SGo0Ny0a1iknt2LN0u5frEen0kg==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-ns-asyncapi-3": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0"
+ }
+ },
+ "node_modules/@swagger-api/apidom-parser-adapter-json": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-json/-/apidom-parser-adapter-json-1.10.2.tgz",
+ "integrity": "sha512-VnwEkarKfsJYRF0zCI9AGiSIyBUXqS2d32KQuhVCt/HeuF1XO9sjeLjGiosA/24YVOnO0ul5TpiNFQn0pw89mA==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-ast": "^1.10.2",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-error": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0",
+ "tree-sitter": "=0.21.1",
+ "tree-sitter-json": "=0.24.8",
+ "web-tree-sitter": "=0.24.5"
+ }
+ },
+ "node_modules/@swagger-api/apidom-parser-adapter-openapi-json-2": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-openapi-json-2/-/apidom-parser-adapter-openapi-json-2-1.10.2.tgz",
+ "integrity": "sha512-+d/o/8TrNBjvFzgPb0RQhrCc8gOWnrHZF+xvCO5gwp+4MUr1XP1AJIox1e6t1SO+j7IQjiF2ocx2r7eFE5QC7w==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-ns-openapi-2": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-json": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0"
+ }
+ },
+ "node_modules/@swagger-api/apidom-parser-adapter-openapi-json-3-0": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-openapi-json-3-0/-/apidom-parser-adapter-openapi-json-3-0-1.10.2.tgz",
+ "integrity": "sha512-3ieUeX8/WywkUzdOO1U1QKQDNmpZFfOeTAeb4ISDd/PKOVwuEx/b0w5I8EuOu97tKAe3UUesEdii+pJlkcFlFw==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-ns-openapi-3-0": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-json": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0"
+ }
+ },
+ "node_modules/@swagger-api/apidom-parser-adapter-openapi-json-3-1": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-openapi-json-3-1/-/apidom-parser-adapter-openapi-json-3-1-1.10.2.tgz",
+ "integrity": "sha512-z0c7IgMPLSDhE+ldTb54Xlhq+yPF0w/8LHXyeHX4V6BS1VG3Utb+mM/qTVfy1Eo+p1KGNlwNDEPsBp6jIaVb5Q==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-ns-openapi-3-1": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-json": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0"
+ }
+ },
+ "node_modules/@swagger-api/apidom-parser-adapter-openapi-json-3-2": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-openapi-json-3-2/-/apidom-parser-adapter-openapi-json-3-2-1.10.2.tgz",
+ "integrity": "sha512-bx/kEIXWtpHu+4LEiyNdt0v8ER5EVwPjhQdlpOaC5qghnRH9aUYOTawZtVHsNHAQWTIMNn9DdPKYQgttQKD0Pw==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-ns-openapi-3-2": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-json": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0"
+ }
+ },
+ "node_modules/@swagger-api/apidom-parser-adapter-openapi-yaml-2": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-openapi-yaml-2/-/apidom-parser-adapter-openapi-yaml-2-1.10.2.tgz",
+ "integrity": "sha512-e86JUXHGGEVsO4/xpy/GRSvYXGN30hLt1lMUhjzCFuE95N6/K3hmQHE3rA/H7ot1ajCWUhzukW5rGQac79NIjA==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-ns-openapi-2": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0"
+ }
+ },
+ "node_modules/@swagger-api/apidom-parser-adapter-openapi-yaml-3-0": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-openapi-yaml-3-0/-/apidom-parser-adapter-openapi-yaml-3-0-1.10.2.tgz",
+ "integrity": "sha512-ucfc13Ai31tJ0ruAm1YiHhqENgcBuiOXL00OhoICWA56ggAcnA5WfWmvtsXVMlZsTHVbhZP3XpsH5rui2N8u5w==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-ns-openapi-3-0": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0"
+ }
+ },
+ "node_modules/@swagger-api/apidom-parser-adapter-openapi-yaml-3-1": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-openapi-yaml-3-1/-/apidom-parser-adapter-openapi-yaml-3-1-1.10.2.tgz",
+ "integrity": "sha512-7o8j93qgf9yYAaaJ/GpH+5sB3fC9EmvmjTCqlw5YWXp+cRgCn9q7f80Sv4+NjbracUafB6qL4i9F/m+Xs0XZaQ==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-ns-openapi-3-1": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0"
+ }
+ },
+ "node_modules/@swagger-api/apidom-parser-adapter-openapi-yaml-3-2": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-openapi-yaml-3-2/-/apidom-parser-adapter-openapi-yaml-3-2-1.10.2.tgz",
+ "integrity": "sha512-blDIeVmo8bpXYV/C+b6PYi54yS+5jPEZTFsK5jQ2NzpCPrkBPacp/KTuHBUBzJsYj4bj/ivRL3+JXGw4YovUHw==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-ns-openapi-3-2": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0"
+ }
+ },
+ "node_modules/@swagger-api/apidom-parser-adapter-yaml-1-2": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-parser-adapter-yaml-1-2/-/apidom-parser-adapter-yaml-1-2-1.10.2.tgz",
+ "integrity": "sha512-I5eCls8XS3SVEwH/cuL6T3iar1TPaFYh3gXwS/2rzP1aZQNKSHDP3y3ney7nAomKG4dFvE8Q248FL36arG7T/w==",
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-ast": "^1.10.2",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-error": "^1.10.2",
+ "@tree-sitter-grammars/tree-sitter-yaml": "=0.7.1",
+ "@types/ramda": "~0.30.0",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0",
+ "tree-sitter": "=0.22.4",
+ "web-tree-sitter": "=0.24.5"
+ }
+ },
+ "node_modules/@swagger-api/apidom-parser-adapter-yaml-1-2/node_modules/@tree-sitter-grammars/tree-sitter-yaml": {
+ "version": "0.7.1",
+ "resolved": "https://registry.npmjs.org/@tree-sitter-grammars/tree-sitter-yaml/-/tree-sitter-yaml-0.7.1.tgz",
+ "integrity": "sha512-AynBwkIoQCTgjDR33bDUp9Mqq+YTco0is3n5hRApMqG9of/6A4eQsfC1/uSEeHSUyMQSYawcAWamsexnVpIP4Q==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "node-addon-api": "^8.3.1",
+ "node-gyp-build": "^4.8.4"
+ },
+ "peerDependencies": {
+ "tree-sitter": "^0.22.4"
+ },
+ "peerDependenciesMeta": {
+ "tree-sitter": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@swagger-api/apidom-parser-adapter-yaml-1-2/node_modules/tree-sitter": {
+ "version": "0.22.4",
+ "resolved": "https://registry.npmjs.org/tree-sitter/-/tree-sitter-0.22.4.tgz",
+ "integrity": "sha512-usbHZP9/oxNsUY65MQUsduGRqDHQOou1cagUSwjhoSYAmSahjQDAVsh9s+SlZkn8X8+O1FULRGwHu7AFP3kjzg==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "node-addon-api": "^8.3.0",
+ "node-gyp-build": "^4.8.4"
+ }
+ },
+ "node_modules/@swagger-api/apidom-reference": {
+ "version": "1.10.2",
+ "resolved": "https://registry.npmjs.org/@swagger-api/apidom-reference/-/apidom-reference-1.10.2.tgz",
+ "integrity": "sha512-H5UqOmae9CXdiLJbbh1j+/hwvcECmr6ci2XtUKTQpFviemvsIDZmPV1DKUAxCfzGr2iOkDO6SZc+/OEWlETqiQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.26.10",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-error": "^1.10.2",
+ "@types/ramda": "~0.30.0",
+ "axios": "^1.15.0",
+ "minimatch": "^10.2.1",
+ "ramda": "~0.30.0",
+ "ramda-adjunct": "^5.0.0"
+ },
+ "optionalDependencies": {
+ "@swagger-api/apidom-json-pointer": "^1.10.2",
+ "@swagger-api/apidom-ns-arazzo-1": "^1.10.2",
+ "@swagger-api/apidom-ns-asyncapi-2": "^1.10.2",
+ "@swagger-api/apidom-ns-openapi-2": "^1.10.2",
+ "@swagger-api/apidom-ns-openapi-3-0": "^1.10.2",
+ "@swagger-api/apidom-ns-openapi-3-1": "^1.10.2",
+ "@swagger-api/apidom-ns-openapi-3-2": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-api-design-systems-json": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-api-design-systems-yaml": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-arazzo-json-1": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-arazzo-yaml-1": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-asyncapi-json-2": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-asyncapi-json-3": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-asyncapi-yaml-2": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-asyncapi-yaml-3": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-json": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-openapi-json-2": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-openapi-json-3-0": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-openapi-json-3-1": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-openapi-json-3-2": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-openapi-yaml-2": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-openapi-yaml-3-0": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-openapi-yaml-3-1": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-openapi-yaml-3-2": "^1.10.2",
+ "@swagger-api/apidom-parser-adapter-yaml-1-2": "^1.10.2"
+ }
+ },
+ "node_modules/@swaggerexpert/cookie": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/@swaggerexpert/cookie/-/cookie-2.0.2.tgz",
+ "integrity": "sha512-DPI8YJ0Vznk4CT+ekn3rcFNq1uQwvUHZhH6WvTSPD0YKBIlMS9ur2RYKghXuxxOiqOam/i4lHJH4xTIiTgs3Mg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "apg-lite": "^1.0.3"
+ },
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
+ "node_modules/@swaggerexpert/json-pointer": {
+ "version": "2.10.2",
+ "resolved": "https://registry.npmjs.org/@swaggerexpert/json-pointer/-/json-pointer-2.10.2.tgz",
+ "integrity": "sha512-qMx1nOrzoB+PF+pzb26Q4Tc2sOlrx9Ba2UBNX9hB31Omrq+QoZ2Gly0KLrQWw4Of1AQ4J9lnD+XOdwOdcdXqqw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "apg-lite": "^1.0.4"
+ },
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
+ "node_modules/@types/json-schema": {
+ "version": "7.0.15",
+ "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
+ "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",
+ "license": "MIT"
+ },
"node_modules/@types/prop-types": {
"version": "15.7.15",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",
@@ -417,6 +1188,15 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@types/ramda": {
+ "version": "0.30.2",
+ "resolved": "https://registry.npmjs.org/@types/ramda/-/ramda-0.30.2.tgz",
+ "integrity": "sha512-PyzHvjCalm2BRYjAU6nIB3TprYwMNOUY/7P/N8bSzp9W/yM2YrtGtAnnVtaCNSeOZ8DzKyFDvaqQs7LnWwwmBA==",
+ "license": "MIT",
+ "dependencies": {
+ "types-ramda": "^0.30.1"
+ }
+ },
"node_modules/@types/react": {
"version": "18.3.28",
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.28.tgz",
@@ -438,15 +1218,214 @@
"@types/react": "^18.0.0"
}
},
- "node_modules/csstype": {
- "version": "3.2.3",
- "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
- "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
- "dev": true,
- "license": "MIT"
+ "node_modules/ajv": {
+ "version": "8.18.0",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz",
+ "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==",
+ "license": "MIT",
+ "dependencies": {
+ "fast-deep-equal": "^3.1.3",
+ "fast-uri": "^3.0.1",
+ "json-schema-traverse": "^1.0.0",
+ "require-from-string": "^2.0.2"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/epoberezkin"
+ }
},
- "node_modules/esbuild": {
- "version": "0.21.5",
+ "node_modules/ajv-draft-04": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/ajv-draft-04/-/ajv-draft-04-1.0.0.tgz",
+ "integrity": "sha512-mv00Te6nmYbRp5DCwclxtt7yV/joXJPGS7nM+97GdxvuttCOfgI3K4U25zboyeX0O+myI8ERluxQe5wljMmVIw==",
+ "license": "MIT",
+ "peerDependencies": {
+ "ajv": "^8.5.0"
+ },
+ "peerDependenciesMeta": {
+ "ajv": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/apg-lite": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/apg-lite/-/apg-lite-1.0.5.tgz",
+ "integrity": "sha512-SlI+nLMQDzCZfS39ihzjGp3JNBQfJXyMi6cg9tkLOCPVErgFsUIAEdO9IezR7kbP5Xd0ozcPNQBkf9TO5cHgWw==",
+ "license": "BSD-2-Clause"
+ },
+ "node_modules/argparse": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
+ "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
+ "license": "Python-2.0"
+ },
+ "node_modules/asynckit": {
+ "version": "0.4.0",
+ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
+ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
+ "license": "MIT"
+ },
+ "node_modules/axios": {
+ "version": "1.15.0",
+ "resolved": "https://registry.npmjs.org/axios/-/axios-1.15.0.tgz",
+ "integrity": "sha512-wWyJDlAatxk30ZJer+GeCWS209sA42X+N5jU2jy6oHTp7ufw8uzUTVFBX9+wTfAlhiJXGS0Bq7X6efruWjuK9Q==",
+ "license": "MIT",
+ "dependencies": {
+ "follow-redirects": "^1.15.11",
+ "form-data": "^4.0.5",
+ "proxy-from-env": "^2.1.0"
+ }
+ },
+ "node_modules/balanced-match": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
+ "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",
+ "license": "MIT",
+ "engines": {
+ "node": "18 || 20 || >=22"
+ }
+ },
+ "node_modules/brace-expansion": {
+ "version": "5.0.5",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.5.tgz",
+ "integrity": "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==",
+ "license": "MIT",
+ "dependencies": {
+ "balanced-match": "^4.0.2"
+ },
+ "engines": {
+ "node": "18 || 20 || >=22"
+ }
+ },
+ "node_modules/call-bind-apply-helpers": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "function-bind": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/call-me-maybe": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/call-me-maybe/-/call-me-maybe-1.0.2.tgz",
+ "integrity": "sha512-HpX65o1Hnr9HH25ojC1YGs7HCQLq0GCOibSaWER0eNpgJ/Z1MZv2mTc7+xh6WOPxbRVcmgbv4hGU+uSQ/2xFZQ==",
+ "license": "MIT"
+ },
+ "node_modules/combined-stream": {
+ "version": "1.0.8",
+ "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
+ "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
+ "license": "MIT",
+ "dependencies": {
+ "delayed-stream": "~1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/core-js-pure": {
+ "version": "3.49.0",
+ "resolved": "https://registry.npmjs.org/core-js-pure/-/core-js-pure-3.49.0.tgz",
+ "integrity": "sha512-XM4RFka59xATyJv/cS3O3Kml72hQXUeGRuuTmMYFxwzc9/7C8OYTaIR/Ji+Yt8DXzsFLNhat15cE/JP15HrCgw==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/core-js"
+ }
+ },
+ "node_modules/csstype": {
+ "version": "3.2.3",
+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
+ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/deepmerge": {
+ "version": "4.3.1",
+ "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz",
+ "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/delayed-stream": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
+ "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
+ "node_modules/dunder-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "gopd": "^1.2.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-define-property": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-errors": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-object-atoms": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
+ "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-set-tostringtag": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
+ "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.6",
+ "has-tostringtag": "^1.0.2",
+ "hasown": "^2.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/esbuild": {
+ "version": "0.21.5",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz",
"integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==",
"dev": true,
@@ -484,6 +1463,167 @@
"@esbuild/win32-x64": "0.21.5"
}
},
+ "node_modules/fast-deep-equal": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
+ "license": "MIT"
+ },
+ "node_modules/fast-json-patch": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/fast-json-patch/-/fast-json-patch-3.1.1.tgz",
+ "integrity": "sha512-vf6IHUX2SBcA+5/+4883dsIjpBTqmfBjmYiWK1savxQmFk4JfBMLa7ynTYOs1Rolp/T1betJxHiGD3g1Mn8lUQ==",
+ "license": "MIT"
+ },
+ "node_modules/fast-uri": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz",
+ "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/follow-redirects": {
+ "version": "1.16.0",
+ "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz",
+ "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://github.com/sponsors/RubenVerborgh"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=4.0"
+ },
+ "peerDependenciesMeta": {
+ "debug": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/form-data": {
+ "version": "4.0.5",
+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz",
+ "integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==",
+ "license": "MIT",
+ "dependencies": {
+ "asynckit": "^0.4.0",
+ "combined-stream": "^1.0.8",
+ "es-set-tostringtag": "^2.1.0",
+ "hasown": "^2.0.2",
+ "mime-types": "^2.1.12"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/function-bind": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/get-intrinsic": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.2",
+ "es-define-property": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "es-object-atoms": "^1.1.1",
+ "function-bind": "^1.1.2",
+ "get-proto": "^1.0.1",
+ "gopd": "^1.2.0",
+ "has-symbols": "^1.1.0",
+ "hasown": "^2.0.2",
+ "math-intrinsics": "^1.1.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/get-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
+ "license": "MIT",
+ "dependencies": {
+ "dunder-proto": "^1.0.1",
+ "es-object-atoms": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/gopd": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/has-symbols": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/has-tostringtag": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
+ "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
+ "license": "MIT",
+ "dependencies": {
+ "has-symbols": "^1.0.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/hasown": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
+ "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
+ "license": "MIT",
+ "dependencies": {
+ "function-bind": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
"node_modules/js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
@@ -491,6 +1631,30 @@
"license": "MIT",
"peer": true
},
+ "node_modules/js-yaml": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
+ "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",
+ "license": "MIT",
+ "dependencies": {
+ "argparse": "^2.0.1"
+ },
+ "bin": {
+ "js-yaml": "bin/js-yaml.js"
+ }
+ },
+ "node_modules/json-schema-traverse": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
+ "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
+ "license": "MIT"
+ },
+ "node_modules/lodash": {
+ "version": "4.18.1",
+ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",
+ "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==",
+ "license": "MIT"
+ },
"node_modules/loose-envify": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
@@ -504,6 +1668,211 @@
"loose-envify": "cli.js"
}
},
+ "node_modules/math-intrinsics": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/mime-db": {
+ "version": "1.52.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/mime-types": {
+ "version": "2.1.35",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
+ "license": "MIT",
+ "dependencies": {
+ "mime-db": "1.52.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/minim": {
+ "version": "0.23.8",
+ "resolved": "https://registry.npmjs.org/minim/-/minim-0.23.8.tgz",
+ "integrity": "sha512-bjdr2xW1dBCMsMGGsUeqM4eFI60m94+szhxWys+B1ztIt6gWSfeGBdSVCIawezeHYLYn0j6zrsXdQS/JllBzww==",
+ "license": "MIT",
+ "dependencies": {
+ "lodash": "^4.15.0"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/minimatch": {
+ "version": "10.2.5",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz",
+ "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==",
+ "license": "BlueOak-1.0.0",
+ "dependencies": {
+ "brace-expansion": "^5.0.5"
+ },
+ "engines": {
+ "node": "18 || 20 || >=22"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "node_modules/neotraverse": {
+ "version": "0.6.18",
+ "resolved": "https://registry.npmjs.org/neotraverse/-/neotraverse-0.6.18.tgz",
+ "integrity": "sha512-Z4SmBUweYa09+o6pG+eASabEpP6QkQ70yHj351pQoEXIs8uHbaU2DWVmzBANKgflPa47A50PtB2+NgRpQvr7vA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/node-abort-controller": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/node-abort-controller/-/node-abort-controller-3.1.1.tgz",
+ "integrity": "sha512-AGK2yQKIjRuqnc6VkX2Xj5d+QW8xZ87pa1UK6yA6ouUyuxfHuMP6umE5QK7UmTeOAymo+Zx1Fxiuw9rVx8taHQ==",
+ "license": "MIT"
+ },
+ "node_modules/node-addon-api": {
+ "version": "8.7.0",
+ "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.7.0.tgz",
+ "integrity": "sha512-9MdFxmkKaOYVTV+XVRG8ArDwwQ77XIgIPyKASB1k3JPq3M8fGQQQE3YpMOrKm6g//Ktx8ivZr8xo1Qmtqub+GA==",
+ "license": "MIT",
+ "optional": true,
+ "engines": {
+ "node": "^18 || ^20 || >= 21"
+ }
+ },
+ "node_modules/node-domexception": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",
+ "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==",
+ "deprecated": "Use your platform's native DOMException instead",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/jimmywarting"
+ },
+ {
+ "type": "github",
+ "url": "https://paypal.me/jimmywarting"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.5.0"
+ }
+ },
+ "node_modules/node-fetch-commonjs": {
+ "version": "3.3.2",
+ "resolved": "https://registry.npmjs.org/node-fetch-commonjs/-/node-fetch-commonjs-3.3.2.tgz",
+ "integrity": "sha512-VBlAiynj3VMLrotgwOS3OyECFxas5y7ltLcK4t41lMUZeaK15Ym4QRkqN0EQKAFL42q9i21EPKjzLUPfltR72A==",
+ "license": "MIT",
+ "dependencies": {
+ "node-domexception": "^1.0.0",
+ "web-streams-polyfill": "^3.0.3"
+ },
+ "engines": {
+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/node-fetch"
+ }
+ },
+ "node_modules/node-gyp-build": {
+ "version": "4.8.4",
+ "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz",
+ "integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==",
+ "license": "MIT",
+ "optional": true,
+ "bin": {
+ "node-gyp-build": "bin.js",
+ "node-gyp-build-optional": "optional.js",
+ "node-gyp-build-test": "build-test.js"
+ }
+ },
+ "node_modules/openapi-jsonschema-parameters": {
+ "version": "12.1.3",
+ "resolved": "https://registry.npmjs.org/openapi-jsonschema-parameters/-/openapi-jsonschema-parameters-12.1.3.tgz",
+ "integrity": "sha512-aHypKxWHwu2lVqfCIOCZeJA/2NTDiP63aPwuoIC+5ksLK5/IQZ3oKTz7GiaIegz5zFvpMDxDvLR2DMQQSkOAug==",
+ "license": "MIT",
+ "dependencies": {
+ "openapi-types": "^12.1.3"
+ }
+ },
+ "node_modules/openapi-path-templating": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/openapi-path-templating/-/openapi-path-templating-2.2.1.tgz",
+ "integrity": "sha512-eN14VrDvl/YyGxxrkGOHkVkWEoPyhyeydOUrbvjoz8K5eIGgELASwN1eqFOJ2CTQMGCy2EntOK1KdtJ8ZMekcg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "apg-lite": "^1.0.4"
+ },
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
+ "node_modules/openapi-server-url-templating": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/openapi-server-url-templating/-/openapi-server-url-templating-1.3.0.tgz",
+ "integrity": "sha512-DPlCms3KKEbjVQb0spV6Awfn6UWNheuG/+folQPzh/wUaKwuqvj8zt5gagD7qoyxtE03cIiKPgLFS3Q8Bz00uQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "apg-lite": "^1.0.4"
+ },
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
+ "node_modules/openapi-types": {
+ "version": "12.1.3",
+ "resolved": "https://registry.npmjs.org/openapi-types/-/openapi-types-12.1.3.tgz",
+ "integrity": "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw==",
+ "license": "MIT"
+ },
+ "node_modules/proxy-from-env": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz",
+ "integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/ramda": {
+ "version": "0.30.1",
+ "resolved": "https://registry.npmjs.org/ramda/-/ramda-0.30.1.tgz",
+ "integrity": "sha512-tEF5I22zJnuclswcZMc8bDIrwRHRzf+NqVEmqg50ShAZMP7MWeR/RGDthfM/p+BlqvF2fXAzpn8i+SJcYD3alw==",
+ "license": "MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/ramda"
+ }
+ },
+ "node_modules/ramda-adjunct": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/ramda-adjunct/-/ramda-adjunct-5.1.0.tgz",
+ "integrity": "sha512-8qCpl2vZBXEJyNbi4zqcgdfHtcdsWjOGbiNSEnEBrM6Y0OKOT8UxJbIVGm1TIcjaSu2MxaWcgtsNlKlCk7o7qg==",
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.3"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/ramda-adjunct"
+ },
+ "peerDependencies": {
+ "ramda": ">= 0.30.0"
+ }
+ },
"node_modules/react": {
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
@@ -531,6 +1900,15 @@
"react": "^18.3.1"
}
},
+ "node_modules/require-from-string": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
+ "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/scheduler": {
"version": "0.23.2",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",
@@ -541,6 +1919,96 @@
"loose-envify": "^1.1.0"
}
},
+ "node_modules/short-unique-id": {
+ "version": "5.3.2",
+ "resolved": "https://registry.npmjs.org/short-unique-id/-/short-unique-id-5.3.2.tgz",
+ "integrity": "sha512-KRT/hufMSxXKEDSQujfVE0Faa/kZ51ihUcZQAcmP04t00DvPj7Ox5anHke1sJYUtzSuiT/Y5uyzg/W7bBEGhCg==",
+ "license": "Apache-2.0",
+ "bin": {
+ "short-unique-id": "bin/short-unique-id",
+ "suid": "bin/short-unique-id"
+ }
+ },
+ "node_modules/swagger-client": {
+ "version": "3.37.2",
+ "resolved": "https://registry.npmjs.org/swagger-client/-/swagger-client-3.37.2.tgz",
+ "integrity": "sha512-KcB8psL1On4GWwv9Ribp1oteh50ygNnAyvQbd5MwiXMGkcB4f53rkZEdvZKPDdJO764mQjgErxQEGDVw6QBUMQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@babel/runtime-corejs3": "^7.22.15",
+ "@scarf/scarf": "=1.4.0",
+ "@swagger-api/apidom-core": "^1.10.2",
+ "@swagger-api/apidom-error": "^1.10.2",
+ "@swagger-api/apidom-json-pointer": "^1.10.2",
+ "@swagger-api/apidom-ns-openapi-3-1": "^1.10.2",
+ "@swagger-api/apidom-ns-openapi-3-2": "^1.10.2",
+ "@swagger-api/apidom-reference": "^1.10.2",
+ "@swaggerexpert/cookie": "^2.0.2",
+ "deepmerge": "~4.3.0",
+ "fast-json-patch": "^3.0.0-1",
+ "js-yaml": "^4.1.0",
+ "neotraverse": "=0.6.18",
+ "node-abort-controller": "^3.1.1",
+ "node-fetch-commonjs": "^3.3.2",
+ "openapi-path-templating": "^2.2.1",
+ "openapi-server-url-templating": "^1.3.0",
+ "ramda": "^0.30.1",
+ "ramda-adjunct": "^5.1.0"
+ }
+ },
+ "node_modules/tree-sitter": {
+ "version": "0.21.1",
+ "resolved": "https://registry.npmjs.org/tree-sitter/-/tree-sitter-0.21.1.tgz",
+ "integrity": "sha512-7dxoA6kYvtgWw80265MyqJlkRl4yawIjO7S5MigytjELkX43fV2WsAXzsNfO7sBpPPCF5Gp0+XzHk0DwLCq3xQ==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "node-addon-api": "^8.0.0",
+ "node-gyp-build": "^4.8.0"
+ }
+ },
+ "node_modules/tree-sitter-json": {
+ "version": "0.24.8",
+ "resolved": "https://registry.npmjs.org/tree-sitter-json/-/tree-sitter-json-0.24.8.tgz",
+ "integrity": "sha512-Tc9ZZYwHyWZ3Tt1VEw7Pa2scu1YO7/d2BCBbKTx5hXwig3UfdQjsOPkPyLpDJOn/m1UBEWYAtSdGAwCSyagBqQ==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "node-addon-api": "^8.2.2",
+ "node-gyp-build": "^4.8.2"
+ },
+ "peerDependencies": {
+ "tree-sitter": "^0.21.1"
+ },
+ "peerDependenciesMeta": {
+ "tree-sitter": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/ts-mixer": {
+ "version": "6.0.4",
+ "resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.4.tgz",
+ "integrity": "sha512-ufKpbmrugz5Aou4wcr5Wc1UUFWOLhq+Fm6qa6P0w0K5Qw2yhaUoiWszhCVuNQyNwrlGiscHOmqYoAox1PtvgjA==",
+ "license": "MIT"
+ },
+ "node_modules/ts-toolbelt": {
+ "version": "9.6.0",
+ "resolved": "https://registry.npmjs.org/ts-toolbelt/-/ts-toolbelt-9.6.0.tgz",
+ "integrity": "sha512-nsZd8ZeNUzukXPlJmTBwUAuABDe/9qtVDelJeT/qW0ow3ZS3BsQJtNkan1802aM9Uf68/Y8ljw86Hu0h5IUW3w==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/types-ramda": {
+ "version": "0.30.1",
+ "resolved": "https://registry.npmjs.org/types-ramda/-/types-ramda-0.30.1.tgz",
+ "integrity": "sha512-1HTsf5/QVRmLzcGfldPFvkVsAdi1db1BBKzi7iW3KBUlOICg/nKnFS+jGqDJS3YD8VsWbAh7JiHeBvbsw8RPxA==",
+ "license": "MIT",
+ "dependencies": {
+ "ts-toolbelt": "^9.6.0"
+ }
+ },
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
@@ -554,6 +2022,37 @@
"engines": {
"node": ">=14.17"
}
+ },
+ "node_modules/unraw": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/unraw/-/unraw-3.0.0.tgz",
+ "integrity": "sha512-08/DA66UF65OlpUDIQtbJyrqTR0jTAlJ+jsnkQ4jxR7+K5g5YG1APZKQSMCE1vqqmD+2pv6+IdEjmopFatacvg==",
+ "license": "MIT"
+ },
+ "node_modules/web-streams-polyfill": {
+ "version": "3.3.3",
+ "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz",
+ "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/web-tree-sitter": {
+ "version": "0.24.5",
+ "resolved": "https://registry.npmjs.org/web-tree-sitter/-/web-tree-sitter-0.24.5.tgz",
+ "integrity": "sha512-+J/2VSHN8J47gQUAvF8KDadrfz6uFYVjxoxbKWDoXVsH2u7yLdarCnIURnrMA6uSRkgX3SdmqM5BOoQjPdSh5w==",
+ "license": "MIT",
+ "optional": true
+ },
+ "node_modules/zod": {
+ "version": "3.25.76",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
+ "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/colinhacks"
+ }
}
}
}
diff --git a/lobehub-plugin/package.json b/lobehub-plugin/package.json
index 738b13e6d..8f894d4d0 100644
--- a/lobehub-plugin/package.json
+++ b/lobehub-plugin/package.json
@@ -7,10 +7,13 @@
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
- "build": "tsc && esbuild dist/index.js --bundle --platform=browser --outfile=dist/bundle.js",
- "dev": "tsc --watch & esbuild dist/index.js --bundle --platform=browser --outfile=dist/bundle.js --watch",
+ "build": "tsc && esbuild dist/index.js --bundle --platform=browser --external:react --external:react-dom --outfile=dist/bundle.js",
+ "dev": "tsc --watch & esbuild dist/index.js --bundle --platform=browser --external:react --external:react-dom --outfile=dist/bundle.js --watch",
"type-check": "tsc --noEmit"
},
+ "dependencies": {
+ "@lobehub/chat-plugin-sdk": "^1.0.0"
+ },
"devDependencies": {
"@types/react": "^18.2.0",
"@types/react-dom": "^18.2.0",
diff --git a/lobehub-plugin/src/AgentPane.tsx b/lobehub-plugin/src/AgentPane.tsx
index 54803c9ca..04c77c932 100644
--- a/lobehub-plugin/src/AgentPane.tsx
+++ b/lobehub-plugin/src/AgentPane.tsx
@@ -7,55 +7,107 @@ export interface AgentPaneProps {
}
/**
- * Main plugin component that renders a 3D agent avatar.
- * Listens to chat assistant messages via Lobe hooks and forwards them to the
- * agent via the bridge protocol.
+ * Sidebar plugin component that renders a 3D agent avatar and
+ * forwards LobeChat tool-call payloads to the agent via the bridge.
+ *
+ * LobeChat delivers tool calls by postMessage into the plugin iframe:
+ * { type: 'LobePlugin.renderPlugin', payload: { apiName, arguments } }
+ *
+ * When @lobehub/chat-plugin-sdk ships a stable usePluginStore hook,
+ * replace the window message listener below with that hook so the
+ * React render cycle drives the effect instead of a raw event.
*/
export const AgentPane: React.FC<AgentPaneProps> = ({ settings }) => {
const iframeRef = useRef<HTMLIFrameElement>(null);
const bridgeRef = useRef<AgentBridge | null>(null);
const [isReady, setIsReady] = useState(false);
- const [frameHeight, setFrameHeight] = useState(420);
+ const [frameHeight, setFrameHeight] = useState(480);
const apiOrigin = settings.apiOrigin || DEFAULT_API_ORIGIN;
- const embedUrl = `${apiOrigin}/agent/${settings.agentId}/embed?bg=transparent&name=1`;
+ // Pass agent id via query param; boot.js reads ?agent=
+ const embedUrl = `${apiOrigin}/lobehub/iframe/?agent=${encodeURIComponent(settings.agentId)}&bg=transparent`;
- // Initialize bridge on mount.
+ // Mount bridge once per agentId.
useEffect(() => {
+ setIsReady(false);
const bridge = new AgentBridge({
agentId: settings.agentId,
iframeRef,
onReady: () => setIsReady(true),
- onResize: (height: number) => setFrameHeight(Math.min(height, 600)),
+ onResize: (h: number) => setFrameHeight(Math.min(Math.max(h, 200), 640)),
});
-
bridge.mount();
bridgeRef.current = bridge;
-
return () => {
bridge.unmount();
+ bridgeRef.current = null;
};
}, [settings.agentId]);
- // TODO: Hook into Lobe's onAssistantMessage event.
- // This depends on what @lobehub/ui@latest exports.
- // If usePluginStore or onAssistantMessage doesn't exist,
- // this should be provided by the host Lobe fork.
+ // Observe LobeChat tool calls delivered as postMessage to this plugin iframe.
+ //
+ // LobeChat sends: { type: 'LobePlugin.renderPlugin', payload: { apiName, arguments } }
+ // where `arguments` is a JSON string of the tool's input object.
+ //
+ // Fallback path: if LobeChat changes its message contract or a host-level fork
+ // dispatches { type: 'lobe:assistantMessage', detail: { content } } as a custom
+ // event, the second listener below handles that case.
useEffect(() => {
- const handleLobeMessage = (ev: CustomEvent) => {
- const { content } = ev.detail || {};
- if (content && bridgeRef.current) {
- bridgeRef.current.speak(content);
+ const handleMessage = (ev: MessageEvent) => {
+ if (!ev.data || typeof ev.data !== 'object') return;
+ const { type, payload } = ev.data as {
+ type?: string;
+ payload?: Record<string, unknown>;
+ };
+ if (type !== 'LobePlugin.renderPlugin' || !payload) return;
+
+ const apiName = payload['apiName'] as string | undefined;
+ let args: Record<string, unknown> = {};
+ try {
+ args = JSON.parse((payload['arguments'] as string) || '{}');
+ } catch {
+ return;
}
- };
- // Placeholder: listen for a custom event from the Lobe host.
- // Replace with actual Lobe hook when SDK is available.
- window.addEventListener('lobe:assistantMessage', handleLobeMessage as EventListener);
+ const bridge = bridgeRef.current;
+ if (!bridge) return;
- return () => {
- window.removeEventListener('lobe:assistantMessage', handleLobeMessage as EventListener);
+ switch (apiName) {
+ case 'speak':
+ if (typeof args['text'] === 'string') {
+ bridge
+ .speak(args['text'], {
+ sentiment:
+ typeof args['sentiment'] === 'number' ? args['sentiment'] : 0,
+ })
+ .catch(() => undefined);
+ }
+ break;
+ case 'gesture':
+ if (typeof args['name'] === 'string') {
+ bridge.gesture(args['name']).catch(() => undefined);
+ }
+ break;
+ case 'emote':
+ if (typeof args['trigger'] === 'string') {
+ bridge
+ .emote({
+ trigger: args['trigger'],
+ weight: typeof args['weight'] === 'number' ? args['weight'] : 1,
+ })
+ .catch(() => undefined);
+ }
+ break;
+ case 'render_agent':
+ if (typeof args['agentId'] === 'string') {
+ bridge.setAgent(args['agentId']).catch(() => undefined);
+ }
+ break;
+ }
};
+
+ window.addEventListener('message', handleMessage);
+ return () => window.removeEventListener('message', handleMessage);
}, []);
return (
@@ -68,19 +120,20 @@ export const AgentPane: React.FC<AgentPaneProps> = ({ settings }) => {
backgroundColor: 'transparent',
borderRadius: '8px',
overflow: 'hidden',
+ position: 'relative',
}}
>
{!isReady && (
<div
style={{
+ position: 'absolute',
+ inset: 0,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
- width: '100%',
- height: '100%',
- backgroundColor: 'rgba(0, 0, 0, 0.1)',
- color: 'rgba(0, 0, 0, 0.5)',
+ color: 'rgba(128, 128, 128, 0.6)',
fontSize: '12px',
+ fontFamily: 'system-ui, sans-serif',
}}
>
Loading agent…
@@ -94,7 +147,8 @@ export const AgentPane: React.FC<AgentPaneProps> = ({ settings }) => {
width: '100%',
height: '100%',
border: 'none',
- display: isReady ? 'block' : 'none',
+ opacity: isReady ? 1 : 0,
+ transition: 'opacity 0.3s ease',
}}
sandbox="allow-same-origin allow-scripts allow-presentation"
/>
diff --git a/lobehub-plugin/src/bridge.ts b/lobehub-plugin/src/bridge.ts
index 294ad67a4..31fd2e3ed 100644
--- a/lobehub-plugin/src/bridge.ts
+++ b/lobehub-plugin/src/bridge.ts
@@ -1,111 +1,225 @@
/**
- * PostMessage bridge wrapping the agent embed iframe.
- * Implements the v1 protocol from /public/agent/embed.html (FROZEN).
+ * Host-side PostMessage bridge wrapping the agent embed iframe.
+ *
+ * Wire protocol v1 — envelope shape:
+ * { v: 1, source: 'agent-host' | 'agent-3d', id, inReplyTo?, kind, op, payload }
+ *
+ * Canonical spec: prompts/final-integration/01-embed-bridges.md
*/
-interface AgentHelloMessage {
- type: 'agent:hello';
- agentId: string;
- host?: string;
-}
-
-interface AgentActionMessage {
- type: 'agent:action';
- agentId: string;
- action: Record<string, unknown>;
-}
-
-interface AgentPingMessage {
- type: 'agent:ping';
- agentId: string;
+export type BridgeOp =
+ | 'ping'
+ | 'pong'
+ | 'ready'
+ | 'speak'
+ | 'gesture'
+ | 'emote'
+ | 'look'
+ | 'setAgent'
+ | 'subscribe'
+ | 'error';
+export type BridgeKind = 'request' | 'response' | 'event';
+
+export interface BridgeEnvelope {
+ v: 1;
+ source: 'agent-3d' | 'agent-host';
id: string;
+ inReplyTo?: string;
+ kind: BridgeKind;
+ op: BridgeOp | string;
+ payload: Record<string, unknown>;
}
-interface AgentReadyMessage {
- type: 'agent:ready';
+export interface BridgeReadyPayload {
agentId: string;
- version: string;
capabilities: string[];
- name?: string;
}
-type OutboundMessage = AgentHelloMessage | AgentActionMessage | AgentPingMessage;
-
export interface BridgeOptions {
agentId: string;
iframeRef: React.RefObject<HTMLIFrameElement>;
- onReady?: (msg: AgentReadyMessage) => void;
+ allowedOrigin?: string;
+ onReady?: (payload: BridgeReadyPayload) => void;
onResize?: (height: number) => void;
onAction?: (action: Record<string, unknown>) => void;
}
+function newId(): string {
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
+ return crypto.randomUUID();
+ }
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
+}
+
+type PendingEntry = {
+ resolve: (v: unknown) => void;
+ reject: (e: Error) => void;
+ timer: ReturnType<typeof setTimeout>;
+};
+
export class AgentBridge {
- private agentId: string;
- private iframeRef: React.RefObject<HTMLIFrameElement>;
- private onReady?: (msg: AgentReadyMessage) => void;
- private onResize?: (height: number) => void;
- private onAction?: (action: Record<string, unknown>) => void;
- private messageHandler: (ev: MessageEvent) => void;
+ private readonly agentId: string;
+ private readonly iframeRef: React.RefObject<HTMLIFrameElement>;
+ private readonly allowedOrigin: string | null;
+ private readonly onReady?: (payload: BridgeReadyPayload) => void;
+ private readonly onResize?: (height: number) => void;
+ private readonly onAction?: (action: Record<string, unknown>) => void;
+
+ private readonly messageHandler: (ev: MessageEvent) => void;
+ private readonly pending = new Map<string, PendingEntry>();
+ private queue: BridgeEnvelope[] = [];
+ private connected = false;
constructor(opts: BridgeOptions) {
this.agentId = opts.agentId;
this.iframeRef = opts.iframeRef;
+ this.allowedOrigin = opts.allowedOrigin ?? null;
this.onReady = opts.onReady;
this.onResize = opts.onResize;
this.onAction = opts.onAction;
-
this.messageHandler = (ev: MessageEvent) => this.handleMessage(ev);
}
mount(): void {
window.addEventListener('message', this.messageHandler);
- this.sayHello();
}
unmount(): void {
window.removeEventListener('message', this.messageHandler);
+ for (const { reject, timer } of this.pending.values()) {
+ clearTimeout(timer);
+ reject(new Error('Bridge unmounted'));
+ }
+ this.pending.clear();
}
+ // ── Incoming ──────────────────────────────────────────────────────────────
+
private handleMessage(ev: MessageEvent): void {
- const msg = ev.data;
+ const frame = this.iframeRef.current;
+ if (frame?.contentWindow && ev.source !== frame.contentWindow) return;
+
+ const msg = ev.data as Partial<BridgeEnvelope> & Record<string, unknown>;
if (!msg || typeof msg !== 'object') return;
- if (msg.agentId !== this.agentId) return;
- switch (msg.type) {
- case 'agent:ready':
- this.onReady?.(msg);
- break;
- case 'agent:resize':
- this.onResize?.(msg.height);
+ // Legacy boot.js format: { v:1, ns:'3d-agent', type:'embed:resize', payload }
+ if (msg['ns'] === '3d-agent' && typeof msg['type'] === 'string') {
+ const type = msg['type'] as string;
+ const payload = (msg['payload'] as Record<string, unknown>) ?? {};
+ if (type === 'embed:resize' && typeof payload['height'] === 'number') {
+ this.onResize?.(payload['height'] as number);
+ }
+ if (type === 'embed:hello' || type === 'embed:ready') {
+ this.onReady?.({
+ agentId: this.agentId,
+ capabilities: (payload['capabilities'] as string[]) ?? [],
+ });
+ }
+ return;
+ }
+
+ // v1 spec envelope
+ if (msg.v !== 1 || msg.source !== 'agent-3d') return;
+ const env = msg as BridgeEnvelope;
+
+ if (env.kind === 'event') {
+ this.handleEvent(env);
+ } else if (env.kind === 'response') {
+ this.handleResponse(env);
+ }
+ }
+
+ private handleEvent(env: BridgeEnvelope): void {
+ switch (env.op) {
+ case 'ready': {
+ const p = env.payload as unknown as BridgeReadyPayload;
+ this.connected = true;
+ // Complete handshake: send ping, wait for pong.
+ this.request('ping', {}).catch(() => undefined);
+ this.onReady?.(p);
+ for (const queued of this.queue) this.transmit(queued);
+ this.queue = [];
break;
- case 'agent:action':
- this.onAction?.(msg.action);
+ }
+ case 'resize':
+ if (typeof env.payload['height'] === 'number') {
+ this.onResize?.(env.payload['height'] as number);
+ }
break;
+ default:
+ if (env.op === 'action') {
+ this.onAction?.(env.payload);
+ }
}
}
- private sayHello(): void {
- this.post({
- type: 'agent:hello',
- agentId: this.agentId,
- });
+ private handleResponse(env: BridgeEnvelope): void {
+ if (!env.inReplyTo) return;
+ const entry = this.pending.get(env.inReplyTo);
+ if (!entry) return;
+ clearTimeout(entry.timer);
+ this.pending.delete(env.inReplyTo);
+ entry.resolve(env.payload);
}
- speak(text: string): void {
- this.post({
- type: 'agent:action',
- agentId: this.agentId,
- action: {
- type: 'speak',
- payload: { text },
- },
+ // ── Outgoing ─────────────────────────────────────────────────────────────
+
+ private request(op: BridgeOp, payload: Record<string, unknown>): Promise<unknown> {
+ return new Promise((resolve, reject) => {
+ const id = newId();
+ const env: BridgeEnvelope = {
+ v: 1,
+ source: 'agent-host',
+ id,
+ kind: 'request',
+ op,
+ payload,
+ };
+ const timer = setTimeout(() => {
+ this.pending.delete(id);
+ reject(new Error(`Bridge request "${op}" timed out`));
+ }, 10_000);
+ this.pending.set(id, { resolve, reject, timer });
+ if (this.connected) {
+ this.transmit(env);
+ } else {
+ this.queue.push(env);
+ }
});
}
- private post(msg: OutboundMessage): void {
+ private transmit(env: BridgeEnvelope): void {
const frame = this.iframeRef.current;
- if (frame?.contentWindow) {
- frame.contentWindow.postMessage(msg, '*');
+ if (!frame?.contentWindow) return;
+ try {
+ frame.contentWindow.postMessage(env, this.allowedOrigin ?? '*');
+ } catch (_) {
+ // Silently drop — frame may have been removed.
}
}
+
+ // ── Public API ────────────────────────────────────────────────────────────
+
+ speak(text: string, opts?: { sentiment?: number }): Promise<void> {
+ return this.request('speak', { text, sentiment: opts?.sentiment ?? 0 }) as Promise<void>;
+ }
+
+ gesture(name: string): Promise<void> {
+ return this.request('gesture', { name }) as Promise<void>;
+ }
+
+ emote(opts: { trigger: string; weight?: number }): Promise<void> {
+ return this.request('emote', {
+ trigger: opts.trigger,
+ weight: opts.weight ?? 1,
+ }) as Promise<void>;
+ }
+
+ look(opts: { target: unknown }): Promise<void> {
+ return this.request('look', { target: opts.target }) as Promise<void>;
+ }
+
+ setAgent(nextAgentId: string): Promise<void> {
+ return this.request('setAgent', { agentId: nextAgentId }) as Promise<void>;
+ }
}
diff --git a/prompts/INDEX.md b/prompts/INDEX.md
index 0dcf918ef..a037a050a 100644
--- a/prompts/INDEX.md
+++ b/prompts/INDEX.md
@@ -6,7 +6,7 @@ The **only** goal. Six bands, in order. Everything else is secondary until these
2. **Selfie → agent** — User takes a photo in-browser; we return a rigged 3D avatar bound to their identity.
3. **Edit avatars** — Material/texture/scene editing on an existing avatar (partially shipped), plus regenerate-from-photo and variants.
4. **View + embed** — Public viewer and embeddable snippet (partially shipped); polish, share flow, and per-agent settings.
-5. **Portable embed (Claude.ai + LobeHub)** — The agent shows up *inside* a chat surface looking embodied, not as JSON.
+5. **Portable embed (Claude.ai + LobeHub)** — The agent shows up _inside_ a chat surface looking embodied, not as JSON.
6. **On-chain deployment** — Agent identity lives on-chain; any host (LobeHub, Claude) can summon the same avatar from the address alone.
## Dispatch order
@@ -23,7 +23,7 @@ Each band is a folder. Prompts inside a band can run in parallel unless they tou
- [cz-demo/](./cz-demo/) — **the ship target.** Rolls up bands 1, 5, 6 into one live-demo flow. Work here last, after the bands above are green.
- [build/](./build/) — master flat index (`NN-NN-*.md`) covering bands 1–5 in one place; use as an alternative dispatch list if the band-folder layout gets noisy.
-Don't skip bands. Band 2 depends on band 1 (we need to know *who* owns the agent before generating one). Band 5 depends on band 4 (embed must work on a regular page before it works inside Claude). Band 6 depends on band 1 (wallet = onchain identity).
+Don't skip bands. Band 2 depends on band 1 (we need to know _who_ owns the agent before generating one). Band 5 depends on band 4 (embed must work on a regular page before it works inside Claude). Band 6 depends on band 1 (wallet = onchain identity).
## House rules for every prompt
@@ -40,7 +40,7 @@ Don't skip bands. Band 2 depends on band 1 (we need to know *who* owns the agent
- `api/mcp.js` — MCP tools including `validate_model`, `inspect_model`, `optimize_model`
- `api/_lib/fetch-model.js` — SSRF-hardened URL fetcher
- `public/.well-known/agent-card.json` — A2A discovery with 8 skills
-- `src/erc8004/agent-registry.js` — wallet connect via Privy / injected provider (used for ERC-8004 registration, *not yet* for user auth)
+- `src/erc8004/agent-registry.js` — wallet connect via Privy / injected provider (used for ERC-8004 registration, _not yet_ for user auth)
- `src/agent-identity.js`, `src/agent-memory.js`, `src/agent-protocol.js`, `src/agent-avatar.js`, `src/agent-home.js` — the agent runtime (Empathy Layer etc.)
## What we are NOT prioritizing right now
diff --git a/prompts/README.md b/prompts/README.md
index 1d9b97fc1..d5804cdef 100644
--- a/prompts/README.md
+++ b/prompts/README.md
@@ -6,15 +6,15 @@ Each file is designed to be dropped into a fresh Claude Code agent without extra
## The priority stack (build in this order)
-| Layer | Directory | Ship state |
-|---|---|---|
-| 1. Wallet auth 100% | [wallet-auth/](./wallet-auth/) | Foundation. SIWE login + link-to-user + fix `/api/agents/me` 500. |
-| 2. Selfie → agent | [selfie-agent/](./selfie-agent/) | The magic moment — photo capture becomes a personal avatar. |
-| 3. Edit avatar | [avatar-edit/](./avatar-edit/) | Post-creation morph / outfit / accessory editing. |
-| 4. View + embed | existing `/agent/:id` + [embed/](./embed/) | Mostly working. Polish prompts exist in `embed/`. |
-| 5. Claude / LobeHub embed | [lobehub-embed/](./lobehub-embed/), [claude-artifact/](./claude-artifact/) | Agent renders embodied inside host chats. Primary integration target. |
-| 6. Onchain | [onchain/](./onchain/) | Deploy ERC-8004 contracts, register, hydrate agent from chain. |
-| 🎯 CZ demo | [cz-demo/](./cz-demo/) | Bespoke landing + pre-registered cz.glb onchain + scripted first interaction. |
+| Layer | Directory | Ship state |
+| ------------------------- | -------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
+| 1. Wallet auth 100% | [wallet-auth/](./wallet-auth/) | Foundation. SIWE login + link-to-user + fix `/api/agents/me` 500. |
+| 2. Selfie → agent | [selfie-agent/](./selfie-agent/) | The magic moment — photo capture becomes a personal avatar. |
+| 3. Edit avatar | [avatar-edit/](./avatar-edit/) | Post-creation morph / outfit / accessory editing. |
+| 4. View + embed | existing `/agent/:id` + [embed/](./embed/) | Mostly working. Polish prompts exist in `embed/`. |
+| 5. Claude / LobeHub embed | [lobehub-embed/](./lobehub-embed/), [claude-artifact/](./claude-artifact/) | Agent renders embodied inside host chats. Primary integration target. |
+| 6. Onchain | [onchain/](./onchain/) | Deploy ERC-8004 contracts, register, hydrate agent from chain. |
+| 🎯 CZ demo | [cz-demo/](./cz-demo/) | Bespoke landing + pre-registered cz.glb onchain + scripted first interaction. |
## Side lanes (not blockers for CZ demo)
diff --git a/prompts/agent-3d/01-openai-provider.md b/prompts/agent-3d/01-openai-provider.md
index c3e9e01ba..3e10bfa22 100644
--- a/prompts/agent-3d/01-openai-provider.md
+++ b/prompts/agent-3d/01-openai-provider.md
@@ -13,14 +13,14 @@ Add `OpenAIProvider` to [src/runtime/providers.js](../../src/runtime/providers.j
## Deliverable
1. **`OpenAIProvider` class** in [src/runtime/providers.js](../../src/runtime/providers.js):
- - Constructor accepts `{ model, proxyURL, apiKey, temperature, maxTokens }`. Default model: `gpt-4o-2024-11-20`.
- - `async complete({ system, messages, tools })` — POST to `${proxyURL}/v1/chat/completions` (or `https://api.openai.com/v1/chat/completions` if `apiKey` passed directly). Respect the `key-proxy` pattern from [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md) — never send raw API keys to the browser unless explicitly provided.
- - Convert Anthropic-shaped `messages` (already flowing through the runtime) into OpenAI's chat format:
- - `role: "assistant"` messages with `content: [{ type: "tool_use", id, name, input }]` → OpenAI's `tool_calls: [{ id, type: "function", function: { name, arguments: JSON.stringify(input) } }]`.
- - `role: "user"` messages with `content: [{ type: "tool_result", tool_use_id, content }]` → OpenAI's `role: "tool", tool_call_id, content`.
- - Convert tool schemas: Anthropic's `{ name, description, input_schema }` → OpenAI's `{ type: "function", function: { name, description, parameters } }`.
- - Normalize response to `{ text, toolCalls, thinking: "", stopReason }`.
- - `formatAssistantWithToolCalls(text, toolCalls)` must round-trip through the runtime untouched — meaning the Anthropic-shape message objects the runtime stores are OK; the conversion happens inside `complete()` on the way out.
+ - Constructor accepts `{ model, proxyURL, apiKey, temperature, maxTokens }`. Default model: `gpt-4o-2024-11-20`.
+ - `async complete({ system, messages, tools })` — POST to `${proxyURL}/v1/chat/completions` (or `https://api.openai.com/v1/chat/completions` if `apiKey` passed directly). Respect the `key-proxy` pattern from [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md) — never send raw API keys to the browser unless explicitly provided.
+ - Convert Anthropic-shaped `messages` (already flowing through the runtime) into OpenAI's chat format:
+ - `role: "assistant"` messages with `content: [{ type: "tool_use", id, name, input }]` → OpenAI's `tool_calls: [{ id, type: "function", function: { name, arguments: JSON.stringify(input) } }]`.
+ - `role: "user"` messages with `content: [{ type: "tool_result", tool_use_id, content }]` → OpenAI's `role: "tool", tool_call_id, content`.
+ - Convert tool schemas: Anthropic's `{ name, description, input_schema }` → OpenAI's `{ type: "function", function: { name, description, parameters } }`.
+ - Normalize response to `{ text, toolCalls, thinking: "", stopReason }`.
+ - `formatAssistantWithToolCalls(text, toolCalls)` must round-trip through the runtime untouched — meaning the Anthropic-shape message objects the runtime stores are OK; the conversion happens inside `complete()` on the way out.
2. **Register in `createProvider()`** — extend the factory to dispatch `provider === "openai"`.
3. **Update [specs/AGENT_MANIFEST.md](../../specs/AGENT_MANIFEST.md)** — add `openai` to the `brain.provider` enum line and list representative model ids.
diff --git a/prompts/agent-3d/03-whisper-stt.md b/prompts/agent-3d/03-whisper-stt.md
index 5170c004a..82af38ac4 100644
--- a/prompts/agent-3d/03-whisper-stt.md
+++ b/prompts/agent-3d/03-whisper-stt.md
@@ -13,16 +13,16 @@ Add `WhisperSTT` to [src/runtime/speech.js](../../src/runtime/speech.js) that re
## Deliverable
1. **`WhisperSTT` class** in [src/runtime/speech.js](../../src/runtime/speech.js):
- - Constructor: `{ endpoint, apiKey, language = "en", model = "whisper-1", chunkDurationMs = 3000 }`.
- - `endpoint` defaults to `https://api.openai.com/v1/audio/transcriptions`. Operators can point to their own whisper.cpp server by swapping.
- - `async listen({ onInterim, onFinal })`:
- - Request mic permission via `navigator.mediaDevices.getUserMedia({ audio: true })`.
- - Record with `MediaRecorder` (`audio/webm;codecs=opus`).
- - Option A (simpler): stop recording on VAD silence (see below) or when `stop()` is called, upload the full blob, emit one `onFinal(text)`.
- - Option B (preferred): chunk recording every `chunkDurationMs`, upload each chunk, emit `onInterim(text)` per chunk, emit `onFinal(text)` on stop. Chunks are independent transcriptions; concatenate on the client.
- - Emit VAD-based silence detection using `AudioContext` + `AnalyserNode` RMS threshold — stop recording after ~1.2s of silence unless in `continuous` mode.
- - `stop()` — halt recording, await any in-flight transcription, resolve the `listen()` promise with accumulated text.
- - `listening` getter.
+ - Constructor: `{ endpoint, apiKey, language = "en", model = "whisper-1", chunkDurationMs = 3000 }`.
+ - `endpoint` defaults to `https://api.openai.com/v1/audio/transcriptions`. Operators can point to their own whisper.cpp server by swapping.
+ - `async listen({ onInterim, onFinal })`:
+ - Request mic permission via `navigator.mediaDevices.getUserMedia({ audio: true })`.
+ - Record with `MediaRecorder` (`audio/webm;codecs=opus`).
+ - Option A (simpler): stop recording on VAD silence (see below) or when `stop()` is called, upload the full blob, emit one `onFinal(text)`.
+ - Option B (preferred): chunk recording every `chunkDurationMs`, upload each chunk, emit `onInterim(text)` per chunk, emit `onFinal(text)` on stop. Chunks are independent transcriptions; concatenate on the client.
+ - Emit VAD-based silence detection using `AudioContext` + `AnalyserNode` RMS threshold — stop recording after ~1.2s of silence unless in `continuous` mode.
+ - `stop()` — halt recording, await any in-flight transcription, resolve the `listen()` promise with accumulated text.
+ - `listening` getter.
2. **Register in `createSTT()`**.
3. **Update [specs/AGENT_MANIFEST.md](../../specs/AGENT_MANIFEST.md)** — add `whisper` to the `voice.stt.provider` enum, document `endpoint` and `language` fields.
diff --git a/prompts/agent-3d/04-encrypted-memory.md b/prompts/agent-3d/04-encrypted-memory.md
index 7e50fdf35..5dbec7a10 100644
--- a/prompts/agent-3d/04-encrypted-memory.md
+++ b/prompts/agent-3d/04-encrypted-memory.md
@@ -13,17 +13,17 @@ Implement `encrypted-ipfs` memory mode: writes are encrypted to the agent's owne
## Deliverable
1. **Key derivation** in `src/memory/crypto.js` (new file):
- - Export `deriveEncryptionKey(signer)` — signs a canonical message with the wallet (via `ethers`) and HKDFs a 32-byte key. Use `ethers.hashMessage` + `signer.signMessage` patterns already used in [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js).
- - Export `encryptBlob(plaintext: Uint8Array, key: Uint8Array)` → `{ nonce, ciphertext }` using `crypto.subtle` (`AES-GCM`, 12-byte nonce, authenticated).
- - Export `decryptBlob({ nonce, ciphertext }, key)` → `Uint8Array` or throws on tamper.
+ - Export `deriveEncryptionKey(signer)` — signs a canonical message with the wallet (via `ethers`) and HKDFs a 32-byte key. Use `ethers.hashMessage` + `signer.signMessage` patterns already used in [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js).
+ - Export `encryptBlob(plaintext: Uint8Array, key: Uint8Array)` → `{ nonce, ciphertext }` using `crypto.subtle` (`AES-GCM`, 12-byte nonce, authenticated).
+ - Export `decryptBlob({ nonce, ciphertext }, key)` → `Uint8Array` or throws on tamper.
2. **Extend `Memory` class** in [src/memory/index.js](../../src/memory/index.js):
- - New static `Memory._loadEncryptedIPFS({ namespace, manifestURI, signer, pinner })` — fetch the encrypted blob from IPFS, decrypt with the derived key, parse JSON, hydrate state.
- - New `_persistEncrypted()` method that serializes memory to JSON, encrypts, uploads via the provided `pinner`, and updates the stored CID (in localStorage for fast recovery AND optionally in `manifest.id.memoryCID` if a signer + registry write is authorized).
- - Batch persistence: do NOT pin on every write — debounce by ~3s or a manual `flush()` call.
+ - New static `Memory._loadEncryptedIPFS({ namespace, manifestURI, signer, pinner })` — fetch the encrypted blob from IPFS, decrypt with the derived key, parse JSON, hydrate state.
+ - New `_persistEncrypted()` method that serializes memory to JSON, encrypts, uploads via the provided `pinner`, and updates the stored CID (in localStorage for fast recovery AND optionally in `manifest.id.memoryCID` if a signer + registry write is authorized).
+ - Batch persistence: do NOT pin on every write — debounce by ~3s or a manual `flush()` call.
3. **Pinner abstraction** — accept `pinner: (blob) => Promise<{ cid }>` so this task does not bind to a specific pinning service (see [08-ipfs-pinning-service.md](./08-ipfs-pinning-service.md)).
4. **Element integration** — in [src/element.js](../../src/element.js)'s `_boot()`, when `manifest.memory.mode === "encrypted-ipfs"`:
- - Require a connected signer (if none, surface `agent:error` with `{ phase: "memory", reason: "wallet-required" }`).
- - Wire the pinner from whichever pinning service is configured (default to `window.__agent3dPinner` if present; otherwise no-op with a console warning).
+ - Require a connected signer (if none, surface `agent:error` with `{ phase: "memory", reason: "wallet-required" }`).
+ - Wire the pinner from whichever pinning service is configured (default to `window.__agent3dPinner` if present; otherwise no-op with a console warning).
## Audit checklist
@@ -49,15 +49,15 @@ Implement `encrypted-ipfs` memory mode: writes are encrypted to the agent's owne
1. `node --check src/memory/crypto.js src/memory/index.js`.
2. `npm run build:lib` passes.
3. Integration smoke test in a dev page with a local wallet (hardhat, or signed MetaMask on a testnet):
- - Write memories, refresh, confirm they load and decrypt.
- - Use a different wallet — decryption must fail with a clear error.
- - Flush to IPFS, fetch the CID manually, confirm content is unreadable without the key.
+ - Write memories, refresh, confirm they load and decrypt.
+ - Use a different wallet — decryption must fail with a clear error.
+ - Flush to IPFS, fetch the CID manually, confirm content is unreadable without the key.
## Scope boundaries — do NOT do these
- Do not introduce multi-signer / shared memory (two wallets unlocking the same bundle). That's a future feature.
- Do not attempt on-chain key registration — key derivation stays purely off-chain + deterministic from signatures.
-- Do not re-encrypt every write with a new nonce *and* re-pin the whole bundle if the write is a single-line append — use an append-only blob format OR debounce aggressively (pick one and document).
+- Do not re-encrypt every write with a new nonce _and_ re-pin the whole bundle if the write is a single-line append — use an append-only blob format OR debounce aggressively (pick one and document).
- Do not mask or rotate nonces per entry — per-bundle nonce is fine given AEAD semantics.
## Reporting
diff --git a/prompts/agent-3d/05-skill-sandbox.md b/prompts/agent-3d/05-skill-sandbox.md
index 267408851..69148c292 100644
--- a/prompts/agent-3d/05-skill-sandbox.md
+++ b/prompts/agent-3d/05-skill-sandbox.md
@@ -5,6 +5,7 @@
[src/skills/index.js](../../src/skills/index.js) loads skill `handlers.js` via dynamic `import()`. This gives handlers full DOM access, `window`, arbitrary network — too much. Per [specs/SKILL_SPEC.md](../../specs/SKILL_SPEC.md) § Security model, code skills should execute in an isolated scope with a fixed `ctx` API as their only capability.
Realms (the proposal) isn't available yet. Workers are. A Web Worker-hosted handler gets:
+
- No DOM access.
- No direct `window`, `document`, or origin access beyond what we postMessage in.
- Only `fetch` (we can override) and whatever APIs we explicitly expose.
@@ -16,20 +17,20 @@ Move skill handler execution into a shared Web Worker. The main-thread `ctx` API
## Deliverable
1. **`src/skills/sandbox-worker.js`** (new file):
- - Receives `{ type: "install", uri, handlersSrc }` messages, evaluates the source in the worker scope (via `Function()` or `importScripts()` for classic workers; prefer a module worker with a `blob:` URL).
- - Receives `{ type: "invoke", skillURI, toolName, args }` messages. Calls the handler with a worker-side `ctx` that:
- - Has the same method names as main-thread ctx (`viewer.play`, `memory.write`, `speak`, `loadClip`, ...).
- - Each call becomes a `{ type: "request", id, method, args }` message back to main, which awaits and replies with `{ type: "response", id, result }`.
- - Tracks in-flight requests by id; rejects on timeout (30s).
+ - Receives `{ type: "install", uri, handlersSrc }` messages, evaluates the source in the worker scope (via `Function()` or `importScripts()` for classic workers; prefer a module worker with a `blob:` URL).
+ - Receives `{ type: "invoke", skillURI, toolName, args }` messages. Calls the handler with a worker-side `ctx` that:
+ - Has the same method names as main-thread ctx (`viewer.play`, `memory.write`, `speak`, `loadClip`, ...).
+ - Each call becomes a `{ type: "request", id, method, args }` message back to main, which awaits and replies with `{ type: "response", id, result }`.
+ - Tracks in-flight requests by id; rejects on timeout (30s).
2. **`src/skills/sandbox-host.js`** (new file):
- - Singleton worker manager. `getHost()` returns the shared worker instance.
- - `invoke(skillURI, toolName, args, mainThreadCtx)` — posts to the worker, listens for request messages, forwards each to `mainThreadCtx`, posts responses, resolves when the worker returns the final result.
- - Handles worker death/restart.
+ - Singleton worker manager. `getHost()` returns the shared worker instance.
+ - `invoke(skillURI, toolName, args, mainThreadCtx)` — posts to the worker, listens for request messages, forwards each to `mainThreadCtx`, posts responses, resolves when the worker returns the final result.
+ - Handles worker death/restart.
3. **Refactor `Skill.invoke()`** in [src/skills/index.js](../../src/skills/index.js):
- - Instead of calling the in-process handler, delegate to `sandbox-host.getHost().invoke(...)` — passing the main-thread `ctx` from the runtime as the proxy target.
- - Load `handlersSrc` as text (not dynamic import) and send to the worker at install time.
+ - Instead of calling the in-process handler, delegate to `sandbox-host.getHost().invoke(...)` — passing the main-thread `ctx` from the runtime as the proxy target.
+ - Load `handlersSrc` as text (not dynamic import) and send to the worker at install time.
4. **Opt-out escape hatch**:
- - Manifests can set `manifest.sandboxPolicy: "trusted-main-thread"` (name-bikeshed; document it) to bypass the worker for owner-signed skills. This preserves the current behavior for trusted skills while defaulting new skills to sandboxed.
+ - Manifests can set `manifest.sandboxPolicy: "trusted-main-thread"` (name-bikeshed; document it) to bypass the worker for owner-signed skills. This preserves the current behavior for trusted skills while defaulting new skills to sandboxed.
5. **Spec update** — [specs/SKILL_SPEC.md](../../specs/SKILL_SPEC.md) § Security model: document the worker sandbox and the opt-out.
## Audit checklist
diff --git a/prompts/agent-3d/06-multi-agent-scene.md b/prompts/agent-3d/06-multi-agent-scene.md
index 5afb43e1e..e70e65663 100644
--- a/prompts/agent-3d/06-multi-agent-scene.md
+++ b/prompts/agent-3d/06-multi-agent-scene.md
@@ -13,23 +13,23 @@ Introduce `<agent-stage>` — a parent element that hosts one canvas and zero-or
## Deliverable
1. **`<agent-stage>` element** in `src/stage-element.js` (new file):
- - Creates its own `Viewer` instance (one per stage). All child `<agent-3d>` elements detect the parent and attach their body to the stage's scene rather than creating a new Viewer.
- - Manages shared orbit controls, lighting, environment map.
- - Positions children along a default formation (row, circle, freeform) — `formation="row"` attribute.
- - Exposes `stage.addAgent(manifest)` / `stage.removeAgent(agentId)` JS API in addition to declarative children.
+ - Creates its own `Viewer` instance (one per stage). All child `<agent-3d>` elements detect the parent and attach their body to the stage's scene rather than creating a new Viewer.
+ - Manages shared orbit controls, lighting, environment map.
+ - Positions children along a default formation (row, circle, freeform) — `formation="row"` attribute.
+ - Exposes `stage.addAgent(manifest)` / `stage.removeAgent(agentId)` JS API in addition to declarative children.
2. **Modify [src/element.js](../../src/element.js)**:
- - In `_boot()`, detect `this.closest('agent-stage')`. If present, skip creating a local Viewer — use the parent stage's Viewer, scope the body under a per-agent `Group`, and use a sub-canvas-rect for chat chrome.
- - When detached, fall back to solo mode.
+ - In `_boot()`, detect `this.closest('agent-stage')`. If present, skip creating a local Viewer — use the parent stage's Viewer, scope the body under a per-agent `Group`, and use a sub-canvas-rect for chat chrome.
+ - When detached, fall back to solo mode.
3. **Cross-agent messaging**:
- - Add `stage.broadcast(from, event)` — in-process event dispatch visible to all child agents.
- - Add a built-in tool `observe_agents` to each agent's tool list (scoped by a new `tools` flag in manifest or stage opt-in), returning `[{ agentId, name, position }]` for other agents on the same stage.
- - Add a built-in tool `say_to_agent(agentId, text)` that routes a message to another agent's runtime as a user-turn-from-agent-X.
+ - Add `stage.broadcast(from, event)` — in-process event dispatch visible to all child agents.
+ - Add a built-in tool `observe_agents` to each agent's tool list (scoped by a new `tools` flag in manifest or stage opt-in), returning `[{ agentId, name, position }]` for other agents on the same stage.
+ - Add a built-in tool `say_to_agent(agentId, text)` that routes a message to another agent's runtime as a user-turn-from-agent-X.
4. **Positioning**:
- - `SceneController` gains `setGroup(group: Three.Group)` to scope all its operations to a sub-group.
- - Each child agent's GLB loads into its own Group; bounding-box normalized to a common human height (uses `manifest.body.boundingBoxHeight`); positioned per `formation`.
+ - `SceneController` gains `setGroup(group: Three.Group)` to scope all its operations to a sub-group.
+ - Each child agent's GLB loads into its own Group; bounding-box normalized to a common human height (uses `manifest.body.boundingBoxHeight`); positioned per `formation`.
5. **Spec updates**:
- - New `specs/STAGE_SPEC.md` describing the element, formation options, messaging protocol, event names (`stage:agent-joined`, `stage:agent-left`, `stage:message`).
- - Link from [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md) under a new "Multi-agent" section.
+ - New `specs/STAGE_SPEC.md` describing the element, formation options, messaging protocol, event names (`stage:agent-joined`, `stage:agent-left`, `stage:message`).
+ - Link from [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md) under a new "Multi-agent" section.
## Audit checklist
diff --git a/prompts/agent-3d/07-manifest-builder-ui.md b/prompts/agent-3d/07-manifest-builder-ui.md
index 4498a9d9c..17c764034 100644
--- a/prompts/agent-3d/07-manifest-builder-ui.md
+++ b/prompts/agent-3d/07-manifest-builder-ui.md
@@ -16,19 +16,19 @@ Ship `src/editor/manifest-builder.js` — a shadow-DOM form UI that produces a v
1. **`src/editor/manifest-builder.js`** — `mountManifestBuilder(rootEl, options)` pattern mirroring [src/editor/embed-editor.js](../../src/editor/embed-editor.js).
2. **Form sections** (collapsible, in this order):
- - **Identity** — name, description, tags, image (defaults to first GLB thumbnail).
- - **Body** — GLB drop-zone (reuses `simple-dropzone`), auto-detected rig (Mixamo / VRM), auto-computed bounding box height.
- - **Brain** — provider select (Anthropic / OpenAI / none), model dropdown filtered by provider, temperature slider, `maxTokens`, thinking toggle.
- - **Voice** — TTS provider select, STT provider select, per-provider secondary fields (voiceId for ElevenLabs, language for Browser/Whisper).
- - **Skills** — searchable list of known skills (load from `public/skills-index.json` — stub with 3 entries for now: wave, dance, explain-gltf). Each skill has "Install" toggle and version pin. Manual URI paste for custom skills.
- - **Memory** — mode select (`local` / `ipfs` / `encrypted-ipfs` / `none`), maxTokens, advanced: timeline retention days.
- - **Instructions** — markdown textarea with monospace font and live char counter. Frontmatter auto-prepended on export.
- - **Provenance** (read-only until GLB loaded) — glTF validator report. Show errors/warnings count + a details drawer.
+ - **Identity** — name, description, tags, image (defaults to first GLB thumbnail).
+ - **Body** — GLB drop-zone (reuses `simple-dropzone`), auto-detected rig (Mixamo / VRM), auto-computed bounding box height.
+ - **Brain** — provider select (Anthropic / OpenAI / none), model dropdown filtered by provider, temperature slider, `maxTokens`, thinking toggle.
+ - **Voice** — TTS provider select, STT provider select, per-provider secondary fields (voiceId for ElevenLabs, language for Browser/Whisper).
+ - **Skills** — searchable list of known skills (load from `public/skills-index.json` — stub with 3 entries for now: wave, dance, explain-gltf). Each skill has "Install" toggle and version pin. Manual URI paste for custom skills.
+ - **Memory** — mode select (`local` / `ipfs` / `encrypted-ipfs` / `none`), maxTokens, advanced: timeline retention days.
+ - **Instructions** — markdown textarea with monospace font and live char counter. Frontmatter auto-prepended on export.
+ - **Provenance** (read-only until GLB loaded) — glTF validator report. Show errors/warnings count + a details drawer.
3. **Live preview panel** — always-mounted `<agent-3d>` inside the builder, manifest= fed by a blob URL of the current form state, re-mounted on change (debounced).
4. **Export actions**:
- - **Download ZIP** — bundles manifest.json, instructions.md (with frontmatter), any dropped GLB, memory/MEMORY.md seed, and referenced skill bundles (if local). Pure client-side.
- - **Pin to IPFS** — uses the configured pinner (see [08-ipfs-pinning-service.md](./08-ipfs-pinning-service.md)). On success, shows the CID and a copy-to-clipboard link.
- - **Register on-chain** — opens the existing ERC-8004 flow with the IPFS CID pre-filled.
+ - **Download ZIP** — bundles manifest.json, instructions.md (with frontmatter), any dropped GLB, memory/MEMORY.md seed, and referenced skill bundles (if local). Pure client-side.
+ - **Pin to IPFS** — uses the configured pinner (see [08-ipfs-pinning-service.md](./08-ipfs-pinning-service.md)). On success, shows the CID and a copy-to-clipboard link.
+ - **Register on-chain** — opens the existing ERC-8004 flow with the IPFS CID pre-filled.
5. **Routing** — add to `agent-home.html` (already in [vite.config.js](../../vite.config.js)) as the canonical "create agent" page.
## Audit checklist
diff --git a/prompts/agent-3d/08-ipfs-pinning-service.md b/prompts/agent-3d/08-ipfs-pinning-service.md
index 6e1603078..7b133927d 100644
--- a/prompts/agent-3d/08-ipfs-pinning-service.md
+++ b/prompts/agent-3d/08-ipfs-pinning-service.md
@@ -18,15 +18,15 @@ Ship `src/pinning/` with a `Pinner` interface, three implementations (web3.stora
4. **`src/pinning/pinata.js`** — `POST /pinning/pinFileToIPFS` with JWT auth.
5. **`src/pinning/null-dev.js`** — hashes the blob with SHA-256, returns a fake `bafkdev-...` CID, stores content in a local `Map` so fetches by that CID resolve during dev.
6. **Pinner interface contract**:
- - `async pinBlob(blob: Blob | Uint8Array, opts?: { name, wrapInDir? }): Promise<{ cid: string, size: number }>`
- - `async pinDirectory(files: Array<{ path, data }>): Promise<{ cid, size }>` — required for bundle-based pins (manifest + body + skills).
- - `async unpin(cid): Promise<void>` — optional; throw NotImplemented if unsupported.
+ - `async pinBlob(blob: Blob | Uint8Array, opts?: { name, wrapInDir? }): Promise<{ cid: string, size: number }>`
+ - `async pinDirectory(files: Array<{ path, data }>): Promise<{ cid, size }>` — required for bundle-based pins (manifest + body + skills).
+ - `async unpin(cid): Promise<void>` — optional; throw NotImplemented if unsupported.
7. **Refactor call sites**:
- - [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js) — replace `pinToIPFS` with `getPinner().pinBlob()`. Preserve the existing `pinToIPFS` export as a thin wrapper for backwards compat.
- - Ensure the encrypted-memory task ([04](./04-encrypted-memory.md)) and manifest builder task ([07](./07-manifest-builder-ui.md)) wire to `getPinner()` — not to a specific backend.
+ - [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js) — replace `pinToIPFS` with `getPinner().pinBlob()`. Preserve the existing `pinToIPFS` export as a thin wrapper for backwards compat.
+ - Ensure the encrypted-memory task ([04](./04-encrypted-memory.md)) and manifest builder task ([07](./07-manifest-builder-ui.md)) wire to `getPinner()` — not to a specific backend.
8. **Config surface**:
- - `window.__agent3dPinner` — if set (to a Pinner instance or a config object), initialize the process-wide pinner from it.
- - Server-side config passthrough: the hosted editor can read env vars (separate task for the backend; this task just defines the shape).
+ - `window.__agent3dPinner` — if set (to a Pinner instance or a config object), initialize the process-wide pinner from it.
+ - Server-side config passthrough: the hosted editor can read env vars (separate task for the backend; this task just defines the shape).
## Audit checklist
diff --git a/prompts/agent-3d/09-validator-attestations.md b/prompts/agent-3d/09-validator-attestations.md
index 51232a0d2..fd2b50527 100644
--- a/prompts/agent-3d/09-validator-attestations.md
+++ b/prompts/agent-3d/09-validator-attestations.md
@@ -13,13 +13,13 @@ Emit a signed attestation when a GLB passes validation, pin it alongside the bod
## Deliverable
1. **`src/attestations/gltf.js`** (new file):
- - `async createGlTFAttestation({ glbBlob, validatorReport, signer, agentId })` — SHA-256 the GLB, embed the validator's summary (error/warning counts, severity max) + issuer + timestamp + agentId + GLB hash. Sign the canonical JSON with the signer's `signMessage`. Return `{ type: "gltf-validator", ... , signature: "0x..." }`.
- - `async verifyGlTFAttestation({ attestation, glbBlob, trustedIssuers? })` — recomputes the hash, recovers the signer from the signature, returns `{ valid: boolean, issuer: string, reasons: string[] }`.
+ - `async createGlTFAttestation({ glbBlob, validatorReport, signer, agentId })` — SHA-256 the GLB, embed the validator's summary (error/warning counts, severity max) + issuer + timestamp + agentId + GLB hash. Sign the canonical JSON with the signer's `signMessage`. Return `{ type: "gltf-validator", ... , signature: "0x..." }`.
+ - `async verifyGlTFAttestation({ attestation, glbBlob, trustedIssuers? })` — recomputes the hash, recovers the signer from the signature, returns `{ valid: boolean, issuer: string, reasons: string[] }`.
2. **Register flow integration** — [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js):
- - After validation but before registration JSON is built, call `createGlTFAttestation`, pin via `getPinner()`, add the CID to the registration JSON under `attestations`.
+ - After validation but before registration JSON is built, call `createGlTFAttestation`, pin via `getPinner()`, add the CID to the registration JSON under `attestations`.
3. **Runtime integration** — [src/element.js](../../src/element.js) `_boot()`:
- - If `manifest.attestations` includes a `gltf-validator` entry, fetch the attestation JSON and the GLB, `verifyGlTFAttestation`.
- - On `valid: false`: emit `agent:warning { type: "attestation-invalid" }` and either continue (default) or refuse (if `manifest.require.validAttestation === true`).
+ - If `manifest.attestations` includes a `gltf-validator` entry, fetch the attestation JSON and the GLB, `verifyGlTFAttestation`.
+ - On `valid: false`: emit `agent:warning { type: "attestation-invalid" }` and either continue (default) or refuse (if `manifest.require.validAttestation === true`).
4. **Element attribute** — `require-attestation="true"` refuses to mount agents with invalid or missing attestations.
5. **Spec update** — [specs/AGENT_MANIFEST.md](../../specs/AGENT_MANIFEST.md) § attestations: document the canonical signing message format.
diff --git a/prompts/agent-3d/10-responsive-presets.md b/prompts/agent-3d/10-responsive-presets.md
index 7dc3f3712..9d4a6e4b4 100644
--- a/prompts/agent-3d/10-responsive-presets.md
+++ b/prompts/agent-3d/10-responsive-presets.md
@@ -13,22 +13,25 @@ Ship responsive dimensions: the element adapts sensibly to viewport width when `
## Deliverable
1. **Element-level responsive** — [src/element.js](../../src/element.js):
- - When `responsive` attribute is present (default on), compute `width` / `height` as `clamp(min, preferred, max)` values. Preferred is what the user set; min/max derive from that preferred.
- - For `mode="floating"`, shrink to a pill (mic-only, chat collapsed) when viewport width < 480px. User can tap to expand.
- - For `mode="inline"`, scale height proportionally to width so the avatar doesn't stretch.
- - Use a `ResizeObserver` on `this` so the layout reacts to container size, not just viewport.
+ - When `responsive` attribute is present (default on), compute `width` / `height` as `clamp(min, preferred, max)` values. Preferred is what the user set; min/max derive from that preferred.
+ - For `mode="floating"`, shrink to a pill (mic-only, chat collapsed) when viewport width < 480px. User can tap to expand.
+ - For `mode="inline"`, scale height proportionally to width so the avatar doesn't stretch.
+ - Use a `ResizeObserver` on `this` so the layout reacts to container size, not just viewport.
2. **Floating pill mode** — when collapsed on mobile:
- - Shows only the poster image + a tap target.
- - Expands to a bottom-sheet (full width, ~70vh) on tap, not the full floating rect.
- - Closes to pill on outside tap or swipe-down.
+ - Shows only the poster image + a tap target.
+ - Expands to a bottom-sheet (full width, ~70vh) on tap, not the full floating rect.
+ - Closes to pill on outside tap or swipe-down.
3. **Editor device preview** — [src/editor/embed-editor.js](../../src/editor/embed-editor.js):
- - Add a toolbar: `[ Desktop | Tablet | Mobile ]` above the stage. Each resizes the stage wrapper to 1440×900 / 768×1024 / 390×844 (iPhone 14) and shows the agent at the corresponding computed size.
- - Add a "Responsive preset" selector: `[ Fixed | Mobile-first | Desktop-first ]` — each generates different `width`/`height`/`offset` CSS rules in the snippet output.
- - Snippet output gains a commented block showing the computed CSS:
- ```html
- <!-- generated responsive styles -->
- <agent-3d ... style="--agent-width: clamp(280px, 30vw, 420px); --agent-height: clamp(360px, 40vh, 560px);"></agent-3d>
- ```
+ - Add a toolbar: `[ Desktop | Tablet | Mobile ]` above the stage. Each resizes the stage wrapper to 1440×900 / 768×1024 / 390×844 (iPhone 14) and shows the agent at the corresponding computed size.
+ - Add a "Responsive preset" selector: `[ Fixed | Mobile-first | Desktop-first ]` — each generates different `width`/`height`/`offset` CSS rules in the snippet output.
+ - Snippet output gains a commented block showing the computed CSS:
+ ```html
+ <!-- generated responsive styles -->
+ <agent-3d
+ ...
+ style="--agent-width: clamp(280px, 30vw, 420px); --agent-height: clamp(360px, 40vh, 560px);"
+ ></agent-3d>
+ ```
## Audit checklist
diff --git a/prompts/agent-3d/11-ar-webxr.md b/prompts/agent-3d/11-ar-webxr.md
index 6ed3c3b4d..9c70369be 100644
--- a/prompts/agent-3d/11-ar-webxr.md
+++ b/prompts/agent-3d/11-ar-webxr.md
@@ -5,6 +5,7 @@
Per [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md) the element exposes an `ar` boolean attribute. It's currently a no-op. `<model-viewer>` solved this for a flat GLB preview; we extend their trick for an embodied agent — spawn the body in the user's space, voice continues through the device, agent uses gaze/look-at tools tied to the user's head pose.
Three AR paths need support:
+
- **WebXR immersive-ar** (Chrome Android, modern Meta Quest browser).
- **Quick Look** on iOS via a USDZ export of the GLB (or a pre-pinned USDZ companion).
- **Scene Viewer** on Android as a fallback when WebXR isn't present.
@@ -16,22 +17,22 @@ Implement the `ar` attribute end-to-end: tap the AR button → AR session launch
## Deliverable
1. **`src/ar/webxr.js`** (new file):
- - Detect capability via `navigator.xr?.isSessionSupported("immersive-ar")`.
- - Start a hit-test-enabled session, reuse the element's Three.js renderer with XR mode, anchor the agent body on tap.
- - Maintain a `user` target Vector3 tracked to the XR camera so `lookAt("user")` actually looks at the wearer.
- - End the session cleanly when user exits; return to non-AR mode without re-mounting.
+ - Detect capability via `navigator.xr?.isSessionSupported("immersive-ar")`.
+ - Start a hit-test-enabled session, reuse the element's Three.js renderer with XR mode, anchor the agent body on tap.
+ - Maintain a `user` target Vector3 tracked to the XR camera so `lookAt("user")` actually looks at the wearer.
+ - End the session cleanly when user exits; return to non-AR mode without re-mounting.
2. **`src/ar/scene-viewer.js`**:
- - Detect Android (UA sniffing is acceptable for Intent URLs).
- - Build an Android Intent URL: `intent://arvr.google.com/scene-viewer/1.2?file={glbURL}&mode=ar_preferred#Intent;...`.
+ - Detect Android (UA sniffing is acceptable for Intent URLs).
+ - Build an Android Intent URL: `intent://arvr.google.com/scene-viewer/1.2?file={glbURL}&mode=ar_preferred#Intent;...`.
3. **`src/ar/quick-look.js`**:
- - If iOS and a USDZ companion URL is present in the manifest (`body.usdzURI`), open it with `<a rel="ar" href="{usdz}"><img></a>` sugar.
- - If no USDZ, offer to convert on the fly via a server endpoint (placeholder) or display a graceful "AR unavailable on this device" message.
+ - If iOS and a USDZ companion URL is present in the manifest (`body.usdzURI`), open it with `<a rel="ar" href="{usdz}"><img></a>` sugar.
+ - If no USDZ, offer to convert on the fly via a server endpoint (placeholder) or display a graceful "AR unavailable on this device" message.
4. **Element wiring** — [src/element.js](../../src/element.js):
- - Render a slotted `<button slot="ar-button">View in your space</button>` by default.
- - Click handler selects the best AR path for the device in order: WebXR → Scene Viewer → Quick Look → fail.
- - Emit `ar:start` / `ar:end` events.
+ - Render a slotted `<button slot="ar-button">View in your space</button>` by default.
+ - Click handler selects the best AR path for the device in order: WebXR → Scene Viewer → Quick Look → fail.
+ - Emit `ar:start` / `ar:end` events.
5. **Manifest** — [specs/AGENT_MANIFEST.md](../../specs/AGENT_MANIFEST.md):
- - Add optional `body.usdzURI` and `body.arPreferred` fields.
+ - Add optional `body.usdzURI` and `body.arPreferred` fields.
## Audit checklist
diff --git a/prompts/archive/agent-3d/02-elevenlabs-tts.md b/prompts/archive/agent-3d/02-elevenlabs-tts.md
index f335974d5..e10e135d4 100644
--- a/prompts/archive/agent-3d/02-elevenlabs-tts.md
+++ b/prompts/archive/agent-3d/02-elevenlabs-tts.md
@@ -13,11 +13,11 @@ Add `ElevenLabsTTS` to [src/runtime/speech.js](../../src/runtime/speech.js) that
## Deliverable
1. **`ElevenLabsTTS` class** in [src/runtime/speech.js](../../src/runtime/speech.js):
- - Constructor: `{ voiceId, modelId = "eleven_turbo_v2_5", apiKey, proxyURL, rate = 1, pitch = 1, lang = "en-US" }`.
- - `async speak(text, { onStart, onEnd })` — POST to ElevenLabs `text-to-speech/{voiceId}/stream` endpoint (via `proxyURL` if set, else direct with `apiKey`). Stream the audio response via `MediaSource` or fall back to buffered `<audio>` playback if the browser doesn't support MSE for `audio/mpeg`.
- - `cancel()` aborts the fetch and stops playback. Set `this._speaking = false`.
- - Respect `rate` and `pitch` by mapping to ElevenLabs' `voice_settings` (`stability`, `similarity_boost`, `style`, `use_speaker_boost`) where reasonable. Document mapping choice in a code comment.
- - Same public surface as `BrowserTTS`: `speak`, `cancel`, `speaking` getter.
+ - Constructor: `{ voiceId, modelId = "eleven_turbo_v2_5", apiKey, proxyURL, rate = 1, pitch = 1, lang = "en-US" }`.
+ - `async speak(text, { onStart, onEnd })` — POST to ElevenLabs `text-to-speech/{voiceId}/stream` endpoint (via `proxyURL` if set, else direct with `apiKey`). Stream the audio response via `MediaSource` or fall back to buffered `<audio>` playback if the browser doesn't support MSE for `audio/mpeg`.
+ - `cancel()` aborts the fetch and stops playback. Set `this._speaking = false`.
+ - Respect `rate` and `pitch` by mapping to ElevenLabs' `voice_settings` (`stability`, `similarity_boost`, `style`, `use_speaker_boost`) where reasonable. Document mapping choice in a code comment.
+ - Same public surface as `BrowserTTS`: `speak`, `cancel`, `speaking` getter.
2. **Register in `createTTS()`** — dispatch `provider === "elevenlabs"`.
3. **Update [specs/AGENT_MANIFEST.md](../../specs/AGENT_MANIFEST.md)** — extend the `voice.tts.provider` enum to include `"elevenlabs"` with a note about `voiceId` and `modelId` fields.
4. **Update [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md)** — document that `tts="elevenlabs:{voiceId}"` on the element is shorthand. Parser lives in [src/element.js](../../src/element.js).
diff --git a/prompts/archive/final-integration/01-embed-bridges.md b/prompts/archive/final-integration/01-embed-bridges.md
index 4354b71d4..daf3828b3 100644
--- a/prompts/archive/final-integration/01-embed-bridges.md
+++ b/prompts/archive/final-integration/01-embed-bridges.md
@@ -5,6 +5,7 @@
The `<agent-3d>` web component is the sole distribution channel for the 3D Agent product. It's embedded inside third-party sites (Claude.ai artifacts, LobeHub plugins, customer pages). When an agent lives inside an iframe, the host page has no way to talk to it and vice versa — you can't tell the agent to speak, change avatar, or react to chat messages. You also can't hear the agent's events (skill calls, action logs, state changes) from the parent.
Sprint-100 mapped two bridge modules to fill this gap:
+
- `src/embed-host-bridge.js` — iframe ↔ parent `postMessage` transport. Handshake, origin check, request/response routing.
- `src/embed-action-bridge.js` — translates bridge messages into `AgentProtocol` events on the agent side and back out on the parent side.
@@ -17,10 +18,12 @@ Build a production-grade bidirectional bridge between a host page and an embedde
## Files you own
Create:
+
- `src/embed-host-bridge.js`
- `src/embed-action-bridge.js`
Edit (inside uniquely-named anchor only):
+
- `src/element.js` — add a single anchor block `<!-- BEGIN:EMBED_BRIDGES --> ... <!-- END:EMBED_BRIDGES -->` near the end of the `connectedCallback` / mount path. Wire both bridges in when the element mounts inside an iframe. **Do not edit anything outside that anchor.**
## Files read-only
@@ -47,18 +50,22 @@ Use `postMessage` with a structured envelope. Every message MUST include:
```
Handshake:
+
- Child (`agent-3d`) posts `{ kind: 'event', op: 'ready', payload: { agentId, capabilities: [...] } }` once mounted.
- Parent responds with `{ kind: 'request', op: 'ping' }`; child replies `{ kind: 'response', op: 'pong', inReplyTo }`. That round-trip confirms both sides.
Origin security:
+
- Respect the agent manifest's `policy.origins` allowlist (already parsed by `src/element.js:originAllowed`). Reject any `postMessage` whose `event.origin` is not on the allowlist.
- On the parent side, accept messages only from `event.source === iframe.contentWindow`.
Timeouts & retries:
+
- Requests carry a 10s timeout. If no response, reject with `TimeoutError`.
- No automatic retries — the host decides.
Backpressure:
+
- Queue outgoing requests if handshake is not yet complete. Flush on `ready`.
- Drop events (never buffer them indefinitely) if no listener — cap at 256 queued events to prevent memory runaway.
@@ -90,6 +97,7 @@ Export a class `EmbedActionBridge` that lives **inside** the `<agent-3d>` elemen
4. Translates protocol errors into `kind: 'event', op: 'error', payload: { code, message }`.
Constructor:
+
```js
new EmbedActionBridge({ protocol, avatar, manifest, window: win })
.start(): void
@@ -107,13 +115,13 @@ Inside the anchor block `EMBED_BRIDGES`, at the tail of the mount path (after `r
import { EmbedActionBridge } from './embed-action-bridge.js';
if (window !== window.parent) {
- this._embedBridge = new EmbedActionBridge({
- protocol: this._protocol,
- avatar: this._avatar,
- manifest: this._manifest,
- window,
- });
- this._embedBridge.start();
+ this._embedBridge = new EmbedActionBridge({
+ protocol: this._protocol,
+ avatar: this._avatar,
+ manifest: this._manifest,
+ window,
+ });
+ this._embedBridge.start();
}
// END:EMBED_BRIDGES
```
diff --git a/prompts/final-integration/05-lobehub-real-integration.md b/prompts/archive/final-integration/05-lobehub-real-integration.md
similarity index 76%
rename from prompts/final-integration/05-lobehub-real-integration.md
rename to prompts/archive/final-integration/05-lobehub-real-integration.md
index 1690ca595..649f6dd5b 100644
--- a/prompts/final-integration/05-lobehub-real-integration.md
+++ b/prompts/archive/final-integration/05-lobehub-real-integration.md
@@ -14,6 +14,7 @@ The goal is a **shippable** LobeHub plugin — not a scaffold. When this is done
## Goal
Ship an installable LobeHub plugin with:
+
- A correct manifest matching the current LobeHub plugin schema.
- A React iframe host that resolves an agent id → `<agent-3d>` iframe → working bridge.
- A working hook into LobeChat's message stream (assistant messages → `avatar.speak(...)` with sentiment).
@@ -24,6 +25,7 @@ Ship an installable LobeHub plugin with:
## Files you own
Everything under:
+
- `lobehub-plugin/**` (except `node_modules/`)
- `public/.well-known/lobehub-plugin.json` (the manifest served from the 3dagent.vercel.app origin for remote-plugin installs)
- `public/lobehub/iframe/**` (the iframe target referenced by the manifest — create if it doesn't fully exist yet)
@@ -39,32 +41,33 @@ Everything under:
## Acceptance — what "shippable" means
1. **Manifest.** `public/.well-known/lobehub-plugin.json` validates against the current LobeHub plugin-manifest JSON Schema. Check the LobeHub docs (<https://lobehub.com/docs/usage/plugins/development>) for the schemaVersion and ensure:
- - `identifier` is globally unique (`3d-agent` is reasonable).
- - `$schema` points to the canonical URL.
- - `api` entries either all resolve to real endpoints or the `api` array is omitted if this is iframe-only.
- - `ui.url` points to `https://3dagent.vercel.app/lobehub/iframe/` and that route actually serves HTML.
- - `settings` schema matches what the React component reads (`agentId`, `apiOrigin`).
+ - `identifier` is globally unique (`3d-agent` is reasonable).
+ - `$schema` points to the canonical URL.
+ - `api` entries either all resolve to real endpoints or the `api` array is omitted if this is iframe-only.
+ - `ui.url` points to `https://3dagent.vercel.app/lobehub/iframe/` and that route actually serves HTML.
+ - `settings` schema matches what the React component reads (`agentId`, `apiOrigin`).
2. **Iframe host.** `public/lobehub/iframe/index.html` renders `<agent-3d agent-id="{{agentId}}">` with correct styling for a 420–640px sidebar frame. Transparent background, no scrollbars, respects the `agentId` query param (the LobeHub host passes settings as querystring or fragment — implement whichever the real manifest spec requires).
3. **React plugin package.** `lobehub-plugin/src/`:
- - `AgentPane.tsx` — remove the `TODO: Hook into Lobe's onAssistantMessage` placeholder. Use whatever `@lobehub/ui` / `@lobehub/chat-plugin-sdk` package exposes for assistant-message observation. If the SDK shape is unstable, document fallback to the `window.addEventListener('lobe:assistantMessage', …)` path explicitly with a README note + a clear code comment explaining why this fallback exists.
- - `bridge.ts` — align with the final wire protocol from prompt 01. Every `op` in the manifest's `api` array (`render_agent`, `speak`, `gesture`, `emote`) has a matching bridge method. Handshake, timeout, origin check.
- - `config-schema.ts` — export a zod-like validator (or hand-rolled if zod isn't in deps) that guards `PluginSettings`.
- - `index.ts` — default export the plugin entry expected by the LobeHub runtime.
+ - `AgentPane.tsx` — remove the `TODO: Hook into Lobe's onAssistantMessage` placeholder. Use whatever `@lobehub/ui` / `@lobehub/chat-plugin-sdk` package exposes for assistant-message observation. If the SDK shape is unstable, document fallback to the `window.addEventListener('lobe:assistantMessage', …)` path explicitly with a README note + a clear code comment explaining why this fallback exists.
+ - `bridge.ts` — align with the final wire protocol from prompt 01. Every `op` in the manifest's `api` array (`render_agent`, `speak`, `gesture`, `emote`) has a matching bridge method. Handshake, timeout, origin check.
+ - `config-schema.ts` — export a zod-like validator (or hand-rolled if zod isn't in deps) that guards `PluginSettings`.
+ - `index.ts` — default export the plugin entry expected by the LobeHub runtime.
4. **Build.**
- - `cd lobehub-plugin && npm install && npm run build` produces `dist/bundle.js` with a tree-shaken, production-minified build.
- - No warnings in the build output.
- - `npm run type-check` passes.
+ - `cd lobehub-plugin && npm install && npm run build` produces `dist/bundle.js` with a tree-shaken, production-minified build.
+ - No warnings in the build output.
+ - `npm run type-check` passes.
5. **Dev harness.** `lobehub-plugin/dev/index.html` (new file) loads the built plugin inside a page that mocks the LobeChat host message contract. Include a button to inject a fake assistant message so the avatar can be seen reacting in isolation.
6. **Docs.**
- - `lobehub-plugin/README.md` — install instructions, config options, troubleshooting, link to the manifest URL for "one-click" install in LobeChat.
- - `LICENSE` file (MIT or Apache-2 — match what the rest of the repo uses).
+ - `lobehub-plugin/README.md` — install instructions, config options, troubleshooting, link to the manifest URL for "one-click" install in LobeChat.
+ - `LICENSE` file (MIT or Apache-2 — match what the rest of the repo uses).
7. **Icons / screenshots.**
- - `lobehub-plugin/assets/icon-256.png` (transparent square, 256×256) — if asset missing, generate a placeholder SVG + note in report that a designed icon needs replacing before launch.
- - `lobehub-plugin/assets/screenshots/` with at least one screenshot referenced by the README.
+ - `lobehub-plugin/assets/icon-256.png` (transparent square, 256×256) — if asset missing, generate a placeholder SVG + note in report that a designed icon needs replacing before launch.
+ - `lobehub-plugin/assets/screenshots/` with at least one screenshot referenced by the README.
## Allowed new deps
`lobehub-plugin/package.json` may add:
+
- `@lobehub/chat-plugin-sdk` (or the current official plugin SDK name — verify on npm at build time).
- `zod` if you use it for config validation — optional.
- Nothing else.
@@ -107,6 +110,7 @@ Your `bridge.ts` sends requests matching this exact envelope and op set. If you
## Report + archive
Post the report block from `00-README.md`. Include:
+
- Exact LobeHub SDK package name + version you targeted.
- Whether the SDK exposes a real `onAssistantMessage` hook (and what you used if it doesn't).
- Build output bytes (`dist/bundle.js` size).
diff --git a/prompts/archive/final-integration/06-camera-capture-resolution.md b/prompts/archive/final-integration/06-camera-capture-resolution.md
index deedc5bd9..6965d9a93 100644
--- a/prompts/archive/final-integration/06-camera-capture-resolution.md
+++ b/prompts/archive/final-integration/06-camera-capture-resolution.md
@@ -31,6 +31,7 @@ Either path: **only one camera capture module must exist at the end.**
## Files you own
Edit / delete:
+
- `src/camera-capture.js`
- `src/camera-capture.css`
- `src/selfie-capture.js` (only if you choose Path B and need to merge APIs)
@@ -83,6 +84,7 @@ If any box is unchecked, either close the gap in `selfie-capture.js` as part of
## Report + archive
Post the report block from `00-README.md`. Include:
+
- Path taken (A or B).
- Feature parity gaps found (if any) and how you closed them.
- Files deleted.
diff --git a/prompts/archive/widget-studio/00-studio-foundation.md b/prompts/archive/widget-studio/00-studio-foundation.md
index 1c8d2c0f6..708fc2e88 100644
--- a/prompts/archive/widget-studio/00-studio-foundation.md
+++ b/prompts/archive/widget-studio/00-studio-foundation.md
@@ -20,17 +20,17 @@ None. This prompt assumes the current codebase state as of commit `ef3b0d4`. Rea
## Read these first (do not skip)
-| File | Why |
-|:---|:---|
-| [src/app.js](../../src/app.js) — lines 36–100, 270–340 | Understand the existing App boot sequence, URL hash parsing, `view()` method signature, and how `protocol`/`identity`/`avatar`/`runtime` are wired. You will add `hash.widget` parsing here. |
-| [src/viewer.js](../../src/viewer.js) — constructor + `load()` + `setCamera()` | The `Viewer` class is what you'll render inside the Studio preview iframe. It already supports `cameraPosition`, background color, HDR environments, animations. |
-| [src/account.js](../../src/account.js) | Existing client for avatar CRUD against `/api/avatars`. Mirror this pattern for widgets. |
-| [api/avatars/index.js](../../api/avatars/index.js) and [api/avatars/presign.js](../../api/avatars/presign.js) | Reference implementation for an authenticated Vercel serverless CRUD endpoint backed by Neon. Follow the same auth + error conventions. |
-| [api/_lib/](../../api/_lib/) | Shared helpers: auth middleware, Neon client, response helpers. Use these — do not create duplicates. |
-| [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js) — lines 1–90 | Dashboard's native-DOM rendering pattern. The Studio UI should follow the same style (no framework, no JSX runtime on the client — use `vhtml` if you want JSX, same as the validator components). |
-| [vercel.json](../../vercel.json) | Route table. You will add `/studio` and `/api/widgets/*` routes here. |
-| [style.css](../../style.css) | Existing dark theme tokens. Reuse the CSS variables and classes; do not introduce a new design system. |
-| [index.html](../../index.html) | The SPA shell. You need to understand how hash params are consumed so `#widget=<id>` can hook in without breaking existing `#model=` behavior. |
+| File | Why |
+| :------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| [src/app.js](../../src/app.js) — lines 36–100, 270–340 | Understand the existing App boot sequence, URL hash parsing, `view()` method signature, and how `protocol`/`identity`/`avatar`/`runtime` are wired. You will add `hash.widget` parsing here. |
+| [src/viewer.js](../../src/viewer.js) — constructor + `load()` + `setCamera()` | The `Viewer` class is what you'll render inside the Studio preview iframe. It already supports `cameraPosition`, background color, HDR environments, animations. |
+| [src/account.js](../../src/account.js) | Existing client for avatar CRUD against `/api/avatars`. Mirror this pattern for widgets. |
+| [api/avatars/index.js](../../api/avatars/index.js) and [api/avatars/presign.js](../../api/avatars/presign.js) | Reference implementation for an authenticated Vercel serverless CRUD endpoint backed by Neon. Follow the same auth + error conventions. |
+| [api/\_lib/](../../api/_lib/) | Shared helpers: auth middleware, Neon client, response helpers. Use these — do not create duplicates. |
+| [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js) — lines 1–90 | Dashboard's native-DOM rendering pattern. The Studio UI should follow the same style (no framework, no JSX runtime on the client — use `vhtml` if you want JSX, same as the validator components). |
+| [vercel.json](../../vercel.json) | Route table. You will add `/studio` and `/api/widgets/*` routes here. |
+| [style.css](../../style.css) | Existing dark theme tokens. Reuse the CSS variables and classes; do not introduce a new design system. |
+| [index.html](../../index.html) | The SPA shell. You need to understand how hash params are consumed so `#widget=<id>` can hook in without breaking existing `#model=` behavior. |
Also run `ls api/_lib` and open every file in there — one of them almost certainly has `requireAuth()` or equivalent. Use it. Do not hand-roll auth.
@@ -64,13 +64,13 @@ create index if not exists widgets_type_idx on widgets(type);
Create the following under `api/widgets/`:
-| File | Method + Path | Auth | Purpose |
-|:---|:---|:---|:---|
-| `api/widgets/index.js` | `GET /api/widgets` | required | List current user's widgets. |
-| `api/widgets/index.js` | `POST /api/widgets` | required | Create a widget. Returns `{ id, ... }`. |
-| `api/widgets/[id].js` | `GET /api/widgets/:id` | **public** | Fetch a widget config by id. If `is_public=false`, require auth + ownership. Increment `view_count`. |
-| `api/widgets/[id].js` | `PATCH /api/widgets/:id` | required + owner | Update config/name/is_public. |
-| `api/widgets/[id].js` | `DELETE /api/widgets/:id` | required + owner | Delete. |
+| File | Method + Path | Auth | Purpose |
+| :--------------------- | :------------------------ | :--------------- | :--------------------------------------------------------------------------------------------------- |
+| `api/widgets/index.js` | `GET /api/widgets` | required | List current user's widgets. |
+| `api/widgets/index.js` | `POST /api/widgets` | required | Create a widget. Returns `{ id, ... }`. |
+| `api/widgets/[id].js` | `GET /api/widgets/:id` | **public** | Fetch a widget config by id. If `is_public=false`, require auth + ownership. Increment `view_count`. |
+| `api/widgets/[id].js` | `PATCH /api/widgets/:id` | required + owner | Update config/name/is_public. |
+| `api/widgets/[id].js` | `DELETE /api/widgets/:id` | required + owner | Delete. |
ID format: `wdgt_` + 12 URL-safe random chars (use `crypto.randomBytes(9).toString('base64url')` and verify the length — 9 bytes → 12 base64url chars).
@@ -98,26 +98,35 @@ Create `src/widget-types.js`. Defines:
```js
export const WIDGET_TYPES = {
- 'turntable': { label: 'Turntable Showcase', status: 'ready', icon: '...', desc: '...' },
- 'animation-gallery': { label: 'Animation Gallery', status: 'pending', icon: '...', desc: '...' },
- 'talking-agent': { label: 'Talking Agent', status: 'pending', icon: '...', desc: '...' },
- 'passport': { label: 'ERC-8004 Passport', status: 'pending', icon: '...', desc: '...' },
- 'hotspot-tour': { label: 'Hotspot Tour', status: 'pending', icon: '...', desc: '...' },
+ turntable: { label: 'Turntable Showcase', status: 'ready', icon: '...', desc: '...' },
+ 'animation-gallery': {
+ label: 'Animation Gallery',
+ status: 'pending',
+ icon: '...',
+ desc: '...',
+ },
+ 'talking-agent': { label: 'Talking Agent', status: 'pending', icon: '...', desc: '...' },
+ passport: { label: 'ERC-8004 Passport', status: 'pending', icon: '...', desc: '...' },
+ 'hotspot-tour': { label: 'Hotspot Tour', status: 'pending', icon: '...', desc: '...' },
};
// Shared brand config present on every widget
export const BRAND_DEFAULTS = {
- background: '#0a0a0a',
- accent: '#00e5a0',
- caption: '',
- showControls: true,
- autoRotate: true,
- envPreset: 'neutral',
- cameraPosition: null, // [x, y, z] or null for auto-frame
+ background: '#0a0a0a',
+ accent: '#00e5a0',
+ caption: '',
+ showControls: true,
+ autoRotate: true,
+ envPreset: 'neutral',
+ cameraPosition: null, // [x, y, z] or null for auto-frame
};
-export function defaultConfig(type) { /* returns { ...BRAND_DEFAULTS, ...typeSpecificDefaults[type] } */ }
-export function validateConfig(type, config) { /* zod parse, throws on invalid */ }
+export function defaultConfig(type) {
+ /* returns { ...BRAND_DEFAULTS, ...typeSpecificDefaults[type] } */
+}
+export function validateConfig(type, config) {
+ /* zod parse, throws on invalid */
+}
```
`status: 'ready'` on type `turntable` only (per run order — the Turntable prompt will flip more to `ready` as they ship).
@@ -154,6 +163,7 @@ Column 1 calls `api.listAvatars()` (reuse `dashboard.js`'s `api`). Thumbnail car
Column 2 is an `<iframe src="/?widget-preview=1#model=<model_url>&kiosk=true&...">` that reloads whenever config changes (debounce 200ms). **Do not build a second viewer.** Reuse the existing one via URL hash params. To apply brand colors, post a message to the iframe (next section).
Column 3 is a form. All changes update in-memory state and trigger the debounced preview reload. Fields:
+
- **Name** (text, required)
- **Background color** (color picker)
- **Accent color** (color picker)
@@ -165,18 +175,20 @@ Column 3 is a form. All changes update in-memory state and trigger the debounced
- **Type-specific fields** — for `turntable`, just rotation speed. For others, show a placeholder "Configured by Widget 0X — coming soon."
Below the form:
+
- **[Save Draft]** button → `createWidget()` or `updateWidget()` if editing.
- **[Generate Embed]** button → saves, then opens a modal with:
- - Live preview
- - Shareable URL: `https://<host>/#widget=<id>`
- - Iframe snippet (600x600 default, editable dimensions)
- - One-line script snippet: `<script async src="https://<host>/embed.js" data-widget="<id>"></script>` (stub script file — create `public/embed.js` that just creates an iframe for now)
- - "Show HTML" disclosure showing the raw snippet
- - Copy-to-clipboard buttons
+ - Live preview
+ - Shareable URL: `https://<host>/#widget=<id>`
+ - Iframe snippet (600x600 default, editable dimensions)
+ - One-line script snippet: `<script async src="https://<host>/embed.js" data-widget="<id>"></script>` (stub script file — create `public/embed.js` that just creates an iframe for now)
+ - "Show HTML" disclosure showing the raw snippet
+ - Copy-to-clipboard buttons
### 6. `postMessage` bridge between Studio and preview iframe
The Studio parent sends live config updates to the preview iframe without a full reload. In `src/app.js`, add a message listener that accepts `{ type: 'widget:config', config }` and applies:
+
- Background color → `viewer.setBackgroundColor(config.background)` (add this method to `Viewer` if missing — it already supports background color via dat.gui, so the logic exists).
- Auto-rotate → `viewer.controls.autoRotate = config.autoRotate`.
- Env preset → `viewer.setEnvironment(preset)` (already exists).
@@ -192,13 +204,13 @@ In `src/app.js`, after parsing the hash:
```js
if (hash.widget) {
- const widget = await getWidget(hash.widget); // public endpoint
- // Apply widget.config to this.options before any viewer work:
- // - model URL comes from widget.avatar.model_url (server-joined or second fetch)
- // - cameraPosition, background, etc. from config
- // Then proceed with normal view() flow.
- // Also expose widget.type so later prompts can branch on it:
- window.VIEWER.widget = widget;
+ const widget = await getWidget(hash.widget); // public endpoint
+ // Apply widget.config to this.options before any viewer work:
+ // - model URL comes from widget.avatar.model_url (server-joined or second fetch)
+ // - cameraPosition, background, etc. from config
+ // Then proceed with normal view() flow.
+ // Also expose widget.type so later prompts can branch on it:
+ window.VIEWER.widget = widget;
}
```
@@ -220,11 +232,12 @@ If the widget id is unknown, show an in-page error: "Widget not found." Do not r
- Do not duplicate auth logic — reuse the helper in `api/_lib/`.
- Do not create a mock mode. If the Neon connection fails locally, document how to run Neon in dev (probably via `DATABASE_URL` env var — check how `api/avatars` does it).
- Do not hardcode the production domain. Use `location.origin` client-side and `req.headers.host` (or Vercel env vars) server-side.
-- Do not ship the widget type cards as unclickable placeholders. "Coming soon" types should be *clickable* and render a Studio form with a banner saying "This widget type isn't functional yet — you can save the config; the runtime will light up when its prompt ships." The config still saves and round-trips.
+- Do not ship the widget type cards as unclickable placeholders. "Coming soon" types should be _clickable_ and render a Studio form with a banner saying "This widget type isn't functional yet — you can save the config; the runtime will light up when its prompt ships." The config still saves and round-trips.
## Deliverables (exact file list)
**New:**
+
- `api/_lib/migrations/002_widgets.sql` (or next available number — verify first)
- `api/widgets/index.js`
- `api/widgets/[id].js`
@@ -236,6 +249,7 @@ If the widget id is unknown, show an in-page error: "Widget not found." Do not r
- `public/embed.js` (stub iframe-injector script)
**Modified:**
+
- `src/app.js` — add `hash.widget` handling + postMessage listener
- `src/viewer.js` — add `setBackgroundColor()` if not already exposed as a public method
- `vercel.json` — add `/studio`, `/api/widgets`, `/api/widgets/*` routes
@@ -265,9 +279,9 @@ You are done when **all** of these are true:
4. Click "Use current view" after orbiting — preview persists that camera.
5. Save draft. Refresh. Verify it re-loads the draft.
6. Generate embed. Copy the URL. Paste in a private window. Verify:
- - Model loads.
- - Background, camera, env are applied.
- - No dat.gui panel if `showControls=false`.
+ - Model loads.
+ - Background, camera, env are applied.
+ - No dat.gui panel if `showControls=false`.
7. Deliberately break: visit `/#widget=wdgt_does_not_exist`. Verify graceful error, not a crash.
8. Open `public/embed.js` snippet in an HTML scratch file. Verify it injects an iframe.
9. `npm run build && npm run dev` — confirm production build works.
diff --git a/prompts/avatar-edit/01-edit-appearance-flow.md b/prompts/avatar-edit/01-edit-appearance-flow.md
index 42cc30fb3..27d7aa1a3 100644
--- a/prompts/avatar-edit/01-edit-appearance-flow.md
+++ b/prompts/avatar-edit/01-edit-appearance-flow.md
@@ -17,19 +17,21 @@ AgentId does not change. Wallet link does not change.
## Deliverable
1. **Backend**
- - New endpoint: `POST /api/avatars/:id/session` — creates an Avaturn edit session for the given avatar the caller owns. Returns `{ sessionUrl }`. Rate-limit via `limits.upload(userId)`.
- - New column (or reuse a JSON `meta` field on `avatars`): `parent_avatar_id uuid null references avatars(id)` so history is queryable. If adding a column requires a migration, document the SQL in the reporting section — do not silently change schema.
- - New endpoint: `GET /api/avatars/:id/versions` — returns ordered list of `{ id, created_at, storage_key, is_current }` for an avatar and its ancestors.
- - Update [api/avatars/index.js](../../api/avatars/index.js) (the POST handler) to accept an optional `parent_avatar_id` in the body and persist it; when set, the newly registered avatar is treated as a version of that parent and `agent_identities.avatar_id` is updated in the same transaction.
+
+ - New endpoint: `POST /api/avatars/:id/session` — creates an Avaturn edit session for the given avatar the caller owns. Returns `{ sessionUrl }`. Rate-limit via `limits.upload(userId)`.
+ - New column (or reuse a JSON `meta` field on `avatars`): `parent_avatar_id uuid null references avatars(id)` so history is queryable. If adding a column requires a migration, document the SQL in the reporting section — do not silently change schema.
+ - New endpoint: `GET /api/avatars/:id/versions` — returns ordered list of `{ id, created_at, storage_key, is_current }` for an avatar and its ancestors.
+ - Update [api/avatars/index.js](../../api/avatars/index.js) (the POST handler) to accept an optional `parent_avatar_id` in the body and persist it; when set, the newly registered avatar is treated as a version of that parent and `agent_identities.avatar_id` is updated in the same transaction.
2. **Frontend — src/avatar-creator.js**
- - Extend `AvatarCreator.open(sessionUrl, { existingAvatarUrl } = {})` so the caller can pass a preload URL. Pass it through to `AvaturnSDK.init` as whatever option the SDK exposes for "continue from this avatar" (check the SDK's current options — if no such option exists, document what would be needed and fall back to opening fresh with a warning banner in the modal).
- - Extend `onExport` signature so callers get the same `glbUrl` they do today — no breaking change.
+
+ - Extend `AvatarCreator.open(sessionUrl, { existingAvatarUrl } = {})` so the caller can pass a preload URL. Pass it through to `AvaturnSDK.init` as whatever option the SDK exposes for "continue from this avatar" (check the SDK's current options — if no such option exists, document what would be needed and fall back to opening fresh with a warning banner in the modal).
+ - Extend `onExport` signature so callers get the same `glbUrl` they do today — no breaking change.
3. **Frontend — dashboard**
- - Add an "Edit appearance" button on each avatar card in [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js).
- - Clicking it: `POST /api/avatars/:id/session` → open `AvatarCreator` with the returned sessionUrl and the current GLB URL → on export, run the upload flow from [api/avatars/presign.js](../../api/avatars/presign.js) + `POST /api/avatars` with `parent_avatar_id` set to the row being edited.
- - Show a small "version N of M" chip on the card, clickable to reveal the version list (from `GET /api/avatars/:id/versions`). Clicking a prior version calls `PATCH /api/agents/:agentId { avatar_id }` to revert.
+ - Add an "Edit appearance" button on each avatar card in [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js).
+ - Clicking it: `POST /api/avatars/:id/session` → open `AvatarCreator` with the returned sessionUrl and the current GLB URL → on export, run the upload flow from [api/avatars/presign.js](../../api/avatars/presign.js) + `POST /api/avatars` with `parent_avatar_id` set to the row being edited.
+ - Show a small "version N of M" chip on the card, clickable to reveal the version list (from `GET /api/avatars/:id/versions`). Clicking a prior version calls `PATCH /api/agents/:agentId { avatar_id }` to revert.
## Audit checklist
@@ -46,8 +48,8 @@ AgentId does not change. Wallet link does not change.
- No new runtime dependencies. Use the existing `@avaturn/sdk`.
- If Avaturn's SDK does not expose a "preload existing avatar" option in our pinned version, **do not upgrade** — document it and ship the button flow with a placeholder (fresh session) plus a `console.info` breadcrumb.
- Use the existing R2 presign flow from [api/avatars/presign.js](../../api/avatars/presign.js) + [api/avatars/index.js](../../api/avatars/index.js). Do not add a second upload path.
-- Use `sql` from [_lib/db.js](../../api/_lib/db.js) tagged templates — no ORM, no raw concat.
-- Use `getSessionUser` + `authenticateBearer` from [_lib/auth.js](../../api/_lib/auth.js) — same auth surface as [api/avatars/[id].js](../../api/avatars/[id].js).
+- Use `sql` from [\_lib/db.js](../../api/_lib/db.js) tagged templates — no ORM, no raw concat.
+- Use `getSessionUser` + `authenticateBearer` from [\_lib/auth.js](../../api/_lib/auth.js) — same auth surface as [api/avatars/[id].js](../../api/avatars/[id].js).
- Any version-switch write must go through `PATCH /api/agents/:agentId` or a dedicated endpoint — never update `agent_identities` from client-side JS directly.
## Verification
@@ -55,13 +57,13 @@ AgentId does not change. Wallet link does not change.
1. `node --check` every JS file you modified.
2. `npx vite build` — expect success (ignore the pre-existing `@avaturn/sdk` resolution warning).
3. Manual:
- - Sign in, create a selfie avatar.
- - Note `agent_identities.id` and `avatar_id` in the DB.
- - Click "Edit appearance", export from Avaturn.
- - Confirm `agent_identities.id` is unchanged.
- - Confirm `agent_identities.avatar_id` points at a new `avatars` row whose `parent_avatar_id` is the original.
- - Click "version 1" chip → restore → confirm `avatar_id` is back on the original.
- - Confirm the agent's action history (`agent_actions` rows) is untouched across the full flow.
+ - Sign in, create a selfie avatar.
+ - Note `agent_identities.id` and `avatar_id` in the DB.
+ - Click "Edit appearance", export from Avaturn.
+ - Confirm `agent_identities.id` is unchanged.
+ - Confirm `agent_identities.avatar_id` points at a new `avatars` row whose `parent_avatar_id` is the original.
+ - Click "version 1" chip → restore → confirm `avatar_id` is back on the original.
+ - Confirm the agent's action history (`agent_actions` rows) is untouched across the full flow.
4. Sign out, sign back in with a different user, call `GET /api/avatars/:id/session` on someone else's avatar → expect 404 (`not_found`), not 403 — mirror the pattern in [api/avatars/[id].js](../../api/avatars/[id].js).
## Scope boundaries — do NOT do these
diff --git a/prompts/avatar-edit/01-persona-editor.md b/prompts/avatar-edit/01-persona-editor.md
index 08078f709..0f33882c5 100644
--- a/prompts/avatar-edit/01-persona-editor.md
+++ b/prompts/avatar-edit/01-persona-editor.md
@@ -2,7 +2,7 @@
## Why
-The agent's *personality* lives in `agent_identities.meta.persona` — a blob the runtime prompt builder inlines into the LLM system prompt. Without a UI, users can't shape it. Without shaping, every agent sounds identical.
+The agent's _personality_ lives in `agent_identities.meta.persona` — a blob the runtime prompt builder inlines into the LLM system prompt. Without a UI, users can't shape it. Without shaping, every agent sounds identical.
## Read first
@@ -34,6 +34,7 @@ The agent's *personality* lives in `agent_identities.meta.persona` — a blob th
### 2. Server patch
`PATCH /api/agents/:id` (owner-auth):
+
- Accept a `persona` key.
- Validate with zod (exact limits above).
- Merge into `meta.persona` (don't replace siblings like `edits`).
@@ -43,23 +44,25 @@ The agent's *personality* lives in `agent_identities.meta.persona` — a blob th
### 3. `/agent/:id/edit` page
New route `public/agent-edit/index.html` + `public/agent-edit/edit.js`:
+
- Auth-gated; redirect to `/login?return=/agent/:id/edit` if anon.
- Owner-only; 403 for non-owners.
- Left column: live avatar preview (iframe of the viewer with `#agent=<id>`).
- Right column: form.
- - Name (text, required)
- - Bio (textarea, char count)
- - System prompt (textarea, monospace, char count, "Reset to template" button)
- - Catchphrases (repeating text input, ≤ 5)
- - Sentiment bias (slider, -1 → +1, labels: "stoic" / "effusive")
- - Voice provider (radio)
- - Voice (select populated by provider list — stub for now if ElevenLabs not wired)
- - Do-not-say (chip input)
+ - Name (text, required)
+ - Bio (textarea, char count)
+ - System prompt (textarea, monospace, char count, "Reset to template" button)
+ - Catchphrases (repeating text input, ≤ 5)
+ - Sentiment bias (slider, -1 → +1, labels: "stoic" / "effusive")
+ - Voice provider (radio)
+ - Voice (select populated by provider list — stub for now if ElevenLabs not wired)
+ - Do-not-say (chip input)
- Bottom: **Save** button. On save, `PATCH` → toast → reload iframe so the runtime picks up the new persona.
### 4. Runtime prompt assembly
In `src/runtime/providers.js`, when building the system prompt:
+
- Prepend `persona.systemPrompt` if present.
- Append `You are ${persona.name}. ${persona.bio}`.
- Append `Catchphrases you sometimes use: ${list}`.
@@ -69,6 +72,7 @@ In `src/runtime/providers.js`, when building the system prompt:
### 5. Template picker
Three starter templates the user can click to fill the form (they can then edit):
+
- **Friend** — casual, supportive, high celebration bias
- **Coach** — directive, concise, neutral bias
- **Researcher** — careful, inquisitive, high curiosity bias
diff --git a/prompts/avatar-edit/02-outfit-and-materials.md b/prompts/avatar-edit/02-outfit-and-materials.md
index 5d1909037..187c317ee 100644
--- a/prompts/avatar-edit/02-outfit-and-materials.md
+++ b/prompts/avatar-edit/02-outfit-and-materials.md
@@ -20,8 +20,8 @@ Users want to recolor the shirt, swap eye color, change skin tone. Doing this by
```json
{
- "Body": { "color": "#ffc8a0", "metalness": 0.1, "roughness": 0.8 },
- "Shirt": { "color": "#3b5eff", "emissive": "#000000" }
+ "Body": { "color": "#ffc8a0", "metalness": 0.1, "roughness": 0.8 },
+ "Shirt": { "color": "#3b5eff", "emissive": "#000000" }
}
```
@@ -30,12 +30,14 @@ Only listed fields override; everything else comes from the GLB.
### 2. `/agent/:id/edit` tab "Outfit"
A new tab alongside task 01's persona form. Layout:
+
- Left: live preview.
- Right: a list of every named mesh/material in the current GLB, each as a collapsible card with color + metalness + roughness + emissive controls.
### 3. Apply-on-load
In the viewer pipeline (probably a new `src/editor/apply-overrides.js`):
+
- Fires after model load.
- Reads `meta.edits.materials` from the agent record.
- Walks `traverseMaterials` and applies overrides by material name.
diff --git a/prompts/avatar-edit/02-replace-glb-upload.md b/prompts/avatar-edit/02-replace-glb-upload.md
index 29b1a76e1..d0ad26902 100644
--- a/prompts/avatar-edit/02-replace-glb-upload.md
+++ b/prompts/avatar-edit/02-replace-glb-upload.md
@@ -5,6 +5,7 @@
Repo: `/workspaces/3D`. Today the only path to set an avatar's bytes is through the Avaturn modal ([src/avatar-creator.js](../../src/avatar-creator.js)). Advanced users — people bringing their own rigged GLB, studio artists, or power users swapping to a custom model — have no way to upload directly.
The R2 upload primitives already exist:
+
- [api/avatars/presign.js](../../api/avatars/presign.js) returns a signed PUT URL given `{ content_type, size_bytes, slug? }`.
- [api/avatars/index.js](../../api/avatars/index.js) registers an uploaded object after the browser PUTs raw bytes. It verifies via `headObject()` that the object exists and size matches.
@@ -17,24 +18,26 @@ Ship a "Replace GLB" button on the dashboard avatar card. Clicking it opens a fi
## Deliverable
1. **Frontend — dashboard**
- - In [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js), add a "Replace GLB" action next to "Edit appearance" (from [01-edit-appearance-flow.md](./01-edit-appearance-flow.md)).
- - Use a hidden `<input type="file" accept=".glb,model/gltf-binary">`. Validate client-side:
- - Extension is `.glb`.
- - MIME type is `model/gltf-binary` or `application/octet-stream` (browsers sometimes send the latter).
- - File size ≤ the user's plan quota from `plan_quotas.max_bytes_per_avatar` (fetch once at dashboard mount via existing `/api/auth/me` or a new small endpoint if not surfaced).
- - On select: read first 4 bytes to verify the magic number `glTF` (`0x67 0x6c 0x54 0x46`). If the magic does not match, reject with an inline error — do not upload.
- - Call presign, PUT to the signed URL, then `POST /api/avatars` with `parent_avatar_id` = current avatar id, `source: 'direct-upload'`.
- - Surface an "this bypasses Avaturn — your avatar may not animate correctly if it's not rigged to the Mixamo skeleton" warning before upload. One-click confirm.
+
+ - In [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js), add a "Replace GLB" action next to "Edit appearance" (from [01-edit-appearance-flow.md](./01-edit-appearance-flow.md)).
+ - Use a hidden `<input type="file" accept=".glb,model/gltf-binary">`. Validate client-side:
+ - Extension is `.glb`.
+ - MIME type is `model/gltf-binary` or `application/octet-stream` (browsers sometimes send the latter).
+ - File size ≤ the user's plan quota from `plan_quotas.max_bytes_per_avatar` (fetch once at dashboard mount via existing `/api/auth/me` or a new small endpoint if not surfaced).
+ - On select: read first 4 bytes to verify the magic number `glTF` (`0x67 0x6c 0x54 0x46`). If the magic does not match, reject with an inline error — do not upload.
+ - Call presign, PUT to the signed URL, then `POST /api/avatars` with `parent_avatar_id` = current avatar id, `source: 'direct-upload'`.
+ - Surface an "this bypasses Avaturn — your avatar may not animate correctly if it's not rigged to the Mixamo skeleton" warning before upload. One-click confirm.
2. **Backend**
- - Extend the `createAvatarBody` schema in [_lib/validate.js](../../api/_lib/validate.js) to accept `source: 'direct-upload'` (existing values likely include `'avaturn'`, `'selfie'`, etc. — preserve them).
- - Confirm that [api/avatars/index.js](../../api/avatars/index.js)'s registration handler still calls `headObject()` + size check. No regression.
- - Add optional server-side sanity check on the registered GLB: read the first 12 bytes via a signed GET (or defer until first render). If you add it, keep it behind a feature flag so this task stays small. If skipping, note it in the report.
- - Ensure `agent_identities.avatar_id` update happens in the same SQL transaction as the `avatars` insert. Reuse the transactional helper from task 01 if that task shipped first; otherwise add it here.
+
+ - Extend the `createAvatarBody` schema in [\_lib/validate.js](../../api/_lib/validate.js) to accept `source: 'direct-upload'` (existing values likely include `'avaturn'`, `'selfie'`, etc. — preserve them).
+ - Confirm that [api/avatars/index.js](../../api/avatars/index.js)'s registration handler still calls `headObject()` + size check. No regression.
+ - Add optional server-side sanity check on the registered GLB: read the first 12 bytes via a signed GET (or defer until first render). If you add it, keep it behind a feature flag so this task stays small. If skipping, note it in the report.
+ - Ensure `agent_identities.avatar_id` update happens in the same SQL transaction as the `avatars` insert. Reuse the transactional helper from task 01 if that task shipped first; otherwise add it here.
3. **Compatibility check on the new GLB**
- - In [src/animation-manager.js](../../src/animation-manager.js), the `_buildBoneNameMap` already attempts retargeting. After a replace-GLB upload, trigger a client-side check: load the new GLB into the existing viewer, count bones, compute how many match the project's expected Mixamo-ish names. If under 50%, show a non-blocking warning: "Animations may not play — skeleton mismatch." Do not block the upload.
- - Do not modify `_buildBoneNameMap`. Re-use its logic read-only for the check, or call it directly.
+ - In [src/animation-manager.js](../../src/animation-manager.js), the `_buildBoneNameMap` already attempts retargeting. After a replace-GLB upload, trigger a client-side check: load the new GLB into the existing viewer, count bones, compute how many match the project's expected Mixamo-ish names. If under 50%, show a non-blocking warning: "Animations may not play — skeleton mismatch." Do not block the upload.
+ - Do not modify `_buildBoneNameMap`. Re-use its logic read-only for the check, or call it directly.
## Audit checklist
@@ -52,7 +55,7 @@ Ship a "Replace GLB" button on the dashboard avatar card. Clicking it opens a fi
## Constraints
- No new runtime dependencies. No GLB parser library — magic number byte check is enough client-side.
-- No changes to R2 bucket config, CORS, or presign helpers in [_lib/r2.js](../../api/_lib/r2.js).
+- No changes to R2 bucket config, CORS, or presign helpers in [\_lib/r2.js](../../api/_lib/r2.js).
- Do not add a "drop zone" with drag-and-drop unless it's trivially cheap — the file picker is the minimum viable target.
- No server-side GLB validation beyond magic-number / header in this task. Mesh-level validation exists separately in [src/validator.js](../../src/validator.js) and MCP `validate_model` — do not wire those in here.
- Dashboard stays native-DOM — no framework.
@@ -62,13 +65,13 @@ Ship a "Replace GLB" button on the dashboard avatar card. Clicking it opens a fi
1. `node --check` every modified JS file.
2. `npx vite build`.
3. Manual:
- - Sign in, have an existing avatar.
- - Click "Replace GLB", pick a valid Mixamo-rigged `.glb` (find one under `public/models/` or re-export from Blender). Confirm upload succeeds, `agent_identities.avatar_id` points at the new row, `agentId` unchanged.
- - Try uploading a `.txt` renamed to `.glb` — client-side magic-number check rejects it.
- - Try uploading an oversize file — quota rejects it.
- - Try uploading a non-Mixamo rigged GLB — confirm the "skeleton mismatch" warning surfaces.
- - Revert to the prior version via the version chip (from task 01) — confirm it works.
- - Sign in as user B, try to POST to `/api/avatars` with `parent_avatar_id` pointing at user A's avatar — expect 404 `not_found`.
+ - Sign in, have an existing avatar.
+ - Click "Replace GLB", pick a valid Mixamo-rigged `.glb` (find one under `public/models/` or re-export from Blender). Confirm upload succeeds, `agent_identities.avatar_id` points at the new row, `agentId` unchanged.
+ - Try uploading a `.txt` renamed to `.glb` — client-side magic-number check rejects it.
+ - Try uploading an oversize file — quota rejects it.
+ - Try uploading a non-Mixamo rigged GLB — confirm the "skeleton mismatch" warning surfaces.
+ - Revert to the prior version via the version chip (from task 01) — confirm it works.
+ - Sign in as user B, try to POST to `/api/avatars` with `parent_avatar_id` pointing at user A's avatar — expect 404 `not_found`.
## Scope boundaries — do NOT do these
diff --git a/prompts/avatar-edit/03-animation-vocabulary.md b/prompts/avatar-edit/03-animation-vocabulary.md
index bc9516964..e58b6c1e6 100644
--- a/prompts/avatar-edit/03-animation-vocabulary.md
+++ b/prompts/avatar-edit/03-animation-vocabulary.md
@@ -50,6 +50,7 @@ Missing slots fall back to a default map defined in code.
In `src/runtime/tools.js`, when a tool says `play_clip('wave')`, look up the agent's mapping and pass the actual clip name to `viewer.animationManager.play(clipName)`.
In `src/agent-avatar.js`, the Empathy Layer already fires one-shot gestures on high emotion events. Route those through the same mapping:
+
- celebration > 0.6 → `play('celebrate')`
- concern > 0.6 → `play('concern')`
- curiosity > 0.6 + idle → small `play('think')`
diff --git a/prompts/avatar-edit/03-edit-identity-metadata.md b/prompts/avatar-edit/03-edit-identity-metadata.md
index 414391f3b..4c93531b2 100644
--- a/prompts/avatar-edit/03-edit-identity-metadata.md
+++ b/prompts/avatar-edit/03-edit-identity-metadata.md
@@ -11,6 +11,7 @@ Service endpoints are consumed by [src/manifest.js](../../src/manifest.js) which
## Goal
Add an "Identity" edit panel to the dashboard. The user can change:
+
- **name** (required, 1–120 chars, validated for uniqueness per user)
- **description** / bio (optional, ≤ 2000 chars)
- **skills** (multi-select from the registry; read the built-in skill names from [src/agent-skills.js](../../src/agent-skills.js))
@@ -21,31 +22,33 @@ Changes autosave after a 600 ms debounce. The agent's id, avatar link, wallet li
## Deliverable
1. **Backend**
- - Ensure `PUT /api/agents/:id` (the endpoint `src/agent-identity.js` already calls via `save()`) accepts `name`, `description`, `skills`, `meta`. If the endpoint does not yet exist or doesn't accept all four, add/extend it under `api/agents/[id].js`. Validate with a new zod schema in [_lib/validate.js](../../api/_lib/validate.js).
- - Enforce name uniqueness per `user_id`: a `UNIQUE (user_id, lower(name)) WHERE deleted_at is null` partial index. If adding the index, include the migration SQL in the reporting section.
- - On conflict return 409 `conflict` with `{ error_description: 'name already in use' }`.
- - Validate each service endpoint:
- - `name`: non-empty, ≤ 60 chars.
- - `url`: must parse via `new URL()`; scheme must be one of `https`, `http` (localhost only), `ipfs`, `ar`.
- - `protocol`: enum of `mcp`, `a2a`, `http`, `websocket`.
- - Cap service endpoints at 10 per agent. Dedupe by `name` (case-insensitive).
+
+ - Ensure `PUT /api/agents/:id` (the endpoint `src/agent-identity.js` already calls via `save()`) accepts `name`, `description`, `skills`, `meta`. If the endpoint does not yet exist or doesn't accept all four, add/extend it under `api/agents/[id].js`. Validate with a new zod schema in [\_lib/validate.js](../../api/_lib/validate.js).
+ - Enforce name uniqueness per `user_id`: a `UNIQUE (user_id, lower(name)) WHERE deleted_at is null` partial index. If adding the index, include the migration SQL in the reporting section.
+ - On conflict return 409 `conflict` with `{ error_description: 'name already in use' }`.
+ - Validate each service endpoint:
+ - `name`: non-empty, ≤ 60 chars.
+ - `url`: must parse via `new URL()`; scheme must be one of `https`, `http` (localhost only), `ipfs`, `ar`.
+ - `protocol`: enum of `mcp`, `a2a`, `http`, `websocket`.
+ - Cap service endpoints at 10 per agent. Dedupe by `name` (case-insensitive).
2. **Frontend — dashboard identity panel**
- - New route: `#edit/<agentId>/identity` routed from the existing hash-router in [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js) (the router already splits `#edit/<id>` in `navigate()`).
- - Form fields (native DOM):
- - `<input>` for name — inline uniqueness-check on blur (GET a new tiny endpoint `GET /api/agents/check-name?name=...` that returns `{ available: boolean }`; scoped to the caller's user_id).
- - `<textarea>` for description.
- - Multi-select for skills — checkbox list populated from [src/agent-skills.js](../../src/agent-skills.js)'s built-in list. Do not hard-code the list in the dashboard file; import or fetch it.
- - Service endpoints: repeater with add / remove rows, each row having name + url + protocol (select).
- - Debounced autosave: 600 ms after the last input event. Send a `PATCH /api/agents/:id` (or `PUT`, matching whatever [src/agent-identity.js](../../src/agent-identity.js) already uses — keep one verb).
- - Show a subtle "Saved" indicator near the form (checkmark fades after 1.5 s) and "Saving…" while inflight.
- - Show inline validation errors next to the offending field. Do not block typing.
+
+ - New route: `#edit/<agentId>/identity` routed from the existing hash-router in [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js) (the router already splits `#edit/<id>` in `navigate()`).
+ - Form fields (native DOM):
+ - `<input>` for name — inline uniqueness-check on blur (GET a new tiny endpoint `GET /api/agents/check-name?name=...` that returns `{ available: boolean }`; scoped to the caller's user_id).
+ - `<textarea>` for description.
+ - Multi-select for skills — checkbox list populated from [src/agent-skills.js](../../src/agent-skills.js)'s built-in list. Do not hard-code the list in the dashboard file; import or fetch it.
+ - Service endpoints: repeater with add / remove rows, each row having name + url + protocol (select).
+ - Debounced autosave: 600 ms after the last input event. Send a `PATCH /api/agents/:id` (or `PUT`, matching whatever [src/agent-identity.js](../../src/agent-identity.js) already uses — keep one verb).
+ - Show a subtle "Saved" indicator near the form (checkmark fades after 1.5 s) and "Saving…" while inflight.
+ - Show inline validation errors next to the offending field. Do not block typing.
3. **Client-side integration**
- - Extend [src/agent-identity.js](../../src/agent-identity.js) so `update(patch)` correctly maps `serviceEndpoints` to `meta.service_endpoints` in the outgoing body. Today the method Object.assigns over `_record`; verify that camelCase → snake_case is respected by the backend (see `_normalise` in that file).
- - If the user is currently viewing their own agent via `<agent-3d>`, the element should pick up name/description changes live. Two options — pick one and document:
- - Soft: next load re-fetches. Acceptable.
- - Live: emit a `protocol.emit('identity-updated', { record })` event and have `agent-home.js` re-render. Only do this if trivially cheap.
+ - Extend [src/agent-identity.js](../../src/agent-identity.js) so `update(patch)` correctly maps `serviceEndpoints` to `meta.service_endpoints` in the outgoing body. Today the method Object.assigns over `_record`; verify that camelCase → snake_case is respected by the backend (see `_normalise` in that file).
+ - If the user is currently viewing their own agent via `<agent-3d>`, the element should pick up name/description changes live. Two options — pick one and document:
+ - Soft: next load re-fetches. Acceptable.
+ - Live: emit a `protocol.emit('identity-updated', { record })` event and have `agent-home.js` re-render. Only do this if trivially cheap.
## Audit checklist
@@ -73,14 +76,14 @@ Changes autosave after a 600 ms debounce. The agent's id, avatar link, wallet li
1. `node --check` every modified JS file.
2. `npx vite build`.
3. Manual:
- - Sign in, open `#edit/<agentId>/identity`.
- - Edit name → after 600 ms the "Saving…" indicator flips to "Saved". Reload — value persists.
- - Try to rename to another of your agents' names — inline 409 error.
- - Add a service endpoint with scheme `ftp://…` — rejected.
- - Toggle a skill on/off — round-trips cleanly.
- - Confirm `agent_identities.id` is unchanged before/after.
- - Confirm wallet link is unchanged.
- - Confirm ERC-8004 warning shows when `isRegistered` is true.
+ - Sign in, open `#edit/<agentId>/identity`.
+ - Edit name → after 600 ms the "Saving…" indicator flips to "Saved". Reload — value persists.
+ - Try to rename to another of your agents' names — inline 409 error.
+ - Add a service endpoint with scheme `ftp://…` — rejected.
+ - Toggle a skill on/off — round-trips cleanly.
+ - Confirm `agent_identities.id` is unchanged before/after.
+ - Confirm wallet link is unchanged.
+ - Confirm ERC-8004 warning shows when `isRegistered` is true.
4. As a second user, attempt `PATCH /api/agents/<other user's agentId>` — expect 404 `not_found`.
5. Hit `check-name` 50 times rapidly — rate limit holds.
diff --git a/prompts/avatar-edit/04-animation-library.md b/prompts/avatar-edit/04-animation-library.md
index 208791c05..8467bdfdd 100644
--- a/prompts/avatar-edit/04-animation-library.md
+++ b/prompts/avatar-edit/04-animation-library.md
@@ -9,6 +9,7 @@ Repo: `/workspaces/3D`. Animation handling is centralized in [src/animation-mana
- `loadAll()` for batch load, `play(name)`, `crossfadeTo(name, duration)`, `getLoadedNames()`
What is missing:
+
1. A **persistent** list of which clips belong to an avatar — today `defs` are set per-session in code.
2. A dashboard UI to add/remove clips.
3. A preview mechanism where the dashboard can load the avatar + a candidate clip without touching the live `<agent-3d>` instance.
@@ -22,29 +23,32 @@ Ship an animation-library panel in the dashboard that lists clips attached to th
## Deliverable
1. **Backend**
- - No new endpoints if `PATCH /api/agents/:id` already accepts `meta` (it does, per [src/agent-identity.js](../../src/agent-identity.js)'s `save()` which posts `meta`). Confirm and document.
- - Validate `meta.animations` server-side — add to the agents-patch zod schema:
- - Array, max 30 entries.
- - Each entry: `name` (1–60 chars), `url` (valid URL, `http`/`https`/`ipfs`/`ar`), `loop` (boolean, default true), `clipName` (optional, ≤ 120 chars), `source` (enum).
- - Dedupe by `name` case-insensitively.
- - Optional: add `POST /api/animations/presign` delegating to the same R2 flow if users upload custom `.glb` clips. Scope key under `u/{userId}/animations/{slug}.glb`. Use `limits.upload(userId)`. If this endpoint already exists under a different name (e.g. generic R2 presign), reuse it — do not duplicate.
+
+ - No new endpoints if `PATCH /api/agents/:id` already accepts `meta` (it does, per [src/agent-identity.js](../../src/agent-identity.js)'s `save()` which posts `meta`). Confirm and document.
+ - Validate `meta.animations` server-side — add to the agents-patch zod schema:
+ - Array, max 30 entries.
+ - Each entry: `name` (1–60 chars), `url` (valid URL, `http`/`https`/`ipfs`/`ar`), `loop` (boolean, default true), `clipName` (optional, ≤ 120 chars), `source` (enum).
+ - Dedupe by `name` case-insensitively.
+ - Optional: add `POST /api/animations/presign` delegating to the same R2 flow if users upload custom `.glb` clips. Scope key under `u/{userId}/animations/{slug}.glb`. Use `limits.upload(userId)`. If this endpoint already exists under a different name (e.g. generic R2 presign), reuse it — do not duplicate.
2. **Preset pack**
- - Ship a small curated list in a new JSON file `public/animations/presets.json` with 6–10 entries (idle, wave, nod, shrug, thinking, celebrate, typing, walking). URLs point to `.glb` files in `public/animations/`. Do **not** add the `.glb` binary files in this task — assume they're pre-existing or will be added by a separate content task. Document missing files in the reporting section.
- - Loader in the dashboard fetches `presets.json` and renders each as a one-click "add" tile.
+
+ - Ship a small curated list in a new JSON file `public/animations/presets.json` with 6–10 entries (idle, wave, nod, shrug, thinking, celebrate, typing, walking). URLs point to `.glb` files in `public/animations/`. Do **not** add the `.glb` binary files in this task — assume they're pre-existing or will be added by a separate content task. Document missing files in the reporting section.
+ - Loader in the dashboard fetches `presets.json` and renders each as a one-click "add" tile.
3. **Frontend — dashboard animation panel**
- - New route: `#edit/<agentId>/animations` in [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js).
- - Two columns:
- - Left: current clips (from the agent's `meta.animations`). Each row has name, source, loop toggle, preview button, detach button.
- - Right: add-new area — preset tiles + "upload custom `.glb`" button.
- - Preview: mount an isolated `<agent-3d>` (or a dedicated Viewer instance) in a small modal, load the avatar's current GLB, attach the candidate clip via `AnimationManager`, and play it. Crossfade back to idle when the modal closes.
- - Must not reuse the main app's viewer — create a scoped one so preview playback doesn't disturb a live session in another tab. Use the existing `<agent-3d>` web component with an `animations` attribute if it supports per-instance clip override; otherwise instantiate `Viewer` + `AnimationManager` directly.
- - Attach: updates local state, calls `PATCH /api/agents/:id` with the new `meta.animations` set. Debounce 500 ms so rapid toggles don't spam.
- - Detach: removes from the list; same PATCH.
+
+ - New route: `#edit/<agentId>/animations` in [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js).
+ - Two columns:
+ - Left: current clips (from the agent's `meta.animations`). Each row has name, source, loop toggle, preview button, detach button.
+ - Right: add-new area — preset tiles + "upload custom `.glb`" button.
+ - Preview: mount an isolated `<agent-3d>` (or a dedicated Viewer instance) in a small modal, load the avatar's current GLB, attach the candidate clip via `AnimationManager`, and play it. Crossfade back to idle when the modal closes.
+ - Must not reuse the main app's viewer — create a scoped one so preview playback doesn't disturb a live session in another tab. Use the existing `<agent-3d>` web component with an `animations` attribute if it supports per-instance clip override; otherwise instantiate `Viewer` + `AnimationManager` directly.
+ - Attach: updates local state, calls `PATCH /api/agents/:id` with the new `meta.animations` set. Debounce 500 ms so rapid toggles don't spam.
+ - Detach: removes from the list; same PATCH.
4. **Client runtime integration**
- - When `<agent-3d>` boots (see [src/element.js](../../src/element.js)), after loading the GLB it should hydrate animations from `agent_identities.meta.animations` by calling `AnimationManager.setAnimationDefs()` + `loadAll()` already. Verify this path. If not wired, add it. Do not change its API.
+ - When `<agent-3d>` boots (see [src/element.js](../../src/element.js)), after loading the GLB it should hydrate animations from `agent_identities.meta.animations` by calling `AnimationManager.setAnimationDefs()` + `loadAll()` already. Verify this path. If not wired, add it. Do not change its API.
## IPFS / on-chain re-pinning
@@ -77,13 +81,13 @@ Ship an animation-library panel in the dashboard that lists clips attached to th
1. `node --check` every modified JS file.
2. `npx vite build`.
3. Manual:
- - Open dashboard → avatar card → "Animations".
- - Attach `wave` from presets. Confirm `agent_identities.meta.animations` has an entry. Confirm the preview modal plays the clip.
- - Detach. Confirm the entry is gone and R2 object is untouched.
- - Upload a custom `.glb` animation. Confirm it lands under `u/{userId}/animations/...`.
- - Attempt to attach two clips named `wave` — second fails with inline error.
- - Reload the main app / `<agent-3d>` → confirm `getAnimationDefs()` returns the hydrated list.
- - With an agent where `isRegistered` is true, confirm the re-pin warning shows.
+ - Open dashboard → avatar card → "Animations".
+ - Attach `wave` from presets. Confirm `agent_identities.meta.animations` has an entry. Confirm the preview modal plays the clip.
+ - Detach. Confirm the entry is gone and R2 object is untouched.
+ - Upload a custom `.glb` animation. Confirm it lands under `u/{userId}/animations/...`.
+ - Attempt to attach two clips named `wave` — second fails with inline error.
+ - Reload the main app / `<agent-3d>` → confirm `getAnimationDefs()` returns the hydrated list.
+ - With an agent where `isRegistered` is true, confirm the re-pin warning shows.
4. Confirm agentId + wallet fields unchanged in the DB.
5. Close the preview modal mid-playback → confirm no AnimationMixer errors in the console, RAF cancelled.
diff --git a/prompts/avatar-edit/04-voice-picker.md b/prompts/avatar-edit/04-voice-picker.md
index 82991ac0a..7f89e5b34 100644
--- a/prompts/avatar-edit/04-voice-picker.md
+++ b/prompts/avatar-edit/04-voice-picker.md
@@ -41,6 +41,7 @@ From task 01: `persona.voiceProvider` (`web` | `eleven`), `persona.voiceId`.
### 5. Runtime hook
`src/runtime/speech.js#speak(text)`:
+
- Read `identity.persona.voiceProvider + voiceId`.
- If `web`, synthesize locally.
- If `eleven`, call `/api/tts/eleven`.
diff --git a/prompts/avatar-edit/05-outfits-and-accessories.md b/prompts/avatar-edit/05-outfits-and-accessories.md
index d467d06bc..edd009034 100644
--- a/prompts/avatar-edit/05-outfits-and-accessories.md
+++ b/prompts/avatar-edit/05-outfits-and-accessories.md
@@ -5,12 +5,14 @@
Repo: `/workspaces/3D`. The Avaturn export already includes outfit topology and some morph targets. What's missing is a lightweight way for the user to iterate — try a hat, glasses, swap between 2–3 outfits — **without re-entering Avaturn** and **without branching a new GLB per combination**.
Principle: **stay in the same GLB.** The avatar file on R2 is canonical. Accessories and outfit variants are applied at runtime via:
+
- **Morph targets** the GLB already exposes (e.g. outfit color/pattern blend shapes Avaturn ships with).
- **Bone-attached overlays** for accessories (hat, glasses, earrings) — small `.glb` snippets loaded and parented to head/hand bones at runtime.
The current outfit/morph state lives in `agent_identities.meta.appearance = { outfit: 'preset-id', accessories: ['hat-01', 'glasses-02'], morphs: { ... } }`. Consumed at boot by [src/element.js](../../src/element.js) → [src/runtime/scene.js](../../src/runtime/scene.js).
Relevant existing code to reuse (do not fork):
+
- [src/editor/material-editor.js](../../src/editor/material-editor.js) — exposes material tweaks per mesh.
- [src/editor/scene-explorer.js](../../src/editor/scene-explorer.js) — enumerates the scene graph (useful for finding head/hand bones).
- [src/agent-avatar.js](../../src/agent-avatar.js) — already iterates morph targets every frame for emotion blend. The outfit morph application runs alongside its loop; do not fight it.
@@ -22,38 +24,41 @@ Ship a small preset pack of outfits and accessories, plus a dashboard panel to a
## Deliverable
1. **Preset pack**
- - New directory `public/accessories/` with:
- - `presets.json` listing `{ id, kind: 'hat'|'glasses'|'outfit'|'earrings', name, glbUrl?, morphBinding?, attachBone?, thumbnail }`.
- - 6–10 entries total (2–3 outfits, 2–3 hats, 2 glasses).
- - For outfit presets that rely on morph targets exposed by Avaturn, specify `morphBinding: { 'Outfit.Variant': 1.0 }` instead of a `glbUrl`. For accessory presets, specify `glbUrl` + `attachBone` (e.g. `'Head'`, `'LeftHand'`).
- - Do **not** add the actual `.glb` / thumbnail binaries in this task — assume a separate content pass. Note missing files in the reporting section.
+
+ - New directory `public/accessories/` with:
+ - `presets.json` listing `{ id, kind: 'hat'|'glasses'|'outfit'|'earrings', name, glbUrl?, morphBinding?, attachBone?, thumbnail }`.
+ - 6–10 entries total (2–3 outfits, 2–3 hats, 2 glasses).
+ - For outfit presets that rely on morph targets exposed by Avaturn, specify `morphBinding: { 'Outfit.Variant': 1.0 }` instead of a `glbUrl`. For accessory presets, specify `glbUrl` + `attachBone` (e.g. `'Head'`, `'LeftHand'`).
+ - Do **not** add the actual `.glb` / thumbnail binaries in this task — assume a separate content pass. Note missing files in the reporting section.
2. **Runtime — new module**
- - New file `src/agent-accessories.js`:
- - `class AccessoryManager { constructor(viewer) }`
- - `async applyPreset(preset)` — if `glbUrl`, loads via the same `GLTFLoader` path as the animation manager, parents the root under the named bone, caches the loaded scene. If `morphBinding`, sets morph influences on the matching mesh's `morphTargetDictionary`.
- - `removePreset(id)` — removes the attached object (disposes geometry/material/texture) or zeroes the morph.
- - `list()` — returns currently applied preset ids.
- - `hydrateFromAppearance(appearance)` — applies all presets from `meta.appearance` on boot.
- - Cleanup: when the underlying model is replaced (task 01 / 02 path), `AccessoryManager` must re-hydrate on the new model. Listen on the viewer or wire an explicit `onModelReplaced(newModel)` method.
- - Wire it from [src/element.js](../../src/element.js) or [src/runtime/scene.js](../../src/runtime/scene.js) so a boot with `appearance` applies automatically.
+
+ - New file `src/agent-accessories.js`:
+ - `class AccessoryManager { constructor(viewer) }`
+ - `async applyPreset(preset)` — if `glbUrl`, loads via the same `GLTFLoader` path as the animation manager, parents the root under the named bone, caches the loaded scene. If `morphBinding`, sets morph influences on the matching mesh's `morphTargetDictionary`.
+ - `removePreset(id)` — removes the attached object (disposes geometry/material/texture) or zeroes the morph.
+ - `list()` — returns currently applied preset ids.
+ - `hydrateFromAppearance(appearance)` — applies all presets from `meta.appearance` on boot.
+ - Cleanup: when the underlying model is replaced (task 01 / 02 path), `AccessoryManager` must re-hydrate on the new model. Listen on the viewer or wire an explicit `onModelReplaced(newModel)` method.
+ - Wire it from [src/element.js](../../src/element.js) or [src/runtime/scene.js](../../src/runtime/scene.js) so a boot with `appearance` applies automatically.
3. **Dashboard — outfits panel**
- - New route: `#edit/<agentId>/outfits` in [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js).
- - Tabbed grid: Outfits | Hats | Glasses | Earrings. Each tab renders a thumbnail grid from `public/accessories/presets.json`.
- - Clicking a preset toggles it in a small live preview viewer (isolated, same pattern as [04-animation-library.md](./04-animation-library.md)). Confirm / apply → `PATCH /api/agents/:id` with updated `meta.appearance`.
- - "Remove" button per category.
- - Conflict rules: only one outfit at a time, only one hat at a time, only one pair of glasses at a time. Multiple earrings allowed.
+
+ - New route: `#edit/<agentId>/outfits` in [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js).
+ - Tabbed grid: Outfits | Hats | Glasses | Earrings. Each tab renders a thumbnail grid from `public/accessories/presets.json`.
+ - Clicking a preset toggles it in a small live preview viewer (isolated, same pattern as [04-animation-library.md](./04-animation-library.md)). Confirm / apply → `PATCH /api/agents/:id` with updated `meta.appearance`.
+ - "Remove" button per category.
+ - Conflict rules: only one outfit at a time, only one hat at a time, only one pair of glasses at a time. Multiple earrings allowed.
4. **Backend validation**
- - Extend the agents-patch zod schema to validate `meta.appearance`:
- - `outfit`: string (preset id) | null.
- - `accessories`: array of strings (preset ids), max 8.
- - `morphs`: `Record<string, number>` with values clamped 0..1, max 32 keys.
- - Reject preset ids that don't exist in a server-side allowlist. Options:
- - Ship the allowlist as a `public/accessories/presets.json` read at build time (baked into a small `api/_lib/accessories.js` module), OR
- - Fetch and cache it on cold start.
- - Pick the simpler path and document the choice.
+ - Extend the agents-patch zod schema to validate `meta.appearance`:
+ - `outfit`: string (preset id) | null.
+ - `accessories`: array of strings (preset ids), max 8.
+ - `morphs`: `Record<string, number>` with values clamped 0..1, max 32 keys.
+ - Reject preset ids that don't exist in a server-side allowlist. Options:
+ - Ship the allowlist as a `public/accessories/presets.json` read at build time (baked into a small `api/_lib/accessories.js` module), OR
+ - Fetch and cache it on cold start.
+ - Pick the simpler path and document the choice.
## Important: stay in the same GLB
@@ -87,15 +92,15 @@ Ship a small preset pack of outfits and accessories, plus a dashboard panel to a
1. `node --check` every modified JS file.
2. `npx vite build`.
3. Manual:
- - Open `#edit/<agentId>/outfits`.
- - Apply a hat → dashboard preview shows it parented to the head bone. PATCH persists `meta.appearance.accessories` with the hat id.
- - Apply an outfit preset bound to a morph target → morph influence is set. Persisted.
- - Reload main app with `<agent-3d agent-id="...">` — the same hat + outfit re-apply on boot.
- - Remove the hat → disposed, gone from the record.
- - Apply a second hat → replaces the first (not additive).
- - Apply earrings → two accessories allowed.
- - Confirm emotion blend still animates (smile when greeted) — outfit morphs do not freeze the face.
- - Replace the avatar GLB (task 02 flow). Confirm accessories either re-hydrate on the new skeleton or surface a clear warning.
+ - Open `#edit/<agentId>/outfits`.
+ - Apply a hat → dashboard preview shows it parented to the head bone. PATCH persists `meta.appearance.accessories` with the hat id.
+ - Apply an outfit preset bound to a morph target → morph influence is set. Persisted.
+ - Reload main app with `<agent-3d agent-id="...">` — the same hat + outfit re-apply on boot.
+ - Remove the hat → disposed, gone from the record.
+ - Apply a second hat → replaces the first (not additive).
+ - Apply earrings → two accessories allowed.
+ - Confirm emotion blend still animates (smile when greeted) — outfit morphs do not freeze the face.
+ - Replace the avatar GLB (task 02 flow). Confirm accessories either re-hydrate on the new skeleton or surface a clear warning.
4. Try PATCHing `meta.appearance.outfit = 'not-a-preset'` — expect 400.
5. Confirm `agent_identities.id` unchanged across all these operations.
diff --git a/prompts/avatar-edit/05-reroll-selfie.md b/prompts/avatar-edit/05-reroll-selfie.md
index ecc6e4048..49d9db761 100644
--- a/prompts/avatar-edit/05-reroll-selfie.md
+++ b/prompts/avatar-edit/05-reroll-selfie.md
@@ -25,8 +25,8 @@ Currently one-to-one. Add `avatar_history` (JSONB array on `agent_identities.met
```json
[
- { "avatarId": "avt_old", "createdAt": "…", "replacedAt": "…" },
- { "avatarId": "avt_new", "createdAt": "…" }
+ { "avatarId": "avt_old", "createdAt": "…", "replacedAt": "…" },
+ { "avatarId": "avt_new", "createdAt": "…" }
]
```
@@ -43,6 +43,7 @@ On reroll, the current `avatar_id` row is pushed to history (with `replacedAt`)
### 3. Server endpoint
`POST /api/agents/:id/avatar` (owner-auth):
+
- Body: `{ avatarId }` (must be owned by the user).
- Verifies caller owns both the agent and the avatar.
- Swaps `agent_identities.avatar_id`, appends to history.
@@ -52,6 +53,7 @@ On reroll, the current `avatar_id` row is pushed to history (with `replacedAt`)
### 4. On-chain consideration
If `agent.chain_id` is set, the on-chain `agentURI` still points to the old IPFS CID. Swap flow:
+
- Warn: "This agent is on-chain. The public record still shows your previous avatar until you re-register."
- Offer "Update on-chain" button — pins the new GLB (task onchain/02), pins a new metadata JSON, calls `IdentityRegistry.update(agentId, newURI)`.
- If the user skips, new avatar is local-only.
diff --git a/prompts/avatar-edit/06-accessories.md b/prompts/avatar-edit/06-accessories.md
index a412ac55f..e82a1f689 100644
--- a/prompts/avatar-edit/06-accessories.md
+++ b/prompts/avatar-edit/06-accessories.md
@@ -33,6 +33,7 @@ Each GLB is a single root-anchored mesh. No animations, no skeleton. Local-origi
### 2. Manifest
`public/accessories/index.json`:
+
```json
{
"hats": [ { "id": "baseball-cap", "name": "Cap", "uri": "./hats/baseball-cap.glb", "anchor": "head" } , … ],
@@ -44,6 +45,7 @@ Each GLB is a single root-anchored mesh. No animations, no skeleton. Local-origi
### 3. Anchor resolution
In a new `src/editor/accessories.js`:
+
```js
export function attachAccessory(agentContent, accessory) {
// find bone by anchor name (try: HeadTop_End, Head, Neck, Spine2, Spine1, Spine)
@@ -52,12 +54,15 @@ export function attachAccessory(agentContent, accessory) {
// apply offset + rotation from the accessory manifest
// return a handle so detach works
}
-export function detachAccessory(handle) { /* remove from parent, dispose */ }
+export function detachAccessory(handle) {
+ /* remove from parent, dispose */
+}
```
### 4. Patch shape
`agent_identities.meta.edits.accessories`:
+
```json
{ "hats": "baseball-cap", "glasses": null, "backpacks": "adventurer" }
```
diff --git a/prompts/avatar-edit/README.md b/prompts/avatar-edit/README.md
index 3297a143f..768f76a27 100644
--- a/prompts/avatar-edit/README.md
+++ b/prompts/avatar-edit/README.md
@@ -20,13 +20,13 @@ If a task would orphan or duplicate the agentId, stop and report. This is the wh
## Tasks
-| # | File | Ships |
-|---|---|---|
-| 01 | [01-edit-appearance-flow.md](./01-edit-appearance-flow.md) | Re-enter Avaturn with current avatar loaded → save diff as new GLB version, keep prior as history |
-| 02 | [02-replace-glb-upload.md](./02-replace-glb-upload.md) | Direct GLB upload replaces avatar bytes without going through Avaturn |
-| 03 | [03-edit-identity-metadata.md](./03-edit-identity-metadata.md) | Edit name / bio / skills / service endpoints with debounced autosave + uniqueness checks |
-| 04 | [04-animation-library.md](./04-animation-library.md) | List / attach / detach animation clips on an avatar, preview in dashboard |
-| 05 | [05-outfits-and-accessories.md](./05-outfits-and-accessories.md) | Preset pack (hats, glasses, 2-3 outfits) swapped via morph / bone overlays in the same GLB |
+| # | File | Ships |
+| --- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
+| 01 | [01-edit-appearance-flow.md](./01-edit-appearance-flow.md) | Re-enter Avaturn with current avatar loaded → save diff as new GLB version, keep prior as history |
+| 02 | [02-replace-glb-upload.md](./02-replace-glb-upload.md) | Direct GLB upload replaces avatar bytes without going through Avaturn |
+| 03 | [03-edit-identity-metadata.md](./03-edit-identity-metadata.md) | Edit name / bio / skills / service endpoints with debounced autosave + uniqueness checks |
+| 04 | [04-animation-library.md](./04-animation-library.md) | List / attach / detach animation clips on an avatar, preview in dashboard |
+| 05 | [05-outfits-and-accessories.md](./05-outfits-and-accessories.md) | Preset pack (hats, glasses, 2-3 outfits) swapped via morph / bone overlays in the same GLB |
## Sequencing
diff --git a/prompts/avatar-editing/00-README.md b/prompts/avatar-editing/00-README.md
index b166ab393..ca6153ebc 100644
--- a/prompts/avatar-editing/00-README.md
+++ b/prompts/avatar-editing/00-README.md
@@ -19,12 +19,12 @@ An owner opens `/agent/:slug/edit` (or the equivalent panel) on an avatar they a
## Prompts in this band
-| # | File | Depends on |
-|---|---|---|
-| 01 | [save-edits-to-server.md](./01-save-edits-to-server.md) | — |
-| 02 | [regenerate-from-photo.md](./02-regenerate-from-photo.md) | band 2 done |
-| 03 | [outfit-variants.md](./03-outfit-variants.md) | 01 |
-| 04 | [version-history.md](./04-version-history.md) | 01 |
+| # | File | Depends on |
+| --- | --------------------------------------------------------- | ----------- |
+| 01 | [save-edits-to-server.md](./01-save-edits-to-server.md) | — |
+| 02 | [regenerate-from-photo.md](./02-regenerate-from-photo.md) | band 2 done |
+| 03 | [outfit-variants.md](./03-outfit-variants.md) | 01 |
+| 04 | [version-history.md](./04-version-history.md) | 01 |
## Done = merged when
diff --git a/prompts/avatar-editing/01-save-edits-to-server.md b/prompts/avatar-editing/01-save-edits-to-server.md
index d0de95aef..b089885dd 100644
--- a/prompts/avatar-editing/01-save-edits-to-server.md
+++ b/prompts/avatar-editing/01-save-edits-to-server.md
@@ -20,6 +20,7 @@ Do not change the editor's in-memory state management or the scene explorer.
Placement: immediately under the existing "download GLB (N)" button in the editor GUI. Label: `💾 save to my account (N)` where N is the pending-edit count. Disabled when N=0 or user is not the owner.
Click behavior:
+
1. Export GLB via existing `glb-export.js`.
2. Call `saveEdits({ agentId, glbBytes })` from `save-edits.js`.
3. Show inline toast: `"Saving…"` → `"Saved ✓"` or `"Save failed"` with retry.
@@ -28,6 +29,7 @@ Click behavior:
### Backend accept path
`PATCH /api/avatars/:id` (owner-only, session required):
+
- Validates the uploaded bytes are a GLB (magic bytes check — reuse `api/_lib/model-inspect.js` `isGLB`).
- Re-uses the existing R2 upload helper.
- Overwrites the blob at the same R2 key (or writes a new key + updates `model_url`).
diff --git a/prompts/avatar-editing/03-outfit-variants.md b/prompts/avatar-editing/03-outfit-variants.md
index be1b92e69..1c46d6875 100644
--- a/prompts/avatar-editing/03-outfit-variants.md
+++ b/prompts/avatar-editing/03-outfit-variants.md
@@ -43,6 +43,7 @@ CREATE INDEX IF NOT EXISTS avatar_variants_avatar_idx ON avatar_variants (avatar
### Editor UI
A "Variants" folder in the editor GUI (adjacent to the Editor folder we already added). Controls:
+
- Dropdown: current variant (defaults to "original")
- "Save current edits as new variant" button
- "Delete selected variant" button
diff --git a/prompts/avatar-editing/04-version-history.md b/prompts/avatar-editing/04-version-history.md
index 13a745ea7..9fbecfb57 100644
--- a/prompts/avatar-editing/04-version-history.md
+++ b/prompts/avatar-editing/04-version-history.md
@@ -50,6 +50,7 @@ Whenever task-01's save runs, also `INSERT INTO avatar_versions` with `source='e
### Editor UI
Panel toggle: `🕘` icon in the editor GUI. Opens a sidebar with:
+
- Scrollable list of versions, newest first.
- Each row: thumbnail, version number, source tag, relative time, "Restore" button.
- Clicking a row previews that version in the viewer without committing.
diff --git a/prompts/avatar-platform/01-strip-avaturn.md b/prompts/avatar-platform/01-strip-avaturn.md
index 26904e5c0..de2dc8746 100644
--- a/prompts/avatar-platform/01-strip-avaturn.md
+++ b/prompts/avatar-platform/01-strip-avaturn.md
@@ -27,9 +27,9 @@ After this task:
1. **Package surgery** — `npm uninstall @avaturn/sdk @avaturn-live/web-sdk`. Confirm [package.json](../../package.json) and lockfile diff is exactly the two removals.
2. **Delete** [src/avatar-creator.js](../../src/avatar-creator.js). Search for any imports (`import .* from .*avatar-creator`) and remove them — update callers to no-op the creator-open path with a `console.warn('[creator] not yet wired — see avatar-platform task 03+')`. Don't leave dead buttons; comment them out with a TODO pointing at task 16.
3. **Rename** [src/avaturn-agent.js](../../src/avaturn-agent.js) → `src/agent-panel.js`. Inside:
- - Class `AvaturnAgent` → `AgentPanel`.
- - All CSS classes `avaturn-*` → `agent-*` (keep the suffix: `avaturn-panel` → `agent-panel`, `avaturn-mic` → `agent-mic`, etc.).
- - The header title `SperaxOS` stays (it's a valid brand label).
+ - Class `AvaturnAgent` → `AgentPanel`.
+ - All CSS classes `avaturn-*` → `agent-*` (keep the suffix: `avaturn-panel` → `agent-panel`, `avaturn-mic` → `agent-mic`, etc.).
+ - The header title `SperaxOS` stays (it's a valid brand label).
4. **Update [src/app.js](../../src/app.js)** — import path and class name. No behavioral changes.
5. **Update [style.css](../../style.css)** — replace every `.avaturn-*` selector with `.agent-*`. Verify none are missed.
6. **Update [src/avaturn-agent.js](../../src/avaturn-agent.js) callers** if any exist outside app.js (there shouldn't be).
@@ -56,9 +56,9 @@ After this task:
1. `npm uninstall @avaturn/sdk @avaturn-live/web-sdk` — watch the lockfile diff.
2. `npx vite build` passes.
3. `npm run dev`, open the app:
- - Agent panel toggle works.
- - Typing + pressing Enter echoes a reply.
- - Mic button still toggles active state.
+ - Agent panel toggle works.
+ - Typing + pressing Enter echoes a reply.
+ - Mic button still toggles active state.
4. Open DevTools, inspect panel DOM — classes are all `agent-*`, no `avaturn-*`.
5. Drag-drop a `.glb` into the viewer — it still loads (confirms nothing accidental in viewer path).
diff --git a/prompts/avatar-platform/02-vrm-runtime.md b/prompts/avatar-platform/02-vrm-runtime.md
index fbc4bcf47..043392dc0 100644
--- a/prompts/avatar-platform/02-vrm-runtime.md
+++ b/prompts/avatar-platform/02-vrm-runtime.md
@@ -19,14 +19,14 @@ After this task:
1. **Install** — `npm install @pixiv/three-vrm`. Pin to the latest 3.x (check the upstream for the current major). Update lockfile.
2. **New file** `src/vrm-runtime.js`:
- - Exports `createVRMLoaderPlugin(gltfLoader)` that registers the VRM plugin on the provided `GLTFLoader`.
- - Exports `async loadVRM(gltfLoader, url)` returning `{ scene, vrm }` where `vrm` is the `VRM` instance or `null` if the file is plain GLB.
- - Exports `updateVRM(vrm, deltaSeconds)` calling `vrm.update(dt)` — used by the render loop.
- - Exports `disposeVRM(vrm)` — cleans up spring bones and detaches.
+ - Exports `createVRMLoaderPlugin(gltfLoader)` that registers the VRM plugin on the provided `GLTFLoader`.
+ - Exports `async loadVRM(gltfLoader, url)` returning `{ scene, vrm }` where `vrm` is the `VRM` instance or `null` if the file is plain GLB.
+ - Exports `updateVRM(vrm, deltaSeconds)` calling `vrm.update(dt)` — used by the render loop.
+ - Exports `disposeVRM(vrm)` — cleans up spring bones and detaches.
3. **Modify [src/viewer.js](../../src/viewer.js)** — in the GLTFLoader setup, install the VRM plugin. In the scene-setup path that runs after a model loads, detect `gltf.userData.vrm` (set by the plugin). If present:
- - Store it as `this.activeVRM`.
- - In the render/update loop, call `updateVRM(this.activeVRM, delta)` every frame.
- - On model replacement/dispose, call `disposeVRM(previous)`.
+ - Store it as `this.activeVRM`.
+ - In the render/update loop, call `updateVRM(this.activeVRM, delta)` every frame.
+ - On model replacement/dispose, call `disposeVRM(previous)`.
4. **Expose** — `window.VIEWER.activeVRM` reads from `app.viewer.activeVRM`.
5. **Accept `.vrm` in the file picker / dropzone** — search [src/app.js](../../src/app.js) and the dropzone config for the `.glb, .gltf` accept list; add `.vrm`.
6. **Smoke-test asset** — download a public CC0 VRM (e.g., one of the AvatarSample set from VRoid Hub, or a file from the asset-library task later) into [public/avatars/](../../public/avatars/) as `sample.vrm`. License info goes into a `public/avatars/NOTICES.md` (create it).
@@ -71,4 +71,4 @@ After this task:
- Bundle size before vs after.
- Any console warnings from the VRM plugin on the sample file.
- The sample VRM's source URL and license, copied into `public/avatars/NOTICES.md`.
-- Render-loop deltaTime measurement (mean + p95) with a VRM loaded, before any animation features land.
\ No newline at end of file
+- Render-loop deltaTime measurement (mean + p95) with a VRM loaded, before any animation features land.
diff --git a/prompts/avatar-platform/03-vendor-character-studio.md b/prompts/avatar-platform/03-vendor-character-studio.md
index 986c6dee3..297880361 100644
--- a/prompts/avatar-platform/03-vendor-character-studio.md
+++ b/prompts/avatar-platform/03-vendor-character-studio.md
@@ -21,18 +21,18 @@ After this task:
1. **Fetch upstream** — `git clone https://github.com/M3-org/CharacterStudio /tmp/character-studio` (shallow clone fine). Note the commit SHA; record it in `NOTICE`.
2. **Identify the core** — in upstream, locate `CharacterManager` and the modules it directly imports. Typically: character loading, asset swapping, VRM manipulation, export-to-GLB helpers. Do NOT pull in:
- - React components
- - Next.js routing
- - UI styling
- - Anything under `src/components/` that imports JSX
+ - React components
+ - Next.js routing
+ - UI styling
+ - Anything under `src/components/` that imports JSX
3. **Copy the minimal set** into `src/vendor/character-studio/`. Preserve the original relative import paths within that tree; adjust only the entry point.
4. **Adapter** `src/character/character-manager.js` — exports a class `CharacterManager` (our name, wraps the upstream one) with:
- - `async loadManifest(url)` — loads an asset manifest JSON.
- - `async loadTrait(traitGroup, traitId)` — e.g., `loadTrait('hair', 'hair-03')`.
- - `async removeTrait(traitGroup)`.
- - `getScene()` — returns a `THREE.Object3D` to add to the scene.
- - `async exportVRM()` / `async exportGLB()` — returns a `Blob`.
- - `dispose()`.
+ - `async loadManifest(url)` — loads an asset manifest JSON.
+ - `async loadTrait(traitGroup, traitId)` — e.g., `loadTrait('hair', 'hair-03')`.
+ - `async removeTrait(traitGroup)`.
+ - `getScene()` — returns a `THREE.Object3D` to add to the scene.
+ - `async exportVRM()` / `async exportGLB()` — returns a `Blob`.
+ - `dispose()`.
5. **Manifest bootstrap** — create `public/character-manifest.example.json` showing the schema. Task 17 replaces this with a real asset library.
6. **Viewer hook** — when a `CharacterManager` instance is created and `getScene()` is called, the consumer (future editor UI) decides when to add it. No automatic wiring in the viewer — keep the runtime pluggable.
7. **License handling** — copy upstream `LICENSE` verbatim to `src/vendor/character-studio/NOTICE` with a prepended line: `Vendored from https://github.com/M3-org/CharacterStudio @ <SHA>`.
@@ -60,13 +60,13 @@ After this task:
1. `node --check` each new JS file.
2. `npx vite build` passes.
3. Smoke test in DevTools console:
- ```js
- const { CharacterManager } = await import('/src/character/character-manager.js');
- const mgr = new CharacterManager({ renderer: VIEWER.app.viewer.renderer });
- await mgr.loadManifest('/character-manifest.example.json');
- VIEWER.app.viewer.scene.add(mgr.getScene());
- ```
- Avatar appears. No console errors.
+ ```js
+ const { CharacterManager } = await import('/src/character/character-manager.js');
+ const mgr = new CharacterManager({ renderer: VIEWER.app.viewer.renderer });
+ await mgr.loadManifest('/character-manifest.example.json');
+ VIEWER.app.viewer.scene.add(mgr.getScene());
+ ```
+ Avatar appears. No console errors.
4. `mgr.dispose()` removes the character and frees GPU resources (verify via `renderer.info.memory`).
## Scope boundaries — do NOT do these
diff --git a/prompts/avatar-platform/04-desktop-photo-capture.md b/prompts/avatar-platform/04-desktop-photo-capture.md
index 0373ee7dc..375ccf29a 100644
--- a/prompts/avatar-platform/04-desktop-photo-capture.md
+++ b/prompts/avatar-platform/04-desktop-photo-capture.md
@@ -18,31 +18,31 @@ After this task:
## Deliverable
1. **New module** `src/capture/photo-capture.js` exporting default class `PhotoCapture`:
- - `constructor(container, options)` — `options: { jpegQuality = 0.92, targetSize = { w: 1024, h: 1024 } }`.
- - `async open() -> Promise<{ left: Blob, center: Blob, right: Blob }>` — opens modal, resolves on success, rejects on cancel.
- - `dispose()` — stops tracks, removes DOM.
+ - `constructor(container, options)` — `options: { jpegQuality = 0.92, targetSize = { w: 1024, h: 1024 } }`.
+ - `async open() -> Promise<{ left: Blob, center: Blob, right: Blob }>` — opens modal, resolves on success, rejects on cancel.
+ - `dispose()` — stops tracks, removes DOM.
2. **Modal UX**:
- - Title: "Take three photos to build your avatar"
- - Live `<video>` preview with a face-oriented overlay guide (SVG circle + rule-of-thirds hints).
- - Current step indicator (1/3, 2/3, 3/3) + labeled step: "Left profile" / "Face forward" / "Right profile".
- - Primary button: "Capture" (`space` or `enter` to trigger).
- - Retake button on each thumbnail after capture.
- - Cancel button (`escape`).
+ - Title: "Take three photos to build your avatar"
+ - Live `<video>` preview with a face-oriented overlay guide (SVG circle + rule-of-thirds hints).
+ - Current step indicator (1/3, 2/3, 3/3) + labeled step: "Left profile" / "Face forward" / "Right profile".
+ - Primary button: "Capture" (`space` or `enter` to trigger).
+ - Retake button on each thumbnail after capture.
+ - Cancel button (`escape`).
3. **Capture pipeline**:
- - `getUserMedia({ video: { width: { ideal: 1280 }, height: { ideal: 720 }, facingMode: 'user' } })`.
- - Draw current frame to an offscreen `<canvas>`, resize to `targetSize`, encode as JPEG at `jpegQuality` via `canvas.toBlob()`.
- - Show thumbnail for each captured step.
+ - `getUserMedia({ video: { width: { ideal: 1280 }, height: { ideal: 720 }, facingMode: 'user' } })`.
+ - Draw current frame to an offscreen `<canvas>`, resize to `targetSize`, encode as JPEG at `jpegQuality` via `canvas.toBlob()`.
+ - Show thumbnail for each captured step.
4. **Error handling** — rejections:
- - `PhotoCaptureError('permission_denied')` if `NotAllowedError`.
- - `PhotoCaptureError('no_camera')` if `NotFoundError`.
- - `PhotoCaptureError('cancelled')` on user cancel.
- - `PhotoCaptureError('unsupported')` if `navigator.mediaDevices` is missing.
+ - `PhotoCaptureError('permission_denied')` if `NotAllowedError`.
+ - `PhotoCaptureError('no_camera')` if `NotFoundError`.
+ - `PhotoCaptureError('cancelled')` on user cancel.
+ - `PhotoCaptureError('unsupported')` if `navigator.mediaDevices` is missing.
5. **Styling** — add a block to [style.css](../../style.css) using the `capture-*` class prefix. Dark theme, matches the existing agent panel aesthetic.
6. **Accessibility**:
- - Focus trap in modal.
- - `aria-live` region announces step changes.
- - Buttons have `aria-label`.
- - `prefers-reduced-motion: reduce` disables modal entry/exit animation.
+ - Focus trap in modal.
+ - `aria-live` region announces step changes.
+ - Buttons have `aria-label`.
+ - `prefers-reduced-motion: reduce` disables modal entry/exit animation.
## Audit checklist
diff --git a/prompts/avatar-platform/05-session-bridge.md b/prompts/avatar-platform/05-session-bridge.md
index d6936ab3b..02bbb9aac 100644
--- a/prompts/avatar-platform/05-session-bridge.md
+++ b/prompts/avatar-platform/05-session-bridge.md
@@ -19,23 +19,23 @@ After this task:
## Deliverable
1. **Backend choice** — decide between:
- - A. **Vercel Edge Function + Upstash Redis** (matches existing [vercel.json](../../vercel.json) hint in [package.json:41](../../package.json#L41)). Document the env vars needed.
- - B. **Standalone Node/Bun server** under `server/session/` with in-memory map + SSE.
- - Default to A if the project already deploys to Vercel; else B. **Document the decision** in the reporting section.
+ - A. **Vercel Edge Function + Upstash Redis** (matches existing [vercel.json](../../vercel.json) hint in [package.json:41](../../package.json#L41)). Document the env vars needed.
+ - B. **Standalone Node/Bun server** under `server/session/` with in-memory map + SSE.
+ - Default to A if the project already deploys to Vercel; else B. **Document the decision** in the reporting section.
2. **Endpoints** (names are fixed regardless of backend choice):
- - `POST /api/session/new` → `{ sessionId, sessionUrl, expiresAt }`. `sessionUrl` is `https://<host>/m/<sessionId>`.
- - `GET /api/session/:id/stream` — Server-Sent Events stream pushing `{ type, data }` events to the subscriber (desktop).
- - `POST /api/session/:id/events` — mobile posts `{ type, data }` events (JSON body, multipart for images).
- - `GET /api/session/:id` → metadata only (`{ status, lastEventAt }`), no event payloads.
+ - `POST /api/session/new` → `{ sessionId, sessionUrl, expiresAt }`. `sessionUrl` is `https://<host>/m/<sessionId>`.
+ - `GET /api/session/:id/stream` — Server-Sent Events stream pushing `{ type, data }` events to the subscriber (desktop).
+ - `POST /api/session/:id/events` — mobile posts `{ type, data }` events (JSON body, multipart for images).
+ - `GET /api/session/:id` → metadata only (`{ status, lastEventAt }`), no event payloads.
3. **Client module** `src/capture/session-client.js`:
- - `async createSession() -> { sessionId, sessionUrl, stream }` — `stream` is an `AsyncIterable<Event>`.
- - `async attachSession(sessionId) -> { post(type, data) }`.
- - Auto-reconnects SSE on drop (with backoff).
+ - `async createSession() -> { sessionId, sessionUrl, stream }` — `stream` is an `AsyncIterable<Event>`.
+ - `async attachSession(sessionId) -> { post(type, data) }`.
+ - Auto-reconnects SSE on drop (with backoff).
4. **Security**:
- - Session IDs are 128-bit random, URL-safe base64 (~22 chars).
- - Rate-limit: max 5 `/api/session/new` per IP per minute; max 20 events per session; max 10 MB total payload per session.
- - No CORS wildcard — allow the deployed origin + `localhost`.
- - Images never written to disk; streamed through memory and discarded after dispatch.
+ - Session IDs are 128-bit random, URL-safe base64 (~22 chars).
+ - Rate-limit: max 5 `/api/session/new` per IP per minute; max 20 events per session; max 10 MB total payload per session.
+ - No CORS wildcard — allow the deployed origin + `localhost`.
+ - Images never written to disk; streamed through memory and discarded after dispatch.
5. **Expiry** — sessions self-destruct after 10 min from `createdAt`, or 2 min after `terminated` event, whichever comes first.
6. **Observability** — a minimal counter log line per session (`[session] new <id>`, `[session] end <id> reason=<expiry|done|error>`). **Never** log event payloads.
diff --git a/prompts/avatar-platform/06-mobile-capture-route.md b/prompts/avatar-platform/06-mobile-capture-route.md
index 7986431a6..46892c94f 100644
--- a/prompts/avatar-platform/06-mobile-capture-route.md
+++ b/prompts/avatar-platform/06-mobile-capture-route.md
@@ -16,22 +16,22 @@ Depends on tasks 04 and 05.
## Deliverable
1. **Mobile route entry** `m.html` at the repo root + [vite.config.mjs](../../vite.config.mjs) tweak to register it as an additional input. Page content:
- - Detects `window.location.pathname` → extracts `sessionId`.
- - Loads `src/capture/mobile-capture.js`.
- - Renders full-screen camera preview + capture UI optimized for portrait phone form factor.
+ - Detects `window.location.pathname` → extracts `sessionId`.
+ - Loads `src/capture/mobile-capture.js`.
+ - Renders full-screen camera preview + capture UI optimized for portrait phone form factor.
2. **New module** `src/capture/mobile-capture.js`:
- - `init(sessionId)` — attaches to the session via `attachSession()` from task 05.
- - Three-shot capture flow (left, center, right), mirrored from desktop task 04 but redesigned for touch + portrait + single-hand use.
- - On each capture, POST the blob to `/api/session/:id/events` with `type: 'photo'`, `step: 'left'|'center'|'right'`.
- - After the third capture, POST `type: 'done'` and show "Photos sent — check your desktop".
- - Front-camera only (`facingMode: 'user'`).
- - Fallback: if `getUserMedia` fails, show a file-picker accepting three images with `capture="user"` hint.
+ - `init(sessionId)` — attaches to the session via `attachSession()` from task 05.
+ - Three-shot capture flow (left, center, right), mirrored from desktop task 04 but redesigned for touch + portrait + single-hand use.
+ - On each capture, POST the blob to `/api/session/:id/events` with `type: 'photo'`, `step: 'left'|'center'|'right'`.
+ - After the third capture, POST `type: 'done'` and show "Photos sent — check your desktop".
+ - Front-camera only (`facingMode: 'user'`).
+ - Fallback: if `getUserMedia` fails, show a file-picker accepting three images with `capture="user"` hint.
3. **Desktop QR handoff module** `src/capture/qr-handoff.js`:
- - `async open(container): Promise<{ left, center, right }>` — same return shape as `PhotoCapture` from task 04.
- - Creates a session via `createSession()`, renders the `sessionUrl` as a QR code (use the `qrcode` npm package — add it, it's ~7 KB gzipped).
- - Shows a waiting state with spinner + "Scan to continue on your phone".
- - Subscribes to the SSE stream; collects three `photo` events, resolves when `done` arrives.
- - Has a "Use webcam instead" button that disposes the QR flow and opens `PhotoCapture` from task 04.
+ - `async open(container): Promise<{ left, center, right }>` — same return shape as `PhotoCapture` from task 04.
+ - Creates a session via `createSession()`, renders the `sessionUrl` as a QR code (use the `qrcode` npm package — add it, it's ~7 KB gzipped).
+ - Shows a waiting state with spinner + "Scan to continue on your phone".
+ - Subscribes to the SSE stream; collects three `photo` events, resolves when `done` arrives.
+ - Has a "Use webcam instead" button that disposes the QR flow and opens `PhotoCapture` from task 04.
4. **Styling** — `capture-mobile-*` prefix for the mobile-only CSS. Keep the mobile route CSS in a separate stylesheet loaded only by `m.html` to avoid bloat on the main app.
5. **PWA config** — update `vite-plugin-pwa` options so `m.html` and its module chunk are precached. The main app's existing PWA behavior must not regress.
diff --git a/prompts/avatar-platform/07-photo-to-avatar-fast.md b/prompts/avatar-platform/07-photo-to-avatar-fast.md
index 7b21f15c6..d0159e12d 100644
--- a/prompts/avatar-platform/07-photo-to-avatar-fast.md
+++ b/prompts/avatar-platform/07-photo-to-avatar-fast.md
@@ -13,27 +13,27 @@ Depends on tasks 02 and 04 (or 06).
1. Given `{ center: Blob }` (left/right are ignored in v1 — they'll feed task 08), produce a VRM file (or a patched VRM from a base template) that resembles the user.
2. The template is a neutral base VRM bundled in [public/avatars/](../../public/avatars/).
3. Customization applied:
- - Head shape morphed toward the detected face via landmark-driven morph targets or a blendshape approximation.
- - Face texture projected from the center photo.
- - Skin tone sampled from the face and applied to exposed skin slots.
- - Hair kept from the template (editor UI in task 16 lets the user swap).
+ - Head shape morphed toward the detected face via landmark-driven morph targets or a blendshape approximation.
+ - Face texture projected from the center photo.
+ - Skin tone sampled from the face and applied to exposed skin slots.
+ - Hair kept from the template (editor UI in task 16 lets the user swap).
4. Total time from blob in to avatar rendered < 5 seconds on a mid-range laptop.
## Deliverable
1. **Base template** — `public/avatars/template-neutral.vrm`. A rigged, expression-ready VRM with a neutral face. Source with CC0/MIT license only. Record in `public/avatars/NOTICES.md`.
2. **MediaPipe integration** `src/capture/face-landmarks.js`:
- - Loads MediaPipe Face Landmarker WASM + model from a CDN or vendored at `public/vendor/mediapipe/`.
- - Exports `detectFace(blob) -> { landmarks: Float32Array[478*3], blendshapes: Record<string, number>, matrix: Float32Array[16] }`.
- - Model is loaded lazily on first call, cached for subsequent calls.
+ - Loads MediaPipe Face Landmarker WASM + model from a CDN or vendored at `public/vendor/mediapipe/`.
+ - Exports `detectFace(blob) -> { landmarks: Float32Array[478*3], blendshapes: Record<string, number>, matrix: Float32Array[16] }`.
+ - Model is loaded lazily on first call, cached for subsequent calls.
3. **Avatar generator** `src/capture/fast-avatar.js`:
- - `async generate({ center, left?, right? }) -> Blob` — a VRM Blob.
- - Loads the template VRM, applies morphs/textures, exports with `VRMExporter` (from `@pixiv/three-vrm-core` or implement via `GLTFExporter` + manual VRM extension patching).
+ - `async generate({ center, left?, right? }) -> Blob` — a VRM Blob.
+ - Loads the template VRM, applies morphs/textures, exports with `VRMExporter` (from `@pixiv/three-vrm-core` or implement via `GLTFExporter` + manual VRM extension patching).
4. **Head-shape approximation** — use a small set of morph-target drivers:
- - Face width → `faceWidth` morph (if template has it) or a scale on jaw bones.
- - Face length → scale Y on cranium bone.
- - Nose prominence → nose morph or localized mesh displacement.
- - Document exactly which drivers the template exposes in `public/avatars/template-neutral.vrm.meta.json`.
+ - Face width → `faceWidth` morph (if template has it) or a scale on jaw bones.
+ - Face length → scale Y on cranium bone.
+ - Nose prominence → nose morph or localized mesh displacement.
+ - Document exactly which drivers the template exposes in `public/avatars/template-neutral.vrm.meta.json`.
5. **Texture projection** — crop the center photo to the face region detected by MediaPipe, warp to the template's UV head region using the 478-landmark topology. Use a small offscreen canvas + perspective warp. This is the biggest quality lever; budget it explicitly.
6. **Skin-tone sampling** — average pixels inside the face mesh polygon (excluding eyes/mouth), convert to linear sRGB, find nearest slot and apply to all skin-mapped materials.
7. **Fallback** — if MediaPipe fails to detect a face, resolve with the plain template and emit a `photo_quality_low` warning; the caller can surface a "retake" option.
diff --git a/prompts/avatar-platform/08-photo-to-avatar-hd.md b/prompts/avatar-platform/08-photo-to-avatar-hd.md
index 75382dcbf..1a404a32e 100644
--- a/prompts/avatar-platform/08-photo-to-avatar-hd.md
+++ b/prompts/avatar-platform/08-photo-to-avatar-hd.md
@@ -17,29 +17,29 @@ Depends on task 07 (to have a result to replace).
## Deliverable
1. **Backend service** under `services/nextface/`:
- - `Dockerfile` starting from a PyTorch CUDA base image.
- - `requirements.txt` with NextFace's pins (pull from upstream).
- - `server.py` — a minimal FastAPI or Flask app exposing:
- - `POST /api/reconstruct` — multipart with `center`, `left`, `right` image fields → returns a `application/zip` of `{ mesh.obj, albedo.png, normal.png, meta.json }`.
- - `GET /health` — GPU status, queue depth, model warm/cold.
- - Concurrency: one job at a time per GPU; additional requests queue.
- - Timeouts: 120s hard cap, 60s soft target.
+ - `Dockerfile` starting from a PyTorch CUDA base image.
+ - `requirements.txt` with NextFace's pins (pull from upstream).
+ - `server.py` — a minimal FastAPI or Flask app exposing:
+ - `POST /api/reconstruct` — multipart with `center`, `left`, `right` image fields → returns a `application/zip` of `{ mesh.obj, albedo.png, normal.png, meta.json }`.
+ - `GET /health` — GPU status, queue depth, model warm/cold.
+ - Concurrency: one job at a time per GPU; additional requests queue.
+ - Timeouts: 120s hard cap, 60s soft target.
2. **Deployment docs** in `services/nextface/DEPLOY.md`:
- - Supported hardware (minimum: 8 GB VRAM, CUDA 11.8+).
- - One-liner to run locally: `docker build && docker run --gpus all -p 8080:8080 ...`.
- - One production target choice: Modal, Replicate, RunPod, Baseten, or self-hosted. **Pick one and document it**. Don't spread across all.
+ - Supported hardware (minimum: 8 GB VRAM, CUDA 11.8+).
+ - One-liner to run locally: `docker build && docker run --gpus all -p 8080:8080 ...`.
+ - One production target choice: Modal, Replicate, RunPod, Baseten, or self-hosted. **Pick one and document it**. Don't spread across all.
3. **Client module** `src/capture/hd-avatar.js`:
- - `async requestHD(blobs, baseVRMBlob, { endpoint, timeoutMs = 90000 })` → Promise<`Blob` (upgraded VRM)> or rejects.
- - Posts multipart, streams progress events if the backend supports them (optional, nice-to-have).
- - Applies the returned mesh + textures onto the VRM from task 07:
- - Replaces head mesh geometry (keeping bone weights re-projected via closest-point mapping).
- - Replaces face texture.
- - Normal map applied to the head material if the VRM supports it.
+ - `async requestHD(blobs, baseVRMBlob, { endpoint, timeoutMs = 90000 })` → Promise<`Blob` (upgraded VRM)> or rejects.
+ - Posts multipart, streams progress events if the backend supports them (optional, nice-to-have).
+ - Applies the returned mesh + textures onto the VRM from task 07:
+ - Replaces head mesh geometry (keeping bone weights re-projected via closest-point mapping).
+ - Replaces face texture.
+ - Normal map applied to the head material if the VRM supports it.
4. **Orchestration** `src/capture/avatar-pipeline.js`:
- - Combines 07 + 08. `async runPipeline(blobs, { onFast, onHD, onError })`:
- - Resolves `onFast` with the fast-path VRM.
- - In parallel, kicks off `requestHD`; on resolve, calls `onHD` with the upgraded VRM.
- - On HD failure, calls `onError({ stage: 'hd' })` but does not discard the fast-path result.
+ - Combines 07 + 08. `async runPipeline(blobs, { onFast, onHD, onError })`:
+ - Resolves `onFast` with the fast-path VRM.
+ - In parallel, kicks off `requestHD`; on resolve, calls `onHD` with the upgraded VRM.
+ - On HD failure, calls `onError({ stage: 'hd' })` but does not discard the fast-path result.
5. **Config** — `VITE_HD_ENDPOINT` env var for the client; `NEXTFACE_MODEL_DIR` for the backend.
## Audit checklist
diff --git a/prompts/avatar-platform/09-talking-head.md b/prompts/avatar-platform/09-talking-head.md
index 225c3e9a1..9d75babde 100644
--- a/prompts/avatar-platform/09-talking-head.md
+++ b/prompts/avatar-platform/09-talking-head.md
@@ -20,8 +20,8 @@ Depends on task 02.
1. **Vendor** — clone upstream, record SHA + MIT license in `src/vendor/talking-head/NOTICE`. Copy only the engine module(s); skip demo HTML/CSS.
2. **Dependencies** — TalkingHead expects three.js (we have it) and, for its TTS path, browser APIs. It has optional ties to ElevenLabs / Azure; **do not vendor those paths** — task 10 provides our own TTS with visemes.
3. **Adapter** `src/agent/talking-head.js`:
- - `class TalkingHead { attach(vrm): void; detach(): void; async speak(text, { visemes?, audio? }); setMood(name, strength); playGesture(name); idleOn(); idleOff(); dispose(); }`
- - If `visemes` + `audio` are supplied (from task 10), use them directly. If only `text` is supplied, emit a warning — task 10 is the expected provider.
+ - `class TalkingHead { attach(vrm): void; detach(): void; async speak(text, { visemes?, audio? }); setMood(name, strength); playGesture(name); idleOn(); idleOff(); dispose(); }`
+ - If `visemes` + `audio` are supplied (from task 10), use them directly. If only `text` is supplied, emit a warning — task 10 is the expected provider.
4. **Render-loop integration** — the adapter registers a `tick(delta)` callback that the existing render loop already calls (see how [src/viewer.js](../../src/viewer.js) drives animation). Don't start a second RAF loop.
5. **Auto-attach** — observe `activeVRM` changes. When a new VRM loads (task 02 swap), detach from the old one (if any) and attach to the new. When `activeVRM` is null, idle is paused.
6. **Animation library** — optional: if upstream bundles or expects Mixamo FBX idle loops, put them in [public/animations/](../../public/animations/) with per-file license notes. Keep the set minimal (1 idle, 1 wave, 1 nod).
diff --git a/prompts/avatar-platform/10-tts-visemes.md b/prompts/avatar-platform/10-tts-visemes.md
index 1f6e89870..a7493abbd 100644
--- a/prompts/avatar-platform/10-tts-visemes.md
+++ b/prompts/avatar-platform/10-tts-visemes.md
@@ -21,13 +21,13 @@ Depends on task 09.
1. **HeadTTS vendoring** — HeadTTS is part of the TalkingHead author's stack; vendor the browser build into `src/vendor/headtts/`. Include the Kokoro model or document its CDN URL.
2. **Piper client** `src/agent/tts-piper.js` — POSTs text to a configured `/api/tts` endpoint, receives `{ audioUrl, phonemes: [{ phoneme, startMs, endMs }] }`, maps phonemes to Oculus visemes.
3. **Piper server** under `services/piper/`:
- - Dockerfile (CPU-only, small image).
- - Serves `POST /api/tts` accepting `{ text, voice }` → returns audio + phoneme timestamps.
- - Pick one Piper voice model (e.g., `en_US-amy-medium`) as default; allow override via `voice` param.
+ - Dockerfile (CPU-only, small image).
+ - Serves `POST /api/tts` accepting `{ text, voice }` → returns audio + phoneme timestamps.
+ - Pick one Piper voice model (e.g., `en_US-amy-medium`) as default; allow override via `voice` param.
4. **Unified facade** `src/agent/tts.js`:
- - `class TTS { constructor({ prefer: 'local'|'server'|'auto' }); async synthesize(text, voice?); dispose(); }`
- - Capability detection: WebGPU via `navigator.gpu`, WASM SIMD via a quick probe.
- - Route: `local` → HeadTTS; `server` → Piper; `auto` → HeadTTS if capable else Piper if `/api/tts` reachable else Web Speech API.
+ - `class TTS { constructor({ prefer: 'local'|'server'|'auto' }); async synthesize(text, voice?); dispose(); }`
+ - Capability detection: WebGPU via `navigator.gpu`, WASM SIMD via a quick probe.
+ - Route: `local` → HeadTTS; `server` → Piper; `auto` → HeadTTS if capable else Piper if `/api/tts` reachable else Web Speech API.
5. **Viseme mapping** `src/agent/viseme-map.js` — phoneme→Oculus viseme table. Oculus visemes: `sil, PP, FF, TH, DD, kk, CH, SS, nn, RR, aa, E, I, O, U`. Document gaps (not all phonemes map cleanly).
6. **TalkingHead wiring** — update task 09's `talking-head.js` adapter: `speak(text)` now internally calls `tts.synthesize` and passes the result to the engine. The raw `speak(text, { audio, visemes, ... })` overload stays for callers that synthesize externally.
7. **Audio playback** — use a shared `AudioContext`. Resume on first user interaction (browser autoplay policy). Document the gesture requirement in the reporting section.
diff --git a/prompts/avatar-platform/11-speech-to-text.md b/prompts/avatar-platform/11-speech-to-text.md
index e3d533688..a3c33f8e4 100644
--- a/prompts/avatar-platform/11-speech-to-text.md
+++ b/prompts/avatar-platform/11-speech-to-text.md
@@ -17,19 +17,19 @@ Depends on task 01 (renamed agent panel exists).
1. **Vendor or npm** — whisper-web depends on `@xenova/transformers`. Install via npm (it's infrastructural-ish, and bundling Transformers.js manually is painful).
2. **New module** `src/agent/stt.js`:
- - `class STT { async start({ onPartial, onFinal, onError }); stop(); dispose(); }`
- - Loads the whisper `base.en` model (or `tiny.en` on low-memory devices) lazily on first `start()`.
- - Uses `MediaRecorder` + a VAD-ish silence detector to chunk audio into ~1s windows for streaming transcription.
- - Supports cancel mid-utterance.
+ - `class STT { async start({ onPartial, onFinal, onError }); stop(); dispose(); }`
+ - Loads the whisper `base.en` model (or `tiny.en` on low-memory devices) lazily on first `start()`.
+ - Uses `MediaRecorder` + a VAD-ish silence detector to chunk audio into ~1s windows for streaming transcription.
+ - Supports cancel mid-utterance.
3. **Capability detection** — `STT.canUseLocal()` returns true if:
- - `navigator.hardwareConcurrency >= 4`.
- - `navigator.deviceMemory >= 4` (fallback to `true` on Safari where this API is absent — treat as capable).
- - WebAssembly SIMD probe passes.
+ - `navigator.hardwareConcurrency >= 4`.
+ - `navigator.deviceMemory >= 4` (fallback to `true` on Safari where this API is absent — treat as capable).
+ - WebAssembly SIMD probe passes.
4. **Agent panel integration** — in `src/agent-panel.js`, replace the Web Speech API block with STT:
- - Mic button press → `stt.start(...)`.
- - Partial results render in the input field in a muted color.
- - Final result commits to the input; auto-sends if "push-to-talk" mode is active (new option).
- - Release or press-again → `stt.stop()`.
+ - Mic button press → `stt.start(...)`.
+ - Partial results render in the input field in a muted color.
+ - Final result commits to the input; auto-sends if "push-to-talk" mode is active (new option).
+ - Release or press-again → `stt.stop()`.
5. **Fallback wiring** — if `STT.canUseLocal()` is false, dynamically import the old Web Speech path and route through it with the same event shape.
6. **Model hosting** — prefer the Hugging Face CDN by default; allow override with `VITE_WHISPER_MODEL_URL` for self-hosted deploys.
diff --git a/prompts/avatar-platform/12-mirror-mode.md b/prompts/avatar-platform/12-mirror-mode.md
index d0a20a9ec..f696c02cb 100644
--- a/prompts/avatar-platform/12-mirror-mode.md
+++ b/prompts/avatar-platform/12-mirror-mode.md
@@ -21,13 +21,13 @@ Depends on tasks 02, 09.
1. **Vendor Kalidokit** — MIT. Copy into `src/vendor/kalidokit/` with NOTICE. Kalidokit is tiny; no npm needed.
2. **MediaPipe integration** — reuse `src/capture/face-landmarks.js` from task 07 where possible. Add a `src/capture/pose-landmarks.js` for upper-body tracking (MediaPipe Pose Landmarker).
3. **Module** `src/agent/mirror.js`:
- - `class MirrorMode { constructor(vrm, videoEl); async start(); stop(); dispose(); }`
- - Starts webcam, feeds MediaPipe Face + Pose landmarker on every video frame (throttled to 30fps).
- - Passes landmarks to Kalidokit; applies outputs to:
- - Head bone rotation (yaw/pitch/roll).
- - Upper-body bones (neck, chest, shoulders).
- - Arm bones (hands optional; gate behind a sub-flag — hand tracking doubles CPU).
- - Face blendshapes (mouth, eyes, brows) — routed into VRM expression manager.
+ - `class MirrorMode { constructor(vrm, videoEl); async start(); stop(); dispose(); }`
+ - Starts webcam, feeds MediaPipe Face + Pose landmarker on every video frame (throttled to 30fps).
+ - Passes landmarks to Kalidokit; applies outputs to:
+ - Head bone rotation (yaw/pitch/roll).
+ - Upper-body bones (neck, chest, shoulders).
+ - Arm bones (hands optional; gate behind a sub-flag — hand tracking doubles CPU).
+ - Face blendshapes (mouth, eyes, brows) — routed into VRM expression manager.
4. **UI** — a small toolbar button "Mirror me" that opens a permission prompt + tiny PIP video preview so the user can see what the camera sees.
5. **Integration with TalkingHead** (task 09) — when `MirrorMode.start()` runs, call `talkingHead.idleOff()`. On stop, `idleOn()`. If the brain (task 14) calls `speak()` while mirroring, the jaw/mouth is driven by visemes (TTS) AND the user's mouth-open expression is attenuated — document the blend strategy you pick.
6. **Performance** — render every Nth frame, not every RAF. Target: 30 landmark detections/sec, 60 render fps. Use `requestVideoFrameCallback` if available.
diff --git a/prompts/avatar-platform/13-full-body-mocap.md b/prompts/avatar-platform/13-full-body-mocap.md
index c43c8db59..ea11ccfc6 100644
--- a/prompts/avatar-platform/13-full-body-mocap.md
+++ b/prompts/avatar-platform/13-full-body-mocap.md
@@ -20,9 +20,9 @@ Depends on task 12.
1. **Evaluate XR Animator** — it's a web-based app; check if its core (MediaPipe Pose + retargeting math) can be extracted as a module. If it can't be cleanly vendored, use [BlazeWild/Real-Time-Motion-Transfer](https://github.com/BlazeWild/Real-Time-Motion-Transfer-to-a-3D-Avatar) as a simpler reference.
2. **Vendor the chosen upstream** — copy minimal pose-retargeting code into `src/vendor/fullbody-mocap/`. NOTICE file with license + SHA.
3. **Module** `src/agent/fullbody-mirror.js` extending `MirrorMode` from task 12:
- - `class FullBodyMirror extends MirrorMode { ... }`
- - Adds leg bone retargeting: hip, knee, ankle rotations.
- - Detects "low confidence / legs out of frame" → gracefully degrades to upper-body mode.
+ - `class FullBodyMirror extends MirrorMode { ... }`
+ - Adds leg bone retargeting: hip, knee, ankle rotations.
+ - Detects "low confidence / legs out of frame" → gracefully degrades to upper-body mode.
4. **IK sanity** — legs are IK-sensitive (a wrong hip rotation makes the avatar fall over). Use Kalidokit's or the upstream's stabilization; document any filters/dampeners tuned.
5. **UI** — the "Mirror me" toolbar button from task 12 gains a sub-option "Full body (experimental)".
6. **Camera framing coach** — show a subtle silhouette overlay on the webcam preview guiding the user to step back and include their full body.
diff --git a/prompts/avatar-platform/14-agent-brain.md b/prompts/avatar-platform/14-agent-brain.md
index a41349995..4a8547100 100644
--- a/prompts/avatar-platform/14-agent-brain.md
+++ b/prompts/avatar-platform/14-agent-brain.md
@@ -23,24 +23,24 @@ Depends on tasks 09, 10, 11.
1. **Interface** `src/agent/brain.js` — `class Brain { async respond(history, { signal, onToken }): Promise<string> }` where `history` is `[{role, content}]` and `onToken` streams partials.
2. **WebLLM adapter** `src/agent/brain-webllm.js`:
- - npm install `@mlc-ai/web-llm`.
- - Loads a small model (e.g., `Llama-3.2-3B-Instruct-q4f16_1-MLC`); document model choice with size + VRAM.
- - First call triggers model download with a visible progress UI.
- - Subsequent calls are instant-ish.
+ - npm install `@mlc-ai/web-llm`.
+ - Loads a small model (e.g., `Llama-3.2-3B-Instruct-q4f16_1-MLC`); document model choice with size + VRAM.
+ - First call triggers model download with a visible progress UI.
+ - Subsequent calls are instant-ish.
3. **Cloud adapter** `src/agent/brain-cloud.js`:
- - POSTs to `/api/agent/complete`; streams SSE back.
- - Supports Claude and OpenAI via the same backend endpoint (server decides based on env).
+ - POSTs to `/api/agent/complete`; streams SSE back.
+ - Supports Claude and OpenAI via the same backend endpoint (server decides based on env).
4. **Backend proxy** `services/agent/`:
- - Accepts `{ history, model? }`.
- - Uses server-side API key (`ANTHROPIC_API_KEY` or `OPENAI_API_KEY`).
- - Streams SSE.
- - Rate-limit per IP.
- - **Never** logs request/response content.
- - If no API key is configured, endpoint returns 501 and the frontend auto-degrades to local.
+ - Accepts `{ history, model? }`.
+ - Uses server-side API key (`ANTHROPIC_API_KEY` or `OPENAI_API_KEY`).
+ - Streams SSE.
+ - Rate-limit per IP.
+ - **Never** logs request/response content.
+ - If no API key is configured, endpoint returns 501 and the frontend auto-degrades to local.
5. **Capability selector** `src/agent/brain.js` → `async createBrain({ prefer: 'local'|'cloud'|'auto' })`:
- - `local`: requires WebGPU + `navigator.deviceMemory >= 4` (or unknown on Safari — try).
- - `cloud`: requires backend reachable.
- - `auto`: prefer local if capable, else cloud, else rule-based fallback from task 01.
+ - `local`: requires WebGPU + `navigator.deviceMemory >= 4` (or unknown on Safari — try).
+ - `cloud`: requires backend reachable.
+ - `auto`: prefer local if capable, else cloud, else rule-based fallback from task 01.
6. **System prompt** — templated from viewer state. Include: current model file name, animation list, any validation warnings, whether a VRM is loaded, user's name if known (task 20).
7. **Agent panel wiring** — replace `_generateResponse` with `brain.respond(history, { onToken })`. As tokens stream, push to TalkingHead via `speak` (task 09 + 10) in sentence-sized chunks so lipsync catches up.
8. **Abort handling** — user presses "stop" → `AbortController` cancels both the LLM stream and the TTS synthesis.
diff --git a/prompts/avatar-platform/15-conversation-state.md b/prompts/avatar-platform/15-conversation-state.md
index f42f9b492..ebe4e0035 100644
--- a/prompts/avatar-platform/15-conversation-state.md
+++ b/prompts/avatar-platform/15-conversation-state.md
@@ -16,22 +16,22 @@ Depends on task 14.
## Deliverable
1. **Storage** `src/agent/history.js`:
- - IndexedDB-backed. Key by `agentId` (a client UUID generated on first run).
- - `append({ role, content, toolCalls? })`, `load(limit?)`, `clear()`.
- - Token budget: cap at ~8k tokens for the context window; oldest turns summarized into a running synopsis once cap is hit.
+ - IndexedDB-backed. Key by `agentId` (a client UUID generated on first run).
+ - `append({ role, content, toolCalls? })`, `load(limit?)`, `clear()`.
+ - Token budget: cap at ~8k tokens for the context window; oldest turns summarized into a running synopsis once cap is hit.
2. **Tool definitions** `src/agent/tools.js`:
- - Each tool is `{ name, description, parameters (JSON Schema), handler(args) }`.
- - Tools: `loadModel(url)`, `listAnimations()`, `playAnimation(name)`, `describeCurrentModel()`, `setLighting({ exposure?, environment? })`.
- - Handlers call the viewer API directly; they're the **only** layer that touches `VIEWER.app.viewer`.
+ - Each tool is `{ name, description, parameters (JSON Schema), handler(args) }`.
+ - Tools: `loadModel(url)`, `listAnimations()`, `playAnimation(name)`, `describeCurrentModel()`, `setLighting({ exposure?, environment? })`.
+ - Handlers call the viewer API directly; they're the **only** layer that touches `VIEWER.app.viewer`.
3. **Tool-use wiring** — extend `Brain.respond` to support tool calls:
- - Cloud path: Claude/OpenAI function-calling format (whichever the backend uses).
- - Local path: prompted-JSON convention (Llama tool-use) — the model writes `{"tool": "...", "args": {...}}` in a fenced block; the frontend parses, executes, feeds back.
+ - Cloud path: Claude/OpenAI function-calling format (whichever the backend uses).
+ - Local path: prompted-JSON convention (Llama tool-use) — the model writes `{"tool": "...", "args": {...}}` in a fenced block; the frontend parses, executes, feeds back.
4. **Tool-result UI** — in the chat panel, render tool calls as collapsible cards with the call + result, before the model's final reply.
5. **Settings menu** — small gear icon opens a panel:
- - View history length.
- - "Clear history" button (with confirm).
- - "Forget my avatar" (clears current VRM from local storage; task 20 stores it).
- - Brain mode selector (local/cloud/auto).
+ - View history length.
+ - "Clear history" button (with confirm).
+ - "Forget my avatar" (clears current VRM from local storage; task 20 stores it).
+ - Brain mode selector (local/cloud/auto).
6. **Privacy notice** — a one-line "Conversations are saved on this device only" next to the chat input.
## Audit checklist
diff --git a/prompts/avatar-platform/16-character-editor-ui.md b/prompts/avatar-platform/16-character-editor-ui.md
index 67b7842c8..3ba7d4390 100644
--- a/prompts/avatar-platform/16-character-editor-ui.md
+++ b/prompts/avatar-platform/16-character-editor-ui.md
@@ -17,15 +17,15 @@ Depends on tasks 03, 17 (manifest / asset library).
## Deliverable
1. **New module** `src/character/editor-panel.js` exporting default class `CharacterEditorPanel`:
- - `constructor(container, characterManager)`.
- - `open()` / `close()` / `dispose()`.
+ - `constructor(container, characterManager)`.
+ - `open()` / `close()` / `dispose()`.
2. **Sections**, rendered from the loaded manifest (task 17):
- - **Body** — body shape picker + proportion sliders (head, chest, arms — proxy to `CharacterManager.setBodyProportions`).
- - **Skin** — tone slider + swatch presets.
- - **Face** — morph-target sliders exposed by the current VRM.
- - **Hair** — grid of thumbnails; click to swap.
- - **Clothing** — top, bottom, footwear, accessories tabs.
- - **Expression test** — quick-fire buttons for `aa`, `happy`, `blink`, etc. to sanity-check expression bindings.
+ - **Body** — body shape picker + proportion sliders (head, chest, arms — proxy to `CharacterManager.setBodyProportions`).
+ - **Skin** — tone slider + swatch presets.
+ - **Face** — morph-target sliders exposed by the current VRM.
+ - **Hair** — grid of thumbnails; click to swap.
+ - **Clothing** — top, bottom, footwear, accessories tabs.
+ - **Expression test** — quick-fire buttons for `aa`, `happy`, `blink`, etc. to sanity-check expression bindings.
3. **Live preview** — every slider/click calls into `CharacterManager` synchronously; no "apply" needed for exploration.
4. **Commit + persist** — on "Save", serialize the current trait selections to IndexedDB keyed by `agentId` (task 15). On reload, the last saved state restores.
5. **Undo stack** — last 10 state changes; `cmd+Z` pops. `cmd+shift+Z` redoes.
diff --git a/prompts/avatar-platform/17-asset-library.md b/prompts/avatar-platform/17-asset-library.md
index 3cd8ce831..4d8f267c7 100644
--- a/prompts/avatar-platform/17-asset-library.md
+++ b/prompts/avatar-platform/17-asset-library.md
@@ -5,6 +5,7 @@
Repo: `/workspaces/3D`. Task 16 needs a manifest of traits (hair, clothes, body, accessories) to render its editor. This task builds the manifest + asset hosting pipeline.
Sources:
+
- **[ToxSam/open-source-avatars](https://github.com/ToxSam/open-source-avatars)** — curated CC0 VRM registry.
- **[ToxSam/open-source-3D-assets](https://github.com/ToxSam/open-source-3D-assets)** — 991+ CC0 GLB models.
- **CharacterStudio**'s loot-assets (if license compatible — **verify before including**).
@@ -20,27 +21,27 @@ Sources:
## Deliverable
1. **Manifest schema** `public/character-manifest.schema.json` (JSON Schema):
- ```
- {
- "version": "1",
- "traitGroups": [
- { "id": "hair", "label": "Hair", "traits": [
- { "id": "hair-short-01", "label": "Short messy", "asset": "assets/character/hair/hair-short-01/model.vrm",
- "thumbnail": "assets/character/hair/hair-short-01/thumb.png", "tags": ["casual"], "license": "CC0", "author": "..." }
- ]}
- ]
- }
- ```
+ ```
+ {
+ "version": "1",
+ "traitGroups": [
+ { "id": "hair", "label": "Hair", "traits": [
+ { "id": "hair-short-01", "label": "Short messy", "asset": "assets/character/hair/hair-short-01/model.vrm",
+ "thumbnail": "assets/character/hair/hair-short-01/thumb.png", "tags": ["casual"], "license": "CC0", "author": "..." }
+ ]}
+ ]
+ }
+ ```
2. **Starter asset set** — curate a minimal but usable set (~8 hair, ~10 tops, ~6 bottoms, ~4 footwear, ~6 accessories). Prioritize variety over quantity. License hygiene: **every asset must be CC0, CC-BY (with attribution), or MIT**. Reject CC-BY-SA, CC-NC, any non-commercial terms unless the project has explicitly approved that tradeoff.
3. **Import script** `scripts/import-asset.mjs`:
- - `node scripts/import-asset.mjs <source-url-or-path> --group hair --id hair-short-01 --label "Short messy" --license CC0 --author "..."`
- - Downloads/copies the asset, validates it parses as GLB/VRM, writes to `public/assets/character/<group>/<id>/model.{vrm|glb}`.
- - Appends to `public/character-manifest.json`.
- - Fails loudly on license mismatch or parse errors.
+ - `node scripts/import-asset.mjs <source-url-or-path> --group hair --id hair-short-01 --label "Short messy" --license CC0 --author "..."`
+ - Downloads/copies the asset, validates it parses as GLB/VRM, writes to `public/assets/character/<group>/<id>/model.{vrm|glb}`.
+ - Appends to `public/character-manifest.json`.
+ - Fails loudly on license mismatch or parse errors.
4. **Thumbnail script** `scripts/generate-thumbnails.mjs`:
- - Headless three.js + `node-canvas` or puppeteer rendering.
- - Renders each asset at a standardized camera angle, writes `thumb.png` (256×256).
- - Idempotent: skips assets whose thumb is newer than the model file.
+ - Headless three.js + `node-canvas` or puppeteer rendering.
+ - Renders each asset at a standardized camera angle, writes `thumb.png` (256×256).
+ - Idempotent: skips assets whose thumb is newer than the model file.
5. **License audit** `scripts/audit-licenses.mjs` — scans the manifest, flags any asset with missing or incompatible license fields. Runs in CI (add a GitHub Action or document the intent).
6. **NOTICES.md** — auto-generated from the manifest, listing every author and license. Committed to the repo.
diff --git a/prompts/avatar-platform/18-branding-pass.md b/prompts/avatar-platform/18-branding-pass.md
index 8a704e7b9..3312bc327 100644
--- a/prompts/avatar-platform/18-branding-pass.md
+++ b/prompts/avatar-platform/18-branding-pass.md
@@ -16,14 +16,14 @@ The project identity is TBD at the start of this task — confirm with the user
## Deliverable
1. **Copy audit** — grep user-facing strings for vendor names. Fix each:
- - `grep -ri "avaturn\|charactersudio\|talkinghead\|kalidokit\|mediapipe\|nextface\|whisper\|piper\|kokoro\|webllm" src/ public/ *.html` — triage each hit.
- - Code comments referencing libraries by name are fine. User-visible strings are not.
+ - `grep -ri "avaturn\|charactersudio\|talkinghead\|kalidokit\|mediapipe\|nextface\|whisper\|piper\|kokoro\|webllm" src/ public/ *.html` — triage each hit.
+ - Code comments referencing libraries by name are fine. User-visible strings are not.
2. **CSS prefix scan** — every vendored or custom module should use one of: `agent-`, `editor-`, `capture-`, `mirror-`, `brand-`. No `avaturn-*`, no upstream-vendor prefixes.
3. **HTML metadata** — [index.html](../../index.html), [features.html](../../features.html), `m.html` (from task 06):
- - `<title>`.
- - `<meta name="description">`.
- - OG tags (title, description, image).
- - Favicon.
+ - `<title>`.
+ - `<meta name="description">`.
+ - OG tags (title, description, image).
+ - Favicon.
4. **PWA manifest** — [pwa-manifest.json / manifest.webmanifest](../../) references: name, short_name, description, theme_color, icons.
5. **Credits page** — new `credits.html` route. Lists every vendored dep (from NOTICE files), every asset author (from task 17's NOTICES), and every licensed package of note. Auto-generated ideally, but a hand-maintained version is acceptable.
6. **In-app "About"** — small "(i)" button in the editor/agent panel opens a modal linking to the credits page.
diff --git a/prompts/avatar-platform/19-performance-dispose.md b/prompts/avatar-platform/19-performance-dispose.md
index 2f047a268..4dca0f16d 100644
--- a/prompts/avatar-platform/19-performance-dispose.md
+++ b/prompts/avatar-platform/19-performance-dispose.md
@@ -18,22 +18,22 @@ Should be scheduled **after** tasks 02, 09, 12, 14, 16 are in.
## Deliverable
1. **Dispose audit** — for each module added in tasks 02–17, confirm `dispose()` exists and is called on teardown. Write a `src/runtime/lifecycle.js` that owns the module registry:
- - `register(name, { start, stop, dispose })`.
- - `teardownAll()` calls `dispose` on each in reverse registration order.
+ - `register(name, { start, stop, dispose })`.
+ - `teardownAll()` calls `dispose` on each in reverse registration order.
2. **Render-on-demand** — adapt [src/viewer.js](../../src/viewer.js)'s render loop:
- - Replace the unconditional RAF loop with an `invalidate()` gate.
- - Invalidate on: camera orbit, window resize, texture/material updates, animation active, TalkingHead active, mirror mode active.
- - When nothing demands a frame, skip rendering.
+ - Replace the unconditional RAF loop with an `invalidate()` gate.
+ - Invalidate on: camera orbit, window resize, texture/material updates, animation active, TalkingHead active, mirror mode active.
+ - When nothing demands a frame, skip rendering.
3. **Animation reference counting** — many modules request continuous rendering (TalkingHead idle, mirror, TTS-driven lipsync). Introduce `viewer.requestContinuous(owner)` / `releaseContinuous(owner)`. Render only if count > 0 OR a one-shot invalidate is pending.
4. **Texture/geometry disposal** — on model swap, walk the old scene graph and call `.dispose()` on every `BufferGeometry`, `Material`, and `Texture`. Verify via `renderer.info.memory`.
5. **Throttle landmark detections** — mirror mode (task 12) runs MediaPipe at 30 Hz max; verify this instead of per-RAF.
6. **Web Worker offload** — move whisper-web (task 11) to a Web Worker if not already; move any heavy image processing (task 07 texture projection) to a Worker. Don't block the render thread.
7. **Idle detection** — add a global "user idle" detector (no mouse/keyboard for 60s): pause TalkingHead idle to a slow-blink-only mode, pause mirror mode processing.
8. **Performance budget doc** — `docs/PERFORMANCE.md` (one-time doc, OK here):
- - Budget: 16ms frame at 60 fps idle, 33ms frame budget for mirror/mocap.
- - GPU memory budget per loaded avatar.
- - Tactics (render-on-demand, workers, LOD, throttling).
- - How to profile (Chrome Performance, three.js stats, renderer.info).
+ - Budget: 16ms frame at 60 fps idle, 33ms frame budget for mirror/mocap.
+ - GPU memory budget per loaded avatar.
+ - Tactics (render-on-demand, workers, LOD, throttling).
+ - How to profile (Chrome Performance, three.js stats, renderer.info).
## Audit checklist
diff --git a/prompts/avatar-platform/20-onboarding-flow.md b/prompts/avatar-platform/20-onboarding-flow.md
index de0bd8b13..b67a87305 100644
--- a/prompts/avatar-platform/20-onboarding-flow.md
+++ b/prompts/avatar-platform/20-onboarding-flow.md
@@ -9,25 +9,25 @@ Should be scheduled **after** tasks 04, 06, 07, 08, 14, 16, 18 are in.
## Goal
1. A new user visits the app and within 90 seconds has:
- - A personalized 3D avatar based on their photo.
- - A name entered.
- - A first conversational exchange with the agent.
- - Their state persisted locally for future visits.
+ - A personalized 3D avatar based on their photo.
+ - A name entered.
+ - A first conversational exchange with the agent.
+ - Their state persisted locally for future visits.
2. Returning users land directly in the main experience; onboarding does not re-prompt.
3. Onboarding is skippable — "Use a default avatar and explore" route always available.
## Deliverable
1. **Onboarding controller** `src/onboarding/flow.js`:
- - Steps: `welcome → choose-capture → capture → fast-generating → fast-preview → name → ready` (with `hd-upgrade` happening in the background after `fast-preview`).
- - State machine, explicit transitions, every step has a "back" exit.
+ - Steps: `welcome → choose-capture → capture → fast-generating → fast-preview → name → ready` (with `hd-upgrade` happening in the background after `fast-preview`).
+ - State machine, explicit transitions, every step has a "back" exit.
2. **Welcome** — one-screen hero: "Meet your agent." CTA: "Create my avatar" / secondary "Use a default".
3. **Choose capture** — two tiles: "Scan QR with phone" (opens task 06 desktop QR UI) / "Use webcam" (opens task 04). Third option: "Upload three photos" (file picker, gates only by file count + type).
4. **Fast generating** — loading screen with the fast-path (task 07) running. Subtle copy: "Meeting you…" — 3–5s max on a mid-range machine.
5. **Fast preview** — the avatar appears, rotating in the hero spot. User can:
- - **Retake** — back to capture.
- - **Looks good** — proceed.
- - **Tweak** — open the editor panel (task 16) inline; finishing takes them to "name".
+ - **Retake** — back to capture.
+ - **Looks good** — proceed.
+ - **Tweak** — open the editor panel (task 16) inline; finishing takes them to "name".
6. **HD upgrade (background)** — task 08 runs asynchronously. On completion, a small "HD-ready" toast lets the user accept/dismiss. Accepting hot-swaps the avatar without interrupting flow.
7. **Name** — single input, default suggestion "My Agent". Stored to IndexedDB + sent as system-prompt context to the brain (task 14).
8. **Ready** — opens the agent panel with a welcome message that uses the user's name and avatar description. Agent (task 14 brain) already knows the viewer state.
diff --git a/prompts/avatar-platform/README.md b/prompts/avatar-platform/README.md
index ec8cb968e..56149b1c2 100644
--- a/prompts/avatar-platform/README.md
+++ b/prompts/avatar-platform/README.md
@@ -6,27 +6,29 @@ Self-contained prompt files for replacing the hosted Avaturn integration with a
## Reference repos (all MIT / Apache / MPL)
-| Layer | Repo | Used in tasks |
-|---|---|---|
-| VRM runtime | [pixiv/three-vrm](https://github.com/pixiv/three-vrm) | 02, 09, 12 |
-| Editor | [M3-org/CharacterStudio](https://github.com/M3-org/CharacterStudio) | 03, 16, 17 |
-| Photo → 3D (HD) | [abdallahdib/NextFace](https://github.com/abdallahdib/NextFace) | 08 |
-| Photo → landmarks | [MediaPipe Face Landmarker](https://developers.google.com/mediapipe/solutions/vision/face_landmarker/web_js) | 07, 12 |
-| Talking head + lipsync | [met4citizen/TalkingHead](https://github.com/met4citizen/TalkingHead) | 09 |
-| TTS w/ visemes | [HeadTTS (Kokoro)](https://github.com/met4citizen/TalkingHead) + [rhasspy/Piper](https://github.com/rhasspy/piper) | 10 |
-| STT | [xenova/whisper-web](https://github.com/xenova/whisper-web) | 11 |
-| Mirror mode | [yeemachine/kalidokit](https://github.com/yeemachine/kalidokit) | 12 |
-| Full-body mocap | [ButzYung/SystemAnimatorOnline](https://github.com/ButzYung/SystemAnimatorOnline) | 13 |
-| Local LLM | [mlc-ai/web-llm](https://github.com/mlc-ai/web-llm) | 14 |
+| Layer | Repo | Used in tasks |
+| ---------------------- | ------------------------------------------------------------------------------------------------------------------ | ------------- |
+| VRM runtime | [pixiv/three-vrm](https://github.com/pixiv/three-vrm) | 02, 09, 12 |
+| Editor | [M3-org/CharacterStudio](https://github.com/M3-org/CharacterStudio) | 03, 16, 17 |
+| Photo → 3D (HD) | [abdallahdib/NextFace](https://github.com/abdallahdib/NextFace) | 08 |
+| Photo → landmarks | [MediaPipe Face Landmarker](https://developers.google.com/mediapipe/solutions/vision/face_landmarker/web_js) | 07, 12 |
+| Talking head + lipsync | [met4citizen/TalkingHead](https://github.com/met4citizen/TalkingHead) | 09 |
+| TTS w/ visemes | [HeadTTS (Kokoro)](https://github.com/met4citizen/TalkingHead) + [rhasspy/Piper](https://github.com/rhasspy/piper) | 10 |
+| STT | [xenova/whisper-web](https://github.com/xenova/whisper-web) | 11 |
+| Mirror mode | [yeemachine/kalidokit](https://github.com/yeemachine/kalidokit) | 12 |
+| Full-body mocap | [ButzYung/SystemAnimatorOnline](https://github.com/ButzYung/SystemAnimatorOnline) | 13 |
+| Local LLM | [mlc-ai/web-llm](https://github.com/mlc-ai/web-llm) | 14 |
## Recommended execution order
### Foundation — do these in order, no parallelism
+
1. [01-strip-avaturn.md](./01-strip-avaturn.md) — Remove `@avaturn/sdk`, `@avaturn-live/web-sdk`, rename `AvaturnAgent`. **Blocks everything.**
2. [02-vrm-runtime.md](./02-vrm-runtime.md) — Add `@pixiv/three-vrm`, load VRM into the viewer. **Blocks 03, 09–13, 16.**
3. [03-vendor-character-studio.md](./03-vendor-character-studio.md) — Vendor CharacterStudio's `CharacterManager` into `src/character/`. **Blocks 16, 17.**
### Photo capture pipeline — parallelizable after 02
+
4. [04-desktop-photo-capture.md](./04-desktop-photo-capture.md) — Three-shot webcam capture UI (left/center/right).
5. [05-session-bridge.md](./05-session-bridge.md) — Session store + SSE/WebSocket relay. **Blocks 06.**
6. [06-mobile-capture-route.md](./06-mobile-capture-route.md) — `/m/:sessionId` phone route with QR flow on desktop. **Depends on 05.**
@@ -34,6 +36,7 @@ Self-contained prompt files for replacing the hosted Avaturn integration with a
8. [08-photo-to-avatar-hd.md](./08-photo-to-avatar-hd.md) — Backend path: NextFace GPU service → high-fidelity rebake.
### Animation stack — parallelizable after 02
+
9. [09-talking-head.md](./09-talking-head.md) — Vendor `TalkingHead`, wire to the active VRM.
10. [10-tts-visemes.md](./10-tts-visemes.md) — Browser TTS with phoneme/viseme timestamps. **Depends on 09.**
11. [11-speech-to-text.md](./11-speech-to-text.md) — Replace Web Speech API with whisper-web.
@@ -41,14 +44,17 @@ Self-contained prompt files for replacing the hosted Avaturn integration with a
13. [13-full-body-mocap.md](./13-full-body-mocap.md) — Optional XR Animator-style full-body capture.
### Brain — after 10, 11
+
14. [14-agent-brain.md](./14-agent-brain.md) — Pluggable LLM interface: local (WebLLM) and cloud (Claude/OpenAI).
15. [15-conversation-state.md](./15-conversation-state.md) — Session memory, tool invocations, viewer context.
### Editor + UX — after 03
+
16. [16-character-editor-ui.md](./16-character-editor-ui.md) — Branded side-panel editor driving `CharacterManager`.
17. [17-asset-library.md](./17-asset-library.md) — Browsable VRM asset registry (from CC0 sources).
### Polish
+
18. [18-branding-pass.md](./18-branding-pass.md) — Scrub `avaturn-` everywhere, rename to project brand.
19. [19-performance-dispose.md](./19-performance-dispose.md) — Render-on-demand, GPU disposal, idle throttling.
20. [20-onboarding-flow.md](./20-onboarding-flow.md) — First-run journey: QR → photo → preview → name → ready.
diff --git a/prompts/build/00-stack-e2e-smoke.md b/prompts/build/00-stack-e2e-smoke.md
index 74e97ca82..87f658d3c 100644
--- a/prompts/build/00-stack-e2e-smoke.md
+++ b/prompts/build/00-stack-e2e-smoke.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "End-to-end smoke test of the whole priority stack on a cold browser"
+description: 'End-to-end smoke test of the whole priority stack on a cold browser'
---
# 00 · End-to-end stack smoke test
diff --git a/prompts/build/01-01-wallet-auth-privy.md b/prompts/build/01-01-wallet-auth-privy.md
index 3bd29df17..03f337e44 100644
--- a/prompts/build/01-01-wallet-auth-privy.md
+++ b/prompts/build/01-01-wallet-auth-privy.md
@@ -3,7 +3,7 @@
**Branch:** `feat/auth-privy`
**Stack layer:** 1 (Wallet auth)
**Depends on:** nothing
-**Blocks:** 06-* (onchain registration — needs a wallet the user already holds)
+**Blocks:** 06-\* (onchain registration — needs a wallet the user already holds)
## Why it matters
@@ -11,20 +11,20 @@ Wallet auth is the foundation of the stack. Today [public/wallet-login.js](../..
## Read these first
-| File | Why |
-|:---|:---|
-| [public/wallet-login.js](../../public/wallet-login.js) | Current MetaMask-only flow. You will extend it, not replace it. |
-| [api/auth/siwe/nonce.js](../../api/auth/siwe/nonce.js) | Nonce endpoint — already works, do not touch. |
-| [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) | Verifies the signed message. Works with any EOA that produces an EIP-4361 signature. |
-| [public/login.html](../../public/login.html), [public/register.html](../../public/register.html) | Shells that load `wallet-login.js`. |
-| [api/_lib/auth.js](../../api/_lib/auth.js) | Session cookie issuance — do not duplicate. |
+| File | Why |
+| :----------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------- |
+| [public/wallet-login.js](../../public/wallet-login.js) | Current MetaMask-only flow. You will extend it, not replace it. |
+| [api/auth/siwe/nonce.js](../../api/auth/siwe/nonce.js) | Nonce endpoint — already works, do not touch. |
+| [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) | Verifies the signed message. Works with any EOA that produces an EIP-4361 signature. |
+| [public/login.html](../../public/login.html), [public/register.html](../../public/register.html) | Shells that load `wallet-login.js`. |
+| [api/\_lib/auth.js](../../api/_lib/auth.js) | Session cookie issuance — do not duplicate. |
## Build this
1. Add `@privy-io/react-auth`'s browser-only dependency — **skip** if it requires React. Use `@privy-io/js-sdk-core` (framework-agnostic) instead. Justify the single added dep in the PR description.
2. In [public/wallet-login.js](../../public/wallet-login.js), expose two entry points:
- - `loginWithMetaMask()` — existing flow, unchanged.
- - `loginWithPrivy()` — opens Privy modal, gets an embedded or external wallet, produces an EIP-4361 signature, posts it to `/api/auth/siwe/verify` exactly like the MetaMask path.
+ - `loginWithMetaMask()` — existing flow, unchanged.
+ - `loginWithPrivy()` — opens Privy modal, gets an embedded or external wallet, produces an EIP-4361 signature, posts it to `/api/auth/siwe/verify` exactly like the MetaMask path.
3. Add two buttons to [public/login.html](../../public/login.html) and [public/register.html](../../public/register.html): **"Sign in with MetaMask"** and **"Sign in with Privy"**. Same SIWE backend for both.
4. Add `PRIVY_APP_ID` to `.env.example` (client-side, `VITE_PRIVY_APP_ID`). Document that the user must set this to enable the button; if unset, hide the Privy button.
diff --git a/prompts/build/01-01-wallet-auth-smoke-test.md b/prompts/build/01-01-wallet-auth-smoke-test.md
index 423454ca2..11bd5a9b3 100644
--- a/prompts/build/01-01-wallet-auth-smoke-test.md
+++ b/prompts/build/01-01-wallet-auth-smoke-test.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Smoke-test the SIWE wallet login end-to-end and patch any breakage"
+description: 'Smoke-test the SIWE wallet login end-to-end and patch any breakage'
---
# 01-01 · Wallet auth smoke test
@@ -23,7 +23,7 @@ SIWE endpoints and `wallet-login.js` are in place (2026-04-15). This prompt is a
- [public/wallet-login.js](../../public/wallet-login.js) — SIWE client flow.
- [api/auth/siwe/nonce.js](../../api/auth/siwe/nonce.js) — nonce issuance.
- [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) — signature verification + session issuance.
-- [api/_lib/auth.js](../../api/_lib/auth.js) — `createSession`, `sessionCookie`, `getSessionUser`.
+- [api/\_lib/auth.js](../../api/_lib/auth.js) — `createSession`, `sessionCookie`, `getSessionUser`.
- [api/agents.js](../../api/agents.js) — `/api/agents/me` bootstrap that runs on every page load.
## Build this
@@ -31,19 +31,19 @@ SIWE endpoints and `wallet-login.js` are in place (2026-04-15). This prompt is a
Execute the following and report findings. For anything broken, patch it in the same PR unless it's out of scope (see below).
1. **Cold browser signin path** — private window → `/login` → click wallet → sign → land on `/dashboard/`.
- - Expected: `users` row + `user_wallets` row created on first attempt. Session cookie set. `/api/auth/me` returns the user.
+ - Expected: `users` row + `user_wallets` row created on first attempt. Session cookie set. `/api/auth/me` returns the user.
2. **Repeat login path** — sign out → sign back in with the same wallet.
- - Expected: existing user reused via `user_wallets.address` lookup. No duplicate row. Session rotates (old one destroyed before new one issued).
+ - Expected: existing user reused via `user_wallets.address` lookup. No duplicate row. Session rotates (old one destroyed before new one issued).
3. **Nonce burn** — capture a valid `(message, signature)` from step 1 and `POST /api/auth/siwe/verify` with it a second time.
- - Expected: `nonce_reused` 400, no new session.
+ - Expected: `nonce_reused` 400, no new session.
4. **Domain binding** — craft a SIWE message with a wrong `domain:` line and submit.
- - Expected: `invalid_domain` 400.
+ - Expected: `invalid_domain` 400.
5. **Agent bootstrap** — after login, confirm `GET /api/agents/me` returns an agent (auto-created on first call). Confirm the client in [src/account.js](../../src/account.js) / [src/agent-identity.js](../../src/agent-identity.js) picks it up.
6. **Anonymous path** — hit `/` with no session; `/api/agents/me` must return `{ agent: null }` (not 401).
## Patching rules
-- If any step fails due to a schema mismatch, inspect [api/_lib/db.js](../../api/_lib/db.js) and the migration files; do not invent new columns.
+- If any step fails due to a schema mismatch, inspect [api/\_lib/db.js](../../api/_lib/db.js) and the migration files; do not invent new columns.
- If `APP_ORIGIN` / `ISSUER` env vars are missing, document what's needed in the final report — do **not** hard-code values.
- If the CSP on `/login` blocks `https://esm.sh`, either move `wallet-login.js` into the Vite bundle entry, or widen the CSP for that page only. Prefer bundling.
diff --git a/prompts/build/01-01-wallet-link-existing-account.md b/prompts/build/01-01-wallet-link-existing-account.md
index 8ebc8214b..5b2476943 100644
--- a/prompts/build/01-01-wallet-link-existing-account.md
+++ b/prompts/build/01-01-wallet-link-existing-account.md
@@ -1,13 +1,13 @@
---
mode: agent
-description: "Let an email/password user link a wallet to their existing account without creating a new one"
+description: 'Let an email/password user link a wallet to their existing account without creating a new one'
---
# 01-01 · Link wallet to existing account
## Why it matters
-Today a returning user who signed up with email+password cannot attach a wallet without creating a *second* account. That fragments ownership of agents across two users and breaks the onchain pillar (layer 6) — you want one user → many wallets → many agents. The SIWE verify endpoint already supports a linked branch ([api/auth/siwe/verify.js:114](../../api/auth/siwe/verify.js#L114)); the client just doesn't drive it.
+Today a returning user who signed up with email+password cannot attach a wallet without creating a _second_ account. That fragments ownership of agents across two users and breaks the onchain pillar (layer 6) — you want one user → many wallets → many agents. The SIWE verify endpoint already supports a linked branch ([api/auth/siwe/verify.js:114](../../api/auth/siwe/verify.js#L114)); the client just doesn't drive it.
## Prerequisites
@@ -16,22 +16,22 @@ Today a returning user who signed up with email+password cannot attach a wallet
## Read these first
-| File | Why |
-|:---|:---|
+| File | Why |
+| :------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) | The `link=1` branch — an authenticated caller that signs a nonce should have the wallet attached to the current `userId` instead of creating a new user. Verify the handler already supports this; if not, extend. |
-| [public/wallet-login.js](../../public/wallet-login.js) | Where `completeSignIn(provider)` lives — you'll add a `linkWallet(provider)` sibling. |
-| [api/_lib/auth.js](../../api/_lib/auth.js) | `getSessionUser(req)` — used to know this is a link, not a sign-in. |
-| [api/_lib/schema.sql](../../api/_lib/schema.sql) | `user_wallets` table (line ~143) — linked wallets go here. |
+| [public/wallet-login.js](../../public/wallet-login.js) | Where `completeSignIn(provider)` lives — you'll add a `linkWallet(provider)` sibling. |
+| [api/\_lib/auth.js](../../api/_lib/auth.js) | `getSessionUser(req)` — used to know this is a link, not a sign-in. |
+| [api/\_lib/schema.sql](../../api/_lib/schema.sql) | `user_wallets` table (line ~143) — linked wallets go here. |
## Build this
1. **Confirm or add the link branch in `siwe/verify.js`**:
- - If the request arrives with a valid session cookie AND the signed address is **not already bound to another user**, insert into `user_wallets(user_id, address)` and return `{ linked: true, address }`. Do NOT rotate the session.
- - If the address is already bound to a **different** user, return 409 with a clear error message.
- - If no session, fall through to the existing sign-in/create flow.
+ - If the request arrives with a valid session cookie AND the signed address is **not already bound to another user**, insert into `user_wallets(user_id, address)` and return `{ linked: true, address }`. Do NOT rotate the session.
+ - If the address is already bound to a **different** user, return 409 with a clear error message.
+ - If no session, fall through to the existing sign-in/create flow.
2. **Client helper** in [public/wallet-login.js](../../public/wallet-login.js):
- - Export `linkWallet(provider)` that runs the same EIP-4361 flow as `completeSignIn` but marks the nonce request with `{ intent: 'link' }` and posts to `/api/auth/siwe/verify?intent=link`.
- - On success, dispatch a `wallet:linked` custom event with `{ address, provider }`.
+ - Export `linkWallet(provider)` that runs the same EIP-4361 flow as `completeSignIn` but marks the nonce request with `{ intent: 'link' }` and posts to `/api/auth/siwe/verify?intent=link`.
+ - On success, dispatch a `wallet:linked` custom event with `{ address, provider }`.
3. **Wire from the account/settings page** (see `01-02` for that page) — a "Link a wallet" button that calls `linkWallet('metamask')` or `linkWallet('privy')`.
## Out of scope
diff --git a/prompts/build/01-02-email-password-parity.md b/prompts/build/01-02-email-password-parity.md
index 126172151..964b24e83 100644
--- a/prompts/build/01-02-email-password-parity.md
+++ b/prompts/build/01-02-email-password-parity.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Ensure email/password signup has parity with SIWE: session, user row, agent bootstrap"
+description: 'Ensure email/password signup has parity with SIWE: session, user row, agent bootstrap'
---
# 01-02 · Email/password auth parity
@@ -25,11 +25,11 @@ Wallet is the primary path, but email/password must still work for users without
## Build this
1. **Audit the three code paths side-by-side** (register, password login, SIWE verify) and list what each does:
- - `users` row creation / lookup
- - `user_wallets` row (SIWE only)
- - `destroySession()` before `createSession()`
- - cookie flags (`HttpOnly`, `Secure`, `SameSite`)
- - response shape (`{ user: {...} }`)
+ - `users` row creation / lookup
+ - `user_wallets` row (SIWE only)
+ - `destroySession()` before `createSession()`
+ - cookie flags (`HttpOnly`, `Secure`, `SameSite`)
+ - response shape (`{ user: {...} }`)
2. **Normalize** any field that differs without reason. Pick SIWE's shape as canonical — it's the newest and reviewed.
3. **Agent bootstrap parity** — after a new user registers with email, hitting `GET /api/agents/me` auto-creates the default agent (already true for SIWE because the endpoint is shared). Verify by registering a fresh email and hitting `/dashboard/` — the client-side `AgentIdentity.load()` should succeed.
4. **Logout** — `POST /api/auth/logout` clears the cookie and destroys the session row. Verify `Set-Cookie` has `Max-Age=0` and `sessions.revoked_at` is set.
diff --git a/prompts/build/01-02-session-recovery-and-logout.md b/prompts/build/01-02-session-recovery-and-logout.md
index 964ce0364..611dde3f8 100644
--- a/prompts/build/01-02-session-recovery-and-logout.md
+++ b/prompts/build/01-02-session-recovery-and-logout.md
@@ -7,21 +7,21 @@
## Why it matters
-The SIWE flow works, but the user can't *leave* cleanly or recover a stale session. [/api/agents/me](../../api/agents.js) has been observed 500'ing (see project memory). Wallet auth is only "100% done" when sign-in, sign-out, and the `/me` round-trip are all green.
+The SIWE flow works, but the user can't _leave_ cleanly or recover a stale session. [/api/agents/me](../../api/agents.js) has been observed 500'ing (see project memory). Wallet auth is only "100% done" when sign-in, sign-out, and the `/me` round-trip are all green.
## Read these first
-| File | Why |
-|:---|:---|
-| [api/auth/logout.js](../../api/auth/logout.js) | Exists but has no UI caller. |
-| [api/auth/me.js](../../api/auth/me.js) (or equivalent in `api/auth/`) | The canonical "who am I" endpoint. |
-| [api/agents.js](../../api/agents.js) | Contains the `/api/agents/me` handler and its auto-create-default-agent logic. This is where the 500 comes from. |
-| [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js) | Sign-in state read on page load. |
-| [public/wallet-login.js](../../public/wallet-login.js) | The client session-issuer. |
+| File | Why |
+| :-------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------- |
+| [api/auth/logout.js](../../api/auth/logout.js) | Exists but has no UI caller. |
+| [api/auth/me.js](../../api/auth/me.js) (or equivalent in `api/auth/`) | The canonical "who am I" endpoint. |
+| [api/agents.js](../../api/agents.js) | Contains the `/api/agents/me` handler and its auto-create-default-agent logic. This is where the 500 comes from. |
+| [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js) | Sign-in state read on page load. |
+| [public/wallet-login.js](../../public/wallet-login.js) | The client session-issuer. |
## Build this
-1. **Reproduce the 500.** Call `/api/agents/me` with a valid session cookie but no existing agent row. Capture the stack trace. Fix the underlying cause — likely a null `user_wallets` join or a missing column. Do *not* paper over with a try/catch that swallows errors.
+1. **Reproduce the 500.** Call `/api/agents/me` with a valid session cookie but no existing agent row. Capture the stack trace. Fix the underlying cause — likely a null `user_wallets` join or a missing column. Do _not_ paper over with a try/catch that swallows errors.
2. **Logout button.** In [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js), add a "Sign out" item in the header user menu. POSTs `/api/auth/logout`, clears in-memory state, redirects to `/`.
3. **Session recovery.** On every authenticated page load (`/dashboard`, `/studio` when it ships), call `/api/auth/me` first. If 401, redirect to `/login?return=<current>`. If 500, show a banner "We couldn't load your account — try signing in again" with a logout link.
4. **Agent auto-create safety.** In [api/agents.js](../../api/agents.js), the `/api/agents/me` auto-create path must be idempotent: if a default agent already exists for the user, return it; if not, create it inside a transaction so two racing requests don't both insert.
diff --git a/prompts/build/01-02-wallet-account-section.md b/prompts/build/01-02-wallet-account-section.md
index 8eaa128d4..3b7267c1f 100644
--- a/prompts/build/01-02-wallet-account-section.md
+++ b/prompts/build/01-02-wallet-account-section.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Account page block showing linked wallets with add/remove controls"
+description: 'Account page block showing linked wallets with add/remove controls'
---
# 01-02 · Account page wallet section
@@ -16,27 +16,27 @@ Once `01-01` lands, users can link wallets — but there's no surface that shows
## Read these first
-| File | Why |
-|:---|:---|
-| [public/wallet-login.js](../../public/wallet-login.js) | `linkWallet()` entry point. |
-| [api/auth/me.js](../../api/auth/me.js) | Extend (or confirm) its response includes `wallets: [{ address, linked_at, is_primary }]`. |
-| [api/_lib/schema.sql](../../api/_lib/schema.sql) | `user_wallets` table shape. |
-| [public/dashboard/](../../public/dashboard/) | Dashboard chrome — match header, typography, button styles. |
+| File | Why |
+| :----------------------------------------------------- | :----------------------------------------------------------------------------------------- |
+| [public/wallet-login.js](../../public/wallet-login.js) | `linkWallet()` entry point. |
+| [api/auth/me.js](../../api/auth/me.js) | Extend (or confirm) its response includes `wallets: [{ address, linked_at, is_primary }]`. |
+| [api/\_lib/schema.sql](../../api/_lib/schema.sql) | `user_wallets` table shape. |
+| [public/dashboard/](../../public/dashboard/) | Dashboard chrome — match header, typography, button styles. |
## Build this
1. **Extend `/api/auth/me` response** to include a `wallets` array. One query: `SELECT address, linked_at, is_primary FROM user_wallets WHERE user_id = $1 ORDER BY linked_at`.
2. **New endpoint** `DELETE /api/user-wallets/:address`:
- - Session auth required, ownership check.
- - Reject if it's the only wallet AND the user has no password (would lock them out).
- - Soft-delete is fine; hard-delete is also fine — pick one and note in PR.
+ - Session auth required, ownership check.
+ - Reject if it's the only wallet AND the user has no password (would lock them out).
+ - Soft-delete is fine; hard-delete is also fine — pick one and note in PR.
3. **Account page** at `public/account/index.html` (or wherever is conventional):
- - Fetch `/api/auth/me`, render a "Wallets" section listing each linked wallet with:
- - Truncated address (`0x1234…abcd`), full address on hover.
- - Optional ENS if resolvable (see `01-02-wallet-ens-display.md` — coordinate scope).
- - Linked date, primary indicator.
- - "Remove" button → calls the DELETE endpoint, confirms, refreshes list.
- - "Link another wallet" button → opens the same modal/flow used on sign-in, but calls `linkWallet()` from `01-01`.
+ - Fetch `/api/auth/me`, render a "Wallets" section listing each linked wallet with:
+ - Truncated address (`0x1234…abcd`), full address on hover.
+ - Optional ENS if resolvable (see `01-02-wallet-ens-display.md` — coordinate scope).
+ - Linked date, primary indicator.
+ - "Remove" button → calls the DELETE endpoint, confirms, refreshes list.
+ - "Link another wallet" button → opens the same modal/flow used on sign-in, but calls `linkWallet()` from `01-01`.
4. **Empty state**: if `wallets` is empty, show a friendly "Link your first wallet →" CTA that opens the same flow.
## Out of scope
diff --git a/prompts/build/01-02-wallet-ens-display.md b/prompts/build/01-02-wallet-ens-display.md
index f60f34c3a..baf1e12c7 100644
--- a/prompts/build/01-02-wallet-ens-display.md
+++ b/prompts/build/01-02-wallet-ens-display.md
@@ -7,8 +7,8 @@ Users see `0xabc…1234` today. That's hostile. Showing `nich.eth` or `nich.base
## Context
- SIWE verify path: [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js).
-- Linked-wallet table: `user_wallets` in [api/_lib/schema.sql](../../api/_lib/schema.sql).
-- Session helper: `getSessionUser` in [api/_lib/auth.js](../../api/_lib/auth.js).
+- Linked-wallet table: `user_wallets` in [api/\_lib/schema.sql](../../api/_lib/schema.sql).
+- Session helper: `getSessionUser` in [api/\_lib/auth.js](../../api/_lib/auth.js).
- Dashboard render: [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js).
## What to build
@@ -17,10 +17,10 @@ Users see `0xabc…1234` today. That's hostile. Showing `nich.eth` or `nich.base
- `GET ?address=0x…&chain_id=1|8453`. Public (no session required — names are public).
- Resolves via public RPC, with a 24h cache keyed on `(address, chain_id)`.
- - `chain_id=1` → ENS (`name.eth`) via reverse record.
- - `chain_id=8453` → basename via the Base name registrar. Fall back to ENS mainnet if no basename.
+ - `chain_id=1` → ENS (`name.eth`) via reverse record.
+ - `chain_id=8453` → basename via the Base name registrar. Fall back to ENS mainnet if no basename.
- Response: `{ address, name: "nich.eth" | null, avatar: "https://…" | null, chain_id, ttl }`.
-- Cache: use the existing rate-limit/kv pattern in [api/_lib/rate-limit.js](../../api/_lib/rate-limit.js) (Neon `kv` table or equivalent — reuse, don't invent).
+- Cache: use the existing rate-limit/kv pattern in [api/\_lib/rate-limit.js](../../api/_lib/rate-limit.js) (Neon `kv` table or equivalent — reuse, don't invent).
- Failures (RPC down, no record) → `{ name: null }` with 200, not 5xx.
### Persist on link
diff --git a/prompts/build/01-02-wallet-nav-indicator.md b/prompts/build/01-02-wallet-nav-indicator.md
index ae3f2ae2e..fba212228 100644
--- a/prompts/build/01-02-wallet-nav-indicator.md
+++ b/prompts/build/01-02-wallet-nav-indicator.md
@@ -19,13 +19,13 @@ Source of truth: `GET /api/auth/me` on page load + local cache invalidated on 40
## Read these first
-| File | Why |
-|:---|:---|
-| [api/auth/me.js](../../api/auth/me.js) | Shape of the `user` object — `{ id, email, display_name, plan, avatar_url }`. Note there is NO `wallet_address` field on the returned user today. |
-| [api/_lib/auth.js](../../api/_lib/auth.js) | `getSessionUser` — source SQL. You may need to join `user_wallets` here so `/api/auth/me` returns the primary wallet. |
-| [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js) | Native DOM pattern to follow. |
-| [public/wallet-login.js](../../public/wallet-login.js) | Wallet flow — nothing to change here, but learn what a wallet-created user's `email` looks like (`[email protected]`) so you can hide that ugly string. |
-| [style.css](../../style.css) | Token palette — use `--accent`, `--bg-elevated`, etc. Don't introduce new colors. |
+| File | Why |
+| :------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| [api/auth/me.js](../../api/auth/me.js) | Shape of the `user` object — `{ id, email, display_name, plan, avatar_url }`. Note there is NO `wallet_address` field on the returned user today. |
+| [api/\_lib/auth.js](../../api/_lib/auth.js) | `getSessionUser` — source SQL. You may need to join `user_wallets` here so `/api/auth/me` returns the primary wallet. |
+| [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js) | Native DOM pattern to follow. |
+| [public/wallet-login.js](../../public/wallet-login.js) | Wallet flow — nothing to change here, but learn what a wallet-created user's `email` looks like (`[email protected]`) so you can hide that ugly string. |
+| [style.css](../../style.css) | Token palette — use `--accent`, `--bg-elevated`, etc. Don't introduce new colors. |
## Build this
@@ -61,6 +61,7 @@ Menu: absolute-positioned popover. Close on outside click, Esc, or selection.
### 3. Mount on every page
Add a script tag + chip mount to:
+
- [public/dashboard/index.html](../../public/dashboard/) — top-right, replacing whatever's there.
- `public/studio/index.html` (if it exists from the widget-studio prompts — if not, skip).
- [public/agent/index.html](../../public/agent/index.html) — top-right.
@@ -82,9 +83,11 @@ Do not modify the landing page [index.html](../../index.html) — it has its own
## Deliverables
**New:**
+
- `src/components/wallet-chip.js`
**Modified:**
+
- [api/auth/me.js](../../api/auth/me.js) — include `wallet` on user.
- [public/dashboard/index.html](../../public/dashboard/) — mount chip.
- [public/agent/index.html](../../public/agent/index.html) — mount chip.
diff --git a/prompts/build/01-03-link-wallet-to-existing-account.md b/prompts/build/01-03-link-wallet-to-existing-account.md
index cfe938d13..8d415fecc 100644
--- a/prompts/build/01-03-link-wallet-to-existing-account.md
+++ b/prompts/build/01-03-link-wallet-to-existing-account.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Let a signed-in email user link a wallet without creating a second account"
+description: 'Let a signed-in email user link a wallet without creating a second account'
---
# 01-03 · Link wallet to existing account
@@ -16,18 +16,18 @@ If a user signs up with email then later connects a wallet, they get a second ph
## Read these first
- [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) — current "find or create user" branch.
-- [api/_lib/auth.js](../../api/_lib/auth.js) — `getSessionUser`, `createSession`.
+- [api/\_lib/auth.js](../../api/_lib/auth.js) — `getSessionUser`, `createSession`.
- Schema for `user_wallets` in the Neon DB (see [api/CLAUDE.md](../../api/CLAUDE.md) table list).
## Build this
-1. **Modify `POST /api/auth/siwe/verify`** to check for an existing session *before* the find-or-create branch. If a session exists:
- - If `user_wallets.address` is unused → insert `(user_id=session.user_id, address, chain_id, is_primary=false)`. Return the *existing* user (do not rotate session).
- - If `user_wallets.address` belongs to the *current* user → idempotent success.
- - If `user_wallets.address` belongs to a *different* user → return `409 wallet_in_use` with a generic message (no user leakage).
+1. **Modify `POST /api/auth/siwe/verify`** to check for an existing session _before_ the find-or-create branch. If a session exists:
+ - If `user_wallets.address` is unused → insert `(user_id=session.user_id, address, chain_id, is_primary=false)`. Return the _existing_ user (do not rotate session).
+ - If `user_wallets.address` belongs to the _current_ user → idempotent success.
+ - If `user_wallets.address` belongs to a _different_ user → return `409 wallet_in_use` with a generic message (no user leakage).
2. **New client entry point** — add a "Link wallet" button to [public/dashboard/index.html](../../public/dashboard/index.html). Reuse [public/wallet-login.js](../../public/wallet-login.js) flow, but:
- - POST to the same `/api/auth/siwe/verify` endpoint (which now handles the linked case).
- - On success, show the linked address and update `users.wallet_address` if still null.
+ - POST to the same `/api/auth/siwe/verify` endpoint (which now handles the linked case).
+ - On success, show the linked address and update `users.wallet_address` if still null.
3. **List wallets** — add `GET /api/auth/wallets` returning `[{ address, chain_id, is_primary, last_used_at }]` for the current session. Use the session auth helper only — no bearer.
4. **Remove a wallet** — add `DELETE /api/auth/wallets/:address`. Cannot remove the primary if it's the only one. Update `users.wallet_address` to the next remaining primary if applicable.
diff --git a/prompts/build/01-03-primary-wallet-selection.md b/prompts/build/01-03-primary-wallet-selection.md
index 751815ccb..6f064f9af 100644
--- a/prompts/build/01-03-primary-wallet-selection.md
+++ b/prompts/build/01-03-primary-wallet-selection.md
@@ -6,9 +6,9 @@
## Context
-- Schema: `users.wallet_address`, `user_wallets(user_id, address, chain_id, created_at)` in [api/_lib/schema.sql](../../api/_lib/schema.sql).
+- Schema: `users.wallet_address`, `user_wallets(user_id, address, chain_id, created_at)` in [api/\_lib/schema.sql](../../api/_lib/schema.sql).
- Linking endpoints: `api/auth/siwe/link.js` (from 01-01).
-- Session helper: `getSessionUser` in [api/_lib/auth.js](../../api/_lib/auth.js).
+- Session helper: `getSessionUser` in [api/\_lib/auth.js](../../api/_lib/auth.js).
- Dashboard wallet section: [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js).
## What to build
@@ -27,9 +27,9 @@ One-time backfill (include in the same migration): for each user with ≥1 walle
- Session-authed. Body: `{ address }`.
- In a single transaction:
- 1. Verify the address belongs to the caller in `user_wallets` → else 404.
- 2. `update user_wallets set is_primary = (address = $1) where user_id = $me`.
- 3. `update users set wallet_address = $1 where id = $me`.
+ 1. Verify the address belongs to the caller in `user_wallets` → else 404.
+ 2. `update user_wallets set is_primary = (address = $1) where user_id = $me`.
+ 3. `update users set wallet_address = $1 where id = $me`.
- Returns `{ ok: true, primary: address }`.
### Dashboard UI
diff --git a/prompts/build/01-04-session-expiry-ux.md b/prompts/build/01-04-session-expiry-ux.md
index 418658824..4c72a0ff5 100644
--- a/prompts/build/01-04-session-expiry-ux.md
+++ b/prompts/build/01-04-session-expiry-ux.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Handle expired sessions gracefully across the SPA and public pages"
+description: 'Handle expired sessions gracefully across the SPA and public pages'
---
# 01-04 · Session expiry UX
@@ -17,7 +17,7 @@ Right now, when a session expires, the dashboard throws `401` noisily and the us
- [src/account.js](../../src/account.js) — current authenticated fetch client.
- [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js) — dashboard fetch usage.
-- [api/_lib/auth.js](../../api/_lib/auth.js) — session TTL / revocation.
+- [api/\_lib/auth.js](../../api/_lib/auth.js) — session TTL / revocation.
## Build this
diff --git a/prompts/build/01-04-siwe-hardening.md b/prompts/build/01-04-siwe-hardening.md
index 2b0fd0fde..a9d4683d4 100644
--- a/prompts/build/01-04-siwe-hardening.md
+++ b/prompts/build/01-04-siwe-hardening.md
@@ -9,7 +9,7 @@ Wallet auth is user-facing and unauthenticated at the entry point. Nonce reuse,
- Nonce mint: [api/auth/siwe/nonce.js](../../api/auth/siwe/nonce.js).
- Verify/burn: [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js).
- Link (from 01-01): `api/auth/siwe/link.js`.
-- Shared rate limit: [api/_lib/rate-limit.js](../../api/_lib/rate-limit.js).
+- Shared rate limit: [api/\_lib/rate-limit.js](../../api/_lib/rate-limit.js).
## What to build
@@ -24,7 +24,7 @@ Confirm (or add):
### Rate limits
-Apply via [api/_lib/rate-limit.js](../../api/_lib/rate-limit.js):
+Apply via [api/\_lib/rate-limit.js](../../api/_lib/rate-limit.js):
- `POST /api/auth/siwe/nonce` — 20 / 10min per IP, 5 / 10min per `(IP, requested-address)` if the client sends one.
- `POST /api/auth/siwe/verify` — 10 / 10min per IP, 5 / 10min per address.
diff --git a/prompts/build/01-04-wallet-chain-switch.md b/prompts/build/01-04-wallet-chain-switch.md
index 53474cfc7..e7a37cfe9 100644
--- a/prompts/build/01-04-wallet-chain-switch.md
+++ b/prompts/build/01-04-wallet-chain-switch.md
@@ -20,13 +20,13 @@ Plus: a passive network pill in the wallet chip showing current chain name + col
## Read these first
-| File | Why |
-|:---|:---|
-| [src/erc8004/abi.js](../../src/erc8004/abi.js) | `REGISTRY_DEPLOYMENTS` — source of truth for supported chains. |
-| [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js) | Existing `connectWallet`. See what chain check (if any) is there. |
-| [public/wallet-login.js](../../public/wallet-login.js) | Current sign-in — reads `chainId` but does nothing with it. |
-| [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) | Persists `chain_id` on `user_wallets`. No guard server-side — that's fine, guard is UX-only. |
-| `src/components/wallet-chip.js` (from 01-02) | Where the network pill mounts. |
+| File | Why |
+| :------------------------------------------------------------------- | :------------------------------------------------------------------------------------------- |
+| [src/erc8004/abi.js](../../src/erc8004/abi.js) | `REGISTRY_DEPLOYMENTS` — source of truth for supported chains. |
+| [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js) | Existing `connectWallet`. See what chain check (if any) is there. |
+| [public/wallet-login.js](../../public/wallet-login.js) | Current sign-in — reads `chainId` but does nothing with it. |
+| [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) | Persists `chain_id` on `user_wallets`. No guard server-side — that's fine, guard is UX-only. |
+| `src/components/wallet-chip.js` (from 01-02) | Where the network pill mounts. |
## Build this
@@ -36,13 +36,33 @@ Create `src/lib/chains.js`:
```js
export const CHAINS = {
- 1: { name: 'Ethereum', short: 'ETH', color: '#627eea', rpc: null, explorer: 'https://etherscan.io' },
- 8453: { name: 'Base', short: 'BASE', color: '#0052ff', rpc: 'https://mainnet.base.org', explorer: 'https://basescan.org' },
- 84532: { name: 'Base Sepolia', short: 'B-SEP',color: '#88aaff', rpc: 'https://sepolia.base.org', explorer: 'https://sepolia.basescan.org' },
- // Add more as needed.
+ 1: {
+ name: 'Ethereum',
+ short: 'ETH',
+ color: '#627eea',
+ rpc: null,
+ explorer: 'https://etherscan.io',
+ },
+ 8453: {
+ name: 'Base',
+ short: 'BASE',
+ color: '#0052ff',
+ rpc: 'https://mainnet.base.org',
+ explorer: 'https://basescan.org',
+ },
+ 84532: {
+ name: 'Base Sepolia',
+ short: 'B-SEP',
+ color: '#88aaff',
+ rpc: 'https://sepolia.base.org',
+ explorer: 'https://sepolia.basescan.org',
+ },
+ // Add more as needed.
};
-export function chainInfo(id) { return CHAINS[Number(id)] || { name: `Chain ${id}`, short: 'UNK', color: '#777' }; }
+export function chainInfo(id) {
+ return CHAINS[Number(id)] || { name: `Chain ${id}`, short: 'UNK', color: '#777' };
+}
export const TARGET_CHAIN_ID = Number(import.meta.env.VITE_TARGET_CHAIN_ID) || 84532;
```
@@ -54,8 +74,12 @@ Also document `VITE_TARGET_CHAIN_ID` in `.env.example`.
Create `src/lib/network-guard.js`:
```js
-export async function ensureChain(targetId) { /* returns true if on target chain after prompt, false if user cancelled */ }
-export async function switchOrAdd(provider, chainId) { /* wallet_switchEthereumChain → wallet_addEthereumChain */ }
+export async function ensureChain(targetId) {
+ /* returns true if on target chain after prompt, false if user cancelled */
+}
+export async function switchOrAdd(provider, chainId) {
+ /* wallet_switchEthereumChain → wallet_addEthereumChain */
+}
```
Use dynamic `BrowserProvider` from esm.sh to keep the file CDN-loadable like `wallet-login.js`.
@@ -79,10 +103,12 @@ Extend `src/components/wallet-chip.js` (from 01-02) to show the current chain as
## Deliverables
**New:**
+
- `src/lib/chains.js`
- `src/lib/network-guard.js`
**Modified:**
+
- [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js) — add `ensureChain` calls before each write path.
- `src/components/wallet-chip.js` — network pill + `chainChanged` listener.
- `.env.example` — document `VITE_TARGET_CHAIN_ID`.
diff --git a/prompts/build/02-01-selfie-capture-ui.md b/prompts/build/02-01-selfie-capture-ui.md
index 96cf26f38..4930dd394 100644
--- a/prompts/build/02-01-selfie-capture-ui.md
+++ b/prompts/build/02-01-selfie-capture-ui.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "First-party camera capture page that emits a JPEG blob as selfie:ready"
+description: 'First-party camera capture page that emits a JPEG blob as selfie:ready'
---
# 02-01 · Selfie capture UI
@@ -17,24 +17,24 @@ This prompt is **capture only** — it emits a blob. Upload is 02-02, generation
## Read these first
-| File | Why |
-|:---|:---|
+| File | Why |
+| :------------------------------------------------------------------- | :------------------------------------------------------------- |
| [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js) | Existing RPM iframe flow — to understand what we're replacing. |
-| [public/dashboard/index.html](../../public/dashboard/index.html) | Chrome + CSS to match. |
-| [src/features/](../../src/features/) | Pattern for feature-flagged modules. Follow it. |
-| [api/_lib/auth.js](../../api/_lib/auth.js) | Session requirement for downstream upload. |
+| [public/dashboard/index.html](../../public/dashboard/index.html) | Chrome + CSS to match. |
+| [src/features/](../../src/features/) | Pattern for feature-flagged modules. Follow it. |
+| [api/\_lib/auth.js](../../api/_lib/auth.js) | Session requirement for downstream upload. |
## Build this
1. **New page** `public/selfie/index.html`:
- - Full-viewport dark layout matching the dashboard chrome.
- - Title, a one-sentence primer, a big centered `<video>` element (~640×640 square framing), shutter button, retake button, "Use this photo" button.
- - Mobile-first — camera should be usable on a phone.
+ - Full-viewport dark layout matching the dashboard chrome.
+ - Title, a one-sentence primer, a big centered `<video>` element (~640×640 square framing), shutter button, retake button, "Use this photo" button.
+ - Mobile-first — camera should be usable on a phone.
2. **New module** `public/selfie/selfie.js`:
- - `startCamera()` → calls `navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user', width: 1024, height: 1024 }, audio: false })`, pipes to `<video>`.
- - Graceful error if permission denied: show a card with "Enable camera in your browser settings" and a text link to the upload path (there is already a file-upload path in the dashboard — link to it).
- - `capture()` → draws the `<video>` frame to a hidden `<canvas>`, exports a JPEG blob at quality `0.92`. Stop the media tracks.
- - Preview the captured JPEG, offer "Retake" (restarts camera) or "Use this photo" (dispatches a `CustomEvent('selfie:ready', { detail: { blob, width, height } })` on `document`).
+ - `startCamera()` → calls `navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user', width: 1024, height: 1024 }, audio: false })`, pipes to `<video>`.
+ - Graceful error if permission denied: show a card with "Enable camera in your browser settings" and a text link to the upload path (there is already a file-upload path in the dashboard — link to it).
+ - `capture()` → draws the `<video>` frame to a hidden `<canvas>`, exports a JPEG blob at quality `0.92`. Stop the media tracks.
+ - Preview the captured JPEG, offer "Retake" (restarts camera) or "Use this photo" (dispatches a `CustomEvent('selfie:ready', { detail: { blob, width, height } })` on `document`).
3. **Route** in [vercel.json](../../vercel.json): `/selfie` → `public/selfie/index.html`.
4. **Redirect if unauthenticated**: on load, `fetch('/api/auth/me')`; if 401, `location.href = '/login?next=/selfie'`.
@@ -44,7 +44,7 @@ This prompt is **capture only** — it emits a blob. Upload is 02-02, generation
- Generating the avatar (02-03).
- Face-detection / quality scoring (could be added as 02-05).
- Video/multi-angle capture — single frontal frame is the contract.
-- Any fallback to RPM's iframe. RPM is retired as the capture step; it may remain as an adapter option in 02-07 for *generation*.
+- Any fallback to RPM's iframe. RPM is retired as the capture step; it may remain as an adapter option in 02-07 for _generation_.
## Deliverables
diff --git a/prompts/build/02-02-avatar-generation-pipeline.md b/prompts/build/02-02-avatar-generation-pipeline.md
index 7b7556043..c98d24076 100644
--- a/prompts/build/02-02-avatar-generation-pipeline.md
+++ b/prompts/build/02-02-avatar-generation-pipeline.md
@@ -11,12 +11,12 @@
## Read these first
-| File | Why |
-|:---|:---|
-| [src/avatar-creator.js](../../src/avatar-creator.js) | Existing Avaturn wrapper. Understand `initOptions.url` (session URL with a pre-seeded selfie). |
-| [api/avatars/presign.js](../../api/avatars/presign.js), [api/avatars/index.js](../../api/avatars/index.js) | R2 presign + metadata write. Reuse, don't duplicate. |
-| [api/_lib/](../../api/_lib/) | Auth middleware (`requireAuth()`), Neon client, response helpers. |
-| [public/dashboard/selfie.html](../../public/dashboard/selfie.html) *(from 02-01)* | The caller. Its POST body shape defines this endpoint's input. |
+| File | Why |
+| :--------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------- |
+| [src/avatar-creator.js](../../src/avatar-creator.js) | Existing Avaturn wrapper. Understand `initOptions.url` (session URL with a pre-seeded selfie). |
+| [api/avatars/presign.js](../../api/avatars/presign.js), [api/avatars/index.js](../../api/avatars/index.js) | R2 presign + metadata write. Reuse, don't duplicate. |
+| [api/\_lib/](../../api/_lib/) | Auth middleware (`requireAuth()`), Neon client, response helpers. |
+| [public/dashboard/selfie.html](../../public/dashboard/selfie.html) _(from 02-01)_ | The caller. Its POST body shape defines this endpoint's input. |
## Build this
@@ -25,12 +25,13 @@
- **Auth:** required (`requireAuth()`).
- **Body:** `multipart/form-data` with a single `photo` field (JPEG, ≤ 4 MB). Reject anything else with 400.
- **Pipeline:**
- 1. Stream the JPEG into a temp buffer. Reject non-JPEG magic bytes (`0xFFD8`).
- 2. Upload the selfie to R2 under `selfies/<user_id>/<uuid>.jpg` — private, not publicly listable.
- 3. Call the Avaturn (or equivalent) generation API with the R2 signed-read URL for the selfie. Env var: `AVATAR_GENERATION_API_KEY`. Document in `.env.example`.
- 4. Poll the generation job until `status=ready` or timeout (90s). On timeout, return `202` with `{ job_id }` so the client can poll `GET /api/avatars/from-selfie/:job_id`.
- 5. On success, fetch the generated GLB, stream it to R2 under `avatars/<user_id>/<uuid>.glb`, and create an `avatars` row via the same internal helper used by `POST /api/avatars`.
- 6. Return the created avatar row (same shape as `POST /api/avatars`).
+
+ 1. Stream the JPEG into a temp buffer. Reject non-JPEG magic bytes (`0xFFD8`).
+ 2. Upload the selfie to R2 under `selfies/<user_id>/<uuid>.jpg` — private, not publicly listable.
+ 3. Call the Avaturn (or equivalent) generation API with the R2 signed-read URL for the selfie. Env var: `AVATAR_GENERATION_API_KEY`. Document in `.env.example`.
+ 4. Poll the generation job until `status=ready` or timeout (90s). On timeout, return `202` with `{ job_id }` so the client can poll `GET /api/avatars/from-selfie/:job_id`.
+ 5. On success, fetch the generated GLB, stream it to R2 under `avatars/<user_id>/<uuid>.glb`, and create an `avatars` row via the same internal helper used by `POST /api/avatars`.
+ 6. Return the created avatar row (same shape as `POST /api/avatars`).
- **Status endpoint:** `GET /api/avatars/from-selfie/:job_id` — returns `{ status: 'pending' | 'ready' | 'failed', avatar?: {...}, error?: string }`.
@@ -40,7 +41,7 @@ Only validate at the boundary: reject bad input, surface upstream provider failu
### Zero-new-dep rule
-Use `@aws-sdk/client-s3` (already present). For multipart parsing on Vercel serverless, use `busboy` *only if nothing already in the repo parses multipart* — grep first. If a helper exists, use it.
+Use `@aws-sdk/client-s3` (already present). For multipart parsing on Vercel serverless, use `busboy` _only if nothing already in the repo parses multipart_ — grep first. If a helper exists, use it.
## Out of scope
diff --git a/prompts/build/02-02-selfie-upload-r2.md b/prompts/build/02-02-selfie-upload-r2.md
index fb3470a5c..e25394612 100644
--- a/prompts/build/02-02-selfie-upload-r2.md
+++ b/prompts/build/02-02-selfie-upload-r2.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Presign + upload the captured selfie to R2 under user-scoped key"
+description: 'Presign + upload the captured selfie to R2 under user-scoped key'
---
# 02-02 · Selfie upload to R2
@@ -18,31 +18,32 @@ Second step of the magic moment. The selfie blob from 02-01 must land in R2 unde
- [api/avatars/presign.js](../../api/avatars/presign.js) — canonical presigned PUT flow.
- [api/avatars/index.js](../../api/avatars/index.js) — the "register after upload" pattern including `headObject()` size check.
-- [api/_lib/r2.js](../../api/_lib/r2.js) — presign helpers.
+- [api/\_lib/r2.js](../../api/_lib/r2.js) — presign helpers.
- [api/CLAUDE.md](../../api/CLAUDE.md) — key format: `u/{userId}/selfies/{timestamp}.jpg`.
## Build this
1. **New endpoint** `api/selfies/presign.js`:
- - Session auth required (no anonymous selfies).
- - Body: `{ content_type: 'image/jpeg', size: number }`.
- - Validate: content_type ∈ {`image/jpeg`,`image/png`}, size ≤ 8 MB.
- - Return `{ upload_url, storage_key, headers }`. Key: `u/${userId}/selfies/${Date.now()}.jpg`.
- - Rate-limit: `limits.upload(userId)`.
+ - Session auth required (no anonymous selfies).
+ - Body: `{ content_type: 'image/jpeg', size: number }`.
+ - Validate: content_type ∈ {`image/jpeg`,`image/png`}, size ≤ 8 MB.
+ - Return `{ upload_url, storage_key, headers }`. Key: `u/${userId}/selfies/${Date.now()}.jpg`.
+ - Rate-limit: `limits.upload(userId)`.
2. **New endpoint** `api/selfies/index.js`:
- - `POST` after upload: body `{ storage_key }`. Verify `headObject(key)`, verify key prefix matches current user, insert row into a new `selfies` table (or reuse `avatars` with `source='selfie'` — check existing schema; if adding a table, document the migration in `schema.sql`).
- - Returns `{ selfie: { id, storage_key, created_at } }`.
- - `GET` list: last 10 selfies for the user.
- - `DELETE /api/selfies/:id`: soft-delete, also queues R2 object deletion.
+ - `POST` after upload: body `{ storage_key }`. Verify `headObject(key)`, verify key prefix matches current user, insert row into a new `selfies` table (or reuse `avatars` with `source='selfie'` — check existing schema; if adding a table, document the migration in `schema.sql`).
+ - Returns `{ selfie: { id, storage_key, created_at } }`.
+ - `GET` list: last 10 selfies for the user.
+ - `DELETE /api/selfies/:id`: soft-delete, also queues R2 object deletion.
3. **Client wiring** in `public/selfie/selfie.js`:
- - Listen to the `selfie:ready` event from 02-01.
- - Call `/api/selfies/presign` → `PUT` the blob → `POST /api/selfies` → show "Selfie saved." with the returned `selfie.id`.
- - Preserve the blob in memory so the next step (02-03) can start immediately without a re-download.
+ - Listen to the `selfie:ready` event from 02-01.
+ - Call `/api/selfies/presign` → `PUT` the blob → `POST /api/selfies` → show "Selfie saved." with the returned `selfie.id`.
+ - Preserve the blob in memory so the next step (02-03) can start immediately without a re-download.
4. **Route** both endpoints in [vercel.json](../../vercel.json).
## Schema note
If a `selfies` table doesn't exist, adding it is **a schema change** — per CLAUDE.md, this requires explicit ask. Either:
+
- (Preferred) Reuse `avatars` with `source='selfie'`, `content_type='image/jpeg'` and skip the size-per-avatar quota.
- Or halt and surface the migration before writing it.
diff --git a/prompts/build/02-03-avatar-to-agent-link.md b/prompts/build/02-03-avatar-to-agent-link.md
index 6b9a9cf94..7de0972a9 100644
--- a/prompts/build/02-03-avatar-to-agent-link.md
+++ b/prompts/build/02-03-avatar-to-agent-link.md
@@ -3,28 +3,28 @@
**Branch:** `feat/avatar-agent-link`
**Stack layer:** 2 (Selfie → agent creation)
**Depends on:** 02-01
-**Blocks:** 03-* (edit), 04-* (embed assumes every avatar has an agent)
+**Blocks:** 03-_ (edit), 04-_ (embed assumes every avatar has an agent)
## Why it matters
-Today the database has `avatars` and `agent_identities` but nothing binds them on creation. A user finishes the selfie flow and has a 3D mesh — but no *agent*, which is the actual product. This prompt makes "avatar" and "agent" inseparable from the first save.
+Today the database has `avatars` and `agent_identities` but nothing binds them on creation. A user finishes the selfie flow and has a 3D mesh — but no _agent_, which is the actual product. This prompt makes "avatar" and "agent" inseparable from the first save.
## Read these first
-| File | Why |
-|:---|:---|
-| [api/avatars/index.js](../../api/avatars/index.js) | Where a new avatar record is written. This is the hook point. |
-| [api/agents.js](../../api/agents.js) | Agent creation + `/api/agents/me` + default-agent logic. |
-| [src/agent-identity.js](../../src/agent-identity.js) | Client-side identity model. |
-| [api/_lib/](../../api/_lib/) migrations | Confirm the `agent_identities` schema (avatar_id column exists or needs adding). |
+| File | Why |
+| :--------------------------------------------------- | :------------------------------------------------------------------------------- |
+| [api/avatars/index.js](../../api/avatars/index.js) | Where a new avatar record is written. This is the hook point. |
+| [api/agents.js](../../api/agents.js) | Agent creation + `/api/agents/me` + default-agent logic. |
+| [src/agent-identity.js](../../src/agent-identity.js) | Client-side identity model. |
+| [api/\_lib/](../../api/_lib/) migrations | Confirm the `agent_identities` schema (avatar_id column exists or needs adding). |
## Build this
1. **Schema check.** Confirm `agent_identities.avatar_id` exists and is nullable with a FK to `avatars(id) on delete set null`. If missing, add a migration `003_agent_avatar_fk.sql` (or next free number — verify with `ls api/_lib/migrations/`).
2. **Server-side link on first avatar.** In [api/avatars/index.js](../../api/avatars/index.js) `POST` handler, after the avatar row is created:
- - If the user has no agent yet, create one inside the same transaction with `avatar_id = newAvatar.id` and a sensible default name (derive from avatar name or user handle).
- - If the user has exactly one agent and that agent has `avatar_id IS NULL`, bind the new avatar to it.
- - If the user has ≥2 agents or their sole agent already has an avatar, do nothing — leave the avatar unbound and return it normally.
+ - If the user has no agent yet, create one inside the same transaction with `avatar_id = newAvatar.id` and a sensible default name (derive from avatar name or user handle).
+ - If the user has exactly one agent and that agent has `avatar_id IS NULL`, bind the new avatar to it.
+ - If the user has ≥2 agents or their sole agent already has an avatar, do nothing — leave the avatar unbound and return it normally.
3. **Return shape.** The POST response gains an optional `agent` field: `{ id, name, slug }` if a link happened, absent otherwise.
4. **Client.** In [src/account.js](../../src/account.js), surface the `agent` field from the POST response. Dashboard's success state shows "Avatar saved and bound to agent <name>".
@@ -32,7 +32,7 @@ Today the database has `avatars` and `agent_identities` but nothing binds them o
- Do not add multi-agent UI.
- Do not migrate existing orphan avatars — just fix the creation path. A separate one-off script is fine as a follow-up prompt.
-- Do not touch onchain identity yet — that's 06-*.
+- Do not touch onchain identity yet — that's 06-\*.
## Acceptance
diff --git a/prompts/build/02-03-selfie-to-avatar-pipeline.md b/prompts/build/02-03-selfie-to-avatar-pipeline.md
index 90f533b3d..3de265a35 100644
--- a/prompts/build/02-03-selfie-to-avatar-pipeline.md
+++ b/prompts/build/02-03-selfie-to-avatar-pipeline.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Wire the uploaded selfie to the avatar-generation pipeline (Avaturn or chosen provider)"
+description: 'Wire the uploaded selfie to the avatar-generation pipeline (Avaturn or chosen provider)'
---
# 02-03 · Selfie → avatar pipeline
@@ -18,32 +18,32 @@ The magic moment itself. A JPEG on R2 must become a rigged GLB at `/api/avatars/
- [src/avatar-creator.js](../../src/avatar-creator.js) — existing Avaturn SDK integration (client-side).
- [api/avatars/index.js](../../api/avatars/index.js) — how generated avatars get registered.
-- [api/_lib/r2.js](../../api/_lib/r2.js) — `presignGet` for handing a signed URL to a third-party generator.
+- [api/\_lib/r2.js](../../api/_lib/r2.js) — `presignGet` for handing a signed URL to a third-party generator.
## Build this
1. **Decision doc (one paragraph, in PR description)**: are we calling Avaturn (or Ready Player Me, or a self-hosted pipeline) from the **client** (SDK) or the **server** (REST API)? The rest of this prompt assumes server-side because it's more portable and keeps API keys out of the client. If client-side is required, note why.
2. **New endpoint** `api/selfies/generate.js`:
- - Session auth required.
- - Body: `{ selfie_id }`.
- - Resolve selfie row, generate a short-lived `presignGet` for the R2 object.
- - Submit to provider with a webhook callback URL `/api/avatars/webhook/{provider}`.
- - Insert an `avatar_jobs` row: `{ id, user_id, selfie_id, provider, provider_job_id, status: 'queued' }`. (New table — same schema-change constraint; reuse an existing table if possible or halt and surface.)
- - Return `{ job_id, status: 'queued' }`.
+ - Session auth required.
+ - Body: `{ selfie_id }`.
+ - Resolve selfie row, generate a short-lived `presignGet` for the R2 object.
+ - Submit to provider with a webhook callback URL `/api/avatars/webhook/{provider}`.
+ - Insert an `avatar_jobs` row: `{ id, user_id, selfie_id, provider, provider_job_id, status: 'queued' }`. (New table — same schema-change constraint; reuse an existing table if possible or halt and surface.)
+ - Return `{ job_id, status: 'queued' }`.
3. **New endpoint** `api/avatars/webhook/:provider.js`:
- - Verify webhook signature per provider's scheme.
- - On `completed`: download the GLB from the provider URL, `PUT` it to R2 at `u/{userId}/{slug}/{timestamp}.glb`, register it in `avatars` (reusing `api/avatars/index.js` helpers), mark the job `done`, set `agent_identities.avatar_id` to the new avatar (assign to the user's default agent — the one `/api/agents/me` would return).
- - On `failed`: mark the job `failed`, store the error message.
+ - Verify webhook signature per provider's scheme.
+ - On `completed`: download the GLB from the provider URL, `PUT` it to R2 at `u/{userId}/{slug}/{timestamp}.glb`, register it in `avatars` (reusing `api/avatars/index.js` helpers), mark the job `done`, set `agent_identities.avatar_id` to the new avatar (assign to the user's default agent — the one `/api/agents/me` would return).
+ - On `failed`: mark the job `failed`, store the error message.
4. **Polling endpoint** `api/selfies/generate.js` → also handles `GET ?job_id=` → returns `{ status, avatar_id? }`. Keep polling simple; no websockets.
5. **Client wiring** in `public/selfie/selfie.js`:
- - After `POST /api/selfies` succeeds, call `POST /api/selfies/generate` with the `selfie_id`.
- - Poll `/api/selfies/generate?job_id=...` every 3s, max 120s.
- - On success, redirect to `/agent/${agent_id}` (or `/dashboard/` with a toast if no agent page yet — 04-01 polishes that page).
+ - After `POST /api/selfies` succeeds, call `POST /api/selfies/generate` with the `selfie_id`.
+ - Poll `/api/selfies/generate?job_id=...` every 3s, max 120s.
+ - On success, redirect to `/agent/${agent_id}` (or `/dashboard/` with a toast if no agent page yet — 04-01 polishes that page).
## Out of scope
- Picking between providers — make one call; document in the decision paragraph.
-- Editing the avatar post-generation (03-*).
+- Editing the avatar post-generation (03-\*).
- Multiple-angle capture (single front-facing selfie).
- Anything to do with ERC-8004 registration.
diff --git a/prompts/build/02-04-first-agent-landing.md b/prompts/build/02-04-first-agent-landing.md
index 751f43bd9..04c1d0184 100644
--- a/prompts/build/02-04-first-agent-landing.md
+++ b/prompts/build/02-04-first-agent-landing.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Post-generation landing page so a new user immediately sees their 3D self"
+description: 'Post-generation landing page so a new user immediately sees their 3D self'
---
# 02-04 · First-agent landing
@@ -26,15 +26,15 @@ After 02-03 redirects to `/agent/:id`, the page must feel like an arrival — "t
2. **Celebrate via the Empathy Layer** — on load with `?welcome=1`, emit a `celebration` pulse through the agent protocol so the avatar smiles + leans forward. Use the existing scoring in [src/agent-avatar.js](../../src/agent-avatar.js) — fire an action with high celebration valence; do not invent a new state.
3. **Name the agent** — if the agent's `name` is the default `'Agent'`, show an inline "Name your agent" input that saves via `PUT /api/agents/:id`. No modal.
4. **Next steps strip** — three cards below the viewer:
- - "Edit your look" → `/agent/:id/edit` (03-*)
- - "Share your agent" → opens the existing share panel
- - "Make it onchain" → `/agent/:id/register` (06-*) — disabled state + tooltip "Coming soon" if registration isn't wired yet.
+ - "Edit your look" → `/agent/:id/edit` (03-\*)
+ - "Share your agent" → opens the existing share panel
+ - "Make it onchain" → `/agent/:id/register` (06-\*) — disabled state + tooltip "Coming soon" if registration isn't wired yet.
5. **Clean state after welcome** — once the user names the agent or dismisses the overlay, replace the URL with `history.replaceState` to drop `?welcome=1` so a refresh doesn't re-celebrate.
## Out of scope
-- Building the edit page (03-*).
-- Any onchain registration (06-*).
+- Building the edit page (03-\*).
+- Any onchain registration (06-\*).
- Redesigning the existing share panel.
- Adding a tutorial walkthrough.
diff --git a/prompts/build/02-05-avatar-og-share-image.md b/prompts/build/02-05-avatar-og-share-image.md
index 938dddc3c..aeccc4f55 100644
--- a/prompts/build/02-05-avatar-og-share-image.md
+++ b/prompts/build/02-05-avatar-og-share-image.md
@@ -7,8 +7,8 @@ The moment a user gets their 3D avatar is also the moment they're most likely to
## Context
- OG endpoint scaffold exists: [api/agent-og.js](../../api/agent-og.js).
-- Per-agent record: `api/agents/[id].js`, table `agents` (reference [api/_lib/schema.sql](../../api/_lib/schema.sql)).
-- Avatar storage: `avatars.storage_key` in R2, helper in [api/_lib/r2.js](../../api/_lib/r2.js).
+- Per-agent record: `api/agents/[id].js`, table `agents` (reference [api/\_lib/schema.sql](../../api/_lib/schema.sql)).
+- Avatar storage: `avatars.storage_key` in R2, helper in [api/\_lib/r2.js](../../api/_lib/r2.js).
- Three.js is already a dep — server-side render via `@react-three/offscreen` or node-three is NOT in scope. Use a pre-rendered "hero pose" PNG captured on the client immediately after avatar generation.
## What to build
@@ -43,7 +43,7 @@ On [public/agent/index.html](../../public/agent/index.html), ensure `<meta prope
- Animated OGs (video OG).
- Server-side Three.js rendering.
- Customising the pose per-user (one canonical pose is fine).
-- Editing existing OGs — regenerate on avatar-swap / regenerate (covered implicitly by re-running the client capture after 03-* flows).
+- Editing existing OGs — regenerate on avatar-swap / regenerate (covered implicitly by re-running the client capture after 03-\* flows).
## Acceptance
diff --git a/prompts/build/02-05-selfie-consent-and-retry.md b/prompts/build/02-05-selfie-consent-and-retry.md
index ab680bf68..da80ce654 100644
--- a/prompts/build/02-05-selfie-consent-and-retry.md
+++ b/prompts/build/02-05-selfie-consent-and-retry.md
@@ -4,7 +4,7 @@
## Why it matters
-The selfie pipeline (02-01 → 02-04) assumes the happy path. In practice: users retake photos, change their mind about privacy mid-flow, or hit generation failures (bad lighting, face not detected, timeout). Without a graceful recovery UX, a failure loses the user forever — and this is the *magic moment* we can't afford to botch.
+The selfie pipeline (02-01 → 02-04) assumes the happy path. In practice: users retake photos, change their mind about privacy mid-flow, or hit generation failures (bad lighting, face not detected, timeout). Without a graceful recovery UX, a failure loses the user forever — and this is the _magic moment_ we can't afford to botch.
## What to build
@@ -16,11 +16,11 @@ A three-state wrapper around the existing capture → upload → generate flow:
## Read these first
-| File | Why |
-|:---|:---|
-| `public/studio/selfie.html` or wherever 02-01 landed | Current capture UI you are wrapping. |
-| `api/avatars/presign.js` | Upload path for the selfie. |
-| Backend generation endpoint from 02-02 / 02-03 | Error shape + retry semantics. |
+| File | Why |
+| :--------------------------------------------------- | :----------------------------------------------------- |
+| `public/studio/selfie.html` or wherever 02-01 landed | Current capture UI you are wrapping. |
+| `api/avatars/presign.js` | Upload path for the selfie. |
+| Backend generation endpoint from 02-02 / 02-03 | Error shape + retry semantics. |
| [src/avatar-creator.js](../../src/avatar-creator.js) | Avaturn fallback flow. Reuse as "Upload instead" path. |
## Build this
@@ -32,6 +32,7 @@ New component `src/components/selfie-consent.jsx` (vhtml, matches existing compo
Text: "Take a photo → get a 3D avatar. We store your photo in your account so you can regenerate your avatar later. Never shared, never sold. Delete anytime from /dashboard/privacy."
Buttons:
+
- **Continue** — hides the consent, kicks off camera permission.
- **Upload instead** — opens file picker for a pre-existing photo (jpeg/png only, 8MB max).
- **Use default avatar** — skip selfie entirely, create agent with a placeholder avatar.
@@ -46,14 +47,14 @@ After capture, freeze the canvas and show buttons. Don't upload yet. On **Retake
Backend returns typed errors (add to 02-02 if missing). Surface each with a specific message:
-| Code | User message | Action |
-|:---|:---|:---|
-| `no_face_detected` | "We couldn't find your face. Try better lighting and look at the camera." | [Retake] |
-| `multiple_faces` | "We saw more than one face. Use a photo of just you." | [Retake] / [Upload] |
-| `low_quality` | "Photo is too blurry or dark. Try again in better lighting." | [Retake] |
-| `provider_timeout` | "This is taking longer than usual. Retrying…" | Auto-retry once, then [Try again] |
-| `provider_quota` | "We've hit our daily limit. Try again in a few hours — or upload a GLB manually." | [Upload GLB] link to `/dashboard/avatars/new` |
-| `unknown` | "Something went wrong. If this keeps happening, drop us a note." | [Retake] / [Upload] |
+| Code | User message | Action |
+| :----------------- | :-------------------------------------------------------------------------------- | :-------------------------------------------- |
+| `no_face_detected` | "We couldn't find your face. Try better lighting and look at the camera." | [Retake] |
+| `multiple_faces` | "We saw more than one face. Use a photo of just you." | [Retake] / [Upload] |
+| `low_quality` | "Photo is too blurry or dark. Try again in better lighting." | [Retake] |
+| `provider_timeout` | "This is taking longer than usual. Retrying…" | Auto-retry once, then [Try again] |
+| `provider_quota` | "We've hit our daily limit. Try again in a few hours — or upload a GLB manually." | [Upload GLB] link to `/dashboard/avatars/new` |
+| `unknown` | "Something went wrong. If this keeps happening, drop us a note." | [Retake] / [Upload] |
### 4. Auto-retry logic
@@ -73,11 +74,13 @@ On /dashboard/privacy (create if missing — keep it minimal), list stored selfi
## Deliverables
**New:**
+
- `src/components/selfie-consent.jsx`
- `public/dashboard/privacy.html` + `public/dashboard/privacy.js`
- `api/selfies/[id].js` — DELETE handler (soft-delete row, then R2 `deleteObject`).
**Modified:**
+
- Existing capture UI from 02-01 — wrap with consent + retake.
- Backend generator (02-02) — emit typed error codes.
diff --git a/prompts/build/02-06-no-wallet-guest-creation.md b/prompts/build/02-06-no-wallet-guest-creation.md
index 2d06150aa..ee81fd45d 100644
--- a/prompts/build/02-06-no-wallet-guest-creation.md
+++ b/prompts/build/02-06-no-wallet-guest-creation.md
@@ -6,7 +6,7 @@
Asking users to sign in before they see their 3D self is backwards. The magic moment should come first, then the "save your agent" prompt should drive sign-up. Today, `/dashboard/avatars/new` requires auth.
-Without this, most first-touch users bounce before they ever see themselves in 3D. We need a guest flow that keeps the magic up-front and converts via wallet sign-in *after* they're hooked.
+Without this, most first-touch users bounce before they ever see themselves in 3D. We need a guest flow that keeps the magic up-front and converts via wallet sign-in _after_ they're hooked.
## What to build
@@ -20,13 +20,13 @@ A guest creation flow at `/try` (or `/create`, pick shorter) that:
## Read these first
-| File | Why |
-|:---|:---|
-| [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) | SIWE flow. The claim step reuses this + a follow-up handoff. |
-| [api/avatars/index.js](../../api/avatars/index.js) | Avatar create flow — will need a guest mode that stamps a guest user placeholder. |
-| [api/_lib/auth.js](../../api/_lib/auth.js) | Session helpers. |
-| Backend from 02-02 / 02-03 | Generation pipeline — needs to accept guest-session token. |
-| [api/agents.js](../../api/agents.js) | Agent auto-create on `GET /api/agents/me`. |
+| File | Why |
+| :------------------------------------------------------- | :-------------------------------------------------------------------------------- |
+| [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) | SIWE flow. The claim step reuses this + a follow-up handoff. |
+| [api/avatars/index.js](../../api/avatars/index.js) | Avatar create flow — will need a guest mode that stamps a guest user placeholder. |
+| [api/\_lib/auth.js](../../api/_lib/auth.js) | Session helpers. |
+| Backend from 02-02 / 02-03 | Generation pipeline — needs to accept guest-session token. |
+| [api/agents.js](../../api/agents.js) | Agent auto-create on `GET /api/agents/me`. |
## Build this
@@ -64,10 +64,12 @@ Skip on the guest path — we don't create an agent until the user claims. Just
### 5. Claim flow
Button on the result page: **Claim this agent**. Runs SIWE (or email sign-up). After `verify` returns 200, call `POST /api/guest/claim` with:
+
- `Authorization: Bearer guest:<token>`
- Cookie: the brand-new `__Host-sid`
Server atomically:
+
1. Looks up `guest_id` by token hash.
2. Confirms `claimed_user_id IS NULL`.
3. Transfers the avatar row: `update avatars set owner_id = <user>, guest_id = null where guest_id = <guest>`.
@@ -91,6 +93,7 @@ A cron-friendly (or Vercel cron) endpoint `POST /api/guest/reap` that deletes un
## Deliverables
**New:**
+
- `api/guest/start.js`
- `api/guest/claim.js`
- `api/guest/reap.js`
@@ -98,6 +101,7 @@ A cron-friendly (or Vercel cron) endpoint `POST /api/guest/reap` that deletes un
- Migration: `guests` table + `avatars.guest_id` column (ask before running).
**Modified:**
+
- `api/avatars/presign.js` + `api/avatars/index.js` — accept guest bearer.
- `vercel.json` — `/try` route, guest endpoints, cron entry for `/api/guest/reap`.
diff --git a/prompts/build/03-01-avatar-swap.md b/prompts/build/03-01-avatar-swap.md
index 8494a72e8..61770b59d 100644
--- a/prompts/build/03-01-avatar-swap.md
+++ b/prompts/build/03-01-avatar-swap.md
@@ -11,7 +11,7 @@ Pillar 3: editing. The agent IS the identity — skills, memory, wallet, onchain
## Prerequisites
-- 02-* shipped (at least one avatar exists).
+- 02-\* shipped (at least one avatar exists).
## Read these first
@@ -23,21 +23,21 @@ Pillar 3: editing. The agent IS the identity — skills, memory, wallet, onchain
1. **New page** `public/agent/edit.html` + accompanying JS. Route `/agent/:id/edit` in `vercel.json`.
2. **Layout**:
- - Left: current avatar in the viewer.
- - Right: three tabs — **Retake selfie** (links to `/selfie`) · **Choose from library** (user's existing avatars + a small curated public list) · **Upload GLB** (drag-drop).
- - Bottom: **Save changes** (disabled until something changed) and **Cancel**.
+ - Left: current avatar in the viewer.
+ - Right: three tabs — **Retake selfie** (links to `/selfie`) · **Choose from library** (user's existing avatars + a small curated public list) · **Upload GLB** (drag-drop).
+ - Bottom: **Save changes** (disabled until something changed) and **Cancel**.
3. **Swap logic**:
- - Chosen avatar's `avatar_id` → `PUT /api/agents/:id` with `{ avatar_id }`.
- - Nothing else changes: `name`, `description`, `wallet_address`, `erc8004_agent_id`, `skills`, `meta` all preserved.
- - After save, redirect to `/agent/:id` with a toast "Avatar updated."
+ - Chosen avatar's `avatar_id` → `PUT /api/agents/:id` with `{ avatar_id }`.
+ - Nothing else changes: `name`, `description`, `wallet_address`, `erc8004_agent_id`, `skills`, `meta` all preserved.
+ - After save, redirect to `/agent/:id` with a toast "Avatar updated."
4. **History** — before saving, write the previous `avatar_id` into `agent_identities.meta.avatar_history` (array, capped at 5). Minimal — enough that a user can roll back if needed.
5. **Owner-only guard** — page JS hits `GET /api/agents/:id` and if `user_id !== currentUser.id`, redirect to the public `/agent/:id` view.
## Out of scope
- Live editing the avatar mesh (03-02).
-- Uploading a selfie (02-*).
-- Onchain consequences of the avatar change (06-* — the CID should change but that's not enforced here).
+- Uploading a selfie (02-\*).
+- Onchain consequences of the avatar change (06-\* — the CID should change but that's not enforced here).
- Versioned avatar entities (the history list is lightweight meta, not a new table).
## Deliverables
diff --git a/prompts/build/03-01-dashboard-edit-tab.md b/prompts/build/03-01-dashboard-edit-tab.md
index 9e4998dd1..1fa0963a7 100644
--- a/prompts/build/03-01-dashboard-edit-tab.md
+++ b/prompts/build/03-01-dashboard-edit-tab.md
@@ -3,7 +3,7 @@
**Branch:** `feat/dashboard-edit-tab`
**Stack layer:** 3 (Edit avatar)
**Depends on:** 02-03 (avatars are bound to agents)
-**Blocks:** 03-02 (regenerate/swap), 04-* (embed polish reveals editing gaps)
+**Blocks:** 03-02 (regenerate/swap), 04-\* (embed polish reveals editing gaps)
## Why it matters
@@ -11,12 +11,12 @@
## Read these first
-| File | Why |
-|:---|:---|
+| File | Why |
+| :------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------- |
| [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js) | Tab routing, state shape, existing tab renderers as templates (especially the avatar list renderer). |
-| [api/avatars/[id].js](../../api/avatars/[id].js) | PATCH handler already supports `name`, `description`, `visibility`, `tags`. |
-| [src/account.js](../../src/account.js) | Client helpers — extend, don't duplicate. |
-| [style.css](../../style.css) | Existing form field styles. |
+| [api/avatars/[id].js](../../api/avatars/[id].js) | PATCH handler already supports `name`, `description`, `visibility`, `tags`. |
+| [src/account.js](../../src/account.js) | Client helpers — extend, don't duplicate. |
+| [style.css](../../style.css) | Existing form field styles. |
## Build this
diff --git a/prompts/build/03-02-avatar-regenerate-and-swap.md b/prompts/build/03-02-avatar-regenerate-and-swap.md
index 5204cfabc..3bd5abca4 100644
--- a/prompts/build/03-02-avatar-regenerate-and-swap.md
+++ b/prompts/build/03-02-avatar-regenerate-and-swap.md
@@ -3,26 +3,26 @@
**Branch:** `feat/avatar-regenerate-swap`
**Stack layer:** 3 (Edit avatar)
**Depends on:** 03-01, 02-02
-**Blocks:** nothing critical, but improves 04-* user flow
+**Blocks:** nothing critical, but improves 04-\* user flow
## Why it matters
-After 03-01, users can rename and delete. They still can't *improve* their avatar without starting over and losing the agent identity. Two operations close this gap:
+After 03-01, users can rename and delete. They still can't _improve_ their avatar without starting over and losing the agent identity. Two operations close this gap:
-1. **Regenerate** — take a new selfie, produce a new GLB, attach it to the *same* avatar row (preserves `agent_identities.avatar_id`).
+1. **Regenerate** — take a new selfie, produce a new GLB, attach it to the _same_ avatar row (preserves `agent_identities.avatar_id`).
2. **Swap** — pick a different existing avatar from your library as the agent's body.
Both keep agent identity, memory, and on-chain records intact across a visual refresh.
## Read these first
-| File | Why |
-|:---|:---|
-| [api/avatars/[id].js](../../api/avatars/[id].js) | PATCH/DELETE handler. Regenerate will add a new sub-route. |
-| [api/avatars/from-selfie.js](../../api/avatars/from-selfie.js) *(from 02-02)* | Generation pipeline — reuse its internals. |
-| [api/agents.js](../../api/agents.js) | Agent PATCH accepts `avatar_id`. |
-| [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js) | Where 03-01 placed the edit tab. |
-| [src/agent-identity.js](../../src/agent-identity.js) | Client model — nothing to change; just confirm it holds no GLB state directly. |
+| File | Why |
+| :---------------------------------------------------------------------------- | :----------------------------------------------------------------------------- |
+| [api/avatars/[id].js](../../api/avatars/[id].js) | PATCH/DELETE handler. Regenerate will add a new sub-route. |
+| [api/avatars/from-selfie.js](../../api/avatars/from-selfie.js) _(from 02-02)_ | Generation pipeline — reuse its internals. |
+| [api/agents.js](../../api/agents.js) | Agent PATCH accepts `avatar_id`. |
+| [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js) | Where 03-01 placed the edit tab. |
+| [src/agent-identity.js](../../src/agent-identity.js) | Client model — nothing to change; just confirm it holds no GLB state directly. |
## Build this
diff --git a/prompts/build/03-02-avatar-regenerate.md b/prompts/build/03-02-avatar-regenerate.md
index c22343a61..8638e09dd 100644
--- a/prompts/build/03-02-avatar-regenerate.md
+++ b/prompts/build/03-02-avatar-regenerate.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Re-run the selfie→avatar pipeline reusing the stored selfie, keeping the same agent id"
+description: 'Re-run the selfie→avatar pipeline reusing the stored selfie, keeping the same agent id'
---
# 03-02 · Regenerate avatar from stored selfie
diff --git a/prompts/build/03-03-edit-agent-metadata.md b/prompts/build/03-03-edit-agent-metadata.md
index 898b2067c..279e32399 100644
--- a/prompts/build/03-03-edit-agent-metadata.md
+++ b/prompts/build/03-03-edit-agent-metadata.md
@@ -1,17 +1,17 @@
---
mode: agent
-description: "Inline editing of name, description, and skill list for an agent"
+description: 'Inline editing of name, description, and skill list for an agent'
---
# 03-03 · Edit agent metadata
## Why it matters
-The agent is not just the avatar — name, description, and the skill list define what the agent *is* and *does*. Users need a place to change these without opening a DB client.
+The agent is not just the avatar — name, description, and the skill list define what the agent _is_ and _does_. Users need a place to change these without opening a DB client.
## Prerequisites
-- 01-* (auth), 03-01 (edit page scaffold).
+- 01-\* (auth), 03-01 (edit page scaffold).
## Read these first
@@ -21,11 +21,11 @@ The agent is not just the avatar — name, description, and the skill list defin
## Build this
1. **On `/agent/:id/edit`**, add a "Details" tab with:
- - Name (text input, 1–100 chars).
- - Description (textarea, 0–500 chars).
- - Skills — checkbox list of canonical skills (`greet`, `present-model`, `validate-model`, `remember`, `think`, `sign-action`). No custom skills in this prompt.
+ - Name (text input, 1–100 chars).
+ - Description (textarea, 0–500 chars).
+ - Skills — checkbox list of canonical skills (`greet`, `present-model`, `validate-model`, `remember`, `think`, `sign-action`). No custom skills in this prompt.
2. **Persist** via `PUT /api/agents/:id`. Use optimistic UI: update locally, revert on failure.
-3. **Validation** on the server side — `api/agents.js` already truncates; add zod validation matching the limits above via [api/_lib/validate.js](../../api/_lib/validate.js). Don't hand-roll.
+3. **Validation** on the server side — `api/agents.js` already truncates; add zod validation matching the limits above via [api/\_lib/validate.js](../../api/_lib/validate.js). Don't hand-roll.
4. **Home URL** — if the user filled `home_url`, show it on the agent page as the "official home" link. Accept empty / `null` / a full URL.
## Out of scope
@@ -33,7 +33,7 @@ The agent is not just the avatar — name, description, and the skill list defin
- Adding new skills (custom skill DSL is a separate initiative).
- Markdown in descriptions.
- Avatar changes (03-01).
-- Wallet linking (06-*).
+- Wallet linking (06-\*).
## Deliverables
diff --git a/prompts/build/03-04-animation-set-per-agent.md b/prompts/build/03-04-animation-set-per-agent.md
index 065ef77bd..7a2dcfe2e 100644
--- a/prompts/build/03-04-animation-set-per-agent.md
+++ b/prompts/build/03-04-animation-set-per-agent.md
@@ -2,14 +2,14 @@
## Why it matters
-The Empathy Layer (idle, wave, nod, shake, think) is the difference between a static model and an embodied agent. Today the Mixamo bundle is global and ad-hoc. Each agent needs a *chosen, persisted* animation set so the avatar reads the same across the agent page, embeds, and host integrations (Layers 4–5).
+The Empathy Layer (idle, wave, nod, shake, think) is the difference between a static model and an embodied agent. Today the Mixamo bundle is global and ad-hoc. Each agent needs a _chosen, persisted_ animation set so the avatar reads the same across the agent page, embeds, and host integrations (Layers 4–5).
## Context
- Animation manager: [src/animation-manager.js](../../src/animation-manager.js).
- Fetch script: `npm run fetch-animations` (Mixamo bundle in [public/animations/](../../public/animations/)).
- Manifest spec: [specs/AGENT_MANIFEST.md](../../specs/AGENT_MANIFEST.md).
-- Per-agent record: `agents` table in [api/_lib/schema.sql](../../api/_lib/schema.sql).
+- Per-agent record: `agents` table in [api/\_lib/schema.sql](../../api/_lib/schema.sql).
## What to build
diff --git a/prompts/build/03-04-skill-install-from-registry.md b/prompts/build/03-04-skill-install-from-registry.md
index 053e35339..0bbd537de 100644
--- a/prompts/build/03-04-skill-install-from-registry.md
+++ b/prompts/build/03-04-skill-install-from-registry.md
@@ -17,13 +17,13 @@ A **Skills** tab on the agent edit page (`/agent/:id/edit` or the dashboard agen
## Read these first
-| File | Why |
-|:---|:---|
-| [src/skills/index.js](../../src/skills/index.js) | `SkillRegistry.install(spec, { bundleBase })` — reuse, don't reinvent. |
-| [src/manifest.js](../../src/manifest.js) | Manifest normalization. Skills may live inside a manifest or alone. |
+| File | Why |
+| :---------------------------------------------------- | :--------------------------------------------------------------------------------------------------------- |
+| [src/skills/index.js](../../src/skills/index.js) | `SkillRegistry.install(spec, { bundleBase })` — reuse, don't reinvent. |
+| [src/manifest.js](../../src/manifest.js) | Manifest normalization. Skills may live inside a manifest or alone. |
| [api/agents.js](../../api/agents.js) — `handleUpdate` | Already accepts `skills` in the PUT body. Update is a no-op if you only add/remove strings from the array. |
-| [specs/](../../specs/) | Skill format spec — what's in a skill bundle (`SKILL.md`, `tools.json`, `handlers.js`). |
-| [src/runtime/tools.js](../../src/runtime/tools.js) | Built-in tools the agent already has. Third-party skills add to this set at runtime. |
+| [specs/](../../specs/) | Skill format spec — what's in a skill bundle (`SKILL.md`, `tools.json`, `handlers.js`). |
+| [src/runtime/tools.js](../../src/runtime/tools.js) | Built-in tools the agent already has. Third-party skills add to this set at runtime. |
## Build this
@@ -32,6 +32,7 @@ A **Skills** tab on the agent edit page (`/agent/:id/edit` or the dashboard agen
Create `public/agent/edit-skills.html` + `edit-skills.js` (or add as a tab inside an existing `/agent/:id/edit` page).
Layout:
+
- Header: "Skills for <agent name>"
- Installed list, each row: name · short description · source · [Remove]
- Divider
@@ -54,6 +55,7 @@ On paste + Install, fetch the skill bundle via [src/skills/index.js](../../src/s
Reuse `PUT /api/agents/:id` with a modified `skills` array. No new endpoint.
The `skills` column holds either:
+
- built-in skill name (`"greet"`, `"remember"`, etc.)
- external skill URL (`"https://..."`, `"ipfs://..."`, `"agent://..."`)
@@ -66,6 +68,7 @@ Remove button PATCHes `skills` with the string filtered out. Built-in skills are
### 5. Trust modes
The agent record has a `meta.skill_trust` field:
+
- `any` (default) — allows any URL.
- `owned-only` — only skills authored by the agent's wallet address.
- `whitelist` — explicit list of authors in `meta.skill_authors`.
@@ -86,10 +89,12 @@ At agent boot (`element.js` / `agent-home`), iterate `identity.skills`. For each
## Deliverables
**New:**
+
- `public/agent/edit-skills.html`
- `public/agent/edit-skills.js`
**Modified:**
+
- [src/element.js](../../src/element.js) — iterate `identity.skills`, call `SkillRegistry.install` for URLs.
- [src/agent-home.js](../../src/agent-home.js) — render installed skills list in the home UI (read-only).
diff --git a/prompts/build/03-05-avatar-version-history.md b/prompts/build/03-05-avatar-version-history.md
index a9d9a25f5..e779bc7d0 100644
--- a/prompts/build/03-05-avatar-version-history.md
+++ b/prompts/build/03-05-avatar-version-history.md
@@ -6,10 +6,10 @@ Layer 3 lets users regenerate the GLB without breaking their `agentId` — but e
## Context
-- Avatar table: `avatars` in [api/_lib/schema.sql](../../api/_lib/schema.sql) — already has `version int not null default 1` and `checksum_sha256`.
+- Avatar table: `avatars` in [api/\_lib/schema.sql](../../api/_lib/schema.sql) — already has `version int not null default 1` and `checksum_sha256`.
- Agent record: `agents.avatar_id` in the same schema.
- Swap endpoint: scoped in `03-01-avatar-swap.md` / `03-02-swap-avatar-on-agent.md`. This prompt assumes one of them is merged.
-- R2 helper: [api/_lib/r2.js](../../api/_lib/r2.js).
+- R2 helper: [api/\_lib/r2.js](../../api/_lib/r2.js).
## What to build
diff --git a/prompts/build/03-05-memory-review-and-edit.md b/prompts/build/03-05-memory-review-and-edit.md
index b9e31a4ec..d9621e63f 100644
--- a/prompts/build/03-05-memory-review-and-edit.md
+++ b/prompts/build/03-05-memory-review-and-edit.md
@@ -18,12 +18,12 @@ A **Memory** tab on the agent edit page:
## Read these first
-| File | Why |
-|:---|:---|
-| [src/agent-memory.js](../../src/agent-memory.js) | In-memory 4-type store. |
-| [api/agent-memory.js](../../api/agent-memory.js) | Server CRUD. If this file is thin today, extend rather than replace. |
-| [api/_lib/schema.sql](../../api/_lib/schema.sql) | `agent_memories` columns: `agent_id, type, content, tags, context, salience, expires_at`. |
-| [src/memory/index.js](../../src/memory/index.js) | File-based memory variant — you don't touch this for this task, but understand the shared type vocabulary. |
+| File | Why |
+| :------------------------------------------------ | :--------------------------------------------------------------------------------------------------------- |
+| [src/agent-memory.js](../../src/agent-memory.js) | In-memory 4-type store. |
+| [api/agent-memory.js](../../api/agent-memory.js) | Server CRUD. If this file is thin today, extend rather than replace. |
+| [api/\_lib/schema.sql](../../api/_lib/schema.sql) | `agent_memories` columns: `agent_id, type, content, tags, context, salience, expires_at`. |
+| [src/memory/index.js](../../src/memory/index.js) | File-based memory variant — you don't touch this for this task, but understand the shared type vocabulary. |
## Build this
@@ -45,6 +45,7 @@ Zod schema for the body (4 types only; `salience` 0–1; `content` 1..4000; `tag
`public/agent/edit-memory.html` + `edit-memory.js`.
Type colors (reuse from agent-home if already defined):
+
- `user` — indigo
- `feedback` — amber
- `project` — green
@@ -78,12 +79,14 @@ Memories of type `feedback` with high salience should influence future emotion b
## Deliverables
**New:**
+
- `public/agent/edit-memory.html`
- `public/agent/edit-memory.js`
**Modified:**
+
- [api/agent-memory.js](../../api/agent-memory.js) — full CRUD + auth.
-- [api/_lib/schema.sql](../../api/_lib/schema.sql) — add `deleted_at` column (ask first).
+- [api/\_lib/schema.sql](../../api/_lib/schema.sql) — add `deleted_at` column (ask first).
- [src/agent-memory.js](../../src/agent-memory.js) — respect `deleted_at` in reads.
## Acceptance
diff --git a/prompts/build/04-01-agent-og-image.md b/prompts/build/04-01-agent-og-image.md
index ec8ba8032..f4949e77e 100644
--- a/prompts/build/04-01-agent-og-image.md
+++ b/prompts/build/04-01-agent-og-image.md
@@ -11,11 +11,11 @@
## Read these first
-| File | Why |
-|:---|:---|
-| [public/agent-home.html](../../public/agent-home.html) | References `/api/agent-og`. See the exact param shape it expects. |
-| [api/agents.js](../../api/agents.js) | `GET /api/agents/:id` — used to look up the avatar model URL and agent name. |
-| [vercel.json](../../vercel.json) | Current route table. |
+| File | Why |
+| :----------------------------------------------------- | :--------------------------------------------------------------------------- |
+| [public/agent-home.html](../../public/agent-home.html) | References `/api/agent-og`. See the exact param shape it expects. |
+| [api/agents.js](../../api/agents.js) | `GET /api/agents/:id` — used to look up the avatar model URL and agent name. |
+| [vercel.json](../../vercel.json) | Current route table. |
## Build this
@@ -30,6 +30,7 @@
**Tier 1 (preferred): cached server-rendered PNG.** On first request, render the agent's GLB in a headless three.js context via `@napi-rs/canvas` or `node-canvas` + a Node-side GL shim. If this is too heavy for Vercel serverless limits, skip to Tier 2. Store the resulting PNG in R2 under `og/<agent_id>.png` and redirect there.
**Tier 2 (ship this first): SVG template rendered to PNG.** Compose a 1200×630 SVG with:
+
- Agent name (big)
- Short tagline (from agent bio, truncated)
- Avatar thumbnail (use the `thumbnail_url` field from avatars — if absent, fall back to a generic silhouette)
diff --git a/prompts/build/04-01-agent-public-page-polish.md b/prompts/build/04-01-agent-public-page-polish.md
index bc934d032..c38dae8f6 100644
--- a/prompts/build/04-01-agent-public-page-polish.md
+++ b/prompts/build/04-01-agent-public-page-polish.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Polish /agent/:id so it works as a shareable public page on desktop + mobile"
+description: 'Polish /agent/:id so it works as a shareable public page on desktop + mobile'
---
# 04-01 · Agent public page polish
@@ -25,14 +25,14 @@ The agent's public home is what a pasted link resolves to. It's the unfurl desti
2. **Identity card** — name, description (collapsed to 3 lines, expandable), wallet short-address (if linked), ERC-8004 badge (if registered), skill chips.
3. **Action timeline** — latest 10 actions from the protocol bus, rendered with timestamp. Already provided by `src/agent-home.js` — wire it in if not already.
4. **Share button** — opens the existing iframe/link/`<agent-3d>` share panel. No redesign.
-5. **Owner-only bar** — if viewer === owner, show a thin top bar with "Edit" (→ `/agent/:id/edit`) and "Register onchain" (→ 06-*).
+5. **Owner-only bar** — if viewer === owner, show a thin top bar with "Edit" (→ `/agent/:id/edit`) and "Register onchain" (→ 06-\*).
6. **404** — if the agent id doesn't exist or is soft-deleted, render a friendly 404 page, not a 500.
7. **Lazy loading** — three.js and avatar assets load after the identity card is visible, so first paint is fast even on mobile.
## Out of scope
- OG/oEmbed unfurl (04-02).
-- Editing (03-*).
+- Editing (03-\*).
- Chat / talking agent widget (widget-studio prompts).
## Deliverables
diff --git a/prompts/build/04-02-embed-policy-crud.md b/prompts/build/04-02-embed-policy-crud.md
index 75d3de3d4..3b8c6cf84 100644
--- a/prompts/build/04-02-embed-policy-crud.md
+++ b/prompts/build/04-02-embed-policy-crud.md
@@ -3,7 +3,7 @@
**Branch:** `feat/embed-policy-crud`
**Stack layer:** 4 (View + embed)
**Depends on:** 01-02 (stable session)
-**Blocks:** 05-* (host embeds need a policy to enforce against Claude / Lobehub origins)
+**Blocks:** 05-\* (host embeds need a policy to enforce against Claude / Lobehub origins)
## Why it matters
@@ -11,12 +11,12 @@
## Read these first
-| File | Why |
-|:---|:---|
-| [api/agents/[id]/embed-policy.js](../../api/agents/[id]/embed-policy.js) | Current stub. |
-| [agent-embed.html](../../agent-embed.html) | The iframe page. Its `Content-Security-Policy` + `X-Frame-Options` must reflect the policy. |
-| [api/_lib/](../../api/_lib/) | Auth + Neon helpers. |
-| [api/agents.js](../../api/agents.js) | Schema for agents and how ownership is checked. |
+| File | Why |
+| :----------------------------------------------------------------------- | :------------------------------------------------------------------------------------------ |
+| [api/agents/[id]/embed-policy.js](../../api/agents/[id]/embed-policy.js) | Current stub. |
+| [agent-embed.html](../../agent-embed.html) | The iframe page. Its `Content-Security-Policy` + `X-Frame-Options` must reflect the policy. |
+| [api/\_lib/](../../api/_lib/) | Auth + Neon helpers. |
+| [api/agents.js](../../api/agents.js) | Schema for agents and how ownership is checked. |
## Build this
@@ -45,13 +45,14 @@ In [agent-embed.html](../../agent-embed.html) (and any server-side render of it)
1. Server reads the policy on each request.
2. If `mode === 'private'`, require auth + ownership; 403 otherwise.
3. If `mode === 'allowlist'`, set:
- - `Content-Security-Policy: frame-ancestors <allowed_origins>`
- - `X-Frame-Options: SAMEORIGIN` as a safety net (modern browsers prefer CSP).
+ - `Content-Security-Policy: frame-ancestors <allowed_origins>`
+ - `X-Frame-Options: SAMEORIGIN` as a safety net (modern browsers prefer CSP).
4. If `mode === 'open'`, set `frame-ancestors *`.
### Dashboard UI
On the agent edit view (from 03-01 extended, or a new "Embed" tab), surface:
+
- Mode selector (Open / Allowlist / Private).
- Allowed origins list with add/remove (validate format on blur).
- Live preview of a test iframe loaded from a picker origin to confirm enforcement.
@@ -61,7 +62,7 @@ On the agent edit view (from 03-01 extended, or a new "Embed" tab), surface:
- Do not add per-origin analytics — separate prompt.
- Do not add signed embed tokens — separate prompt.
-- Do not validate that the given origins *actually* resolve to real hosts. We trust the user to know their deployment.
+- Do not validate that the given origins _actually_ resolve to real hosts. We trust the user to know their deployment.
## Acceptance
diff --git a/prompts/build/04-02-og-oembed.md b/prompts/build/04-02-og-oembed.md
index d269aae2f..590f0c0fb 100644
--- a/prompts/build/04-02-og-oembed.md
+++ b/prompts/build/04-02-og-oembed.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "OG image + oEmbed so pasted /agent/:id links unfurl on Slack, X, Discord"
+description: 'OG image + oEmbed so pasted /agent/:id links unfurl on Slack, X, Discord'
---
# 04-02 · Unfurl with OG image + oEmbed
@@ -25,7 +25,7 @@ The viral channel: paste an agent link → see a real preview, not a URL. Withou
Verify the three pieces are wired:
-1. `/api/agent-og?id=X` returns a 1200×630 PNG preview of the agent (avatar rendered headlessly *or* a static thumbnail from the avatar's thumbnail_key if GPU rendering is unavailable).
+1. `/api/agent-og?id=X` returns a 1200×630 PNG preview of the agent (avatar rendered headlessly _or_ a static thumbnail from the avatar's thumbnail_key if GPU rendering is unavailable).
2. `/api/agent-oembed?url=X` returns JSON oEmbed with `type=rich`, `html=<iframe src="/agent/:id/embed">`.
3. `<head>` of `/agent/:id` includes `og:title`, `og:description`, `og:image`, `og:type=website`, `twitter:card=summary_large_image`, `twitter:image`, and `<link rel="alternate" type="application/json+oembed" href="/api/agent-oembed?url=...">`.
diff --git a/prompts/build/04-03-embed-reliability.md b/prompts/build/04-03-embed-reliability.md
index bb9506ab1..98088f678 100644
--- a/prompts/build/04-03-embed-reliability.md
+++ b/prompts/build/04-03-embed-reliability.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Harden /agent/:id/embed so it renders in third-party iframes under CSP"
+description: 'Harden /agent/:id/embed so it renders in third-party iframes under CSP'
---
# 04-03 · Embed iframe reliability
@@ -11,7 +11,7 @@ Pillar 5 (host embed in Claude Artifacts and Lobehub) depends on the embed URL w
## Prerequisites
-- 02-* complete so an agent can actually be embedded.
+- 02-\* complete so an agent can actually be embedded.
## Read these first
@@ -22,21 +22,21 @@ Pillar 5 (host embed in Claude Artifacts and Lobehub) depends on the embed URL w
## Build this
1. **Response headers** for `/agent/:id/embed`:
- - `X-Frame-Options`: remove (it blocks cross-origin iframes).
- - `Content-Security-Policy`: `frame-ancestors *` (or an allowlist — see 04-04).
- - `Permissions-Policy`: allow `camera=(), microphone=(), clipboard-write=(self)` depending on which widgets are enabled.
+ - `X-Frame-Options`: remove (it blocks cross-origin iframes).
+ - `Content-Security-Policy`: `frame-ancestors *` (or an allowlist — see 04-04).
+ - `Permissions-Policy`: allow `camera=(), microphone=(), clipboard-write=(self)` depending on which widgets are enabled.
2. **Transparent background mode** — query param `?bg=transparent` sets the canvas clear alpha to 0 so the avatar sits on host chrome. `?bg=000000` forces opaque. Default: opaque `#111`.
3. **Kiosk mode** — `?kiosk=1` hides dat.gui, the share panel, and the owner bar. Purely the avatar.
4. **postMessage bridge** — document and implement the minimal contract:
- - Host → iframe: `{ type: 'agent:action', action }` — forwarded to the protocol bus.
- - Iframe → host: `{ type: 'agent:ready' }`, `{ type: 'agent:action', action }` (echo), `{ type: 'agent:resize', height }`.
- - All messages include `agentId` so the host can multiplex.
+ - Host → iframe: `{ type: 'agent:action', action }` — forwarded to the protocol bus.
+ - Iframe → host: `{ type: 'agent:ready' }`, `{ type: 'agent:action', action }` (echo), `{ type: 'agent:resize', height }`.
+ - All messages include `agentId` so the host can multiplex.
5. **Resize observer** — post `agent:resize` when the iframe content height changes so hosts can auto-size the iframe.
## Out of scope
- Referrer allowlist (optional; see 04-04 or `prompts/embed/03-embed-allowlist.md`).
-- Actual Claude/Lobehub integration (05-*).
+- Actual Claude/Lobehub integration (05-\*).
## Deliverables
diff --git a/prompts/build/04-03-public-agent-decorate.md b/prompts/build/04-03-public-agent-decorate.md
index 99e453a25..d3e4222c4 100644
--- a/prompts/build/04-03-public-agent-decorate.md
+++ b/prompts/build/04-03-public-agent-decorate.md
@@ -3,7 +3,7 @@
**Branch:** `feat/agent-public-decorate`
**Stack layer:** 4 (View + embed)
**Depends on:** nothing
-**Blocks:** 05-* (host embeds call the public endpoint and should not leak internals)
+**Blocks:** 05-\* (host embeds call the public endpoint and should not leak internals)
## Why it matters
@@ -11,12 +11,12 @@
## Read these first
-| File | Why |
-|:---|:---|
-| [api/agents.js](../../api/agents.js) | `decorate()` function and the GET handler. |
-| [api/_lib/](../../api/_lib/) | Any shared response-shaping helpers. |
-| [src/agent-identity.js](../../src/agent-identity.js) | Client expectation of the agent shape. |
-| [agent-embed.html](../../agent-embed.html), [public/agent-home.html](../../public/agent-home.html) | Public consumers of the endpoint. |
+| File | Why |
+| :------------------------------------------------------------------------------------------------- | :----------------------------------------- |
+| [api/agents.js](../../api/agents.js) | `decorate()` function and the GET handler. |
+| [api/\_lib/](../../api/_lib/) | Any shared response-shaping helpers. |
+| [src/agent-identity.js](../../src/agent-identity.js) | Client expectation of the agent shape. |
+| [agent-embed.html](../../agent-embed.html), [public/agent-home.html](../../public/agent-home.html) | Public consumers of the endpoint. |
## Build this
diff --git a/prompts/build/04-04-agent-card-json.md b/prompts/build/04-04-agent-card-json.md
index 88a716263..e7f8104c6 100644
--- a/prompts/build/04-04-agent-card-json.md
+++ b/prompts/build/04-04-agent-card-json.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Publish agent-card.json and agent-registration.json for A2A discovery"
+description: 'Publish agent-card.json and agent-registration.json for A2A discovery'
---
# 04-04 · A2A discovery: agent-card.json
@@ -22,21 +22,21 @@ A2A (Agent-to-Agent) discovery — other agent runtimes find and introspect your
## Build this
1. **New endpoint** `GET /api/agents/:id/card.json`:
- - Returns the agent card in the A2A convention (use the spec in `specs/` if present; if not, match the shape below).
- - `{ name, description, home, avatar: { url, content_type, size }, skills: [...], identity: { wallet?, chain_id?, erc8004_agent_id? }, endpoints: { embed, postmessage_bridge }, schema_version }`.
- - No auth required — this is public discovery.
- - Etag on the response (hash of the content) so hosts can cache.
+ - Returns the agent card in the A2A convention (use the spec in `specs/` if present; if not, match the shape below).
+ - `{ name, description, home, avatar: { url, content_type, size }, skills: [...], identity: { wallet?, chain_id?, erc8004_agent_id? }, endpoints: { embed, postmessage_bridge }, schema_version }`.
+ - No auth required — this is public discovery.
+ - Etag on the response (hash of the content) so hosts can cache.
2. **Well-known alias** `GET /.well-known/agent-card.json?id=...` → same response. Some consumers only read `.well-known`.
3. **Registration card** `GET /api/agents/:id/registration.json`:
- - Smaller, onchain-bound subset: `{ card_url, card_sha256, avatar_sha256, created_at, wallet }`.
- - Field to record what was pinned to IPFS — the card CID goes onchain in pillar 6.
+ - Smaller, onchain-bound subset: `{ card_url, card_sha256, avatar_sha256, created_at, wallet }`.
+ - Field to record what was pinned to IPFS — the card CID goes onchain in pillar 6.
4. **Viewer link** — add `<link rel="agent-card" href="/api/agents/:id/card.json">` to `/agent/:id` page head.
## Out of scope
-- Pinning to IPFS (06-*).
-- Onchain registration (06-*).
-- Signing the card (06-*).
+- Pinning to IPFS (06-\*).
+- Onchain registration (06-\*).
+- Signing the card (06-\*).
## Deliverables
diff --git a/prompts/build/04-05-embed-sizes-themes-kiosk.md b/prompts/build/04-05-embed-sizes-themes-kiosk.md
index 6d516a72b..3bbe0cc98 100644
--- a/prompts/build/04-05-embed-sizes-themes-kiosk.md
+++ b/prompts/build/04-05-embed-sizes-themes-kiosk.md
@@ -12,26 +12,26 @@ This prompt makes the embed URL self-adapt across sizes and themes via query par
Extend [public/agent/embed.html](../../public/agent/embed.html) to honor a small, documented query-param API:
-| Param | Values | Effect |
-|:---|:---|:---|
-| `bg` | `transparent` (default), `dark`, `light`, `#rrggbb` | Canvas background. Arbitrary hex too. |
-| `theme` | `auto`, `dark`, `light` | UI chrome (name plate, error text). `auto` follows `prefers-color-scheme`. |
-| `size` | `bubble`, `card`, `banner`, `full` | Presets that tune camera distance, name plate visibility, framing. |
-| `name` | `0` / `1` | Show name plate. |
-| `controls` | `0` / `1` | Show orbit controls (default 0 — kiosk). |
-| `autorotate` | `0` / `1` | Default 1 for bubble/card/banner; 0 for full. |
-| `speed` | number (0.1–3) | Autorotate speed. |
-| `expression` | emotion name or `random` | Starting emotion blend seed. |
-| `cta` | url | On click, open this URL in a new tab. If unset, click does nothing. |
+| Param | Values | Effect |
+| :----------- | :-------------------------------------------------- | :------------------------------------------------------------------------- |
+| `bg` | `transparent` (default), `dark`, `light`, `#rrggbb` | Canvas background. Arbitrary hex too. |
+| `theme` | `auto`, `dark`, `light` | UI chrome (name plate, error text). `auto` follows `prefers-color-scheme`. |
+| `size` | `bubble`, `card`, `banner`, `full` | Presets that tune camera distance, name plate visibility, framing. |
+| `name` | `0` / `1` | Show name plate. |
+| `controls` | `0` / `1` | Show orbit controls (default 0 — kiosk). |
+| `autorotate` | `0` / `1` | Default 1 for bubble/card/banner; 0 for full. |
+| `speed` | number (0.1–3) | Autorotate speed. |
+| `expression` | emotion name or `random` | Starting emotion blend seed. |
+| `cta` | url | On click, open this URL in a new tab. If unset, click does nothing. |
## Read these first
-| File | Why |
-|:---|:---|
+| File | Why |
+| :------------------------------------------------------- | :--------------------------------------------------------------------------------- |
| [public/agent/embed.html](../../public/agent/embed.html) | The file you're extending. Keep it small; don't promote to a module if not needed. |
-| [src/agent-avatar.js](../../src/agent-avatar.js) | `setExpression` / emotion API. |
-| [src/viewer.js](../../src/viewer.js) | Camera framing. `kiosk` option already exists. |
-| `src/components/wallet-chip.js` (if present) | Don't mount inside the iframe — the embed is chromeless by design. |
+| [src/agent-avatar.js](../../src/agent-avatar.js) | `setExpression` / emotion API. |
+| [src/viewer.js](../../src/viewer.js) | Camera framing. `kiosk` option already exists. |
+| `src/components/wallet-chip.js` (if present) | Don't mount inside the iframe — the embed is chromeless by design. |
## Build this
@@ -49,12 +49,12 @@ Inside the existing `main()`, after loading the avatar:
### 2. Preset tuning
-| Preset | Camera z | Name plate | Framing | Notes |
-|:---|:---|:---|:---|:---|
-| `bubble` | tight head shot | hidden | chest-up | intended 96–160 px iframes |
-| `card` | tighter than default | visible | upper body | ~300 px |
-| `banner` | medium | visible | full body | 600×600+ |
-| `full` | default | visible | scene fits | full page |
+| Preset | Camera z | Name plate | Framing | Notes |
+| :------- | :------------------- | :--------- | :--------- | :------------------------- |
+| `bubble` | tight head shot | hidden | chest-up | intended 96–160 px iframes |
+| `card` | tighter than default | visible | upper body | ~300 px |
+| `banner` | medium | visible | full body | 600×600+ |
+| `full` | default | visible | scene fits | full page |
### 3. Responsive to iframe size
@@ -78,10 +78,12 @@ Add a section to [public/agent/index.html](../../public/agent/index.html) share
## Deliverables
**Modified:**
+
- [public/agent/embed.html](../../public/agent/embed.html) — accept the new params.
- [public/agent/index.html](../../public/agent/index.html) — preset picker in share panel.
**New (if split needed):**
+
- `public/agent/embed.js`
- `public/agent/embed.css`
diff --git a/prompts/build/04-05-public-agent-gallery.md b/prompts/build/04-05-public-agent-gallery.md
index 75f2c0704..04f848756 100644
--- a/prompts/build/04-05-public-agent-gallery.md
+++ b/prompts/build/04-05-public-agent-gallery.md
@@ -10,21 +10,21 @@ When users share their agent, they want it to be discoverable by others. A `/gal
## Read these first
-| File | Why |
-|:---|:---|
-| [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js) | Native-DOM rendering pattern; copy. |
-| [api/agents.js](../../api/agents.js) | List endpoint — needs a public scope. |
-| [src/agent-resolver.js](../../src/agent-resolver.js) | Resolution helpers. |
-| [api/onchain/agent/[chainId]/[tokenId].js](../../api/onchain/agent/[chainId]/[tokenId].js) | Reputation join. |
+| File | Why |
+| :----------------------------------------------------------------------------------------- | :------------------------------------ |
+| [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js) | Native-DOM rendering pattern; copy. |
+| [api/agents.js](../../api/agents.js) | List endpoint — needs a public scope. |
+| [src/agent-resolver.js](../../src/agent-resolver.js) | Resolution helpers. |
+| [api/onchain/agent/[chainId]/[tokenId].js](../../api/onchain/agent/[chainId]/[tokenId].js) | Reputation join. |
## Build this
1. Add `GET /api/agents/public` — returns paginated list of agents where `visibility = 'public'`. Response: `{ agents: [{ id, name, thumbnail_url, description, owner_handle, reputation? }], next_cursor }`. Cursor-based pagination, 24 per page.
2. Create `public/gallery/index.html` and `public/gallery/gallery.js`. Three-column responsive grid (single column < 600px). Each card:
- - Square thumbnail (CDN-cached).
- - Name + truncated description.
- - Reputation stars if on-chain.
- - Click → `/agent/<id>`.
+ - Square thumbnail (CDN-cached).
+ - Name + truncated description.
+ - Reputation stars if on-chain.
+ - Click → `/agent/<id>`.
3. Filters: search box (debounced 250ms, server-side ILIKE), tag chips (skill-based: `chat`, `art`, `gaming`, `coach`).
4. Add `/gallery` route to [vercel.json](../../vercel.json).
5. Add a "Make public" toggle to dashboard agent settings (re-uses 03-03 metadata flow).
diff --git a/prompts/build/04-05-visitor-chat.md b/prompts/build/04-05-visitor-chat.md
index d272c75b2..0683d24a8 100644
--- a/prompts/build/04-05-visitor-chat.md
+++ b/prompts/build/04-05-visitor-chat.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Visitors on /agent/:id can chat with the agent — text in, animated voice + text out"
+description: 'Visitors on /agent/:id can chat with the agent — text in, animated voice + text out'
---
# 04-05 · Visitor chat on /agent/:id
diff --git a/prompts/build/04-06-copy-snippet-multi-target.md b/prompts/build/04-06-copy-snippet-multi-target.md
index 1f954947f..02f4e63b2 100644
--- a/prompts/build/04-06-copy-snippet-multi-target.md
+++ b/prompts/build/04-06-copy-snippet-multi-target.md
@@ -21,12 +21,12 @@ A refactor of the share panel on [public/agent/index.html](../../public/agent/in
## Read these first
-| File | Why |
-|:---|:---|
-| [public/agent/index.html](../../public/agent/index.html) | Current share panel — replace. |
-| [public/agent/embed.html](../../public/agent/embed.html) | Target URL shape for the iframe snippet. |
-| [src/element.js](../../src/element.js) | `<agent-3d>` attribute surface for the web-component snippet. |
-| `prompts/build/05-*.md` | Drives the claude-artifact + lobehub-plugin snippet strings once that pillar ships. It's OK if those hosts' runtimes don't exist yet — the snippet picker still generates valid strings for future use. |
+| File | Why |
+| :------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| [public/agent/index.html](../../public/agent/index.html) | Current share panel — replace. |
+| [public/agent/embed.html](../../public/agent/embed.html) | Target URL shape for the iframe snippet. |
+| [src/element.js](../../src/element.js) | `<agent-3d>` attribute surface for the web-component snippet. |
+| `prompts/build/05-*.md` | Drives the claude-artifact + lobehub-plugin snippet strings once that pillar ships. It's OK if those hosts' runtimes don't exist yet — the snippet picker still generates valid strings for future use. |
## Build this
@@ -36,9 +36,9 @@ Create `src/components/snippet-picker.jsx` (vhtml). Signature:
```js
export function SnippetPicker({ agent, origin }) {
- // state: target, size, theme, bg, showName
- // derived: snippet string
- // returns: JSX block mountable into a container
+ // state: target, size, theme, bg, showName
+ // derived: snippet string
+ // returns: JSX block mountable into a container
}
```
@@ -48,13 +48,13 @@ export function SnippetPicker({ agent, origin }) {
function generate(target, opts) { ... }
```
-| Target | Output |
-|:---|:---|
-| `iframe` | `<iframe src="https://<origin>/agent/<id>/embed?size=<s>&theme=<t>&bg=<bg>&name=<n>" width="<w>" height="<h>" style="border:0;background:transparent" loading="lazy"></iframe>` |
-| `web-component` | `<script type="module" src="https://<origin>/dist-lib/index.js"></script>\n<agent-3d agent-id="<id>" size="<s>" theme="<t>" bg="<bg>" name="<n>"></agent-3d>` |
+| Target | Output |
+| :---------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `iframe` | `<iframe src="https://<origin>/agent/<id>/embed?size=<s>&theme=<t>&bg=<bg>&name=<n>" width="<w>" height="<h>" style="border:0;background:transparent" loading="lazy"></iframe>` |
+| `web-component` | `<script type="module" src="https://<origin>/dist-lib/index.js"></script>\n<agent-3d agent-id="<id>" size="<s>" theme="<t>" bg="<bg>" name="<n>"></agent-3d>` |
| `claude-artifact` | The single-file snippet from `05-01-claude-artifact-single-file-bundle` — refer to the target output there. If that pillar hasn't shipped, output a placeholder `<!-- Claude Artifact target not yet available -->` and disable the Copy button with a tooltip. |
-| `lobehub-plugin` | JSON plugin manifest snippet (from `05-03`). Same degrade-gracefully fallback. |
-| `link` | `https://<origin>/agent/<id>` |
+| `lobehub-plugin` | JSON plugin manifest snippet (from `05-03`). Same degrade-gracefully fallback. |
+| `link` | `https://<origin>/agent/<id>` |
### 3. Preview modal
@@ -80,10 +80,12 @@ Iframe target shows two extra number inputs (width/height) pre-filled with size-
## Deliverables
**New:**
+
- `src/components/snippet-picker.jsx`
- `public/preview/web-component.html`
**Modified:**
+
- [public/agent/index.html](../../public/agent/index.html) — replace existing tabbed share panel with SnippetPicker.
- [public/agent/agent.js](../../public/agent/) (if present) — mount SnippetPicker.
- [style.css](../../style.css) — small additions for the picker; reuse token palette.
diff --git a/prompts/build/04-06-seo-and-structured-data.md b/prompts/build/04-06-seo-and-structured-data.md
index 565ec4d48..bb69ee39f 100644
--- a/prompts/build/04-06-seo-and-structured-data.md
+++ b/prompts/build/04-06-seo-and-structured-data.md
@@ -15,13 +15,13 @@ Public agent pages are the only surface we expose to search. Without structured
### Dynamic sitemap — `api/sitemap.xml.js`
- `GET` → `application/xml`. Streams from `agents where visibility = 'public' and deleted_at is null` ordered by `updated_at desc`. One `<url>` per agent:
- ```xml
- <url>
- <loc>https://3dagent.vercel.app/a/{id}</loc>
- <lastmod>{updated_at iso}</lastmod>
- <changefreq>weekly</changefreq>
- </url>
- ```
+ ```xml
+ <url>
+ <loc>https://3dagent.vercel.app/a/{id}</loc>
+ <lastmod>{updated_at iso}</lastmod>
+ <changefreq>weekly</changefreq>
+ </url>
+ ```
- Add the landing page, `/features`, `/docs-widgets`, and the top-level `/` explicitly.
- Cache: `public, max-age=3600`.
- Update [public/robots.txt](../../public/robots.txt) to point at the dynamic path: `Sitemap: https://3dagent.vercel.app/sitemap.xml`. Wire `/sitemap.xml` in [vercel.json](../../vercel.json) to the serverless function.
@@ -32,13 +32,13 @@ Inject a `<script type="application/ld+json">` block into [public/agent/index.ht
```json
{
- "@context": "https://schema.org",
- "@type": "Person",
- "name": "<agent name>",
- "image": "<og-image url>",
- "url": "https://3dagent.vercel.app/a/<id>",
- "identifier": "<agentId>",
- "sameAs": ["<erc8004 explorer url if onchain>"]
+ "@context": "https://schema.org",
+ "@type": "Person",
+ "name": "<agent name>",
+ "image": "<og-image url>",
+ "url": "https://3dagent.vercel.app/a/<id>",
+ "identifier": "<agentId>",
+ "sameAs": ["<erc8004 explorer url if onchain>"]
}
```
diff --git a/prompts/build/04-06-share-card-twitter.md b/prompts/build/04-06-share-card-twitter.md
index 08f045967..e5e6a3945 100644
--- a/prompts/build/04-06-share-card-twitter.md
+++ b/prompts/build/04-06-share-card-twitter.md
@@ -10,25 +10,25 @@ When someone pastes `/agent/<id>` into Twitter, iMessage, WhatsApp, Slack, the u
## Read these first
-| File | Why |
-|:---|:---|
-| [api/agent-og.js](../../api/agent-og.js) | OG image generator. |
-| [public/agent/index.html](../../public/agent/index.html) | Where meta tags belong. |
-| [src/manifest.js](../../src/manifest.js) | Source of name + description. |
-| [api/agent-oembed.js](../../api/agent-oembed.js) | oEmbed for richer hosts. |
+| File | Why |
+| :------------------------------------------------------- | :---------------------------- |
+| [api/agent-og.js](../../api/agent-og.js) | OG image generator. |
+| [public/agent/index.html](../../public/agent/index.html) | Where meta tags belong. |
+| [src/manifest.js](../../src/manifest.js) | Source of name + description. |
+| [api/agent-oembed.js](../../api/agent-oembed.js) | oEmbed for richer hosts. |
## Build this
1. Generate dynamic meta on `/agent/<id>` (server-render the head, even if the body is SPA). Include:
- - `<meta property="og:title">`, `og:description`, `og:image`, `og:url`, `og:type=profile`
- - `<meta name="twitter:card" content="summary_large_image">`
- - `<meta name="twitter:site" content="@3dagent">` (env-configurable handle)
- - `<meta name="twitter:image:alt">` with agent name
- - `<link rel="alternate" type="application/json+oembed" href="…">`
+ - `<meta property="og:title">`, `og:description`, `og:image`, `og:url`, `og:type=profile`
+ - `<meta name="twitter:card" content="summary_large_image">`
+ - `<meta name="twitter:site" content="@3dagent">` (env-configurable handle)
+ - `<meta name="twitter:image:alt">` with agent name
+ - `<link rel="alternate" type="application/json+oembed" href="…">`
2. OG image:
- - 1200×630, agent thumbnail centered on left, name + first sentence of description on right.
- - Reputation stars if on-chain.
- - Watermark `3dagent.vercel.app` bottom-right.
+ - 1200×630, agent thumbnail centered on left, name + first sentence of description on right.
+ - Reputation stars if on-chain.
+ - Watermark `3dagent.vercel.app` bottom-right.
3. Validate with the official validators in the test plan.
4. For widget pages (`/w/<id>`), do the same with widget-flavored copy.
5. Cache the OG image in CDN with `s-maxage=3600, stale-while-revalidate=86400`. Bust by appending `?v=<updated_at>`.
@@ -50,10 +50,10 @@ When someone pastes `/agent/<id>` into Twitter, iMessage, WhatsApp, Slack, the u
## Test plan
1. Deploy a preview branch (or use ngrok). Paste `/agent/<id>` into:
- - Twitter compose box
- - iMessage to self
- - Slack DM
- - WhatsApp Web
+ - Twitter compose box
+ - iMessage to self
+ - Slack DM
+ - WhatsApp Web
2. Confirm large image + correct text in each.
3. Curl `/agent/<id>` and grep for the meta tags.
4. Edit agent name → reload preview → image updates after `?v=` bump.
diff --git a/prompts/build/04-06-share-panel.md b/prompts/build/04-06-share-panel.md
index c97c1412d..fe428a1cc 100644
--- a/prompts/build/04-06-share-panel.md
+++ b/prompts/build/04-06-share-panel.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "One-click share panel on the agent page — link, embed snippet, Claude Artifact, Lobehub"
+description: 'One-click share panel on the agent page — link, embed snippet, Claude Artifact, Lobehub'
---
# 04-06 · Share panel on /agent/:id
@@ -33,20 +33,26 @@ Three tabs:
1. **Link** — the canonical `/agent/:id` URL with a copy button. Shows a preview of the OG card so owners see what it looks like when pasted into Slack/Discord.
2. **Embed** — three one-click snippets:
- - **iframe** — for static sites.
- ```html
- <iframe src="https://3dagent.vercel.app/agent/ID/embed" width="400" height="500" frameborder="0" allow="camera; microphone"></iframe>
- ```
- - **web component** — for modern sites.
- ```html
- <script type="module" src="https://3dagent.vercel.app/agent-3d.js"></script>
- <agent-avatar agent-id="ID" height="500px"></agent-avatar>
- ```
- - **Markdown** — for GitHub READMEs (falls back to an image link to the OG card).
+ - **iframe** — for static sites.
+ ```html
+ <iframe
+ src="https://3dagent.vercel.app/agent/ID/embed"
+ width="400"
+ height="500"
+ frameborder="0"
+ allow="camera; microphone"
+ ></iframe>
+ ```
+ - **web component** — for modern sites.
+ ```html
+ <script type="module" src="https://3dagent.vercel.app/agent-3d.js"></script>
+ <agent-avatar agent-id="ID" height="500px"></agent-avatar>
+ ```
+ - **Markdown** — for GitHub READMEs (falls back to an image link to the OG card).
3. **Apps** — destination launchers (these link out; the actual integrations live in pillar 5 prompts):
- - "Open in Claude.ai" — links to a pre-filled prompt that asks Claude to render the agent via the Artifact shim.
- - "Install in Lobehub" — links to the Lobehub plugin install deep-link (see `05-02`).
- - "Download agent-card.json" — downloads the A2A card for other hosts.
+ - "Open in Claude.ai" — links to a pre-filled prompt that asks Claude to render the agent via the Artifact shim.
+ - "Install in Lobehub" — links to the Lobehub plugin install deep-link (see `05-02`).
+ - "Download agent-card.json" — downloads the A2A card for other hosts.
### Copy UX
diff --git a/prompts/build/05-01-claude-artifact-embed.md b/prompts/build/05-01-claude-artifact-embed.md
index 2620ef779..28a3cf043 100644
--- a/prompts/build/05-01-claude-artifact-embed.md
+++ b/prompts/build/05-01-claude-artifact-embed.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Agent embeds cleanly inside a Claude.ai Artifact with the right iframe hints"
+description: 'Agent embeds cleanly inside a Claude.ai Artifact with the right iframe hints'
---
# 05-01 · Embed in a Claude Artifact
@@ -23,14 +23,17 @@ The novel unlock of pillar 5. A Claude user pastes an agent URL into a chat →
## Build this
1. **Claude-friendly HTML snippet** — produce a canonical Artifact-ready snippet and display it on `/agent/:id` under Share → "Claude Artifact":
- ```html
- <iframe src="https://3dagent.vercel.app/agent/<ID>/embed?kiosk=1&bg=transparent"
- width="100%" height="520"
- style="border:0;border-radius:16px"
- allow="autoplay; fullscreen"
- referrerpolicy="no-referrer-when-downgrade">
- </iframe>
- ```
+ ```html
+ <iframe
+ src="https://3dagent.vercel.app/agent/<ID>/embed?kiosk=1&bg=transparent"
+ width="100%"
+ height="520"
+ style="border:0;border-radius:16px"
+ allow="autoplay; fullscreen"
+ referrerpolicy="no-referrer-when-downgrade"
+ >
+ </iframe>
+ ```
2. **Static HTML fallback** — under the iframe, include a "No-iframe fallback" snippet (for hosts that strip iframes): a link + a static thumbnail image. Claude sometimes strips iframes; graceful degradation matters.
3. **Dynamic resize** — Claude Artifacts can't observe `agent:resize` messages; size the iframe with a fixed aspect ratio fallback. Use a `padding-top: 100%` CSS trick wrapper for square.
4. **Test in a real Claude conversation** — paste the snippet, confirm rendering, record browser console errors if any. If CSP blocks something, narrow the permissions rather than widening.
diff --git a/prompts/build/05-01-claude-artifact-export.md b/prompts/build/05-01-claude-artifact-export.md
index ea6f46439..4cba17d62 100644
--- a/prompts/build/05-01-claude-artifact-export.md
+++ b/prompts/build/05-01-claude-artifact-export.md
@@ -3,19 +3,19 @@
**Branch:** `feat/claude-artifact-export`
**Stack layer:** 5 (Host embed — Claude)
**Depends on:** 04-01 (OG image), 04-02 (embed policy), 04-03 (redacted public fetch)
-**Blocks:** 06-* (onchain resolution wants a concrete host integration to validate against)
+**Blocks:** 06-\* (onchain resolution wants a concrete host integration to validate against)
## Why it matters
-Claude Artifacts are self-contained HTML documents. A user pastes the artifact into a Claude chat and the agent appears *embodied in the conversation* — exactly the novel unlock in the priority stack. This prompt produces the artifact HTML on demand, scoped to a single agent.
+Claude Artifacts are self-contained HTML documents. A user pastes the artifact into a Claude chat and the agent appears _embodied in the conversation_ — exactly the novel unlock in the priority stack. This prompt produces the artifact HTML on demand, scoped to a single agent.
## Read these first
-| File | Why |
-|:---|:---|
-| [src/element.js](../../src/element.js) | `<agent-3d>` web component — the minimal embed surface. |
-| [agent-embed.html](../../agent-embed.html) | Current iframe shell; structurally close to what the artifact will contain. |
-| [api/agents.js](../../api/agents.js), the public `toPublicAgent` helper from 04-03 | The data that goes into the artifact. |
+| File | Why |
+| :------------------------------------------------------------------------------------------------------ | :-------------------------------------------------------------------------- |
+| [src/element.js](../../src/element.js) | `<agent-3d>` web component — the minimal embed surface. |
+| [agent-embed.html](../../agent-embed.html) | Current iframe shell; structurally close to what the artifact will contain. |
+| [api/agents.js](../../api/agents.js), the public `toPublicAgent` helper from 04-03 | The data that goes into the artifact. |
| Claude Artifacts docs — assume: single HTML file, external resources allowed, sandboxed iframe context. |
## Build this
@@ -24,22 +24,24 @@ Claude Artifacts are self-contained HTML documents. A user pastes the artifact i
- **Auth:** public; rate-limited.
- **Output:** a single, self-contained HTML document (content-type `text/html; charset=utf-8`) that:
- 1. Loads the built web-component bundle from the production origin (`<script type="module" src="https://3dagent.vercel.app/dist-lib/agent-3d.js">`).
- 2. Renders `<agent-3d agent-id="<id>" host="claude"></agent-3d>`.
- 3. Sets a viewport meta tag, a dark background, and sane mobile defaults.
- 4. Includes Open Graph meta tags (reusing the 04-01 OG image) so previews of the artifact render correctly outside Claude too.
+ 1. Loads the built web-component bundle from the production origin (`<script type="module" src="https://3dagent.vercel.app/dist-lib/agent-3d.js">`).
+ 2. Renders `<agent-3d agent-id="<id>" host="claude"></agent-3d>`.
+ 3. Sets a viewport meta tag, a dark background, and sane mobile defaults.
+ 4. Includes Open Graph meta tags (reusing the 04-01 OG image) so previews of the artifact render correctly outside Claude too.
The goal: drop-in paste into Claude Artifacts, shows the agent.
### Dashboard UI
On the agent home / dashboard, add a **"Embed in Claude"** button. Clicking it:
+
- Generates a copy-to-clipboard snippet containing the artifact HTML (inlined — not a URL).
- Also offers a short-lived signed URL (`/api/agents/:id/artifact.html?token=...`) for users who prefer linking.
### `host=claude` behaviour
The web component reads its `host` attribute. When `host=claude`:
+
- Disable any hover-only UI (Claude artifacts may sandbox pointer events).
- Default to `kiosk=true` (no dat.gui, no header).
- Cap the canvas devicePixelRatio at 2 to keep perf bounded inside Claude.
diff --git a/prompts/build/05-01-claude-artifact-single-file-bundle.md b/prompts/build/05-01-claude-artifact-single-file-bundle.md
index bbb9f9fba..562f81320 100644
--- a/prompts/build/05-01-claude-artifact-single-file-bundle.md
+++ b/prompts/build/05-01-claude-artifact-single-file-bundle.md
@@ -4,7 +4,7 @@
## Why it matters
-Claude Artifacts render a **single HTML file** in a sandboxed iframe. No external modules (unless via esm.sh / unpkg), no cookies to our origin, no back-channel auth. If our agent can render *inside an Artifact* — visible, speaking, expressive — that's the category shift from "agent is JSON" to "agent is present." This is the #5 pillar.
+Claude Artifacts render a **single HTML file** in a sandboxed iframe. No external modules (unless via esm.sh / unpkg), no cookies to our origin, no back-channel auth. If our agent can render _inside an Artifact_ — visible, speaking, expressive — that's the category shift from "agent is JSON" to "agent is present." This is the #5 pillar.
## What to build
@@ -20,14 +20,14 @@ The artifact embed URL is the copyable snippet from `04-06` for the `claude-arti
## Read these first
-| File | Why |
-|:---|:---|
+| File | Why |
+| :------------------------------------------------------- | :---------------------------------------------------------------------------------------------------- | ----------------------------------------- |
| [public/agent/embed.html](../../public/agent/embed.html) | Closest existing sibling. Artifact version is embed.html minus cookie-auth and plus CDN-only imports. |
-| [src/agent-protocol.js](../../src/agent-protocol.js) | Event vocabulary — same bus inside the artifact. |
-| [src/agent-avatar.js](../../src/agent-avatar.js) | Empathy Layer — must load via dynamic CDN import. |
-| [src/viewer.js](../../src/viewer.js) | Viewer class, its imports. |
-| [api/agents.js](../../api/agents.js) | Public GET `/api/agents/:id` returns public fields when unauthenticated. |
-| [api/avatars/index.js](../../api/avatars/index.js) | Public avatar fetch: ensure `GET /api/avatars/:id` returns a CDN URL for `visibility='public'|'unlisted'` without auth. If not, extend. |
+| [src/agent-protocol.js](../../src/agent-protocol.js) | Event vocabulary — same bus inside the artifact. |
+| [src/agent-avatar.js](../../src/agent-avatar.js) | Empathy Layer — must load via dynamic CDN import. |
+| [src/viewer.js](../../src/viewer.js) | Viewer class, its imports. |
+| [api/agents.js](../../api/agents.js) | Public GET `/api/agents/:id` returns public fields when unauthenticated. |
+| [api/avatars/index.js](../../api/avatars/index.js) | Public avatar fetch: ensure `GET /api/avatars/:id` returns a CDN URL for `visibility='public' | 'unlisted'` without auth. If not, extend. |
## Build this
@@ -46,9 +46,9 @@ The artifact runs in a cross-origin sandbox. Verify `GET /api/avatars/:id`:
- Look up the agent (public fields only).
- Reject if the avatar is private → 403 JSON.
- Render a single HTML string that inlines:
- - Title, noindex meta.
- - Inline CSS (transparent bg, full viewport, no scroll).
- - A single `<script type="module">` with the boot logic.
+ - Title, noindex meta.
+ - Inline CSS (transparent bg, full viewport, no scroll).
+ - A single `<script type="module">` with the boot logic.
- Set `Content-Type: text/html; charset=utf-8` and `Cache-Control: public, max-age=60, stale-while-revalidate=600`.
Template literals for the HTML string; no SSR framework.
@@ -71,12 +71,12 @@ The Empathy Layer from [src/agent-avatar.js](../../src/agent-avatar.js) has to b
Listen for messages with shape `{ __agent: <id>, type, payload }`:
-| Type | Payload | Effect |
-|:---|:---|:---|
-| `speak` | `{ text, sentiment }` | Log + nudge emotion blend (no TTS in artifact) |
-| `emote` | `{ trigger, weight }` | Add to blend |
-| `gesture` | `{ name, duration }` | One-shot morph target pop |
-| `look-at` | `{ target: 'user'\|'camera' }` | Orient head |
+| Type | Payload | Effect |
+| :-------- | :----------------------------- | :--------------------------------------------- |
+| `speak` | `{ text, sentiment }` | Log + nudge emotion blend (no TTS in artifact) |
+| `emote` | `{ trigger, weight }` | Add to blend |
+| `gesture` | `{ name, duration }` | One-shot morph target pop |
+| `look-at` | `{ target: 'user'\|'camera' }` | Orient head |
Validate `event.origin` against an allowlist: `https://claude.ai`, `https://*.lobehub.com`, and the embedder's own origin. Log + ignore everything else.
@@ -98,10 +98,12 @@ Respect `?size=bubble|card|banner|full&bg=transparent|#hex` query params (same v
## Deliverables
**New:**
+
- `api/agents/[id]/artifact.js` — the generator.
- Tiny unit of the Empathy Layer inlined into the HTML template. Keep it short.
**Modified:**
+
- [api/avatars/index.js](../../api/avatars/index.js) (or the `[id].js` variant — check) — ensure public/unlisted avatars return GLB URL without auth + permissive CORS.
- `vercel.json` — route `/api/agents/:id/artifact.html`.
@@ -118,9 +120,12 @@ Respect `?size=bubble|card|banner|full&bg=transparent|#hex` query params (same v
1. Verify GLB fetch from a clean `curl -I` with no cookies returns 200 + `Access-Control-Allow-Origin: *`.
2. Open the artifact URL in a normal browser → avatar renders.
3. Paste this into a Claude Artifact:
- ```html
- <iframe src="https://3dagent.vercel.app/api/agents/<id>/artifact.html" style="width:100%;height:400px;border:0;background:transparent"></iframe>
- ```
- Confirm it renders.
+ ```html
+ <iframe
+ src="https://3dagent.vercel.app/api/agents/<id>/artifact.html"
+ style="width:100%;height:400px;border:0;background:transparent"
+ ></iframe>
+ ```
+ Confirm it renders.
4. From parent page console: `frames[0].postMessage({ __agent: '<id>', type: 'emote', payload: { trigger: 'celebrate', weight: 0.8 } }, '*')` → avatar reacts.
5. Try with a private avatar → artifact shows a clear error message, not a blank.
diff --git a/prompts/build/05-01-claude-artifacts-shim.md b/prompts/build/05-01-claude-artifacts-shim.md
index 8204fb8eb..2545e48c1 100644
--- a/prompts/build/05-01-claude-artifacts-shim.md
+++ b/prompts/build/05-01-claude-artifacts-shim.md
@@ -11,19 +11,19 @@ Claude.ai Artifacts run user-pasted HTML inside a sandboxed iframe (`sandbox="al
## Read these first
-| File | Why |
-|:---|:---|
-| [src/element.js](../../src/element.js) | The `<agent-3d>` web component. Detect Artifact context here. |
-| [src/manifest.js](../../src/manifest.js) | Manifest loader — currently uses same-origin fetch. |
-| [api/agents/[id].js](../../api/agents/[id].js) | Public read shape; verify CORS + cache headers. |
-| [public/agent/embed.html](../../public/agent/embed.html) | Iframe target — must work in nested sandbox. |
-| [vercel.json](../../vercel.json) | Add CORS headers to the public read routes. |
+| File | Why |
+| :------------------------------------------------------- | :------------------------------------------------------------ |
+| [src/element.js](../../src/element.js) | The `<agent-3d>` web component. Detect Artifact context here. |
+| [src/manifest.js](../../src/manifest.js) | Manifest loader — currently uses same-origin fetch. |
+| [api/agents/[id].js](../../api/agents/[id].js) | Public read shape; verify CORS + cache headers. |
+| [public/agent/embed.html](../../public/agent/embed.html) | Iframe target — must work in nested sandbox. |
+| [vercel.json](../../vercel.json) | Add CORS headers to the public read routes. |
## Build this
1. In [src/element.js](../../src/element.js), detect opaque origin: `try { document.cookie } catch { isArtifact = true }` (Artifacts throw `SecurityError`). Also set when `window.location.origin === 'null'`.
2. When `isArtifact`, force absolute URL for every backend call: `https://3dagent.vercel.app/api/...` (read host from `data-host` attribute on the script tag, fall back to `3dagent.vercel.app`).
-3. Add CORS headers to public-read endpoints: `Access-Control-Allow-Origin: *`, `Access-Control-Allow-Methods: GET, OPTIONS`, no credentials. Apply to: `/api/agents/:id`, `/api/widgets/:id`, `/api/avatars/public`, `/api/agents/:id/embed-policy`. Reuse the helper in [api/_lib/http.js](../../api/_lib/http.js) — add `corsPublic(res)`.
+3. Add CORS headers to public-read endpoints: `Access-Control-Allow-Origin: *`, `Access-Control-Allow-Methods: GET, OPTIONS`, no credentials. Apply to: `/api/agents/:id`, `/api/widgets/:id`, `/api/avatars/public`, `/api/agents/:id/embed-policy`. Reuse the helper in [api/\_lib/http.js](../../api/_lib/http.js) — add `corsPublic(res)`.
4. Reject any `credentials: 'include'` fetch when `isArtifact` (cookies are useless in sandbox; sending them just confuses CORS).
5. Add a `data-host` attribute to the canonical embed snippet generator at [embed.html](../../embed.html).
diff --git a/prompts/build/05-02-claude-artifact-copy-button.md b/prompts/build/05-02-claude-artifact-copy-button.md
index 69598e928..cd0f2b25e 100644
--- a/prompts/build/05-02-claude-artifact-copy-button.md
+++ b/prompts/build/05-02-claude-artifact-copy-button.md
@@ -24,11 +24,11 @@ Copying that into a fresh Claude chat reliably produces an artifact with the age
## Read these first
-| File | Why |
-|:---|:---|
-| `src/components/snippet-picker.jsx` (from 04-06) | Where the snippet string lives. |
-| `api/agents/[id]/artifact.js` (from 05-01) | Target URL. |
-| [public/agent/index.html](../../public/agent/index.html) | Share panel mount. |
+| File | Why |
+| :------------------------------------------------------- | :------------------------------ |
+| `src/components/snippet-picker.jsx` (from 04-06) | Where the snippet string lives. |
+| `api/agents/[id]/artifact.js` (from 05-01) | Target URL. |
+| [public/agent/index.html](../../public/agent/index.html) | Share panel mount. |
## Build this
@@ -83,9 +83,11 @@ Keep short — one screen, no tabs.
## Deliverables
**New:**
+
- `public/preview/claude-artifact.html` — 20-line test harness.
**Modified:**
+
- `src/components/snippet-picker.jsx` — generator + copy flow + hint text.
- `public/agent/index.html` (or wherever SnippetPicker mounts) — confirm the `claude-artifact` tab is no longer a placeholder.
diff --git a/prompts/build/05-02-lobehub-plugin-manifest.md b/prompts/build/05-02-lobehub-plugin-manifest.md
index e14fa8418..80ddba850 100644
--- a/prompts/build/05-02-lobehub-plugin-manifest.md
+++ b/prompts/build/05-02-lobehub-plugin-manifest.md
@@ -3,7 +3,7 @@
**Branch:** `feat/lobehub-plugin`
**Stack layer:** 5 (Host embed — Lobehub — the user's primary integration target)
**Depends on:** 04-02 (embed policy), 04-03 (public decorate), 05-01 (web component bundle)
-**Blocks:** 06-* (onchain → Lobehub demo)
+**Blocks:** 06-\* (onchain → Lobehub demo)
## Why it matters
@@ -11,18 +11,19 @@ The user has a Lobehub fork — the primary integration target for the whole pro
## Read these first
-| File | Why |
-|:---|:---|
-| LobeChat plugin schema — `lobe-chat-plugin-sdk` docs | Plugin manifest shape, API route conventions. Confirm before wiring. |
-| [src/element.js](../../src/element.js) | `<agent-3d>` — the embeddable render surface. |
-| [api/agents.js](../../api/agents.js) with 04-03 applied | Public agent fetch. |
-| [api/agents/[id]/embed-policy.js](../../api/agents/[id]/embed-policy.js) from 04-02 | Lobehub's origin must be added to default allowlists here. |
+| File | Why |
+| :---------------------------------------------------------------------------------- | :------------------------------------------------------------------- |
+| LobeChat plugin schema — `lobe-chat-plugin-sdk` docs | Plugin manifest shape, API route conventions. Confirm before wiring. |
+| [src/element.js](../../src/element.js) | `<agent-3d>` — the embeddable render surface. |
+| [api/agents.js](../../api/agents.js) with 04-03 applied | Public agent fetch. |
+| [api/agents/[id]/embed-policy.js](../../api/agents/[id]/embed-policy.js) from 04-02 | Lobehub's origin must be added to default allowlists here. |
## Build this
### Plugin manifest — `GET /api/lobehub/manifest.json`
Serve a valid LobeChat plugin manifest with:
+
- `identifier`: `3dagent`
- `version`: from `package.json`
- `api`: a single tool — `showAgent(agentId: string)` — that returns a `text/html` widget embedding `<agent-3d agent-id="<id>" host="lobehub"></agent-3d>`.
@@ -38,6 +39,7 @@ Serve a valid LobeChat plugin manifest with:
### `host=lobehub` behaviour in `<agent-3d>`
Mirror the `host=claude` treatment from 05-01:
+
- Kiosk defaults.
- Listen for LobeChat theme messages (dark / light) via postMessage and apply to the canvas background.
- Cap DPR to 2.
diff --git a/prompts/build/05-02-lobehub-plugin.md b/prompts/build/05-02-lobehub-plugin.md
index a56542050..1798c9c4a 100644
--- a/prompts/build/05-02-lobehub-plugin.md
+++ b/prompts/build/05-02-lobehub-plugin.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Produce a Lobehub plugin manifest so an agent URL renders embodied in Lobehub chat"
+description: 'Produce a Lobehub plugin manifest so an agent URL renders embodied in Lobehub chat'
---
# 05-02 · Lobehub plugin manifest
@@ -17,24 +17,24 @@ The user maintains a Lobehub fork. The product's killer demo is: paste an agent
## Read these first
- Lobehub plugin docs (external). Link and summarize in the PR description — Lobehub uses a `lobe-chat-plugin` manifest convention. We need to produce:
- - A plugin manifest JSON.
- - An openapi-ish schema describing inputs.
- - A render hint so Lobehub renders our iframe rather than JSON.
+ - A plugin manifest JSON.
+ - An openapi-ish schema describing inputs.
+ - A render hint so Lobehub renders our iframe rather than JSON.
- [public/agent/embed.html](../../public/agent/embed.html)
- Existing `src/element.js` — `<agent-3d>` web component.
## Build this
1. **New endpoint** `GET /.well-known/lobehub-plugin.json` (or the exact path Lobehub requires — confirm from the docs):
- - Describes the plugin: name, description, icon, author, homepage.
- - Declares a `renderer` of type `iframe` pointing at `/agent/{id}/embed?kiosk=1`.
- - Inputs: `agent_id` (string).
+ - Describes the plugin: name, description, icon, author, homepage.
+ - Declares a `renderer` of type `iframe` pointing at `/agent/{id}/embed?kiosk=1`.
+ - Inputs: `agent_id` (string).
2. **New endpoint** `POST /api/lobehub/resolve`:
- - Accepts `{ agent_id }`, returns `{ iframe_url, card_url, name, description }`.
- - Uses `agent-card.json` internally for the metadata.
+ - Accepts `{ agent_id }`, returns `{ iframe_url, card_url, name, description }`.
+ - Uses `agent-card.json` internally for the metadata.
3. **Installation snippet** — on `/agent/:id` Share panel, add a "Lobehub" tab with:
- - A one-click "Install in your Lobehub" link that deep-links into the user's Lobehub fork plugin registry (confirm Lobehub deep-link format from docs).
- - A manual JSON snippet for users whose Lobehub doesn't support deep-link install.
+ - A one-click "Install in your Lobehub" link that deep-links into the user's Lobehub fork plugin registry (confirm Lobehub deep-link format from docs).
+ - A manual JSON snippet for users whose Lobehub doesn't support deep-link install.
4. **User's fork** — note in the PR: if the plugin needs to be pre-registered in the fork's plugin registry rather than self-hosted, we add a PR to the fork. Don't write that PR here; flag it as next step.
## Out of scope
diff --git a/prompts/build/05-03-lobehub-plugin-manifest.md b/prompts/build/05-03-lobehub-plugin-manifest.md
index e44f24f46..78335930f 100644
--- a/prompts/build/05-03-lobehub-plugin-manifest.md
+++ b/prompts/build/05-03-lobehub-plugin-manifest.md
@@ -4,7 +4,7 @@
## Why it matters
-User has a Lobehub fork and it's the *primary* integration target per the priority stack. Lobehub plugins are installed via a plugin manifest (JSON) that registers tools + UI surfaces. Our avatar needs to show up in Lobehub as an installable plugin so any Lobehub user can add their 3D agent to their chat.
+User has a Lobehub fork and it's the _primary_ integration target per the priority stack. Lobehub plugins are installed via a plugin manifest (JSON) that registers tools + UI surfaces. Our avatar needs to show up in Lobehub as an installable plugin so any Lobehub user can add their 3D agent to their chat.
## What to build
@@ -12,11 +12,11 @@ A public endpoint `GET /api/agents/:id/lobe-plugin.json` that returns a **Lobehu
## Read these first
-| File | Why |
-|:---|:---|
-| [api/agents.js](../../api/agents.js) | Public fields of an agent. |
-| `api/agents/[id]/artifact.js` (from 05-01) | Artifact URL — the Lobehub plugin uses this (or a Lobehub-specific variant). |
-| Lobehub plugin docs (for your reference; user has the fork — don't assume an API that doesn't exist in the fork) | Manifest schema. |
+| File | Why |
+| :--------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------- |
+| [api/agents.js](../../api/agents.js) | Public fields of an agent. |
+| `api/agents/[id]/artifact.js` (from 05-01) | Artifact URL — the Lobehub plugin uses this (or a Lobehub-specific variant). |
+| Lobehub plugin docs (for your reference; user has the fork — don't assume an API that doesn't exist in the fork) | Manifest schema. |
## Build this
@@ -29,32 +29,40 @@ A public endpoint `GET /api/agents/:id/lobe-plugin.json` that returns a **Lobehu
```json
{
- "$schema": "https://chat-plugins.lobehub.com/schema/plugin.json",
- "identifier": "3d-agent-<agentId>",
- "api": [
- {
- "url": "https://3dagent.vercel.app/api/agents/<agentId>/lobe/tool/<name>",
- "name": "emote",
- "description": "Have the agent express an emotion: celebrate, concern, curiosity, empathy, patience, neutral.",
- "parameters": { "type": "object", "properties": { "emotion": { "type": "string" }, "weight": { "type": "number" } }, "required": ["emotion"] }
- },
- {
- "url": "https://3dagent.vercel.app/api/agents/<agentId>/lobe/tool/gesture",
- "name": "gesture",
- "description": "Trigger a one-shot gesture.",
- "parameters": { "type": "object", "properties": { "name": { "type": "string" } }, "required": ["name"] }
- }
- ],
- "ui": {
- "url": "https://3dagent.vercel.app/api/agents/<agentId>/lobe-ui.html",
- "height": 420
- },
- "meta": {
- "avatar": "<agent.avatar_thumbnail_url or favicon>",
- "title": "<agent.name>",
- "description": "<agent.description>",
- "tags": ["3d", "avatar", "embodied"]
- }
+ "$schema": "https://chat-plugins.lobehub.com/schema/plugin.json",
+ "identifier": "3d-agent-<agentId>",
+ "api": [
+ {
+ "url": "https://3dagent.vercel.app/api/agents/<agentId>/lobe/tool/<name>",
+ "name": "emote",
+ "description": "Have the agent express an emotion: celebrate, concern, curiosity, empathy, patience, neutral.",
+ "parameters": {
+ "type": "object",
+ "properties": { "emotion": { "type": "string" }, "weight": { "type": "number" } },
+ "required": ["emotion"]
+ }
+ },
+ {
+ "url": "https://3dagent.vercel.app/api/agents/<agentId>/lobe/tool/gesture",
+ "name": "gesture",
+ "description": "Trigger a one-shot gesture.",
+ "parameters": {
+ "type": "object",
+ "properties": { "name": { "type": "string" } },
+ "required": ["name"]
+ }
+ }
+ ],
+ "ui": {
+ "url": "https://3dagent.vercel.app/api/agents/<agentId>/lobe-ui.html",
+ "height": 420
+ },
+ "meta": {
+ "avatar": "<agent.avatar_thumbnail_url or favicon>",
+ "title": "<agent.name>",
+ "description": "<agent.description>",
+ "tags": ["3d", "avatar", "embodied"]
+ }
}
```
@@ -63,6 +71,7 @@ A public endpoint `GET /api/agents/:id/lobe-plugin.json` that returns a **Lobehu
### 2. UI iframe endpoint
`GET /api/agents/:id/lobe-ui.html` — a Lobehub-optimized variant of the artifact. It's the artifact HTML from 05-01 with:
+
- Lobehub-friendly CSS (full width, 420px height default).
- postMessage origin allowlist includes Lobehub-fork hostnames.
- Chat log hook: listens for `{ type: 'lobe:message', payload: { role, content } }` and when `role === 'assistant'`, emits `speak` + derived emotion.
@@ -71,11 +80,11 @@ A public endpoint `GET /api/agents/:id/lobe-plugin.json` that returns a **Lobehu
Each tool in the manifest maps to `POST /api/agents/:id/lobe/tool/:name`:
-| Tool | Effect |
-|:---|:---|
-| `emote` | Emits an emote event to the agent's runtime bus (via the UI iframe's channel). |
-| `gesture` | Same. |
-| `speak` | Feeds an override line to the agent's TTS (if enabled). |
+| Tool | Effect |
+| :-------- | :----------------------------------------------------------------------------- |
+| `emote` | Emits an emote event to the agent's runtime bus (via the UI iframe's channel). |
+| `gesture` | Same. |
+| `speak` | Feeds an override line to the agent's TTS (if enabled). |
These endpoints do NOT call our server mutating APIs — they post to a broadcast channel the UI iframe listens to. Effectively a thin proxy to `postMessage` since Lobehub's plugin runtime is disconnected from our iframe.
@@ -101,11 +110,13 @@ Plus the install instructions ("Paste this URL in Lobehub → Settings → Plugi
## Deliverables
**New:**
+
- `api/agents/[id]/lobe-plugin.js` — manifest endpoint.
- `api/agents/[id]/lobe-ui.js` — UI iframe variant.
- `api/agents/[id]/lobe/tool/[name].js` — tool proxy endpoints.
**Modified:**
+
- `src/components/snippet-picker.jsx` (from 04-06) — `lobehub-plugin` target returns the manifest URL + install instructions.
- `vercel.json` — routes.
diff --git a/prompts/build/05-03-mcp-spawn-agent-tool.md b/prompts/build/05-03-mcp-spawn-agent-tool.md
index 501d58223..6cba34c8b 100644
--- a/prompts/build/05-03-mcp-spawn-agent-tool.md
+++ b/prompts/build/05-03-mcp-spawn-agent-tool.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Expose a render_agent MCP tool so Claude/hosts can spawn an agent body in a conversation"
+description: 'Expose a render_agent MCP tool so Claude/hosts can spawn an agent body in a conversation'
---
# 05-03 · MCP `render_agent` tool
@@ -22,19 +22,30 @@ Pillar 5's reach. Any MCP-compatible host (Claude, Claude Desktop, Lobehub) that
## Build this
1. **Add tool** `render_agent` to the MCP tool list in `api/mcp.js`:
- - Inputs: `{ id: string }`.
- - Scope: none (public). No auth required — the returned card is already public.
- - Returns:
- ```json
- {
- "content": [
- { "type": "text", "text": "Render this 3D agent: <name>" },
- { "type": "resource", "resource": { "uri": "https://.../agent/<id>/embed?kiosk=1", "mimeType": "text/html" } }
- ],
- "structuredContent": { "card_url": "...", "embed_url": "...", "name": "...", "description": "..." }
- }
- ```
- - Rate-limit: reuse `limits.mcpIp` or add a `limits.mcpRender` preset if usage justifies.
+ - Inputs: `{ id: string }`.
+ - Scope: none (public). No auth required — the returned card is already public.
+ - Returns:
+ ```json
+ {
+ "content": [
+ { "type": "text", "text": "Render this 3D agent: <name>" },
+ {
+ "type": "resource",
+ "resource": {
+ "uri": "https://.../agent/<id>/embed?kiosk=1",
+ "mimeType": "text/html"
+ }
+ }
+ ],
+ "structuredContent": {
+ "card_url": "...",
+ "embed_url": "...",
+ "name": "...",
+ "description": "..."
+ }
+ }
+ ```
+ - Rate-limit: reuse `limits.mcpIp` or add a `limits.mcpRender` preset if usage justifies.
2. **Usage event** — emit a `usage_events` row with `kind='mcp_render_agent', tool='render_agent'`.
3. **Update MCP catalog** in any `/.well-known` descriptor and the tool list endpoint if present.
4. **Smoke test** with the MCP inspector (`npx @modelcontextprotocol/inspector`) pointing at the dev server.
diff --git a/prompts/build/05-03-postmessage-event-bridge.md b/prompts/build/05-03-postmessage-event-bridge.md
index ab870585a..bc3235f10 100644
--- a/prompts/build/05-03-postmessage-event-bridge.md
+++ b/prompts/build/05-03-postmessage-event-bridge.md
@@ -11,30 +11,32 @@ Hosts (Claude Artifacts, Lobehub, ChatGPT canvas, generic iframes) need a unifor
## Read these first
-| File | Why |
-|:---|:---|
-| [src/element.js](../../src/element.js) | Mount point for the bridge. |
-| [src/agent-protocol.js](../../src/agent-protocol.js) | Bus that bridges messages dispatch into. |
-| [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md) | Embed spec — append the host-message protocol section here. |
-| [src/agent-skills.js](../../src/agent-skills.js) | Skill execution — what `host:perform-skill` calls. |
+| File | Why |
+| :--------------------------------------------------- | :---------------------------------------------------------- |
+| [src/element.js](../../src/element.js) | Mount point for the bridge. |
+| [src/agent-protocol.js](../../src/agent-protocol.js) | Bus that bridges messages dispatch into. |
+| [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md) | Embed spec — append the host-message protocol section here. |
+| [src/agent-skills.js](../../src/agent-skills.js) | Skill execution — what `host:perform-skill` calls. |
## Build this
1. Add `src/host-bridge.js` — small ESM module exporting `mountHostBridge(element, protocol)`. Listens to `window.message`, validates origin against `element.dataset.allowOrigins` (CSV) or a sane default (Claude, Lobehub, same-origin).
2. Define and document the protocol (extend [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md)):
- **Inbound (host → agent):**
- - `host:hello` `{ host, version }` → reply `agent:ready { agentId, capabilities, version }`
- - `host:set-context` `{ agentId?, theme?, locale? }` → swap context live
- - `host:perform-skill` `{ skill, args, callId }` → reply `agent:skill-result { callId, ok, result|error }`
- - `host:say` `{ text }` → triggers `speak` action on bus
- - `host:resize` `{ width, height }` → element adopts dimensions
-
- **Outbound (agent → host):**
- - `agent:ready` (boot complete)
- - `agent:action` `{ type, payload }` (mirror of every protocol bus event)
- - `agent:request-resize` `{ height }` (when content height changes)
- - `agent:request-auth` (when user clicks something requiring SIWE)
+ **Inbound (host → agent):**
+
+ - `host:hello` `{ host, version }` → reply `agent:ready { agentId, capabilities, version }`
+ - `host:set-context` `{ agentId?, theme?, locale? }` → swap context live
+ - `host:perform-skill` `{ skill, args, callId }` → reply `agent:skill-result { callId, ok, result|error }`
+ - `host:say` `{ text }` → triggers `speak` action on bus
+ - `host:resize` `{ width, height }` → element adopts dimensions
+
+ **Outbound (agent → host):**
+
+ - `agent:ready` (boot complete)
+ - `agent:action` `{ type, payload }` (mirror of every protocol bus event)
+ - `agent:request-resize` `{ height }` (when content height changes)
+ - `agent:request-auth` (when user clicks something requiring SIWE)
3. Wire `mountHostBridge` from `<agent-3d>` connected callback. Tear down on disconnect.
4. Add a `data-host-debug="1"` attribute that logs every inbound + outbound message to console (off by default).
diff --git a/prompts/build/05-04-host-postmessage-contract.md b/prompts/build/05-04-host-postmessage-contract.md
index c53e36016..a19ee5556 100644
--- a/prompts/build/05-04-host-postmessage-contract.md
+++ b/prompts/build/05-04-host-postmessage-contract.md
@@ -12,13 +12,13 @@ A spec file + a tiny helper library used by the agent iframe AND any host that w
## Read these first
-| File | Why |
-|:---|:---|
-| [public/agent/embed.html](../../public/agent/embed.html) | Current message loop. |
-| `api/agents/[id]/artifact.js` (from 05-01) | Artifact message loop. |
-| `api/agents/[id]/lobe-ui.js` (from 05-03) | Lobehub message loop. |
-| [specs/](../../specs/) | Where the spec file goes. |
-| [src/agent-protocol.js](../../src/agent-protocol.js) | Internal event vocabulary — the outer postMessage protocol mirrors this. |
+| File | Why |
+| :------------------------------------------------------- | :----------------------------------------------------------------------- |
+| [public/agent/embed.html](../../public/agent/embed.html) | Current message loop. |
+| `api/agents/[id]/artifact.js` (from 05-01) | Artifact message loop. |
+| `api/agents/[id]/lobe-ui.js` (from 05-03) | Lobehub message loop. |
+| [specs/](../../specs/) | Where the spec file goes. |
+| [src/agent-protocol.js](../../src/agent-protocol.js) | Internal event vocabulary — the outer postMessage protocol mirrors this. |
## Build this
@@ -28,18 +28,18 @@ Document:
- **Envelope:** every message has `{ __agent: <agentId>, v: 1, type, payload }`. Reject messages missing `__agent` or where `__agent` ≠ our agent id.
- **Inbound types (host → agent):**
- - `speak` `{ text: string, sentiment?: number }` — agent logs + nudges emotion (no TTS in sandbox contexts).
- - `emote` `{ trigger: string, weight: number }` — add to emotion blend (clamped 0..1).
- - `gesture` `{ name: string, duration?: number }` — one-shot clip.
- - `look-at` `{ target: 'user' | 'camera' | 'model' }` — reorient head.
- - `load-avatar` `{ avatarId: string }` — swap the loaded GLB (only if same owner; otherwise ignored).
- - `ping` `{}` — responds with `pong`.
+ - `speak` `{ text: string, sentiment?: number }` — agent logs + nudges emotion (no TTS in sandbox contexts).
+ - `emote` `{ trigger: string, weight: number }` — add to emotion blend (clamped 0..1).
+ - `gesture` `{ name: string, duration?: number }` — one-shot clip.
+ - `look-at` `{ target: 'user' | 'camera' | 'model' }` — reorient head.
+ - `load-avatar` `{ avatarId: string }` — swap the loaded GLB (only if same owner; otherwise ignored).
+ - `ping` `{}` — responds with `pong`.
- **Outbound types (agent → host):**
- - `ready` `{ name: string, avatar_id: string, chain?: { id, token_id } }`
- - `error` `{ message: string, code?: string }`
- - `state` `{ emotion: { concern, celebration, patience, curiosity, empathy }, currentClip?: string }` — throttled to 10 Hz.
- - `action-done` `{ type, ok: boolean, detail? }` — ack for inbound messages.
- - `pong` `{}` — response to ping.
+ - `ready` `{ name: string, avatar_id: string, chain?: { id, token_id } }`
+ - `error` `{ message: string, code?: string }`
+ - `state` `{ emotion: { concern, celebration, patience, curiosity, empathy }, currentClip?: string }` — throttled to 10 Hz.
+ - `action-done` `{ type, ok: boolean, detail? }` — ack for inbound messages.
+ - `pong` `{}` — response to ping.
- **Origin allowlist:** `https://claude.ai`, `https://*.lobehub.com`, `https://3dagent.vercel.app`, and the embedding page's origin itself. Anything else → log + ignore.
- **Version negotiation:** `v` defaults to 1. If host sends `v: 2` we don't know, reply with `{ type: 'error', code: 'unsupported_version' }` and ignore the payload.
@@ -49,13 +49,18 @@ Two exports:
```js
// Used INSIDE agent iframe
-export function createAgentBridge({ agentId, onMessage, allowedOrigins }) { /* returns { post, destroy } */ }
+export function createAgentBridge({ agentId, onMessage, allowedOrigins }) {
+ /* returns { post, destroy } */
+}
// Used by hosts (including our own test harness) to drive an agent iframe
-export function createHostBridge({ frame, agentId, onMessage }) { /* returns { emote, gesture, speak, lookAt, ping, destroy } */ }
+export function createHostBridge({ frame, agentId, onMessage }) {
+ /* returns { emote, gesture, speak, lookAt, ping, destroy } */
+}
```
Both:
+
- Filter messages by `__agent` + origin.
- Drop malformed payloads silently (don't throw on untrusted input).
- Auto-reply to `ping`.
@@ -64,6 +69,7 @@ Both:
### 3. Adopt the bridge
Replace ad-hoc listeners in:
+
- [public/agent/embed.html](../../public/agent/embed.html)
- `api/agents/[id]/artifact.js` inlined boot script (inline a minified copy of the bridge — can't import cross-origin from the artifact).
- `api/agents/[id]/lobe-ui.js`
@@ -82,11 +88,13 @@ Replace ad-hoc listeners in:
## Deliverables
**New:**
+
- `specs/EMBED_POSTMESSAGE.md`
- `src/lib/embed-bridge.js`
- `public/preview/embed-tester.html`
**Modified:**
+
- [public/agent/embed.html](../../public/agent/embed.html) — adopt bridge.
- `api/agents/[id]/artifact.js` (05-01) — inline the bridge code.
- `api/agents/[id]/lobe-ui.js` (05-03) — adopt bridge.
diff --git a/prompts/build/05-04-host-postmessage-protocol.md b/prompts/build/05-04-host-postmessage-protocol.md
index 47dafb25d..ea34344d2 100644
--- a/prompts/build/05-04-host-postmessage-protocol.md
+++ b/prompts/build/05-04-host-postmessage-protocol.md
@@ -23,24 +23,24 @@ All messages are JSON-serializable. Always include `v`. The agent ignores messag
### Host → agent messages
-| type | payload | behavior |
-|---|---|---|
-| `init` | `{ originAllowlist?: string[] }` | handshake — agent replies with `ready` |
-| `speak` | `{ text, voice?: 'system' }` | emits `speech:say` on the protocol bus |
-| `play_animation` | `{ slot: 'wave' | 'nod' | 'shake' | 'think' }` | emits `empathy:<slot>` |
-| `set_mood` | `{ mood: 'happy'|'sad'|'neutral'|'surprised' }` | emits `empathy:mood` |
-| `resize` | `{ width, height }` | lets the host tell the agent to re-layout (useful inside auto-sizing panels) |
-| `dispose` | `{}` | cleans up and emits `ready: false` |
+| type | payload | behavior |
+| ---------------- | -------------------------------- | ---------------------------------------------------------------------------- | --------- | -------------- | ---------------------- |
+| `init` | `{ originAllowlist?: string[] }` | handshake — agent replies with `ready` |
+| `speak` | `{ text, voice?: 'system' }` | emits `speech:say` on the protocol bus |
+| `play_animation` | `{ slot: 'wave' | 'nod' | 'shake' | 'think' }` | emits `empathy:<slot>` |
+| `set_mood` | `{ mood: 'happy' | 'sad' | 'neutral' | 'surprised' }` | emits `empathy:mood` |
+| `resize` | `{ width, height }` | lets the host tell the agent to re-layout (useful inside auto-sizing panels) |
+| `dispose` | `{}` | cleans up and emits `ready: false` |
### Agent → host messages
-| type | payload | when |
-|---|---|---|
-| `ready` | `{ agentId, capabilities: string[] }` | once after load |
-| `speaking_started` / `speaking_ended` | `{ utteranceId }` | while TTS plays |
-| `animation_started` / `animation_ended` | `{ slot }` | per animation |
-| `click` | `{ region: 'head'|'body'|'hand' }` | user clicks the avatar (if host enabled) |
-| `error` | `{ code, message }` | non-fatal failures |
+| type | payload | when |
+| --------------------------------------- | ------------------------------------- | ------------------ | --------- | ---------------------------------------- |
+| `ready` | `{ agentId, capabilities: string[] }` | once after load |
+| `speaking_started` / `speaking_ended` | `{ utteranceId }` | while TTS plays |
+| `animation_started` / `animation_ended` | `{ slot }` | per animation |
+| `click` | `{ region: 'head' | 'body' | 'hand' }` | user clicks the avatar (if host enabled) |
+| `error` | `{ code, message }` | non-fatal failures |
### Origin handshake
diff --git a/prompts/build/05-04-host-theme-sync.md b/prompts/build/05-04-host-theme-sync.md
index 5f0dc5e02..0aa8c5ffb 100644
--- a/prompts/build/05-04-host-theme-sync.md
+++ b/prompts/build/05-04-host-theme-sync.md
@@ -10,20 +10,20 @@ When our agent embeds in Lobehub or Claude Artifacts, a black background on a wh
## Read these first
-| File | Why |
-|:---|:---|
-| [src/host-bridge.js](../../src/host-bridge.js) | Bridge to extend. |
-| [src/viewer.js](../../src/viewer.js) | `setBackgroundColor`, `setEnvironment`. |
-| [src/agent-home.js](../../src/agent-home.js) | Renders the identity card — needs to honor theme. |
-| [style.css](../../style.css) | CSS tokens — verify `--bg`, `--fg`, `--accent` exist. |
+| File | Why |
+| :--------------------------------------------- | :---------------------------------------------------- |
+| [src/host-bridge.js](../../src/host-bridge.js) | Bridge to extend. |
+| [src/viewer.js](../../src/viewer.js) | `setBackgroundColor`, `setEnvironment`. |
+| [src/agent-home.js](../../src/agent-home.js) | Renders the identity card — needs to honor theme. |
+| [style.css](../../style.css) | CSS tokens — verify `--bg`, `--fg`, `--accent` exist. |
## Build this
1. Extend `host:set-context` to accept `theme: 'light' | 'dark' | 'auto'` (auto = follow `prefers-color-scheme`).
2. When theme changes:
- - Toggle a `data-theme="light|dark"` attribute on the embed root.
- - Switch viewer background: dark → `#0a0a0a`, light → `#f7f7f7`.
- - Switch HDR environment to `studio-soft` (light) vs `neutral` (dark) — only if the user hasn't pinned an env in the widget config.
+ - Toggle a `data-theme="light|dark"` attribute on the embed root.
+ - Switch viewer background: dark → `#0a0a0a`, light → `#f7f7f7`.
+ - Switch HDR environment to `studio-soft` (light) vs `neutral` (dark) — only if the user hasn't pinned an env in the widget config.
3. Add CSS rules under `[data-theme="light"]` overriding the dark tokens (`--bg`, `--fg`, etc.) — keep it minimal, no new design system.
4. If the host doesn't send a theme, fall back to `prefers-color-scheme`.
diff --git a/prompts/build/05-04-postmessage-bridge-spec.md b/prompts/build/05-04-postmessage-bridge-spec.md
index 1f6d4cc21..129faaf3e 100644
--- a/prompts/build/05-04-postmessage-bridge-spec.md
+++ b/prompts/build/05-04-postmessage-bridge-spec.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Freeze the host↔agent postMessage bridge as a versioned contract + tiny JS SDK"
+description: 'Freeze the host↔agent postMessage bridge as a versioned contract + tiny JS SDK'
---
# 05-04 · Host ↔ agent postMessage bridge
@@ -21,28 +21,28 @@ Third-party hosts (Lobehub fork, Claude Artifacts, future embedders) only work r
## Build this
1. **Document the contract** at the top of `public/agent/embed.html` as a comment block:
- ```
- Bridge v1
- Host → iframe:
- { type: 'agent:action', agentId, action } // forward action to protocol bus
- { type: 'agent:hello', agentId, host } // handshake; iframe replies with agent:ready
- { type: 'agent:ping', id } // liveness; replies agent:pong
- Iframe → host:
- { type: 'agent:ready', agentId, version, capabilities: [...] }
- { type: 'agent:action', agentId, action } // echo of actions emitted
- { type: 'agent:resize', agentId, height }
- { type: 'agent:pong', id }
- All messages include `agentId`. Unknown `type` values are ignored.
- ```
+ ```
+ Bridge v1
+ Host → iframe:
+ { type: 'agent:action', agentId, action } // forward action to protocol bus
+ { type: 'agent:hello', agentId, host } // handshake; iframe replies with agent:ready
+ { type: 'agent:ping', id } // liveness; replies agent:pong
+ Iframe → host:
+ { type: 'agent:ready', agentId, version, capabilities: [...] }
+ { type: 'agent:action', agentId, action } // echo of actions emitted
+ { type: 'agent:resize', agentId, height }
+ { type: 'agent:pong', id }
+ All messages include `agentId`. Unknown `type` values are ignored.
+ ```
2. **Implement** matching handlers in `public/agent/embed.html` if any are missing.
3. **Add a tiny JS SDK** `public/embed-sdk.js` (≤ 100 lines) that a host developer can `<script src="...">` and use:
- ```js
- const bridge = Agent3D.connect(iframeEl, { agentId, onAction, onReady, onResize });
- bridge.send({ type: 'present-model', url: '...' });
- ```
- - Two-way message routing.
- - Auto-resize the iframe to reported height.
- - Timeout on hello → fallback behavior.
+ ```js
+ const bridge = Agent3D.connect(iframeEl, { agentId, onAction, onReady, onResize });
+ bridge.send({ type: 'present-model', url: '...' });
+ ```
+ - Two-way message routing.
+ - Auto-resize the iframe to reported height.
+ - Timeout on hello → fallback behavior.
4. **Link from Share panel** — add a "Custom embed" tab that shows the bridge docs and links to `embed-sdk.js`.
## Out of scope
diff --git a/prompts/build/05-05-host-resize-and-mode.md b/prompts/build/05-05-host-resize-and-mode.md
index 97debd002..aa8c10394 100644
--- a/prompts/build/05-05-host-resize-and-mode.md
+++ b/prompts/build/05-05-host-resize-and-mode.md
@@ -10,21 +10,21 @@ The agent needs to fit the host's layout — sometimes inline (300px), sometimes
## Read these first
-| File | Why |
-|:---|:---|
-| [src/element.js](../../src/element.js) | Existing `mode` attribute (inline | floating | section | fullscreen). |
-| [src/host-bridge.js](../../src/host-bridge.js) | Bridge to extend (created in 05-03). |
-| [src/viewer.js](../../src/viewer.js) | `resize()` method or equivalent — the canvas needs to react. |
-| [style.css](../../style.css) | Mode-specific CSS classes. |
+| File | Why |
+| :--------------------------------------------- | :----------------------------------------------------------- | -------- | ------- | ------------ |
+| [src/element.js](../../src/element.js) | Existing `mode` attribute (inline | floating | section | fullscreen). |
+| [src/host-bridge.js](../../src/host-bridge.js) | Bridge to extend (created in 05-03). |
+| [src/viewer.js](../../src/viewer.js) | `resize()` method or equivalent — the canvas needs to react. |
+| [style.css](../../style.css) | Mode-specific CSS classes. |
## Build this
1. Extend the bridge inbound protocol with `host:set-mode { mode }` — accepted values: `inline | floating | section | fullscreen`.
2. On mode change:
- - Update `data-mode` on the embed root.
- - Call `viewer.resize()` after the next animation frame.
- - In `floating` mode, position absolute bottom-right with a 16px margin and a max-size of 240×240.
- - In `fullscreen` mode, fix to viewport, hide all chrome.
+ - Update `data-mode` on the embed root.
+ - Call `viewer.resize()` after the next animation frame.
+ - In `floating` mode, position absolute bottom-right with a 16px margin and a max-size of 240×240.
+ - In `fullscreen` mode, fix to viewport, hide all chrome.
3. Add `agent:request-resize { width, height }` outbound — emit when the avatar's natural display height changes (e.g. caption text wraps to a new line).
4. Listen to `ResizeObserver` on the host iframe element (when `data-host-bridge-track="1"`) and call `viewer.resize()` automatically.
5. Honor `prefers-reduced-motion` — disable the floating-mode entrance bounce.
diff --git a/prompts/build/05-05-host-speak-bridge.md b/prompts/build/05-05-host-speak-bridge.md
index f87f6407b..f6d98db4a 100644
--- a/prompts/build/05-05-host-speak-bridge.md
+++ b/prompts/build/05-05-host-speak-bridge.md
@@ -4,7 +4,7 @@
## Why it matters
-Both Claude Artifact and Lobehub can pipe the assistant's current reply into the agent iframe. What's missing is the *sentiment analysis* step — without it, the agent just mouths words silently. The Empathy Layer needs a valence + arousal signal per utterance.
+Both Claude Artifact and Lobehub can pipe the assistant's current reply into the agent iframe. What's missing is the _sentiment analysis_ step — without it, the agent just mouths words silently. The Empathy Layer needs a valence + arousal signal per utterance.
## What to build
@@ -12,11 +12,11 @@ A tiny client-side sentiment scorer that the host bridge runs before calling `sp
## Read these first
-| File | Why |
-|:---|:---|
-| [src/agent-avatar.js](../../src/agent-avatar.js) | The Empathy Layer's stimulus rules — what the avatar does with sentiment. |
-| `src/lib/embed-bridge.js` (from 05-04) | Where this wires in. |
-| [src/agent-protocol.js](../../src/agent-protocol.js) | `speak` event payload shape. |
+| File | Why |
+| :--------------------------------------------------- | :------------------------------------------------------------------------ |
+| [src/agent-avatar.js](../../src/agent-avatar.js) | The Empathy Layer's stimulus rules — what the avatar does with sentiment. |
+| `src/lib/embed-bridge.js` (from 05-04) | Where this wires in. |
+| [src/agent-protocol.js](../../src/agent-protocol.js) | `speak` event payload shape. |
## Build this
@@ -24,11 +24,12 @@ A tiny client-side sentiment scorer that the host bridge runs before calling `sp
```js
export function score(text) {
- // returns { sentiment: -1..1, arousal: 0..1, tags: string[] }
+ // returns { sentiment: -1..1, arousal: 0..1, tags: string[] }
}
```
Implementation sketch:
+
- Normalize: lowercase, strip punctuation except `!`, `?`.
- Bag-of-words counts against small positive/negative dictionaries (inline literals — no file I/O).
- Arousal: presence of `!`, ALL CAPS ratio, exclamation density.
@@ -42,14 +43,15 @@ Extend the `speak` method on `createHostBridge` (from 05-04):
```js
function speak(text, overrides = {}) {
- const { sentiment, arousal, tags } = score(text);
- post('speak', { text, sentiment, arousal, tags, ...overrides });
+ const { sentiment, arousal, tags } = score(text);
+ post('speak', { text, sentiment, arousal, tags, ...overrides });
}
```
### 3. Agent-side wiring
Inside the iframe (embed.html / artifact / lobe-ui), when a `speak` message arrives:
+
- Always nudge emotion: positive `sentiment` → celebration weight; negative → concern; high `arousal` → curiosity.
- If `tags` include a direct emotion name, emit `emote` with that trigger + weight 0.4.
- Still log to timeline regardless.
@@ -72,9 +74,11 @@ The artifact (05-01) already accepts inbound `speak`; nothing to change beyond e
## Deliverables
**New:**
+
- `src/lib/sentiment-heuristic.js`
**Modified:**
+
- `src/lib/embed-bridge.js` (05-04) — auto-score on `speak`.
- Agent iframe runtimes (05-01, 05-03, embed.html) — honor `sentiment`/`arousal`/`tags`.
diff --git a/prompts/build/05-06-csp-and-sandbox-compat.md b/prompts/build/05-06-csp-and-sandbox-compat.md
index 9aa8a932e..3b373582d 100644
--- a/prompts/build/05-06-csp-and-sandbox-compat.md
+++ b/prompts/build/05-06-csp-and-sandbox-compat.md
@@ -10,34 +10,34 @@ Strict hosts apply Content-Security-Policy and `<iframe sandbox>` restrictions.
## Read these first
-| File | Why |
-|:---|:---|
-| [src/element.js](../../src/element.js) | Mount point — verify no inline event handlers added at runtime. |
-| [vite.config.js](../../vite.config.js) | Build config — can disable `eval`-like outputs. |
-| [public/agent/embed.html](../../public/agent/embed.html) | The embed page — must work under strict CSP. |
-| [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md) | Spec to extend. |
+| File | Why |
+| :------------------------------------------------------- | :-------------------------------------------------------------- |
+| [src/element.js](../../src/element.js) | Mount point — verify no inline event handlers added at runtime. |
+| [vite.config.js](../../vite.config.js) | Build config — can disable `eval`-like outputs. |
+| [public/agent/embed.html](../../public/agent/embed.html) | The embed page — must work under strict CSP. |
+| [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md) | Spec to extend. |
## Build this
1. Audit the production bundle for forbidden patterns:
- - `eval(`, `new Function(`, `Function('return`
- - inline `<script>` without nonce
- - inline `on*` handlers
- - `javascript:` URLs
- Use a one-shot grep against `dist/` after `npm run build`. Document in the PR.
+ - `eval(`, `new Function(`, `Function('return`
+ - inline `<script>` without nonce
+ - inline `on*` handlers
+ - `javascript:` URLs
+ Use a one-shot grep against `dist/` after `npm run build`. Document in the PR.
2. If three.js / dat.gui pull in any of the above, gate them behind a build flag (`TARGET=embed`) or replace the offender. Document any unavoidable exception in the spec.
3. Add a recommended host CSP block to [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md):
- ```
- frame-src 'self' https://3dagent.vercel.app https://3d.irish;
- script-src 'self' https://3dagent.vercel.app;
- img-src 'self' https://3dagent.vercel.app data: blob:;
- connect-src 'self' https://3dagent.vercel.app https://*.r2.cloudflarestorage.com;
- ```
+ ```
+ frame-src 'self' https://3dagent.vercel.app https://3d.irish;
+ script-src 'self' https://3dagent.vercel.app;
+ img-src 'self' https://3dagent.vercel.app data: blob:;
+ connect-src 'self' https://3dagent.vercel.app https://*.r2.cloudflarestorage.com;
+ ```
4. Add a recommended `iframe sandbox` block:
- ```
- sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"
- ```
- Document the failure mode if `allow-same-origin` is omitted (no cookies, must use 05-01 shim).
+ ```
+ sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"
+ ```
+ Document the failure mode if `allow-same-origin` is omitted (no cookies, must use 05-01 shim).
5. Set `Permissions-Policy` headers on `/agent/:id/embed` to restrict cameras/mics unless the agent declares them in its manifest.
## Out of scope
diff --git a/prompts/build/05-06-lobehub-chat-role-follow.md b/prompts/build/05-06-lobehub-chat-role-follow.md
index 0380160eb..d367c42a5 100644
--- a/prompts/build/05-06-lobehub-chat-role-follow.md
+++ b/prompts/build/05-06-lobehub-chat-role-follow.md
@@ -4,28 +4,28 @@
## Why it matters
-In a Lobehub chat, there are two speakers: user and assistant. A present agent should *look like* it's listening when the user types, and *speak* (animate) when the assistant replies. This is the sub-second cue that sells "present" over "rendered."
+In a Lobehub chat, there are two speakers: user and assistant. A present agent should _look like_ it's listening when the user types, and _speak_ (animate) when the assistant replies. This is the sub-second cue that sells "present" over "rendered."
## What to build
Tap into Lobehub's chat lifecycle events (which the fork already emits) and translate them to agent bus events:
-| Lobehub event | Agent effect |
-|:---|:---|
-| User starts typing | `emote:patience + look-at:user` |
-| User sends message | `emote:curiosity` brief pulse |
-| Assistant begins streaming | `gesture:speak-start` (subtle mouth pre-shape) |
-| Assistant token arrives | continuous `emote:sentiment` from `05-05` scoring of the partial |
-| Assistant finishes | `gesture:speak-end` (return to neutral gaze) |
-| Error / rate limit | `emote:concern + look-at:user` |
+| Lobehub event | Agent effect |
+| :------------------------- | :--------------------------------------------------------------- |
+| User starts typing | `emote:patience + look-at:user` |
+| User sends message | `emote:curiosity` brief pulse |
+| Assistant begins streaming | `gesture:speak-start` (subtle mouth pre-shape) |
+| Assistant token arrives | continuous `emote:sentiment` from `05-05` scoring of the partial |
+| Assistant finishes | `gesture:speak-end` (return to neutral gaze) |
+| Error / rate limit | `emote:concern + look-at:user` |
## Read these first
-| File | Why |
-|:---|:---|
-| `api/agents/[id]/lobe-ui.js` (from 05-03) | The iframe that runs inside Lobehub. |
-| `src/lib/embed-bridge.js` (from 05-04) | Bridge API. |
-| `src/lib/sentiment-heuristic.js` (from 05-05) | Score function. |
+| File | Why |
+| :------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `api/agents/[id]/lobe-ui.js` (from 05-03) | The iframe that runs inside Lobehub. |
+| `src/lib/embed-bridge.js` (from 05-04) | Bridge API. |
+| `src/lib/sentiment-heuristic.js` (from 05-05) | Score function. |
| User's Lobehub fork — `/chat` UI or plugin runtime | What `postMessage` events Lobehub actually emits into plugin UIs. **Grep the fork first**; do not assume an API. If the fork doesn't emit these, add the minimum bridge hook in the fork (separate PR against the fork) and document it here. |
## Build this
@@ -64,9 +64,11 @@ When idle (no chat activity for 5s), gently look back to the camera and settle t
## Deliverables
**New:**
+
- If the fork needs a patch: `lobehub-patch.md` in this repo documenting the diff to apply in the Lobehub fork (separate checkout).
**Modified:**
+
- `api/agents/[id]/lobe-ui.js` — full listener + role follow behavior.
## Acceptance
diff --git a/prompts/build/05-07-embed-perf-budget.md b/prompts/build/05-07-embed-perf-budget.md
index 3f2646d4b..7deac90bc 100644
--- a/prompts/build/05-07-embed-perf-budget.md
+++ b/prompts/build/05-07-embed-perf-budget.md
@@ -10,23 +10,23 @@ When the embed is the first thing a user sees inside another app, slow cold star
## Read these first
-| File | Why |
-|:---|:---|
+| File | Why |
+| :------------------------------------- | :---------------------------------------------- |
| [vite.config.js](../../vite.config.js) | Bundle config — needs a separate `embed` entry. |
-| [src/element.js](../../src/element.js) | Boot path — find what's eagerly imported. |
-| [src/lib.js](../../src/lib.js) | Library entry — current bundle composition. |
-| [package.json](../../package.json) | `build:lib` script. |
+| [src/element.js](../../src/element.js) | Boot path — find what's eagerly imported. |
+| [src/lib.js](../../src/lib.js) | Library entry — current bundle composition. |
+| [package.json](../../package.json) | `build:lib` script. |
## Build this
1. Add a new Vite build target `embed` that produces `dist-embed/`. Entry: `src/embed-bootstrap.js` — a tiny shim (~10KB) that:
- - Reads the agent id from script tag.
- - Renders a placeholder dot/loader.
- - Dynamically imports the heavy bundle on `requestIdleCallback` (or after IntersectionObserver fires).
+ - Reads the agent id from script tag.
+ - Renders a placeholder dot/loader.
+ - Dynamically imports the heavy bundle on `requestIdleCallback` (or after IntersectionObserver fires).
2. Code-split:
- - **Always:** bootstrap, host-bridge, agent-protocol stub.
- - **Lazy on visible:** Three.js, viewer, agent-avatar.
- - **Lazy on first interaction:** ethers, agent-identity, agent-skills tools.
+ - **Always:** bootstrap, host-bridge, agent-protocol stub.
+ - **Lazy on visible:** Three.js, viewer, agent-avatar.
+ - **Lazy on first interaction:** ethers, agent-identity, agent-skills tools.
3. Add a CI check that fails if the always-loaded chunk exceeds 50KB gzipped.
4. Preload the lazy chunks on hover (when the embed dot becomes visible) using `<link rel="modulepreload">`.
5. Inline a 1KB CSS-only loading shimmer so the user sees something within 100ms.
diff --git a/prompts/build/05-07-host-identity-handshake.md b/prompts/build/05-07-host-identity-handshake.md
index 4cca3494d..0ae03b586 100644
--- a/prompts/build/05-07-host-identity-handshake.md
+++ b/prompts/build/05-07-host-identity-handshake.md
@@ -12,11 +12,11 @@ Extend the `ready` outbound message from the agent iframe to carry the full iden
## Read these first
-| File | Why |
-|:---|:---|
-| `src/lib/embed-bridge.js` (from 05-04) | `ready` envelope lives here. |
-| [api/agents.js](../../api/agents.js) `decorate()` | Fields available for public consumers. |
-| `specs/EMBED_POSTMESSAGE.md` (from 05-04) | Where to document the extended `ready`. |
+| File | Why |
+| :------------------------------------------------ | :-------------------------------------- |
+| `src/lib/embed-bridge.js` (from 05-04) | `ready` envelope lives here. |
+| [api/agents.js](../../api/agents.js) `decorate()` | Fields available for public consumers. |
+| `specs/EMBED_POSTMESSAGE.md` (from 05-04) | Where to document the extended `ready`. |
## Build this
@@ -60,6 +60,7 @@ Update the three host UIs:
### 5. Privacy defaults
Do NOT send:
+
- `user_id` (owner)
- `email`
- Internal skill URLs (just the short names).
@@ -76,6 +77,7 @@ Any host-facing URL must be the public `home_url`, not an authenticated dashboar
## Deliverables
**Modified:**
+
- `src/lib/embed-bridge.js` — extended `ready` payload.
- `public/agent/embed.html` — emit extended `ready`.
- `api/agents/[id]/artifact.js` (05-01) — emit extended `ready`.
diff --git a/prompts/build/05-07-referrer-allowlist-enforcement.md b/prompts/build/05-07-referrer-allowlist-enforcement.md
index 6b83436fd..cceca3aef 100644
--- a/prompts/build/05-07-referrer-allowlist-enforcement.md
+++ b/prompts/build/05-07-referrer-allowlist-enforcement.md
@@ -19,13 +19,13 @@ Reroute `/a/:id/embed` through a serverless function that:
1. Loads the agent's `agent_embed_policies` row.
2. If `require_referrer = true`:
- - Extract `Referer` header (fall back to `Origin` / `Sec-Fetch-Site` for stricter browsers).
- - If the request is top-level (Sec-Fetch-Site: `none`) and `require_referrer` is true → allow only if the policy explicitly whitelists `*` or the page's own origin.
- - Match the referrer origin against `origin_allowlist`. Support glob entries like `https://*.lobehub.com`.
+ - Extract `Referer` header (fall back to `Origin` / `Sec-Fetch-Site` for stricter browsers).
+ - If the request is top-level (Sec-Fetch-Site: `none`) and `require_referrer` is true → allow only if the policy explicitly whitelists `*` or the page's own origin.
+ - Match the referrer origin against `origin_allowlist`. Support glob entries like `https://*.lobehub.com`.
3. On match → serve the existing static [public/agent/embed.html](../../public/agent/embed.html) with:
- - `Content-Security-Policy: frame-ancestors <joined-allowlist>;`
- - `X-Frame-Options` omitted intentionally (CSP is authoritative and CSP `frame-ancestors` deprecates XFO).
- - `X-Robots-Tag: noindex`.
+ - `Content-Security-Policy: frame-ancestors <joined-allowlist>;`
+ - `X-Frame-Options` omitted intentionally (CSP is authoritative and CSP `frame-ancestors` deprecates XFO).
+ - `X-Robots-Tag: noindex`.
4. On miss → `403` with a styled explainer page (HTML) that names the expected allowlist and a "Contact agent owner" mailto. Do not leak the full allowlist; show only the requested origin.
### Vercel rewrite
diff --git a/prompts/build/05-08-host-auth-bridge.md b/prompts/build/05-08-host-auth-bridge.md
index 6b609cfc5..e1734993c 100644
--- a/prompts/build/05-08-host-auth-bridge.md
+++ b/prompts/build/05-08-host-auth-bridge.md
@@ -2,20 +2,20 @@
**Branch:** `feat/host-auth-bridge`
**Stack layer:** 5 (Host embed)
-**Depends on:** 05-03 (postMessage bridge), 01-* (wallet auth)
+**Depends on:** 05-03 (postMessage bridge), 01-\* (wallet auth)
## Why it matters
-A user viewing an agent inside Lobehub may want to *adopt* it — write to its memory, sign actions on its behalf, link it to their wallet. From inside an opaque-origin sandbox they can't use cookies. We need a popup-based SIWE flow that returns a short-lived bearer token to the embed via postMessage.
+A user viewing an agent inside Lobehub may want to _adopt_ it — write to its memory, sign actions on its behalf, link it to their wallet. From inside an opaque-origin sandbox they can't use cookies. We need a popup-based SIWE flow that returns a short-lived bearer token to the embed via postMessage.
## Read these first
-| File | Why |
-|:---|:---|
-| [api/auth/siwe/](../../api/auth/siwe/) | Existing SIWE endpoints — reuse, don't duplicate. |
-| [src/host-bridge.js](../../src/host-bridge.js) | Bridge to extend. |
-| [api/_lib/auth.js](../../api/_lib/auth.js) | Bearer token issuance — likely already supports JWT. |
-| [public/wallet-login.js](../../public/wallet-login.js) | Existing SIWE client. |
+| File | Why |
+| :----------------------------------------------------- | :--------------------------------------------------- |
+| [api/auth/siwe/](../../api/auth/siwe/) | Existing SIWE endpoints — reuse, don't duplicate. |
+| [src/host-bridge.js](../../src/host-bridge.js) | Bridge to extend. |
+| [api/\_lib/auth.js](../../api/_lib/auth.js) | Bearer token issuance — likely already supports JWT. |
+| [public/wallet-login.js](../../public/wallet-login.js) | Existing SIWE client. |
## Build this
diff --git a/prompts/build/05-09-skill-permissions-prompt.md b/prompts/build/05-09-skill-permissions-prompt.md
index 2c83e1edc..9597bcf84 100644
--- a/prompts/build/05-09-skill-permissions-prompt.md
+++ b/prompts/build/05-09-skill-permissions-prompt.md
@@ -2,7 +2,7 @@
**Branch:** `feat/host-skill-permissions`
**Stack layer:** 5 (Host embed)
-**Depends on:** 05-08 (auth bridge), 11-* (mcp-skills bridge)
+**Depends on:** 05-08 (auth bridge), 11-\* (mcp-skills bridge)
## Why it matters
@@ -10,18 +10,18 @@ If a host can ask the embedded agent to perform a skill (`host:perform-skill`),
## Read these first
-| File | Why |
-|:---|:---|
-| [src/agent-skills.js](../../src/agent-skills.js) | Skill registry — each skill has a `dangerLevel` field (add if missing). |
-| [src/host-bridge.js](../../src/host-bridge.js) | Bridge that routes `host:perform-skill`. |
-| [src/agent-protocol.js](../../src/agent-protocol.js) | `perform-skill` event — gate before dispatch. |
+| File | Why |
+| :--------------------------------------------------- | :---------------------------------------------------------------------- |
+| [src/agent-skills.js](../../src/agent-skills.js) | Skill registry — each skill has a `dangerLevel` field (add if missing). |
+| [src/host-bridge.js](../../src/host-bridge.js) | Bridge that routes `host:perform-skill`. |
+| [src/agent-protocol.js](../../src/agent-protocol.js) | `perform-skill` event — gate before dispatch. |
## Build this
1. Add a `dangerLevel: 'safe' | 'medium' | 'high'` field to each built-in skill in [src/agent-skills.js](../../src/agent-skills.js):
- - `safe`: greet, present-model, think — no prompt.
- - `medium`: remember, sign-action — prompt once per origin per session.
- - `high`: any skill that calls external APIs or moves money — prompt every call.
+ - `safe`: greet, present-model, think — no prompt.
+ - `medium`: remember, sign-action — prompt once per origin per session.
+ - `high`: any skill that calls external APIs or moves money — prompt every call.
2. Add `src/permission-prompt.js` — small DOM module that renders an in-iframe overlay: "{host} wants to use skill **{skillName}**. Allow once / Allow always / Deny." Returns a Promise.
3. Wire into the bridge: when `host:perform-skill` arrives, look up `dangerLevel`, prompt as needed, store the decision in `sessionStorage` keyed by `${hostOrigin}:${skillId}`.
4. Reject denied calls with `agent:skill-result { ok: false, error: 'permission_denied' }`.
diff --git a/prompts/build/06-01-erc8004-deploy-base-sepolia.md b/prompts/build/06-01-erc8004-deploy-base-sepolia.md
index 580f71196..f3111a425 100644
--- a/prompts/build/06-01-erc8004-deploy-base-sepolia.md
+++ b/prompts/build/06-01-erc8004-deploy-base-sepolia.md
@@ -4,7 +4,7 @@
## Why it matters
-Pillar 6 promises: the same agent renders inside any host app *directly from its onchain record*. That requires three registries deployed on a public chain: `IdentityRegistry`, `ReputationRegistry`, `ValidationRegistry`. The contracts exist in [contracts/src/](../../contracts/src/) but may not be deployed anywhere non-local, or the deployed addresses may not be wired into [src/erc8004/abi.js](../../src/erc8004/abi.js)'s `REGISTRY_DEPLOYMENTS`. Ship this first; everything downstream (06-02+) assumes it.
+Pillar 6 promises: the same agent renders inside any host app _directly from its onchain record_. That requires three registries deployed on a public chain: `IdentityRegistry`, `ReputationRegistry`, `ValidationRegistry`. The contracts exist in [contracts/src/](../../contracts/src/) but may not be deployed anywhere non-local, or the deployed addresses may not be wired into [src/erc8004/abi.js](../../src/erc8004/abi.js)'s `REGISTRY_DEPLOYMENTS`. Ship this first; everything downstream (06-02+) assumes it.
## What to build
@@ -12,15 +12,15 @@ A clean deployment to Base Sepolia + wired addresses + a public block explorer l
## Read these first
-| File | Why |
-|:---|:---|
-| [contracts/src/IdentityRegistry.sol](../../contracts/src/IdentityRegistry.sol) | The three registries. |
-| [contracts/src/ReputationRegistry.sol](../../contracts/src/ReputationRegistry.sol) | |
-| [contracts/src/ValidationRegistry.sol](../../contracts/src/ValidationRegistry.sol) | |
-| [contracts/script/Deploy.s.sol](../../contracts/script/Deploy.s.sol) | Existing Foundry script. Read it and confirm it deploys the three in one run. |
-| [contracts/foundry.toml](../../contracts/foundry.toml) | Network profile. |
-| [src/erc8004/abi.js](../../src/erc8004/abi.js) | `REGISTRY_DEPLOYMENTS` keyed by chainId. Add Base Sepolia entries after deploy. |
-| [contracts/CLAUDE.md](../../contracts/CLAUDE.md) | Local project rules. |
+| File | Why |
+| :--------------------------------------------------------------------------------- | :------------------------------------------------------------------------------ |
+| [contracts/src/IdentityRegistry.sol](../../contracts/src/IdentityRegistry.sol) | The three registries. |
+| [contracts/src/ReputationRegistry.sol](../../contracts/src/ReputationRegistry.sol) | |
+| [contracts/src/ValidationRegistry.sol](../../contracts/src/ValidationRegistry.sol) | |
+| [contracts/script/Deploy.s.sol](../../contracts/script/Deploy.s.sol) | Existing Foundry script. Read it and confirm it deploys the three in one run. |
+| [contracts/foundry.toml](../../contracts/foundry.toml) | Network profile. |
+| [src/erc8004/abi.js](../../src/erc8004/abi.js) | `REGISTRY_DEPLOYMENTS` keyed by chainId. Add Base Sepolia entries after deploy. |
+| [contracts/CLAUDE.md](../../contracts/CLAUDE.md) | Local project rules. |
## Build this
@@ -37,6 +37,7 @@ Confirm all three contracts deploy and pass any existing tests. If tests fail, s
### 2. Deploy to Base Sepolia
Requirements:
+
- `DEPLOYER_PRIVATE_KEY` in env (never committed).
- ~0.05 ETH test balance on Base Sepolia (faucet: `https://www.coinbase.com/faucets/base-ethereum-sepolia-faucet`).
@@ -86,10 +87,12 @@ Use `cast` or a tiny script to call a read function on IdentityRegistry and conf
## Deliverables
**Modified:**
+
- [src/erc8004/abi.js](../../src/erc8004/abi.js) — add Base Sepolia entry.
- [contracts/README.md](../../contracts/README.md) — deployment table.
**Runtime artifacts (check in under contracts/broadcast/):**
+
- Foundry broadcast logs. Git should track these per Foundry convention.
## Acceptance
diff --git a/prompts/build/06-01-erc8004-mint-from-ui.md b/prompts/build/06-01-erc8004-mint-from-ui.md
index d40d8886f..907aaa10a 100644
--- a/prompts/build/06-01-erc8004-mint-from-ui.md
+++ b/prompts/build/06-01-erc8004-mint-from-ui.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Let a signed-in user mint an ERC-8004 agent id from the agent page"
+description: 'Let a signed-in user mint an ERC-8004 agent id from the agent page'
---
# 06-01 · Mint ERC-8004 id from UI
@@ -26,10 +26,10 @@ Pillar 6 begins here. The agent record lives on-chain, portable across hosts. To
## Build this
1. **New page** `/agent/:id/register` (owner-only) with a step wizard:
- - Step 1 — connect wallet (reuse `wallet-login.js` logic; if already linked via 01-03, skip).
- - Step 2 — preview the agent-card.json payload that will be committed.
- - Step 3 — confirm chain + network fee, sign & send the `registerAgent` tx via the user's wallet (ethers `BrowserProvider`).
- - Step 4 — on success: extract the `AgentRegistered` event's `agentId`, `PUT /api/agents/:id/wallet` with `{ erc8004_agent_id, chain_id, wallet_address }`.
+ - Step 1 — connect wallet (reuse `wallet-login.js` logic; if already linked via 01-03, skip).
+ - Step 2 — preview the agent-card.json payload that will be committed.
+ - Step 3 — confirm chain + network fee, sign & send the `registerAgent` tx via the user's wallet (ethers `BrowserProvider`).
+ - Step 4 — on success: extract the `AgentRegistered` event's `agentId`, `PUT /api/agents/:id/wallet` with `{ erc8004_agent_id, chain_id, wallet_address }`.
2. **Error states** — wrong network, insufficient funds, user rejected, contract revert — each gets a clear message and a retry button. No cryptic hex strings shown.
3. **Display on `/agent/:id`** — if `erc8004_agent_id` is set, show "On-chain: #<id> on <chain>" with a block-explorer link. Read-only badge.
4. **Anti-double-register guard** — if agent already has `erc8004_agent_id`, the register page shows a "Already registered" state with the id and link; no double-mint.
diff --git a/prompts/build/06-01-onchain-registration-ui.md b/prompts/build/06-01-onchain-registration-ui.md
index dbab69fb8..a1932be74 100644
--- a/prompts/build/06-01-onchain-registration-ui.md
+++ b/prompts/build/06-01-onchain-registration-ui.md
@@ -11,14 +11,14 @@ The ERC-8004 contracts are deployed ([src/erc8004/abi.js](../../src/erc8004/abi.
## Read these first
-| File | Why |
-|:---|:---|
-| [src/erc8004/register-ui.js](../../src/erc8004/register-ui.js) | Existing component — understand its current API before wiring. |
-| [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js) | `registerAgent()`, `buildRegistrationJSON()`, `pinToIPFS()`. |
-| [src/erc8004/abi.js](../../src/erc8004/abi.js) | ABIs + deployed addresses. |
-| [src/erc8004/privy.js](../../src/erc8004/privy.js) | Existing Privy integration stubs. |
-| [src/agent-identity.js](../../src/agent-identity.js) | Client model; `/api/agents/:id` PATCH accepts `wallet_address`, `chain_id`. |
-| [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js) | Mount the new tab here. |
+| File | Why |
+| :------------------------------------------------------------------- | :-------------------------------------------------------------------------- |
+| [src/erc8004/register-ui.js](../../src/erc8004/register-ui.js) | Existing component — understand its current API before wiring. |
+| [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js) | `registerAgent()`, `buildRegistrationJSON()`, `pinToIPFS()`. |
+| [src/erc8004/abi.js](../../src/erc8004/abi.js) | ABIs + deployed addresses. |
+| [src/erc8004/privy.js](../../src/erc8004/privy.js) | Existing Privy integration stubs. |
+| [src/agent-identity.js](../../src/agent-identity.js) | Client model; `/api/agents/:id` PATCH accepts `wallet_address`, `chain_id`. |
+| [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js) | Mount the new tab here. |
## Build this
@@ -27,19 +27,21 @@ The ERC-8004 contracts are deployed ([src/erc8004/abi.js](../../src/erc8004/abi.
New tab on an agent's detail view: **"Onchain Identity"**. Three states:
1. **Not registered.**
- - Summary of what registration does ("Your agent gets a portable, verifiable identity on-chain…").
- - Chain picker (default to Base Sepolia if available in `REGISTRY_DEPLOYMENTS`, switchable to mainnet).
- - "Connect wallet" — reuse the Privy flow from 01-01.
- - "Register" button → builds the registration JSON (name, bio, avatar URL, skills, web presence URL = `https://3dagent.vercel.app/agent/<slug>`), pins to IPFS via [agent-registry.js](../../src/erc8004/agent-registry.js)'s `pinToIPFS()`, then calls `registerAgent()`.
- - Progress states: pinning → signing → waiting confirmation → complete.
+
+ - Summary of what registration does ("Your agent gets a portable, verifiable identity on-chain…").
+ - Chain picker (default to Base Sepolia if available in `REGISTRY_DEPLOYMENTS`, switchable to mainnet).
+ - "Connect wallet" — reuse the Privy flow from 01-01.
+ - "Register" button → builds the registration JSON (name, bio, avatar URL, skills, web presence URL = `https://3dagent.vercel.app/agent/<slug>`), pins to IPFS via [agent-registry.js](../../src/erc8004/agent-registry.js)'s `pinToIPFS()`, then calls `registerAgent()`.
+ - Progress states: pinning → signing → waiting confirmation → complete.
2. **Pending.**
- - Show tx hash + block explorer link. Poll for confirmation.
+
+ - Show tx hash + block explorer link. Poll for confirmation.
3. **Registered.**
- - Show ERC-8004 `agent_id`, chain, IPFS URI, block explorer link, registered wallet.
- - "Re-pin metadata" button for when agent profile changes.
- - "Unregister" / "Transfer" — not in this prompt; render as disabled "coming soon".
+ - Show ERC-8004 `agent_id`, chain, IPFS URI, block explorer link, registered wallet.
+ - "Re-pin metadata" button for when agent profile changes.
+ - "Unregister" / "Transfer" — not in this prompt; render as disabled "coming soon".
### Backend — `PATCH /api/agents/:id`
diff --git a/prompts/build/06-01-supported-trust-wizard.md b/prompts/build/06-01-supported-trust-wizard.md
index 8d302c72e..ecc0d282b 100644
--- a/prompts/build/06-01-supported-trust-wizard.md
+++ b/prompts/build/06-01-supported-trust-wizard.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Add supportedTrust multi-select to the ERC-8004 registration wizard and edit modal"
+description: 'Add supportedTrust multi-select to the ERC-8004 registration wizard and edit modal'
---
# 06-01 · supportedTrust Multi-Select in ERC-8004 Wizard
@@ -37,6 +37,7 @@ export function buildRegistrationJSON({
```
And the `json` object sets:
+
```js
supportedTrust: ['reputation'],
```
@@ -59,6 +60,7 @@ export function buildRegistrationJSON({
```
In the `json` object, replace the hardcoded line with:
+
```js
supportedTrust: Array.isArray(supportedTrust) && supportedTrust.length > 0
? supportedTrust
@@ -70,24 +72,29 @@ supportedTrust: Array.isArray(supportedTrust) && supportedTrust.length > 0
There are two form objects in `src/erc8004/register-ui.js`:
**Primary form init** (around line 270 in the constructor, after `x402Support: false`):
+
```js
services: [],
x402Support: false,
apiToken: '',
```
+
Add `supportedTrust: ['reputation'],` after `x402Support: false`.
**Scratch reset** (around line 680, inside `_resetWizard` when `mode === 'scratch'`):
+
```js
services: [],
x402Support: false,
apiToken: this.form.apiToken || '',
```
+
Add `supportedTrust: ['reputation'],` after `x402Support: false`.
### 3. `_renderStepServices` — add checkbox group
In `_renderStepServices`, find the x402 checkbox block:
+
```html
<label class="erc8004-checkbox" style="margin-top:12px">
<input type="checkbox" data-role="x402" ${this.form.x402Support ? 'checked' : ''} />
@@ -96,6 +103,7 @@ In `_renderStepServices`, find the x402 checkbox block:
```
Add a trust multi-select block immediately after it:
+
```html
<fieldset class="erc8004-fieldset" style="margin-top:14px;border:1px solid var(--erc8004-border,#333);border-radius:6px;padding:10px 12px">
<legend class="erc8004-label" style="padding:0 4px">Trust models</legend>
@@ -110,37 +118,40 @@ Add a trust multi-select block immediately after it:
```
Then in the JS wiring section of `_renderStepServices` (after the x402 change listener), add listeners for each trust checkbox:
+
```js
['reputation', 'validation', 'stake'].forEach((t) => {
- body.querySelector(`[data-role="trust-${t}"]`).addEventListener('change', () => {
- const checked = ['reputation', 'validation', 'stake'].filter(
- (x) => body.querySelector(`[data-role="trust-${x}"]`)?.checked,
- );
- this.form.supportedTrust = checked.length > 0 ? checked : ['reputation'];
- });
+ body.querySelector(`[data-role="trust-${t}"]`).addEventListener('change', () => {
+ const checked = ['reputation', 'validation', 'stake'].filter(
+ (x) => body.querySelector(`[data-role="trust-${x}"]`)?.checked,
+ );
+ this.form.supportedTrust = checked.length > 0 ? checked : ['reputation'];
+ });
});
```
### 4. `_doRegister` — pass `supportedTrust` to `registerAgent`
In `_doRegister` (line ~1347), find the `registerAgent` call:
+
```js
return await registerAgent({
- name,
- description,
- glbFile: glbFile || undefined,
- glbUrl: glbUrl || undefined,
- imageUrl: imageUrl || undefined,
- apiToken: apiToken || undefined,
- services: extraServices,
- x402Support: !!this.form.x402Support,
- onStatus: say,
+ name,
+ description,
+ glbFile: glbFile || undefined,
+ glbUrl: glbUrl || undefined,
+ imageUrl: imageUrl || undefined,
+ apiToken: apiToken || undefined,
+ services: extraServices,
+ x402Support: !!this.form.x402Support,
+ onStatus: say,
});
```
`registerAgent` calls `buildRegistrationJSON` internally. Look at how `registerAgent` is defined in `src/erc8004/agent-registry.js` (around line 218+) — add `supportedTrust` to its destructured params and forward it to `buildRegistrationJSON`. Then pass `supportedTrust: this.form.supportedTrust || ['reputation']` in the `registerAgent` call from `_doRegister`.
In `src/erc8004/agent-registry.js`, the `registerAgent` function (around line 218+):
+
```js
export async function registerAgent({
name,
@@ -155,43 +166,47 @@ export async function registerAgent({
onStatus = () => {},
}) {
```
+
Add `supportedTrust = ['reputation'],` to the destructuring. Then find the `buildRegistrationJSON` call inside it (around line 321) and add `supportedTrust` to that call:
+
```js
const registrationJSON = buildRegistrationJSON({
- name,
- description,
- imageUrl,
- glbUrl,
- agentId,
- chainId,
- registryAddr,
- services,
- x402Support,
- supportedTrust,
+ name,
+ description,
+ imageUrl,
+ glbUrl,
+ agentId,
+ chainId,
+ registryAddr,
+ services,
+ x402Support,
+ supportedTrust,
});
```
### 5. `_doUpdateAgent` — preserve or override `supportedTrust`
In `_doUpdateAgent` (line ~1895), find the `buildRegistrationJSON` call:
+
```js
const registrationJSON = buildRegistrationJSON({
- name,
- description,
- imageUrl: newImageUrl || '',
- glbUrl,
- agentId,
- chainId,
- registryAddr,
- services: preservedServices,
- x402Support:
- typeof x402Support === 'boolean'
- ? x402Support
- : !!(currentMeta?.x402Support || currentMeta?.x402),
+ name,
+ description,
+ imageUrl: newImageUrl || '',
+ glbUrl,
+ agentId,
+ chainId,
+ registryAddr,
+ services: preservedServices,
+ x402Support:
+ typeof x402Support === 'boolean'
+ ? x402Support
+ : !!(currentMeta?.x402Support || currentMeta?.x402),
});
```
Add `supportedTrust` similarly — use it when provided (from the edit modal), otherwise fall back to whatever was in the existing metadata:
+
```js
supportedTrust: Array.isArray(supportedTrust) && supportedTrust.length > 0
? supportedTrust
@@ -205,6 +220,7 @@ Add `supportedTrust` to the `_doUpdateAgent` destructured params (alongside `x40
### 6. `_openEditModal` — read `supportedTrust` from existing metadata + add checkboxes
In `_openEditModal` (line ~1727), find the x402 checkbox in the modal HTML:
+
```html
<label class="erc8004-checkbox">
<input type="checkbox" name="x402Support" ${currentMeta?.x402Support || currentMeta?.x402 ? 'checked' : ''} />
@@ -213,6 +229,7 @@ In `_openEditModal` (line ~1727), find the x402 checkbox in the modal HTML:
```
Add the same trust fieldset immediately after it:
+
```html
<fieldset class="erc8004-fieldset" style="margin-top:14px;border:1px solid var(--erc8004-border,#333);border-radius:6px;padding:10px 12px">
<legend class="erc8004-label" style="padding:0 4px">Trust models</legend>
@@ -226,9 +243,10 @@ Add the same trust fieldset immediately after it:
```
In the modal save handler (where `x402Support` is read), add:
+
```js
const supportedTrust = ['reputation', 'validation', 'stake'].filter(
- (t) => !!modal.querySelector(`[name="trust-${t}"]`)?.checked,
+ (t) => !!modal.querySelector(`[name="trust-${t}"]`)?.checked,
);
```
diff --git a/prompts/build/06-02-hub-my-agents-autohighlight.md b/prompts/build/06-02-hub-my-agents-autohighlight.md
index 0d467e8a0..a6faa0ea4 100644
--- a/prompts/build/06-02-hub-my-agents-autohighlight.md
+++ b/prompts/build/06-02-hub-my-agents-autohighlight.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "When opening RegisterUI from the hub Manage button, auto-highlight the specific registered agent in the My Agents tab"
+description: 'When opening RegisterUI from the hub Manage button, auto-highlight the specific registered agent in the My Agents tab'
---
# 06-02 · Hub Manage Button — Auto-Highlight Registered Agent in My Agents Tab
@@ -11,9 +11,12 @@ On `/agent/:id`, the owner sees a "Deploy on-chain" button that, when the agent
```js
new RegisterUI(
- wrap,
- () => { wrap.remove(); location.reload(); },
- { initialTab: 'my' },
+ wrap,
+ () => {
+ wrap.remove();
+ location.reload();
+ },
+ { initialTab: 'my' },
);
```
@@ -43,9 +46,9 @@ In `_renderMyAgents` (line ~1382), before the `listAgentsByOwner` call, if a hig
```js
if (this._highlightChainId && this._highlightChainId !== this.selectedChainId) {
- this.selectedChainId = this._highlightChainId;
- const sel = this.el.querySelector('.erc8004-chain-select');
- if (sel) sel.value = String(this._highlightChainId);
+ this.selectedChainId = this._highlightChainId;
+ const sel = this.el.querySelector('.erc8004-chain-select');
+ if (sel) sel.value = String(this._highlightChainId);
}
```
@@ -57,18 +60,18 @@ In `_fillAgentCard` (line ~1443), after the card's full `innerHTML` is set and t
```js
if (this._highlightAgentId && Number(agentId) === this._highlightAgentId) {
- card.classList.add('erc8004-agent-card--highlight');
- // Scroll into view after a brief frame so layout is complete
- requestAnimationFrame(() => card.scrollIntoView({ behavior: 'smooth', block: 'nearest' }));
- // If this card has an edit button, click it automatically so the owner
- // lands directly in the edit flow without an extra click.
- if (opts.withEdit) {
- const editBtn = card.querySelector('[data-role="edit"]');
- if (editBtn) {
- // Small delay to let the scroll finish
- setTimeout(() => editBtn.click(), 400);
- }
- }
+ card.classList.add('erc8004-agent-card--highlight');
+ // Scroll into view after a brief frame so layout is complete
+ requestAnimationFrame(() => card.scrollIntoView({ behavior: 'smooth', block: 'nearest' }));
+ // If this card has an edit button, click it automatically so the owner
+ // lands directly in the edit flow without an extra click.
+ if (opts.withEdit) {
+ const editBtn = card.querySelector('[data-role="edit"]');
+ if (editBtn) {
+ // Small delay to let the scroll finish
+ setTimeout(() => editBtn.click(), 400);
+ }
+ }
}
```
@@ -78,8 +81,8 @@ The `erc8004-agent-card--highlight` class needs a visual distinction. Find where
```css
.erc8004-agent-card--highlight {
- outline: 2px solid var(--erc8004-accent, #7c6fff);
- outline-offset: 2px;
+ outline: 2px solid var(--erc8004-accent, #7c6fff);
+ outline-offset: 2px;
}
```
@@ -91,12 +94,12 @@ In the registered-agent click handler (around line 59–79), find:
```js
new RegisterUI(
- wrap,
- () => {
- wrap.remove();
- location.reload();
- },
- { initialTab: 'my' },
+ wrap,
+ () => {
+ wrap.remove();
+ location.reload();
+ },
+ { initialTab: 'my' },
);
```
@@ -104,16 +107,16 @@ Change to:
```js
new RegisterUI(
- wrap,
- () => {
- wrap.remove();
- location.reload();
- },
- {
- initialTab: 'my',
- highlightAgentId: erc8004AgentId || null,
- highlightChainId: chainId || null,
- },
+ wrap,
+ () => {
+ wrap.remove();
+ location.reload();
+ },
+ {
+ initialTab: 'my',
+ highlightAgentId: erc8004AgentId || null,
+ highlightChainId: chainId || null,
+ },
);
```
diff --git a/prompts/build/06-02-onchain-identity-resolution.md b/prompts/build/06-02-onchain-identity-resolution.md
index bb8a436c1..bcc278bda 100644
--- a/prompts/build/06-02-onchain-identity-resolution.md
+++ b/prompts/build/06-02-onchain-identity-resolution.md
@@ -1,4 +1,4 @@
-# 06-02 — Render an agent *from chain* into a host app
+# 06-02 — Render an agent _from chain_ into a host app
**Branch:** `feat/onchain-agent-resolution`
**Stack layer:** 6 (Onchain identity — the novel unlock)
@@ -7,28 +7,30 @@
## Why it matters
-This is the entire strategic bet: a host app (Claude Artifact, Lobehub, anything) takes an ERC-8004 agent id and renders the agent embodied — pulling the identity, avatar URL, skills, and reputation directly from chain, with our platform only serving the runtime. When this works, *other people's apps* can render *our* agents without knowing or caring about our backend.
+This is the entire strategic bet: a host app (Claude Artifact, Lobehub, anything) takes an ERC-8004 agent id and renders the agent embodied — pulling the identity, avatar URL, skills, and reputation directly from chain, with our platform only serving the runtime. When this works, _other people's apps_ can render _our_ agents without knowing or caring about our backend.
## Read these first
-| File | Why |
-|:---|:---|
+| File | Why |
+| :------------------------------------------------------------------- | :--------------------------------------------------------- |
| [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js) | `registerAgent()` + JSON shape — the mirror of resolution. |
-| [src/erc8004/abi.js](../../src/erc8004/abi.js) | ABIs, deployed addresses, chain constants. |
-| [src/element.js](../../src/element.js) | `<agent-3d>` — gets a new attribute mode. |
-| [src/agent-resolver.js](../../src/agent-resolver.js) | Existing manifest resolver; extend it. |
-| [specs/](../../specs/) | Manifest spec — confirm agent JSON matches. |
+| [src/erc8004/abi.js](../../src/erc8004/abi.js) | ABIs, deployed addresses, chain constants. |
+| [src/element.js](../../src/element.js) | `<agent-3d>` — gets a new attribute mode. |
+| [src/agent-resolver.js](../../src/agent-resolver.js) | Existing manifest resolver; extend it. |
+| [specs/](../../specs/) | Manifest spec — confirm agent JSON matches. |
## Build this
### New `<agent-3d>` attribute: `chain-id` + `onchain-id`
Usage:
+
```html
<agent-3d chain-id="84532" onchain-id="123"></agent-3d>
```
On connect, the component:
+
1. Reads a free/public RPC for the given `chain-id` (configurable via `rpc-url` attr; defaults to a set of known public RPCs keyed by chain id).
2. Calls `IdentityRegistry.getAgent(onchainId)` → returns `{ registrationURI, owner }`.
3. Fetches the registration JSON from `registrationURI` (HTTP or IPFS gateway).
diff --git a/prompts/build/06-02-pin-card-to-ipfs.md b/prompts/build/06-02-pin-card-to-ipfs.md
index 69bde0315..d5cae0f87 100644
--- a/prompts/build/06-02-pin-card-to-ipfs.md
+++ b/prompts/build/06-02-pin-card-to-ipfs.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Pin agent-card.json to IPFS and record the CID before/with on-chain registration"
+description: 'Pin agent-card.json to IPFS and record the CID before/with on-chain registration'
---
# 06-02 · Pin agent-card to IPFS
@@ -22,13 +22,13 @@ The onchain registry stores a **CID** pointing at the agent's card, not the card
## Build this
1. **New endpoint** `POST /api/agents/:id/pin` (owner-only):
- - Build the canonical card JSON via the same code path as `/api/agents/:id/card.json`.
- - Pin it via the provider SDK (server-side — keep the token off the client).
- - `UPDATE agent_identities SET registration_cid = $1 WHERE id = $2`.
- - Return `{ cid, gateway_url }`.
+ - Build the canonical card JSON via the same code path as `/api/agents/:id/card.json`.
+ - Pin it via the provider SDK (server-side — keep the token off the client).
+ - `UPDATE agent_identities SET registration_cid = $1 WHERE id = $2`.
+ - Return `{ cid, gateway_url }`.
2. **Wire it into the register page** (06-01):
- - Before signing the on-chain tx, call `/pin` and include the returned CID in the registration payload.
- - The registry function signature expects a `bytes32` CID or `string` URI — check `IdentityRegistry.sol` and match exactly. If it's `bytes32`, store the raw digest; document the encoding in the endpoint response.
+ - Before signing the on-chain tx, call `/pin` and include the returned CID in the registration payload.
+ - The registry function signature expects a `bytes32` CID or `string` URI — check `IdentityRegistry.sol` and match exactly. If it's `bytes32`, store the raw digest; document the encoding in the endpoint response.
3. **Re-pin on change** — if the owner edits metadata (03-03) or swaps avatar (03-01), show a "Re-pin" button that calls `/pin` again. New CID overrides old. Only the owner can trigger this; only after registration.
4. **Resolver integration** — `src/agent-resolver.js` should try fetching `registration_cid` from the card first (authoritative), fall back to `/api/agents/:id/card.json`.
diff --git a/prompts/build/06-03-edit-modal-services.md b/prompts/build/06-03-edit-modal-services.md
index d6e2fbec7..a13cd4c15 100644
--- a/prompts/build/06-03-edit-modal-services.md
+++ b/prompts/build/06-03-edit-modal-services.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Add service endpoint editor to the existing on-chain agent edit modal in RegisterUI"
+description: 'Add service endpoint editor to the existing on-chain agent edit modal in RegisterUI'
---
# 06-03 · Edit Modal — Service Endpoint Editor
@@ -29,6 +29,7 @@ The service list logic in `_renderStepServices` builds a list of `{ name, type,
Then in `_renderStepServices`, call `this._buildServiceEditor(serviceContainer, this.form.services)` and wire the returned `getServices` to update `this.form.services` on next/deploy click (replacing the current inline list-render logic).
**Read `_renderStepServices` carefully** before extracting — the current code around line 768–825 uses:
+
- `renderList()` — a closure that re-renders rows from a `services` array
- An "add" button (`data-role="add"`)
- Per-row remove buttons (`data-role="rm"`)
@@ -43,71 +44,79 @@ In `_openEditModal`, find the edit modal HTML template (the `modal.innerHTML = .
```html
<div class="erc8004-label" style="margin-top:14px">Service endpoints</div>
-<p class="erc8004-hint">Add or remove A2A / MCP / web endpoints. The 3D avatar service is managed by the "3D Avatar (GLB)" field above.</p>
+<p class="erc8004-hint">
+ Add or remove A2A / MCP / web endpoints. The 3D avatar service is managed by the "3D Avatar
+ (GLB)" field above.
+</p>
<div data-role="services-editor"></div>
```
After the modal is appended to `this.el`, wire the service editor:
+
```js
const nonAvatarServices = (meta?.services || []).filter(
- (s) => s?.name !== 'avatar' && s?.name !== '3D',
+ (s) => s?.name !== 'avatar' && s?.name !== '3D',
);
const { getServices } = this._buildServiceEditor(
- modal.querySelector('[data-role="services-editor"]'),
- nonAvatarServices,
+ modal.querySelector('[data-role="services-editor"]'),
+ nonAvatarServices,
);
```
### 3. Edit modal save handler — read services and pass to `_doUpdateAgent`
In the save handler (around line 1796–1826), currently:
+
```js
const x402Support = !!modal.querySelector('[name="x402Support"]')?.checked;
await this._doUpdateAgent({
- agentId,
- name,
- description,
- imageUrl: imageUrlInput,
- glbFile,
- removeAvatar,
- x402Support,
- apiToken,
- currentMeta: card._meta,
- say,
+ agentId,
+ name,
+ description,
+ imageUrl: imageUrlInput,
+ glbFile,
+ removeAvatar,
+ x402Support,
+ apiToken,
+ currentMeta: card._meta,
+ say,
});
```
Add services read and pass it through:
+
```js
const editedServices = getServices();
const x402Support = !!modal.querySelector('[name="x402Support"]')?.checked;
await this._doUpdateAgent({
- agentId,
- name,
- description,
- imageUrl: imageUrlInput,
- glbFile,
- removeAvatar,
- x402Support,
- services: editedServices,
- apiToken,
- currentMeta: card._meta,
- say,
+ agentId,
+ name,
+ description,
+ imageUrl: imageUrlInput,
+ glbFile,
+ removeAvatar,
+ x402Support,
+ services: editedServices,
+ apiToken,
+ currentMeta: card._meta,
+ say,
});
```
### 4. `_doUpdateAgent` — use provided services instead of always pulling from metadata
Currently `_doUpdateAgent` (line ~1834) always reconstructs services from `currentMeta`:
+
```js
const preservedServices = (currentMeta?.services || []).filter(
- (s) => s?.name !== 'avatar' && s?.name !== '3D',
+ (s) => s?.name !== 'avatar' && s?.name !== '3D',
);
```
Add a `services` parameter to `_doUpdateAgent` and use it when provided:
+
```js
async _doUpdateAgent({
agentId,
@@ -125,10 +134,11 @@ async _doUpdateAgent({
```
Then change the `preservedServices` line:
+
```js
const preservedServices = Array.isArray(services)
- ? services
- : (currentMeta?.services || []).filter((s) => s?.name !== 'avatar' && s?.name !== '3D');
+ ? services
+ : (currentMeta?.services || []).filter((s) => s?.name !== 'avatar' && s?.name !== '3D');
```
This keeps backward compat — callers that don't pass `services` still get the metadata-preserve behavior.
@@ -136,8 +146,9 @@ This keeps backward compat — callers that don't pass `services` still get the
## Service type options (for the editor select)
Use the same set as Step 2:
+
- `a2a` → label "A2A"
-- `mcp` → label "MCP"
+- `mcp` → label "MCP"
- `web` → label "Web"
- `x402` → label "x402"
diff --git a/prompts/build/06-03-resolve-agent-from-chain.md b/prompts/build/06-03-resolve-agent-from-chain.md
index 7553595de..21ef17f6f 100644
--- a/prompts/build/06-03-resolve-agent-from-chain.md
+++ b/prompts/build/06-03-resolve-agent-from-chain.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Given an on-chain agent id, resolve to a full rendered agent in any host"
+description: 'Given an on-chain agent id, resolve to a full rendered agent in any host'
---
# 06-03 · Resolve agent from chain
@@ -23,12 +23,12 @@ The payoff of pillar 6. Any host — Lobehub, Claude, a random site — can take
## Build this
1. **Server-side resolver** `GET /api/agents/by-chain?chain_id=X&erc8004_id=Y`:
- - Look up the on-chain record via a read-only RPC (reuse any provider config).
- - Extract the pinned CID.
- - Fetch the card JSON from IPFS (multi-gateway fallback via `src/ipfs.js`).
- - Resolve the avatar URL from the card.
- - Return `{ id?, name, description, avatar: { url }, card_cid, card_url, embed_url }`. If the agent is *also* in our Neon DB (one of ours), include the local `id`.
- - Cache the response (CDN, 60s) — on-chain reads are slow.
+ - Look up the on-chain record via a read-only RPC (reuse any provider config).
+ - Extract the pinned CID.
+ - Fetch the card JSON from IPFS (multi-gateway fallback via `src/ipfs.js`).
+ - Resolve the avatar URL from the card.
+ - Return `{ id?, name, description, avatar: { url }, card_cid, card_url, embed_url }`. If the agent is _also_ in our Neon DB (one of ours), include the local `id`.
+ - Cache the response (CDN, 60s) — on-chain reads are slow.
2. **Client helper** — extend `src/agent-resolver.js` so `<agent-3d chain-id="1" erc8004-id="42">` works, using `/api/agents/by-chain`.
3. **Embed resolver** — `/agent/chain/:chainId/:erc8004Id` route that renders the embed for a chain-resolved agent (not an internal id). Lets hosts paste chain-native URLs.
4. **Card trust** — verify the card's declared `wallet` matches the on-chain owner before rendering; reject otherwise. Protects against a CID that points to a spoofed card.
diff --git a/prompts/build/06-03-validation-registry.md b/prompts/build/06-03-validation-registry.md
index 606b34a92..2f8699bda 100644
--- a/prompts/build/06-03-validation-registry.md
+++ b/prompts/build/06-03-validation-registry.md
@@ -2,13 +2,13 @@
## Why it matters
-Reputation (06-02) is subjective. The ValidationRegistry complements it with *verifiable* claims — "this agent signed this output", "this agent delivered this tool call on this block". These are how hosts prove, without trusting us or the agent, that a given action happened. Critical for host-embed trust (Layer 5) and for the onchain-discovery flywheel (06-07).
+Reputation (06-02) is subjective. The ValidationRegistry complements it with _verifiable_ claims — "this agent signed this output", "this agent delivered this tool call on this block". These are how hosts prove, without trusting us or the agent, that a given action happened. Critical for host-embed trust (Layer 5) and for the onchain-discovery flywheel (06-07).
## Context
- Validation contract: [contracts/src/ValidationRegistry.sol](../../contracts/src/ValidationRegistry.sol).
- ABI entries: [src/erc8004/abi.js](../../src/erc8004/abi.js).
-- Agent actions table: `agent_actions` (reference [api/_lib/schema.sql](../../api/_lib/schema.sql)).
+- Agent actions table: `agent_actions` (reference [api/\_lib/schema.sql](../../api/_lib/schema.sql)).
- Requires: 06-01 merged.
## What to build
diff --git a/prompts/build/06-04-lobehub-onchain-import.md b/prompts/build/06-04-lobehub-onchain-import.md
index 92c021f4c..7bcb57761 100644
--- a/prompts/build/06-04-lobehub-onchain-import.md
+++ b/prompts/build/06-04-lobehub-onchain-import.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Lobehub (or any MCP host) imports an agent directly from its on-chain record"
+description: 'Lobehub (or any MCP host) imports an agent directly from its on-chain record'
---
# 06-04 · Lobehub onchain import
@@ -21,7 +21,7 @@ This is the specific demo that proves the whole product thesis: a user in Lobehu
## Build this
1. **Extend the Lobehub plugin manifest** (05-02) with an alternate input mode:
- - `{ chain_id, erc8004_id }` instead of / in addition to `{ agent_id }`.
+ - `{ chain_id, erc8004_id }` instead of / in addition to `{ agent_id }`.
2. **Resolver call** — plugin renderer calls `/api/agents/by-chain?...` (06-03) and renders the returned `embed_url` in its iframe renderer.
3. **Native chat command** — document a `/3d-agent chain:1 id:42` slash-command pattern for the Lobehub fork. Include a minimal command-parser snippet in the PR; the user will wire it into their fork.
4. **End-to-end test** — in the user's Lobehub fork, trigger the import with a known on-chain id and verify the avatar appears embodied inline.
diff --git a/prompts/build/06-04-pull-from-chain-resolver.md b/prompts/build/06-04-pull-from-chain-resolver.md
index 3759af734..9c0df9eba 100644
--- a/prompts/build/06-04-pull-from-chain-resolver.md
+++ b/prompts/build/06-04-pull-from-chain-resolver.md
@@ -2,7 +2,7 @@
## Why it matters
-This is the payoff for Layer 6. Given an onchain agent id, any host — Lobehub, Claude, a cold wallet, a random web page — should be able to load and render the agent *without* our server. The resolver is the code path that turns `erc8004://<chain>:<id>` into a runnable manifest + GLB, using only public RPC and IPFS. If this works, the product escapes us.
+This is the payoff for Layer 6. Given an onchain agent id, any host — Lobehub, Claude, a cold wallet, a random web page — should be able to load and render the agent _without_ our server. The resolver is the code path that turns `erc8004://<chain>:<id>` into a runnable manifest + GLB, using only public RPC and IPFS. If this works, the product escapes us.
## Context
@@ -26,13 +26,13 @@ Accept any of:
```js
export async function resolveAgent(urn, { rpcUrl, ipfsGateway } = {}) {
- // 1. parse urn -> { chain_id, onchain_id }
- // 2. fetch IdentityRegistry(chain_id).getAgent(onchain_id)
- // 3. read manifest_cid, controller, updated_at
- // 4. fetch manifest JSON via ipfs gateway(s) with fallback
- // 5. resolve GLB and thumbnails (ipfs:// → https:// via gateway)
- // 6. attach reputation / validation rollups (lightweight; 06-02/06-03)
- // 7. return a normalized manifest object
+ // 1. parse urn -> { chain_id, onchain_id }
+ // 2. fetch IdentityRegistry(chain_id).getAgent(onchain_id)
+ // 3. read manifest_cid, controller, updated_at
+ // 4. fetch manifest JSON via ipfs gateway(s) with fallback
+ // 5. resolve GLB and thumbnails (ipfs:// → https:// via gateway)
+ // 6. attach reputation / validation rollups (lightweight; 06-02/06-03)
+ // 7. return a normalized manifest object
}
```
diff --git a/prompts/build/06-05-controller-transfer.md b/prompts/build/06-05-controller-transfer.md
index 393780be5..de092ce8a 100644
--- a/prompts/build/06-05-controller-transfer.md
+++ b/prompts/build/06-05-controller-transfer.md
@@ -22,14 +22,14 @@ Users change wallets — lose a seed, switch from hot to hardware, migrate custo
### Confirmation — `POST /api/agents/:id/transfer-controller/confirm`
- Body `{ tx_hash }`. Server waits for receipt, parses `ControllerTransferred(onchain_id, old, new)`, updates:
- - `user_wallets`: flip `is_primary` (only if `new_controller` is on the caller's wallet list and becomes the new primary).
- - `agents`: no column change — controller is derived from onchain state, not cached in DB. If any cached column exists (e.g. `agents.onchain_controller`), update it.
+ - `user_wallets`: flip `is_primary` (only if `new_controller` is on the caller's wallet list and becomes the new primary).
+ - `agents`: no column change — controller is derived from onchain state, not cached in DB. If any cached column exists (e.g. `agents.onchain_controller`), update it.
- Emits an `agent_actions` row with type `controller_transferred` (audited).
### Post-transfer UX
- Dashboard shows a banner on the agent page: "Controller is now 0x…. Future onchain actions (update manifest, anchor) will be signed by this wallet."
-- If the new controller isn't the user's *primary* wallet, offer a one-click "Make primary" that calls the 01-03 endpoint.
+- If the new controller isn't the user's _primary_ wallet, offer a one-click "Make primary" that calls the 01-03 endpoint.
### Edge cases
diff --git a/prompts/build/06-05-erc8004-deploy-script.md b/prompts/build/06-05-erc8004-deploy-script.md
index b46f74bbf..1abd2c533 100644
--- a/prompts/build/06-05-erc8004-deploy-script.md
+++ b/prompts/build/06-05-erc8004-deploy-script.md
@@ -11,23 +11,23 @@ Today contract addresses are hand-pasted into [src/erc8004/abi.js](../../src/erc
## Read these first
-| File | Why |
-|:---|:---|
-| [contracts/](../../contracts/) | Foundry project layout. |
-| [contracts/script/](../../contracts/script/) | Existing deploy scripts — match style. |
-| [src/erc8004/abi.js](../../src/erc8004/abi.js) | Hardcoded ABIs + `REGISTRY_DEPLOYMENTS` address map — output target. |
-| [contracts/CLAUDE.md](../../contracts/CLAUDE.md) | Existing deploy notes. |
+| File | Why |
+| :----------------------------------------------- | :------------------------------------------------------------------- |
+| [contracts/](../../contracts/) | Foundry project layout. |
+| [contracts/script/](../../contracts/script/) | Existing deploy scripts — match style. |
+| [src/erc8004/abi.js](../../src/erc8004/abi.js) | Hardcoded ABIs + `REGISTRY_DEPLOYMENTS` address map — output target. |
+| [contracts/CLAUDE.md](../../contracts/CLAUDE.md) | Existing deploy notes. |
## Build this
1. Add `contracts/script/DeployAll.s.sol` — deploys IdentityRegistry, ReputationRegistry, ValidationRegistry deterministically (CREATE2 with the existing salt). Fail loudly if any address differs from the expected deterministic address.
2. Add `scripts/deploy-erc8004.mjs` — Node wrapper that:
- - Reads target chain ID from CLI arg.
- - Reads `DEPLOYER_PK` and `RPC_URL_<CHAIN>` from env.
- - Runs `forge script DeployAll --broadcast`.
- - Parses the broadcast JSON for the three deployed addresses.
- - Updates `REGISTRY_DEPLOYMENTS` in [src/erc8004/abi.js](../../src/erc8004/abi.js) using a string-replace (don't rewrite the whole file).
- - Verifies on Etherscan via `forge verify-contract` if `ETHERSCAN_API_KEY_<CHAIN>` is set.
+ - Reads target chain ID from CLI arg.
+ - Reads `DEPLOYER_PK` and `RPC_URL_<CHAIN>` from env.
+ - Runs `forge script DeployAll --broadcast`.
+ - Parses the broadcast JSON for the three deployed addresses.
+ - Updates `REGISTRY_DEPLOYMENTS` in [src/erc8004/abi.js](../../src/erc8004/abi.js) using a string-replace (don't rewrite the whole file).
+ - Verifies on Etherscan via `forge verify-contract` if `ETHERSCAN_API_KEY_<CHAIN>` is set.
3. Add `scripts/sync-erc8004-abi.mjs` — reads `contracts/out/*.sol/*.json`, extracts the ABI, regenerates the human-readable ethers v6 array in [src/erc8004/abi.js](../../src/erc8004/abi.js). Idempotent.
4. Add npm scripts: `deploy:erc8004 -- <chainId>`, `sync:erc8004-abi`.
5. Document `RPC_URL_*`, `DEPLOYER_PK`, `ETHERSCAN_API_KEY_*` in `.env.example`.
diff --git a/prompts/build/06-05-signed-action-log.md b/prompts/build/06-05-signed-action-log.md
index 90879b22b..bda029c64 100644
--- a/prompts/build/06-05-signed-action-log.md
+++ b/prompts/build/06-05-signed-action-log.md
@@ -1,13 +1,13 @@
---
mode: agent
-description: "Sign every agent action with the linked wallet so the action log is verifiable"
+description: 'Sign every agent action with the linked wallet so the action log is verifiable'
---
# 06-05 · Wallet-signed action log
## Why it matters
-The onchain identity is worth nothing if the agent's *actions* are unsigned — a host can't distinguish real moves from forged ones. Signing each action with the owner wallet (off-chain, stored in `agent_actions.signature`) makes the action log cryptographically attributable.
+The onchain identity is worth nothing if the agent's _actions_ are unsigned — a host can't distinguish real moves from forged ones. Signing each action with the owner wallet (off-chain, stored in `agent_actions.signature`) makes the action log cryptographically attributable.
## Prerequisites
@@ -24,7 +24,7 @@ The onchain identity is worth nothing if the agent's *actions* are unsigned —
1. **Action signing on the client** — before `POST /api/agent-actions`, run the action payload through `wallet.signMessage(canonicalize(action))`. Canonicalize via sorted keys + no whitespace. Store `{ signature, signer_address, message_digest }` alongside the action.
2. **Server verification** — on insert, verify the signature recovers the agent's `wallet_address`. Reject if mismatch.
-3. **Unsigned fallback** — anonymous visitors (no linked wallet) continue to write actions *without* signatures; those rows get `signature IS NULL`. Signed vs unsigned is filterable.
+3. **Unsigned fallback** — anonymous visitors (no linked wallet) continue to write actions _without_ signatures; those rows get `signature IS NULL`. Signed vs unsigned is filterable.
4. **Expose signed-only timeline on public views** — on `/agent/:id`, an optional toggle "Verified actions only" shows rows where `signer_address = agent.wallet_address`. Default: show all.
5. **Prompt the user** to sign once per session — use a "delegation" message (SIWE-style) that authorizes the browser session to sign subsequent actions locally with a session-scoped key. Rather than wallet-popup-per-action, which kills UX.
diff --git a/prompts/build/06-06-erc8004-indexer.md b/prompts/build/06-06-erc8004-indexer.md
index fce87cd9c..124547a42 100644
--- a/prompts/build/06-06-erc8004-indexer.md
+++ b/prompts/build/06-06-erc8004-indexer.md
@@ -3,7 +3,7 @@
**Branch:** `feat/erc8004-indexer`
**Stack layer:** 6 (Onchain portability)
**Depends on:** 06-05 (canonical ABI + address map)
-**Blocks:** 06-07 (reputation UI), 14-* (agent gallery)
+**Blocks:** 06-07 (reputation UI), 14-\* (agent gallery)
## Why it matters
@@ -11,49 +11,51 @@
## Read these first
-| File | Why |
-|:---|:---|
-| [src/erc8004/abi.js](../../src/erc8004/abi.js) | Event signatures + addresses. |
-| [api/_lib/db.js](../../api/_lib/db.js) | Neon client. |
-| [api/_lib/migrations/](../../api/_lib/migrations/) | Migration pattern (see 00 prompt). |
-| [api/agents/[id].js](../../api/agents/[id].js) | Read endpoint that will join the new tables. |
+| File | Why |
+| :-------------------------------------------------- | :------------------------------------------- |
+| [src/erc8004/abi.js](../../src/erc8004/abi.js) | Event signatures + addresses. |
+| [api/\_lib/db.js](../../api/_lib/db.js) | Neon client. |
+| [api/\_lib/migrations/](../../api/_lib/migrations/) | Migration pattern (see 00 prompt). |
+| [api/agents/[id].js](../../api/agents/[id].js) | Read endpoint that will join the new tables. |
## Build this
1. **Schema** (new migration `0NN_onchain_index.sql`):
- ```sql
- create table if not exists onchain_agents (
- chain_id bigint not null,
- token_id bigint not null,
- wallet text not null,
- agent_uri text not null,
- registered_at timestamptz not null,
- last_seen_block bigint not null,
- primary key (chain_id, token_id)
- );
- create index if not exists onchain_agents_wallet_idx on onchain_agents(wallet);
-
- create table if not exists onchain_reputation (
- chain_id bigint not null,
- token_id bigint not null,
- score_x100 integer not null,
- count integer not null,
- updated_at timestamptz not null,
- primary key (chain_id, token_id)
- );
-
- create table if not exists indexer_cursor (
- chain_id bigint primary key,
- last_block bigint not null,
- updated_at timestamptz not null default now()
- );
- ```
+
+ ```sql
+ create table if not exists onchain_agents (
+ chain_id bigint not null,
+ token_id bigint not null,
+ wallet text not null,
+ agent_uri text not null,
+ registered_at timestamptz not null,
+ last_seen_block bigint not null,
+ primary key (chain_id, token_id)
+ );
+ create index if not exists onchain_agents_wallet_idx on onchain_agents(wallet);
+
+ create table if not exists onchain_reputation (
+ chain_id bigint not null,
+ token_id bigint not null,
+ score_x100 integer not null,
+ count integer not null,
+ updated_at timestamptz not null,
+ primary key (chain_id, token_id)
+ );
+
+ create table if not exists indexer_cursor (
+ chain_id bigint primary key,
+ last_block bigint not null,
+ updated_at timestamptz not null default now()
+ );
+ ```
+
2. **Indexer** at `scripts/indexer.mjs`:
- - Reads chain list from `REGISTRY_DEPLOYMENTS`.
- - Per chain: loads cursor, queries `Registered` + `FeedbackSubmitted` from cursor → `latest - 1`, upserts rows, advances cursor.
- - Caps each query window to 5000 blocks; loops until caught up.
- - Sleeps 30s between polling cycles.
- - Logs structured JSON.
+ - Reads chain list from `REGISTRY_DEPLOYMENTS`.
+ - Per chain: loads cursor, queries `Registered` + `FeedbackSubmitted` from cursor → `latest - 1`, upserts rows, advances cursor.
+ - Caps each query window to 5000 blocks; loops until caught up.
+ - Sleeps 30s between polling cycles.
+ - Logs structured JSON.
3. **Vercel cron** entry in [vercel.json](../../vercel.json) → `api/cron/index-onchain.js` calling the indexer for one cycle. 1-minute cron.
4. **Read endpoint** `api/onchain/agent/[chainId]/[tokenId].js` — returns the joined row.
5. Wire `api/agents/[id].js` to optionally include `onchain: { chain_id, token_id, score_x100, count }` if the off-chain agent has a stored chain id + token id (column `onchain_token_id` on `agents`).
diff --git a/prompts/build/06-07-reputation-validation-ui.md b/prompts/build/06-07-reputation-validation-ui.md
index 7afa1068e..16076d908 100644
--- a/prompts/build/06-07-reputation-validation-ui.md
+++ b/prompts/build/06-07-reputation-validation-ui.md
@@ -10,24 +10,24 @@ The on-chain reputation score is meaningless if no one sees it. Surface the scor
## Read these first
-| File | Why |
-|:---|:---|
-| [src/erc8004/reputation.js](../../src/erc8004/reputation.js) | `submitFeedback`, `getReputation`, `getRecentReviews`. |
-| [src/agent-home.js](../../src/agent-home.js) | Identity card mount point. |
-| [public/agent/index.html](../../public/agent/index.html) | Public agent page. |
-| [api/onchain/agent/[chainId]/[tokenId].js](../../api/onchain/agent/[chainId]/[tokenId].js) | Read endpoint from 06-06. |
+| File | Why |
+| :----------------------------------------------------------------------------------------- | :----------------------------------------------------- |
+| [src/erc8004/reputation.js](../../src/erc8004/reputation.js) | `submitFeedback`, `getReputation`, `getRecentReviews`. |
+| [src/agent-home.js](../../src/agent-home.js) | Identity card mount point. |
+| [public/agent/index.html](../../public/agent/index.html) | Public agent page. |
+| [api/onchain/agent/[chainId]/[tokenId].js](../../api/onchain/agent/[chainId]/[tokenId].js) | Read endpoint from 06-06. |
## Build this
1. In [src/agent-home.js](../../src/agent-home.js), add a `<reputation-card>` block:
- - Star rating (5-star, derived from `score_x100 / 20`).
- - Total feedback count.
- - "View on chain" link → block explorer for the registry contract.
+ - Star rating (5-star, derived from `score_x100 / 20`).
+ - Total feedback count.
+ - "View on chain" link → block explorer for the registry contract.
2. On the public agent page, add a "Leave feedback" button → opens a modal:
- - Connect wallet (reuse [public/wallet-login.js](../../public/wallet-login.js) flow).
- - Slider: −100 to +100, default 0.
- - Optional 280-char comment (stored in IPFS, hash submitted on-chain).
- - Submit → `submitFeedback(chainId, tokenId, score, ipfsHash)`.
+ - Connect wallet (reuse [public/wallet-login.js](../../public/wallet-login.js) flow).
+ - Slider: −100 to +100, default 0.
+ - Optional 280-char comment (stored in IPFS, hash submitted on-chain).
+ - Submit → `submitFeedback(chainId, tokenId, score, ipfsHash)`.
3. Show a small "verified ✓" badge if `count >= 5` and `score_x100 >= 4000` (i.e. avg ≥ +40). Otherwise show neutral.
4. Cache the read in the client for 60s to avoid hammering the indexer.
5. If the agent has no on-chain twin, hide the entire reputation block (don't show "0 reviews" — looks broken).
diff --git a/prompts/build/06-08-write-actions-onchain.md b/prompts/build/06-08-write-actions-onchain.md
index a7b330a5e..7cc415ff8 100644
--- a/prompts/build/06-08-write-actions-onchain.md
+++ b/prompts/build/06-08-write-actions-onchain.md
@@ -10,29 +10,29 @@ Today every agent action goes to the in-memory protocol bus and an off-chain aud
## Read these first
-| File | Why |
-|:---|:---|
-| [src/agent-protocol.js](../../src/agent-protocol.js) | Bus emits `sign` actions today — reuse. |
-| [src/agent-identity.js](../../src/agent-identity.js) | Where the agent's wallet lives. |
-| [api/agent-actions.js](../../api/agent-actions.js) | Off-chain action store; will receive Merkle batching. |
-| [contracts/src/](../../contracts/src/) | Existing registries; you may add a small `ActionAnchor.sol`. |
+| File | Why |
+| :--------------------------------------------------- | :----------------------------------------------------------- |
+| [src/agent-protocol.js](../../src/agent-protocol.js) | Bus emits `sign` actions today — reuse. |
+| [src/agent-identity.js](../../src/agent-identity.js) | Where the agent's wallet lives. |
+| [api/agent-actions.js](../../api/agent-actions.js) | Off-chain action store; will receive Merkle batching. |
+| [contracts/src/](../../contracts/src/) | Existing registries; you may add a small `ActionAnchor.sol`. |
## Build this
1. **Sign every action** at the boundary: when the protocol bus emits a `sign-eligible` action (configurable per skill), wrap the payload in EIP-712 and sign with the agent's wallet (Privy or local key). Persist `{action, signature, signer, ts}` to `agent_actions`.
2. **Anchor in epochs.** Add `contracts/src/ActionAnchor.sol`:
- ```solidity
- contract ActionAnchor {
- event AnchorPosted(uint256 indexed tokenId, bytes32 root, uint256 epoch);
- mapping(uint256 => mapping(uint256 => bytes32)) public roots; // tokenId => epoch => root
- function anchor(uint256 tokenId, uint256 epoch, bytes32 root) external { /* ... */ }
- }
- ```
+ ```solidity
+ contract ActionAnchor {
+ event AnchorPosted(uint256 indexed tokenId, bytes32 root, uint256 epoch);
+ mapping(uint256 => mapping(uint256 => bytes32)) public roots; // tokenId => epoch => root
+ function anchor(uint256 tokenId, uint256 epoch, bytes32 root) external { /* ... */ }
+ }
+ ```
3. **Batcher cron** at `api/cron/anchor-actions.js`:
- - Once per hour (configurable), per agent with new actions:
- - Build a Merkle tree of action hashes.
- - Call `anchor(tokenId, epoch, root)` from a relayer wallet (gas-only key, scoped to ActionAnchor).
- - Persist the root + epoch into `agent_actions_anchor` table.
+ - Once per hour (configurable), per agent with new actions:
+ - Build a Merkle tree of action hashes.
+ - Call `anchor(tokenId, epoch, root)` from a relayer wallet (gas-only key, scoped to ActionAnchor).
+ - Persist the root + epoch into `agent_actions_anchor` table.
4. **Verifier helper** in [src/erc8004/](../../src/erc8004/) — given an action + Merkle proof + on-chain root, return `{ valid, anchoredAt }`.
5. **UI** in [src/agent-home.js](../../src/agent-home.js) timeline: green "anchored" pip on actions whose epoch root has been settled; tooltip shows tx hash + block.
diff --git a/prompts/build/06-09-cross-chain-resolver.md b/prompts/build/06-09-cross-chain-resolver.md
index a8b663206..6445c6366 100644
--- a/prompts/build/06-09-cross-chain-resolver.md
+++ b/prompts/build/06-09-cross-chain-resolver.md
@@ -10,29 +10,29 @@ An agent identifier in the wild looks like `did:erc8004:<chainId>:<tokenId>` or
## Read these first
-| File | Why |
-|:---|:---|
-| [src/agent-resolver.js](../../src/agent-resolver.js) | Today's resolver. |
-| [src/erc8004/abi.js](../../src/erc8004/abi.js) | Address map per chain. |
-| [api/onchain/agent/[chainId]/[tokenId].js](../../api/onchain/agent/[chainId]/[tokenId].js) | Indexer read endpoint from 06-06. |
-| [src/manifest.js](../../src/manifest.js) | Manifest loader — adapt to chain-specific URIs. |
+| File | Why |
+| :----------------------------------------------------------------------------------------- | :---------------------------------------------- |
+| [src/agent-resolver.js](../../src/agent-resolver.js) | Today's resolver. |
+| [src/erc8004/abi.js](../../src/erc8004/abi.js) | Address map per chain. |
+| [api/onchain/agent/[chainId]/[tokenId].js](../../api/onchain/agent/[chainId]/[tokenId].js) | Indexer read endpoint from 06-06. |
+| [src/manifest.js](../../src/manifest.js) | Manifest loader — adapt to chain-specific URIs. |
## Build this
1. Define the canonical agent ID format and document it in `specs/AGENT_ID.md` (single new file allowed for this prompt):
- - Preferred: `did:erc8004:<chainId>:<tokenId>` (CAIP-style)
- - Aliases accepted: `<chainName>:<tokenId>`, `<tokenId>@<chainName>`
- - Names: `mainnet, sepolia, base, optimism, arbitrum, polygon, bnb, avalanche, fantom, gnosis, scroll, linea, blast, mode`
+ - Preferred: `did:erc8004:<chainId>:<tokenId>` (CAIP-style)
+ - Aliases accepted: `<chainName>:<tokenId>`, `<tokenId>@<chainName>`
+ - Names: `mainnet, sepolia, base, optimism, arbitrum, polygon, bnb, avalanche, fantom, gnosis, scroll, linea, blast, mode`
2. Add `src/agent-id.js`:
- ```js
- export function parseAgentId(input) // → { chainId, tokenId } | null
- export function formatAgentId(chainId, tokenId)
- export function chainNameToId(name)
- ```
+ ```js
+ export function parseAgentId(input) // → { chainId, tokenId } | null
+ export function formatAgentId(chainId, tokenId)
+ export function chainNameToId(name)
+ ```
3. Extend [src/agent-resolver.js](../../src/agent-resolver.js):
- - If input parses as a chain-qualified ID, hit `/api/onchain/agent/:chain/:token` first.
- - On miss, fall back to live RPC read of `tokenURI(tokenId)` from IdentityRegistry on that chain.
- - Cache hits in `sessionStorage` for 5 minutes.
+ - If input parses as a chain-qualified ID, hit `/api/onchain/agent/:chain/:token` first.
+ - On miss, fall back to live RPC read of `tokenURI(tokenId)` from IdentityRegistry on that chain.
+ - Cache hits in `sessionStorage` for 5 minutes.
4. Update `<agent-3d agent-id="…">` to accept the qualified format.
5. Bare numeric IDs (no chain) default to the production primary chain (configurable via env, default `1`).
diff --git a/prompts/build/06-10-portable-manifest-spec.md b/prompts/build/06-10-portable-manifest-spec.md
index d496502bd..81d228018 100644
--- a/prompts/build/06-10-portable-manifest-spec.md
+++ b/prompts/build/06-10-portable-manifest-spec.md
@@ -11,37 +11,35 @@ The `agentURI` field in IdentityRegistry currently points to a JSON document wit
## Read these first
-| File | Why |
-|:---|:---|
-| [src/manifest.js](../../src/manifest.js) | Existing manifest loader. |
-| [specs/](../../specs/) | Existing spec files; this prompt adds one. |
-| [examples/coach-leo/](../../examples/coach-leo/) | Reference agent — must validate against the new schema after migration. |
-| [src/agent-resolver.js](../../src/agent-resolver.js) | Resolver that consumes manifests. |
+| File | Why |
+| :--------------------------------------------------- | :---------------------------------------------------------------------- |
+| [src/manifest.js](../../src/manifest.js) | Existing manifest loader. |
+| [specs/](../../specs/) | Existing spec files; this prompt adds one. |
+| [examples/coach-leo/](../../examples/coach-leo/) | Reference agent — must validate against the new schema after migration. |
+| [src/agent-resolver.js](../../src/agent-resolver.js) | Resolver that consumes manifests. |
## Build this
1. Add `specs/AGENT_MANIFEST.md` documenting v1 schema:
- ```jsonc
- {
- "$schema": "https://3dagent.vercel.app/schemas/agent-manifest-v1.json",
- "version": 1,
- "id": "did:erc8004:1:42",
- "name": "Coach Leo",
- "description": "Personal posture coach",
- "avatar": {
- "model_url": "ipfs://bafy.../leo.glb",
- "thumbnail_url": "ipfs://bafy.../thumb.png"
- },
- "skills": [
- { "id": "greet", "version": "1.0.0", "danger": "safe" }
- ],
- "memory": { "mode": "encrypted-ipfs", "root": "ipfs://..." },
- "wallet": "0x...",
- "homepage": "https://3dagent.vercel.app/agent/leo",
- "created_at": "2026-04-15T00:00:00Z",
- "signature": "0x..." // wallet-signed hash of the rest of the doc
- }
- ```
+ ```jsonc
+ {
+ "$schema": "https://3dagent.vercel.app/schemas/agent-manifest-v1.json",
+ "version": 1,
+ "id": "did:erc8004:1:42",
+ "name": "Coach Leo",
+ "description": "Personal posture coach",
+ "avatar": {
+ "model_url": "ipfs://bafy.../leo.glb",
+ "thumbnail_url": "ipfs://bafy.../thumb.png",
+ },
+ "skills": [{ "id": "greet", "version": "1.0.0", "danger": "safe" }],
+ "memory": { "mode": "encrypted-ipfs", "root": "ipfs://..." },
+ "wallet": "0x...",
+ "homepage": "https://3dagent.vercel.app/agent/leo",
+ "created_at": "2026-04-15T00:00:00Z",
+ "signature": "0x...", // wallet-signed hash of the rest of the doc
+ }
+ ```
2. Generate `public/schemas/agent-manifest-v1.json` (JSON Schema draft 2020-12).
3. Add `src/manifest-validate.js` exporting `validateManifest(json)` using zod (mirror schema). Returns `{ ok, errors }`.
4. Update [src/manifest.js](../../src/manifest.js) to call the validator on every load; reject malformed manifests with a structured error.
diff --git a/prompts/build/06-11-validation-attestation-flow.md b/prompts/build/06-11-validation-attestation-flow.md
index 938e6762a..dd8c5ee73 100644
--- a/prompts/build/06-11-validation-attestation-flow.md
+++ b/prompts/build/06-11-validation-attestation-flow.md
@@ -6,16 +6,16 @@
## Why it matters
-ValidationRegistry exists on testnets; the contract lets allow-listed validators attest to off-chain proofs about an agent (e.g. "model passes gltf-validator", "manifest signature verified", "skill output reproducible"). Without a flow that *uses* it, the registry is dead weight.
+ValidationRegistry exists on testnets; the contract lets allow-listed validators attest to off-chain proofs about an agent (e.g. "model passes gltf-validator", "manifest signature verified", "skill output reproducible"). Without a flow that _uses_ it, the registry is dead weight.
## Read these first
-| File | Why |
-|:---|:---|
-| [contracts/src/ValidationRegistry.sol](../../contracts/src/ValidationRegistry.sol) | Contract surface. |
-| [src/erc8004/validation-recorder.js](../../src/erc8004/validation-recorder.js) | `recordValidation`, `hashReport`. |
-| [api/mcp.js](../../api/mcp.js) | `validate_model` tool — produces a report we can attest. |
-| [api/_lib/](../../api/_lib/) | Auth + db helpers. |
+| File | Why |
+| :--------------------------------------------------------------------------------- | :------------------------------------------------------- |
+| [contracts/src/ValidationRegistry.sol](../../contracts/src/ValidationRegistry.sol) | Contract surface. |
+| [src/erc8004/validation-recorder.js](../../src/erc8004/validation-recorder.js) | `recordValidation`, `hashReport`. |
+| [api/mcp.js](../../api/mcp.js) | `validate_model` tool — produces a report we can attest. |
+| [api/\_lib/](../../api/_lib/) | Auth + db helpers. |
## Build this
@@ -42,5 +42,5 @@ ValidationRegistry exists on testnets; the contract lets allow-listed validators
1. Local anvil with all three registries deployed and indexed.
2. Mint a valid GLB-backed agent. Wait one cron tick. Confirm row in `validations` and on-chain tx.
-3. Mint an agent with a malformed GLB. Confirm it does *not* get a `gltf-valid` attestation.
+3. Mint an agent with a malformed GLB. Confirm it does _not_ get a `gltf-valid` attestation.
4. POST a user-submitted report; verify it appears with unverified tag.
diff --git a/prompts/build/06-12-ipfs-pinning-fallback.md b/prompts/build/06-12-ipfs-pinning-fallback.md
index 049947ee9..6a11a29f2 100644
--- a/prompts/build/06-12-ipfs-pinning-fallback.md
+++ b/prompts/build/06-12-ipfs-pinning-fallback.md
@@ -10,27 +10,29 @@ Manifests and GLBs pinned to web3.storage today rely on a single gateway. If web
## Read these first
-| File | Why |
-|:---|:---|
-| [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js) | Today's pin path. |
-| [src/ipfs.js](../../src/ipfs.js) | IPFS helpers. |
-| [.env.example](../../.env.example) | Document new env vars. |
+| File | Why |
+| :------------------------------------------------------------------- | :--------------------- |
+| [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js) | Today's pin path. |
+| [src/ipfs.js](../../src/ipfs.js) | IPFS helpers. |
+| [.env.example](../../.env.example) | Document new env vars. |
## Build this
1. Add a second pinning provider — `pinata` (no SDK, plain `fetch` to `https://api.pinata.cloud/pinning/pinFileToIPFS`). Configurable via `PINATA_JWT`. If unset, skip silently.
2. Pin in parallel; the upload returns the union `{ cid, providers: ['web3', 'pinata'] }`. Persist in `pins` table.
3. **Gateway list** in `src/ipfs.js`:
- ```js
- export const IPFS_GATEWAYS = [
- 'https://w3s.link/ipfs/',
- 'https://gateway.pinata.cloud/ipfs/',
- 'https://ipfs.io/ipfs/',
- 'https://cloudflare-ipfs.com/ipfs/',
- ];
- export async function fetchFromIpfs(cid, opts) { /* race + fallback */ }
- ```
- Race the first 2; if both fail/timeout (3s), fall back to the rest serially.
+ ```js
+ export const IPFS_GATEWAYS = [
+ 'https://w3s.link/ipfs/',
+ 'https://gateway.pinata.cloud/ipfs/',
+ 'https://ipfs.io/ipfs/',
+ 'https://cloudflare-ipfs.com/ipfs/',
+ ];
+ export async function fetchFromIpfs(cid, opts) {
+ /* race + fallback */
+ }
+ ```
+ Race the first 2; if both fail/timeout (3s), fall back to the rest serially.
4. Update [src/manifest.js](../../src/manifest.js) and any GLB loader that takes `ipfs://` URLs to use `fetchFromIpfs`.
5. Add `scripts/repin.mjs <cid>` — utility to re-pin an existing CID to all configured providers.
diff --git a/prompts/build/06-13-encrypted-memory-mode.md b/prompts/build/06-13-encrypted-memory-mode.md
index dcf38ba3a..5fb2a6351 100644
--- a/prompts/build/06-13-encrypted-memory-mode.md
+++ b/prompts/build/06-13-encrypted-memory-mode.md
@@ -10,21 +10,21 @@
## Read these first
-| File | Why |
-|:---|:---|
-| [src/agent-memory.js](../../src/agent-memory.js) | Memory store; mode dispatch. |
-| [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js) | Pinning helpers. |
-| [src/ipfs.js](../../src/ipfs.js) | Fetch helpers (extended in 06-12). |
+| File | Why |
+| :------------------------------------------------------------------- | :--------------------------------- |
+| [src/agent-memory.js](../../src/agent-memory.js) | Memory store; mode dispatch. |
+| [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js) | Pinning helpers. |
+| [src/ipfs.js](../../src/ipfs.js) | Fetch helpers (extended in 06-12). |
## Build this
1. Use `WebCrypto` only (no new dep). Implement `src/memory-encryption.js`:
- - `encryptMemory(plaintext, key)` → `{ iv, ciphertext }` (AES-GCM-256).
- - `decryptMemory(blob, key)` → plaintext.
- - `deriveKeyFromSignature(signature, salt)` → CryptoKey (HKDF). The signature is produced by signing a fixed challenge string with the agent's wallet — deterministic per wallet, no plaintext key on disk.
+ - `encryptMemory(plaintext, key)` → `{ iv, ciphertext }` (AES-GCM-256).
+ - `decryptMemory(blob, key)` → plaintext.
+ - `deriveKeyFromSignature(signature, salt)` → CryptoKey (HKDF). The signature is produced by signing a fixed challenge string with the agent's wallet — deterministic per wallet, no plaintext key on disk.
2. Wire into `agent-memory.js`:
- - On `add()` in `encrypted-ipfs` mode: encrypt, pin via dual provider (06-12), persist `{ cid, iv }` in localStorage and (if authed) in `agent_memories` server table.
- - On `recall()`: fetch CID, decrypt, return.
+ - On `add()` in `encrypted-ipfs` mode: encrypt, pin via dual provider (06-12), persist `{ cid, iv }` in localStorage and (if authed) in `agent_memories` server table.
+ - On `recall()`: fetch CID, decrypt, return.
3. Add a key-rotation flow: `rotateKey()` re-encrypts the memory log under a new key, repins, updates pointers. Ship the function but no UI yet.
4. Surface mode in [src/agent-home.js](../../src/agent-home.js): show a tiny lock icon when memory is encrypted.
diff --git a/prompts/build/07-01-production-readiness.md b/prompts/build/07-01-production-readiness.md
index 4bcd8dd8a..67cb6325a 100644
--- a/prompts/build/07-01-production-readiness.md
+++ b/prompts/build/07-01-production-readiness.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Make the deployment actually observable — error tracking, usage metrics, health checks"
+description: 'Make the deployment actually observable — error tracking, usage metrics, health checks'
---
# 07-01 · Production readiness
@@ -15,16 +15,16 @@ None. Can be done anytime after pillar 1 ships.
## Read these first
-- [api/_lib/http.js](../../api/_lib/http.js) — `wrap()` catches all unhandled errors. Extend it.
-- [api/_lib/env.js](../../api/_lib/env.js) — env var access pattern.
-- [api/_lib/rate-limit.js](../../api/_lib/rate-limit.js) — Upstash Redis already a dep.
+- [api/\_lib/http.js](../../api/_lib/http.js) — `wrap()` catches all unhandled errors. Extend it.
+- [api/\_lib/env.js](../../api/_lib/env.js) — env var access pattern.
+- [api/\_lib/rate-limit.js](../../api/_lib/rate-limit.js) — Upstash Redis already a dep.
## Build this
### 1. Error reporting
- Add Sentry (or a simpler equivalent like Axiom / Logtail) as the error sink. Sentry is the conservative choice — the `@sentry/node` SDK works in Vercel functions.
-- Initialize at the top of [api/_lib/http.js](../../api/_lib/http.js)'s `wrap` helper.
+- Initialize at the top of [api/\_lib/http.js](../../api/_lib/http.js)'s `wrap` helper.
- Tag events with: `endpoint` (req.url), `user_id` (if session), `release` (git sha at build time).
- Env: `SENTRY_DSN`. If unset, log to stderr and no-op on network — do not crash.
@@ -50,10 +50,10 @@ None. Can be done anytime after pillar 1 ships.
### 5. Deploy script
- Add a `scripts/deploy-check.sh` that:
- 1. Runs `npm run build`.
- 2. POSTs to `/api/health` on the current Vercel preview URL — fails if not 200.
- 3. Runs `scripts/smoke-stack.sh` (from prompt `00-stack-e2e-smoke.md`).
- 4. Only on green, prints the promote-to-prod command.
+ 1. Runs `npm run build`.
+ 2. POSTs to `/api/health` on the current Vercel preview URL — fails if not 200.
+ 3. Runs `scripts/smoke-stack.sh` (from prompt `00-stack-e2e-smoke.md`).
+ 4. Only on green, prints the promote-to-prod command.
Do not auto-promote. Deploys are still manual.
diff --git a/prompts/build/07-02-owner-analytics.md b/prompts/build/07-02-owner-analytics.md
index 9beb92317..d678575b0 100644
--- a/prompts/build/07-02-owner-analytics.md
+++ b/prompts/build/07-02-owner-analytics.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Owner analytics: views, chat msgs, embed loads per agent — shown on the dashboard"
+description: 'Owner analytics: views, chat msgs, embed loads per agent — shown on the dashboard'
---
# 07-02 · Owner analytics
@@ -16,9 +16,9 @@ Owners who share their agent want to know if anyone's actually interacting with
## Read these first
-- [api/_lib/http.js](../../api/_lib/http.js) — `wrap()` is where we'll record events.
-- [api/_lib/rate-limit.js](../../api/_lib/rate-limit.js) — reuses Upstash Redis.
-- [api/_lib/schema.sql](../../api/_lib/schema.sql) — `usage_events` table already exists.
+- [api/\_lib/http.js](../../api/_lib/http.js) — `wrap()` is where we'll record events.
+- [api/\_lib/rate-limit.js](../../api/_lib/rate-limit.js) — reuses Upstash Redis.
+- [api/\_lib/schema.sql](../../api/_lib/schema.sql) — `usage_events` table already exists.
## Build this
@@ -26,7 +26,7 @@ Owners who share their agent want to know if anyone's actually interacting with
Instrument these endpoints to write rows into `usage_events`:
-- `GET /agent/:id` (via a middleware or shared helper) → `kind='agent_view'`.
+- `GET /agent/:id` (via a middleware or shared helper) → `kind='agent_view'`.
- `GET /agent/:id/embed` → `kind='agent_embed_view'`.
- `POST /api/agents/:id/chat` (prompt `04-05`) → `kind='agent_chat_msg'`.
- `GET /api/agent-oembed` → `kind='agent_unfurl'`.
diff --git a/prompts/build/08-01-marketing-landing.md b/prompts/build/08-01-marketing-landing.md
index ca740aa39..a9b922fc5 100644
--- a/prompts/build/08-01-marketing-landing.md
+++ b/prompts/build/08-01-marketing-landing.md
@@ -1,6 +1,6 @@
---
mode: agent
-description: "Rewrite the root landing page to sell the actual product: embodied agents you can embed anywhere"
+description: 'Rewrite the root landing page to sell the actual product: embodied agents you can embed anywhere'
---
# 08-01 · Marketing landing page
diff --git a/prompts/build/README.md b/prompts/build/README.md
index f726c8392..04a46afbe 100644
--- a/prompts/build/README.md
+++ b/prompts/build/README.md
@@ -9,7 +9,7 @@ Prompts in this directory are scoped to the product priority stack. If a prompt
3. **Edit avatar** — swap, regenerate, tweak without destroying identity. `03-*`.
4. **View & embed** — agent page polish and iframe/oEmbed so the avatar can be shared. `04-*`.
5. **Host embed** — avatar lives inside Claude.ai Artifacts and Lobehub chat (user has a Lobehub fork — primary integration target). `05-*`.
-6. **Onchain portability** — the agent is pulled *from chain* into any host. The novel unlock. `06-*`.
+6. **Onchain portability** — the agent is pulled _from chain_ into any host. The novel unlock. `06-*`.
## Prompt file format
@@ -37,9 +37,11 @@ Within a pillar, suffix numbers indicate sequence: `02-01-*` before `02-02-*`.
## Prompts
**Stack-wide**
+
- [00-stack-e2e-smoke.md](./00-stack-e2e-smoke.md) — end-to-end smoke script
**Pillar 1 — Wallet auth**
+
- [01-01-wallet-auth-smoke-test.md](./01-01-wallet-auth-smoke-test.md) — e2e verification of SIWE login
- [01-01-wallet-auth-privy.md](./01-01-wallet-auth-privy.md) — Privy fallback provider
- [01-01-wallet-link-existing-account.md](./01-01-wallet-link-existing-account.md) — link without new account
@@ -55,6 +57,7 @@ Within a pillar, suffix numbers indicate sequence: `02-01-*` before `02-02-*`.
- [01-04-wallet-chain-switch.md](./01-04-wallet-chain-switch.md) — chain switching prompt UX
**Pillar 2 — Selfie → agent**
+
- [02-01-selfie-capture-ui.md](./02-01-selfie-capture-ui.md) — camera capture page
- [02-02-selfie-upload-r2.md](./02-02-selfie-upload-r2.md) — presign + PUT to R2
- [02-02-image-to-3d-backend.md](./02-02-image-to-3d-backend.md) — backend pipeline scaffolding
@@ -68,6 +71,7 @@ Within a pillar, suffix numbers indicate sequence: `02-01-*` before `02-02-*`.
- [02-06-no-wallet-guest-creation.md](./02-06-no-wallet-guest-creation.md) — guest path (no wallet required)
**Pillar 3 — Edit avatar**
+
- [03-01-avatar-swap.md](./03-01-avatar-swap.md) — swap GLB on existing agent
- [03-01-dashboard-edit-tab.md](./03-01-dashboard-edit-tab.md) — edit tab on dashboard
- [03-01-regenerate-from-new-selfie.md](./03-01-regenerate-from-new-selfie.md) — retake + regenerate
@@ -81,6 +85,7 @@ Within a pillar, suffix numbers indicate sequence: `02-01-*` before `02-02-*`.
- [03-05-memory-review-and-edit.md](./03-05-memory-review-and-edit.md) — inspect and edit memories
**Pillar 4 — View & embed**
+
- [04-01-agent-public-page-polish.md](./04-01-agent-public-page-polish.md) — mobile-first polish
- [04-01-agent-page-polish.md](./04-01-agent-page-polish.md) — desktop-side polish
- [04-01-agent-og-image.md](./04-01-agent-og-image.md) — dedicated OG endpoint
@@ -92,6 +97,7 @@ Within a pillar, suffix numbers indicate sequence: `02-01-*` before `02-02-*`.
- [04-04-agent-card-json.md](./04-04-agent-card-json.md) — A2A discovery card
**Pillar 5 — Host embed**
+
- [05-01-claude-artifact-embed.md](./05-01-claude-artifact-embed.md) — Claude iframe snippet
- [05-01-claude-artifact-build.md](./05-01-claude-artifact-build.md) — artifact builder tooling
- [05-01-claude-artifact-export.md](./05-01-claude-artifact-export.md) — export-as-artifact flow
@@ -105,6 +111,7 @@ Within a pillar, suffix numbers indicate sequence: `02-01-*` before `02-02-*`.
- [05-05-host-resize-and-mode.md](./05-05-host-resize-and-mode.md) — auto-resize + kiosk modes
**Pillar 6 — Onchain portability**
+
- [06-01-erc8004-mint-from-ui.md](./06-01-erc8004-mint-from-ui.md) — mint wizard
- [06-02-pin-card-to-ipfs.md](./06-02-pin-card-to-ipfs.md) — pin card, store CID
- [06-03-resolve-agent-from-chain.md](./06-03-resolve-agent-from-chain.md) — chain → body resolver
diff --git a/prompts/claude-artifact/01-artifact-snippet.md b/prompts/claude-artifact/01-artifact-snippet.md
index d46380b76..a55635d8e 100644
--- a/prompts/claude-artifact/01-artifact-snippet.md
+++ b/prompts/claude-artifact/01-artifact-snippet.md
@@ -22,7 +22,7 @@ Create a copy-pasteable HTML template, &lt;2 KB, that a Claude user drops into c
## Deliverable
1. **File created** — `public/artifact/index.html`. This is both the documentation of the snippet and a working preview page when hit directly. Contents are the snippet verbatim, wrapped only in enough surrounding `<html><body>` to render standalone.
-2. **File created** — `public/artifact/snippet.html`. The *exact* string users copy/paste. Minified where safe. Ends with a comment naming the project and version.
+2. **File created** — `public/artifact/snippet.html`. The _exact_ string users copy/paste. Minified where safe. Ends with a comment naming the project and version.
3. **File created** — `prompts/claude-artifact/TESTED-SNIPPET.md` (NOT a codebase doc — it lives in this prompts dir only) — the verbatim snippet that was tested in a real Claude Artifact, plus a note on the date tested and the Claude model used.
4. **Edit** — add a "Claude Artifact" tab to the share panel on [public/agent/index.html](../../public/agent/index.html) next to the existing iframe/link/`<agent-3d>` tabs, exposing a copy button that yields the snippet from `snippet.html` with `agentId` substituted in.
@@ -30,14 +30,18 @@ Create a copy-pasteable HTML template, &lt;2 KB, that a Claude user drops into c
```html
<!doctype html>
-<html><head><meta charset="utf-8"></head>
-<body style="margin:0;background:#0b0d10">
-<div id="a" style="width:100%;height:100vh"></div>
-<script src="https://3dagent.vercel.app/artifact.js"></script>
-<script>
- Agent3D.mount('#a', { agentId: 'AGENT_ID_HERE' });
-</script>
-</body></html>
+<html>
+ <head>
+ <meta charset="utf-8" />
+ </head>
+ <body style="margin:0;background:#0b0d10">
+ <div id="a" style="width:100%;height:100vh"></div>
+ <script src="https://3dagent.vercel.app/artifact.js"></script>
+ <script>
+ Agent3D.mount('#a', { agentId: 'AGENT_ID_HERE' });
+ </script>
+ </body>
+</html>
```
- Background is a reasonable default (dark). The user can change it.
@@ -79,7 +83,7 @@ Implement (1) inline with a small `onerror` handler on the script tag. (2) and (
1. `wc -c public/artifact/snippet.html` — report bytes.
2. `npx vite build` — report result.
3. Manually: open a Claude chat, paste the snippet with a real agentId (`0x-demo-agent` or equivalent) into an `html` artifact. Screenshot or describe the result. If the avatar renders and breathes, verification passes.
-4. Paste the snippet with `AGENT_ID_HERE` *unchanged* — expect a clear instruction overlay, not a silent blank.
+4. Paste the snippet with `AGENT_ID_HERE` _unchanged_ — expect a clear instruction overlay, not a silent blank.
5. Verify the share-panel copy button in `public/agent/index.html` yields the exact bytes of `snippet.html` with id substituted.
## Scope boundaries — do NOT do these
@@ -93,6 +97,7 @@ Implement (1) inline with a small `onerror` handler on the script tag. (2) and (
## Reporting
At the end, summarise:
+
- Byte count of `snippet.html`.
- Which files were created and which edited (list sections in `public/agent/index.html`).
- The exact snippet that was pasted into a live Claude Artifact and what happened.
diff --git a/prompts/claude-artifact/02-zero-dep-viewer-bundle.md b/prompts/claude-artifact/02-zero-dep-viewer-bundle.md
index ffd5c90b4..f11b775fb 100644
--- a/prompts/claude-artifact/02-zero-dep-viewer-bundle.md
+++ b/prompts/claude-artifact/02-zero-dep-viewer-bundle.md
@@ -17,6 +17,7 @@ This task produces `artifact.js` — a single self-contained, zero-install, CDN-
5. Supports both `agentId` lookup and **ERC-8004 onchain lookup** (delegating to [../../src/agent-resolver.js](../../src/agent-resolver.js) logic, ported into the bundle as needed).
Relevant existing modules:
+
- [../../src/element.js](../../src/element.js) — full web component. Too heavy for an Artifact bundle. Cannibalise selectively.
- [../../src/viewer.js](../../src/viewer.js) — ~11k LOC. Do **not** bundle as-is; port only the minimum: GLB load, render loop, camera setup.
- [../../src/agent-avatar.js](../../src/agent-avatar.js) — Empathy Layer. Small and self-contained. Port whole.
@@ -59,7 +60,7 @@ Agent3D.mount(target, opts) → Promise<Instance>
1. **New directory** `artifact-bundle/` at the repo root with its own `package.json`, `src/index.js`, `rollup.config.js` (or `esbuild.config.js`). This is a separate build pipeline from the main Vite app — its output is `public/artifact.js`, committed, not gitignored, so Vercel serves it statically.
2. **Build script** wired into the root `package.json` as `npm run build:artifact`. CI-safe (`npm run build` does NOT need to run it — but document clearly in the bundle's README that `build:artifact` must be re-run before shipping changes).
3. **Port, don't re-depend** — the bundle must not import the full [src/viewer.js](../../src/viewer.js). Extract the render loop + GLB load into `artifact-bundle/src/mini-viewer.js`. The Empathy Layer ([src/agent-avatar.js](../../src/agent-avatar.js)) and protocol ([src/agent-protocol.js](../../src/agent-protocol.js)) can be imported or copy-forwarded — document the choice in the bundle README.
-4. **CORS** — add `Access-Control-Allow-Origin: *` to responses from `/api/agents/:id`, `/api/avatars/:id`, and `/api/agents/:id/resolve` (or whatever the resolver consumes). Verify in [api/_lib/](../../api/_lib/) that CORS middleware exists or add it. Allowed origins MUST include at minimum: `claude.ai`, `*.claude.ai`, `claude.com`, `*.claude.com`, `anthropic.com`, `*.anthropic.com`, or be `*`.
+4. **CORS** — add `Access-Control-Allow-Origin: *` to responses from `/api/agents/:id`, `/api/avatars/:id`, and `/api/agents/:id/resolve` (or whatever the resolver consumes). Verify in [api/\_lib/](../../api/_lib/) that CORS middleware exists or add it. Allowed origins MUST include at minimum: `claude.ai`, `*.claude.ai`, `claude.com`, `*.claude.com`, `anthropic.com`, `*.anthropic.com`, or be `*`.
5. **three.js loading** — inside `mount()`, dynamically inject `<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.min.js">` and the GLTFLoader companion. Wait for `window.THREE`. If already present, skip.
6. **Output file** — committed at `public/artifact.js`. Vercel serves `/artifact.js` at edge.
@@ -112,6 +113,7 @@ Agent3D.mount(target, opts) → Promise<Instance>
## Reporting
At the end, summarise:
+
- `public/artifact.js` size (raw + gzipped).
- Which files from `src/` were ported vs imported vs rewritten.
- CORS changes shipped (which endpoints, what headers).
diff --git a/prompts/claude-artifact/03-idle-animation-loop.md b/prompts/claude-artifact/03-idle-animation-loop.md
index 5c194d732..2e1bd2a25 100644
--- a/prompts/claude-artifact/03-idle-animation-loop.md
+++ b/prompts/claude-artifact/03-idle-animation-loop.md
@@ -9,20 +9,21 @@ The Empathy Layer in [../../src/agent-avatar.js](../../src/agent-avatar.js) is a
This task specifies an idle-loop driver that lives inside the bundle from [./02-zero-dep-viewer-bundle.md](./02-zero-dep-viewer-bundle.md) and makes the avatar look alive without any user input.
Relevant existing files:
+
- [../../src/agent-avatar.js](../../src/agent-avatar.js) — Empathy Layer. The `_injectStimulus(emotion, weight)` method is the right entry point for injecting synthetic stimuli (see `_onSpeak`, `_onSkillDone` etc. for patterns).
- [../../src/agent-protocol.js](../../src/agent-protocol.js) — the bus. Idle-loop stimuli can be fired through `protocol.emit()` so the Empathy Layer reacts naturally rather than directly poking `_emotion`.
## Goal
-Design and implement an idle animation loop that makes the Artifact-embedded avatar look subtly alive — continuous breathing, occasional head glances, very rare blinks — without being distracting and without requiring any user interaction. The loop must be layered *on top of* the existing Empathy Layer so that real stimuli (from task 04's chat-message postMessage bridge) still override it cleanly.
+Design and implement an idle animation loop that makes the Artifact-embedded avatar look subtly alive — continuous breathing, occasional head glances, very rare blinks — without being distracting and without requiring any user interaction. The loop must be layered _on top of_ the existing Empathy Layer so that real stimuli (from task 04's chat-message postMessage bridge) still override it cleanly.
## Deliverable
1. **File created** — `artifact-bundle/src/idle-loop.js` (lives under the bundle directory from task 02). Exports `class IdleLoop`:
```js
- new IdleLoop({ avatar, protocol, viewer }).start()
- idle.stop()
+ new IdleLoop({ avatar, protocol, viewer }).start();
+ idle.stop();
```
2. Integration point in `artifact-bundle/src/index.js` (from task 02) — when `opts.idle !== false`, instantiate and start the loop at the end of `mount()`.
@@ -32,25 +33,30 @@ Design and implement an idle animation loop that makes the Artifact-embedded ava
## Behaviour specification
### Breathing (continuous)
+
- Apply a sine-wave scale to the root bone's Y position (or chest bone if found): `amplitude = 0.006` in world units, `period = 4.0 s`. This is pure kinematics — do NOT route through the emotion blend.
- Find-the-bone logic: traverse scene for a bone named `Spine`, `Spine1`, `Chest`, or `mixamorigSpine`, case-insensitive. Fall back to animating the root of the skinned mesh if no bone found.
- Budget: &lt;0.05 ms per frame.
### Head glance (occasional)
+
- Every `randBetween(6, 14)` seconds, pick a random off-axis look target within a cone of ±30° horizontal, ±15° vertical, at distance 2m in front of the avatar. Hold for `randBetween(1.2, 2.5)` seconds, then glance back to center for a random hold `randBetween(2, 5)` seconds.
- Drive this through the Empathy Layer by calling `avatar.setLookTarget(vec3)` — existing API. Do NOT bypass.
- While a glance is active, inject a very small `curiosity` stimulus (`weight: 0.15`) on glance-start so the avatar's face subtly engages.
### Blink (rare — only when model supports it)
+
- Detect if any morph target named `eyeBlinkLeft` / `eyeBlinkRight` / `eyesClosed` exists on any mesh. If not, skip entirely.
- Every `randBetween(3, 7)` seconds, play a 120 ms blink: ramp closed→0.95, hold 40 ms, ramp open→0.0. Apply directly to morph targets, do NOT route through the blend map.
- Never fire mid-glance (skip if glance just started).
### Ambient emotion drift (very subtle)
+
- Every `randBetween(15, 40)` seconds, inject one of `{ curiosity: 0.20, empathy: 0.15, celebration: 0.18 }` — choose uniformly. Let the Empathy Layer's existing decay handle fade-out. Never inject concern from the idle loop.
- Skip injection entirely if the current blended weight of that emotion is already &gt; 0.3 (don't pile on).
### First-encounter behaviour
+
- The existing Empathy Layer already does a curiosity burst at attach-time (see [src/agent-avatar.js:120-126](../../src/agent-avatar.js)). The idle loop must NOT duplicate it. Add a 2-second grace period after `start()` before the idle loop fires its first stimulus.
## Audit checklist — must handle all of these
@@ -93,6 +99,7 @@ Design and implement an idle animation loop that makes the Artifact-embedded ava
## Reporting
At the end, summarise:
+
- File created (`artifact-bundle/src/idle-loop.js`), lines of code.
- Integration point changed in `artifact-bundle/src/index.js` (one line or a block).
- Bundle size delta (before/after gzipped).
diff --git a/prompts/claude-artifact/04-example-gallery.md b/prompts/claude-artifact/04-example-gallery.md
index 2e5f9d7fc..01bd5000a 100644
--- a/prompts/claude-artifact/04-example-gallery.md
+++ b/prompts/claude-artifact/04-example-gallery.md
@@ -10,6 +10,7 @@ Repo: `/workspaces/3D`. Tasks [./01-artifact-snippet.md](./01-artifact-snippet.m
This task extends that with a **curated gallery of ready-to-paste templates** for the four main use cases. The goal is that a Claude user (or, meta-circle, a Claude instance generating HTML for its user) can pick the closest template and paste it verbatim.
Relevant existing files:
+
- [../../public/agent/index.html](../../public/agent/index.html) — already hosts a share panel; add a "Claude Artifacts" tab group here.
- [../../public/artifact/snippet.html](../../public/artifact/) — produced by task 01.
- [../../public/artifact.js](../../public/artifact.js) — produced by task 02.
@@ -22,58 +23,71 @@ Produce four self-contained Claude Artifact HTML templates, each &lt;3 KB, hoste
## The four templates
### A. "My agent"
+
The trivial case — the signed-in user's own agent.
+
```html
<script src="https://3dagent.vercel.app/artifact.js"></script>
<script>
- Agent3D.mount('#a', { agentId: 'AGENT_ID_HERE' });
+ Agent3D.mount('#a', { agentId: 'AGENT_ID_HERE' });
</script>
```
-*Already delivered by task 01. Just reference it from the gallery.*
+
+_Already delivered by task 01. Just reference it from the gallery._
### B. "Any wallet's agent"
+
Resolve the primary agent for a given Ethereum address.
+
```html
<script src="https://3dagent.vercel.app/artifact.js"></script>
<script>
- Agent3D.mount('#a', { wallet: '0xWALLET_HERE' });
+ Agent3D.mount('#a', { wallet: '0xWALLET_HERE' });
</script>
```
-*Depends on the bundle's `wallet` mode (task 02). If the wallet has no registered agent, the bundle renders the stand-in.*
+
+_Depends on the bundle's `wallet` mode (task 02). If the wallet has no registered agent, the bundle renders the stand-in._
### C. "Any ERC-8004 agent from chain"
+
Look up directly by onchain agent id.
+
```html
<script src="https://3dagent.vercel.app/artifact.js"></script>
<script>
- Agent3D.mount('#a', { chain: 'base', onchainId: 42 });
+ Agent3D.mount('#a', { chain: 'base', onchainId: 42 });
</script>
```
-*`chain` accepts keys from `REGISTRY_DEPLOYMENTS` in [../../src/erc8004/abi.js](../../src/erc8004/abi.js). Document the supported chain keys inline in the gallery.*
+
+_`chain` accepts keys from `REGISTRY_DEPLOYMENTS` in [../../src/erc8004/abi.js](../../src/erc8004/abi.js). Document the supported chain keys inline in the gallery._
### D. "Talking agent — responds to chat messages via postMessage"
+
The novel template. The Artifact sandbox receives `postMessage` from its parent (Claude's chat UI) or from a sibling Artifact, and the avatar responds by speaking the text (routing through the Empathy Layer so the face reacts).
+
```html
<script src="https://3dagent.vercel.app/artifact.js"></script>
<script>
- const agent = Agent3D.mount('#a', { agentId: 'AGENT_ID_HERE' });
- window.addEventListener('message', (ev) => {
- const msg = ev.data;
- if (msg && msg.type === 'speak' && typeof msg.text === 'string') {
- agent.then(a => a.say(msg.text));
- }
- });
+ const agent = Agent3D.mount('#a', { agentId: 'AGENT_ID_HERE' });
+ window.addEventListener('message', (ev) => {
+ const msg = ev.data;
+ if (msg && msg.type === 'speak' && typeof msg.text === 'string') {
+ agent.then((a) => a.say(msg.text));
+ }
+ });
</script>
```
-*Caveat: Claude's chat UI does not currently post arbitrary messages into Artifact iframes. This template is valuable for (1) Artifact-to-Artifact communication within the same chat, (2) hosts beyond Claude that adopt the same protocol, (3) future Claude features. The gallery page must document this caveat clearly.*
+
+_Caveat: Claude's chat UI does not currently post arbitrary messages into Artifact iframes. This template is valuable for (1) Artifact-to-Artifact communication within the same chat, (2) hosts beyond Claude that adopt the same protocol, (3) future Claude features. The gallery page must document this caveat clearly._
## Deliverable
1. **File created** — `public/artifact/gallery.html`. A static page under `/artifact/gallery` that:
- - Lists the four templates as cards with a live preview iframe for each (loading `public/artifact/preview-{a,b,c,d}.html`).
- - Each card has a "Copy" button that copies the template's HTML snippet to clipboard.
- - Includes the Artifact-sandbox caveats from [./README.md](./README.md) in a short expandable section.
- - Minimal CSS, self-contained, no frameworks.
+
+ - Lists the four templates as cards with a live preview iframe for each (loading `public/artifact/preview-{a,b,c,d}.html`).
+ - Each card has a "Copy" button that copies the template's HTML snippet to clipboard.
+ - Includes the Artifact-sandbox caveats from [./README.md](./README.md) in a short expandable section.
+ - Minimal CSS, self-contained, no frameworks.
2. **Files created** — `public/artifact/preview-a.html`, `preview-b.html`, `preview-c.html`, `preview-d.html`. Each is a rendering of the corresponding template with a working placeholder id/wallet/onchainId so visitors can see what the result looks like before pasting into Claude.
@@ -126,6 +140,7 @@ The novel template. The Artifact sandbox receives `postMessage` from its parent
## Reporting
At the end, summarise:
+
- Files created under `public/artifact/` with byte counts.
- The one `prompts/README.md` edit (one bullet, line number).
- The paste-into-Claude result for each of the four templates — one line each.
diff --git a/prompts/claude-artifact/README.md b/prompts/claude-artifact/README.md
index f59a879fa..eb94b4b78 100644
--- a/prompts/claude-artifact/README.md
+++ b/prompts/claude-artifact/README.md
@@ -10,7 +10,7 @@ Claude.ai renders each `html` Artifact in a sandboxed iframe. A Claude user shou
## What's the deliverable exactly
-Not code. The deliverable for this directory is *prompts* that a future Claude Code session will execute to produce:
+Not code. The deliverable for this directory is _prompts_ that a future Claude Code session will execute to produce:
1. A copy-pasteable minimal HTML snippet (task 01).
2. A hosted single-file bundle, `https://3dagent.vercel.app/artifact.js`, that the snippet loads (task 02).
diff --git a/prompts/claude-lobehub/00-README.md b/prompts/claude-lobehub/00-README.md
index fd481a222..06cb89909 100644
--- a/prompts/claude-lobehub/00-README.md
+++ b/prompts/claude-lobehub/00-README.md
@@ -5,12 +5,13 @@
**Claude.ai / Artifacts**: An MCP tool call returns a self-contained HTML artifact that renders the agent's 3D avatar inline in the Claude conversation. User sees an embodied agent, not a JSON blob.
**LobeHub**: In the user's LobeHub fork (they are the primary integration target), the chat panel has an always-on 3D avatar beside the messages. The avatar:
+
- is summoned from an agent id or wallet address
- reacts to chat events (typing, speaking, emoting)
- persists across turns in the same session
- can be swapped by entering a different agent id
-The novelty is that *the same agent* renders identically in both hosts, because both pull from the same public URL (band 4) or on-chain record (band 6).
+The novelty is that _the same agent_ renders identically in both hosts, because both pull from the same public URL (band 4) or on-chain record (band 6).
## Current state
@@ -20,12 +21,12 @@ The novelty is that *the same agent* renders identically in both hosts, because
## Prompts in this band
-| # | File | Depends on |
-|---|---|---|
-| 01 | [claude-artifact.md](./01-claude-artifact.md) | band 4 public embed solid |
-| 02 | [lobehub-plugin-scaffold.md](./02-lobehub-plugin-scaffold.md) | — |
-| 03 | [lobehub-chat-bridge.md](./03-lobehub-chat-bridge.md) | 02 |
-| 04 | [agent-from-url-or-id.md](./04-agent-from-url-or-id.md) | 02 |
+| # | File | Depends on |
+| --- | ------------------------------------------------------------- | ------------------------- |
+| 01 | [claude-artifact.md](./01-claude-artifact.md) | band 4 public embed solid |
+| 02 | [lobehub-plugin-scaffold.md](./02-lobehub-plugin-scaffold.md) | — |
+| 03 | [lobehub-chat-bridge.md](./03-lobehub-chat-bridge.md) | 02 |
+| 04 | [agent-from-url-or-id.md](./04-agent-from-url-or-id.md) | 02 |
## Done = merged when
diff --git a/prompts/complete/01-walletconnect-siwe.md b/prompts/complete/01-walletconnect-siwe.md
index a6f440301..c0cf4feb8 100644
--- a/prompts/complete/01-walletconnect-siwe.md
+++ b/prompts/complete/01-walletconnect-siwe.md
@@ -2,7 +2,7 @@
## Why
-SIWE end-to-end already works via injected wallets (MetaMask) and Privy (see [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) and [src/erc8004/privy.js](../../src/erc8004/privy.js)). What's missing: an explicit, documented WalletConnect v2 path so a user on a mobile-only wallet can still sign in without Privy. Privy *bundles* WalletConnect internally, but there's no clean standalone path for devs who don't want Privy as a dep.
+SIWE end-to-end already works via injected wallets (MetaMask) and Privy (see [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) and [src/erc8004/privy.js](../../src/erc8004/privy.js)). What's missing: an explicit, documented WalletConnect v2 path so a user on a mobile-only wallet can still sign in without Privy. Privy _bundles_ WalletConnect internally, but there's no clean standalone path for devs who don't want Privy as a dep.
Closes the audit's only remaining wallet-auth gap.
@@ -20,13 +20,13 @@ export async function disconnectWalletConnect() → void
Signature:
1. Lazy-load `@walletconnect/ethereum-provider` from a CDN (esm.sh) — **no new npm dep**. Use dynamic `import()` so this code only runs when the user clicks the WalletConnect button.
-2. Read `projectId` from arg → `VITE_WALLETCONNECT_PROJECT_ID` env → `/api/config` fallback (already returns arbitrary public config; see [api/config.js](../../api/config.js) — add a key *only* if you must, otherwise read from VITE\_).
+2. Read `projectId` from arg → `VITE_WALLETCONNECT_PROJECT_ID` env → `/api/config` fallback (already returns arbitrary public config; see [api/config.js](../../api/config.js) — add a key _only_ if you must, otherwise read from VITE\_).
3. Connect provider, request `eth_requestAccounts`, then run the existing SIWE flow:
- - `GET /api/auth/siwe/nonce` → nonce
- - Build EIP-4361 message matching the format in [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) (domain = `location.host`, uri = `location.origin`, chainId from provider, version `1`, issuedAt ISO).
- - Sign via `provider.request({ method: 'personal_sign', params: [message, address] })`.
- - `POST /api/auth/siwe/verify` with `{ message, signature, address }`.
- - On success, set cookie (server does this), call `writeAuthHint(true)` from [src/account.js](../../src/account.js).
+ - `GET /api/auth/siwe/nonce` → nonce
+ - Build EIP-4361 message matching the format in [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) (domain = `location.host`, uri = `location.origin`, chainId from provider, version `1`, issuedAt ISO).
+ - Sign via `provider.request({ method: 'personal_sign', params: [message, address] })`.
+ - `POST /api/auth/siwe/verify` with `{ message, signature, address }`.
+ - On success, set cookie (server does this), call `writeAuthHint(true)` from [src/account.js](../../src/account.js).
4. On failure, surface a typed error `{ code: 'wc/<stage>', message }` so the sign-in UI can show it.
Also add: `src/auth/walletconnect-bridge.test.html` — a minimal standalone page (not linked from the app) that instantiates the bridge, shows connect/sign-in/disconnect buttons, and logs results. Useful for manual smoke.
diff --git a/prompts/complete/02-editor-spec.md b/prompts/complete/02-editor-spec.md
index 9ecdbfebb..d7591a673 100644
--- a/prompts/complete/02-editor-spec.md
+++ b/prompts/complete/02-editor-spec.md
@@ -23,6 +23,7 @@ Document how `<agent-3d editor>` activates the editor panel. List every editor-o
### 3. Editor panels (one subsection each)
Walk [src/editor/](../../src/editor/) and document each panel's public interface:
+
- `material-editor.js` — what it edits, what events it fires, what state it owns.
- `scene-explorer.js` — tree shape, selection semantics, mesh visibility toggle.
- `texture-inspector.js` — read-only? mutating? export path.
diff --git a/prompts/complete/03-claude-artifact.md b/prompts/complete/03-claude-artifact.md
index afde60b63..e25717a22 100644
--- a/prompts/complete/03-claude-artifact.md
+++ b/prompts/complete/03-claude-artifact.md
@@ -2,7 +2,7 @@
## Why
-Band 5 goal: an embodied agent renders *inside* a Claude.ai chat as an artifact, not as a JSON blob. Claude.ai artifacts are standalone HTML documents — no external script tags allowed beyond whatever runs inside the sandboxed iframe the artifact is rendered in.
+Band 5 goal: an embodied agent renders _inside_ a Claude.ai chat as an artifact, not as a JSON blob. Claude.ai artifacts are standalone HTML documents — no external script tags allowed beyond whatever runs inside the sandboxed iframe the artifact is rendered in.
Today [api/mcp.js](../../api/mcp.js) has a `render_avatar` tool but there's no dedicated endpoint that returns a **single self-contained HTML document** an agent can cite directly. This prompt ships that.
@@ -21,24 +21,37 @@ Output shape — a minimal HTML document inline-styled and inline-scripted, usin
```html
<!doctype html>
<html lang="en">
- <head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width,initial-scale=1">
- <title>CZ — 3D Agent</title>
- <style>html,body{margin:0;height:100%;background:#080814;} agent-3d{display:block;width:100%;height:100%}</style>
- </head>
- <body>
- <agent-3d agent="{agentId}" eager></agent-3d>
- <script src="https://3dagent.vercel.app/dist-lib/agent-3d.umd.cjs"></script>
- </body>
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>CZ — 3D Agent</title>
+ <style>
+ html,
+ body {
+ margin: 0;
+ height: 100%;
+ background: #080814;
+ }
+ agent-3d {
+ display: block;
+ width: 100%;
+ height: 100%;
+ }
+ </style>
+ </head>
+ <body>
+ <agent-3d agent="{agentId}" eager></agent-3d>
+ <script src="https://3dagent.vercel.app/dist-lib/agent-3d.umd.cjs"></script>
+ </body>
</html>
```
Requirements:
-- Validate `agentId` / `glbUrl` — reject anything that doesn't match `/^[a-z0-9-]{3,64}$/i` for agent, or a whitelisted https origin for model (reuse [api/_lib/fetch-model.js](../../api/_lib/fetch-model.js) if it has a URL-validation helper).
+
+- Validate `agentId` / `glbUrl` — reject anything that doesn't match `/^[a-z0-9-]{3,64}$/i` for agent, or a whitelisted https origin for model (reuse [api/\_lib/fetch-model.js](../../api/_lib/fetch-model.js) if it has a URL-validation helper).
- `Content-Security-Policy: default-src 'self' https://3dagent.vercel.app; script-src 'self' 'unsafe-inline' https://3dagent.vercel.app; img-src * data: blob:; connect-src *; style-src 'self' 'unsafe-inline'; frame-ancestors *` — permissive enough to embed in Claude.ai's artifact iframe.
-- Use [api/_lib/http.js](../../api/_lib/http.js) to set headers; output via `res.end(html)` is OK here *only* because we're returning HTML, not JSON (the "no res.end" rule is for JSON responses). Document this exception inline.
-- Rate-limit via `limits.publicRead` from [api/_lib/limits.js](../../api/_lib/limits.js) if the preset exists.
+- Use [api/\_lib/http.js](../../api/_lib/http.js) to set headers; output via `res.end(html)` is OK here _only_ because we're returning HTML, not JSON (the "no res.end" rule is for JSON responses). Document this exception inline.
+- Rate-limit via `limits.publicRead` from [api/\_lib/limits.js](../../api/_lib/limits.js) if the preset exists.
### 2. Static fallback + docs
diff --git a/prompts/complete/04-lobehub-plugin.md b/prompts/complete/04-lobehub-plugin.md
index 4a84b77bc..36090d1d0 100644
--- a/prompts/complete/04-lobehub-plugin.md
+++ b/prompts/complete/04-lobehub-plugin.md
@@ -32,7 +32,7 @@ Create `public/lobehub/iframe/index.html` — minimal page that:
Create `api/lobehub/handshake.js` — POST-only JSON endpoint that, given `{ agentId, hostOrigin }`, returns `{ ok: true, iframeUrl, embedPolicy }`. This lets LobeHub pre-validate the agent before rendering the iframe (avoiding a broken iframe on unknown agents).
-Use `sql` from [api/_lib/db.js](../../api/_lib/db.js) to look up `agents` by id — return 404 if missing. Use `json()` / `error()` from [api/_lib/http.js](../../api/_lib/http.js). Rate-limit with `limits.publicRead`.
+Use `sql` from [api/\_lib/db.js](../../api/_lib/db.js) to look up `agents` by id — return 404 if missing. Use `json()` / `error()` from [api/\_lib/http.js](../../api/_lib/http.js). Rate-limit with `limits.publicRead`.
### 4. Manifest serving endpoint
@@ -41,6 +41,7 @@ Create `api/lobehub/manifest.js` — GET-only, returns the contents of `public/l
### 5. Docs
Create `public/lobehub/README.md` covering:
+
- How to install the plugin into a LobeHub fork (the operator task).
- postMessage contract (types, payload shapes, origin rules).
- What the plugin does NOT do yet (any LobeHub features we skipped).
diff --git a/prompts/complete/05-reputation-dashboard.md b/prompts/complete/05-reputation-dashboard.md
index 68178ae1f..304b628ff 100644
--- a/prompts/complete/05-reputation-dashboard.md
+++ b/prompts/complete/05-reputation-dashboard.md
@@ -32,6 +32,7 @@ export class ReputationDashboard {
```
Use:
+
- `getReputation`, `getRecentReviews`, `submitFeedback` from [src/erc8004/reputation.js](../../src/erc8004/reputation.js).
- `connectWallet` from [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js).
- vhtml JSX for templates (file ends `.jsx` if you write JSX; or plain template strings if not).
diff --git a/prompts/complete/07-avatar-regenerate.md b/prompts/complete/07-avatar-regenerate.md
index 374778f69..f8fe8cbcf 100644
--- a/prompts/complete/07-avatar-regenerate.md
+++ b/prompts/complete/07-avatar-regenerate.md
@@ -12,18 +12,22 @@ When an ML provider is chosen later, wiring it in is one config change. Until th
Create `api/avatars/regenerate.js`:
-- `POST /api/avatars/regenerate` — auth required (via `getSessionUser` from [api/_lib/auth.js](../../api/_lib/auth.js)).
+- `POST /api/avatars/regenerate` — auth required (via `getSessionUser` from [api/\_lib/auth.js](../../api/_lib/auth.js)).
- Body: `{ sourceAvatarId: string, mode: 'remesh' | 'retex' | 'rerig' | 'restyle', params: object }`.
-- Look up source avatar via `sql\`SELECT * FROM avatars WHERE id = ${id} AND owner_user_id = ${user.id}\`` — 404 if not found or not owned.
+- Look up source avatar via `sql\`SELECT \* FROM avatars WHERE id = ${id} AND owner_user_id = ${user.id}\`` — 404 if not found or not owned.
- Check env `AVATAR_REGEN_PROVIDER` — if unset or `"none"`, return:
- ```json
- { "ok": false, "error": "regen-unconfigured", "message": "Avatar regeneration is not yet wired to an ML backend. Set AVATAR_REGEN_PROVIDER env var." }
- ```
- with HTTP 501.
+ ```json
+ {
+ "ok": false,
+ "error": "regen-unconfigured",
+ "message": "Avatar regeneration is not yet wired to an ML backend. Set AVATAR_REGEN_PROVIDER env var."
+ }
+ ```
+ with HTTP 501.
- If set to `"stub"`, return a deterministic fake job: `{ ok: true, jobId: 'stub-<uuid>', status: 'queued', eta: null }`.
- Document the future provider plug shape in a comment: what input the provider function receives, what output shape is expected (probably `{ glbUrl, textureUrls[], meta }`).
-Rate-limit via `limits.authedWrite` from [api/_lib/limits.js](../../api/_lib/limits.js) (or the closest equivalent). Use `json()` / `error()` from [api/_lib/http.js](../../api/_lib/http.js).
+Rate-limit via `limits.authedWrite` from [api/\_lib/limits.js](../../api/_lib/limits.js) (or the closest equivalent). Use `json()` / `error()` from [api/\_lib/http.js](../../api/_lib/http.js).
### 2. Status endpoint
@@ -48,6 +52,7 @@ Create `src/editor/regenerate-panel.js` — a UI panel that:
### 4. Docs
Create `api/avatars/REGENERATE.md` describing:
+
- The endpoint contract.
- Provider plug shape.
- Roadmap: what providers are candidates (Meshy, CSM, Rodin, TripoSR, etc.) — note that picking one is out of scope.
diff --git a/prompts/complete/08-register-prep-endpoint.md b/prompts/complete/08-register-prep-endpoint.md
index a1e7d2f97..e58f91fff 100644
--- a/prompts/complete/08-register-prep-endpoint.md
+++ b/prompts/complete/08-register-prep-endpoint.md
@@ -15,10 +15,10 @@ Create `api/agents/register-prep.js`:
- `POST /api/agents/register-prep` — **auth required** via `getSessionUser`.
- Body: `{ name, description, avatarId, brain?, skills?, embedPolicy?, demoSlug? }`.
- Validation:
- - `name`: 1–60 chars.
- - `description`: ≤ 280 chars.
- - `avatarId`: must belong to the authed user (`SELECT * FROM avatars WHERE id = ${avatarId} AND owner_user_id = ${user.id}`). 404 if not.
- - `skills`: array of strings, ≤ 16, each ≤ 40 chars, ascii + hyphen.
+ - `name`: 1–60 chars.
+ - `description`: ≤ 280 chars.
+ - `avatarId`: must belong to the authed user (`SELECT * FROM avatars WHERE id = ${avatarId} AND owner_user_id = ${user.id}`). 404 if not.
+ - `skills`: array of strings, ≤ 16, each ≤ 40 chars, ascii + hyphen.
- Build the registration JSON — canonical shape per [specs/AGENT_MANIFEST.md](../../specs/AGENT_MANIFEST.md). Must include `_baseURI` ending in `/` (hard rule per repo invariants).
- Pin to IPFS via helpers in [src/ipfs.js](../../src/ipfs.js). If ipfs helpers aren't import-safe from serverless, use direct HTTP against `api.web3.storage` — document which path taken.
- Store a prep record: `INSERT INTO agent_registrations_pending (user_id, cid, payload, created_at, expires_at)` with a 1-hour expiry. (If that table doesn't exist, create a migration SQL file at `scripts/sql/<ts>-create-agent-registrations-pending.sql` — don't auto-apply.)
@@ -33,7 +33,7 @@ Create `api/agents/register-confirm.js`:
- `POST /api/agents/register-confirm` with `{ prepId, chainId, agentId, txHash }`.
- Verifies the prep record exists, not expired, belongs to the authed user.
- Verifies the tx on-chain via a read-only RPC: fetch the tx receipt, parse the `AgentRegistered` event, check the event's `metadataURI` matches the prep record's `ipfs://<cid>`.
-- On success: upsert the `agents` row (or whatever the existing agents table shape requires — read [api/_lib/db.js](../../api/_lib/db.js) / the schema for authority) with `{ owner_user_id, chain_id, onchain_agent_id, metadata_cid, avatar_id }`.
+- On success: upsert the `agents` row (or whatever the existing agents table shape requires — read [api/\_lib/db.js](../../api/_lib/db.js) / the schema for authority) with `{ owner_user_id, chain_id, onchain_agent_id, metadata_cid, avatar_id }`.
- Returns `{ ok: true, agentId }`.
This closes the loop without ever needing a private key on the server.
diff --git a/prompts/complete/09-cz-landing-claim.md b/prompts/complete/09-cz-landing-claim.md
index f6678bb18..09cc367a7 100644
--- a/prompts/complete/09-cz-landing-claim.md
+++ b/prompts/complete/09-cz-landing-claim.md
@@ -24,12 +24,12 @@ Create `public/cz/state.json` with a stub shape:
```json
{
- "status": "pre-onchain",
- "chainId": null,
- "agentId": null,
- "metadataURI": null,
- "ownerAddress": null,
- "avatarUrl": "/avatars/cz.glb"
+ "status": "pre-onchain",
+ "chainId": null,
+ "agentId": null,
+ "metadataURI": null,
+ "ownerAddress": null,
+ "avatarUrl": "/avatars/cz.glb"
}
```
@@ -41,14 +41,16 @@ Create `src/cz-flow.js` — standalone ES module:
```js
export async function startClaim({ state, onProgress }) {
- // 1. connectWallet() via src/erc8004/agent-registry.js
- // 2. If state.status === 'pre-onchain' → show "Claim opens when CZ is registered" modal.
- // 3. If state.ownerAddress === '0x0' → call claim() on IdentityRegistry.
- // 4. If state.ownerAddress is a known demo EOA → guide user through transferOwner flow.
- // 5. Emit progress via onProgress({ step, status, txHash? })
+ // 1. connectWallet() via src/erc8004/agent-registry.js
+ // 2. If state.status === 'pre-onchain' → show "Claim opens when CZ is registered" modal.
+ // 3. If state.ownerAddress === '0x0' → call claim() on IdentityRegistry.
+ // 4. If state.ownerAddress is a known demo EOA → guide user through transferOwner flow.
+ // 5. Emit progress via onProgress({ step, status, txHash? })
}
-export function mountEmbedCopy(container, { state }) { /* CTA that copies an <agent-3d> snippet */ }
+export function mountEmbedCopy(container, { state }) {
+ /* CTA that copies an <agent-3d> snippet */
+}
```
Imports allowed: [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js), [src/erc8004/abi.js](../../src/erc8004/abi.js). Do **not** re-implement wallet connection.
@@ -67,6 +69,7 @@ When `state.chainId` / `state.agentId` are present, interpolate them in.
### 5. Analytics (no-op if unconfigured)
Fire `window.dispatchEvent(new CustomEvent('cz-demo-event', { detail: { event, props } }))` at key moments:
+
- `landing_view`
- `claim_start`
- `claim_wallet_connected`
diff --git a/prompts/complete/11-agents-directory.md b/prompts/complete/11-agents-directory.md
index 9c30849bb..d2e583966 100644
--- a/prompts/complete/11-agents-directory.md
+++ b/prompts/complete/11-agents-directory.md
@@ -2,7 +2,7 @@
## Why
-Bands 4 and 6 both benefit from a public index of every registered agent. Today there's no `/agents` list — you can only view an agent if you already know its id. The existing [public/explore/](../../public/explore/) is for 3D *models*, not agents.
+Bands 4 and 6 both benefit from a public index of every registered agent. Today there's no `/agents` list — you can only view an agent if you already know its id. The existing [public/explore/](../../public/explore/) is for 3D _models_, not agents.
A public directory makes the ecosystem feel alive, lets users discover agents, and is the natural surface to paginate on-chain registrations.
diff --git a/prompts/complete/MATRIX.md b/prompts/complete/MATRIX.md
index b55767b75..f05e9d44c 100644
--- a/prompts/complete/MATRIX.md
+++ b/prompts/complete/MATRIX.md
@@ -2,29 +2,29 @@
Each prompt lists its owned files. No two prompts may write to the same file. Shared reads are fine.
-| File / dir | Owner |
-|---|---|
-| `src/auth/walletconnect-bridge.js` | 01 |
-| `src/auth/walletconnect-bridge.test.html` | 01 |
-| `specs/EDITOR_SPEC.md` | 02 |
-| `api/artifact.js` | 03 |
-| `public/artifact/` | 03 |
-| `public/lobehub/` | 04 |
-| `api/lobehub/handshake.js` | 04 |
-| `api/lobehub/manifest.js` | 04 |
-| `public/reputation/` | 05 |
-| `src/reputation-ui.js` | 05 |
-| `public/validation/` | 06 |
-| `src/validation-ui.js` | 06 |
-| `api/avatars/regenerate.js` | 07 |
-| `src/editor/regenerate-panel.js` | 07 |
-| `api/agents/register-prep.js` | 08 |
-| `public/cz/` | 09 |
-| `src/cz-flow.js` | 09 |
-| `docs/CZ_DEMO_RUNBOOK.md` | 10 |
-| `scripts/cz-demo/runbook.sh` | 10 |
-| `public/agents/` | 11 |
-| `src/agents-directory.js` | 11 |
+| File / dir | Owner |
+| ----------------------------------------- | ----- |
+| `src/auth/walletconnect-bridge.js` | 01 |
+| `src/auth/walletconnect-bridge.test.html` | 01 |
+| `specs/EDITOR_SPEC.md` | 02 |
+| `api/artifact.js` | 03 |
+| `public/artifact/` | 03 |
+| `public/lobehub/` | 04 |
+| `api/lobehub/handshake.js` | 04 |
+| `api/lobehub/manifest.js` | 04 |
+| `public/reputation/` | 05 |
+| `src/reputation-ui.js` | 05 |
+| `public/validation/` | 06 |
+| `src/validation-ui.js` | 06 |
+| `api/avatars/regenerate.js` | 07 |
+| `src/editor/regenerate-panel.js` | 07 |
+| `api/agents/register-prep.js` | 08 |
+| `public/cz/` | 09 |
+| `src/cz-flow.js` | 09 |
+| `docs/CZ_DEMO_RUNBOOK.md` | 10 |
+| `scripts/cz-demo/runbook.sh` | 10 |
+| `public/agents/` | 11 |
+| `src/agents-directory.js` | 11 |
## Read-only (shared) modules — do not modify
diff --git a/prompts/complete/README.md b/prompts/complete/README.md
index 7a0d260fa..6d4dccff5 100644
--- a/prompts/complete/README.md
+++ b/prompts/complete/README.md
@@ -8,19 +8,19 @@ Each prompt only creates new files under a unique path, or edits exactly one fil
## Prompts
-| # | Title | Band | Primary output |
-|---|---|---|---|
-| 01 | [WalletConnect SIWE bridge](01-walletconnect-siwe.md) | 1 | `src/auth/walletconnect-bridge.js` |
-| 02 | [EDITOR_SPEC spec doc](02-editor-spec.md) | 3, 4 | `specs/EDITOR_SPEC.md` |
-| 03 | [Claude.ai artifact HTML](03-claude-artifact.md) | 5 | `api/artifact.js`, `public/artifact/` |
-| 04 | [LobeHub plugin manifest + handshake](04-lobehub-plugin.md) | 5 | `public/lobehub/`, `api/lobehub/*` |
-| 05 | [Reputation dashboard UI](05-reputation-dashboard.md) | 6 | `public/reputation/`, `src/reputation-ui.js` |
-| 06 | [Validation dashboard UI](06-validation-dashboard.md) | 6 | `public/validation/`, `src/validation-ui.js` |
-| 07 | [Avatar regenerate endpoint + UI](07-avatar-regenerate.md) | 3 | `api/avatars/regenerate.js`, `src/editor/regenerate-panel.js` |
-| 08 | [Server-side registration prep endpoint](08-register-prep-endpoint.md) | 6 | `api/agents/register-prep.js` |
-| 09 | [CZ landing + claim flow](09-cz-landing-claim.md) | cz-demo | `public/cz/`, `src/cz-flow.js` |
-| 10 | [CZ demo runbook](10-cz-runbook.md) | cz-demo | `docs/CZ_DEMO_RUNBOOK.md` |
-| 11 | [Public agents directory](11-agents-directory.md) | 4, 6 | `public/agents/`, `src/agents-directory.js` |
+| # | Title | Band | Primary output |
+| --- | ---------------------------------------------------------------------- | ------- | ------------------------------------------------------------- |
+| 01 | [WalletConnect SIWE bridge](01-walletconnect-siwe.md) | 1 | `src/auth/walletconnect-bridge.js` |
+| 02 | [EDITOR_SPEC spec doc](02-editor-spec.md) | 3, 4 | `specs/EDITOR_SPEC.md` |
+| 03 | [Claude.ai artifact HTML](03-claude-artifact.md) | 5 | `api/artifact.js`, `public/artifact/` |
+| 04 | [LobeHub plugin manifest + handshake](04-lobehub-plugin.md) | 5 | `public/lobehub/`, `api/lobehub/*` |
+| 05 | [Reputation dashboard UI](05-reputation-dashboard.md) | 6 | `public/reputation/`, `src/reputation-ui.js` |
+| 06 | [Validation dashboard UI](06-validation-dashboard.md) | 6 | `public/validation/`, `src/validation-ui.js` |
+| 07 | [Avatar regenerate endpoint + UI](07-avatar-regenerate.md) | 3 | `api/avatars/regenerate.js`, `src/editor/regenerate-panel.js` |
+| 08 | [Server-side registration prep endpoint](08-register-prep-endpoint.md) | 6 | `api/agents/register-prep.js` |
+| 09 | [CZ landing + claim flow](09-cz-landing-claim.md) | cz-demo | `public/cz/`, `src/cz-flow.js` |
+| 10 | [CZ demo runbook](10-cz-runbook.md) | cz-demo | `docs/CZ_DEMO_RUNBOOK.md` |
+| 11 | [Public agents directory](11-agents-directory.md) | 4, 6 | `public/agents/`, `src/agents-directory.js` |
## House rules
diff --git a/prompts/cz-demo/01-cz-landing-page.md b/prompts/cz-demo/01-cz-landing-page.md
index 4f902bd74..11c8df95b 100644
--- a/prompts/cz-demo/01-cz-landing-page.md
+++ b/prompts/cz-demo/01-cz-landing-page.md
@@ -19,24 +19,24 @@ Ship a `/cz` route with a curated layout, strong hero copy, and the CZ avatar re
## Deliverable
1. New file [public/cz.html](../../public/cz.html) — a standalone entry that reuses the shared build output. Two acceptable implementations; **pick one** and justify in the reporting section:
- - **(a) Route variant:** a top-level `cz.html` file Vite serves at `/cz.html`, with a redirect in [vercel.json](../../vercel.json) rewriting `/cz` → `/cz.html`.
- - **(b) Hash variant:** reuse `/` and gate on `window.location.hash === '#cz'`; preferred if `vercel.json` changes are risky.
+ - **(a) Route variant:** a top-level `cz.html` file Vite serves at `/cz.html`, with a redirect in [vercel.json](../../vercel.json) rewriting `/cz` → `/cz.html`.
+ - **(b) Hash variant:** reuse `/` and gate on `window.location.hash === '#cz'`; preferred if `vercel.json` changes are risky.
2. New module [src/features/cz-landing.js](../../src/features/cz-landing.js) exporting `mountCzLanding(containerEl, opts)` that:
- - Injects the hero layout: left column = agent stage; right column = title, subtitle, three CTAs.
- - Mounts a `Viewer` instance with the CZ GLB.
- - Uses **poster-first** rendering: shows a blurred thumbnail until the GLB's first frame paints, then fades the poster out (generate the poster PNG once via `scripts/cz-demo/gen-poster.js` — see `Deliverable 5`).
- - Wires up the first-interaction hook: `window.addEventListener('cz:viewer-ready', ...)` fires a `CustomEvent('cz:greet')` exactly once after viewer.load completes and 300ms settle — consumed by [03](./03-scripted-first-interaction.md).
- - If the on-chain hydrate from [onchain/01-hydrate-agent-from-chain.md](../onchain/01-hydrate-agent-from-chain.md) is available, hydrates name/description from `(chainId, agentId)` provided in `opts`. Falls back to hard-coded copy if not (the demo works without the onchain hydration being live).
+ - Injects the hero layout: left column = agent stage; right column = title, subtitle, three CTAs.
+ - Mounts a `Viewer` instance with the CZ GLB.
+ - Uses **poster-first** rendering: shows a blurred thumbnail until the GLB's first frame paints, then fades the poster out (generate the poster PNG once via `scripts/cz-demo/gen-poster.js` — see `Deliverable 5`).
+ - Wires up the first-interaction hook: `window.addEventListener('cz:viewer-ready', ...)` fires a `CustomEvent('cz:greet')` exactly once after viewer.load completes and 300ms settle — consumed by [03](./03-scripted-first-interaction.md).
+ - If the on-chain hydrate from [onchain/01-hydrate-agent-from-chain.md](../onchain/01-hydrate-agent-from-chain.md) is available, hydrates name/description from `(chainId, agentId)` provided in `opts`. Falls back to hard-coded copy if not (the demo works without the onchain hydration being live).
3. Hero copy (final, ship as-is; tweak if the reviewer asks):
- - Eyebrow: `A 3D agent with a passport`
- - H1: `This is CZ. Say hi.`
- - Subtitle: `A signed, embodied, portable agent you can embed anywhere — inside a Claude Artifact, a chat sidebar, or your own site.`
- - CTAs: `Chat with CZ` · `Embed this agent` · `Register your own`
+ - Eyebrow: `A 3D agent with a passport`
+ - H1: `This is CZ. Say hi.`
+ - Subtitle: `A signed, embodied, portable agent you can embed anywhere — inside a Claude Artifact, a chat sidebar, or your own site.`
+ - CTAs: `Chat with CZ` · `Embed this agent` · `Register your own`
4. Styling: keep the CZ route **dark-themed** (matches the app default `#191919`). Use a subtle radial gradient behind the stage (`radial-gradient(ellipse at center, rgba(80,120,255,0.18) 0%, transparent 60%)`). No new global CSS — scoped classes under `.cz-hero-*`. Inject via a `<style>` tag the module appends once.
5. New build-time script [scripts/cz-demo/gen-poster.js](../../scripts/cz-demo/gen-poster.js) — Node script that uses `puppeteer` or an existing headless renderer **only if already a dev-dep**; otherwise write a hand-authored 1200×800 PNG based on a screenshot you take manually and commit as [public/cz-poster.png](../../public/cz-poster.png). Prefer the manual commit path — simpler, zero new deps.
6. Route wiring:
- - In [src/app.js](../../src/app.js), detect the `/cz` route (or `#cz` hash) early in the boot sequence and delegate to `mountCzLanding` **instead of** the normal app. The generic viewer should not initialise for this route.
- - OG tags (title, description, `og:image = /cz-og.png`) — see [04-share-card-and-embed-presets.md](./04-share-card-and-embed-presets.md) for the OG image. For this task, just emit the `<meta>` tags referencing the filename even if the image isn't committed yet.
+ - In [src/app.js](../../src/app.js), detect the `/cz` route (or `#cz` hash) early in the boot sequence and delegate to `mountCzLanding` **instead of** the normal app. The generic viewer should not initialise for this route.
+ - OG tags (title, description, `og:image = /cz-og.png`) — see [04-share-card-and-embed-presets.md](./04-share-card-and-embed-presets.md) for the OG image. For this task, just emit the `<meta>` tags referencing the filename even if the image isn't committed yet.
## Audit checklist
@@ -64,10 +64,10 @@ Ship a `/cz` route with a curated layout, strong hero copy, and the CZ avatar re
1. `node --check src/features/cz-landing.js` and any other modified JS.
2. `npx vite build` passes.
3. `npx vite` then open `/cz` (or `/#cz` depending on variant):
- - Poster visible → GLB loads → poster fades.
- - Window title is `CZ — 3D Agent`.
- - DevTools Lighthouse on mobile: LCP under 2.5s.
- - `window.dispatchEvent(new Event('cz:greet'))` and nothing crashes (proper hook even before [03](./03-scripted-first-interaction.md) lands).
+ - Poster visible → GLB loads → poster fades.
+ - Window title is `CZ — 3D Agent`.
+ - DevTools Lighthouse on mobile: LCP under 2.5s.
+ - `window.dispatchEvent(new Event('cz:greet'))` and nothing crashes (proper hook even before [03](./03-scripted-first-interaction.md) lands).
4. Test with `#cz&raw=1`: landing UI gone; bare viewer behind.
5. Test `/` still works. Test `/#agent=...` still works.
diff --git a/prompts/cz-demo/01-preregister-cz-onchain.md b/prompts/cz-demo/01-preregister-cz-onchain.md
index 0f99b8989..32930455c 100644
--- a/prompts/cz-demo/01-preregister-cz-onchain.md
+++ b/prompts/cz-demo/01-preregister-cz-onchain.md
@@ -20,18 +20,18 @@ Create `scripts/cz-demo/registration-cz.json` (committed, not generated). Shape:
```json
{
- "type": "agent-registration/0.1",
- "name": "CZ",
- "description": "Test agent for the CZ demo — the canonical embodied agent for demonstrating portable onchain identity.",
- "body": {
- "uri": "https://3d.irish/avatars/cz.glb",
- "format": "glb"
- },
- "brain": { "provider": "anthropic", "model": "claude-opus-4-6" },
- "skills": ["greet", "present-model", "validate-model", "remember", "think", "sign-action"],
- "owner": "0x0000000000000000000000000000000000000000",
- "createdAt": "2026-04-15T00:00:00Z",
- "demo": { "slug": "cz" }
+ "type": "agent-registration/0.1",
+ "name": "CZ",
+ "description": "Test agent for the CZ demo — the canonical embodied agent for demonstrating portable onchain identity.",
+ "body": {
+ "uri": "https://3d.irish/avatars/cz.glb",
+ "format": "glb"
+ },
+ "brain": { "provider": "anthropic", "model": "claude-opus-4-6" },
+ "skills": ["greet", "present-model", "validate-model", "remember", "think", "sign-action"],
+ "owner": "0x0000000000000000000000000000000000000000",
+ "createdAt": "2026-04-15T00:00:00Z",
+ "demo": { "slug": "cz" }
}
```
diff --git a/prompts/cz-demo/02-cz-landing-page.md b/prompts/cz-demo/02-cz-landing-page.md
index f22125799..33bc7b2ea 100644
--- a/prompts/cz-demo/02-cz-landing-page.md
+++ b/prompts/cz-demo/02-cz-landing-page.md
@@ -27,10 +27,10 @@ Route: `/cz` → `public/cz/index.html`. Add to [vercel.json](../../vercel.json)
- Full-viewport black background.
- Centered 3D stage — 70vh tall, the CZ avatar center-stage, auto-rotating slowly (0.2 rad/sec).
- Below the stage:
- - `<h1>` "CZ" + tagline "An embodied agent. Signed onchain."
- - Address chip showing the current onchain `owner` (shortened: `0x1234…abcd`).
- - Metadata pills: `chain: base-sepolia · agent #123 · CID Qm…`.
- - One primary button: **Claim your agent →**.
+ - `<h1>` "CZ" + tagline "An embodied agent. Signed onchain."
+ - Address chip showing the current onchain `owner` (shortened: `0x1234…abcd`).
+ - Metadata pills: `chain: base-sepolia · agent #123 · CID Qm…`.
+ - One primary button: **Claim your agent →**.
- Below the fold: three short paragraphs explaining what's happening technically (onchain identity, portable embed, Empathy Layer).
### 3. Rendering
@@ -39,9 +39,9 @@ Use the same `Viewer` + agent stack as `/agent/:id`. Import from `dist-lib/agent
```html
<agent-3d
- agent-id-chain="base-sepolia:123"
- eager
- style="width:100%;height:70vh;background:transparent"
+ agent-id-chain="base-sepolia:123"
+ eager
+ style="width:100%;height:70vh;background:transparent"
></agent-3d>
```
@@ -54,6 +54,7 @@ Hooked to the flow defined in [03-claim-transfer-flow.md](./03-claim-transfer-fl
### 5. Post-claim state
When `localStorage['cz:claimed'] === 'true'`:
+
- Replace "Claim your agent →" with `Open in LobeHub →` + `Open in Claude →` buttons.
- Hide the address chip's old owner, show the new owner address.
- Show a small green dot + "claimed" label next to the agent id.
diff --git a/prompts/cz-demo/03-claim-transfer-flow.md b/prompts/cz-demo/03-claim-transfer-flow.md
index bf898fe90..1892f34a3 100644
--- a/prompts/cz-demo/03-claim-transfer-flow.md
+++ b/prompts/cz-demo/03-claim-transfer-flow.md
@@ -23,11 +23,11 @@ User calls the claim function directly. CZ's wallet pays gas.
1. Read `agentId`, `chainId`, contract address from a new small endpoint `GET /api/cz/identity` that reads from `agent_identities` by `meta.demo = 'cz'` (use the row from task 01 step 4).
2. `window.claimAgent()` on the `/cz` page:
- - Require `window.ethereum`. Prompt `eth_requestAccounts`.
- - Prompt chain switch to `chainId` via `wallet_switchEthereumChain`. If unknown chain, use `wallet_addEthereumChain` with the Base Sepolia params.
- - Call `IdentityRegistry.claim(agentId)` via `viem`.
- - Wait for receipt, parse `OwnerSet` event, confirm `newOwner === caller`.
- - `localStorage.setItem('cz:claimed', 'true')`; reload.
+ - Require `window.ethereum`. Prompt `eth_requestAccounts`.
+ - Prompt chain switch to `chainId` via `wallet_switchEthereumChain`. If unknown chain, use `wallet_addEthereumChain` with the Base Sepolia params.
+ - Call `IdentityRegistry.claim(agentId)` via `viem`.
+ - Wait for receipt, parse `OwnerSet` event, confirm `newOwner === caller`.
+ - `localStorage.setItem('cz:claimed', 'true')`; reload.
### Pattern B — "Pre-authorized transfer" (if only `transferOwner(uint256, address)` exists, requires current owner signature)
@@ -52,8 +52,8 @@ On successful claim, add a small canvas-confetti burst + change the agent's Empa
```js
window.VIEWER.agent_protocol.emit('skill-done', {
- skill: 'claim-onchain',
- result: { success: true, output: 'Claimed', sentiment: 0.9 }
+ skill: 'claim-onchain',
+ result: { success: true, output: 'Claimed', sentiment: 0.9 },
});
```
diff --git a/prompts/cz-demo/04-lobehub-embed-drop-in.md b/prompts/cz-demo/04-lobehub-embed-drop-in.md
index 50e33bd6e..7c676114c 100644
--- a/prompts/cz-demo/04-lobehub-embed-drop-in.md
+++ b/prompts/cz-demo/04-lobehub-embed-drop-in.md
@@ -7,8 +7,8 @@ The "embodied, not JSON" moment of the demo. CZ opens your LobeHub fork and sees
## Shared context
- You maintain a LobeHub fork. That repo is **separate** from this one. This task produces:
- 1. Instructions + a patch/diff for the LobeHub side.
- 2. The iframe embed source + postMessage protocol on the 3D side.
+ 1. Instructions + a patch/diff for the LobeHub side.
+ 2. The iframe embed source + postMessage protocol on the 3D side.
- 3D side embed URL: `/agent/chain/:chainId/:agentId/embed` (or `/embed?chain=...&agent=...` — reuse whichever lands from [../lobehub-embed/04-embed-from-chain.md](../lobehub-embed/04-embed-from-chain.md)).
- 3D side embed page: [public/agent/embed.html](../../public/agent/embed.html) already supports a `postMessage` bridge. Extend it with a defined protocol (see [../lobehub-embed/02-postmessage-protocol.md](../lobehub-embed/02-postmessage-protocol.md)).
@@ -17,6 +17,7 @@ The "embodied, not JSON" moment of the demo. CZ opens your LobeHub fork and sees
### 1. Define the parent ↔ embed postMessage protocol (confirm or extend)
Messages the **host → embed**:
+
```
{ type: 'agent/user-message', text: string, role: 'user'|'assistant' }
{ type: 'agent/set-theme', theme: 'light'|'dark' }
@@ -24,6 +25,7 @@ Messages the **host → embed**:
```
Messages the **embed → host**:
+
```
{ type: 'agent/ready' }
{ type: 'agent/speak', text: string, sentiment: number }
@@ -51,6 +53,7 @@ The patch file is for **operator application** — they'll apply it in the LobeH
If a full LobeHub patch is too invasive for the demo timeline, provide `public/cz/lobehub-embed-demo.html` — a static page that **looks** like LobeHub's chat and iframes the agent embed. Useful for rehearsal and as a backup if the fork patch isn't ready.
Simple two-column layout:
+
- Left 60%: fake chat with three preset CZ messages. Typing simulated in JS.
- Right 40%: iframe of the agent embed. Reacts to each message via postMessage.
diff --git a/prompts/cz-demo/05-demo-script-and-fallbacks.md b/prompts/cz-demo/05-demo-script-and-fallbacks.md
index 0311ec00f..0aaff1d68 100644
--- a/prompts/cz-demo/05-demo-script-and-fallbacks.md
+++ b/prompts/cz-demo/05-demo-script-and-fallbacks.md
@@ -11,6 +11,7 @@ The CZ demo is a live event. Everything can fail — RPC flaps, the venue wifi,
Sections:
**Pre-flight checklist (T-24h)**
+
- [ ] `scripts/cz-demo/register-onchain.mjs` has been run; `agentId` in `.state.json`.
- [ ] Basescan confirms `AgentRegistered` event exists for that agentId.
- [ ] `/cz` loads on the staging URL; avatar renders; camera orbits.
@@ -23,6 +24,7 @@ Sections:
- [ ] `window.VIEWER.agent_protocol.history` shows clean boot (no errors) on `/cz`.
**Pre-flight checklist (T-1h)**
+
- [ ] Fresh browser profile, MetaMask imported from CZ's seed (or hardware wallet plugged in).
- [ ] DNS cached for the demo origin (`nslookup` twice).
- [ ] Phone on hotspot ready if venue wifi dies.
@@ -41,17 +43,18 @@ Sections:
**Failure modes + response**
-| Symptom | Likely cause | Response |
-|---|---|---|
-| Avatar never renders | GLB 404 or CORS | Fallback 1 |
-| Claim tx pending > 45s | RPC congestion | Continue talking; fallback 2 if > 2 min |
-| MetaMask doesn't pop | Popup blocker | Click wallet icon directly |
-| LobeHub iframe blank | `postMessage` origin mismatch | Fallback 3 |
-| IPFS gateway fetch slow | ipfs.io rate limit | Switch to `dweb.link` via URL fragment |
+| Symptom | Likely cause | Response |
+| ----------------------- | ----------------------------- | --------------------------------------- |
+| Avatar never renders | GLB 404 or CORS | Fallback 1 |
+| Claim tx pending > 45s | RPC congestion | Continue talking; fallback 2 if > 2 min |
+| MetaMask doesn't pop | Popup blocker | Click wallet icon directly |
+| LobeHub iframe blank | `postMessage` origin mismatch | Fallback 3 |
+| IPFS gateway fetch slow | ipfs.io rate limit | Switch to `dweb.link` via URL fragment |
### 2. Fallback 1 — "demo mode" static build
Create `public/cz/demo.html` — a **self-contained** page with zero network calls after initial load:
+
- GLB bundled as a blob URL (read at build-time from `public/avatars/cz.glb`).
- No `/api/agents/me`, no `/api/cz/identity` — all identity data baked into the HTML.
- Fake claim flow: clicking "Claim" plays the confetti + flips the UI after a 1.5s delay; no MetaMask call.
@@ -66,6 +69,7 @@ Have a sacrificial pre-mined claim transaction ready — the agent is pre-claime
### 4. Fallback 3 — service-worker warm cache
`public/cz/sw.js` — pre-caches:
+
- `/avatars/cz.glb`
- `/animations/*.glb`
- `/dist-lib/agent-3d.js`
@@ -76,6 +80,7 @@ Register on `/cz` page load. Serve from cache when offline. Document that 5s of
### 5. Operator one-liner
`scripts/cz-demo/preflight.sh`:
+
```bash
#!/usr/bin/env bash
set -e
@@ -88,7 +93,7 @@ echo "Preflight complete"
## Files you own
- Create: `docs/cz-demo-runbook.md`, `public/cz/demo.html`, `public/cz/sw.js`, `scripts/cz-demo/preflight.sh`
-- Edit: `public/cz/claim.js` (rehearsal-mode branch — *only* this branch; do not restructure), `public/cz/index.html` (one `<script>` line to register the SW)
+- Edit: `public/cz/claim.js` (rehearsal-mode branch — _only_ this branch; do not restructure), `public/cz/index.html` (one `<script>` line to register the SW)
## Files off-limits
diff --git a/prompts/cz-demo/README.md b/prompts/cz-demo/README.md
index a533560cf..bf287eaef 100644
--- a/prompts/cz-demo/README.md
+++ b/prompts/cz-demo/README.md
@@ -16,13 +16,13 @@ CZ opens a link. He sees a 3D CZ avatar standing in a scene — pre-registered o
## Execution order
-| # | File | Ships |
-|---|---|---|
-| 01 | [01-preregister-cz-onchain.md](./01-preregister-cz-onchain.md) | Script + one-time action that mints the CZ agent onchain on Base Sepolia with known `agentId`, metadata on IPFS, `cz.glb` in the registration JSON. |
-| 02 | [02-cz-landing-page.md](./02-cz-landing-page.md) | Bespoke `/cz` route — dark theme, spotlit CZ avatar, owner chip, one "Claim your agent" CTA, post-claim state. |
-| 03 | [03-claim-transfer-flow.md](./03-claim-transfer-flow.md) | Onchain ownership flip from ops-owner (or `0x0`) to CZ's wallet via one user-signed tx. |
-| 04 | [04-lobehub-embed-drop-in.md](./04-lobehub-embed-drop-in.md) | LobeHub-fork patch + fallback HTML that puts the agent embed inside the chat sidebar, hydrated from chain. |
-| 05 | [05-demo-script-and-fallbacks.md](./05-demo-script-and-fallbacks.md) | Live-demo runbook, preflight script, kill-switch (`?rehearsal=1`), service-worker warm cache, offline demo mode. |
+| # | File | Ships |
+| --- | -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
+| 01 | [01-preregister-cz-onchain.md](./01-preregister-cz-onchain.md) | Script + one-time action that mints the CZ agent onchain on Base Sepolia with known `agentId`, metadata on IPFS, `cz.glb` in the registration JSON. |
+| 02 | [02-cz-landing-page.md](./02-cz-landing-page.md) | Bespoke `/cz` route — dark theme, spotlit CZ avatar, owner chip, one "Claim your agent" CTA, post-claim state. |
+| 03 | [03-claim-transfer-flow.md](./03-claim-transfer-flow.md) | Onchain ownership flip from ops-owner (or `0x0`) to CZ's wallet via one user-signed tx. |
+| 04 | [04-lobehub-embed-drop-in.md](./04-lobehub-embed-drop-in.md) | LobeHub-fork patch + fallback HTML that puts the agent embed inside the chat sidebar, hydrated from chain. |
+| 05 | [05-demo-script-and-fallbacks.md](./05-demo-script-and-fallbacks.md) | Live-demo runbook, preflight script, kill-switch (`?rehearsal=1`), service-worker warm cache, offline demo mode. |
01 is the dependency root. 02 + 04 can run in parallel after 01. 03 depends on 01 + the wallet-auth / onchain tasks. 05 is written last, once the flow is green end-to-end.
diff --git a/prompts/drop-edit-embed/00-README.md b/prompts/drop-edit-embed/00-README.md
index cb6a394c6..0c3e1dff4 100644
--- a/prompts/drop-edit-embed/00-README.md
+++ b/prompts/drop-edit-embed/00-README.md
@@ -48,16 +48,16 @@ The gap is the **hand-off** — today a user who drops+edits a GLB in the viewer
Run 01 → 02 → 03 → 04 first; those ship the happy path. 05 → 06 harden it. 07 → 08 verify.
-| Prompt | Ships | Can parallel with |
-|---|---|---|
-| [01-editor-on-dropped-glb.md](./01-editor-on-dropped-glb.md) | Editor reliably attaches for drag-drop + `#model=` loads | — |
-| [02-publish-client.md](./02-publish-client.md) | `src/editor/publish.js` — one function that uploads + mints widget | 01 |
-| [03-publish-button-and-modal.md](./03-publish-button-and-modal.md) | "📤 Publish as embed" button in editor + share modal with 3 snippets | depends on 02 |
-| [04-publish-auth-gate.md](./04-publish-auth-gate.md) | Signed-out users get sent to `/login?next=...` with their edits preserved | depends on 03 |
-| [05-republish-existing.md](./05-republish-existing.md) | Loaded-from-a-widget re-edit → Update vs Create new | depends on 03 |
-| [06-size-and-cors-guards.md](./06-size-and-cors-guards.md) | Block >25 MB, catch CORS-blocked remote GLBs with a useful error | depends on 02 |
-| [07-widget-metadata.md](./07-widget-metadata.md) | Verify + polish OG card + oEmbed for `/w/<id>` | parallel with 01–06 |
-| [08-smoke-test.md](./08-smoke-test.md) | E2E manual checklist — drop, edit, publish, paste in each surface | last |
+| Prompt | Ships | Can parallel with |
+| ------------------------------------------------------------------ | ------------------------------------------------------------------------- | ------------------- |
+| [01-editor-on-dropped-glb.md](./01-editor-on-dropped-glb.md) | Editor reliably attaches for drag-drop + `#model=` loads | — |
+| [02-publish-client.md](./02-publish-client.md) | `src/editor/publish.js` — one function that uploads + mints widget | 01 |
+| [03-publish-button-and-modal.md](./03-publish-button-and-modal.md) | "📤 Publish as embed" button in editor + share modal with 3 snippets | depends on 02 |
+| [04-publish-auth-gate.md](./04-publish-auth-gate.md) | Signed-out users get sent to `/login?next=...` with their edits preserved | depends on 03 |
+| [05-republish-existing.md](./05-republish-existing.md) | Loaded-from-a-widget re-edit → Update vs Create new | depends on 03 |
+| [06-size-and-cors-guards.md](./06-size-and-cors-guards.md) | Block >25 MB, catch CORS-blocked remote GLBs with a useful error | depends on 02 |
+| [07-widget-metadata.md](./07-widget-metadata.md) | Verify + polish OG card + oEmbed for `/w/<id>` | parallel with 01–06 |
+| [08-smoke-test.md](./08-smoke-test.md) | E2E manual checklist — drop, edit, publish, paste in each surface | last |
## House rules for every prompt (inherits from `/CLAUDE.md`)
diff --git a/prompts/drop-edit-embed/01-editor-on-dropped-glb.md b/prompts/drop-edit-embed/01-editor-on-dropped-glb.md
index ef81967b4..c4320de59 100644
--- a/prompts/drop-edit-embed/01-editor-on-dropped-glb.md
+++ b/prompts/drop-edit-embed/01-editor-on-dropped-glb.md
@@ -13,7 +13,7 @@ The `Editor` class in [src/editor/index.js](../../src/editor/index.js) already e
## Shared context
- [src/app.js](../../src/app.js) is the main SPA entry. It constructs the `Viewer` and handles the dropzone + URL hash.
- - Search for where `new Viewer(...)` is called and where model loads happen (`view()`, `load()`).
+ - Search for where `new Viewer(...)` is called and where model loads happen (`view()`, `load()`).
- The `Editor` import is `import { Editor } from './editor/index.js';` (already imported on app.js line ~4).
- `EditorSession.reset({ url, file, name })` in [src/editor/session.js](../../src/editor/session.js) is what the editor uses to track the source for export. If `onContentChanged` isn't called, `session.getSourceBuffer()` will return null and GLB export fails silently later.
- The editor renders into `viewer.gui` (dat.gui). If the viewer is in kiosk mode (no gui), the editor currently degrades gracefully (see `_addExportFolder()` early-return). Leave that as-is.
diff --git a/prompts/drop-edit-embed/02-publish-client.md b/prompts/drop-edit-embed/02-publish-client.md
index 6c5aa0096..ba2dd8d20 100644
--- a/prompts/drop-edit-embed/02-publish-client.md
+++ b/prompts/drop-edit-embed/02-publish-client.md
@@ -7,9 +7,9 @@ Task 03 adds a "📤 Publish as embed" button. That button needs a single async
## Shared context
- The three endpoints you'll call — **read them before you wire** — are:
- - `POST /api/avatars/presign` → [api/avatars/presign.js](../../api/avatars/presign.js). Returns `{ storage_key, upload_url, method: 'PUT', headers: { 'content-type' }, expires_in }`.
- - `POST /api/avatars` → [api/avatars/index.js](../../api/avatars/index.js). Registers an avatar given `{ name, slug, storage_key, content_type, size_bytes, ... }`. Verifies R2 object exists via `headObject()`. Returns `{ avatar: { id, slug, url, ... } }`.
- - `POST /api/widgets` → [api/widgets/index.js](../../api/widgets/index.js). Shape: `{ type: 'turntable', name, avatar_id, config, is_public }`. Returns `{ widget: { id, url, ... } }`.
+ - `POST /api/avatars/presign` → [api/avatars/presign.js](../../api/avatars/presign.js). Returns `{ storage_key, upload_url, method: 'PUT', headers: { 'content-type' }, expires_in }`.
+ - `POST /api/avatars` → [api/avatars/index.js](../../api/avatars/index.js). Registers an avatar given `{ name, slug, storage_key, content_type, size_bytes, ... }`. Verifies R2 object exists via `headObject()`. Returns `{ avatar: { id, slug, url, ... } }`.
+ - `POST /api/widgets` → [api/widgets/index.js](../../api/widgets/index.js). Shape: `{ type: 'turntable', name, avatar_id, config, is_public }`. Returns `{ widget: { id, url, ... } }`.
- Edit-to-bytes is already done: [src/editor/glb-export.js](../../src/editor/glb-export.js) exports `exportEditedGLB(session) → Uint8Array`.
- The `EditorSession` exposes `sourceName` (the original filename or URL tail) — use that as the default avatar name, sanitized.
- Auth is cookie-based for the browser flow (`credentials: 'include'`). The helper does **not** handle login — it throws a typed `AuthRequiredError` and lets the caller redirect. Task 04 wires the redirect.
@@ -70,11 +70,11 @@ export const MAX_BYTES = 25 * 1024 * 1024;
- On 401 from any step → throw `AuthRequiredError`. Do not retry.
- On 413 from `/api/avatars` → throw `SizeTooLargeError(bytes, MAX_BYTES)`.
- `onStep` emits:
- - `{ step: 'export', pct: 0 }` then `{ step: 'export', pct: 1 }`
- - `{ step: 'presign', pct: 1 }`
- - `{ step: 'upload', pct: 0..1 }` — use `XMLHttpRequest` for real upload progress; `fetch` doesn't give you upload progress in browsers. If you'd rather keep `fetch`, emit `0` at start and `1` on completion — that's acceptable for this task.
- - `{ step: 'register', pct: 1 }`
- - `{ step: 'widget', pct: 1 }`
+ - `{ step: 'export', pct: 0 }` then `{ step: 'export', pct: 1 }`
+ - `{ step: 'presign', pct: 1 }`
+ - `{ step: 'upload', pct: 0..1 }` — use `XMLHttpRequest` for real upload progress; `fetch` doesn't give you upload progress in browsers. If you'd rather keep `fetch`, emit `0` at start and `1` on completion — that's acceptable for this task.
+ - `{ step: 'register', pct: 1 }`
+ - `{ step: 'widget', pct: 1 }`
- Widget `config`: the defaults for `turntable` are in [public/studio/studio.js](../../public/studio/studio.js) (`TYPE_DEFAULTS.turntable` = `{ rotationSpeed: 0.5 }`). Include `{ rotationSpeed: 0.5, autoRotate: true, showControls: true, background: '#0a0a0a', accent: '#8b5cf6' }` as the baseline; shallow-merge caller-supplied `config` on top.
### Do NOT
@@ -100,13 +100,13 @@ export const MAX_BYTES = 25 * 1024 * 1024;
- `node --check src/editor/publish.js` passes.
- `npm run verify` passes.
- Manual smoke in DevTools console after loading any model:
- ```js
- const { publishEditedGLB } = await import('/src/editor/publish.js');
- const session = window.VIEWER.editor.session;
- const result = await publishEditedGLB(session, { onStep: (s) => console.log(s) });
- console.log(result.urls);
- ```
- Expected: progress events, resolves with a `{ widget, avatar, urls }` object where `urls.page` is a working `/w/<id>` URL. (You must be signed in; if not, expect `AuthRequiredError` — that's correct.)
+ ```js
+ const { publishEditedGLB } = await import('/src/editor/publish.js');
+ const session = window.VIEWER.editor.session;
+ const result = await publishEditedGLB(session, { onStep: (s) => console.log(s) });
+ console.log(result.urls);
+ ```
+ Expected: progress events, resolves with a `{ widget, avatar, urls }` object where `urls.page` is a working `/w/<id>` URL. (You must be signed in; if not, expect `AuthRequiredError` — that's correct.)
## Reporting
diff --git a/prompts/drop-edit-embed/03-publish-button-and-modal.md b/prompts/drop-edit-embed/03-publish-button-and-modal.md
index 7c16e8504..c7112bbba 100644
--- a/prompts/drop-edit-embed/03-publish-button-and-modal.md
+++ b/prompts/drop-edit-embed/03-publish-button-and-modal.md
@@ -18,9 +18,7 @@ Tasks 01–02 built the plumbing. This one ships the user-visible piece: a butto
In [src/editor/index.js](../../src/editor/index.js) `_addExportFolder()`, after the `💾 download GLB` row, add:
```js
-folder
- .add({ publish: () => this._openPublishModal() }, 'publish')
- .name('📤 publish as embed');
+folder.add({ publish: () => this._openPublishModal() }, 'publish').name('📤 publish as embed');
```
Store a reference (`this._publishCtrl = …`) so you can disable it while a publish is in-flight.
diff --git a/prompts/drop-edit-embed/04-publish-auth-gate.md b/prompts/drop-edit-embed/04-publish-auth-gate.md
index 4d5c38c3f..9034014e2 100644
--- a/prompts/drop-edit-embed/04-publish-auth-gate.md
+++ b/prompts/drop-edit-embed/04-publish-auth-gate.md
@@ -7,10 +7,10 @@ After task 03, signed-out users who click Publish see a "Sign in" modal. If they
## Shared context
- Login page is [public/login.html](../../public/login.html). It reads `?next=<url>` and redirects to it on success. Verify by reading the file — do not assume.
-- Session cookie is set by `/api/auth/login` ([api/auth/login.js](../../api/auth/login.js)) via `createSession` / `sessionCookie` from [api/_lib/auth.js](../../api/_lib/auth.js). The browser will have a valid cookie after login completes.
+- Session cookie is set by `/api/auth/login` ([api/auth/login.js](../../api/auth/login.js)) via `createSession` / `sessionCookie` from [api/\_lib/auth.js](../../api/_lib/auth.js). The browser will have a valid cookie after login completes.
- The Editor session state that needs to survive the round-trip:
- - The loaded source (URL or the dropped file bytes)
- - `session.materialEdits`, `session.transformEdits`, `session.visibilityEdits` from [src/editor/session.js](../../src/editor/session.js)
+ - The loaded source (URL or the dropped file bytes)
+ - `session.materialEdits`, `session.transformEdits`, `session.visibilityEdits` from [src/editor/session.js](../../src/editor/session.js)
- File bytes can't go in the URL. Dropped files are the hard case — browsers won't let us re-drop a file after navigation. We store dropped bytes in `IndexedDB` keyed by a short random id; URL-loaded models are re-fetched by URL after login.
- Edits are small JSON — they can round-trip in `sessionStorage`.
@@ -73,8 +73,9 @@ const resumeToken = new URLSearchParams(location.search).get('resume');
if (resumeToken) {
const stashed = await restoreSession(resumeToken);
if (stashed) {
- if (stashed.source.url) await this.view(stashed.source.url, '', new Map());
- else if (stashed.source.file) await this.load(new Map([[stashed.source.file.name, stashed.source.file]]));
+ if (stashed.source.url) await this.view(stashed.source.url, '', new Map());
+ else if (stashed.source.file)
+ await this.load(new Map([[stashed.source.file.name, stashed.source.file]]));
// Replay edits into the new session.
this.editor.session.restoreEdits(stashed.edits);
// Auto-open Publish if &publish=1.
diff --git a/prompts/drop-edit-embed/05-republish-existing.md b/prompts/drop-edit-embed/05-republish-existing.md
index 90d2be41e..03ed1c064 100644
--- a/prompts/drop-edit-embed/05-republish-existing.md
+++ b/prompts/drop-edit-embed/05-republish-existing.md
@@ -8,14 +8,14 @@ Once a user has published their first widget, they'll reload it (e.g. via `#widg
- The viewer already accepts `#widget=wdgt_abc123` as a hash param (per README and [src/app.js](../../src/app.js) — verify the exact key and the fetch path it uses).
- A loaded widget gives us:
- - `widget.id`
- - `widget.avatar_id`
- - `widget.name`
- - `widget.config`
+ - `widget.id`
+ - `widget.avatar_id`
+ - `widget.name`
+ - `widget.config`
- `PATCH /api/widgets/:id` exists in [api/widgets/\[id\].js](../../api/widgets/[id].js). Verify its accepted body shape — expect `{ name?, config?, is_public?, avatar_id? }`. Do not assume; read the file.
- **Avatar swap vs edit-in-place:** the edited GLB is always a new avatar (different bytes, different `storage_key`). Re-publish = upload new avatar, then either:
- - (A) Update the widget to point at the new `avatar_id`, or
- - (B) Mint a fresh widget.
+ - (A) Update the widget to point at the new `avatar_id`, or
+ - (B) Mint a fresh widget.
- Option A preserves the `/w/<id>` URL — critical for links already pasted elsewhere.
## What to build
@@ -48,10 +48,10 @@ If no widget context, skip this step and run the existing flow directly (task 03
`Go` calls either:
- **Update:** a new `updateWidget()` function in [src/editor/publish.js](../../src/editor/publish.js) (task 02). Steps:
- 1. `exportEditedGLB(session)` → bytes
- 2. Upload → register new avatar (same as first-publish)
- 3. `PATCH /api/widgets/:id` with `{ avatar_id: newAvatar.id }`
- 4. Resolves `{ widget: updated, avatar: new, urls }` — same shape as `publishEditedGLB`.
+ 1. `exportEditedGLB(session)` → bytes
+ 2. Upload → register new avatar (same as first-publish)
+ 3. `PATCH /api/widgets/:id` with `{ avatar_id: newAvatar.id }`
+ 4. Resolves `{ widget: updated, avatar: new, urls }` — same shape as `publishEditedGLB`.
- **Create new:** the existing `publishEditedGLB(session, …)` — unchanged.
Result modal shows:
diff --git a/prompts/drop-edit-embed/06-size-and-cors-guards.md b/prompts/drop-edit-embed/06-size-and-cors-guards.md
index 46e03bb5f..2548f2677 100644
--- a/prompts/drop-edit-embed/06-size-and-cors-guards.md
+++ b/prompts/drop-edit-embed/06-size-and-cors-guards.md
@@ -5,16 +5,16 @@
Task 02 added a single 25 MB size check. That's the easy half. The harder failure modes live in two spots:
1. **Server-side size policy** — plan quotas exist in the `plan_quotas` table. A free user may be under a stricter cap than 25 MB per avatar. Today the editor client doesn't know; it hits `/api/avatars/presign` and gets a cryptic 413.
-2. **Remote GLBs loaded via `#model=<url>`** — the editor *can* display them (the viewer fetches them), but the editor's `EditorSession.getSourceBuffer()` may or may not have kept the original bytes, and re-fetching cross-origin often fails at CORS. Exporting then fails silently or with a confusing error.
+2. **Remote GLBs loaded via `#model=<url>`** — the editor _can_ display them (the viewer fetches them), but the editor's `EditorSession.getSourceBuffer()` may or may not have kept the original bytes, and re-fetching cross-origin often fails at CORS. Exporting then fails silently or with a confusing error.
We surface both failures with useful error copy, blocks them before users upload, and gives one clear remediation for each.
## Shared context
-- Plan quotas live in the `plan_quotas` table ([api/_lib/schema.sql](../../api/_lib/schema.sql)) and are read by endpoints that need them — search for `plan_quotas` to see where.
+- Plan quotas live in the `plan_quotas` table ([api/\_lib/schema.sql](../../api/_lib/schema.sql)) and are read by endpoints that need them — search for `plan_quotas` to see where.
- [api/avatars/index.js](../../api/avatars/index.js) returns 413 with `error: 'payload_too_large'` and an `error_description` if size exceeds the user's plan.
- `EditorSession` in [src/editor/session.js](../../src/editor/session.js) exposes `getSourceBuffer()`. Check whether it caches the bytes on load or re-fetches on demand; if it re-fetches, CORS will bite on cross-origin URLs loaded via `#model=`.
-- The viewer's load path goes through `GLTFLoader` which internally manages fetching. We need to capture the bytes *at load time* regardless of how the viewer fetched them, then hand them to the editor session.
+- The viewer's load path goes through `GLTFLoader` which internally manages fetching. We need to capture the bytes _at load time_ regardless of how the viewer fetched them, then hand them to the editor session.
## What to build
@@ -24,10 +24,10 @@ Create [api/me/limits.js](../../api/me/limits.js). Returns the caller's avatar s
```json
{
- "max_avatars": 20,
- "max_bytes_per_avatar": 26214400,
- "max_total_bytes": 524288000,
- "current_total_bytes": 48271934
+ "max_avatars": 20,
+ "max_bytes_per_avatar": 26214400,
+ "max_total_bytes": 524288000,
+ "current_total_bytes": 48271934
}
```
@@ -59,9 +59,9 @@ Edit [src/editor/session.js](../../src/editor/session.js) `reset({ url, file, na
- If `file` is a `File` or `Blob` → read it once with `await file.arrayBuffer()` and cache on `this._sourceBytes`.
- If `url` is provided → attempt one `fetch(url, { credentials: 'omit' })`; on success cache the `ArrayBuffer` in `this._sourceBytes`; on CORS / network failure, set `this._sourceBytes = null` and store the failure reason in `this._sourceBytesError = { url, reason }`.
- Replace `getSourceBuffer()` with:
- - If `_sourceBytes` → return it.
- - Else if `_sourceBytesError` → throw a new typed `SourceFetchError` with copy: "Couldn't re-read the model bytes for export. Most often this is a CORS issue with the host. Try: (1) hosting the GLB on the same origin, or (2) drag-and-dropping the file directly."
- - Else throw `new Error('No source buffer for export')` (existing behavior).
+ - If `_sourceBytes` → return it.
+ - Else if `_sourceBytesError` → throw a new typed `SourceFetchError` with copy: "Couldn't re-read the model bytes for export. Most often this is a CORS issue with the host. Try: (1) hosting the GLB on the same origin, or (2) drag-and-dropping the file directly."
+ - Else throw `new Error('No source buffer for export')` (existing behavior).
Export `SourceFetchError` from `src/editor/session.js` so `publish.js` can wrap it as `ExportFailedError` with the same copy.
diff --git a/prompts/drop-edit-embed/07-widget-metadata.md b/prompts/drop-edit-embed/07-widget-metadata.md
index 011dfc1b9..2bc58e866 100644
--- a/prompts/drop-edit-embed/07-widget-metadata.md
+++ b/prompts/drop-edit-embed/07-widget-metadata.md
@@ -9,15 +9,15 @@ This runs in parallel with 01–06. It's verification + targeted polish, not new
## Shared context
- `/w/:id` is served by [api/widgets/page.js](../../api/widgets/page.js) (read it). It should render a full HTML shell with:
- - `<title>` and `<meta name="description">` from `widget.name` / description
- - `og:image` → `/api/widgets/:id/og`
- - `og:url` → canonical `/w/:id`
- - `twitter:card`, `twitter:image`
- - `<link rel="alternate" type="application/json+oembed" href="/api/widgets/oembed?url=<encoded>">`
- - An `<iframe>` or direct `<agent-3d>` that renders the avatar
+ - `<title>` and `<meta name="description">` from `widget.name` / description
+ - `og:image` → `/api/widgets/:id/og`
+ - `og:url` → canonical `/w/:id`
+ - `twitter:card`, `twitter:image`
+ - `<link rel="alternate" type="application/json+oembed" href="/api/widgets/oembed?url=<encoded>">`
+ - An `<iframe>` or direct `<agent-3d>` that renders the avatar
- [api/widgets/og.js](../../api/widgets/og.js) generates the preview image. Read it and determine:
- - Does it 302 to the avatar's `thumbnail_url` when one exists?
- - Does it generate a fallback SVG/PNG when there's no thumbnail? (New avatars from this flow won't have a thumbnail until we build thumbnail generation — out of scope here.)
+ - Does it 302 to the avatar's `thumbnail_url` when one exists?
+ - Does it generate a fallback SVG/PNG when there's no thumbnail? (New avatars from this flow won't have a thumbnail until we build thumbnail generation — out of scope here.)
- [api/widgets/oembed.js](../../api/widgets/oembed.js) — verify it returns `type: 'rich'`, `html: '<iframe …>'`, `provider_name`, `thumbnail_url`, `width`/`height`.
## What to build
@@ -35,10 +35,10 @@ Read and record in your reporting block:
For widgets with no avatar thumbnail:
- Render a server-side SVG (served as `image/svg+xml`) with:
- - Dark background `#0b0d10`.
- - Widget name in large text (truncate at ~40 chars).
- - A small `◎` glyph (match the `3D Agent` brand — same glyph used in the Widget Studio type-picker).
- - Dimensions `1200x630` (Open Graph sweet spot).
+ - Dark background `#0b0d10`.
+ - Widget name in large text (truncate at ~40 chars).
+ - A small `◎` glyph (match the `3D Agent` brand — same glyph used in the Widget Studio type-picker).
+ - Dimensions `1200x630` (Open Graph sweet spot).
- Slack, Discord, X, and iMessage accept SVG for OG. WordPress sometimes strips SVG — acceptable trade-off; note it.
- Cache header: `public, max-age=3600, s-maxage=86400`.
- Do NOT add any image-processing dependency. No `sharp`, no canvas.
@@ -51,19 +51,19 @@ Verify the oEmbed endpoint returns, at minimum:
```json
{
- "type": "rich",
- "version": "1.0",
- "provider_name": "3D Agent",
- "provider_url": "https://3dagent.vercel.app",
- "title": "<widget.name>",
- "html": "<iframe src=\"https://3dagent.vercel.app/w/<id>\" width=\"600\" height=\"600\" frameborder=\"0\" allow=\"autoplay; fullscreen\" allowfullscreen></iframe>",
- "width": 600,
- "height": 600,
- "thumbnail_url": "https://3dagent.vercel.app/api/widgets/<id>/og",
- "thumbnail_width": 1200,
- "thumbnail_height": 630,
- "author_name": "<widget owner display name or empty>",
- "cache_age": 900
+ "type": "rich",
+ "version": "1.0",
+ "provider_name": "3D Agent",
+ "provider_url": "https://3dagent.vercel.app",
+ "title": "<widget.name>",
+ "html": "<iframe src=\"https://3dagent.vercel.app/w/<id>\" width=\"600\" height=\"600\" frameborder=\"0\" allow=\"autoplay; fullscreen\" allowfullscreen></iframe>",
+ "width": 600,
+ "height": 600,
+ "thumbnail_url": "https://3dagent.vercel.app/api/widgets/<id>/og",
+ "thumbnail_width": 1200,
+ "thumbnail_height": 630,
+ "author_name": "<widget owner display name or empty>",
+ "cache_age": 900
}
```
@@ -101,10 +101,10 @@ The drop-edit-embed flow defaults to `is_public: true` (task 02), so this is a s
- Publish a new widget via tasks 01–05 flow → copy `/w/<id>`.
- Paste in Slack, Discord, and X DMs (use real accounts or the bot-test tools below) → all three unfurl with a thumbnail + title.
- - Slack debug: https://api.slack.com/reflection/tools/link-checker (or paste into a private channel)
- - X debug: https://cards-dev.twitter.com/validator (deprecated but still works for some)
- - Discord: just paste it; expect the same unfurl.
- - Facebook sharing debugger: https://developers.facebook.com/tools/debug/ (also checks OG).
+ - Slack debug: https://api.slack.com/reflection/tools/link-checker (or paste into a private channel)
+ - X debug: https://cards-dev.twitter.com/validator (deprecated but still works for some)
+ - Discord: just paste it; expect the same unfurl.
+ - Facebook sharing debugger: https://developers.facebook.com/tools/debug/ (also checks OG).
- Paste in Notion → auto-embeds as iframe via oEmbed.
- `curl -s https://<host>/api/widgets/oembed?url=https://<host>/w/<id>` returns the JSON above.
- `curl -sI https://<host>/api/widgets/<id>/og` returns 200 with an `image/*` content-type.
diff --git a/prompts/drop-edit-embed/08-smoke-test.md b/prompts/drop-edit-embed/08-smoke-test.md
index 9f6f9149e..92ff6fc6a 100644
--- a/prompts/drop-edit-embed/08-smoke-test.md
+++ b/prompts/drop-edit-embed/08-smoke-test.md
@@ -15,55 +15,55 @@ This prompt is a checklist, not a build. The deliverable is a report posted in t
## Golden path (required — this must pass)
-| # | Action | Expected | Pass/Fail |
-|---|---|---|---|
-| 1 | Load `http://localhost:3000` in Incognito | Default model loads, no editor folder (signed-out gates later) or editor visible with grayed-out publish — match task 01 decision | |
-| 2 | Drag a ~2 MB `.glb` onto the page | Model loads, editor folder appears, `📤 publish as embed` present | |
-| 3 | Change one material's base color via Material Editor | Color updates live in viewport | |
-| 4 | Click `📤 publish as embed` | Modal opens, shows "Sign in to publish" (task 04) | |
-| 5 | Click Sign in | Lands on `/login?next=…&resume=…&publish=1` | |
-| 6 | Sign in | Lands back on `/`, same model re-loads, your color edit is still applied | |
-| 7 | Publish modal auto-opens and runs through Export → Upload → Register → Widget steps | All four steps complete, result modal shows 3 snippets | |
-| 8 | Click `Copy` on the iframe snippet, paste into `test.html` locally, open in browser | Avatar renders | |
-| 9 | Click `Open` on the link row | `/w/<id>` opens in a new tab with the avatar | |
-| 10 | Paste the `/w/<id>` link into a Slack channel | Unfurls with an OG card (task 07) | |
-| 11 | Paste into a Notion page | Auto-embeds via oEmbed | |
-| 12 | Return to `/`, change the color again, click Publish | Modal offers `Update` vs `Create new` (task 05) — `Update` is the default radio | |
-| 13 | Click `Go` with Update | Result modal says "Updated ✓", same `/w/<id>` URL | |
-| 14 | Reload the Slack message / Notion block (where possible) | New color is visible | |
+| # | Action | Expected | Pass/Fail |
+| --- | ----------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | --------- |
+| 1 | Load `http://localhost:3000` in Incognito | Default model loads, no editor folder (signed-out gates later) or editor visible with grayed-out publish — match task 01 decision | |
+| 2 | Drag a ~2 MB `.glb` onto the page | Model loads, editor folder appears, `📤 publish as embed` present | |
+| 3 | Change one material's base color via Material Editor | Color updates live in viewport | |
+| 4 | Click `📤 publish as embed` | Modal opens, shows "Sign in to publish" (task 04) | |
+| 5 | Click Sign in | Lands on `/login?next=…&resume=…&publish=1` | |
+| 6 | Sign in | Lands back on `/`, same model re-loads, your color edit is still applied | |
+| 7 | Publish modal auto-opens and runs through Export → Upload → Register → Widget steps | All four steps complete, result modal shows 3 snippets | |
+| 8 | Click `Copy` on the iframe snippet, paste into `test.html` locally, open in browser | Avatar renders | |
+| 9 | Click `Open` on the link row | `/w/<id>` opens in a new tab with the avatar | |
+| 10 | Paste the `/w/<id>` link into a Slack channel | Unfurls with an OG card (task 07) | |
+| 11 | Paste into a Notion page | Auto-embeds via oEmbed | |
+| 12 | Return to `/`, change the color again, click Publish | Modal offers `Update` vs `Create new` (task 05) — `Update` is the default radio | |
+| 13 | Click `Go` with Update | Result modal says "Updated ✓", same `/w/<id>` URL | |
+| 14 | Reload the Slack message / Notion block (where possible) | New color is visible | |
## Edge cases (must be exercised; each becomes a follow-up prompt if it fails)
-| # | Action | Expected | Pass/Fail | Follow-up prompt name |
-|---|---|---|---|---|
-| E1 | Drop a 30 MB glb | Modal shows `SizeTooLargeError` with plan cap (task 06) | | 09-size-error-copy.md |
-| E2 | Load `#model=<cross-origin-CORS-blocked-url>`, edit, publish | `SourceFetchError` with the clear remediation copy (task 06) | | 09-cors-fallback.md |
-| E3 | Publish anonymously-public widget, set `is_public: false` via Studio, re-paste | Unfurl shows "Private widget," no leak (task 07) | | 09-private-unfurl.md |
-| E4 | Publish on `/` with kiosk mode on (`#kiosk=true`) | Editor + publish button are absent, no errors | | 09-kiosk-regression.md |
-| E5 | Load `#widget=<someone-else's-public-widget>`, edit, publish → Update | Server returns 403; modal flips to Create new with friendly copy | | 09-foreign-widget-copy.md |
-| E6 | Publish a widget whose GLB uses Draco + KTX2 compression | Export succeeds, published widget renders same as original | | 09-compressed-glb.md |
-| E7 | Refresh page mid-upload (step 3 of the 4-step progress) | No orphan avatar row; re-publish works | | 09-upload-abort-cleanup.md |
-| E8 | Two tabs publishing at once | Both succeed, no race on the slug generator | | 09-slug-race.md |
+| # | Action | Expected | Pass/Fail | Follow-up prompt name |
+| --- | ------------------------------------------------------------------------------ | ---------------------------------------------------------------- | --------- | -------------------------- |
+| E1 | Drop a 30 MB glb | Modal shows `SizeTooLargeError` with plan cap (task 06) | | 09-size-error-copy.md |
+| E2 | Load `#model=<cross-origin-CORS-blocked-url>`, edit, publish | `SourceFetchError` with the clear remediation copy (task 06) | | 09-cors-fallback.md |
+| E3 | Publish anonymously-public widget, set `is_public: false` via Studio, re-paste | Unfurl shows "Private widget," no leak (task 07) | | 09-private-unfurl.md |
+| E4 | Publish on `/` with kiosk mode on (`#kiosk=true`) | Editor + publish button are absent, no errors | | 09-kiosk-regression.md |
+| E5 | Load `#widget=<someone-else's-public-widget>`, edit, publish → Update | Server returns 403; modal flips to Create new with friendly copy | | 09-foreign-widget-copy.md |
+| E6 | Publish a widget whose GLB uses Draco + KTX2 compression | Export succeeds, published widget renders same as original | | 09-compressed-glb.md |
+| E7 | Refresh page mid-upload (step 3 of the 4-step progress) | No orphan avatar row; re-publish works | | 09-upload-abort-cleanup.md |
+| E8 | Two tabs publishing at once | Both succeed, no race on the slug generator | | 09-slug-race.md |
## Paste-surface matrix (must cover at least one per row)
For each surface, paste the `/w/<id>` URL and record unfurl behavior.
-| Surface | Expected | Pass/Fail |
-|---|---|---|
-| Slack channel | Full OG card + iframe preview (Slack may expand the iframe in unfurl; may not — just the card is OK) | |
-| Discord server | Embed with OG image + title + description | |
-| X (Twitter) post | Summary-large-image card | |
-| iMessage | Link preview with image | |
-| WhatsApp | Same | |
-| Notion page | oEmbed → auto-iframe | |
-| WordPress post | oEmbed → auto-iframe | |
-| Ghost post | oEmbed → auto-iframe | |
-| Raw `<iframe src="…/w/<id>">` in a vanilla HTML file | Renders | |
-| `<agent-3d src="…">` web-component snippet in a vanilla HTML file | Renders | |
-| Claude.ai artifact (paste iframe snippet in a conversation with HTML rendering) | Renders | |
-| LobeHub plugin slot | Renders | |
-| **SperaxOS chat** | Either an iframe render (if they allow HTML) or an OG-style preview (if they only render links) | |
+| Surface | Expected | Pass/Fail |
+| ------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | --------- |
+| Slack channel | Full OG card + iframe preview (Slack may expand the iframe in unfurl; may not — just the card is OK) | |
+| Discord server | Embed with OG image + title + description | |
+| X (Twitter) post | Summary-large-image card | |
+| iMessage | Link preview with image | |
+| WhatsApp | Same | |
+| Notion page | oEmbed → auto-iframe | |
+| WordPress post | oEmbed → auto-iframe | |
+| Ghost post | oEmbed → auto-iframe | |
+| Raw `<iframe src="…/w/<id>">` in a vanilla HTML file | Renders | |
+| `<agent-3d src="…">` web-component snippet in a vanilla HTML file | Renders | |
+| Claude.ai artifact (paste iframe snippet in a conversation with HTML rendering) | Renders | |
+| LobeHub plugin slot | Renders | |
+| **SperaxOS chat** | Either an iframe render (if they allow HTML) or an OG-style preview (if they only render links) | |
If SperaxOS doesn't render iframes and their link preview doesn't fire from oEmbed, file a follow-up (`09-sperax-preview-adapter.md`) describing the exact behavior you saw.
diff --git a/prompts/embed/01-og-oembed.md b/prompts/embed/01-og-oembed.md
index 00f51c793..fae374fb4 100644
--- a/prompts/embed/01-og-oembed.md
+++ b/prompts/embed/01-og-oembed.md
@@ -11,8 +11,8 @@ When anyone pastes an agent URL like `https://3dagent.vercel.app/agent/ab12cd` i
- The share panel on that page is already built and works. You only need to improve what link-previewers see — do not touch the share-panel UI.
- Agent records are fetched via `GET /api/agents/:id` → `{ agent: { id, name, description, avatar_id, ... } }` (see [api/agents/[id].js](../../api/agents/[id].js)).
- Avatar records: `GET /api/avatars/:id` → `{ avatar: { url, thumbnail_url, ... } }`. Use `thumbnail_url` if present; otherwise render the OG image from the GLB (see "OG image implementation" below).
-- HTTP helpers: [api/_lib/http.js](../../api/_lib/http.js) exports `cors`, `json`, `error`, `wrap`, `method`.
-- Avatar helpers: [api/_lib/avatars.js](../../api/_lib/avatars.js) exports `getAvatar`, `resolveAvatarUrl`.
+- HTTP helpers: [api/\_lib/http.js](../../api/_lib/http.js) exports `cors`, `json`, `error`, `wrap`, `method`.
+- Avatar helpers: [api/\_lib/avatars.js](../../api/_lib/avatars.js) exports `getAvatar`, `resolveAvatarUrl`.
## What to build
@@ -43,16 +43,22 @@ Add these tags. Use placeholder `__AGENT__` tokens for any per-agent values —
```html
<!-- unfurl (populated at runtime from identity) -->
-<meta property="og:type" content="website" />
-<meta property="og:title" content="Agent" id="og-title" />
-<meta property="og:description" content="An embodied 3D agent." id="og-description" />
-<meta property="og:image" content="" id="og-image" />
-<meta property="og:url" content="" id="og-url" />
-<meta name="twitter:card" content="summary_large_image" />
-<meta name="twitter:title" content="Agent" id="tw-title" />
-<meta name="twitter:description" content="" id="tw-description" />
-<meta name="twitter:image" content="" id="tw-image" />
-<link rel="alternate" type="application/json+oembed" href="" id="oembed-link" title="Agent oEmbed" />
+<meta property="og:type" content="website" />
+<meta property="og:title" content="Agent" id="og-title" />
+<meta property="og:description" content="An embodied 3D agent." id="og-description" />
+<meta property="og:image" content="" id="og-image" />
+<meta property="og:url" content="" id="og-url" />
+<meta name="twitter:card" content="summary_large_image" />
+<meta name="twitter:title" content="Agent" id="tw-title" />
+<meta name="twitter:description" content="" id="tw-description" />
+<meta name="twitter:image" content="" id="tw-image" />
+<link
+ rel="alternate"
+ type="application/json+oembed"
+ href=""
+ id="oembed-link"
+ title="Agent oEmbed"
+/>
```
In the runtime helper, populate every `id` above once identity loads. `og:image` and `twitter:image` → `/api/agent/{id}/og`. `og:url` → `location.href`. `oembed-link.href` → `/api/oembed?url=<encoded agent url>`.
@@ -84,14 +90,15 @@ Do not touch any other route.
1. `node --check api/agent-og.js api/agent-oembed.js` passes.
2. `npx vite build` — note result.
3. Manual URL checks (report the response shape):
- - `GET /api/agent/SOMEID/og` → 200 image or 302 to thumbnail.
- - `GET /api/oembed?url=http://localhost:3000/agent/SOMEID` → 200 JSON with `html` containing an iframe pointing at `/agent/SOMEID/embed`.
- - `GET /agent/SOMEID` → `<head>` contains populated `og:image` with `/api/agent/SOMEID/og`.
+ - `GET /api/agent/SOMEID/og` → 200 image or 302 to thumbnail.
+ - `GET /api/oembed?url=http://localhost:3000/agent/SOMEID` → 200 JSON with `html` containing an iframe pointing at `/agent/SOMEID/embed`.
+ - `GET /agent/SOMEID` → `<head>` contains populated `og:image` with `/api/agent/SOMEID/og`.
4. Paste a real agent URL into https://www.opengraph.xyz/ or Slack's link-preview debugger and confirm the card renders (manual — flag if you can't test this).
## Reporting
Report:
+
- Files created and line counts
- Files edited with which sections touched
- `node --check` / `vite build` results
diff --git a/prompts/embed/02-agent-id-resolver.md b/prompts/embed/02-agent-id-resolver.md
index 29db44f6d..6aabe8c2c 100644
--- a/prompts/embed/02-agent-id-resolver.md
+++ b/prompts/embed/02-agent-id-resolver.md
@@ -9,12 +9,12 @@ We want: `<agent-3d agent-id="ab12cd">` resolves directly against the hosted API
## Shared context
- [src/element.js](../../src/element.js) is the full `<agent-3d>` custom element. Its `_boot()` method currently:
- 1. Calls `_resolveManifest()` which reads the `src` attribute.
- 2. Loads the manifest, resolves `manifest.body.uri` as a GLB, constructs a `Viewer`, loads the GLB, wires Memory/Skills/Runtime.
+ 1. Calls `_resolveManifest()` which reads the `src` attribute.
+ 2. Loads the manifest, resolves `manifest.body.uri` as a GLB, constructs a `Viewer`, loads the GLB, wires Memory/Skills/Runtime.
- You are adding a **third path** into `_resolveManifest()` that activates when the element has an `agent-id` attribute (and no `src`).
- API:
- - `GET /api/agents/:id` → `{ agent: { id, name, description, avatar_id, skills, wallet_address, chain_id, meta, ... } }`
- - `GET /api/avatars/:id` → `{ avatar: { url, thumbnail_url, ... } }` — `url` is the GLB
+ - `GET /api/agents/:id` → `{ agent: { id, name, description, avatar_id, skills, wallet_address, chain_id, meta, ... } }`
+ - `GET /api/avatars/:id` → `{ avatar: { url, thumbnail_url, ... } }` — `url` is the GLB
- The existing manifest loader is in [src/manifest.js](../../src/manifest.js). The in-memory manifest you build should be shaped the same way a file-based manifest looks, so downstream code (`manifest.brain`, `manifest.body.uri`, `manifest.skills`, `manifest.id`, `manifest._baseURI`) just works.
## What to build
@@ -24,7 +24,10 @@ We want: `<agent-3d agent-id="ab12cd">` resolves directly against the hosted API
Create `src/agent-resolver.js`. Exports one function:
```js
-export async function resolveAgentById(agentId, { origin = location.origin, fetchFn = fetch } = {}) {
+export async function resolveAgentById(
+ agentId,
+ { origin = location.origin, fetchFn = fetch } = {},
+) {
// 1. Fetch /api/agents/:id — throw a typed error on non-200
// 2. Fetch /api/avatars/:avatar_id — throw if no avatar bound
// 3. Return a manifest-shaped object:
@@ -55,9 +58,9 @@ Edit [src/element.js](../../src/element.js):
- If both `agent-id` and `src` are present, prefer `src` (the existing path) and log a one-line console warning.
- On resolver error, dispatch the existing error-phase event the element uses for manifest failures. Do not invent a new event type.
- Import:
- ```js
- import { resolveAgentById, AgentResolveError } from './agent-resolver.js';
- ```
+ ```js
+ import { resolveAgentById, AgentResolveError } from './agent-resolver.js';
+ ```
### 3. Update the share-panel snippet (one-line edit)
@@ -91,14 +94,15 @@ webcomponent: `<script type="module" src="${origin}/dist-lib/agent-3d.js"><\/scr
1. `node --check src/agent-resolver.js src/element.js` passes.
2. `npx vite build` — note result (the web-component bundle should still build).
3. Manual test — write a tiny ad-hoc HTML page (do not commit it) that loads `<agent-3d agent-id="REAL_AGENT_ID">` against a local or deployed backend and confirm:
- - Avatar GLB loads in the stage
- - Agent name appears in the chrome
- - Console shows no unhandled errors
+ - Avatar GLB loads in the stage
+ - Agent name appears in the chrome
+ - Console shows no unhandled errors
4. Edge case: `<agent-3d agent-id="does-not-exist">` — confirm it dispatches the manifest-error event without throwing uncaught.
## Reporting
Report:
+
- `src/agent-resolver.js` line count and exported symbols
- Exact diff summary for `src/element.js` (which methods touched)
- The one-line diff for `public/agent/index.html`
diff --git a/prompts/embed/03-embed-allowlist.md b/prompts/embed/03-embed-allowlist.md
index 3723bcce4..a0626563f 100644
--- a/prompts/embed/03-embed-allowlist.md
+++ b/prompts/embed/03-embed-allowlist.md
@@ -8,8 +8,8 @@ Right now `/agent/:id/embed` renders for anyone who iframes it. Agent owners may
- Embed page: [public/agent/embed.html](../../public/agent/embed.html) — loads the avatar, no chrome. You will add a **referrer check** that runs before the 3D scene mounts.
- Agent records are stored server-side; there is no `embed_policy` field yet — you add it.
-- Auth helpers: [api/_lib/auth.js](../../api/_lib/auth.js) exports `getSessionUser`, `authenticateBearer`, `extractBearer`, `hasScope`.
-- HTTP helpers: [api/_lib/http.js](../../api/_lib/http.js) exports `cors`, `json`, `error`, `wrap`, `method`, `readJson`.
+- Auth helpers: [api/\_lib/auth.js](../../api/_lib/auth.js) exports `getSessionUser`, `authenticateBearer`, `extractBearer`, `hasScope`.
+- HTTP helpers: [api/\_lib/http.js](../../api/_lib/http.js) exports `cors`, `json`, `error`, `wrap`, `method`, `readJson`.
- Existing agent endpoint: [api/agents/[id].js](../../api/agents/[id].js) — do **not** modify it. Add a sibling endpoint for policy (spec below).
- DB layer: agents are in table `agent_identities`. Find the current schema file (search for `CREATE TABLE agent_identities` in the repo) and extend it with your migration file. Do not modify existing migrations.
@@ -20,10 +20,10 @@ Right now `/agent/:id/embed` renders for anyone who iframes it. Agent owners may
- Add a migration file alongside existing ones (follow whatever naming pattern you find — e.g. `specs/schema/NNN-embed-policy.sql`, or wherever migrations live). If you cannot locate a migrations directory, create `specs/schema/embed-policy.sql` with just the `ALTER TABLE` and a comment explaining it needs to be applied manually.
- Column: `embed_policy JSONB` — nullable (null = "allow all embeds," the current behavior).
- Shape when non-null:
- ```json
- { "mode": "allowlist", "hosts": ["example.com", "*.substack.com"] }
- ```
- `mode` is `"allowlist"` or `"denylist"`. `hosts` supports exact matches and a single leading-wildcard segment (`*.foo.com`).
+ ```json
+ { "mode": "allowlist", "hosts": ["example.com", "*.substack.com"] }
+ ```
+ `mode` is `"allowlist"` or `"denylist"`. `hosts` supports exact matches and a single leading-wildcard segment (`*.foo.com`).
### 2. Server endpoint — `GET / PUT /api/agents/:id/embed-policy`
@@ -50,7 +50,7 @@ Edit [public/agent/embed.html](../../public/agent/embed.html):
- Before creating the `Viewer`, fetch `GET /api/agents/${agentId}/embed-policy`.
- If `policy === null` → proceed (current behavior, allow all).
- Otherwise, derive the embedding host from `document.referrer` (top-level) or `window.location.ancestorOrigins?.[0]` when available. Parse the hostname.
- - Browser note: `ancestorOrigins` is Chromium/Safari only. `document.referrer` is the correct cross-browser signal for the parent origin of a first-party iframe. Prefer `ancestorOrigins` when present; fall back to `referrer`.
+ - Browser note: `ancestorOrigins` is Chromium/Safari only. `document.referrer` is the correct cross-browser signal for the parent origin of a first-party iframe. Prefer `ancestorOrigins` when present; fall back to `referrer`.
- Match the host against `policy.hosts` with leading-`*` wildcard support.
- On block: replace the stage with a small centered message — "This agent can only be embedded on approved sites." — style to match the existing `#error` div. Do not render the avatar.
- On allow: proceed as before.
@@ -71,7 +71,9 @@ Create a new page (or panel, depending on the dashboard's structure — inspect
In [public/agent/index.html](../../public/agent/index.html), near the existing "preview embed →" link (it already exists — grep for `agent-embed-preview`), add **one sibling link** right after it:
```html
-<a class="agent-embed-preview-link" id="agent-embed-settings" href="" target="_blank" rel="noopener">embed settings →</a>
+<a class="agent-embed-preview-link" id="agent-embed-settings" href="" target="_blank" rel="noopener"
+ >embed settings →</a
+>
```
And in the existing script, set `.href = '/dashboard/embed-policy?agent=' + identity.id`. Only this link — do not touch anything else in the file.
@@ -93,17 +95,18 @@ And in the existing script, set `.href = '/dashboard/embed-policy?agent=' + iden
1. `node --check api/agents/[id]/embed-policy.js` passes.
2. `npx vite build` — note result.
3. Manual:
- - `GET /api/agents/SOMEID/embed-policy` → `{ policy: null }` when unset.
- - As owner, `PUT /api/agents/SOMEID/embed-policy` with `{ mode: "allowlist", hosts: ["example.com"] }` → returns the policy.
- - `GET` again returns it.
- - `DELETE` clears it.
- - Open `/agent/SOMEID/embed` from the project origin — still loads (same-origin implicit allow OR `?preview=1`).
- - Open an iframe of `/agent/SOMEID/embed` from a page on a disallowed host — confirm the block message renders instead of the avatar.
+ - `GET /api/agents/SOMEID/embed-policy` → `{ policy: null }` when unset.
+ - As owner, `PUT /api/agents/SOMEID/embed-policy` with `{ mode: "allowlist", hosts: ["example.com"] }` → returns the policy.
+ - `GET` again returns it.
+ - `DELETE` clears it.
+ - Open `/agent/SOMEID/embed` from the project origin — still loads (same-origin implicit allow OR `?preview=1`).
+ - Open an iframe of `/agent/SOMEID/embed` from a page on a disallowed host — confirm the block message renders instead of the avatar.
4. Dashboard page loads, shows current policy, saves a change, reload reflects it.
## Reporting
Report:
+
- All created files with line counts
- Files edited with which sections touched (keep edits narrowly scoped — call out if you had to go beyond the spec)
- Migration file path and exact SQL
diff --git a/prompts/embed/04-public-agent-page.md b/prompts/embed/04-public-agent-page.md
index 98b80d285..4b07dcfd0 100644
--- a/prompts/embed/04-public-agent-page.md
+++ b/prompts/embed/04-public-agent-page.md
@@ -22,9 +22,9 @@ This is the canonical URL a user shares when they want the world to see their ag
- Viewer canvas takes the full viewport on mobile, 70% on desktop.
- Below: the agent name + a 2-line description + three compact action buttons:
- - **Chat** — opens the Nich agent chat drawer.
- - **Embed** — opens a modal with an iframe snippet and `<agent-3d id="…">` snippet.
- - **Share** — uses `navigator.share` if available, else copies the page URL.
+ - **Chat** — opens the Nich agent chat drawer.
+ - **Embed** — opens a modal with an iframe snippet and `<agent-3d id="…">` snippet.
+ - **Share** — uses `navigator.share` if available, else copies the page URL.
- Owner-only: a "Manage" button linking to the edit panel.
### Embed modal content
@@ -37,7 +37,13 @@ This is the canonical URL a user shares when they want the world to see their ag
Plus iframe fallback:
```html
-<iframe src="https://3dagent.vercel.app/agent/{{agentId}}?kiosk=1" width="100%" height="500" allow="accelerometer; gyroscope; camera" style="border:0"></iframe>
+<iframe
+ src="https://3dagent.vercel.app/agent/{{agentId}}?kiosk=1"
+ width="100%"
+ height="500"
+ allow="accelerometer; gyroscope; camera"
+ style="border:0"
+></iframe>
```
Copy-to-clipboard buttons for each.
diff --git a/prompts/embed/05-agent3d-element-docs.md b/prompts/embed/05-agent3d-element-docs.md
index 902f9984e..5d905ecbf 100644
--- a/prompts/embed/05-agent3d-element-docs.md
+++ b/prompts/embed/05-agent3d-element-docs.md
@@ -15,6 +15,7 @@
### Attribute audit
Read [src/element.js](../../src/element.js) + [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md). List every attribute the element reads. For each:
+
- Name (kebab-case as attribute, camelCase as property).
- Accepted values + type.
- Default when absent.
@@ -23,6 +24,7 @@ Read [src/element.js](../../src/element.js) + [specs/EMBED_SPEC.md](../../specs/
### Spec update
Rewrite the attribute table in [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md). Add these sections if missing:
+
- **Loading** — `eager` vs IntersectionObserver lazy-load.
- **Kiosk vs interactive** — `kiosk` hides all chrome.
- **Brain** — `brain="none"` (pattern match) vs `brain="anthropic"` + `proxy-url`.
@@ -36,6 +38,7 @@ Check that `element.js` defaults match the spec. Fix mismatches by updating the
### Example gallery
Add two new worked examples to [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md):
+
- Minimum embed (just `agent-id`).
- Kiosk with a custom brain proxy.
diff --git a/prompts/embed/06-iframe-sandbox.md b/prompts/embed/06-iframe-sandbox.md
index df1d2826e..9a9415ac0 100644
--- a/prompts/embed/06-iframe-sandbox.md
+++ b/prompts/embed/06-iframe-sandbox.md
@@ -15,6 +15,7 @@ Claude artifacts and many other host environments iframe-embed with `sandbox` at
### Sandbox-safe boot
In the embed entry script:
+
1. Detect `window.top !== window.self && sandbox attribute present`.
2. If `localStorage` is blocked (DOMException on write) → fall back to `sessionStorage`.
3. If `sessionStorage` is also blocked → memory-only identity (no persistence).
@@ -24,6 +25,7 @@ In the embed entry script:
### CSP audit
Document required CSP:
+
```
default-src 'self' https://3dagent.vercel.app;
img-src 'self' data: blob: https:;
diff --git a/prompts/embed/README.md b/prompts/embed/README.md
index b1842cf5a..e4be6cd17 100644
--- a/prompts/embed/README.md
+++ b/prompts/embed/README.md
@@ -14,11 +14,11 @@ Self-contained prompt files for follow-up work on the "share/embed any agent ava
All three tasks can run simultaneously in separate chats. File ownership is disjoint except for `vercel.json` (each task adds routes in a distinct block, so git merges cleanly).
-| Task | What it ships | File ownership |
-|---|---|---|
-| [01-og-oembed.md](./01-og-oembed.md) | Link unfurls — OG image + oembed endpoint so pasted `/agent/:id` links preview on Slack/X/Discord | owns `api/agent-og.js`, `api/agent-oembed.js`; edits `<head>` of `public/agent/index.html` + `vercel.json` |
-| [02-agent-id-resolver.md](./02-agent-id-resolver.md) | Native `<agent-3d agent-id="...">` attribute so the web-component embed works without a manifest URL | owns `src/agent-resolver.js`; edits `src/element.js` only |
-| [03-embed-allowlist.md](./03-embed-allowlist.md) | Per-agent embed referrer allowlist + dashboard UI for owners to gate where their avatar renders | owns `api/agents/[id]/embed-policy.js`, new dashboard panel; edits `public/agent/embed.html` + `vercel.json` |
+| Task | What it ships | File ownership |
+| ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
+| [01-og-oembed.md](./01-og-oembed.md) | Link unfurls — OG image + oembed endpoint so pasted `/agent/:id` links preview on Slack/X/Discord | owns `api/agent-og.js`, `api/agent-oembed.js`; edits `<head>` of `public/agent/index.html` + `vercel.json` |
+| [02-agent-id-resolver.md](./02-agent-id-resolver.md) | Native `<agent-3d agent-id="...">` attribute so the web-component embed works without a manifest URL | owns `src/agent-resolver.js`; edits `src/element.js` only |
+| [03-embed-allowlist.md](./03-embed-allowlist.md) | Per-agent embed referrer allowlist + dashboard UI for owners to gate where their avatar renders | owns `api/agents/[id]/embed-policy.js`, new dashboard panel; edits `public/agent/embed.html` + `vercel.json` |
## Rules that apply to all tasks
diff --git a/prompts/erc8004-parity/00-README.md b/prompts/erc8004-parity/00-README.md
index 5dcd460b1..5a3471487 100644
--- a/prompts/erc8004-parity/00-README.md
+++ b/prompts/erc8004-parity/00-README.md
@@ -24,7 +24,7 @@ Mirror the reference hero:
- "● Live on 20+ EVM Chains" pill badge
- H1: "Create **Trustless Agents** on Any Chain" (second word in accent)
- Subtitle: "Register AI agents on-chain with ERC-8004. Get a portable, censorship-resistant identity backed by an ERC-721 NFT — discoverable across the entire agent economy."
-- The stats row (630 / 22 / v2.0) should sit under this hero, *above* the tabs (move it out of the current card header).
+- The stats row (630 / 22 / v2.0) should sit under this hero, _above_ the tabs (move it out of the current card header).
### 2. Mainnet warning banner
@@ -103,14 +103,14 @@ Today `/#register` has no visible entry. Add one:
- [ ] `node --check src/erc8004/register-ui.js`
- [ ] `npm run build`
- [ ] Load `/#register` on `localhost:3000`:
- - Hero + stats render above the card
- - 6 tabs present; each one renders content
- - BSC Testnet selected → no mainnet banner; switch to BSC Mainnet → red banner appears
- - Create flow still mints (testnet) end-to-end
- - Search an agent → QR button opens modal with scannable code + Download PNG works
- - Filter chips on Search narrow results
- - Batch: drop a 2-row CSV, wallet connected on testnet → both rows confirm
- - Step 4 Deploy → Export Options accordion shows 4 snippets
+ - Hero + stats render above the card
+ - 6 tabs present; each one renders content
+ - BSC Testnet selected → no mainnet banner; switch to BSC Mainnet → red banner appears
+ - Create flow still mints (testnet) end-to-end
+ - Search an agent → QR button opens modal with scannable code + Download PNG works
+ - Filter chips on Search narrow results
+ - Batch: drop a 2-row CSV, wallet connected on testnet → both rows confirm
+ - Step 4 Deploy → Export Options accordion shows 4 snippets
- [ ] Footer renders with all three columns
- [ ] `/agent/:id` hub's "Deploy on-chain" button navigates to `/#register` (or opens in modal — match what task 04 chose)
- [ ] Homepage footer has "Register on-chain" link
diff --git a/prompts/final-integration/00-README.md b/prompts/final-integration/00-README.md
index 0e5bf78f6..e99a7a591 100644
--- a/prompts/final-integration/00-README.md
+++ b/prompts/final-integration/00-README.md
@@ -19,15 +19,15 @@ The audit that produced these prompts found that ~72% of the stated work is wire
## File-ownership map (no overlaps)
-| # | Prompt | Primary new files | Shared-file anchors |
-|---|---|---|---|
-| 01 | `01-embed-bridges.md` | `src/embed-host-bridge.js`, `src/embed-action-bridge.js` | `src/element.js` — anchor `EMBED_BRIDGES` |
-| 02 | `02-idle-animation.md` | `src/idle-animation.js` | `src/agent-avatar.js` — anchor `IDLE_LOOP` |
-| 03 | `03-agent-home-integration.md` | (none) | `agent-home.html` — anchor `AGENT_HOME_ORPHANS` |
-| 04 | `04-discover-page.md` | `public/discover/index.html`, `public/discover/discover.js`, `public/discover/discover.css` | homepage CTA added via anchor `DISCOVER_LINK` in `index.html` |
-| 05 | `05-lobehub-real-integration.md` | everything under `lobehub-plugin/` | — |
-| 06 | `06-camera-capture-resolution.md` | — | `src/camera-capture.js` (delete or repurpose) + `src/camera-capture.css` |
-| 07 | `07-qa-smoke-test.md` | `docs/SMOKE_TEST.md` | — (read-only audit; may open small surgical fixes in any file with 1-line patch rule) |
+| # | Prompt | Primary new files | Shared-file anchors |
+| --- | --------------------------------- | ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
+| 01 | `01-embed-bridges.md` | `src/embed-host-bridge.js`, `src/embed-action-bridge.js` | `src/element.js` — anchor `EMBED_BRIDGES` |
+| 02 | `02-idle-animation.md` | `src/idle-animation.js` | `src/agent-avatar.js` — anchor `IDLE_LOOP` |
+| 03 | `03-agent-home-integration.md` | (none) | `agent-home.html` — anchor `AGENT_HOME_ORPHANS` |
+| 04 | `04-discover-page.md` | `public/discover/index.html`, `public/discover/discover.js`, `public/discover/discover.css` | homepage CTA added via anchor `DISCOVER_LINK` in `index.html` |
+| 05 | `05-lobehub-real-integration.md` | everything under `lobehub-plugin/` | — |
+| 06 | `06-camera-capture-resolution.md` | — | `src/camera-capture.js` (delete or repurpose) + `src/camera-capture.css` |
+| 07 | `07-qa-smoke-test.md` | `docs/SMOKE_TEST.md` | — (read-only audit; may open small surgical fixes in any file with 1-line patch rule) |
## Shared-file anchor protocol
@@ -43,6 +43,7 @@ This guarantees parallel runs never stomp each other even if two agents touch th
## What counts as "done"
A prompt is complete when:
+
- Every file listed under **Deliverables** exists and passes `node --check`.
- `npm run build` succeeds with zero new warnings.
- The **Acceptance** checklist passes.
diff --git a/prompts/final-integration/04-discover-page.md b/prompts/final-integration/04-discover-page.md
index c283cc617..04a918ec1 100644
--- a/prompts/final-integration/04-discover-page.md
+++ b/prompts/final-integration/04-discover-page.md
@@ -2,7 +2,7 @@
## Context
-Users sign in with their wallet. Behind that wallet, they may already own ERC-8004 agent NFTs that they've registered or acquired elsewhere — the product should *find* those agents and pull them into the user's library automatically. The backend endpoint `/api/erc8004/hydrate` already enumerates on-chain agents for any linked wallet; the client helper `src/erc8004/hydrate.js` wraps both `fetchDiscoveredAgents()` and `importAgent()`.
+Users sign in with their wallet. Behind that wallet, they may already own ERC-8004 agent NFTs that they've registered or acquired elsewhere — the product should _find_ those agents and pull them into the user's library automatically. The backend endpoint `/api/erc8004/hydrate` already enumerates on-chain agents for any linked wallet; the client helper `src/erc8004/hydrate.js` wraps both `fetchDiscoveredAgents()` and `importAgent()`.
**The UI that uses these helpers does not exist.** The module is an orphan.
@@ -11,6 +11,7 @@ Your job: build a polished standalone `/discover` page that shows the signed-in
## Goal
A `/discover` route that, for a signed-in user:
+
- Lists every agent discovered via their linked wallets across all supported chains.
- Flags ones already imported vs. importable.
- One-click imports an agent into the user's library (calls `importAgent()`).
@@ -22,14 +23,17 @@ This page is how a new wallet-first user gets their existing agents into the app
## Files you own
Create:
+
- `public/discover/index.html`
- `public/discover/discover.js`
- `public/discover/discover.css`
Edit (inside uniquely-named anchor only):
+
- `index.html` — add anchor block `<!-- BEGIN:DISCOVER_LINK --> ... <!-- END:DISCOVER_LINK -->` on the homepage. Inside: a single CTA link/button that routes to `/discover` (visible only when signed in — use a JS gate inside the anchor, or a CSS class toggled by existing session code). **No edits outside the anchor.**
Also ensure `/discover` resolves:
+
- Check [vite.config.js](../../vite.config.js) `vercel-rewrites` plugin and [vercel.json](../../vercel.json). The rewrite rules may already match `public/**` → add an entry if `/discover` does not resolve to `public/discover/index.html`. If you need to add a single line to either file, do so inside a `BEGIN:DISCOVER_ROUTE` anchor in that file. Otherwise leave both untouched.
## Files read-only
@@ -45,26 +49,29 @@ Also ensure `/discover` resolves:
## UX requirements
**Page layout:**
+
- Header with title `On-chain Agents`, subtitle `Agents we found in your linked wallets`.
- Link back to homepage + link to dashboard.
- Grid of agent cards (1 col mobile, 2 col tablet, 3 col desktop).
- Each card: square thumbnail (glbUrl preview fallback to `image`), name, chain pill, short description, action button (`Import` or `Already in library`).
- Empty states:
- - Not signed in → page renders a single CTA `Sign in to discover your agents` → `/login.html`.
- - Signed in, no linked wallets → CTA `Link a wallet to get started` → `/dashboard/wallets.html`.
- - Signed in, wallets linked, zero agents → friendly illustration/text `No on-chain agents yet — register one from the dashboard`.
+ - Not signed in → page renders a single CTA `Sign in to discover your agents` → `/login.html`.
+ - Signed in, no linked wallets → CTA `Link a wallet to get started` → `/dashboard/wallets.html`.
+ - Signed in, wallets linked, zero agents → friendly illustration/text `No on-chain agents yet — register one from the dashboard`.
- Error states:
- - Network error → inline error with a retry button.
- - Rate-limited (429) → explicit `Too many requests. Try again in a minute.`
+ - Network error → inline error with a retry button.
+ - Rate-limited (429) → explicit `Too many requests. Try again in a minute.`
- Loading state: skeleton cards with shimmer animation (CSS only, no JS animation).
**Import flow:**
+
- Click `Import` → button enters busy state, disables, fetches `importAgent(...)` via `src/erc8004/hydrate.js`.
- On success: card flips state to `Already in library` + shows a link to `/agent/<new-id>`.
- On failure: revert button state, inline error under card.
- Imports are independent — one failing does not block others.
**Visuals:**
+
- Reuse the CSS tokens / design language of `public/dashboard/` (fonts, spacing, colors). Pull class names from an existing dashboard subpage and mirror them. Do not import the dashboard's CSS file; copy only the tokens you need into `discover.css`.
- All styling scoped via BEM or a single `.discover-*` prefix to avoid leakage.
@@ -82,14 +89,12 @@ Inside the `DISCOVER_LINK` anchor on `index.html`:
```html
<!-- BEGIN:DISCOVER_LINK -->
-<a href="/discover" id="discoverLink" class="discover-cta" hidden>
- Find my on-chain agents →
-</a>
+<a href="/discover" id="discoverLink" class="discover-cta" hidden> Find my on-chain agents → </a>
<script type="module">
- // Reveal when signed in. Non-blocking — failures stay hidden.
- fetch('/api/auth/me', { credentials: 'include' })
- .then((r) => r.ok && (document.getElementById('discoverLink').hidden = false))
- .catch(() => {});
+ // Reveal when signed in. Non-blocking — failures stay hidden.
+ fetch('/api/auth/me', { credentials: 'include' })
+ .then((r) => r.ok && (document.getElementById('discoverLink').hidden = false))
+ .catch(() => {});
</script>
<!-- END:DISCOVER_LINK -->
```
diff --git a/prompts/final-integration/07-qa-smoke-test.md b/prompts/final-integration/07-qa-smoke-test.md
index 0dc6c3d0b..eb24ecdb6 100644
--- a/prompts/final-integration/07-qa-smoke-test.md
+++ b/prompts/final-integration/07-qa-smoke-test.md
@@ -13,15 +13,18 @@ Exercise every critical user flow in a real browser, produce a `docs/SMOKE_TEST.
## Files you own
Create:
+
- `docs/SMOKE_TEST.md` — the living smoke-test document.
Edit (surgical only — the **one-line patch rule**):
+
- Any file in the repo for fixes ≤ 10 lines of change. Each fix must be:
- - Clearly defect-driven (not a refactor, not a "while I'm here").
- - Accompanied by a note in `SMOKE_TEST.md` citing which flow step surfaced it.
- - Kept to the minimum change that makes the flow pass.
+ - Clearly defect-driven (not a refactor, not a "while I'm here").
+ - Accompanied by a note in `SMOKE_TEST.md` citing which flow step surfaced it.
+ - Kept to the minimum change that makes the flow pass.
Do NOT:
+
- Add features.
- Rename things.
- Touch shared-file anchors owned by sibling prompts (`EMBED_BRIDGES`, `IDLE_LOOP`, `AGENT_HOME_ORPHANS`, `DISCOVER_LINK`). If the smoke test reveals a bug inside one of those anchors, file it in `SMOKE_TEST.md` as a follow-up and do not touch the code.
@@ -32,12 +35,14 @@ Do NOT:
Run each flow in the dev server (`npm run dev`) against a real browser. Chrome/Edge + Firefox minimum; Safari if the host has one. For each step, record PASS / FAIL / BLOCKED with a short note.
### Flow A — First-time wallet sign-in
+
1. Open `http://localhost:3000/` in a private window.
2. Click sign-in with wallet button.
3. Complete SIWE flow with a fresh wallet (MetaMask or WalletConnect).
4. Land on dashboard.
### Flow B — Selfie → agent
+
1. From dashboard, click "Create agent".
2. Grant camera permission.
3. Capture a selfie.
@@ -46,6 +51,7 @@ Run each flow in the dev server (`npm run dev`) against a real browser. Chrome/E
6. Save; land on `/agent/<id>`.
### Flow C — Edit + save-back
+
1. On any owned agent's `/agent/<id>/edit`, open the editor.
2. Change a material color.
3. Click save.
@@ -53,30 +59,40 @@ Run each flow in the dev server (`npm run dev`) against a real browser. Chrome/E
5. Check `/api/avatars/<id>/versions` returns ≥ 2 rows.
### Flow D — Share + embed
+
1. On `/agent/<id>`, click Share.
2. Copy the iframe snippet. Paste into a local scratch HTML file; open it.
3. Agent renders correctly in the iframe.
4. Open browser devtools → Network → confirm no CORS errors.
### Flow E — Embed bridge round-trip
+
1. Load the scratch HTML from Flow D. Open devtools → Console on the parent page.
2. Run:
- ```js
- const iframe = document.querySelector('iframe');
- iframe.contentWindow.postMessage({
- v: 1, source: 'agent-host', id: crypto.randomUUID(),
- kind: 'request', op: 'ping'
- }, '*');
- ```
+ ```js
+ const iframe = document.querySelector('iframe');
+ iframe.contentWindow.postMessage(
+ {
+ v: 1,
+ source: 'agent-host',
+ id: crypto.randomUUID(),
+ kind: 'request',
+ op: 'ping',
+ },
+ '*',
+ );
+ ```
3. Expect a `pong` event in the console (install a temporary `window.addEventListener('message', …)` to see it).
4. Try `op: 'speak', payload: { text: 'Hello world' }` — avatar should visibly speak.
### Flow F — Idle loop
+
1. On `/agent/<id>`, watch the avatar for 10 seconds without interacting.
2. Observe: blinks occur, subtle head drift, no jank.
3. Open the Performance tab; record 5 seconds. Average frame time < 16.7ms.
### Flow G — Discover page
+
1. Sign in with a wallet that owns on-chain agents (or a test wallet pre-seeded on Base Sepolia).
2. Visit `/discover`.
3. Discovered agents render as cards.
@@ -85,6 +101,7 @@ Run each flow in the dev server (`npm run dev`) against a real browser. Chrome/E
6. Click through → `/agent/<new-id>` renders.
### Flow H — Deploy on-chain
+
1. As the agent owner, open `/agent/<id>`.
2. Deploy chip visible.
3. Click Deploy.
@@ -93,22 +110,26 @@ Run each flow in the dev server (`npm run dev`) against a real browser. Chrome/E
6. `api/agents/by-address/<wallet>` returns the new agent.
### Flow I — LobeHub plugin dev harness
+
1. `cd lobehub-plugin && npm install && npm run build`.
2. Open `lobehub-plugin/dev/index.html` via `python3 -m http.server 5555`.
3. Inject a fake assistant message.
4. Avatar in the iframe visibly speaks.
### Flow J — Dashboard sidebar pages
+
1. From `/dashboard/`, navigate to: Avatars, Agents, Sessions, Wallets, Actions, Reputation.
2. Every sidebar page loads without console errors.
3. Each page fetches and displays real data (or a correct empty state).
### Flow K — Logout + session revocation
+
1. From `/dashboard/sessions.html`, click "Sign out all devices".
2. Refresh; land on sign-in.
3. `/api/auth/me` returns 401.
### Flow L — Mobile layout smoke
+
1. Chrome devtools → device toolbar → iPhone SE (360×667).
2. Visit homepage, `/agent/<id>`, `/discover`, `/dashboard/`.
3. No horizontal scroll, no overlapping elements, all CTAs tappable.
@@ -124,19 +145,23 @@ Run each flow in the dev server (`npm run dev`) against a real browser. Chrome/E
**Dev server:** npm run dev (port 3000)
## Summary
-| Flow | Result | Notes |
-|------|--------|-------|
-| A. Wallet sign-in | PASS/FAIL/BLOCKED | … |
-| B. Selfie → agent | … | … |
+
+| Flow | Result | Notes |
+| ------------------ | ----------------- | ----- |
+| A. Wallet sign-in | PASS/FAIL/BLOCKED | … |
+| B. Selfie → agent | … | … |
| … (every flow A–L) |
## Defects fixed in this pass
+
- [ ] <short description> — file:line — 1-line summary of fix.
## Defects NOT fixed (follow-up prompts recommended)
+
- [ ] <short description> — file:line — why escalated (out of scope, > 10 LOC, touches sibling anchor, etc.).
## Environment notes
+
<Anything about test wallets, seeded chain state, or setup that the next runner needs.>
```
@@ -145,6 +170,7 @@ Keep the doc evergreen — future QA passes append to the same file rather than
## One-line-patch rule
A fix qualifies as in-scope if ALL of:
+
- ≤ 10 lines changed in one file.
- No new files added (except `SMOKE_TEST.md` itself).
- No anchor-owned block touched.
diff --git a/prompts/lobehub-embed/00-fork-sidebar-fastpath.md b/prompts/lobehub-embed/00-fork-sidebar-fastpath.md
index 6435f0b7e..46dbe336f 100644
--- a/prompts/lobehub-embed/00-fork-sidebar-fastpath.md
+++ b/prompts/lobehub-embed/00-fork-sidebar-fastpath.md
@@ -61,7 +61,9 @@ export function AgentDock() {
{collapsed ? '‹' : '›'}
</button>
<span className="agent-dock__name">{/* populated from ready event */}</span>
- <a href={`${ORIGIN}/agent/${agentId}`} target="_blank" rel="noopener">⚙</a>
+ <a href={`${ORIGIN}/agent/${agentId}`} target="_blank" rel="noopener">
+ ⚙
+ </a>
</header>
{!collapsed && (
<iframe
@@ -113,7 +115,7 @@ Purpose: listen to LobeHub's chat-stream state (find it via the fork's Zustand s
```ts
import { RefObject, useEffect } from 'react';
-import { useChatStore } from '@/store/chat'; // path depends on fork — confirm first
+import { useChatStore } from '@/store/chat'; // path depends on fork — confirm first
export function useChatStreamBridge(iframeRef: RefObject<HTMLIFrameElement>, origin: string) {
useEffect(() => {
@@ -137,10 +139,16 @@ export function useChatStreamBridge(iframeRef: RefObject<HTMLIFrameElement>, ori
// Optional: when the assistant finishes, forward the final text.
const unsubDone = useChatStore.subscribe(
(s) => s.lastAssistantMessage,
- (msg) => msg && post('speak', { text: msg.content, sentiment: detectSentiment(msg.content) }),
+ (msg) =>
+ msg &&
+ post('speak', { text: msg.content, sentiment: detectSentiment(msg.content) }),
);
- return () => { unsubSend(); unsubStream(); unsubDone(); };
+ return () => {
+ unsubSend();
+ unsubStream();
+ unsubDone();
+ };
}, [iframeRef, origin]);
}
@@ -177,15 +185,30 @@ CSS (in `src/features/AgentDock/dock.module.css` or a global stylesheet — matc
transition: transform 0.25s ease;
z-index: 40;
}
-.agent-dock--collapsed { transform: translateX(calc(100% - 32px)); }
+.agent-dock--collapsed {
+ transform: translateX(calc(100% - 32px));
+}
.agent-dock__header {
- display: flex; align-items: center; gap: 8px;
+ display: flex;
+ align-items: center;
+ gap: 8px;
padding: 10px 12px;
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
}
-.agent-dock__name { font-size: 13px; opacity: 0.7; flex: 1; }
-.agent-dock iframe { flex: 1; min-height: 0; }
-@media (max-width: 900px) { .agent-dock { display: none; } } /* hide on mobile for now */
+.agent-dock__name {
+ font-size: 13px;
+ opacity: 0.7;
+ flex: 1;
+}
+.agent-dock iframe {
+ flex: 1;
+ min-height: 0;
+}
+@media (max-width: 900px) {
+ .agent-dock {
+ display: none;
+ }
+} /* hide on mobile for now */
```
Push the main content left by `360px` when the dock is expanded (search the fork's main layout for `margin-right` / CSS variable control — follow the existing pattern).
@@ -258,6 +281,7 @@ Keep the change to under 25 lines. Do **not** change the `AgentAvatar` decay rat
## Files you own
In the fork:
+
- `src/features/AgentDock/index.tsx` (create)
- `src/features/AgentDock/store.ts` (create)
- `src/features/AgentDock/useChatStreamBridge.ts` (create)
@@ -267,6 +291,7 @@ In the fork:
- `next.config.js` CSP (if edits required — flag if so)
In this repo (optional, step 7 only):
+
- [public/agent/embed.html](../../public/agent/embed.html) — tiny `?host=lobehub` branch. No other edits.
## Files off-limits
diff --git a/prompts/lobehub-embed/01-plugin-manifest.md b/prompts/lobehub-embed/01-plugin-manifest.md
index 8b3234fc5..f3ba64585 100644
--- a/prompts/lobehub-embed/01-plugin-manifest.md
+++ b/prompts/lobehub-embed/01-plugin-manifest.md
@@ -19,17 +19,17 @@ Produce a LobeHub plugin manifest, hosted at a stable public URL under this depl
## Deliverable
1. **Manifest file** at `public/.well-known/lobehub-plugin.json` (served at `https://<host>/.well-known/lobehub-plugin.json`) that declares:
- - `identifier` — kebab-case, e.g. `3d-agent`
- - `meta` — `{ title, description, avatar, tags }`
- - `author`, `homepage`, `version` (read from `package.json`'s version at build if trivial; otherwise hard-code `0.1.0` and note)
- - `ui.url` — absolute URL to our iframe (e.g. `https://<host>/agent/{AGENT_ID}/embed?host=lobehub`). Use a placeholder token if LobeHub supports runtime interpolation; otherwise require the user to edit.
- - `ui.height` — default iframe height (e.g. `520`)
- - `api` — tool schemas the chat model can call, each with `name`, `description`, `parameters` (JSON Schema). Start with:
- - `render_agent({ agentId })` — mount the avatar for a given agent id
- - `speak({ text, sentiment? })` — make the avatar speak with emotional valence
- - `gesture({ name, duration? })` — trigger a named gesture (wave, nod, point, shrug)
- - `emote({ trigger, weight? })` — inject an emotion (`concern`, `celebration`, `patience`, `curiosity`, `empathy`)
- - `systemRole` — optional priming text so the LobeHub chat model knows an embodied agent is present
+ - `identifier` — kebab-case, e.g. `3d-agent`
+ - `meta` — `{ title, description, avatar, tags }`
+ - `author`, `homepage`, `version` (read from `package.json`'s version at build if trivial; otherwise hard-code `0.1.0` and note)
+ - `ui.url` — absolute URL to our iframe (e.g. `https://<host>/agent/{AGENT_ID}/embed?host=lobehub`). Use a placeholder token if LobeHub supports runtime interpolation; otherwise require the user to edit.
+ - `ui.height` — default iframe height (e.g. `520`)
+ - `api` — tool schemas the chat model can call, each with `name`, `description`, `parameters` (JSON Schema). Start with:
+ - `render_agent({ agentId })` — mount the avatar for a given agent id
+ - `speak({ text, sentiment? })` — make the avatar speak with emotional valence
+ - `gesture({ name, duration? })` — trigger a named gesture (wave, nod, point, shrug)
+ - `emote({ trigger, weight? })` — inject an emotion (`concern`, `celebration`, `patience`, `curiosity`, `empathy`)
+ - `systemRole` — optional priming text so the LobeHub chat model knows an embodied agent is present
2. **Vercel route** — add a route to `vercel.json` that serves the manifest with `Content-Type: application/json` and `Cache-Control: public, max-age=300`. Place the route in the existing `.well-known/*` block if present; otherwise add it grouped with other well-known entries.
3. **Served copy for discovery** — if LobeHub reads from `.well-known/` specifically, no extra work. If not, also link it from the top of `.well-known/agent-card.json` via a non-breaking `lobehub_plugin_url` field.
diff --git a/prompts/lobehub-embed/02-iframe-handshake.md b/prompts/lobehub-embed/02-iframe-handshake.md
index b5f5584bb..87fb38809 100644
--- a/prompts/lobehub-embed/02-iframe-handshake.md
+++ b/prompts/lobehub-embed/02-iframe-handshake.md
@@ -21,11 +21,11 @@ Replace the ad-hoc bridge with a versioned, typed, bidirectional protocol betwee
## Deliverable
1. **Protocol module** — new file `src/embed-host-bridge.js`. Pure JS, no runtime deps. Exports a class `EmbedHostBridge` with:
- - Constructor: `new EmbedHostBridge({ protocol, identity, viewer, avatarCtl, agentId })`
- - `attach()` — starts listening for host messages, posts `hello`
- - `detach()` — removes listeners
- - `postToHost(type, payload)` — envelope helper
- - Internal event vocabulary below
+ - Constructor: `new EmbedHostBridge({ protocol, identity, viewer, avatarCtl, agentId })`
+ - `attach()` — starts listening for host messages, posts `hello`
+ - `detach()` — removes listeners
+ - `postToHost(type, payload)` — envelope helper
+ - Internal event vocabulary below
2. **Edit embed page** — [public/agent/embed.html](../../public/agent/embed.html) imports the bridge and replaces the inline `window.addEventListener('message', ...)` block. The existing `ready`/`blocked` posts should be routed through the bridge.
3. **Version** — first line of every envelope: `{ v: 1, ns: '3d-agent', ... }`. Reject unknown `v`.
@@ -35,27 +35,27 @@ All messages are JSON objects. Outbound (embed → host) and inbound (host → e
### Inbound (host → embed)
-| type | payload | effect |
-|---|---|---|
-| `host:hello` | `{ hostName, hostVersion, capabilities: string[] }` | Handshake. Embed replies with `embed:hello` including its capability list. |
-| `host:set-agent` | `{ agentId }` | Rebind to a different agent id. Tear down current avatar, resolve new one, boot. |
-| `host:action` | `{ action: { type, payload, sourceSkill? } }` | Emit on `protocol`. Covered in full in [04-action-passthrough.md](./04-action-passthrough.md); for this task, keep the existing relay wrapped in the new envelope. |
-| `host:pause` | `{}` | Call `viewer.pause?.()` or stop RAF. |
-| `host:resume` | `{}` | Resume viewer. |
-| `host:theme` | `{ mode: 'dark' \| 'light' \| 'transparent', accent? }` | Apply background + accent without reload. |
-| `host:ping` | `{}` | Reply with `embed:pong`. Used by host to detect stale iframes. |
+| type | payload | effect |
+| ---------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `host:hello` | `{ hostName, hostVersion, capabilities: string[] }` | Handshake. Embed replies with `embed:hello` including its capability list. |
+| `host:set-agent` | `{ agentId }` | Rebind to a different agent id. Tear down current avatar, resolve new one, boot. |
+| `host:action` | `{ action: { type, payload, sourceSkill? } }` | Emit on `protocol`. Covered in full in [04-action-passthrough.md](./04-action-passthrough.md); for this task, keep the existing relay wrapped in the new envelope. |
+| `host:pause` | `{}` | Call `viewer.pause?.()` or stop RAF. |
+| `host:resume` | `{}` | Resume viewer. |
+| `host:theme` | `{ mode: 'dark' \| 'light' \| 'transparent', accent? }` | Apply background + accent without reload. |
+| `host:ping` | `{}` | Reply with `embed:pong`. Used by host to detect stale iframes. |
### Outbound (embed → host)
-| type | payload | when |
-|---|---|---|
-| `embed:hello` | `{ embedVersion, agentId, capabilities }` | On `host:hello` or first post after DOM ready |
-| `embed:ready` | `{ agentId, name, avatarUrl }` | Avatar GLB loaded, `AgentAvatar` attached |
-| `embed:blocked` | `{ reason: 'policy' }` | Embed-policy check failed |
-| `embed:error` | `{ code, message, phase }` | Any boot or runtime error (phases: `policy`, `identity`, `avatar`, `viewer`, `bridge`) |
-| `embed:action` | `{ action: { type, payload, sourceSkill, timestamp, agentId } }` | Mirrors every `protocol` event outward so the host can log what the avatar did. Filter to protocol's `ACTION_TYPES` only. |
-| `embed:resize` | `{ width, height, contentHeight }` | When the viewer reports a new content height (e.g. name plate grew, error shown) |
-| `embed:pong` | `{}` | Reply to `host:ping` |
+| type | payload | when |
+| --------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
+| `embed:hello` | `{ embedVersion, agentId, capabilities }` | On `host:hello` or first post after DOM ready |
+| `embed:ready` | `{ agentId, name, avatarUrl }` | Avatar GLB loaded, `AgentAvatar` attached |
+| `embed:blocked` | `{ reason: 'policy' }` | Embed-policy check failed |
+| `embed:error` | `{ code, message, phase }` | Any boot or runtime error (phases: `policy`, `identity`, `avatar`, `viewer`, `bridge`) |
+| `embed:action` | `{ action: { type, payload, sourceSkill, timestamp, agentId } }` | Mirrors every `protocol` event outward so the host can log what the avatar did. Filter to protocol's `ACTION_TYPES` only. |
+| `embed:resize` | `{ width, height, contentHeight }` | When the viewer reports a new content height (e.g. name plate grew, error shown) |
+| `embed:pong` | `{}` | Reply to `host:ping` |
## Audit checklist
diff --git a/prompts/lobehub-embed/03-host-auth-handoff.md b/prompts/lobehub-embed/03-host-auth-handoff.md
index 561facb0d..ef0069f17 100644
--- a/prompts/lobehub-embed/03-host-auth-handoff.md
+++ b/prompts/lobehub-embed/03-host-auth-handoff.md
@@ -19,22 +19,22 @@ Define and implement the three-tier viewer identity handoff inside the embed, an
## Deliverable
1. **Extend the handshake** in `src/embed-host-bridge.js` (created in [02](./02-iframe-handshake.md)) with two new envelope types:
- - Inbound: `host:identity` — `{ hostUserId, hostUserName?, hostUserAvatar?, hostSignedToken? }`
- - Outbound: `embed:identity-request` — `{ want: ['wallet' | 'host-user'], reason }` (embed asks host to either (a) reveal its user id, or (b) trigger wallet link)
+ - Inbound: `host:identity` — `{ hostUserId, hostUserName?, hostUserAvatar?, hostSignedToken? }`
+ - Outbound: `embed:identity-request` — `{ want: ['wallet' | 'host-user'], reason }` (embed asks host to either (a) reveal its user id, or (b) trigger wallet link)
2. **Viewer identity state machine** — new file `src/embed-viewer-identity.js`:
- - Tiers: `anon` → `host-user` → `wallet-linked`
- - Transitions stored in `sessionStorage` under key `3d-agent:viewer-identity:<agentId>`
- - Methods: `current()`, `setHostUser(info)`, `linkWallet({ address, chainId, signature, message })`, `clear()`
- - Expose a read-only object: `{ tier, hostUserId?, walletAddress?, chainId? }`
+ - Tiers: `anon` → `host-user` → `wallet-linked`
+ - Transitions stored in `sessionStorage` under key `3d-agent:viewer-identity:<agentId>`
+ - Methods: `current()`, `setHostUser(info)`, `linkWallet({ address, chainId, signature, message })`, `clear()`
+ - Expose a read-only object: `{ tier, hostUserId?, walletAddress?, chainId? }`
3. **Optional SIWE-on-open** — an opt-in flow:
- - Embed renders a small, dismissible prompt in the corner: "Link wallet to let [agent name] act as you" with a "Connect" button.
- - Clicking "Connect" posts `embed:identity-request { want: ['wallet'] }` to host so LobeHub can open its wallet UI — **or** if host capability `inline-wallet` is false, opens a same-origin SIWE pop-up using our existing wallet infra.
- - Completed SIWE stores tier=`wallet-linked`, notifies host with `embed:identity-change`.
- - The prompt must be **dismissible** and **remembered** per agent id for the session.
+ - Embed renders a small, dismissible prompt in the corner: "Link wallet to let [agent name] act as you" with a "Connect" button.
+ - Clicking "Connect" posts `embed:identity-request { want: ['wallet'] }` to host so LobeHub can open its wallet UI — **or** if host capability `inline-wallet` is false, opens a same-origin SIWE pop-up using our existing wallet infra.
+ - Completed SIWE stores tier=`wallet-linked`, notifies host with `embed:identity-change`.
+ - The prompt must be **dismissible** and **remembered** per agent id for the session.
4. **Avatar behavior gating** — when tier is `anon`:
- - Avatar still renders with full Empathy Layer (do **not** flatten).
- - Memory operates in "ephemeral" mode (in-process only, no persistence to the agent's wallet-scoped namespace).
- - Skills that require `ctx.wallet` or `ctx.sign` return `{ ok: false, error: 'wallet-required' }` instead of throwing.
+ - Avatar still renders with full Empathy Layer (do **not** flatten).
+ - Memory operates in "ephemeral" mode (in-process only, no persistence to the agent's wallet-scoped namespace).
+ - Skills that require `ctx.wallet` or `ctx.sign` return `{ ok: false, error: 'wallet-required' }` instead of throwing.
5. **Propagation to the runtime** — when tier changes, re-hydrate [AgentIdentity](../../src/agent-identity.js) with the new scope. Existing avatar instance is **not** re-mounted (avoid full reboot); only the identity record is swapped.
## Audit checklist
@@ -59,10 +59,10 @@ Define and implement the three-tier viewer identity handoff inside the embed, an
1. `node --check src/embed-viewer-identity.js api/embed/verify-host-token.js` passes.
2. `npx vite build` succeeds.
3. Manual matrix:
- - **Anon**: iframe the embed, send no messages. Avatar works.
- - **Host-user only**: iframe sends `host:identity { hostUserId: 'u1' }`. Prompt appears. Dismiss persists.
- - **Host-user + wallet**: dismiss then re-init with a `linkWallet()` call in console. Tier flips to `wallet-linked`. `embed:identity-change` fires.
- - **Tier downgrade**: call `clear()`. Avatar keeps running; memory flips to ephemeral. Skills fail softly.
+ - **Anon**: iframe the embed, send no messages. Avatar works.
+ - **Host-user only**: iframe sends `host:identity { hostUserId: 'u1' }`. Prompt appears. Dismiss persists.
+ - **Host-user + wallet**: dismiss then re-init with a `linkWallet()` call in console. Tier flips to `wallet-linked`. `embed:identity-change` fires.
+ - **Tier downgrade**: call `clear()`. Avatar keeps running; memory flips to ephemeral. Skills fail softly.
4. Unit-test the state machine in isolation via a quick node REPL (`import('./src/embed-viewer-identity.js')`). Document what you ran.
## Scope boundaries — do NOT do these
diff --git a/prompts/lobehub-embed/04-action-passthrough.md b/prompts/lobehub-embed/04-action-passthrough.md
index 5af04d9fc..68dde9534 100644
--- a/prompts/lobehub-embed/04-action-passthrough.md
+++ b/prompts/lobehub-embed/04-action-passthrough.md
@@ -21,27 +21,27 @@ Wire bidirectional, lossless relay between LobeHub's chat tool-call surface and
## Deliverable
1. **New module** `src/embed-action-relay.js`:
- - `class EmbedActionRelay` wired to the bridge from [02](./02-iframe-handshake.md) and the [protocol](../../src/agent-protocol.js) singleton.
- - `attach({ bridge, protocol, identity })` — starts both directions.
- - `detach()` — tears both down.
+ - `class EmbedActionRelay` wired to the bridge from [02](./02-iframe-handshake.md) and the [protocol](../../src/agent-protocol.js) singleton.
+ - `attach({ bridge, protocol, identity })` — starts both directions.
+ - `detach()` — tears both down.
2. **Inbound mapping** (host tool call → protocol emit):
- | LobeHub tool | ACTION_TYPE | payload shape |
- |---|---|---|
- | `render_agent({ agentId })` | (no emit; triggers `bridge` `host:set-agent` path) | — |
- | `speak({ text, sentiment? })` | `SPEAK` | `{ text, sentiment: clamp(sentiment, -1, 1) }` |
- | `gesture({ name, duration? })` | `GESTURE` | `{ name, duration: duration \|\| 1.5 }` |
- | `emote({ trigger, weight? })` | `EMOTE` | `{ trigger, weight: clamp(weight, 0, 1) }` |
- | `look_at({ target })` | `LOOK_AT` | `{ target }` (validate against `'model'\|'user'\|'camera'`) |
+ | LobeHub tool | ACTION_TYPE | payload shape |
+ | ------------------------------ | -------------------------------------------------- | ----------------------------------------------------------- |
+ | `render_agent({ agentId })` | (no emit; triggers `bridge` `host:set-agent` path) | — |
+ | `speak({ text, sentiment? })` | `SPEAK` | `{ text, sentiment: clamp(sentiment, -1, 1) }` |
+ | `gesture({ name, duration? })` | `GESTURE` | `{ name, duration: duration \|\| 1.5 }` |
+ | `emote({ trigger, weight? })` | `EMOTE` | `{ trigger, weight: clamp(weight, 0, 1) }` |
+ | `look_at({ target })` | `LOOK_AT` | `{ target }` (validate against `'model'\|'user'\|'camera'`) |
- Every emit must be tagged `sourceSkill: 'lobehub-host'` so the outbound relay filters it out (no loops).
+ Every emit must be tagged `sourceSkill: 'lobehub-host'` so the outbound relay filters it out (no loops).
3. **Outbound mapping** (protocol event → host envelope):
- - Subscribe to `protocol.on('*', handler)`.
- - Skip events whose `sourceSkill === 'lobehub-host'` (loop guard).
- - Skip high-frequency internal events (`load-start` and `load-end` are **allowed**; per-frame morph lerps **never** reach the protocol anyway).
- - Translate the canonical action shape into `{ v: 1, ns: '3d-agent', type: 'embed:action', payload: { action: { type, payload, sourceSkill, timestamp, agentId } } }`.
- - Post via the bridge.
+ - Subscribe to `protocol.on('*', handler)`.
+ - Skip events whose `sourceSkill === 'lobehub-host'` (loop guard).
+ - Skip high-frequency internal events (`load-start` and `load-end` are **allowed**; per-frame morph lerps **never** reach the protocol anyway).
+ - Translate the canonical action shape into `{ v: 1, ns: '3d-agent', type: 'embed:action', payload: { action: { type, payload, sourceSkill, timestamp, agentId } } }`.
+ - Post via the bridge.
4. **Tool-result replies** — when an inbound tool call carried an envelope `id`, post back `{ type: 'embed:tool-result', id, payload: { ok: true, ... } }` once the corresponding protocol event has fired (or after a short timeout with `{ ok: false, error: 'timed-out' }`). This is how LobeHub's chat model closes the tool-call round trip.
5. **Signed actions surface** — when the avatar emits `SIGN` (agent signs an action with its wallet per [03](./03-host-auth-handoff.md) + ERC-8004), the outbound `embed:action` envelope must include `signature`, `address`, and `chainId` from the payload. Downstream task [05](./05-plugin-submission.md) covers the chat-UI representation.
@@ -67,9 +67,9 @@ Wire bidirectional, lossless relay between LobeHub's chat tool-call surface and
1. `node --check src/embed-action-relay.js` passes.
2. `npx vite build` succeeds.
3. Ad-hoc test harness (do not commit): a small HTML page that iframes the embed, sends the five tool calls in order, and asserts:
- - Each produces the expected protocol emission (observe via debug global `window.VIEWER.agent_protocol.history`).
- - Each produces an `embed:action` mirror back out (listen in parent).
- - No loop — count of host-originated events in history === count sent.
+ - Each produces the expected protocol emission (observe via debug global `window.VIEWER.agent_protocol.history`).
+ - Each produces an `embed:action` mirror back out (listen in parent).
+ - No loop — count of host-originated events in history === count sent.
4. Trigger a skill from inside the avatar (e.g. `protocol.emit({ type: 'speak', payload: { text: 'hi', sentiment: 0.5 }, agentId: ... })` from devtools) and confirm it surfaces back to parent as `embed:action`.
5. Trigger an unknown tool `{ type: 'tool', name: 'nope' }` — confirm `embed:tool-result { ok: false, error: 'unknown-tool' }`.
6. Open the agent log in the parent frame; confirm the action timeline matches [agent-home](../../src/agent-home.js) style (types + timestamps).
diff --git a/prompts/lobehub-embed/05-plugin-submission.md b/prompts/lobehub-embed/05-plugin-submission.md
index 26bd4bf2c..ea32ad008 100644
--- a/prompts/lobehub-embed/05-plugin-submission.md
+++ b/prompts/lobehub-embed/05-plugin-submission.md
@@ -20,19 +20,19 @@ Produce everything needed to (a) reproduce a green local smoke test of the plugi
## Deliverable
1. **Local-test harness** under `prompts/lobehub-embed/fixtures/`:
- - `sample-lobehub-config.json` — a LobeHub plugin-install descriptor pointing at `https://3dagent.vercel.app/.well-known/lobehub-plugin.json` (or a local dev URL).
- - `mock-host.html` — a standalone page that mimics the LobeHub host frame: iframes our embed, sends the full handshake sequence (`host:hello` → `host:identity` → `host:action` samples), logs replies. Use for offline testing.
- - `smoke.md` — a step-by-step manual smoke test script (10–15 steps) covering: install, open agent, chat sends tool call, avatar speaks with emotion, wallet link prompt, signed action surfaces back to transcript.
+ - `sample-lobehub-config.json` — a LobeHub plugin-install descriptor pointing at `https://3dagent.vercel.app/.well-known/lobehub-plugin.json` (or a local dev URL).
+ - `mock-host.html` — a standalone page that mimics the LobeHub host frame: iframes our embed, sends the full handshake sequence (`host:hello` → `host:identity` → `host:action` samples), logs replies. Use for offline testing.
+ - `smoke.md` — a step-by-step manual smoke test script (10–15 steps) covering: install, open agent, chat sends tool call, avatar speaks with emotion, wallet link prompt, signed action surfaces back to transcript.
2. **Submission bundle** under `prompts/lobehub-embed/submission/`:
- - `PR_DESCRIPTION.md` — marketplace PR body. Must include:
- - What the plugin does (2–3 sentence pitch focused on embodied + Empathy Layer)
- - Why users want it (scenarios: paste an agent id in chat, see a 3D avatar react emotionally, sign onchain actions via ERC-8004)
- - Compliance statement (no arbitrary code execution in host, no data exfiltration, origin-checked `postMessage`)
- - Link to the hosted manifest
- - Link to a demo video / GIF (placeholder URL the maintainer fills in)
- - Maintainer contact
- - `SCREENSHOTS.md` — a script (not actual images) describing the five screenshots to capture: (1) install dialog, (2) agent rendered in a chat bubble, (3) avatar mid-gesture, (4) emotion blend visible (concerned face), (5) signed-action receipt in transcript. For each, list the URL, window size, and visible elements.
- - `DEMO_SCRIPT.md` — 60-second walkthrough script for recording a demo GIF/MP4. Word-for-word spoken lines optional.
+ - `PR_DESCRIPTION.md` — marketplace PR body. Must include:
+ - What the plugin does (2–3 sentence pitch focused on embodied + Empathy Layer)
+ - Why users want it (scenarios: paste an agent id in chat, see a 3D avatar react emotionally, sign onchain actions via ERC-8004)
+ - Compliance statement (no arbitrary code execution in host, no data exfiltration, origin-checked `postMessage`)
+ - Link to the hosted manifest
+ - Link to a demo video / GIF (placeholder URL the maintainer fills in)
+ - Maintainer contact
+ - `SCREENSHOTS.md` — a script (not actual images) describing the five screenshots to capture: (1) install dialog, (2) agent rendered in a chat bubble, (3) avatar mid-gesture, (4) emotion blend visible (concerned face), (5) signed-action receipt in transcript. For each, list the URL, window size, and visible elements.
+ - `DEMO_SCRIPT.md` — 60-second walkthrough script for recording a demo GIF/MP4. Word-for-word spoken lines optional.
3. **Tracking metadata** — add a single line to `public/.well-known/lobehub-plugin.json` (if not already present): `"marketplaceStatus": "pending"` (string), updated to `"listed"` post-acceptance.
4. **Release notes stub** — append a `## v0.1.0 — LobeHub plugin` section to the repo's existing CHANGELOG if one exists; otherwise note its absence in the report.
@@ -58,8 +58,8 @@ Produce everything needed to (a) reproduce a green local smoke test of the plugi
## Verification
1. All fixture files parse:
- - `node -e "JSON.parse(require('fs').readFileSync('prompts/lobehub-embed/fixtures/sample-lobehub-config.json','utf8'))"`
- - Open `mock-host.html` in a browser; confirm it loads and sends the handshake without errors.
+ - `node -e "JSON.parse(require('fs').readFileSync('prompts/lobehub-embed/fixtures/sample-lobehub-config.json','utf8'))"`
+ - Open `mock-host.html` in a browser; confirm it loads and sends the handshake without errors.
2. Run `smoke.md` end-to-end, cross off each step, paste the transcript into the report.
3. `npx vite build` still succeeds — fixture files outside `public/` must not interfere with the build.
4. `node --check` passes on any JS touched (probably none for this task).
diff --git a/prompts/lobehub-embed/06-host-sdk-package.md b/prompts/lobehub-embed/06-host-sdk-package.md
index 956f6a726..f277e1b06 100644
--- a/prompts/lobehub-embed/06-host-sdk-package.md
+++ b/prompts/lobehub-embed/06-host-sdk-package.md
@@ -3,6 +3,7 @@
## Why
Every host (LobeHub, Claude Artifact, a third-party chat) needs the same surface area:
+
```js
import { mountAgent } from '@3dagent/embed';
const handle = mountAgent(element, { agentId: 'agt_abc' });
@@ -50,15 +51,15 @@ export interface AgentHandle {
}
export interface MountOptions {
- agentId?: string;
- agentAddress?: string;
- agentName?: string;
- src?: string; // manifest URL alternative
- origin?: string; // default 'https://3dagent.vercel.app'
+ agentId?: string;
+ agentAddress?: string;
+ agentName?: string;
+ src?: string; // manifest URL alternative
+ origin?: string; // default 'https://3dagent.vercel.app'
transparentBg?: boolean;
- kiosk?: boolean;
- width?: string; // default '100%'
- height?: string; // default '100%'
+ kiosk?: boolean;
+ width?: string; // default '100%'
+ height?: string; // default '100%'
}
export function mountAgent(target: HTMLElement, opts: MountOptions): AgentHandle;
@@ -69,12 +70,14 @@ export function mountAgent(target: HTMLElement, opts: MountOptions): AgentHandle
The package creates an iframe (`origin + '/agent/' + id + '/embed'`) inside `target` and bridges via `postMessage`. The bridge vocabulary already exists in [public/agent/embed.html](../../public/agent/embed.html) — reuse it verbatim.
Events (`event.data.type`):
+
- `ready` — iframe loaded, agent mounted
- `speak` — `{ text, sentiment }`
- `action` — `{ type, payload }`
- `error` — `{ message, code }`
Imperative methods post messages:
+
- `say(text)` → `{ type: 'say', text }`
- `playClip(name)` → `{ type: 'play-clip', name }`
- `setExpression(name, weight)` → `{ type: 'expression', name, weight }`
@@ -101,7 +104,7 @@ Also produce an IIFE build at `packages/embed/dist/embed.iife.js` and host under
```html
<script src="https://3dagent.vercel.app/dist-lib/embed.iife.js"></script>
<script>
- window.Agent3D.mountAgent(document.getElementById('stage'), { agentAddress: '0xabc…' });
+ window.Agent3D.mountAgent(document.getElementById('stage'), { agentAddress: '0xabc…' });
</script>
```
diff --git a/prompts/lobehub-embed/07-message-renderer.md b/prompts/lobehub-embed/07-message-renderer.md
index a2099715e..4f6b0c63c 100644
--- a/prompts/lobehub-embed/07-message-renderer.md
+++ b/prompts/lobehub-embed/07-message-renderer.md
@@ -7,7 +7,7 @@ LobeHub's chat renders messages as React components. When a message contains an
## Depends on
- Task 01 (SDK) shipped or pinned via git URL.
-- LobeHub fork checked out on the user's side (we write *against* its conventions, not *in* its repo).
+- LobeHub fork checked out on the user's side (we write _against_ its conventions, not _in_ its repo).
## Read first
@@ -50,7 +50,7 @@ export function AgentMention({ query }: { query: string }) {
function resolveQueryToOpts(q: string) {
if (q.startsWith('agt_')) return { agentId: q };
- if (q.startsWith('0x')) return { agentAddress: q };
+ if (q.startsWith('0x')) return { agentAddress: q };
return { agentName: q };
}
```
diff --git a/prompts/lobehub-embed/08-mention-autocomplete.md b/prompts/lobehub-embed/08-mention-autocomplete.md
index 74931a1df..a509daff2 100644
--- a/prompts/lobehub-embed/08-mention-autocomplete.md
+++ b/prompts/lobehub-embed/08-mention-autocomplete.md
@@ -21,13 +21,13 @@ Task 03 shipped.
- Query: `?q=<prefix>&limit=8`.
- Public endpoint. CORS open.
- Returns:
- ```json
- { agents: [ { id, name, avatar_thumb, address, ens?: string }, … ] }
- ```
+ ```json
+ { agents: [ { id, name, avatar_thumb, address, ens?: string }, … ] }
+ ```
- Ranking:
- 1. Prefix match on ENS / Basename
- 2. Prefix match on agent name
- 3. Recent usage (stretch — MVP can skip this)
+ 1. Prefix match on ENS / Basename
+ 2. Prefix match on agent name
+ 3. Recent usage (stretch — MVP can skip this)
- Cache 60 seconds.
### 2. Input plugin in LobeHub
@@ -40,13 +40,13 @@ export const agentMentionRule = {
async suggest(query: string) {
const res = await fetch(`${ORIGIN}/api/agents/suggest?q=${query}`);
const { agents } = await res.json();
- return agents.map(a => ({
- id: a.id,
+ return agents.map((a) => ({
+ id: a.id,
label: a.ens ?? a.name,
avatar: a.avatar_thumb,
insert: a.ens ? `@${a.ens}` : `@${a.id}`,
}));
- }
+ },
};
```
@@ -55,6 +55,7 @@ Attach to whichever mention plugin LobeHub already ships (tiptap / slate / quill
### 3. Preview in the suggest menu
Each row shows:
+
- Avatar thumbnail (24×24)
- Name / ENS (bold if exact match)
- Short description (muted, truncated)
diff --git a/prompts/lobehub-embed/AUDIT.md b/prompts/lobehub-embed/AUDIT.md
index 55c80bff0..86fb5a6c6 100644
--- a/prompts/lobehub-embed/AUDIT.md
+++ b/prompts/lobehub-embed/AUDIT.md
@@ -40,6 +40,7 @@ If the fork is unavailable, note explicitly that the `mock-host.html` fallback f
Files in the folder are `06-host-sdk-package.md`, `07-message-renderer.md`, `08-mention-autocomplete.md`. Their in-file headers say `Task 01`, `Task 03`, `Task 04` respectively. They were clearly authored as a separate 01–04 series ("host SDK sub-stack") and copied in without renumbering.
Evidence:
+
- [06-host-sdk-package.md:1](./06-host-sdk-package.md) → `# Task 01 — @3dagent/embed host SDK package`
- [07-message-renderer.md:1](./07-message-renderer.md) → `# Task 03 — In-chat message renderer`
- [08-mention-autocomplete.md:1](./08-mention-autocomplete.md) → `# Task 04 — @ autocomplete for agents`
diff --git a/prompts/lobehub-embed/README.md b/prompts/lobehub-embed/README.md
index e361903bd..de99e3ead 100644
--- a/prompts/lobehub-embed/README.md
+++ b/prompts/lobehub-embed/README.md
@@ -6,11 +6,11 @@ Priority 5 in the [top-level stack](../README.md). One of two parallel host-inte
## Two parallel deliverables in this folder
-| Deliverable | Ships to | Tasks |
-|---|---|---|
-| **Fast path** — mount the avatar in your own LobeHub fork's right sidebar | your fork only, not public | [00-fork-sidebar-fastpath.md](./00-fork-sidebar-fastpath.md) |
-| **Plugin stack** — marketplace plugin so anyone's LobeHub can install | LobeHub plugin marketplace | [01](./01-plugin-manifest.md) → [05](./05-plugin-submission.md) |
-| **Host SDK + mention UX** — `@3dagent/embed` npm package + inline `@mentions` + autocomplete | npm + your fork | [06](./06-host-sdk-package.md) → [08](./08-mention-autocomplete.md) |
+| Deliverable | Ships to | Tasks |
+| -------------------------------------------------------------------------------------------- | -------------------------- | ------------------------------------------------------------------- |
+| **Fast path** — mount the avatar in your own LobeHub fork's right sidebar | your fork only, not public | [00-fork-sidebar-fastpath.md](./00-fork-sidebar-fastpath.md) |
+| **Plugin stack** — marketplace plugin so anyone's LobeHub can install | LobeHub plugin marketplace | [01](./01-plugin-manifest.md) → [05](./05-plugin-submission.md) |
+| **Host SDK + mention UX** — `@3dagent/embed` npm package + inline `@mentions` + autocomplete | npm + your fork | [06](./06-host-sdk-package.md) → [08](./08-mention-autocomplete.md) |
Dispatch **task 00 first** — it ships the demo today. Then pick plugin, SDK, or both.
@@ -20,17 +20,17 @@ LobeHub is the **primary** integration target for embodied-agent rendering insid
## Task index
-| # | File | What it ships | Blocks on |
-|---|---|---|---|
-| 00 | [00-fork-sidebar-fastpath.md](./00-fork-sidebar-fastpath.md) | Iframe mounted in the fork's right sidebar; persistent; reacts to chat stream | nothing |
-| 01 | [01-plugin-manifest.md](./01-plugin-manifest.md) | `.well-known/lobehub-plugin.json` manifest hosted publicly | resolving `TODO(lobehub-spec)` flags (see AUDIT.md §6) |
-| 02 | [02-iframe-handshake.md](./02-iframe-handshake.md) | Versioned `postMessage` bridge module `src/embed-host-bridge.js` | 01 |
-| 03 | [03-host-auth-handoff.md](./03-host-auth-handoff.md) | Anon / host-user / wallet-linked identity tiers with opt-in SIWE prompt | 02 |
-| 04 | [04-action-passthrough.md](./04-action-passthrough.md) | Bidirectional chat-tool ↔ protocol relay `src/embed-action-relay.js` | 02, 03 |
-| 05 | [05-plugin-submission.md](./05-plugin-submission.md) | Marketplace submission bundle + smoke test fixtures | 01–04 |
-| 06 | [06-host-sdk-package.md](./06-host-sdk-package.md) | `@3dagent/embed` npm package (`packages/embed/`) | nothing (can parallel 01–05) |
-| 07 | [07-message-renderer.md](./07-message-renderer.md) | Inline `<AgentMention>` React component for @-tokens in chat | 06 |
-| 08 | [08-mention-autocomplete.md](./08-mention-autocomplete.md) | `@`-trigger suggest menu + `GET /api/agents/suggest` endpoint | 07 |
+| # | File | What it ships | Blocks on |
+| --- | ------------------------------------------------------------ | ----------------------------------------------------------------------------- | ------------------------------------------------------ |
+| 00 | [00-fork-sidebar-fastpath.md](./00-fork-sidebar-fastpath.md) | Iframe mounted in the fork's right sidebar; persistent; reacts to chat stream | nothing |
+| 01 | [01-plugin-manifest.md](./01-plugin-manifest.md) | `.well-known/lobehub-plugin.json` manifest hosted publicly | resolving `TODO(lobehub-spec)` flags (see AUDIT.md §6) |
+| 02 | [02-iframe-handshake.md](./02-iframe-handshake.md) | Versioned `postMessage` bridge module `src/embed-host-bridge.js` | 01 |
+| 03 | [03-host-auth-handoff.md](./03-host-auth-handoff.md) | Anon / host-user / wallet-linked identity tiers with opt-in SIWE prompt | 02 |
+| 04 | [04-action-passthrough.md](./04-action-passthrough.md) | Bidirectional chat-tool ↔ protocol relay `src/embed-action-relay.js` | 02, 03 |
+| 05 | [05-plugin-submission.md](./05-plugin-submission.md) | Marketplace submission bundle + smoke test fixtures | 01–04 |
+| 06 | [06-host-sdk-package.md](./06-host-sdk-package.md) | `@3dagent/embed` npm package (`packages/embed/`) | nothing (can parallel 01–05) |
+| 07 | [07-message-renderer.md](./07-message-renderer.md) | Inline `<AgentMention>` React component for @-tokens in chat | 06 |
+| 08 | [08-mention-autocomplete.md](./08-mention-autocomplete.md) | `@`-trigger suggest menu + `GET /api/agents/suggest` endpoint | 07 |
## Rules that apply to every task in this series
diff --git a/prompts/onboarding-flow/00-README.md b/prompts/onboarding-flow/00-README.md
index c61540372..f5b28f87a 100644
--- a/prompts/onboarding-flow/00-README.md
+++ b/prompts/onboarding-flow/00-README.md
@@ -4,24 +4,24 @@
Restructure the 3D Agent user journey into a clear funnel: **anonymous playground → sign in → create avatar → customize → embed** (with optional on-chain).
-Current state is fragmented: the homepage advertises a 3-step flow that doesn't match what actually works, the `/create` page is wired to a selfie-to-GLB pipeline that isn't functional, and the Avaturn iframe entry point (which *did* work) was removed from the UI during a rewrite. This band of tasks fixes all of it.
+Current state is fragmented: the homepage advertises a 3-step flow that doesn't match what actually works, the `/create` page is wired to a selfie-to-GLB pipeline that isn't functional, and the Avaturn iframe entry point (which _did_ work) was removed from the UI during a rewrite. This band of tasks fixes all of it.
## Principles
-1. **Embed is free and immediate.** Never gate the embed path behind wallet connect or on-chain deployment. On-chain is a *badge upgrade*, not a requirement.
-2. **Anonymous `/app` is the funnel.** Users land, drop a GLB, see it render, *then* hit the "save this" wall that prompts sign-in. Don't force auth before showing the product.
+1. **Embed is free and immediate.** Never gate the embed path behind wallet connect or on-chain deployment. On-chain is a _badge upgrade_, not a requirement.
+2. **Anonymous `/app` is the funnel.** Users land, drop a GLB, see it render, _then_ hit the "save this" wall that prompts sign-in. Don't force auth before showing the product.
3. **One hub page per agent.** After create, user lands on `/agent/:id`. Every action (customize, embed, deploy, edit) returns here.
4. **Selfie-to-GLB is deferred.** The pipeline isn't working. Keep the code (`src/selfie-capture.js`, `src/selfie-pipeline.js`, `api/onboarding/avaturn-session.js`) but unroute it from `/create` and show "Coming Soon" in the UI.
## Task list
-| # | File | Depends on | Ready to delegate? |
-|---|---|---|---|
-| 01 | [01-homepage-how-it-works.md](./01-homepage-how-it-works.md) — rewrite homepage "How It Works" to 4 steps | — | Yes |
-| 02 | [02-create-page-3-cards.md](./02-create-page-3-cards.md) — rewrite `/create` as 3-card picker | 03 | After 03 |
-| 03 | [03-avaturn-iframe-rewire.md](./03-avaturn-iframe-rewire.md) — re-enable Avaturn default-editor iframe | — | Yes |
-| 04 | [04-agent-page-hub.md](./04-agent-page-hub.md) — make `/agent/:id` the action hub | 02, 03 | After 02, 03 |
-| 05 | [05-app-html-sandbox.md](./05-app-html-sandbox.md) — position `/app` as anonymous sandbox + authed editor | — | Yes |
+| # | File | Depends on | Ready to delegate? |
+| --- | --------------------------------------------------------------------------------------------------------- | ---------- | ------------------ |
+| 01 | [01-homepage-how-it-works.md](./01-homepage-how-it-works.md) — rewrite homepage "How It Works" to 4 steps | — | Yes |
+| 02 | [02-create-page-3-cards.md](./02-create-page-3-cards.md) — rewrite `/create` as 3-card picker | 03 | After 03 |
+| 03 | [03-avaturn-iframe-rewire.md](./03-avaturn-iframe-rewire.md) — re-enable Avaturn default-editor iframe | — | Yes |
+| 04 | [04-agent-page-hub.md](./04-agent-page-hub.md) — make `/agent/:id` the action hub | 02, 03 | After 02, 03 |
+| 05 | [05-app-html-sandbox.md](./05-app-html-sandbox.md) — position `/app` as anonymous sandbox + authed editor | — | Yes |
Tasks 01, 03, 05 are independent and can run in parallel. Tasks 02 and 04 depend on 03 completing (they consume the re-wired Avaturn entry).
@@ -36,6 +36,7 @@ Tasks 01, 03, 05 are independent and can run in parallel. Tasks 02 and 04 depend
## Reporting
After each task, report:
+
- Files changed with line counts
- Output of `node --check` on every modified JS file
- Output of `npm run build`
diff --git a/prompts/onboarding-flow/01-homepage-how-it-works.md b/prompts/onboarding-flow/01-homepage-how-it-works.md
index 490e09428..aeccdd148 100644
--- a/prompts/onboarding-flow/01-homepage-how-it-works.md
+++ b/prompts/onboarding-flow/01-homepage-how-it-works.md
@@ -14,20 +14,20 @@ Replace the 3-step "How It Works" section with **4 steps** that accurately descr
Connect your wallet or sign in with email. Your avatars, animations, and on-chain identities are saved to your account.
**Step 02 — Create your avatar**
-Edit a default avatar in our web editor, or drop in your own GLB. Need a model? Try [Avaturn](https://avaturn.me) or [Mixamo](https://mixamo.com). *(Selfie-to-avatar — coming soon.)*
+Edit a default avatar in our web editor, or drop in your own GLB. Need a model? Try [Avaturn](https://avaturn.me) or [Mixamo](https://mixamo.com). _(Selfie-to-avatar — coming soon.)_
**Step 03 — Customize**
Name your agent, pick animations, add voice, and connect a brain. Save once, use everywhere.
**Step 04 — Embed anywhere**
-Generate a widget — one iframe, any site. Works in Notion, Ghost, WordPress, and more. *Optionally claim an on-chain identity via ERC-8004.*
+Generate a widget — one iframe, any site. Works in Notion, Ghost, WordPress, and more. _Optionally claim an on-chain identity via ERC-8004._
## Deliverable
1. Edit [index.html](../../index.html) section `#how-it-works` ([index.html:109-129](../../index.html#L109-L129)). Replace the 3 `.step` divs with 4 new ones containing the copy above.
2. Tweak the hero "Open viewer" ghost CTA copy ([index.html:66](../../index.html#L66)) to better signal the sandbox:
- - Current: `Open viewer`
- - New: `Try the viewer →` with `title="No sign-in needed — drop a GLB and play"` attribute
+ - Current: `Open viewer`
+ - New: `Try the viewer →` with `title="No sign-in needed — drop a GLB and play"` attribute
3. Update the `<meta name="description">` ([index.html:9](../../index.html#L9)) only if the old copy is now stale — otherwise leave it.
4. Verify the `.scroll-reveal` delays still stagger correctly (the JS at [index.html:246-266](../../index.html#L246-L266) picks up all `.scroll-reveal` siblings and assigns delays — no JS changes needed).
@@ -49,6 +49,6 @@ Generate a widget — one iframe, any site. Works in Notion, Ghost, WordPress, a
## Reporting
-- Confirm the diff is *only* to the `#how-it-works` section and the hero ghost CTA.
+- Confirm the diff is _only_ to the `#how-it-works` section and the hero ghost CTA.
- Screenshot or describe the rendered section.
- Any scroll-reveal delay weirdness (there shouldn't be any).
diff --git a/prompts/onboarding-flow/02-create-page-3-cards.md b/prompts/onboarding-flow/02-create-page-3-cards.md
index d1b4c7f71..52ebd4f07 100644
--- a/prompts/onboarding-flow/02-create-page-3-cards.md
+++ b/prompts/onboarding-flow/02-create-page-3-cards.md
@@ -15,40 +15,45 @@ Rewrite the `/create` page body as a 3-card picker. Each card represents an avat
## The 3 cards
### Card 1 — "Use default avatar"
+
- Icon/visual: default avatar thumbnail or abstract avatar illustration
- Title: **Use default avatar**
-- Subtitle: *Edit a ready-made avatar in our web editor. No download required.*
+- Subtitle: _Edit a ready-made avatar in our web editor. No download required._
- CTA: **Open editor**
- Action: calls `AvatarCreator.openDefaultEditor()` (added in task 03). On export → upload GLB via [src/account.js](../../src/account.js) flow → redirect to `/agent/:id`.
### Card 2 — "Upload your own GLB"
+
- Icon/visual: upload arrow or 3D cube illustration
- Title: **Upload your own GLB**
-- Subtitle: *Drop a `.glb` file. Works with any glTF 2.0 model.*
+- Subtitle: _Drop a `.glb` file. Works with any glTF 2.0 model._
- CTA: **Choose file**
- Action: opens hidden `<input type="file" accept=".glb,model/gltf-binary">`. On select → validate (ext + magic bytes `glTF`) → upload via presign → redirect to `/agent/:id`.
-- **Tooltip** (render as `<small>` under the CTA): *Need a model? Try [Avaturn](https://avaturn.me) or [Mixamo](https://mixamo.com).* Links should open in new tabs with `rel="noopener"`.
+- **Tooltip** (render as `<small>` under the CTA): _Need a model? Try [Avaturn](https://avaturn.me) or [Mixamo](https://mixamo.com)._ Links should open in new tabs with `rel="noopener"`.
### Card 3 — "From a selfie" (disabled)
+
- Icon/visual: camera illustration with a faded/greyscale treatment
- Title: **From a selfie**
-- Subtitle: *Turn a photo into a rigged avatar.*
+- Subtitle: _Turn a photo into a rigged avatar._
- Badge: **Coming Soon** (top-right corner of card)
- Action: no click handler. Card has `aria-disabled="true"` and does not receive keyboard focus.
## Deliverable
1. **Rewrite [create.html](../../create.html)**:
- - Replace the current selfie-capture template ([create.html:308-368](../../create.html#L308-L368) and any surrounding method-selection HTML) with a `<section class="create-picker">` containing three `<button class="create-card">` elements (or `<div>` for the disabled one).
- - Keep the existing `<header>` and overall page chrome.
- - Do **not** delete [src/selfie-capture.js](../../src/selfie-capture.js) or [src/selfie-pipeline.js](../../src/selfie-pipeline.js). Just unroute them.
+
+ - Replace the current selfie-capture template ([create.html:308-368](../../create.html#L308-L368) and any surrounding method-selection HTML) with a `<section class="create-picker">` containing three `<button class="create-card">` elements (or `<div>` for the disabled one).
+ - Keep the existing `<header>` and overall page chrome.
+ - Do **not** delete [src/selfie-capture.js](../../src/selfie-capture.js) or [src/selfie-pipeline.js](../../src/selfie-pipeline.js). Just unroute them.
2. **New file: `src/create.js`** (the page controller). Wires the three cards:
- - Card 1 → instantiates `AvatarCreator` with an `onExport` callback that POSTs the Blob through the presign + upload + `/api/agents/me` create flow (mirror what [src/account.js](../../src/account.js) does in the save path — factor a shared helper if clean).
- - Card 2 → file input handler, validates, uploads, creates agent.
- - Card 3 → no handler.
- - On successful avatar save: `window.location.href = '/agent/' + agentId`.
- - Use [src/account.js](../../src/account.js) `readAuthHint()` to check auth; if unauthed, redirect to `/login?next=/create`.
+
+ - Card 1 → instantiates `AvatarCreator` with an `onExport` callback that POSTs the Blob through the presign + upload + `/api/agents/me` create flow (mirror what [src/account.js](../../src/account.js) does in the save path — factor a shared helper if clean).
+ - Card 2 → file input handler, validates, uploads, creates agent.
+ - Card 3 → no handler.
+ - On successful avatar save: `window.location.href = '/agent/' + agentId`.
+ - Use [src/account.js](../../src/account.js) `readAuthHint()` to check auth; if unauthed, redirect to `/login?next=/create`.
3. **CSS** — add minimal styles to [style.css](../../style.css) (or a new `create.css` if you prefer — match the existing pattern in the repo). Cards should be equal-width on desktop, stacked on mobile. Use existing CSS variables from the homepage so the visual language matches.
@@ -68,10 +73,10 @@ Rewrite the `/create` page body as a 3-card picker. Each card represents an avat
- [ ] `npm run build` passes
- [ ] `node --check create.html` — actually, HTML doesn't need `node --check`; just ensure `src/create.js` parses: `node --check src/create.js`
- [ ] `localhost:3000/create`:
- - Three cards visible, equal width on desktop
- - Card 1 opens the Avaturn iframe modal (via task 03's `openDefaultEditor`)
- - Card 2 opens a file picker; uploading a valid GLB redirects to `/agent/:id`
- - Card 3 shows "Coming Soon" badge, doesn't open anything when clicked
+ - Three cards visible, equal width on desktop
+ - Card 1 opens the Avaturn iframe modal (via task 03's `openDefaultEditor`)
+ - Card 2 opens a file picker; uploading a valid GLB redirects to `/agent/:id`
+ - Card 3 shows "Coming Soon" badge, doesn't open anything when clicked
- [ ] Unauthed user visiting `/create` redirects to `/login?next=/create`
- [ ] Authenticated user after export lands on `/agent/:id` with the correct avatar loaded
diff --git a/prompts/onboarding-flow/03-avaturn-iframe-rewire.md b/prompts/onboarding-flow/03-avaturn-iframe-rewire.md
index 06b51d045..8a336c7d5 100644
--- a/prompts/onboarding-flow/03-avaturn-iframe-rewire.md
+++ b/prompts/onboarding-flow/03-avaturn-iframe-rewire.md
@@ -15,11 +15,12 @@ Add `AvatarCreator.openDefaultEditor()` — a new entry point that loads Avaturn
## Deliverable
1. **Add `openDefaultEditor()` method to `AvatarCreator`** in [src/avatar-creator.js](../../src/avatar-creator.js):
- - Resolve the default editor URL from env: `VITE_AVATURN_EDITOR_URL` with fallback (confirm the correct public URL against [docs/avaturn-docs.md](../../docs/avaturn-docs.md) — likely `https://editor.avaturn.me/` or similar; if uncertain, make the URL configurable via env and document the expected value).
- - Set `this._avaturnMode = true`, `this._avaturnOrigin = new URL(defaultUrl).origin`.
- - Build modal via existing `_buildModal()`.
- - Set `this.iframe.src = defaultUrl`.
- - Register `message` listener via existing pathway.
+
+ - Resolve the default editor URL from env: `VITE_AVATURN_EDITOR_URL` with fallback (confirm the correct public URL against [docs/avaturn-docs.md](../../docs/avaturn-docs.md) — likely `https://editor.avaturn.me/` or similar; if uncertain, make the URL configurable via env and document the expected value).
+ - Set `this._avaturnMode = true`, `this._avaturnOrigin = new URL(defaultUrl).origin`.
+ - Build modal via existing `_buildModal()`.
+ - Set `this.iframe.src = defaultUrl`.
+ - Register `message` listener via existing pathway.
2. **If Avaturn requires a public developer ID / SDK key** in the URL querystring, add it via env `VITE_AVATURN_DEVELOPER_ID`. Document both env vars in [.env.example](../../.env.example).
@@ -31,12 +32,12 @@ Add `AvatarCreator.openDefaultEditor()` — a new entry point that loads Avaturn
```js
const creator = new AvatarCreator(document.body, async (glb) => {
- // glb is a Blob, type 'model/gltf-binary'
- await uploadGlbToAccount(glb);
+ // glb is a Blob, type 'model/gltf-binary'
+ await uploadGlbToAccount(glb);
});
-await creator.openDefaultEditor(); // NEW — no args, opens default editor
+await creator.openDefaultEditor(); // NEW — no args, opens default editor
// or still valid:
-await creator.open(someSessionUrl); // session-based (selfie flow, deferred)
+await creator.open(someSessionUrl); // session-based (selfie flow, deferred)
```
## Constraints
diff --git a/prompts/onboarding-flow/04-agent-page-hub.md b/prompts/onboarding-flow/04-agent-page-hub.md
index 18ff1f6f5..ee09a1fe2 100644
--- a/prompts/onboarding-flow/04-agent-page-hub.md
+++ b/prompts/onboarding-flow/04-agent-page-hub.md
@@ -17,31 +17,35 @@ Add a primary actions row to the agent hub page with four CTAs. Each CTA either
## The four actions
### 1. Customize
+
- **Label:** Customize
- **Icon:** gear / slider
- **Action:** navigate to `/app?agent=:id` (the authenticated editing surface — see task 05)
- **Always enabled** when user owns the agent
### 2. Embed
+
- **Label:** Embed
- **Icon:** code brackets `</>`
- **Action:** open an "Embed" modal with copy-to-clipboard for:
- - **iframe snippet** — `<iframe src="https://3dagent.vercel.app/agent/:id" width="400" height="600" frameborder="0"></iframe>`
- - **web component snippet** — `<agent-3d agent-id=":id"></agent-3d>` plus `<script src="https://3dagent.vercel.app/agent-3d.js"></script>`
+ - **iframe snippet** — `<iframe src="https://3dagent.vercel.app/agent/:id" width="400" height="600" frameborder="0"></iframe>`
+ - **web component snippet** — `<agent-3d agent-id=":id"></agent-3d>` plus `<script src="https://3dagent.vercel.app/agent-3d.js"></script>`
- **Always enabled** — never gated behind on-chain or wallet
- Uses existing `<agent-3d>` component at [src/element.js:183](../../src/element.js#L183)
### 3. Deploy on-chain
-- **Label:** Deploy on-chain · *Optional*
+
+- **Label:** Deploy on-chain · _Optional_
- **Icon:** chain link
- **Action:** open the existing ERC-8004 register flow at [src/erc8004/register-ui.js](../../src/erc8004/register-ui.js)
- **States:**
- - Not deployed → "Deploy on-chain"
- - Deploying → disabled spinner
- - Deployed → chip showing chain name + shortened address, clicking opens the registry record
+ - Not deployed → "Deploy on-chain"
+ - Deploying → disabled spinner
+ - Deployed → chip showing chain name + shortened address, clicking opens the registry record
- **Gated:** requires wallet connect; show "Connect wallet first" if no wallet session
### 4. Edit avatar
+
- **Label:** Edit avatar
- **Icon:** pencil
- **Action:** navigate to `/agent/:id/edit` (existing page at [public/agent-edit/](../../public/agent-edit/)) OR open the "swap GLB" flow re-using [src/avatar-creator.js](../../src/avatar-creator.js) — pick whichever matches the current state of that page. If `/agent/:id/edit` exists and loads cleanly, link there. Otherwise, open the material/texture editor from [src/editor/](../../src/editor/) in a modal.
@@ -49,19 +53,22 @@ Add a primary actions row to the agent hub page with four CTAs. Each CTA either
## Deliverable
1. **Modify [src/agent-home.js](../../src/agent-home.js)** (or create [src/agent-hub-actions.js](../../src/agent-hub-actions.js) if cleaner):
- - Render a `<div class="agent-hub-actions">` row with the four CTAs above.
- - Place it above the timeline, below the identity card.
- - Each CTA is a `<button>` with icon + label. Use inline SVG for icons (consistent with the existing nav icons).
+
+ - Render a `<div class="agent-hub-actions">` row with the four CTAs above.
+ - Place it above the timeline, below the identity card.
+ - Each CTA is a `<button>` with icon + label. Use inline SVG for icons (consistent with the existing nav icons).
2. **Embed modal** — new component, likely [src/agent-embed-modal.js](../../src/agent-embed-modal.js):
- - Renders the two snippets with syntax highlighting (reuse the `code-block` pattern from [index.html:135-149](../../index.html#L135-L149) if possible).
- - Copy-to-clipboard buttons (use `navigator.clipboard.writeText`).
- - Close via backdrop click, Esc key, or explicit close button (mirror [src/avatar-creator.js:166-173](../../src/avatar-creator.js#L166-L173) pattern).
+
+ - Renders the two snippets with syntax highlighting (reuse the `code-block` pattern from [index.html:135-149](../../index.html#L135-L149) if possible).
+ - Copy-to-clipboard buttons (use `navigator.clipboard.writeText`).
+ - Close via backdrop click, Esc key, or explicit close button (mirror [src/avatar-creator.js:166-173](../../src/avatar-creator.js#L166-L173) pattern).
3. **On-chain state hydration:**
- - Check `agent_identities.chainId` + `chainAddress` columns via [api/agents.js](../../api/agents.js) GET response.
- - If present → render "Deployed" chip. If absent → render "Deploy on-chain" button.
- - Button click → existing flow at [src/erc8004/register-ui.js](../../src/erc8004/register-ui.js).
+
+ - Check `agent_identities.chainId` + `chainAddress` columns via [api/agents.js](../../api/agents.js) GET response.
+ - If present → render "Deployed" chip. If absent → render "Deploy on-chain" button.
+ - Button click → existing flow at [src/erc8004/register-ui.js](../../src/erc8004/register-ui.js).
4. **Hide actions if viewer is not the owner** — check against `session.address` or `session.userId` vs agent.`ownerAddress` / `ownerUserId`. Non-owners see a read-only view (current behavior).
@@ -78,11 +85,11 @@ Add a primary actions row to the agent hub page with four CTAs. Each CTA either
- [ ] `node --check` on all modified JS files
- [ ] `npm run build` passes
- [ ] Navigate to `/agent/:id` as the owner:
- - Four action buttons render above the timeline
- - Customize → `/app?agent=:id`
- - Embed → modal opens with two copy-able snippets; copy-to-clipboard works
- - Deploy on-chain → opens register UI if not deployed; shows chip if deployed
- - Edit avatar → navigates to `/agent/:id/edit` (or opens material editor modal)
+ - Four action buttons render above the timeline
+ - Customize → `/app?agent=:id`
+ - Embed → modal opens with two copy-able snippets; copy-to-clipboard works
+ - Deploy on-chain → opens register UI if not deployed; shows chip if deployed
+ - Edit avatar → navigates to `/agent/:id/edit` (or opens material editor modal)
- [ ] As a non-owner visitor, the action row is hidden but the identity card + timeline still render
- [ ] Embed works on a fresh agent that has never been deployed on-chain (prove the non-gating)
diff --git a/prompts/onboarding-flow/05-app-html-sandbox.md b/prompts/onboarding-flow/05-app-html-sandbox.md
index 8a772fd9b..2b87e6a82 100644
--- a/prompts/onboarding-flow/05-app-html-sandbox.md
+++ b/prompts/onboarding-flow/05-app-html-sandbox.md
@@ -16,35 +16,39 @@ Make `/app` work seamlessly for both anonymous drop-a-GLB users and authenticate
## Deliverable
1. **Edit [app.html](../../app.html):**
- - Remove the `/app#register` nav link ([app.html:45](../../app.html#L45)). On-chain deployment now lives on the agent hub page, not as a viewer nav item.
- - Add a persistent "Save to account" CTA in the header area, visible *only* when a GLB is loaded (anonymous or authed). Mirror the `.make-widget-btn` pattern at [app.html:46-49](../../app.html#L46-L49).
+
+ - Remove the `/app#register` nav link ([app.html:45](../../app.html#L45)). On-chain deployment now lives on the agent hub page, not as a viewer nav item.
+ - Add a persistent "Save to account" CTA in the header area, visible _only_ when a GLB is loaded (anonymous or authed). Mirror the `.make-widget-btn` pattern at [app.html:46-49](../../app.html#L46-L49).
2. **Edit [src/app.js](../../src/app.js):**
- - Parse a new URL query/hash param: `agent=<id>`. Add to the list at [src/CLAUDE.md#L60](../../src/CLAUDE.md) (Agent URL hash keys).
- - When `agent=:id` is present: fetch `/api/agents/:id`, hydrate `manifest.body.uri` as the loaded GLB, and tag the session as "editing agent :id" (so save-back updates that agent, not creates a new one).
- - When absent: current anonymous behavior is preserved — drop GLB, play, no persistence.
+
+ - Parse a new URL query/hash param: `agent=<id>`. Add to the list at [src/CLAUDE.md#L60](../../src/CLAUDE.md) (Agent URL hash keys).
+ - When `agent=:id` is present: fetch `/api/agents/:id`, hydrate `manifest.body.uri` as the loaded GLB, and tag the session as "editing agent :id" (so save-back updates that agent, not creates a new one).
+ - When absent: current anonymous behavior is preserved — drop GLB, play, no persistence.
3. **Save-to-account CTA behavior:**
- - **Anonymous user, clicks Save:**
- - Stash current GLB + config in `sessionStorage` under key `pending_save`:
- ```json
- { "glbUrl": "blob:...", "manifest": { ... }, "returnTo": "/app" }
- ```
- - Redirect to `/login?next=/app?pending=1`.
- - **Authenticated user with no `?agent`:**
- - Create new avatar + agent via `/api/avatars/presign` → PUT → `/api/agents/me` POST.
- - Redirect to `/agent/:id` (the hub).
- - **Authenticated user with `?agent=:id`:**
- - PATCH the existing agent's avatar (use the versioning endpoint if it exists; otherwise re-upload and PUT).
- - Redirect to `/agent/:id`.
+
+ - **Anonymous user, clicks Save:**
+ - Stash current GLB + config in `sessionStorage` under key `pending_save`:
+ ```json
+ { "glbUrl": "blob:...", "manifest": { ... }, "returnTo": "/app" }
+ ```
+ - Redirect to `/login?next=/app?pending=1`.
+ - **Authenticated user with no `?agent`:**
+ - Create new avatar + agent via `/api/avatars/presign` → PUT → `/api/agents/me` POST.
+ - Redirect to `/agent/:id` (the hub).
+ - **Authenticated user with `?agent=:id`:**
+ - PATCH the existing agent's avatar (use the versioning endpoint if it exists; otherwise re-upload and PUT).
+ - Redirect to `/agent/:id`.
4. **On `/app` boot, check `sessionStorage.pending_save`:**
- - If present AND user is now authenticated → re-hydrate the GLB + config, trigger the save flow, clear the stash.
- - If present but still unauthed → no-op (they cancelled auth).
+
+ - If present AND user is now authenticated → re-hydrate the GLB + config, trigger the save flow, clear the stash.
+ - If present but still unauthed → no-op (they cancelled auth).
5. **Keep the existing "Make this a widget" button** ([app.html:46-49](../../app.html#L46-L49)):
- - For anonymous users, it prompts sign-in (same `sessionStorage` pattern).
- - For authed users with `?agent=:id`, it creates a widget bound to that agent.
+ - For anonymous users, it prompts sign-in (same `sessionStorage` pattern).
+ - For authed users with `?agent=:id`, it creates a widget bound to that agent.
## Constraints
diff --git a/prompts/onchain/00-README.md b/prompts/onchain/00-README.md
index 5175d4c77..66d0c4a23 100644
--- a/prompts/onchain/00-README.md
+++ b/prompts/onchain/00-README.md
@@ -3,6 +3,7 @@
## The end state
A user's agent exists on-chain. The record contains:
+
- owner wallet
- agent id (also an NFT or ERC-8004 entry)
- GLB URI (IPFS or Arweave for permanence)
@@ -19,13 +20,13 @@ From any host (Claude, LobeHub, the user's personal site, a random iframe on X),
## Prompts in this band
-| # | File | Depends on |
-|---|---|---|
-| 01 | [erc8004-write-flow.md](./01-erc8004-write-flow.md) | contracts deployed |
-| 02 | [ipfs-arweave-pinning.md](./02-ipfs-arweave-pinning.md) | — |
-| 03 | [agent-by-address-resolver.md](./03-agent-by-address-resolver.md) | 01, 02 |
-| 04 | [ens-naming.md](./04-ens-naming.md) | 03 |
-| 05 | [action-provenance-signing.md](./05-action-provenance-signing.md) | band 1 wallet auth |
+| # | File | Depends on |
+| --- | ----------------------------------------------------------------- | ------------------ |
+| 01 | [erc8004-write-flow.md](./01-erc8004-write-flow.md) | contracts deployed |
+| 02 | [ipfs-arweave-pinning.md](./02-ipfs-arweave-pinning.md) | — |
+| 03 | [agent-by-address-resolver.md](./03-agent-by-address-resolver.md) | 01, 02 |
+| 04 | [ens-naming.md](./04-ens-naming.md) | 03 |
+| 05 | [action-provenance-signing.md](./05-action-provenance-signing.md) | band 1 wallet auth |
## Done = merged when
diff --git a/prompts/onchain/01-erc8004-write-flow.md b/prompts/onchain/01-erc8004-write-flow.md
index 11bbc5f8f..9ee8a1e1b 100644
--- a/prompts/onchain/01-erc8004-write-flow.md
+++ b/prompts/onchain/01-erc8004-write-flow.md
@@ -29,18 +29,19 @@ On the agent page, if `agent.owner_user_id === current_user.id` **and** `agent.c
```
Click flow:
+
1. Open modal: "Choose network" — radio list of deployed chains (from step 1). Default to Base Sepolia.
2. Load network for their wallet; prompt to switch if needed.
3. Build the `agentURI` metadata JSON (`buildRegistrationJSON`):
- ```json
- {
- "name": "…",
- "description": "…",
- "avatar": { "uri": "ipfs://<cid>", "mimeType": "model/gltf-binary" },
- "skills": [...],
- "schema": "agent-manifest/0.1"
- }
- ```
+ ```json
+ {
+ "name": "…",
+ "description": "…",
+ "avatar": { "uri": "ipfs://<cid>", "mimeType": "model/gltf-binary" },
+ "skills": [...],
+ "schema": "agent-manifest/0.1"
+ }
+ ```
4. Pin that JSON to IPFS (task 02 wires the pinning; here just call the helper with a clear error if pinning fails).
5. Estimate gas. Show fee preview. Require explicit confirm.
6. Call `IdentityRegistry.register(agentURI)` via ethers.
@@ -52,6 +53,7 @@ Click flow:
### 3. Server endpoint
`POST /api/agents/:id/chain` (auth + owner gate):
+
- Validates `chainId` is a known deployment.
- Validates `agentId` by reading the chain (`IdentityRegistry.getAgent(agentId) == caller`).
- Updates `agent_identities` row.
diff --git a/prompts/onchain/01-hydrate-agent-from-chain.md b/prompts/onchain/01-hydrate-agent-from-chain.md
index 1656ed5e5..f58ba4ea5 100644
--- a/prompts/onchain/01-hydrate-agent-from-chain.md
+++ b/prompts/onchain/01-hydrate-agent-from-chain.md
@@ -13,18 +13,18 @@ Add a read-only hydration path so any caller with `(chainId, agentId)` can build
## Deliverable
1. New file [src/erc8004/hydrate.js](../../src/erc8004/hydrate.js) exporting:
- - `async function hydrateFromChain({ chainId, agentId, rpcURL? })` → returns a **plain record** shaped like `AgentRecord` in [agent-identity.js](../../src/agent-identity.js) (`id`, `name`, `description`, `avatarId` — leave `null` if only a body URI is known, `homeUrl`, `walletAddress`, `chainId`, `skills: []`, `meta`, `createdAt`, `isRegistered: true`). Must also set a `meta.onchain = { chainId, agentId, registryAddr, tokenURI, ownerAddress, agentRegistry }` block.
- - Internally:
- - Resolve registry address via `REGISTRY_DEPLOYMENTS[chainId].identityRegistry`. Throw a typed error (`new Error('unknown-chain')` etc.) if missing.
- - Use `JsonRpcProvider` from `ethers` with the given `rpcURL` or fall back to a known default (extend `DEFAULT_RPCS` in [manifest.js](../../src/manifest.js) if new chains are needed, do **not** fork it — import and reuse).
- - Read `tokenURI(agentId)` and `ownerOf(agentId)` via the identity registry.
- - Resolve the `tokenURI` through [src/ipfs.js](../../src/ipfs.js) `resolveURI` / `fetchWithFallback`, then parse the registration JSON.
- - Pass the JSON through `normalize()` in [src/manifest.js](../../src/manifest.js) to reuse the ERC-8004 adapter (preferred) OR read the relevant fields directly — but if you read directly, cover the ERC-8004 `registrations[]` shape and the nested `image` / `body.uri` fallback.
- - Shape the return value so `AgentIdentity` can consume it without further translation.
+ - `async function hydrateFromChain({ chainId, agentId, rpcURL? })` → returns a **plain record** shaped like `AgentRecord` in [agent-identity.js](../../src/agent-identity.js) (`id`, `name`, `description`, `avatarId` — leave `null` if only a body URI is known, `homeUrl`, `walletAddress`, `chainId`, `skills: []`, `meta`, `createdAt`, `isRegistered: true`). Must also set a `meta.onchain = { chainId, agentId, registryAddr, tokenURI, ownerAddress, agentRegistry }` block.
+ - Internally:
+ - Resolve registry address via `REGISTRY_DEPLOYMENTS[chainId].identityRegistry`. Throw a typed error (`new Error('unknown-chain')` etc.) if missing.
+ - Use `JsonRpcProvider` from `ethers` with the given `rpcURL` or fall back to a known default (extend `DEFAULT_RPCS` in [manifest.js](../../src/manifest.js) if new chains are needed, do **not** fork it — import and reuse).
+ - Read `tokenURI(agentId)` and `ownerOf(agentId)` via the identity registry.
+ - Resolve the `tokenURI` through [src/ipfs.js](../../src/ipfs.js) `resolveURI` / `fetchWithFallback`, then parse the registration JSON.
+ - Pass the JSON through `normalize()` in [src/manifest.js](../../src/manifest.js) to reuse the ERC-8004 adapter (preferred) OR read the relevant fields directly — but if you read directly, cover the ERC-8004 `registrations[]` shape and the nested `image` / `body.uri` fallback.
+ - Shape the return value so `AgentIdentity` can consume it without further translation.
2. Extend [src/agent-identity.js](../../src/agent-identity.js):
- - Add constructor option `{ onchain: { chainId, agentId, rpcURL? } }`.
- - When `onchain` is set and `autoLoad` is true, the internal `_loadAsync` **tries chain first**, falls back to localStorage/backend if chain hydration throws.
- - Add a new method `async hydrateOnchain({ chainId, agentId, rpcURL? })` that callers can invoke later to merge on-chain fields into the current record (merging only non-empty fields — never overwrite a user-set local name/description with an empty on-chain one).
+ - Add constructor option `{ onchain: { chainId, agentId, rpcURL? } }`.
+ - When `onchain` is set and `autoLoad` is true, the internal `_loadAsync` **tries chain first**, falls back to localStorage/backend if chain hydration throws.
+ - Add a new method `async hydrateOnchain({ chainId, agentId, rpcURL? })` that callers can invoke later to merge on-chain fields into the current record (merging only non-empty fields — never overwrite a user-set local name/description with an empty on-chain one).
3. Minimal unit-ish smoke in a REPL (document in the verification block below) — no new test file required.
## Audit checklist
@@ -51,12 +51,12 @@ Add a read-only hydration path so any caller with `(chainId, agentId)` can build
1. `node --check src/erc8004/hydrate.js src/agent-identity.js`.
2. `npx vite build` — passes (ignore `@avaturn/sdk` warning).
3. In a browser console on a running dev server:
- ```js
- const { hydrateFromChain } = await import('/src/erc8004/hydrate.js');
- const rec = await hydrateFromChain({ chainId: 84532, agentId: 1 });
- console.log(rec);
- // Expect: { id: '84532:1', meta: { onchain: { registryAddr: '0x8004A818...', tokenURI: 'ipfs://...', ownerAddress: '0x...' } }, ... }
- ```
+ ```js
+ const { hydrateFromChain } = await import('/src/erc8004/hydrate.js');
+ const rec = await hydrateFromChain({ chainId: 84532, agentId: 1 });
+ console.log(rec);
+ // Expect: { id: '84532:1', meta: { onchain: { registryAddr: '0x8004A818...', tokenURI: 'ipfs://...', ownerAddress: '0x...' } }, ... }
+ ```
4. Use `new AgentIdentity({ agentId: null, autoLoad: false, onchain: { chainId: 84532, agentId: 1 } }); await ident.load();` and confirm the loaded record has `isRegistered === true` and `meta.onchain.tokenURI` set.
5. Negative case: pass `agentId: 99999999` on a testnet and confirm `Error('not-found')`.
diff --git a/prompts/onchain/02-ipfs-arweave-pinning.md b/prompts/onchain/02-ipfs-arweave-pinning.md
index 4a0c5094d..274789e1f 100644
--- a/prompts/onchain/02-ipfs-arweave-pinning.md
+++ b/prompts/onchain/02-ipfs-arweave-pinning.md
@@ -20,6 +20,7 @@ Must support: JSON pins + binary (GLB) pins, dashboard, API keys, free tier. Rec
### 2. Server endpoint
`POST /api/pin` (auth required):
+
```
body: { kind: 'json' | 'glb', uri?: string, data?: object, contentType?: string }
```
diff --git a/prompts/onchain/02-wallet-to-agents.md b/prompts/onchain/02-wallet-to-agents.md
index 87e7525c8..0746730bc 100644
--- a/prompts/onchain/02-wallet-to-agents.md
+++ b/prompts/onchain/02-wallet-to-agents.md
@@ -15,15 +15,15 @@ Add a read-only function that takes `(walletAddress, chainId)` and returns an ar
## Deliverable
1. New file [src/erc8004/wallet-agents.js](../../src/erc8004/wallet-agents.js) exporting:
- - `async function listAgentsByOwner({ owner, chainId, rpcURL?, fromBlock? })` → `Promise<{ agentId: bigint, tokenURI: string | null }[]>`
- - `async function listAgentsAcrossChains({ owner, chainIds?, rpcURL? })` → `Promise<{ chainId, agents }[]>` — defaults to iterating every chain in `REGISTRY_DEPLOYMENTS`, concurrency cap of 4.
+ - `async function listAgentsByOwner({ owner, chainId, rpcURL?, fromBlock? })` → `Promise<{ agentId: bigint, tokenURI: string | null }[]>`
+ - `async function listAgentsAcrossChains({ owner, chainIds?, rpcURL? })` → `Promise<{ chainId, agents }[]>` — defaults to iterating every chain in `REGISTRY_DEPLOYMENTS`, concurrency cap of 4.
2. Strategy inside `listAgentsByOwner`:
- - First pass: call `balanceOf(owner)`. If it returns 0n → return `[]` early.
- - Second pass: scan `Transfer(from, to, tokenId)` where `to === owner` from `fromBlock` (default: chain deployment block if known, else `0`) to `latest`, in chunks of 10_000 blocks (configurable const `LOG_CHUNK = 10_000`), retrying halved on `-32005` / `range too large` errors down to `LOG_CHUNK_MIN = 500`.
- - Collect `tokenId`s where the most recent Transfer whose party is `owner` resulted in `owner` being the `to`. Verify final ownership with `ownerOf(tokenId)` and drop tokens that have since moved.
- - For each surviving token, call `tokenURI(tokenId)` in parallel with a 6-wide limit. Swallow `tokenURI` errors as `tokenURI: null` — a token with no URI is still owned.
+ - First pass: call `balanceOf(owner)`. If it returns 0n → return `[]` early.
+ - Second pass: scan `Transfer(from, to, tokenId)` where `to === owner` from `fromBlock` (default: chain deployment block if known, else `0`) to `latest`, in chunks of 10_000 blocks (configurable const `LOG_CHUNK = 10_000`), retrying halved on `-32005` / `range too large` errors down to `LOG_CHUNK_MIN = 500`.
+ - Collect `tokenId`s where the most recent Transfer whose party is `owner` resulted in `owner` being the `to`. Verify final ownership with `ownerOf(tokenId)` and drop tokens that have since moved.
+ - For each surviving token, call `tokenURI(tokenId)` in parallel with a 6-wide limit. Swallow `tokenURI` errors as `tokenURI: null` — a token with no URI is still owned.
3. Dashboard integration:
- - In [public/dashboard/](../../public/dashboard/), find the module that renders "my agents" (look for the fetch to `/api/agents/me`). Add a secondary list sourced from `listAgentsAcrossChains` for the currently connected wallet, merged with the backend list by `meta.onchain.agentId`. De-dupe: if an agent already shows in the backend list with a matching `(chainId, agentId)`, **don't add it twice**; decorate the backend card with an "on-chain" badge instead.
+ - In [public/dashboard/](../../public/dashboard/), find the module that renders "my agents" (look for the fetch to `/api/agents/me`). Add a secondary list sourced from `listAgentsAcrossChains` for the currently connected wallet, merged with the backend list by `meta.onchain.agentId`. De-dupe: if an agent already shows in the backend list with a matching `(chainId, agentId)`, **don't add it twice**; decorate the backend card with an "on-chain" badge instead.
4. Expose the helper in [src/erc8004/index.js](../../src/erc8004/index.js) (create if missing) as a barrel export next to `registerAgent`.
## Audit checklist
@@ -52,13 +52,15 @@ Add a read-only function that takes `(walletAddress, chainId)` and returns an ar
1. `node --check src/erc8004/wallet-agents.js` plus any file you edited in `public/dashboard/`.
2. `npx vite build` — passes (ignore `@avaturn/sdk`).
3. In a browser console on dev server:
- ```js
- const { listAgentsByOwner, listAgentsAcrossChains } = await import('/src/erc8004/wallet-agents.js');
- const agents = await listAgentsByOwner({ owner: '0x...', chainId: 84532 });
- console.log(agents.length, agents.slice(0,3));
- const all = await listAgentsAcrossChains({ owner: '0x...' });
- console.log(all);
- ```
+ ```js
+ const { listAgentsByOwner, listAgentsAcrossChains } = await import(
+ '/src/erc8004/wallet-agents.js'
+ );
+ const agents = await listAgentsByOwner({ owner: '0x...', chainId: 84532 });
+ console.log(agents.length, agents.slice(0, 3));
+ const all = await listAgentsAcrossChains({ owner: '0x...' });
+ console.log(all);
+ ```
4. On the dashboard, connect a wallet that owns ≥ 1 on-chain agent (use the pre-registered CZ agent after [cz-demo/02](../cz-demo/02-cz-preregistered-agent.md) lands). Confirm it appears with the "on-chain" badge. Confirm backend agents still render.
5. Empty wallet: no crash, empty state shown.
diff --git a/prompts/onchain/03-agent-by-address-resolver.md b/prompts/onchain/03-agent-by-address-resolver.md
index 6b10c5a8e..68d2c6dc5 100644
--- a/prompts/onchain/03-agent-by-address-resolver.md
+++ b/prompts/onchain/03-agent-by-address-resolver.md
@@ -16,23 +16,26 @@ Hosts (Claude, LobeHub) paste a wallet address. We must return the canonical age
### 1. `GET /api/agents/by-address/:addr`
Public (no auth). Accepts:
+
- `0x…` address (EIP-55 or lowercased)
- Optional `?chain=base-sepolia` (default: try every deployed chain in order, first hit wins)
Flow:
+
1. Normalize address to lowercase.
2. Check `agents` cache: `select * from agent_identities where lower(wallet_address) = $1`. If hit and `chain_id` set, return.
3. Otherwise, for each chainId in `REGISTRY_DEPLOYMENTS`:
- - `IdentityRegistry.agentOf(address)` → `agentId` (or 0)
- - If nonzero, `IdentityRegistry.getAgent(agentId)` → `agentURI`
- - Fetch `agentURI` (IPFS → HTTPS gateway fallback, using the `ipfs.js` helper)
- - Build a cache row in `agent_identities` (mark `_source: 'chain'`). Use the metadata's `name`, `description`, `avatar.uri`, `skills`.
- - Return it.
+ - `IdentityRegistry.agentOf(address)` → `agentId` (or 0)
+ - If nonzero, `IdentityRegistry.getAgent(agentId)` → `agentURI`
+ - Fetch `agentURI` (IPFS → HTTPS gateway fallback, using the `ipfs.js` helper)
+ - Build a cache row in `agent_identities` (mark `_source: 'chain'`). Use the metadata's `name`, `description`, `avatar.uri`, `skills`.
+ - Return it.
4. If nothing on any chain, 404 with `{ ok: false, error: 'not_registered' }`.
### 2. Client resolver update
Extend [src/agent-resolver.js](../../src/agent-resolver.js):
+
```js
export async function resolveAgentByAddress(addr, opts) { … }
```
diff --git a/prompts/onchain/03-register-flow-polish.md b/prompts/onchain/03-register-flow-polish.md
index 29dc9e4ac..916eec9eb 100644
--- a/prompts/onchain/03-register-flow-polish.md
+++ b/prompts/onchain/03-register-flow-polish.md
@@ -25,15 +25,15 @@ Make registration feel trustworthy on a live production wallet. Show cost before
In [register-ui.js](../../src/erc8004/register-ui.js), classify errors by a new helper `classifyTxError(err)` (put it in [src/erc8004/errors.js](../../src/erc8004/errors.js), new file) returning `{ code, title, detail, hint }`. Codes to handle:
-| Code | Trigger | User hint |
-|---|---|---|
-| `user-rejected` | `err.code === 4001` or `err.code === 'ACTION_REJECTED'` | "You cancelled the signature." |
-| `insufficient-funds` | `err.code === 'INSUFFICIENT_FUNDS'` or error message matches `/insufficient funds/i` | "This wallet doesn't have enough native token for gas on chain X. Try Base Sepolia testnet." |
-| `chain-mismatch` | network chainId not in `REGISTRY_DEPLOYMENTS` | "ERC-8004 isn't deployed on chain N. Switch to a supported chain." Show a "switch chain" button that calls `wallet_switchEthereumChain`. |
-| `ipfs-no-token` | `pinToIPFS` throws about missing token | "IPFS pinning requires an API token. Paste your web3.storage or Filebase token." |
-| `ipfs-upload-failed` | `pinToIPFS` HTTP error | "IPFS pinning failed ({status}). Try a different token or gateway." |
-| `tx-reverted` | receipt status 0 | "The transaction was mined but reverted — likely a contract-level check." Link to the explorer. |
-| `unknown` | fallback | Show raw message below a collapsible "details" toggle. |
+| Code | Trigger | User hint |
+| -------------------- | ------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- |
+| `user-rejected` | `err.code === 4001` or `err.code === 'ACTION_REJECTED'` | "You cancelled the signature." |
+| `insufficient-funds` | `err.code === 'INSUFFICIENT_FUNDS'` or error message matches `/insufficient funds/i` | "This wallet doesn't have enough native token for gas on chain X. Try Base Sepolia testnet." |
+| `chain-mismatch` | network chainId not in `REGISTRY_DEPLOYMENTS` | "ERC-8004 isn't deployed on chain N. Switch to a supported chain." Show a "switch chain" button that calls `wallet_switchEthereumChain`. |
+| `ipfs-no-token` | `pinToIPFS` throws about missing token | "IPFS pinning requires an API token. Paste your web3.storage or Filebase token." |
+| `ipfs-upload-failed` | `pinToIPFS` HTTP error | "IPFS pinning failed ({status}). Try a different token or gateway." |
+| `tx-reverted` | receipt status 0 | "The transaction was mined but reverted — likely a contract-level check." Link to the explorer. |
+| `unknown` | fallback | Show raw message below a collapsible "details" toggle. |
Render errors as a **card** above the log with title/detail/hint — not a red line in a scrolling log.
@@ -44,10 +44,10 @@ Before the user clicks "Register Agent On-Chain", once wallet is connected + fil
- Estimate gas for `register(string)` using `contract.estimateGas['register(string)'](placeholderURI)` where `placeholderURI` can be `'ipfs://placeholder-for-estimate'`.
- Fetch `getFeeData()` and compute `gasLimit * (maxFeePerGas || gasPrice)`.
- Render under the register button:
- ```
- Est. gas: ~250,000 · Est. cost: 0.0012 ETH (≈ $4.30)
- ```
- ETH→USD conversion is best-effort via `https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd` — silently drop the USD string on fetch failure.
+ ```
+ Est. gas: ~250,000 · Est. cost: 0.0012 ETH (≈ $4.30)
+ ```
+ ETH→USD conversion is best-effort via `https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd` — silently drop the USD string on fetch failure.
- Cache the estimate for 30s; recompute if file or chain changes.
- Add a second line covering the `setAgentURI` step: estimate separately, show as "+ update-URI step: ~0.0003 ETH". Total cost = sum.
@@ -68,11 +68,11 @@ Each step shows `pending | in-progress | done | failed`. Render inside the exist
After success:
1. Re-fetch [public/.well-known/agent-registration.json](../../public/.well-known/agent-registration.json), append to `registrations[]` the `{ agentId, agentRegistry }` the new agent lives at (build via `agentRegistryId(chainId, registryAddr)` from [abi.js](../../src/erc8004/abi.js)), and `PUT` to a **new backend endpoint** [api/well-known-register.js](../../api/well-known-register.js) — new serverless route — that rewrites `public/.well-known/agent-registration.json` on disk (idempotent; no dup entries).
- - If the backend endpoint isn't available (local static preview), fail silently with a console warning — don't block the success UX.
+ - If the backend endpoint isn't available (local static preview), fail silently with a console warning — don't block the success UX.
2. In the result card, add three buttons:
- - **"View agent"** → `window.location.href = '/agent/' + agentId` (the page consumes [01-hydrate-agent-from-chain.md](./01-hydrate-agent-from-chain.md) for chain-only data).
- - **"Copy share link"** → copies `https://3dagent.vercel.app/agent/{agentId}?chain={chainId}`.
- - **"View tx on explorer"** → uses a new `explorerTxURL(chainId, txHash)` helper in [src/erc8004/explorers.js](../../src/erc8004/explorers.js).
+ - **"View agent"** → `window.location.href = '/agent/' + agentId` (the page consumes [01-hydrate-agent-from-chain.md](./01-hydrate-agent-from-chain.md) for chain-only data).
+ - **"Copy share link"** → copies `https://3dagent.vercel.app/agent/{agentId}?chain={chainId}`.
+ - **"View tx on explorer"** → uses a new `explorerTxURL(chainId, txHash)` helper in [src/erc8004/explorers.js](../../src/erc8004/explorers.js).
3. Emit a DOM event on `window`: `window.dispatchEvent(new CustomEvent('agent:registered', { detail: { agentId, chainId, registrationCID, txHash } }))`. Dashboard / other surfaces can listen and refresh.
## Audit checklist
@@ -99,11 +99,11 @@ After success:
1. `node --check` every modified JS file and the new files.
2. `npx vite build` — passes.
3. Manual with MetaMask on Base Sepolia:
- - Connect wallet → name input → attach small GLB. Within a couple of seconds, gas preview line appears.
- - Click Register. Stepper advances 1 → 2, tx hash link appears.
- - Reject the `register(string)` prompt. Error card shows "You cancelled the signature." Register button re-enables.
- - Accept the first tx, watch stepper through 5. Reject the second (`setAgentURI`) → error card explains and lets you retry the URI step only (don't re-mint).
- - After full success, the `.well-known/agent-registration.json` fetch shows the new entry in `registrations[]`.
+ - Connect wallet → name input → attach small GLB. Within a couple of seconds, gas preview line appears.
+ - Click Register. Stepper advances 1 → 2, tx hash link appears.
+ - Reject the `register(string)` prompt. Error card shows "You cancelled the signature." Register button re-enables.
+ - Accept the first tx, watch stepper through 5. Reject the second (`setAgentURI`) → error card explains and lets you retry the URI step only (don't re-mint).
+ - After full success, the `.well-known/agent-registration.json` fetch shows the new entry in `registrations[]`.
4. Insufficient-funds path: switch to Ethereum mainnet on a gas-less wallet, trigger register → clean error card.
## Scope boundaries — do NOT do these
diff --git a/prompts/onchain/04-ens-naming.md b/prompts/onchain/04-ens-naming.md
index 70d00db42..d067ea21d 100644
--- a/prompts/onchain/04-ens-naming.md
+++ b/prompts/onchain/04-ens-naming.md
@@ -39,6 +39,7 @@ When rendering the agent page for someone who arrived via address, do a reverse
### 4. UX on /agent
URL shapes:
+
- `/agent/0xabc…` — address
- `/agent/vitalik.eth` — ENS (redirect to `/agent/<resolved-address>`? or keep the name in the URL? Pick the one that keeps the URL stable across name changes — lean **address-canonical** with a small ENS chip in the header)
diff --git a/prompts/onchain/04-update-agent-uri.md b/prompts/onchain/04-update-agent-uri.md
index f81c99160..32cd00e89 100644
--- a/prompts/onchain/04-update-agent-uri.md
+++ b/prompts/onchain/04-update-agent-uri.md
@@ -18,33 +18,35 @@ Add an idempotent, resumable "update agent URI" flow that runs after avatar-edit
1. New file [src/erc8004/update-agent.js](../../src/erc8004/update-agent.js) exporting:
- ```
- async function updateAgentURI({
- agentId, // number | bigint | string
- chainId,
- newGLB?, // File | Blob — optional; if absent, only re-pin metadata
- nextRecord, // merged patch: { name?, description?, image?, services?, supportedTrust?, ... }
- apiToken,
- signer,
- onStatus, // structured step emitter, same shape as 03
- })
- ```
-
- Flow:
- 1. If `newGLB` is provided → `pinToIPFS(newGLB)` → new `imageCID`.
- 2. Fetch the current `tokenURI(agentId)` from chain; resolve + fetch the current registration JSON (reuse [src/ipfs.js](../../src/ipfs.js) fallback).
- 3. Deep-merge the existing JSON with `nextRecord`, replacing `image` with `ipfs://<imageCID>` when a new GLB was pinned. **Preserve** `registrations[]` exactly — do not rewrite the `agentId`/`agentRegistry` fields.
- 4. Pin the merged JSON → new `registrationCID`.
- 5. Connect contract with `signer`; call `setAgentURI(agentId, 'ipfs://<registrationCID>')`. Return `{ imageCID?, registrationCID, txHash }`.
+ ```
+ async function updateAgentURI({
+ agentId, // number | bigint | string
+ chainId,
+ newGLB?, // File | Blob — optional; if absent, only re-pin metadata
+ nextRecord, // merged patch: { name?, description?, image?, services?, supportedTrust?, ... }
+ apiToken,
+ signer,
+ onStatus, // structured step emitter, same shape as 03
+ })
+ ```
+
+ Flow:
+
+ 1. If `newGLB` is provided → `pinToIPFS(newGLB)` → new `imageCID`.
+ 2. Fetch the current `tokenURI(agentId)` from chain; resolve + fetch the current registration JSON (reuse [src/ipfs.js](../../src/ipfs.js) fallback).
+ 3. Deep-merge the existing JSON with `nextRecord`, replacing `image` with `ipfs://<imageCID>` when a new GLB was pinned. **Preserve** `registrations[]` exactly — do not rewrite the `agentId`/`agentRegistry` fields.
+ 4. Pin the merged JSON → new `registrationCID`.
+ 5. Connect contract with `signer`; call `setAgentURI(agentId, 'ipfs://<registrationCID>')`. Return `{ imageCID?, registrationCID, txHash }`.
+
2. **Idempotence key.** Write to `localStorage` under key `erc8004:update-in-flight:{chainId}:{agentId}` a JSON blob `{ step, imageCID?, registrationCID?, newTokenURI, startedAt }` as the flow progresses. On re-entry with the same `(chainId, agentId)`, the flow:
- - If `step === 'pinning-glb'` and no `imageCID` yet → re-pin.
- - If `step === 'pinning-json'` but `imageCID` already set → skip re-pin of GLB, rebuild & re-pin JSON (OK to re-pin JSON; deterministic content would yield the same CID anyway).
- - If `step === 'sending-tx'` → check if `tokenURI(agentId)` already equals the in-flight `newTokenURI`. If yes → clear the localStorage key, return the record; if no → resend the tx.
- - On terminal success → clear the key.
+ - If `step === 'pinning-glb'` and no `imageCID` yet → re-pin.
+ - If `step === 'pinning-json'` but `imageCID` already set → skip re-pin of GLB, rebuild & re-pin JSON (OK to re-pin JSON; deterministic content would yield the same CID anyway).
+ - If `step === 'sending-tx'` → check if `tokenURI(agentId)` already equals the in-flight `newTokenURI`. If yes → clear the localStorage key, return the record; if no → resend the tx.
+ - On terminal success → clear the key.
3. **Ownership guard.** Before step 5, call `ownerOf(agentId)` and compare to `signer.getAddress()` (case-insensitive checksum). If mismatch, throw `new Error('not-owner')`.
4. Integration point in the avatar-edit flow:
- - In [src/avatar-creator.js](../../src/avatar-creator.js) (or wherever avatar-edit's "save" handler lives — search for the save/confirm callback) add a post-save hook that, **only if** `AgentIdentity.isRegistered === true` and `meta.onchain.chainId` is set, calls `updateAgentURI`. Gate this behind an explicit user confirmation dialog: "Publish changes on-chain? This requires a signature and ~0.0003 ETH."
- - If the user cancels, local/backend state is still updated (unchanged behavior); only the on-chain step is skipped.
+ - In [src/avatar-creator.js](../../src/avatar-creator.js) (or wherever avatar-edit's "save" handler lives — search for the save/confirm callback) add a post-save hook that, **only if** `AgentIdentity.isRegistered === true` and `meta.onchain.chainId` is set, calls `updateAgentURI`. Gate this behind an explicit user confirmation dialog: "Publish changes on-chain? This requires a signature and ~0.0003 ETH."
+ - If the user cancels, local/backend state is still updated (unchanged behavior); only the on-chain step is skipped.
5. Standalone surface: add a button "Republish on-chain" to [src/agent-home.js](../../src/agent-home.js) that appears only for owners of registered agents; clicking invokes `updateAgentURI` with no `newGLB`, forcing a metadata-only refresh (useful for renaming or editing description).
## Audit checklist
@@ -71,11 +73,11 @@ Add an idempotent, resumable "update agent URI" flow that runs after avatar-edit
1. `node --check` each modified / new JS file.
2. `npx vite build` passes.
3. Manual:
- - Register an agent on Base Sepolia (uses [03](./03-register-flow-polish.md)).
- - Open avatar-edit, swap a hair, save → confirm "Publish changes on-chain?" dialog → accept → tx lands → `tokenURI(agentId)` now resolves to a new registration JSON with updated `image`.
- - Console-kill the tab between step 4 (pin JSON) and step 5 (tx). Reload. Trigger save again — flow resumes, tx sends once.
- - Without a wallet, call `updateAgentURI` → fails with `not-owner` or `no-signer`.
- - Rename the agent locally, click "Republish on-chain" → only step 3-5 run; no new GLB pinned.
+ - Register an agent on Base Sepolia (uses [03](./03-register-flow-polish.md)).
+ - Open avatar-edit, swap a hair, save → confirm "Publish changes on-chain?" dialog → accept → tx lands → `tokenURI(agentId)` now resolves to a new registration JSON with updated `image`.
+ - Console-kill the tab between step 4 (pin JSON) and step 5 (tx). Reload. Trigger save again — flow resumes, tx sends once.
+ - Without a wallet, call `updateAgentURI` → fails with `not-owner` or `no-signer`.
+ - Rename the agent locally, click "Republish on-chain" → only step 3-5 run; no new GLB pinned.
4. Read the final on-chain `tokenURI` and confirm `registrations[0]` is unchanged from before the update.
## Scope boundaries — do NOT do these
diff --git a/prompts/onchain/05-action-provenance-signing.md b/prompts/onchain/05-action-provenance-signing.md
index 8a5f5bf02..ec7a0533c 100644
--- a/prompts/onchain/05-action-provenance-signing.md
+++ b/prompts/onchain/05-action-provenance-signing.md
@@ -41,6 +41,7 @@ Every action sent to `/api/agent-actions` becomes a canonical JSON:
### 2. Hash chain
Each action's `prevHash` references the previous action's `actionHash`. The chain:
+
- Is per-agent.
- Genesis action's `prevHash = 0x00…00`.
- A broken chain means tampering — server rejects.
@@ -48,6 +49,7 @@ Each action's `prevHash` references the previous action's `actionHash`. The chai
### 3. Server endpoint
`POST /api/agent-actions`:
+
- Verify `signer_address` matches `agents.wallet_address`.
- Verify `prevHash` matches last stored action's `action_hash`.
- Recompute `actionHash` server-side from the canonical JSON; ensure match.
@@ -59,6 +61,7 @@ Reject with `{ ok: false, error: 'signature_invalid' | 'chain_mismatch' | 'stale
### 4. Client batch
Many events per second (speak + emote + think). Batch every 300ms:
+
- Collect actions in a queue.
- Build a single Merkle root over the batch; sign the root.
- Send `/api/agent-actions/batch` with `{ items: […], merkleRoot, signature }`.
@@ -67,12 +70,14 @@ Many events per second (speak + emote + think). Batch every 300ms:
### 5. Public audit endpoint
`GET /api/agent-actions/:agentId/verify?from=<n>&to=<m>`:
+
- Returns a proof bundle (all actions + sigs + Merkle paths).
- Client-side verifier at `/agent/:id/audit` re-verifies every sig + chain link in-browser and shows ✓ / ✗ per link.
### 6. UI
On `/agent/:id`, the Timeline already exists. Add a small green/red chip per entry:
+
- ✓ = signature verified locally
- ✗ = signature invalid (should only happen if someone tampered)
- hover → shows signer address
diff --git a/prompts/onchain/05-reputation-display-and-submit.md b/prompts/onchain/05-reputation-display-and-submit.md
index a24733b14..6ce8491a5 100644
--- a/prompts/onchain/05-reputation-display-and-submit.md
+++ b/prompts/onchain/05-reputation-display-and-submit.md
@@ -19,24 +19,24 @@ On `/agent/:id`, show aggregate reputation + a capped list of recent reviews; le
## Deliverable
1. New file [src/erc8004/reputation-ui.js](../../src/erc8004/reputation-ui.js) exporting class `ReputationPanel`:
- - Constructor: `new ReputationPanel(containerEl, { agentId, chainId, ownerAddress, provider, signer? })`
- - Renders into `containerEl`:
- - Top strip: `★ 84 · 12 reviews` (average score + count). If no reviews → `"Be the first to review"`.
- - A bar chart of the score distribution (bins of 10) — pure CSS bars, no chart lib.
- - Up to 10 most-recent reviews, each showing: submitter address (truncated 0x1234…abcd), score, comment, block number, link to explorer.
- - A "Write a review" form (score slider 1–100, comment textarea maxlength 500, submit button) visible **only** when a wallet is connected AND the connected address !== `ownerAddress`.
- - Handles the "no reviews yet" revert:
- - Wrap `getReputation` in a try/catch. On revert or on `count === 0`, show the empty state. Don't log an error to console.
- - In [reputation.js](../../src/erc8004/reputation.js), update `getReputation` to swallow the revert and return `{ total: 0, count: 0, average: 0 }` so it's uniform — document this behavior in a JSDoc comment. Do this in a single helper `_tryReadReputation(contract, agentId)` internal to the file.
- - On submit:
- - Validate `Number.isInteger(score) && score >= 1 && score <= 100` (UI enforces but guard anyway).
- - Call `submitReputation`. Use structured `onStatus` consistent with [03](./03-register-flow-polish.md) if that lands: steps `estimating → signing → mining → done`.
- - On success, optimistically prepend the new review to the list and re-fetch aggregate; don't full-reload.
- - On error, reuse `classifyTxError` if available, otherwise show a dismissible error card.
+ - Constructor: `new ReputationPanel(containerEl, { agentId, chainId, ownerAddress, provider, signer? })`
+ - Renders into `containerEl`:
+ - Top strip: `★ 84 · 12 reviews` (average score + count). If no reviews → `"Be the first to review"`.
+ - A bar chart of the score distribution (bins of 10) — pure CSS bars, no chart lib.
+ - Up to 10 most-recent reviews, each showing: submitter address (truncated 0x1234…abcd), score, comment, block number, link to explorer.
+ - A "Write a review" form (score slider 1–100, comment textarea maxlength 500, submit button) visible **only** when a wallet is connected AND the connected address !== `ownerAddress`.
+ - Handles the "no reviews yet" revert:
+ - Wrap `getReputation` in a try/catch. On revert or on `count === 0`, show the empty state. Don't log an error to console.
+ - In [reputation.js](../../src/erc8004/reputation.js), update `getReputation` to swallow the revert and return `{ total: 0, count: 0, average: 0 }` so it's uniform — document this behavior in a JSDoc comment. Do this in a single helper `_tryReadReputation(contract, agentId)` internal to the file.
+ - On submit:
+ - Validate `Number.isInteger(score) && score >= 1 && score <= 100` (UI enforces but guard anyway).
+ - Call `submitReputation`. Use structured `onStatus` consistent with [03](./03-register-flow-polish.md) if that lands: steps `estimating → signing → mining → done`.
+ - On success, optimistically prepend the new review to the list and re-fetch aggregate; don't full-reload.
+ - On error, reuse `classifyTxError` if available, otherwise show a dismissible error card.
2. Wire `ReputationPanel` into [src/agent-home.js](../../src/agent-home.js):
- - Mount only when `AgentIdentity.isRegistered === true` AND `meta.onchain.chainId` is known.
- - Sits below the existing identity card + action timeline, not above.
- - Provider: use a read-only `JsonRpcProvider` with `DEFAULT_RPCS[chainId]` from [manifest.js](../../src/manifest.js) by default. If the user has connected a wallet, swap in that signer for submit-time only.
+ - Mount only when `AgentIdentity.isRegistered === true` AND `meta.onchain.chainId` is known.
+ - Sits below the existing identity card + action timeline, not above.
+ - Provider: use a read-only `JsonRpcProvider` with `DEFAULT_RPCS[chainId]` from [manifest.js](../../src/manifest.js) by default. If the user has connected a wallet, swap in that signer for submit-time only.
3. CSS: add styles inside an injected `<style>` tag the module appends once to `document.head`. Keep classes namespaced (`.rep-panel-*`). No Tailwind, no new global stylesheet.
## Audit checklist
@@ -64,11 +64,11 @@ On `/agent/:id`, show aggregate reputation + a capped list of recent reviews; le
1. `node --check` all new/modified JS files.
2. `npx vite build` passes.
3. Manual on Base Sepolia:
- - Load `/agent/:id` for an agent with **zero** reviews → panel shows "Be the first to review"; no console errors.
- - Connect a wallet that is NOT the owner → form appears. Submit a 73 with comment "Very smooth wave." → tx lands → review appears at top; aggregate updates to 73 / 1.
- - Submit a second review from a different wallet. Bar chart updates.
- - Load `/agent/:id` as the owner — form is hidden; only aggregate + list shown.
- - Disconnect wallet; form disappears, "Connect wallet to review" CTA shows.
+ - Load `/agent/:id` for an agent with **zero** reviews → panel shows "Be the first to review"; no console errors.
+ - Connect a wallet that is NOT the owner → form appears. Submit a 73 with comment "Very smooth wave." → tx lands → review appears at top; aggregate updates to 73 / 1.
+ - Submit a second review from a different wallet. Bar chart updates.
+ - Load `/agent/:id` as the owner — form is hidden; only aggregate + list shown.
+ - Disconnect wallet; form disappears, "Connect wallet to review" CTA shows.
4. Throttle the RPC (DevTools network) — panel should degrade to spinners, never crash.
## Scope boundaries — do NOT do these
diff --git a/prompts/onchain/06-cross-chain-lookup.md b/prompts/onchain/06-cross-chain-lookup.md
index 7a1b6f64b..7e3ddf1e8 100644
--- a/prompts/onchain/06-cross-chain-lookup.md
+++ b/prompts/onchain/06-cross-chain-lookup.md
@@ -6,9 +6,12 @@ Repo: `/workspaces/3D`. The ERC-8004 registration JSON identifies the agent's ch
```json
{
- "registrations": [
- { "agentId": 42, "agentRegistry": "eip155:11155111:0x8004A818BFB912233c491871b3d84c89A494BD9e" }
- ]
+ "registrations": [
+ {
+ "agentId": 42,
+ "agentRegistry": "eip155:11155111:0x8004A818BFB912233c491871b3d84c89A494BD9e"
+ }
+ ]
}
```
@@ -25,24 +28,24 @@ Make the resolver chain-aware. Any flow that has a registration JSON (directly o
## Deliverable
1. New file [src/erc8004/resolver.js](../../src/erc8004/resolver.js) exporting:
- - `parseAgentRegistry(str)` → `{ chainId: number, registryAddr: string }` or throws. Accepts `"eip155:<n>:<0x…>"`; tolerates whitespace; rejects malformed input with a clear error.
- - `agentRegistryFromJSON(json)` → convenience that finds `json.registrations?.[0]?.agentRegistry` and parses it; returns `null` (not throws) if absent.
- - `async probeAgentAcrossChains({ agentId, chainIds?, rpcURL? })` → returns the first chain on which `ownerOf(agentId)` resolves to a non-zero address. Probes in parallel with concurrency cap 4, 3s per-chain timeout. If no chain has it → `null`. Order of probing: prefer chains whose `deployment.identityRegistry === '0x8004A169…'` (mainnet) first, then testnets. Consumers can pass `chainIds` to restrict.
+ - `parseAgentRegistry(str)` → `{ chainId: number, registryAddr: string }` or throws. Accepts `"eip155:<n>:<0x…>"`; tolerates whitespace; rejects malformed input with a clear error.
+ - `agentRegistryFromJSON(json)` → convenience that finds `json.registrations?.[0]?.agentRegistry` and parses it; returns `null` (not throws) if absent.
+ - `async probeAgentAcrossChains({ agentId, chainIds?, rpcURL? })` → returns the first chain on which `ownerOf(agentId)` resolves to a non-zero address. Probes in parallel with concurrency cap 4, 3s per-chain timeout. If no chain has it → `null`. Order of probing: prefer chains whose `deployment.identityRegistry === '0x8004A169…'` (mainnet) first, then testnets. Consumers can pass `chainIds` to restrict.
2. Update [src/manifest.js](../../src/manifest.js):
- - In `loadFromAgentURI`, after parsing the URI's `{chain}` segment, still fetch the tokenURI. Then parse the resolved JSON's `agentRegistry` field. If it **disagrees** with the URI's chain, prefer the JSON's chain and log `console.warn('[manifest] URI chain', chainName, 'disagrees with registration agentRegistry, using JSON chain')`. Re-query `tokenURI` on the correct chain only if the original read failed (don't double-read when data is good).
- - In `normalize()`, stamp the parsed `chainId` / `registryAddr` onto `manifest.id` from the JSON's `agentRegistry` field whenever present, **overwriting** any chain info passed in via `baseURI` / caller hints. Do not silently downgrade existing non-empty fields.
+ - In `loadFromAgentURI`, after parsing the URI's `{chain}` segment, still fetch the tokenURI. Then parse the resolved JSON's `agentRegistry` field. If it **disagrees** with the URI's chain, prefer the JSON's chain and log `console.warn('[manifest] URI chain', chainName, 'disagrees with registration agentRegistry, using JSON chain')`. Re-query `tokenURI` on the correct chain only if the original read failed (don't double-read when data is good).
+ - In `normalize()`, stamp the parsed `chainId` / `registryAddr` onto `manifest.id` from the JSON's `agentRegistry` field whenever present, **overwriting** any chain info passed in via `baseURI` / caller hints. Do not silently downgrade existing non-empty fields.
3. Update [01-hydrate-agent-from-chain.md](./01-hydrate-agent-from-chain.md)'s `hydrate.js` (if that task has landed; otherwise note the dependency in your report):
- - After fetching `tokenURI` + parsing JSON, call `agentRegistryFromJSON`; if it yields a chainId different from the requested one, log a warning and **use the JSON's chain** for subsequent operations (reputation, ownerOf), stamping both into `meta.onchain`.
+ - After fetching `tokenURI` + parsing JSON, call `agentRegistryFromJSON`; if it yields a chainId different from the requested one, log a warning and **use the JSON's chain** for subsequent operations (reputation, ownerOf), stamping both into `meta.onchain`.
4. Update [src/app.js](../../src/app.js) hash routing:
- - Search for the hard-coded Base chainId fallback (`8453`) used when `agent=...` is present without `chain=...`. Replace with: first try the localStorage identity's `meta.onchain.chainId` if any, else call `probeAgentAcrossChains({ agentId })`. If the probe returns null, render an error banner ("Couldn't find agent on any supported chain. Try adding `&chain=<id>` to the URL.") with a list of supported chains.
+ - Search for the hard-coded Base chainId fallback (`8453`) used when `agent=...` is present without `chain=...`. Replace with: first try the localStorage identity's `meta.onchain.chainId` if any, else call `probeAgentAcrossChains({ agentId })`. If the probe returns null, render an error banner ("Couldn't find agent on any supported chain. Try adding `&chain=<id>` to the URL.") with a list of supported chains.
5. Document the resolver contract in the top-of-file JSDoc of `resolver.js`: one short table of priority rules, for future readers.
## Audit checklist
- `parseAgentRegistry` rejects:
- - missing `eip155:` prefix
- - non-numeric chainId
- - malformed address (wrong length, non-hex)
+ - missing `eip155:` prefix
+ - non-numeric chainId
+ - malformed address (wrong length, non-hex)
- `agentRegistryFromJSON` returns `null` cleanly for registration JSONs that omit `registrations[]` (some minimal manifests do).
- `probeAgentAcrossChains` uses `Promise.any` semantics: the first successful `ownerOf` wins; other probes are cancelled via `AbortSignal` if the RPC client supports it (best-effort — document limitation if `ethers` does not).
- Probe skips chains whose `deployment.identityRegistry` is falsy.
@@ -64,17 +67,17 @@ Make the resolver chain-aware. Any flow that has a registration JSON (directly o
1. `node --check src/erc8004/resolver.js src/manifest.js src/app.js`.
2. `npx vite build` passes.
3. Unit-ish sanity in a browser console:
- ```js
- const r = await import('/src/erc8004/resolver.js');
- r.parseAgentRegistry('eip155:84532:0x8004A818BFB912233c491871b3d84c89A494BD9e'); // ok
- r.parseAgentRegistry('bad'); // throws
- await r.probeAgentAcrossChains({ agentId: 1 }); // returns { chainId, registryAddr } or null
- ```
+ ```js
+ const r = await import('/src/erc8004/resolver.js');
+ r.parseAgentRegistry('eip155:84532:0x8004A818BFB912233c491871b3d84c89A494BD9e'); // ok
+ r.parseAgentRegistry('bad'); // throws
+ await r.probeAgentAcrossChains({ agentId: 1 }); // returns { chainId, registryAddr } or null
+ ```
4. Manual URL tests:
- - `/#agent=<idOnBaseSepolia>` (no `chain=`) — loads without Base fallback error.
- - `/#agent=<idOnOptimism>&chain=10` — loads on Optimism.
- - `/#agent=<idOnBaseSepolia>&chain=8453` (wrong chain specified) — after fetching tokenURI, prefers the JSON's chain, with console warning.
- - `/#agent=999999999` — probe returns null, error banner shown.
+ - `/#agent=<idOnBaseSepolia>` (no `chain=`) — loads without Base fallback error.
+ - `/#agent=<idOnOptimism>&chain=10` — loads on Optimism.
+ - `/#agent=<idOnBaseSepolia>&chain=8453` (wrong chain specified) — after fetching tokenURI, prefers the JSON's chain, with console warning.
+ - `/#agent=999999999` — probe returns null, error banner shown.
5. Check that [src/manifest.js](../../src/manifest.js) `loadManifest('ipfs://<CID>')` correctly picks up the `agentRegistry` chain and stamps it on `manifest.id.chainId`.
## Scope boundaries — do NOT do these
diff --git a/prompts/onchain/README.md b/prompts/onchain/README.md
index 6e4111d39..bb55d2c00 100644
--- a/prompts/onchain/README.md
+++ b/prompts/onchain/README.md
@@ -24,14 +24,14 @@ The remaining work is **integration + UX**. The registration code path exists ([
## Execution order
-| # | File | Depends on |
-|---|---|---|
-| 1 | [01-hydrate-agent-from-chain.md](./01-hydrate-agent-from-chain.md) | — |
-| 2 | [02-wallet-to-agents.md](./02-wallet-to-agents.md) | 01 (shares hydrate path) |
-| 3 | [03-register-flow-polish.md](./03-register-flow-polish.md) | — |
-| 4 | [04-update-agent-uri.md](./04-update-agent-uri.md) | 03 helpful but not required |
-| 5 | [05-reputation-display-and-submit.md](./05-reputation-display-and-submit.md) | 01 (uses hydrate on `/agent/:id`) |
-| 6 | [06-cross-chain-lookup.md](./06-cross-chain-lookup.md) | 01 |
+| # | File | Depends on |
+| --- | ---------------------------------------------------------------------------- | --------------------------------- |
+| 1 | [01-hydrate-agent-from-chain.md](./01-hydrate-agent-from-chain.md) | — |
+| 2 | [02-wallet-to-agents.md](./02-wallet-to-agents.md) | 01 (shares hydrate path) |
+| 3 | [03-register-flow-polish.md](./03-register-flow-polish.md) | — |
+| 4 | [04-update-agent-uri.md](./04-update-agent-uri.md) | 03 helpful but not required |
+| 5 | [05-reputation-display-and-submit.md](./05-reputation-display-and-submit.md) | 01 (uses hydrate on `/agent/:id`) |
+| 6 | [06-cross-chain-lookup.md](./06-cross-chain-lookup.md) | 01 |
## Rules for every task
diff --git a/prompts/parallel-finish/01-siwe-csrf-hardening.md b/prompts/parallel-finish/01-siwe-csrf-hardening.md
index 3d965732b..fb057edb4 100644
--- a/prompts/parallel-finish/01-siwe-csrf-hardening.md
+++ b/prompts/parallel-finish/01-siwe-csrf-hardening.md
@@ -36,6 +36,7 @@ npm run build
```
Manually:
+
- `curl -sX POST /api/auth/siwe/verify -d '{}'` → 403 `invalid_request` with no CSRF.
- Fresh nonce → verify flow works end-to-end in the browser.
diff --git a/prompts/parallel-finish/02-sessions-management.md b/prompts/parallel-finish/02-sessions-management.md
index a54440f2d..2f14e2dae 100644
--- a/prompts/parallel-finish/02-sessions-management.md
+++ b/prompts/parallel-finish/02-sessions-management.md
@@ -4,7 +4,7 @@
Repo root: `/workspaces/3D-Agent`. Read [/CLAUDE.md](../../CLAUDE.md) and [api/CLAUDE.md](../../api/CLAUDE.md) first.
-The `sessions` table (see [api/_lib/schema.sql](../../api/_lib/schema.sql)) tracks each logged-in session with `last_seen_at`, `user_agent`, `ip`. There is currently no way for a user to list or revoke their sessions. We need a "sign out everywhere" path and a per-session revoke.
+The `sessions` table (see [api/\_lib/schema.sql](../../api/_lib/schema.sql)) tracks each logged-in session with `last_seen_at`, `user_agent`, `ip`. There is currently no way for a user to list or revoke their sessions. We need a "sign out everywhere" path and a per-session revoke.
## Files you own (exclusive — create all as new files)
diff --git a/prompts/parallel-finish/04-link-wallet-api.md b/prompts/parallel-finish/04-link-wallet-api.md
index 3df439e72..ff4937243 100644
--- a/prompts/parallel-finish/04-link-wallet-api.md
+++ b/prompts/parallel-finish/04-link-wallet-api.md
@@ -4,7 +4,7 @@
Repo root: `/workspaces/3D-Agent`. Read [/CLAUDE.md](../../CLAUDE.md) and [api/CLAUDE.md](../../api/CLAUDE.md) first.
-The `user_wallets` table (see [api/_lib/schema.sql](../../api/_lib/schema.sql)) already supports many wallets per user, but there is no API for an authenticated user to link a new wallet to their existing account. Users who sign in with wallet A cannot later add wallet B.
+The `user_wallets` table (see [api/\_lib/schema.sql](../../api/_lib/schema.sql)) already supports many wallets per user, but there is no API for an authenticated user to link a new wallet to their existing account. Users who sign in with wallet A cannot later add wallet B.
The linking flow is: authenticated user requests a nonce → signs a SIWE-like message with the new wallet → server verifies the signature and inserts a `user_wallets` row. No new session is created (the user is already signed in).
diff --git a/prompts/parallel-finish/05-first-meet-flow.md b/prompts/parallel-finish/05-first-meet-flow.md
index f2996a037..8703ff865 100644
--- a/prompts/parallel-finish/05-first-meet-flow.md
+++ b/prompts/parallel-finish/05-first-meet-flow.md
@@ -21,10 +21,10 @@ This task builds a **standalone page** at `/first-meet/?avatar=<id>` so it doesn
1. **Auth check** — redirect to `/login` if not signed in.
2. **Load the avatar** — `fetch('/api/avatars/<id>')` — show `<model-viewer>` preview.
3. **Step 1: Name.** Single input, autofocus, 2–40 chars, defaults to `My Agent`. Skip button allowed.
-4. **Step 2: Bio.** `<textarea>`, 0–280 chars, optional. Placeholder: *"What should people know about this agent?"*.
+4. **Step 2: Bio.** `<textarea>`, 0–280 chars, optional. Placeholder: _"What should people know about this agent?"_.
5. **Step 3: Voice + body type.** Dropdowns. Voice options: `en-US-female`, `en-US-male`, `en-GB-female`, `en-GB-male`. Body type: `feminine`, `masculine`, `neutral`.
6. **Step 4: Greet.** Render the avatar with the built-in `<agent-3d>` element loaded from `/dist-lib/agent-3d.js` (already built by `npm run build:lib`). On mount, call the greet sequence: a wave + an emit of `speak` event saying `Hi — I'm <name>. <bio line or fallback>`. Use browser TTS (the element handles this if `voice=<chosen>` attribute is set).
-7. **Step 5: Done.** Two buttons: *Go to my agent* (links to `/agent/<id>`) and *Back to dashboard* (`/dashboard`).
+7. **Step 5: Done.** Two buttons: _Go to my agent_ (links to `/agent/<id>`) and _Back to dashboard_ (`/dashboard`).
All steps persist progress to `PATCH /api/avatars/<id>` and, if an agent identity exists, to `PATCH /api/agents/<agentId>` for the bio/voice. If no agent exists, call `POST /api/agents` with `{ avatarId, name, bio, voice }` (see [api/agents/index.js](../../api/agents/index.js) for shape).
diff --git a/prompts/parallel-finish/06-selfie-progress-ui.md b/prompts/parallel-finish/06-selfie-progress-ui.md
index f272eddbb..abd76266d 100644
--- a/prompts/parallel-finish/06-selfie-progress-ui.md
+++ b/prompts/parallel-finish/06-selfie-progress-ui.md
@@ -28,7 +28,7 @@ Stages 3–4 are inferred client-side from elapsed time because the current back
- If in flight more than 6s, flip to `building`.
- If in flight more than 30s, show a "still working — this occasionally takes up to 60s" note. Do not abort.
-If the POST errors, show the error and a *Try again* button. Never leave the user stuck on a spinner.
+If the POST errors, show the error and a _Try again_ button. Never leave the user stuck on a spinner.
## UI requirements
diff --git a/prompts/parallel-finish/07-avatar-agent-link.md b/prompts/parallel-finish/07-avatar-agent-link.md
index e2dade5a6..407ce5de4 100644
--- a/prompts/parallel-finish/07-avatar-agent-link.md
+++ b/prompts/parallel-finish/07-avatar-agent-link.md
@@ -19,7 +19,7 @@ We fix this with a single small endpoint + a tweak to the avatar-create hook.
### `POST /api/avatars/:` (success branch hook)
-After a successful INSERT, *if* the caller is authenticated *and* the request `source === 'avaturn'` or `'selfie'` *and* the user has a primary agent with `avatar_id IS NULL`, UPDATE that agent to point at the new avatar. Fire-and-forget — if the UPDATE fails, the 201 still returns.
+After a successful INSERT, _if_ the caller is authenticated _and_ the request `source === 'avaturn'` or `'selfie'` _and_ the user has a primary agent with `avatar_id IS NULL`, UPDATE that agent to point at the new avatar. Fire-and-forget — if the UPDATE fails, the 201 still returns.
Do this inline; do not introduce a job queue or event bus.
diff --git a/prompts/parallel-finish/08-artifact-bundle.md b/prompts/parallel-finish/08-artifact-bundle.md
index 799d8acef..a737a8e59 100644
--- a/prompts/parallel-finish/08-artifact-bundle.md
+++ b/prompts/parallel-finish/08-artifact-bundle.md
@@ -4,7 +4,7 @@
Repo root: `/workspaces/3D-Agent`. Read [/CLAUDE.md](../../CLAUDE.md) and [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md) first.
-Claude Artifacts run inside a sandboxed iframe. The dashboard currently generates a snippet that puts *another* iframe inside — nested iframes work poorly and break the postMessage bridge. We want a **zero-dependency, self-contained bundle** the user can paste as a single `<script>` + `<div>` and get a live agent inside a Claude Artifact.
+Claude Artifacts run inside a sandboxed iframe. The dashboard currently generates a snippet that puts _another_ iframe inside — nested iframes work poorly and break the postMessage bridge. We want a **zero-dependency, self-contained bundle** the user can paste as a single `<script>` + `<div>` and get a live agent inside a Claude Artifact.
The bundle lives at `https://3dagent.vercel.app/artifact.js`. It includes three.js + GLTFLoader inlined (or fetched from a CDN the Artifact sandbox allows — `esm.sh`), reads config from a `<script type="application/json" id="agent3d-config">` block, resolves the agent via `GET /api/agents/:id`, loads the GLB, renders it with basic controls + a caption line (no chat).
@@ -30,7 +30,7 @@ The bundle lives at `https://3dagent.vercel.app/artifact.js`. It includes three.
## Claude Artifact compatibility
- Works inside `<iframe sandbox="allow-scripts">` with no `allow-same-origin`. That means the bundle must not access `document.cookie`, `localStorage`, or parent window.
-- CORS: ensure `GET /api/agents/:id` has `Access-Control-Allow-Origin: *` — check [api/_lib/http.js](../../api/_lib/http.js) `cors()` helper; you can use it but do not edit it.
+- CORS: ensure `GET /api/agents/:id` has `Access-Control-Allow-Origin: *` — check [api/\_lib/http.js](../../api/_lib/http.js) `cors()` helper; you can use it but do not edit it.
## Out of scope
diff --git a/prompts/parallel-finish/09-lobehub-plugin.md b/prompts/parallel-finish/09-lobehub-plugin.md
index 763a82c33..72d405ab2 100644
--- a/prompts/parallel-finish/09-lobehub-plugin.md
+++ b/prompts/parallel-finish/09-lobehub-plugin.md
@@ -38,22 +38,22 @@ lobehub-plugin/
```json
{
- "identifier": "3dagent",
- "schemaVersion": 1,
- "meta": {
- "title": "3D Agent",
- "description": "Render a 3D avatar that reacts to the chat.",
- "avatar": "https://3dagent.vercel.app/favicon.ico",
- "tags": ["avatar", "3d", "agent"]
- },
- "ui": {
- "position": "right",
- "size": { "width": 320, "height": 420 }
- },
- "settings": [
- { "name": "agentId", "type": "string", "required": true, "title": "Agent ID" },
- { "name": "apiOrigin", "type": "string", "default": "https://3dagent.vercel.app" }
- ]
+ "identifier": "3dagent",
+ "schemaVersion": 1,
+ "meta": {
+ "title": "3D Agent",
+ "description": "Render a 3D avatar that reacts to the chat.",
+ "avatar": "https://3dagent.vercel.app/favicon.ico",
+ "tags": ["avatar", "3d", "agent"]
+ },
+ "ui": {
+ "position": "right",
+ "size": { "width": 320, "height": 420 }
+ },
+ "settings": [
+ { "name": "agentId", "type": "string", "required": true, "title": "Agent ID" },
+ { "name": "apiOrigin", "type": "string", "default": "https://3dagent.vercel.app" }
+ ]
}
```
diff --git a/prompts/parallel-finish/11-validation-registry-deploy.md b/prompts/parallel-finish/11-validation-registry-deploy.md
index 48387f3e7..d52e5ccde 100644
--- a/prompts/parallel-finish/11-validation-registry-deploy.md
+++ b/prompts/parallel-finish/11-validation-registry-deploy.md
@@ -21,7 +21,7 @@ This task produces the **script + runbook**, not the broadcast itself. Per [/CLA
- Identical CREATE2 salt to the existing deploy script — ensures deterministic address parity with the testnet deployment (if one exists — check `REGISTRY_DEPLOYMENTS` for testnet ValidationRegistry addresses and **must match**).
- Reads `IDENTITY_REGISTRY` env var if the constructor needs it, else hardcode the canonical CREATE2 address from `contracts/CLAUDE.md`.
-- Logs the computed address *before* deploying (so a human can sanity-check).
+- Logs the computed address _before_ deploying (so a human can sanity-check).
- `forge script ... --rpc-url $RPC --sender $DEPLOYER` as the dry-run. Broadcast is `--broadcast --verify --etherscan-api-key $KEY`.
## Runbook requirements
diff --git a/prompts/parallel-finish/12-hydrate-from-chain.md b/prompts/parallel-finish/12-hydrate-from-chain.md
index db13abd53..53c0b373e 100644
--- a/prompts/parallel-finish/12-hydrate-from-chain.md
+++ b/prompts/parallel-finish/12-hydrate-from-chain.md
@@ -32,7 +32,7 @@ The crawler at [api/cron/erc8004-crawl.js](../../api/cron/erc8004-crawl.js) inde
- Auth required.
- Validate `chainId` (integer, in the 15-chain allowlist) and `agentId` (integer).
- Look up the index row. Must exist. Must be owned by one of the caller's linked wallets.
-- Resolve `tokenURI` → metadata (use the existing `resolveOnChainAgent` helper in [api/_lib/onchain.js](../../api/_lib/onchain.js)).
+- Resolve `tokenURI` → metadata (use the existing `resolveOnChainAgent` helper in [api/\_lib/onchain.js](../../api/_lib/onchain.js)).
- INSERT `agent_identities` with the resolved name, description, avatar (download and store via R2 if you want, or link directly — document which you chose).
- 409 if already imported.
- Output `{ agent: { id, erc8004_agent_id, erc8004_agent_id_chain_id, name, avatar_url } }`.
diff --git a/prompts/parallel-finish/13-signed-action-log-ui.md b/prompts/parallel-finish/13-signed-action-log-ui.md
index 9af65febd..a69235278 100644
--- a/prompts/parallel-finish/13-signed-action-log-ui.md
+++ b/prompts/parallel-finish/13-signed-action-log-ui.md
@@ -44,7 +44,7 @@ There is **no UI** to view this log. We need one — the timeline is the most ho
- Do not add a "re-sign all" button.
- Do not integrate into the dashboard sidebar.
-- Do not implement action *replay* (playing back a speak/gesture in the viewer).
+- Do not implement action _replay_ (playing back a speak/gesture in the viewer).
- Do not add time-range picker beyond the infinite-scroll.
- Do not add CSV export — JSON is enough.
diff --git a/prompts/parallel-finish/14-ipfs-pinning-real.md b/prompts/parallel-finish/14-ipfs-pinning-real.md
index 444b49e15..a0f4669ef 100644
--- a/prompts/parallel-finish/14-ipfs-pinning-real.md
+++ b/prompts/parallel-finish/14-ipfs-pinning-real.md
@@ -9,7 +9,7 @@ The ERC-8004 registration flow ([src/erc8004/agent-registry.js](../../src/erc800
1. **Pinata JWT path** — real IPFS. Good.
2. **Internal `/api/erc8004/pin` path** — currently uploads to R2 and returns an `https://...` URL. The on-chain `tokenURI` then points at a centralized R2 URL. Not truly decentralized.
-We want path 2 to also return an `ipfs://<cid>` URI by uploading to an IPFS service (web3.storage, nft.storage, or a self-hosted IPFS node) and optionally *also* mirroring to R2 for speed. The client is already happy with an `ipfs://` return value.
+We want path 2 to also return an `ipfs://<cid>` URI by uploading to an IPFS service (web3.storage, nft.storage, or a self-hosted IPFS node) and optionally _also_ mirroring to R2 for speed. The client is already happy with an `ipfs://` return value.
## Files you own (exclusive)
@@ -21,16 +21,16 @@ We want path 2 to also return an `ipfs://<cid>` URI by uploading to an IPFS serv
- **Prefer:** `WEB3_STORAGE_TOKEN` env var → upload via web3.storage HTTP API, return `ipfs://<cid>/<filename>`.
- **Fallback:** `NFT_STORAGE_TOKEN` env var → upload via nft.storage, same return format.
-- **Final fallback:** if neither is set, *and* `R2_BUCKET` is configured, keep the existing R2 path but also return `{ url, ipfs: null, warning: 'R2-only pin — not decentralized' }` so the client can surface a clear warning.
+- **Final fallback:** if neither is set, _and_ `R2_BUCKET` is configured, keep the existing R2 path but also return `{ url, ipfs: null, warning: 'R2-only pin — not decentralized' }` so the client can surface a clear warning.
- **Response shape:**
- ```
- { cid: string | null, uri: string, url: string, warning?: string }
- ```
+ ```
+ { cid: string | null, uri: string, url: string, warning?: string }
+ ```
- - `uri` is the preferred value to pin on-chain (`ipfs://...` when possible).
- - `url` is an HTTPS gateway URL (always set, even for IPFS — use `https://w3s.link/ipfs/<cid>`).
- - `cid` is the raw CID string when available.
+ - `uri` is the preferred value to pin on-chain (`ipfs://...` when possible).
+ - `url` is an HTTPS gateway URL (always set, even for IPFS — use `https://w3s.link/ipfs/<cid>`).
+ - `cid` is the raw CID string when available.
- **Content-addressing:** if the same bytes are uploaded twice, the same `cid` comes back (web3.storage and nft.storage both guarantee this). Verify this in a comment.
diff --git a/prompts/parallel-finish/README.md b/prompts/parallel-finish/README.md
index 4fced9117..8c6f47836 100644
--- a/prompts/parallel-finish/README.md
+++ b/prompts/parallel-finish/README.md
@@ -8,22 +8,22 @@ These prompts are designed to run **simultaneously in separate agent chats** wit
## File ownership map (no overlaps)
-| Prompt | Owns (create/edit) |
-|---|---|
-| `01-siwe-csrf-hardening.md` | `api/auth/siwe/verify.js`, `api/auth/siwe/nonce.js` |
-| `02-sessions-management.md` | `api/auth/sessions/` (new), `public/dashboard/sessions.html` (new) |
-| `03-privy-backend-verify.md` | `api/auth/privy/` (new) |
-| `04-link-wallet-api.md` | `api/auth/wallets/` (new), `public/dashboard/wallets.html` (new) |
-| `05-first-meet-flow.md` | `public/first-meet/` (new) |
-| `06-selfie-progress-ui.md` | `src/selfie-pipeline.js`, `src/selfie-capture.js` |
-| `07-avatar-agent-link.md` | `api/avatars/index.js` (post-create hook only), `api/onboarding/link-avatar.js` (new) |
-| `08-artifact-bundle.md` | `public/artifact/` (new), `vite.config.artifact.js` (new) |
-| `09-lobehub-plugin.md` | `lobehub-plugin/` (new top-level package) |
-| `10-reputation-ui.md` | `public/reputation/` (new) |
+| Prompt | Owns (create/edit) |
+| ---------------------------------- | ----------------------------------------------------------------------------------------- |
+| `01-siwe-csrf-hardening.md` | `api/auth/siwe/verify.js`, `api/auth/siwe/nonce.js` |
+| `02-sessions-management.md` | `api/auth/sessions/` (new), `public/dashboard/sessions.html` (new) |
+| `03-privy-backend-verify.md` | `api/auth/privy/` (new) |
+| `04-link-wallet-api.md` | `api/auth/wallets/` (new), `public/dashboard/wallets.html` (new) |
+| `05-first-meet-flow.md` | `public/first-meet/` (new) |
+| `06-selfie-progress-ui.md` | `src/selfie-pipeline.js`, `src/selfie-capture.js` |
+| `07-avatar-agent-link.md` | `api/avatars/index.js` (post-create hook only), `api/onboarding/link-avatar.js` (new) |
+| `08-artifact-bundle.md` | `public/artifact/` (new), `vite.config.artifact.js` (new) |
+| `09-lobehub-plugin.md` | `lobehub-plugin/` (new top-level package) |
+| `10-reputation-ui.md` | `public/reputation/` (new) |
| `11-validation-registry-deploy.md` | `contracts/script/DeployValidationMainnet.s.sol` (new), `docs/VALIDATION_DEPLOY.md` (new) |
-| `12-hydrate-from-chain.md` | `public/hydrate/` (new), `src/erc8004/hydrate.js` (new) |
-| `13-signed-action-log-ui.md` | `public/dashboard/actions.html` (new) |
-| `14-ipfs-pinning-real.md` | `api/erc8004/pin.js` |
+| `12-hydrate-from-chain.md` | `public/hydrate/` (new), `src/erc8004/hydrate.js` (new) |
+| `13-signed-action-log-ui.md` | `public/dashboard/actions.html` (new) |
+| `14-ipfs-pinning-real.md` | `api/erc8004/pin.js` |
## Running them
diff --git a/prompts/portable-embed/00-README.md b/prompts/portable-embed/00-README.md
index dab22698f..0f671bf44 100644
--- a/prompts/portable-embed/00-README.md
+++ b/prompts/portable-embed/00-README.md
@@ -9,16 +9,16 @@ Anyone with the share URL sees a public, interactive 3D agent page. Anyone with
- Public viewer exists at `public/agent/index.html`; embed at `public/agent/embed.html`.
- OG/oEmbed metadata partially shipped (see `prompts/embed/01-og-oembed.md`).
- Agent-id resolver work in flight (`prompts/embed/02-agent-id-resolver.md`).
-- Per-agent embed allowlist spec exists (`prompts/embed/03-embed-allowlist.md`) — *not* a priority right now; owners can worry about it later.
+- Per-agent embed allowlist spec exists (`prompts/embed/03-embed-allowlist.md`) — _not_ a priority right now; owners can worry about it later.
## Prompts in this band
-| # | File | Depends on |
-|---|---|---|
-| 01 | [share-panel.md](./01-share-panel.md) | — |
-| 02 | [embed-snippet-generator.md](./02-embed-snippet-generator.md) | 01 |
-| 03 | [public-agent-page-polish.md](./03-public-agent-page-polish.md) | — |
-| 04 | [embed-sizing-and-theming.md](./04-embed-sizing-and-theming.md) | — |
+| # | File | Depends on |
+| --- | --------------------------------------------------------------- | ---------- |
+| 01 | [share-panel.md](./01-share-panel.md) | — |
+| 02 | [embed-snippet-generator.md](./02-embed-snippet-generator.md) | 01 |
+| 03 | [public-agent-page-polish.md](./03-public-agent-page-polish.md) | — |
+| 04 | [embed-sizing-and-theming.md](./04-embed-sizing-and-theming.md) | — |
All four can run in parallel after a quick scan of `public/agent/`.
@@ -31,6 +31,6 @@ All four can run in parallel after a quick scan of `public/agent/`.
## Off-limits for this band
-- Don't do Claude.ai / LobeHub integration here — that's band 5. This band is about the *generic* embed being solid first.
+- Don't do Claude.ai / LobeHub integration here — that's band 5. This band is about the _generic_ embed being solid first.
- Don't build a CDN. R2 is the blob store; Vercel serves the HTML.
- Don't introduce a new model-viewer component. `<model-viewer>` is fine.
diff --git a/prompts/portable-embed/02-embed-snippet-generator.md b/prompts/portable-embed/02-embed-snippet-generator.md
index 434624dba..c866c29fd 100644
--- a/prompts/portable-embed/02-embed-snippet-generator.md
+++ b/prompts/portable-embed/02-embed-snippet-generator.md
@@ -14,16 +14,16 @@ The iframe snippet from task 01 is a good default but embedders want knobs — s
### Supported params
-| Param | Values | Default |
-|---|---|---|
-| `height` | `<css length>` | `480px` |
-| `width` | `<css length>` | `100%` |
-| `theme` | `light` / `dark` / `auto` | `auto` |
-| `autoplay` | `0` / `1` | `1` |
-| `rotate` | `0` / `1` | `1` |
-| `bg` | `transparent` / `solid` / `gradient` | `transparent` |
-| `variant` | `<slug>` | — |
-| `camera` | `"20deg 68deg 3.4m"` etc. | — |
+| Param | Values | Default |
+| ---------- | ------------------------------------ | ------------- |
+| `height` | `<css length>` | `480px` |
+| `width` | `<css length>` | `100%` |
+| `theme` | `light` / `dark` / `auto` | `auto` |
+| `autoplay` | `0` / `1` | `1` |
+| `rotate` | `0` / `1` | `1` |
+| `bg` | `transparent` / `solid` / `gradient` | `transparent` |
+| `variant` | `<slug>` | — |
+| `camera` | `"20deg 68deg 3.4m"` etc. | — |
The embed page honors these by setting `<model-viewer>` attributes. CSS-injected values are validated with `safeCssValue` / `safeCssLength` helpers that already exist in `api/mcp.js` — lift them into a shared module `src/shared/safe-css.js` that both files import.
@@ -34,6 +34,7 @@ Inline under the snippet: labeled inputs for each param. As the user flips them,
### Snippet formats
Offer three:
+
1. **iframe** — the default.
2. **Web component** — `<script src=".../agent-3d.js" />` + `<agent-3d id="…" height="…" …>`.
3. **oEmbed URL** — a link embedders paste into platforms that auto-resolve oEmbed (Slack, Notion, etc.).
diff --git a/prompts/pretext/01-install-and-scaffold.md b/prompts/pretext/01-install-and-scaffold.md
index f6c8e5f67..3958c8435 100644
--- a/prompts/pretext/01-install-and-scaffold.md
+++ b/prompts/pretext/01-install-and-scaffold.md
@@ -22,13 +22,13 @@ Without the flag, the page must render exactly as it does today.
1. **Install the dep** — `npm install @chenglou/pretext`. Update [package.json](../../package.json) and [package-lock.json](../../package-lock.json). No other deps.
2. **New file** `src/features/hero-pretext.js` — exports a default class `PretextHero` with:
- - `constructor(root)` — `root` is the `.hero` element. Caches references to `.hero-content`, `.hero-title`, `.hero-subtitle`, `.hero-avatar`.
- - `async init()` — dynamic-imports `@chenglou/pretext`, stores the API on `this.pretext`, logs `[pretext-hero] ready`, returns `this`.
- - `dispose()` — no-op for now; reserved for later tasks.
+ - `constructor(root)` — `root` is the `.hero` element. Caches references to `.hero-content`, `.hero-title`, `.hero-subtitle`, `.hero-avatar`.
+ - `async init()` — dynamic-imports `@chenglou/pretext`, stores the API on `this.pretext`, logs `[pretext-hero] ready`, returns `this`.
+ - `dispose()` — no-op for now; reserved for later tasks.
3. **Modify [features.html](../../features.html)** — at the bottom of `<body>`, add a small bootstrap `<script type="module">` that:
- - Parses `new URLSearchParams(location.search).get('pretext')`.
- - If the flag is `'1'` (or `'2'`, `'3'`, `'4'` — room for later tasks to enable themselves), dynamic-imports `/src/features/hero-pretext.js` and calls `new PretextHero(document.querySelector('.hero')).init()`.
- - Wraps the whole thing in `try/catch` so a failure leaves the page in its current state.
+ - Parses `new URLSearchParams(location.search).get('pretext')`.
+ - If the flag is `'1'` (or `'2'`, `'3'`, `'4'` — room for later tasks to enable themselves), dynamic-imports `/src/features/hero-pretext.js` and calls `new PretextHero(document.querySelector('.hero')).init()`.
+ - Wraps the whole thing in `try/catch` so a failure leaves the page in its current state.
4. **Do NOT** modify [features.css](../../features.css) in this task.
## Audit checklist
diff --git a/prompts/pretext/02-hero-text-wrap.md b/prompts/pretext/02-hero-text-wrap.md
index 6772a03d4..3b9579a97 100644
--- a/prompts/pretext/02-hero-text-wrap.md
+++ b/prompts/pretext/02-hero-text-wrap.md
@@ -17,14 +17,14 @@ Default (`?pretext=1` or no flag) continues to use the CSS-only grid layout. The
## Deliverable
1. **Extend [src/features/hero-pretext.js](../../src/features/hero-pretext.js)**:
- - Add `enableStaticWrap()` method triggered when the flag is `>= 2`.
- - Computes the avatar's bounding circle in page-space via `getBoundingClientRect()` (read once, cached).
- - Calls Pretext's layout API with the subtitle text + the avatar circle as an exclusion. **Verify the exact API by reading `node_modules/@chenglou/pretext/` + [chenglou.me/pretext](https://chenglou.me/pretext/) Dragon/Editorial demos before implementing.** If the public API doesn't support per-line exclusion, fall back to splitting the subtitle into a 2-column flow that flanks the avatar (see §Fallback).
- - Renders laid-out lines into an absolutely-positioned overlay `<div class="hero-subtitle-pretext">` inside `.hero-content`, replacing the original `.hero-subtitle` visually (keep the original in DOM as `aria-hidden="false"` for screen readers; mark the overlay `aria-hidden="true"`).
- - On `resize` (debounced ~120ms), recompute and re-render.
+ - Add `enableStaticWrap()` method triggered when the flag is `>= 2`.
+ - Computes the avatar's bounding circle in page-space via `getBoundingClientRect()` (read once, cached).
+ - Calls Pretext's layout API with the subtitle text + the avatar circle as an exclusion. **Verify the exact API by reading `node_modules/@chenglou/pretext/` + [chenglou.me/pretext](https://chenglou.me/pretext/) Dragon/Editorial demos before implementing.** If the public API doesn't support per-line exclusion, fall back to splitting the subtitle into a 2-column flow that flanks the avatar (see §Fallback).
+ - Renders laid-out lines into an absolutely-positioned overlay `<div class="hero-subtitle-pretext">` inside `.hero-content`, replacing the original `.hero-subtitle` visually (keep the original in DOM as `aria-hidden="false"` for screen readers; mark the overlay `aria-hidden="true"`).
+ - On `resize` (debounced ~120ms), recompute and re-render.
2. **Add CSS to [features.css](../../features.css)** under a new `/* ── Pretext overlay ─── */` section:
- - `.hero-subtitle-pretext` — absolute positioned, matches `.hero-subtitle` typography (font, size, color, weight, line-height) via CSS custom props or explicit rules.
- - When Pretext is active, hide the original `.hero-subtitle` via a `.pretext-active` class on `.hero` (`.pretext-active .hero-subtitle { visibility: hidden; }`). This keeps the layout reserved if Pretext fails to paint.
+ - `.hero-subtitle-pretext` — absolute positioned, matches `.hero-subtitle` typography (font, size, color, weight, line-height) via CSS custom props or explicit rules.
+ - When Pretext is active, hide the original `.hero-subtitle` via a `.pretext-active` class on `.hero` (`.pretext-active .hero-subtitle { visibility: hidden; }`). This keeps the layout reserved if Pretext fails to paint.
3. **No layout thrash** — all `getBoundingClientRect()` reads happen up front; writes follow. Use a single `requestAnimationFrame` to paint lines.
## Audit checklist
diff --git a/prompts/pretext/03-gaze-follow.md b/prompts/pretext/03-gaze-follow.md
index eec179d0c..0e0c1abe1 100644
--- a/prompts/pretext/03-gaze-follow.md
+++ b/prompts/pretext/03-gaze-follow.md
@@ -15,12 +15,12 @@ With `?pretext=3` (or `?gaze=1` — choose one, document it), hovering the hero
## Deliverable
1. **Extend [src/features/hero-pretext.js](../../src/features/hero-pretext.js)** (or add a small sibling `src/features/gaze-follow.js` and import it — your call, document the choice):
- - `enableGazeFollow()` method triggered by the flag.
- - Attach `pointermove` (throttled to rAF) on `.hero` — convert cursor position to a pair of offsets relative to the avatar center, normalized to `[-1, 1]` per axis.
- - Map to orbit deltas: max ±15° on theta (horizontal), max ±8° on phi (vertical). Feel free to tune, but keep magnitudes subtle.
- - Disable `auto-rotate` while tracking; re-enable after 1.2s of idle (no pointer movement) or on `pointerleave`.
- - Smooth toward target with a critically-damped spring or `lerp` with `alpha ≈ 0.12` per frame — no stuttering, no overshoot.
- - Honor `prefers-reduced-motion: reduce` — if set, skip the entire feature and leave `auto-rotate` on.
+ - `enableGazeFollow()` method triggered by the flag.
+ - Attach `pointermove` (throttled to rAF) on `.hero` — convert cursor position to a pair of offsets relative to the avatar center, normalized to `[-1, 1]` per axis.
+ - Map to orbit deltas: max ±15° on theta (horizontal), max ±8° on phi (vertical). Feel free to tune, but keep magnitudes subtle.
+ - Disable `auto-rotate` while tracking; re-enable after 1.2s of idle (no pointer movement) or on `pointerleave`.
+ - Smooth toward target with a critically-damped spring or `lerp` with `alpha ≈ 0.12` per frame — no stuttering, no overshoot.
+ - Honor `prefers-reduced-motion: reduce` — if set, skip the entire feature and leave `auto-rotate` on.
2. **No CSS changes** required. If you need to hint interactivity (e.g. `cursor: none` or a subtle reticle), propose it in the reporting section but do not ship it.
## Audit checklist
@@ -46,9 +46,9 @@ With `?pretext=3` (or `?gaze=1` — choose one, document it), hovering the hero
1. `node --check` the new/modified JS file.
2. `npx vite build` completes.
3. Dev server, `/features?pretext=3`:
- - Move cursor in a slow circle over the hero → avatar head tracks smoothly.
- - Flick the cursor left↔right fast → no stutter, no snap-back.
- - Leave the hero → ~400ms eased return → auto-rotate resumes within ~1.2s.
+ - Move cursor in a slow circle over the hero → avatar head tracks smoothly.
+ - Flick the cursor left↔right fast → no stutter, no snap-back.
+ - Leave the hero → ~400ms eased return → auto-rotate resumes within ~1.2s.
4. `prefers-reduced-motion: reduce` set in OS or DevTools → feature disabled, auto-rotate unchanged.
5. Touch device (DevTools device emulation) → feature disabled.
6. DevTools Performance → `pointermove`-driven frames stay under 16ms.
diff --git a/prompts/pretext/04-dragon-mode.md b/prompts/pretext/04-dragon-mode.md
index 7ae90afb2..b5acd7603 100644
--- a/prompts/pretext/04-dragon-mode.md
+++ b/prompts/pretext/04-dragon-mode.md
@@ -22,25 +22,25 @@ All other flags (`?pretext=1`, `=2`, `=3`) behave as before.
## Deliverable
1. **Extend [src/features/hero-pretext.js](../../src/features/hero-pretext.js)**:
- - `enableDragonMode()` method, activated when the flag is `>= 4`.
- - Records the avatar's "home" rect on init.
- - Adds `.hero--dragon` class to the hero, which in CSS lets the avatar use `position: absolute; inset: auto; transform: translate3d(x, y, 0);`.
- - `pointermove` (rAF-coalesced) sets a target (x, y) in hero-local coordinates, clamped so the avatar stays fully within `.hero`.
- - Integrator runs on `requestAnimationFrame`:
- - Damped spring toward target: `stiffness ≈ 120`, `damping ≈ 20`, `mass ≈ 1`. Tune for a "trailing fish" feel.
- - Applies translation via `transform` on `.hero-avatar` (never left/top).
- - Reads the avatar's new center, computes bounding circle, calls Pretext to re-lay the subtitle, paints via the same `.hero-subtitle-pretext` overlay from task 02.
- - `pointerleave` on `.hero`: target becomes home position; integrator continues until `|velocity|` and `|home - position|` are both below thresholds; then the class is removed and task 02's static layout takes over.
- - `prefers-reduced-motion: reduce` → fully disabled; falls back to task 02 behavior.
- - Touch devices (`matchMedia('(hover: none)')`) → disabled; falls back to task 02.
+ - `enableDragonMode()` method, activated when the flag is `>= 4`.
+ - Records the avatar's "home" rect on init.
+ - Adds `.hero--dragon` class to the hero, which in CSS lets the avatar use `position: absolute; inset: auto; transform: translate3d(x, y, 0);`.
+ - `pointermove` (rAF-coalesced) sets a target (x, y) in hero-local coordinates, clamped so the avatar stays fully within `.hero`.
+ - Integrator runs on `requestAnimationFrame`:
+ - Damped spring toward target: `stiffness ≈ 120`, `damping ≈ 20`, `mass ≈ 1`. Tune for a "trailing fish" feel.
+ - Applies translation via `transform` on `.hero-avatar` (never left/top).
+ - Reads the avatar's new center, computes bounding circle, calls Pretext to re-lay the subtitle, paints via the same `.hero-subtitle-pretext` overlay from task 02.
+ - `pointerleave` on `.hero`: target becomes home position; integrator continues until `|velocity|` and `|home - position|` are both below thresholds; then the class is removed and task 02's static layout takes over.
+ - `prefers-reduced-motion: reduce` → fully disabled; falls back to task 02 behavior.
+ - Touch devices (`matchMedia('(hover: none)')`) → disabled; falls back to task 02.
2. **CSS additions in [features.css](../../features.css)** under `/* ── Dragon mode ─── */`:
- - `.hero--dragon .hero-avatar { position: absolute; top: 0; left: 0; will-change: transform; }`
- - `.hero--dragon .hero-content` retains its width — text column no longer shares the grid with the avatar; set `grid-column: 1 / -1` so the subtitle has full-hero width to reflow in.
- - Disable `.hero-avatar-ring`/`pulse`/`tag` during dragon mode if they interfere with the feel (acceptable to hide them for this mode).
- - Ensure z-index: the avatar stays above the text overlay but below `.hero-bg` glows? Decide and document. Default recommendation: avatar above text (parting-water metaphor).
+ - `.hero--dragon .hero-avatar { position: absolute; top: 0; left: 0; will-change: transform; }`
+ - `.hero--dragon .hero-content` retains its width — text column no longer shares the grid with the avatar; set `grid-column: 1 / -1` so the subtitle has full-hero width to reflow in.
+ - Disable `.hero-avatar-ring`/`pulse`/`tag` during dragon mode if they interfere with the feel (acceptable to hide them for this mode).
+ - Ensure z-index: the avatar stays above the text overlay but below `.hero-bg` glows? Decide and document. Default recommendation: avatar above text (parting-water metaphor).
3. **Performance budget**:
- - Frame budget for Pretext relayout: ≤4ms on a mid-range laptop (measure with `performance.now()`).
- - If the measured cost exceeds 8ms over a 30-frame rolling window, **automatically downgrade** — disable per-frame reflow, keep cursor chase, fall back to task 02's static wrap. Log a single `[pretext-hero] dragon downgraded` warning. This guard is mandatory.
+ - Frame budget for Pretext relayout: ≤4ms on a mid-range laptop (measure with `performance.now()`).
+ - If the measured cost exceeds 8ms over a 30-frame rolling window, **automatically downgrade** — disable per-frame reflow, keep cursor chase, fall back to task 02's static wrap. Log a single `[pretext-hero] dragon downgraded` warning. This guard is mandatory.
## Audit checklist
@@ -68,13 +68,13 @@ All other flags (`?pretext=1`, `=2`, `=3`) behave as before.
1. `node --check` on the modified JS.
2. `npx vite build` completes.
3. `/features?pretext=4`:
- - Slow circle → avatar trails smoothly; subtitle parts.
- - Fast flick → avatar lags realistically; no stutter; subtitle keeps up.
- - Cursor out → eased return home; static wrap resumes.
+ - Slow circle → avatar trails smoothly; subtitle parts.
+ - Fast flick → avatar lags realistically; no stutter; subtitle keeps up.
+ - Cursor out → eased return home; static wrap resumes.
4. DevTools Performance, 10s recording of a circular mouse motion:
- - p95 frame time < 16ms.
- - Long tasks < 50ms.
- - Paste the Pretext relayout cost (mean/p95) into the reporting section.
+ - p95 frame time < 16ms.
+ - Long tasks < 50ms.
+ - Paste the Pretext relayout cost (mean/p95) into the reporting section.
5. Force the downgrade — set the threshold very low temporarily, confirm the warning fires and reflow stops but the chase continues.
6. `prefers-reduced-motion: reduce` → falls back to task 02 exactly.
7. Mobile emulation → falls back to task 02.
diff --git a/prompts/scalability/01-dispose.md b/prompts/scalability/01-dispose.md
index 2a47133ce..6dff52f05 100644
--- a/prompts/scalability/01-dispose.md
+++ b/prompts/scalability/01-dispose.md
@@ -15,14 +15,15 @@ Add a `dispose()` method on `Viewer` that fully tears down the instance, so `vie
## Deliverable
1. Modified [src/viewer.js](../../src/viewer.js) with:
- - A new `dispose()` method
- - All listener callbacks stored on `this._…` fields during construction so they can be removed
- - The existing `window.addEventListener('resize', …)` and `window.addEventListener('keydown', …)` — currently anonymous/bound inline — refactored to stored bound handlers
+ - A new `dispose()` method
+ - All listener callbacks stored on `this._…` fields during construction so they can be removed
+ - The existing `window.addEventListener('resize', …)` and `window.addEventListener('keydown', …)` — currently anonymous/bound inline — refactored to stored bound handlers
2. Updated callers (check [src/app.js](../../src/app.js), [src/avatar-creator.js](../../src/avatar-creator.js)) that destroy or recreate viewers — call `dispose()` before discarding.
## Audit checklist — must handle all of these
**three.js resources (constructor)**
+
- `this.renderer` → `renderer.dispose()`, then remove `renderer.domElement` from `this.el`, then `renderer.forceContextLoss()` is optional but recommended
- `this.pmremGenerator` → `.dispose()`
- `this.neutralEnvironment` (texture from PMREMGenerator) → `.dispose()`
@@ -36,6 +37,7 @@ Add a `dispose()` method on `Viewer` that fully tears down the instance, so `vie
- `this.content` → reuse existing `clear()` logic
**UI resources**
+
- `this.stats` → `stats.dom.remove()`
- `this.gui` (dat.gui) → `gui.destroy()`
- `this.annotationEls` → `.forEach((a) => a.el.remove())`
@@ -43,6 +45,7 @@ Add a `dispose()` method on `Viewer` that fully tears down the instance, so `vie
- Any canvas overlays for annotations (see [src/annotations.js](../../src/annotations.js))
**Listeners / observers / RAF**
+
- `cancelAnimationFrame(this._rafId)` and null it
- `document.removeEventListener('visibilitychange', this._onVisibilityChange)`
- `this._intersectionObserver?.disconnect()`
@@ -50,6 +53,7 @@ Add a `dispose()` method on `Viewer` that fully tears down the instance, so `vie
- `window.removeEventListener('keydown', this._onKeyDown)` — **refactor the current anonymous `(e) => …` handler** at roughly lines 182–184 to a stored bound handler
**State**
+
- Null out `this.content`, `this.mixer`, `this.clips`, `this.scene`, `this.renderer`, `this.controls`, `this.gui` at the end of dispose, so accidental reuse fails loudly rather than silently.
## Constraints
@@ -63,14 +67,14 @@ Add a `dispose()` method on `Viewer` that fully tears down the instance, so `vie
1. `node --check src/viewer.js` — parses.
2. Manually in a browser console after the app loads:
- ```js
- window.app.viewer.dispose();
- // Check: no errors in console
- // Check: renderer.domElement no longer in DOM
- // Check: GUI panel gone
- // Check: stats panel gone
- // Call it again — should not throw
- ```
+ ```js
+ window.app.viewer.dispose();
+ // Check: no errors in console
+ // Check: renderer.domElement no longer in DOM
+ // Check: GUI panel gone
+ // Check: stats panel gone
+ // Call it again — should not throw
+ ```
3. Create a second viewer (`window.app.createViewer()` or equivalent) and confirm it works.
4. Load a scene, toggle env, load another scene, dispose, recreate, repeat — observe memory does not grow in DevTools Memory tab across several cycles.
@@ -84,6 +88,7 @@ Add a `dispose()` method on `Viewer` that fully tears down the instance, so `vie
## Reporting
At the end, summarise:
+
- What was disposed
- Which listeners were refactored to stored handlers
- Any resource you found that had no cleanup path and that you added
diff --git a/prompts/scalability/02-render-on-demand.md b/prompts/scalability/02-render-on-demand.md
index a16fc621a..ffdae5f29 100644
--- a/prompts/scalability/02-render-on-demand.md
+++ b/prompts/scalability/02-render-on-demand.md
@@ -24,8 +24,8 @@ Modified [src/viewer.js](../../src/viewer.js) with:
1. `invalidate()` method on `Viewer`.
2. Reworked `animate()`:
- - If any animation mixer action is active (`this._animating === true`) → keep looping (`requestAnimationFrame(this.animate)`) and updating mixer.
- - Else → render once if `_needsRender`, then stop scheduling.
+ - If any animation mixer action is active (`this._animating === true`) → keep looping (`requestAnimationFrame(this.animate)`) and updating mixer.
+ - Else → render once if `_needsRender`, then stop scheduling.
3. `_needsRender` flag set by `invalidate()`, cleared in `animate()` after rendering.
4. `_animating` flag maintained when animation clips play/pause/finish.
5. Invalidation wired into every mutation site — see list below.
@@ -64,6 +64,7 @@ Audit the full file. At minimum:
- `controls.update()` currently runs every frame inside `animate()`; it still needs to run when auto-rotate is active (which is why auto-rotate sets `_animating = true`). When not animating, `controls.update()` only needs to run when user interacts — but OrbitControls' damping also needs `update()` called each frame until damping settles. **If `controls.enableDamping === true`, treat user interaction as short-lived animation**: on `start` event begin animating, on `end` event stop after damping settles (a few RAF ticks). Simpler alternative: on `change` event, invalidate and always call `controls.update()` inside the render path whether animating or not.
Recommended simplest correct approach:
+
- Every `change` event → invalidate.
- `animate()` always calls `controls.update()` before `renderer.render()`.
- If damping is on, also call `invalidate()` for one extra frame after `change` to let damping settle — in practice OrbitControls keeps firing `change` during damping, so this is self-sustaining.
diff --git a/prompts/scalability/03-module-split.md b/prompts/scalability/03-module-split.md
index 18db0c25b..1ad149c25 100644
--- a/prompts/scalability/03-module-split.md
+++ b/prompts/scalability/03-module-split.md
@@ -114,13 +114,13 @@ After each step: `node --check` and (if possible) load the app and smoke-test.
1. `node --check` each new file.
2. Run `npx vite build` — must succeed or fail only on the known pre-existing `@avaturn/sdk` error in `avatar-creator.js`, which is unrelated.
3. Manual smoke test:
- - App loads, drop a GLB, model appears
- - Change environment from the GUI — IBL updates
- - Toggle background, wireframe, skeleton, grid
- - Play animations from the GUI
- - Resize the window — camera aspect updates
- - Press `p` — screenshot downloads
- - Open the model info panel — fields populated
+ - App loads, drop a GLB, model appears
+ - Change environment from the GUI — IBL updates
+ - Toggle background, wireframe, skeleton, grid
+ - Play animations from the GUI
+ - Resize the window — camera aspect updates
+ - Press `p` — screenshot downloads
+ - Open the model info panel — fields populated
4. Compare the network tab / memory before and after — should be identical.
## Reporting
diff --git a/prompts/scalability/04-web-component.md b/prompts/scalability/04-web-component.md
index dc1c574ca..5334f3cb4 100644
--- a/prompts/scalability/04-web-component.md
+++ b/prompts/scalability/04-web-component.md
@@ -35,19 +35,19 @@ Use `mv-viewer`. Do **not** use `model-viewer` — that's Google's element and t
## Attributes to support (initial set)
-| Attribute | Type | Default | Notes |
-|-----------|------|---------|-------|
-| `src` | URL | — | glTF or GLB URL. Setting/changing triggers load. |
-| `environment` | string | `"neutral"` | Matches `environments.js` IDs. |
-| `exposure` | number | `1.0` | Renderer exposure. |
-| `tone-mapping` | `"aces" \| "linear"` | `"aces"` | |
-| `background-color` | CSS color | `"#191919"` (match existing default) | |
-| `auto-rotate` | boolean attr | off | Presence-toggle. |
-| `camera-controls` | boolean attr | **on** | Enable OrbitControls. |
-| `reveal` | `"auto" \| "interaction"` | `"auto"` | `"interaction"` defers GLB fetch until first click or pointer enter. |
-| `poster` | URL | — | Image shown before reveal. |
-| `disable-zoom` | boolean attr | off | |
-| `disable-pan` | boolean attr | off | |
+| Attribute | Type | Default | Notes |
+| ------------------ | ------------------------- | ------------------------------------ | -------------------------------------------------------------------- |
+| `src` | URL | — | glTF or GLB URL. Setting/changing triggers load. |
+| `environment` | string | `"neutral"` | Matches `environments.js` IDs. |
+| `exposure` | number | `1.0` | Renderer exposure. |
+| `tone-mapping` | `"aces" \| "linear"` | `"aces"` | |
+| `background-color` | CSS color | `"#191919"` (match existing default) | |
+| `auto-rotate` | boolean attr | off | Presence-toggle. |
+| `camera-controls` | boolean attr | **on** | Enable OrbitControls. |
+| `reveal` | `"auto" \| "interaction"` | `"auto"` | `"interaction"` defers GLB fetch until first click or pointer enter. |
+| `poster` | URL | — | Image shown before reveal. |
+| `disable-zoom` | boolean attr | off | |
+| `disable-pan` | boolean attr | off | |
Implement `observedAttributes` and `attributeChangedCallback` for all of these.
@@ -64,6 +64,7 @@ Bubbling, composed `CustomEvent`s on the element:
## Lifecycle
**`connectedCallback`:**
+
- Create a light-DOM `<div class="mv-viewer__stage">` sized to fill the element.
- Instantiate `new Viewer(stageEl, opts)` where `opts` is derived from current attributes.
- If `reveal === "interaction"`, do **not** call `viewer.load` yet. Show the poster (if any) or an empty stage. Attach a one-shot click/pointerenter listener that removes the poster and calls `viewer.load(src)`.
@@ -71,23 +72,25 @@ Bubbling, composed `CustomEvent`s on the element:
- Wire viewer events → element events.
**`disconnectedCallback`:**
+
- Call `viewer.dispose()` (**depends on [01-dispose.md](./01-dispose.md)** shipping first).
- Null out references.
- Disconnect any observers created by the element.
**`attributeChangedCallback(name, old, next)`:**
+
- If the viewer hasn't been created yet (element not yet connected), stash the change on a pending-options object.
- Otherwise, translate to a `viewer.*` method call:
- - `src` → `viewer.clear(); viewer.load(next, '', new Map())`
- - `environment` → `viewer.state.environment = …; viewer.updateEnvironment(); viewer.invalidate?.()`
- - `exposure` → `viewer.renderer.toneMappingExposure = Number(next); viewer.invalidate?.()`
- - `tone-mapping` → map to three.js constants (`ACESFilmicToneMapping` | `LinearToneMapping`); `viewer.invalidate?.()`
- - `background-color` → `viewer.state.bgColor = next; viewer.updateBackground(); viewer.invalidate?.()`
- - `auto-rotate` → `viewer.state.autoRotate = this.hasAttribute('auto-rotate'); viewer.controls.autoRotate = …; viewer.invalidate?.()`
- - `camera-controls` → `viewer.controls.enabled = this.hasAttribute('camera-controls')` (default true if unset)
- - `disable-zoom` → `viewer.controls.enableZoom = !this.hasAttribute('disable-zoom')`
- - `disable-pan` → `viewer.controls.enablePan = !this.hasAttribute('disable-pan')`
- - `reveal` / `poster` → only meaningful at connect time; ignore runtime changes, or log a warning.
+ - `src` → `viewer.clear(); viewer.load(next, '', new Map())`
+ - `environment` → `viewer.state.environment = …; viewer.updateEnvironment(); viewer.invalidate?.()`
+ - `exposure` → `viewer.renderer.toneMappingExposure = Number(next); viewer.invalidate?.()`
+ - `tone-mapping` → map to three.js constants (`ACESFilmicToneMapping` | `LinearToneMapping`); `viewer.invalidate?.()`
+ - `background-color` → `viewer.state.bgColor = next; viewer.updateBackground(); viewer.invalidate?.()`
+ - `auto-rotate` → `viewer.state.autoRotate = this.hasAttribute('auto-rotate'); viewer.controls.autoRotate = …; viewer.invalidate?.()`
+ - `camera-controls` → `viewer.controls.enabled = this.hasAttribute('camera-controls')` (default true if unset)
+ - `disable-zoom` → `viewer.controls.enableZoom = !this.hasAttribute('disable-zoom')`
+ - `disable-pan` → `viewer.controls.enablePan = !this.hasAttribute('disable-pan')`
+ - `reveal` / `poster` → only meaningful at connect time; ignore runtime changes, or log a warning.
> Several `viewer.invalidate?.()` calls above are hedged because [02-render-on-demand.md](./02-render-on-demand.md) hasn't shipped yet. The optional-chaining means this code works both before and after that lands.
@@ -104,10 +107,29 @@ Keep this simple — a CSS fade is fine. No animation library.
The element defines its own size via CSS. Default stylesheet, inlined into the element via a scoped `<style>` tag appended once to `document.head`:
```css
-mv-viewer { display: block; position: relative; width: 100%; height: 480px; background: #191919; }
-mv-viewer .mv-viewer__stage { width: 100%; height: 100%; }
-mv-viewer .mv-viewer__poster { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; transition: opacity .3s; }
-mv-viewer .mv-viewer__poster[data-hidden] { opacity: 0; pointer-events: none; }
+mv-viewer {
+ display: block;
+ position: relative;
+ width: 100%;
+ height: 480px;
+ background: #191919;
+}
+mv-viewer .mv-viewer__stage {
+ width: 100%;
+ height: 100%;
+}
+mv-viewer .mv-viewer__poster {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ transition: opacity 0.3s;
+}
+mv-viewer .mv-viewer__poster[data-hidden] {
+ opacity: 0;
+ pointer-events: none;
+}
```
Do not use Shadow DOM. Light DOM is simpler for this case and integrates with the site's CSS.
@@ -124,10 +146,10 @@ Do not use Shadow DOM. Light DOM is simpler for this case and integrates with th
1. `node --check src/components/ModelViewerElement.js`.
2. Open `examples/web-component.html` in a browser (via `npx vite --port 3000` with the example added to the Vite entry or served as a static file).
3. Test each variant:
- - Minimal `<mv-viewer src="sample.glb">` loads and renders.
- - `auto-rotate` attribute → model rotates. Remove attribute → stops.
- - `reveal="interaction"` + `poster` → poster visible; click → poster fades, model loads.
- - Change `exposure` attribute from DevTools → lighting updates immediately.
+ - Minimal `<mv-viewer src="sample.glb">` loads and renders.
+ - `auto-rotate` attribute → model rotates. Remove attribute → stops.
+ - `reveal="interaction"` + `poster` → poster visible; click → poster fades, model loads.
+ - Change `exposure` attribute from DevTools → lighting updates immediately.
4. Confirm events fire: attach `el.addEventListener('load', …)` in the demo and log.
5. Remove the element from the DOM (`el.remove()`) → no uncaught errors.
diff --git a/prompts/scalability/05-shared-renderer.md b/prompts/scalability/05-shared-renderer.md
index 28fb59e15..86531f0b5 100644
--- a/prompts/scalability/05-shared-renderer.md
+++ b/prompts/scalability/05-shared-renderer.md
@@ -11,6 +11,7 @@ Google's `<model-viewer>` solves this with one shared `WebGLRenderer` drawing in
## Goal
Introduce a `Renderer` singleton that:
+
- Owns the only `WebGLRenderer` in the application.
- Lets each viewer instance request renders via `renderer.render(scene, camera, targetCanvas)`.
- Schedules frames across instances based on visibility and animation state.
@@ -19,27 +20,28 @@ Introduce a `Renderer` singleton that:
## Deliverable
1. `src/viewer/Renderer.js` exporting a singleton:
- ```js
- export class Renderer {
- static singleton;
- constructor();
- registerScene(scene); // returns handle
- unregisterScene(handle);
- render(scene, camera, targetCanvas2D); // synchronous blit
- invalidate(scene); // mark dirty for next frame
- dispose();
- }
- ```
+ ```js
+ export class Renderer {
+ static singleton;
+ constructor();
+ registerScene(scene); // returns handle
+ unregisterScene(handle);
+ render(scene, camera, targetCanvas2D); // synchronous blit
+ invalidate(scene); // mark dirty for next frame
+ dispose();
+ }
+ ```
2. Refactor [src/viewer.js](../../src/viewer.js) to:
- - No longer create its own `WebGLRenderer`.
- - Own a 2D canvas (`CanvasRenderingContext2D`) that it mounts into `this.el`.
- - Register with the shared `Renderer` on construct, unregister on dispose.
- - Route all `this.renderer.render(...)` calls through the shared renderer.
+ - No longer create its own `WebGLRenderer`.
+ - Own a 2D canvas (`CanvasRenderingContext2D`) that it mounts into `this.el`.
+ - Register with the shared `Renderer` on construct, unregister on dispose.
+ - Route all `this.renderer.render(...)` calls through the shared renderer.
3. Update all places that read from `this.renderer` directly — e.g., PMREM generator creation, screenshot export via `this.renderer.domElement.toBlob()`, `pixelRatio` setting, shadow map config, tone mapping. These need to be rerouted either to the shared renderer (shared config) or computed differently (screenshots need an explicit render-to-target-canvas step).
## Architecture notes
**Compositing path.** Each viewer mounts a 2D `<canvas>` sized to its element. The shared WebGL canvas is sized to the largest visible viewer's pixel dimensions (or a configured max). On render:
+
1. Set WebGL renderer size to the target viewer's pixel size.
2. `renderer.render(scene, camera)`.
3. `target2dCtx.drawImage(webglCanvas, 0, 0, w, h)`.
@@ -49,18 +51,22 @@ This adds a copy per frame but saves N–1 WebGL contexts.
Alternative (more modern, less broadly supported): `renderer.domElement.transferControlToOffscreen()` and assign as OffscreenCanvas — but requires a totally different pipeline. Prefer the drawImage path.
**Scheduler.**
+
- Maintain a list of registered scenes + their visibility/dirty state.
- Each frame: pick visible + (dirty OR animating) scenes, render each in priority order.
- Budget: a max of e.g. 4 renders per frame, defer the rest.
- If all registered scenes are idle, don't schedule RAF.
**Shared config.**
+
- Tone mapping, exposure, pixel ratio — these are per-render settings, applied just before each `renderer.render`. Store them per-scene in the viewer, apply on render.
**PMREM.**
+
- Move PMREM generator to the shared renderer (it also needs a GL context). Expose a `Renderer.singleton.pmrem` or similar. Environment textures become globally cached by URL.
**Screenshot.**
+
- `takeScreenshot()` currently uses `this.renderer.domElement.toBlob()`. After this refactor, capture from the per-viewer 2D canvas (which mirrors the last frame) or force a fresh render to a RenderTarget → readPixels → canvas → toBlob.
## Risks / things that bite
diff --git a/prompts/selfie-agent/01-camera-capture-ui.md b/prompts/selfie-agent/01-camera-capture-ui.md
index 249d19aa5..33db1bb44 100644
--- a/prompts/selfie-agent/01-camera-capture-ui.md
+++ b/prompts/selfie-agent/01-camera-capture-ui.md
@@ -22,10 +22,10 @@ On accept, the flow hands the `Blob` off to a single exported function `onCaptur
## Deliverable
1. **New file: `src/selfie-capture.js`** — class `SelfieCapture` with:
- - `constructor(rootEl, { onCaptureReady })`
- - `mount()` / `unmount()` — idempotent
- - Internal `_startCamera()`, `_stopCamera()`, `_capture()`, `_showReview(blob)`, `_retake()`, `_handleUploadFallback(file)`
- - All `addEventListener` callbacks stored on `this._…` fields so `unmount()` can remove them cleanly (follow the stored-bound-handler pattern used in [src/avatar-creator.js](../../src/avatar-creator.js)).
+ - `constructor(rootEl, { onCaptureReady })`
+ - `mount()` / `unmount()` — idempotent
+ - Internal `_startCamera()`, `_stopCamera()`, `_capture()`, `_showReview(blob)`, `_retake()`, `_handleUploadFallback(file)`
+ - All `addEventListener` callbacks stored on `this._…` fields so `unmount()` can remove them cleanly (follow the stored-bound-handler pattern used in [src/avatar-creator.js](../../src/avatar-creator.js)).
2. **New file: `public/create.html`** — minimal skeleton (DOCTYPE, meta viewport, single `<div id="create-root">`). Import `../src/selfie-capture.js` via a `<script type="module">` and call `new SelfieCapture(root, { onCaptureReady }).mount()`.
3. **Edit [vercel.json](../../vercel.json)** — add `{ "src": "/create", "dest": "/public/create.html" }` and `{ "src": "/create/", "dest": "/public/create.html" }` above the catch-all `/public/$1` route.
4. **Edit [index.html](../../index.html)** — make `#create-avatar-btn` navigate to `/create` (use an `<a>` or plain `window.location = '/create'` click handler). Keep the existing in-page Avaturn modal reachable via a "Skip — use the editor" link inside `/create` for users without a camera.
@@ -34,30 +34,36 @@ On accept, the flow hands the `Blob` off to a single exported function `onCaptur
## Audit checklist — must handle all of these
**Camera lifecycle**
+
- Request camera only after the user explicitly taps "Start camera" — never on mount. iOS Safari requires the prompt to happen inside a user gesture.
- Request `{ video: { facingMode: 'user', width: { ideal: 1024 }, height: { ideal: 1024 } }, audio: false }`.
- Store the `MediaStream` on `this._stream` and always stop all tracks (`this._stream.getTracks().forEach(t => t.stop())`) on: `unmount()`, retake-that-reopens-camera is fine but the previous stream must stop first, successful accept, navigation away (`pagehide` listener), and tab hidden (`visibilitychange` → pause/stop).
**Capture**
+
- Draw `<video>` onto a 1024×1024 `<canvas>` with center-crop (match shorter edge, centered).
- `canvas.toBlob(cb, 'image/jpeg', 0.92)`.
- Reject images smaller than 128×128 with an inline message.
**Review step**
+
- Show the frozen JPEG via `URL.createObjectURL(blob)` and `URL.revokeObjectURL` on retake / accept.
- Two buttons: **Use this photo** and **Retake**. Both must be thumb-reachable on mobile.
**Upload fallback**
+
- Hidden `<input type="file" accept="image/*" capture="user">`. `capture="user"` triggers the rear/front camera picker on mobile browsers that support it.
- Same review step as camera capture.
- Enforce a 10 MB client-side cap, reject anything else with an inline message.
**Errors** (no `alert()` — render inline under the preview)
+
- `NotAllowedError` / `PermissionDeniedError` → "Camera permission denied. Upload a photo instead." + surface the upload button.
- `NotFoundError` / `OverconstrainedError` → "No camera detected. Upload a photo instead."
- `NotReadableError` → "Camera is busy in another app. Close it and retry."
**Accessibility**
+
- The capture button is a real `<button>` with `aria-label="Take photo"`.
- Live preview `<video>` has `playsinline`, `muted`, `autoplay`, and no controls.
- Review step images have `alt="Captured photo"`.
@@ -92,6 +98,7 @@ On accept, the flow hands the `Blob` off to a single exported function `onCaptur
## Reporting
Report:
+
- Files created and their line counts.
- Files edited and which sections.
- Commands run (`node --check`, `npx vite build`) and their output.
diff --git a/prompts/selfie-agent/02-avaturn-session-bridge.md b/prompts/selfie-agent/02-avaturn-session-bridge.md
index c6d6d5bfc..32f3b6140 100644
--- a/prompts/selfie-agent/02-avaturn-session-bridge.md
+++ b/prompts/selfie-agent/02-avaturn-session-bridge.md
@@ -28,7 +28,11 @@ Callers receive structured errors:
```js
class SelfieAvatarError extends Error {
- constructor(code, message, cause) { super(message); this.code = code; this.cause = cause; }
+ constructor(code, message, cause) {
+ super(message);
+ this.code = code;
+ this.cause = cause;
+ }
}
// code ∈ 'quota_exceeded' | 'session_timeout' | 'pipeline_failed' | 'invalid_photo' | 'network'
```
@@ -42,10 +46,12 @@ class SelfieAvatarError extends Error {
## Audit checklist — must handle all of these
**Input validation**
+
- Reject blobs with `blob.type` not in `['image/jpeg', 'image/png', 'image/webp']` → `invalid_photo`.
- Reject blobs `size > 10 * 1024 * 1024` → `invalid_photo` (prompt 01 already caps this; enforce defensively).
**Photo upload step**
+
- `POST /api/avatars/presign` with `content_type: blob.type`, `size_bytes: blob.size`. Shape of the presign endpoint is locked today in [api/avatars/presign.js](../../api/avatars/presign.js). See also [src/account.js](../../src/account.js) `saveRemoteGlbToAccount` for a working client example of the same handshake.
- `PUT` the blob to `presign.upload_url` with the `content-type` header Avaturn will see.
- If the presign call returns `401` → throw `SelfieAvatarError('quota_exceeded'?, …)` → actually map `401` to `pipeline_failed` with a message "sign in required" — quota is `429`. Do not silently sign the user out.
@@ -53,8 +59,9 @@ class SelfieAvatarError extends Error {
- Emit `opts.onProgress('uploading_photo')` before and `'photo_uploaded'` after.
**Avaturn handoff**
+
- Prefer an SDK entry point that accepts a seed photo URL — check `@avaturn/sdk` for `createFromPhoto`, `photoAvatar`, `fromImage`, or equivalent. If none exists, document in a JSDoc comment on the function which symbol you actually called and why.
-- Pass the *public* URL form of the uploaded seed (from presign response — most likely a signed GET URL since the avatar is still private). If the SDK requires CORS-enabled URLs, note in the JSDoc.
+- Pass the _public_ URL form of the uploaded seed (from presign response — most likely a signed GET URL since the avatar is still private). If the SDK requires CORS-enabled URLs, note in the JSDoc.
- Subscribe to the same `export` event the existing [src/avatar-creator.js](../../src/avatar-creator.js) listens for, plus any `error` / `session-timeout` / `quota-exceeded` events the SDK emits.
- Wrap the whole Avaturn step in a 90s timeout via `AbortSignal.timeout(90_000)` combined with `opts.signal`. If both fire, the user's abort wins semantically.
- Emit `onProgress('generating_avatar')` before and `'avatar_ready'` after.
@@ -71,11 +78,13 @@ class SelfieAvatarError extends Error {
Log the full underlying error on `console.error` with a `[selfie-pipeline]` prefix — never swallow it silently.
**Teardown**
+
- On abort or failure, call `sdk.destroy()` if the SDK was initialised.
- Revoke any `URL.createObjectURL` you allocated.
- Do not leave the Avaturn iframe container mounted after the function returns — whether success or failure.
**UX in create.html**
+
- Progress is one visible string at a time, driven by `onProgress`.
- The Try-again button re-calls `createAvatarFromSelfie(blob, …)` with the same blob (cache it in memory; do not re-prompt the camera).
- Error panel surfaces the `code` as a subtle `data-error-code` attribute for QA / analytics, and the human message as the visible text.
@@ -111,6 +120,7 @@ Log the full underlying error on `console.error` with a `[selfie-pipeline]` pref
## Reporting
Report:
+
- Files created and their line counts.
- Files edited and which sections.
- The exact `@avaturn/sdk` symbol you used for the photo entry point and why.
diff --git a/prompts/selfie-agent/03-glb-pin-and-store.md b/prompts/selfie-agent/03-glb-pin-and-store.md
index ca250df3d..5c0cabaea 100644
--- a/prompts/selfie-agent/03-glb-pin-and-store.md
+++ b/prompts/selfie-agent/03-glb-pin-and-store.md
@@ -26,24 +26,27 @@ If the user is not signed in, redirect them through the existing wallet sign-in
## Deliverable
1. **New file: `src/selfie-persist.js`** — exports:
- ```js
- /**
- * @param {string} glbUrl - Avaturn-hosted GLB
- * @param {{ thumbnailUrl?: string,
- * avaturnSessionId?: string,
- * name: string,
- * description?: string,
- * slug: string }} meta
- * @returns {Promise<{ avatar: AvatarRow, agent: AgentRow }>}
- */
- export async function persistSelfieAgent(glbUrl, meta) { ... }
- ```
- Internally: fetch the GLB with `{ mode: 'cors' }`, compute `sha256`, presign, PUT, register via `POST /api/avatars`, then `POST /api/agents` with `{ name, description, avatar_id, skills: ['greet','present-model','remember'] }`, then fire-and-forget `linkWallet` via the existing endpoint `POST /api/agents/:id/wallet` with `{ wallet_address, chain_id }` read from the user's primary wallet.
+
+ ```js
+ /**
+ * @param {string} glbUrl - Avaturn-hosted GLB
+ * @param {{ thumbnailUrl?: string,
+ * avaturnSessionId?: string,
+ * name: string,
+ * description?: string,
+ * slug: string }} meta
+ * @returns {Promise<{ avatar: AvatarRow, agent: AgentRow }>}
+ */
+ export async function persistSelfieAgent(glbUrl, meta) { ... }
+ ```
+
+ Internally: fetch the GLB with `{ mode: 'cors' }`, compute `sha256`, presign, PUT, register via `POST /api/avatars`, then `POST /api/agents` with `{ name, description, avatar_id, skills: ['greet','present-model','remember'] }`, then fire-and-forget `linkWallet` via the existing endpoint `POST /api/agents/:id/wallet` with `{ wallet_address, chain_id }` read from the user's primary wallet.
2. **New API file: `api/agents/create.js`** (or extend [api/agents.js](../../api/agents.js)'s existing POST handler — whichever requires fewer new routes). It must accept `{ name, description, avatar_id, skills?, meta? }`, insert a row, and return `{ agent }`. Enforce:
- - `name` is validated by the same schema prompt 04 adds (`trim, min 2, max 32`, per-wallet unique, denylist).
- - `avatar_id` must belong to the caller (`SELECT ... WHERE id = $1 AND owner_id = $user`) — refuse with 404 otherwise.
- - Caller has fewer than N agents (soft cap: 10 — read from `plan_quotas` if present, else fall back to constant). Return 402 `quota_exceeded` if over.
+
+ - `name` is validated by the same schema prompt 04 adds (`trim, min 2, max 32`, per-wallet unique, denylist).
+ - `avatar_id` must belong to the caller (`SELECT ... WHERE id = $1 AND owner_id = $user`) — refuse with 404 otherwise.
+ - Caller has fewer than N agents (soft cap: 10 — read from `plan_quotas` if present, else fall back to constant). Return 402 `quota_exceeded` if over.
3. **Edit [vercel.json](../../vercel.json)** — only if you create a new file at `api/agents/create.js`. If you extend [api/agents.js](../../api/agents.js) instead, no route change is needed (it already handles POST via `handleCreate` in the same handler).
@@ -54,6 +57,7 @@ If the user is not signed in, redirect them through the existing wallet sign-in
## Audit checklist — must handle all of these
**GLB re-host**
+
- Fetch from Avaturn with `{ mode: 'cors' }`. If it fails CORS, log and fall back to a server-side proxy — but do **not** add a new proxy endpoint in this task; instead fail with a specific error code `glb_cors_blocked` and report it. A proxy endpoint is worth its own task.
- Compute `sha256` over the blob (use `crypto.subtle.digest` — match the helper in [src/account.js](../../src/account.js)).
- Presign via existing [api/avatars/presign.js](../../api/avatars/presign.js) with `content_type: 'model/gltf-binary'`, `size_bytes: blob.size`.
@@ -61,17 +65,21 @@ If the user is not signed in, redirect them through the existing wallet sign-in
- Register via existing `POST /api/avatars` with `{ storage_key, size_bytes, content_type, checksum_sha256, name, description, visibility: 'private', source: 'avaturn', source_meta: { source_url: glbUrl, avaturn_session_id } }`.
**Thumbnail (optional, don't block on failure)**
+
- If `meta.thumbnailUrl` is present, repeat the same presign+PUT+register loop for a PNG/JPEG, but do not create an avatar row for it — attach it via `PATCH /api/avatars/:id` `{ thumbnail_key }` on the primary row. If the `avatars` schema doesn't expose `thumbnail_key` in the register body today, **log and skip** rather than blocking agent creation.
**Agent row**
+
- `POST /api/agents` with `{ name, description, avatar_id, skills: ['greet','present-model','remember'] }`.
- On success, the server response shape is `{ agent }`. Pass it through.
- Then `POST /api/agents/:id/wallet` with the user's primary wallet (from layer 1 — look it up via `/api/auth/me` or a new helper). Fire-and-forget; the wallet link is nice-to-have, not blocking.
**Default-agent promotion**
+
- [api/agents.js](../../api/agents.js) `/me` already picks the oldest non-deleted agent as default (see `handleGetOrCreateMe`). For this task, the simplest option is: if the caller had a default placeholder agent auto-created earlier (with name `'Agent'` and no `avatar_id`), soft-delete it via `DELETE /api/agents/:id` so the new one becomes `/me`. Only delete the placeholder if it has `avatar_id IS NULL` — never delete a real avatar.
**Idempotency**
+
- If `persistSelfieAgent` is called twice with the same `glbUrl` in the same tab (e.g. user double-clicks Try-again), serialize via a module-level in-flight Promise — return the same Promise, don't start two uploads.
- `sessionStorage['pending_selfie_agent']` must be cleared on success and on explicit user cancel. It must not outlive a successful persistence (otherwise next load re-creates).
@@ -86,6 +94,7 @@ If the user is not signed in, redirect them through the existing wallet sign-in
| Anything else | `persist_failed` |
**Security**
+
- Never POST `owner_id` client-side — the server reads it from the session.
- Never POST a `storage_key` under another user's prefix. Existing presign enforces `u/{userId}/…` scoping; trust it.
- Do not log GLB bytes or checksums in analytics events. Log the `avatar.id` only after creation.
@@ -95,16 +104,16 @@ If the user is not signed in, redirect them through the existing wallet sign-in
- No new runtime dependencies.
- No new DB tables or columns. If you find the schema is missing something (e.g. `thumbnail_key`), note it in the report and skip the feature gracefully — schema migration is its own task.
- Do not touch [src/avatar-creator.js](../../src/avatar-creator.js) (the existing editor flow).
-- Do not touch the agent wallet-key generation in [api/_lib/agent-wallet.js](../../api/_lib/agent-wallet.js). It's generated by `handleGetOrCreateMe` already; a fresh `POST /api/agents` row should reuse the same helper in the server handler — or you can leave new-agent rows without an agent-wallet if the existing POST handler doesn't populate one. Note the behaviour in the report.
+- Do not touch the agent wallet-key generation in [api/\_lib/agent-wallet.js](../../api/_lib/agent-wallet.js). It's generated by `handleGetOrCreateMe` already; a fresh `POST /api/agents` row should reuse the same helper in the server handler — or you can leave new-agent rows without an agent-wallet if the existing POST handler doesn't populate one. Note the behaviour in the report.
## Verification
1. `node --check src/selfie-persist.js` and `node --check api/agents.js` (or `api/agents/create.js`) — pass.
2. `npx vite build` — passes.
3. Manual happy path: signed-in user with a linked wallet runs `/create` end-to-end — check Neon:
- - one new row in `avatars` with `source = 'avaturn'`, `owner_id = your user id`, `visibility = 'private'`.
- - one new row in `agent_identities` with `avatar_id` matching, `wallet_address` matching the user's primary wallet.
- - previous placeholder agent (if any) soft-deleted (`deleted_at IS NOT NULL`).
+ - one new row in `avatars` with `source = 'avaturn'`, `owner_id = your user id`, `visibility = 'private'`.
+ - one new row in `agent_identities` with `avatar_id` matching, `wallet_address` matching the user's primary wallet.
+ - previous placeholder agent (if any) soft-deleted (`deleted_at IS NOT NULL`).
4. Manual signed-out path: clear cookies, run `/create`, confirm redirect to `/login?return=/create`, sign in, confirm resume → same DB state as happy path. No duplicate avatar rows.
5. Manual idempotency: on the persistence screen, double-click Try-again — exactly one `avatars` row and one `agent_identities` row created.
6. Manual quota: temporarily set the soft cap to 0 — confirm UI surfaces `agent_quota_exceeded` and does not create an avatar row either (or does create + orphan it — whichever, document behaviour).
@@ -122,6 +131,7 @@ If the user is not signed in, redirect them through the existing wallet sign-in
## Reporting
Report:
+
- Files created / edited with line counts.
- Which server handler you extended (`api/agents.js` POST vs new `api/agents/create.js`).
- Whether the schema supports `thumbnail_key` — if not, note and skip.
diff --git a/prompts/selfie-agent/04-name-and-description.md b/prompts/selfie-agent/04-name-and-description.md
index 17791007b..76a857a7d 100644
--- a/prompts/selfie-agent/04-name-and-description.md
+++ b/prompts/selfie-agent/04-name-and-description.md
@@ -6,11 +6,11 @@ Repo: `/workspaces/3D`. Once the selfie pipeline (prompts 01-02) produces a GLB
Existing building blocks you'll reuse:
-- `slug` zod schema in [api/_lib/validate.js](../../api/_lib/validate.js) — lowercase alphanumeric + `-`/`_`, max 64 chars.
+- `slug` zod schema in [api/\_lib/validate.js](../../api/_lib/validate.js) — lowercase alphanumeric + `-`/`_`, max 64 chars.
- `agent_identities` table already has a `name` column but no `slug` column. This task **does not** add a column; slug is a derived, per-user-unique string enforced by checking `LOWER(name)` collisions at insert time. A proper slug column + routing is a later migration task.
- Wallet address for the caller is reachable via `/api/auth/me` and the `user_wallets` table (layer 1 — already shipped).
- Display surfaces that read the name: [src/agent-home.js](../../src/agent-home.js), the `agent-home.html` route, and the `.name` getter on [src/agent-identity.js](../../src/agent-identity.js).
-- Existing session auth helpers in [api/_lib/auth.js](../../api/_lib/auth.js) (`getSessionUser`) and the standard serverless endpoint shape in [api/CLAUDE.md](../../api/CLAUDE.md).
+- Existing session auth helpers in [api/\_lib/auth.js](../../api/_lib/auth.js) (`getSessionUser`) and the standard serverless endpoint shape in [api/CLAUDE.md](../../api/CLAUDE.md).
## Goal
@@ -31,27 +31,30 @@ On submit, hand `{ name, description, slug }` up the call chain so prompt 03 can
## Deliverable
1. **New file: `src/selfie-name-form.js`** — class `SelfieNameForm(rootEl, { onSubmit, initial })` with:
- - Form rendering name + description inputs, character counters, a Continue button.
- - Debounced (300ms) availability check against `GET /api/agents/check-name?slug=…` → `{ available, reason? }`.
- - Inline error messages under the name field: `"Name must be 2-32 characters."`, `"Name contains disallowed characters."`, `"That name isn't allowed."`, `"You already have an agent with that name."`.
- - Continue disabled until the current name is syntactically valid and remotely available.
- - `onSubmit({ name, description, slug })` fires on Continue click.
- - All listeners stored on `this._…` fields for clean `unmount()` (follow the pattern used in [src/avatar-creator.js](../../src/avatar-creator.js)).
+
+ - Form rendering name + description inputs, character counters, a Continue button.
+ - Debounced (300ms) availability check against `GET /api/agents/check-name?slug=…` → `{ available, reason? }`.
+ - Inline error messages under the name field: `"Name must be 2-32 characters."`, `"Name contains disallowed characters."`, `"That name isn't allowed."`, `"You already have an agent with that name."`.
+ - Continue disabled until the current name is syntactically valid and remotely available.
+ - `onSubmit({ name, description, slug })` fires on Continue click.
+ - All listeners stored on `this._…` fields for clean `unmount()` (follow the pattern used in [src/avatar-creator.js](../../src/avatar-creator.js)).
2. **New file: `src/selfie-denylist.js`** — export:
- - `DENYLIST: Set<string>` of disallowed substrings (case-insensitive). Keep it short and obvious; stub real slurs with `/* …redacted, fill locally… */` comments if you prefer not to commit the words. Include at minimum `null`, `undefined`, and a handful of common slurs.
- - `RESERVED_SLUGS: Set<string>` — `admin`, `root`, `support`, `api`, `agent`, `agents`, `login`, `logout`, `signin`, `signup`, `create`, `system`, `wallet`, `settings`, `help`, `docs`, `me`, `null`, `undefined`.
- - `isNameAllowed(name): boolean`
- - `isSlugReserved(slug): boolean`
- - `deriveSlug(name): string` — `name.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 64)`.
+
+ - `DENYLIST: Set<string>` of disallowed substrings (case-insensitive). Keep it short and obvious; stub real slurs with `/* …redacted, fill locally… */` comments if you prefer not to commit the words. Include at minimum `null`, `undefined`, and a handful of common slurs.
+ - `RESERVED_SLUGS: Set<string>` — `admin`, `root`, `support`, `api`, `agent`, `agents`, `login`, `logout`, `signin`, `signup`, `create`, `system`, `wallet`, `settings`, `help`, `docs`, `me`, `null`, `undefined`.
+ - `isNameAllowed(name): boolean`
+ - `isSlugReserved(slug): boolean`
+ - `deriveSlug(name): string` — `name.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 64)`.
3. **New API: `api/agents/check-name.js`** — `GET /api/agents/check-name?slug=…`:
- - Auth: session cookie only (`getSessionUser(req)`). No bearer.
- - Validate `slug` via the existing `slug` zod schema from [api/_lib/validate.js](../../api/_lib/validate.js).
- - Call `isSlugReserved(slug)` → if reserved, return `{ available: false, reason: 'reserved' }`.
- - SQL: `SELECT 1 FROM agent_identities WHERE user_id = $1 AND LOWER(name) = $2 AND deleted_at IS NULL LIMIT 1`. The `$2` is the *lowercased original name*, not the slug — reasoning: uniqueness is on the name surface, slug is just a stable identity for the check request. Accept both `?name=` and `?slug=` query params; prefer `name` if present and fall back to deriving.
- - Return `{ available: boolean, reason?: 'reserved'|'taken' }`.
- - Rate-limit via `limits.authIp(clientIp(req))` per [api/CLAUDE.md](../../api/CLAUDE.md).
+
+ - Auth: session cookie only (`getSessionUser(req)`). No bearer.
+ - Validate `slug` via the existing `slug` zod schema from [api/\_lib/validate.js](../../api/_lib/validate.js).
+ - Call `isSlugReserved(slug)` → if reserved, return `{ available: false, reason: 'reserved' }`.
+ - SQL: `SELECT 1 FROM agent_identities WHERE user_id = $1 AND LOWER(name) = $2 AND deleted_at IS NULL LIMIT 1`. The `$2` is the _lowercased original name_, not the slug — reasoning: uniqueness is on the name surface, slug is just a stable identity for the check request. Accept both `?name=` and `?slug=` query params; prefer `name` if present and fall back to deriving.
+ - Return `{ available: boolean, reason?: 'reserved'|'taken' }`.
+ - Rate-limit via `limits.authIp(clientIp(req))` per [api/CLAUDE.md](../../api/CLAUDE.md).
4. **New file: `api/_lib/agent-names.js`** — exports `assertNameAvailable({ userId, name }): Promise<void>` that throws `{ status: 409, code: 'name_taken', message: '…' }` if the caller already has a live agent with that name. Prompt 03's POST handler will `await` this before insert.
@@ -62,6 +65,7 @@ On submit, hand `{ name, description, slug }` up the call chain so prompt 03 can
## Audit checklist — must handle all of these
**Name validation (client + server, same rules)**
+
- Trim input before any check.
- Length 2-32 chars after trim.
- Allowed character class: `[A-Za-z0-9 _'.-]`. Reject anything else.
@@ -69,24 +73,29 @@ On submit, hand `{ name, description, slug }` up the call chain so prompt 03 can
- Derived slug runs through the `slug` zod schema. Empty slug after derivation → rejected as `invalid_name`.
**Denylist**
+
- Case-insensitive substring match against `DENYLIST`. Any match → `"That name isn't allowed."`. This is a **blunt** instrument on purpose — it's a stopgap, not moderation.
- Reserved slugs are **exact match** against `RESERVED_SLUGS`.
**Uniqueness**
+
- Per-user, not global. `LOWER(name)` comparison in SQL.
- No fuzzy / trigram match.
**Debounce + race**
+
- 300ms input debounce.
- Cancel prior in-flight checks via `AbortController`. Only the latest response is surfaced.
- If Continue is pressed while a check is pending, await the pending result before firing `onSubmit`.
**Accessibility**
+
- `<label>`s linked to inputs via `for`/`id`.
- Inline errors in an `aria-live="polite"` container.
- Continue button gets `aria-busy="true"` while a check or submit is in flight.
**Mobile**
+
- Inputs scale to full width on a 375px viewport.
- `autocapitalize="words"` on name, `autocapitalize="sentences"` on description.
- Plain `type="text"` — never `type="email"` / `type="tel"`.
@@ -126,6 +135,7 @@ On submit, hand `{ name, description, slug }` up the call chain so prompt 03 can
## Reporting
Report:
+
- Files created / edited with line counts.
- The final denylist + reserved-slug contents (so a reviewer can tweak).
- The slug derivation rule you shipped and any edge case you found (e.g. CJK input collapses to empty — how you handled it).
diff --git a/prompts/selfie-agent/05-first-meet-moment.md b/prompts/selfie-agent/05-first-meet-moment.md
index 7071b764b..1074d49b8 100644
--- a/prompts/selfie-agent/05-first-meet-moment.md
+++ b/prompts/selfie-agent/05-first-meet-moment.md
@@ -2,7 +2,7 @@
## Context
-Repo: `/workspaces/3D`. After prompt 04, the user lands at `/create#step=meet`. Their agent exists, the GLB is registered, the slug is reserved. This is the one-time payoff — the first time they see *themselves* in 3D, greeting them.
+Repo: `/workspaces/3D`. After prompt 04, the user lands at `/create#step=meet`. Their agent exists, the GLB is registered, the slug is reserved. This is the one-time payoff — the first time they see _themselves_ in 3D, greeting them.
The [Empathy Layer](../../src/agent-avatar.js) already blends `celebration` + `curiosity` on `skill-done` with positive sentiment. The existing `greet` skill in [src/agent-skills.js](../../src/agent-skills.js) fires a wave gesture plus a "speak" event. Animation manager in [src/animation-manager.js](../../src/animation-manager.js) has a `waving` clip when the animation pack is installed.
@@ -13,22 +13,25 @@ The [Empathy Layer](../../src/agent-avatar.js) already blends `celebration` + `c
## Deliverable
1. **Module — `src/features/create-meet.js`**
- - Export `mountCreateMeet(root)` → `{ destroy }`.
- - Load the user's agent + avatar via `GET /api/agents/me`.
- - Instantiate a minimal viewer (reuse [src/viewer.js](../../src/viewer.js)) in kiosk-like mode (no controls, controlled camera).
- - Run a scripted camera orbit for ~1.5 s, settle.
- - `protocol.emit({ type: ACTION_TYPES.SPEAK, payload: { text: `Hi, I'm ${agent.name}.`, sentiment: 0.7 } })` then `protocol.emit({ type: ACTION_TYPES.GESTURE, payload: { name: 'waving', duration: 2500 } })` (animation-manager handles the clip if installed; graceful degrade if not).
+
+ - Export `mountCreateMeet(root)` → `{ destroy }`.
+ - Load the user's agent + avatar via `GET /api/agents/me`.
+ - Instantiate a minimal viewer (reuse [src/viewer.js](../../src/viewer.js)) in kiosk-like mode (no controls, controlled camera).
+ - Run a scripted camera orbit for ~1.5 s, settle.
+ - `protocol.emit({ type: ACTION_TYPES.SPEAK, payload: { text: `Hi, I'm ${agent.name}.`, sentiment: 0.7 } })` then `protocol.emit({ type: ACTION_TYPES.GESTURE, payload: { name: 'waving', duration: 2500 } })` (animation-manager handles the clip if installed; graceful degrade if not).
2. **Confetti**
- - Tiny inline confetti — plain DOM / CSS animation. No library. ~30 particles, 1.5 s total. One-shot. Respects `prefers-reduced-motion`: drop the confetti if reduced motion is set.
+
+ - Tiny inline confetti — plain DOM / CSS animation. No library. ~30 particles, 1.5 s total. One-shot. Respects `prefers-reduced-motion`: drop the confetti if reduced motion is set.
3. **CTAs**
- - **Chat** — `location.assign('/agent/' + agent.id)`.
- - **Embed** — open a small inline modal with the embed snippet (reuse [public/agent/embed.html](../../public/agent/embed.html) pattern) from `prompts/embed/` work if available; otherwise show a simple `<iframe>` snippet with the agent id.
- - **Share** — `navigator.share({ title, url })` if available; else copy URL to clipboard and show a "Copied!" tick.
+
+ - **Chat** — `location.assign('/agent/' + agent.id)`.
+ - **Embed** — open a small inline modal with the embed snippet (reuse [public/agent/embed.html](../../public/agent/embed.html) pattern) from `prompts/embed/` work if available; otherwise show a simple `<iframe>` snippet with the agent id.
+ - **Share** — `navigator.share({ title, url })` if available; else copy URL to clipboard and show a "Copied!" tick.
4. **Analytics breadcrumb**
- - `protocol.emit({ type: ACTION_TYPES.REMEMBER, payload: { type: 'project', content: 'First-meet moment shown on ' + new Date().toISOString().slice(0,10) }, agentId: agent.id })`.
+ - `protocol.emit({ type: ACTION_TYPES.REMEMBER, payload: { type: 'project', content: 'First-meet moment shown on ' + new Date().toISOString().slice(0,10) }, agentId: agent.id })`.
## Audit checklist
@@ -50,10 +53,10 @@ The [Empathy Layer](../../src/agent-avatar.js) already blends `celebration` + `c
1. `node --check` all new / edited files.
2. `npx vite build` — expect success.
3. Manual:
- - Walk through prompts 01 → 04 → 05 end-to-end.
- - Confirm the avatar waves, the head tilts slightly (empathy+curiosity), the mouth shape changes briefly (celebration blend).
- - With `prefers-reduced-motion`, no confetti, no orbit.
- - Clicking each CTA behaves as described.
+ - Walk through prompts 01 → 04 → 05 end-to-end.
+ - Confirm the avatar waves, the head tilts slightly (empathy+curiosity), the mouth shape changes briefly (celebration blend).
+ - With `prefers-reduced-motion`, no confetti, no orbit.
+ - Clicking each CTA behaves as described.
## Scope boundaries — do NOT do these
diff --git a/prompts/selfie-agent/README.md b/prompts/selfie-agent/README.md
index e1b404233..ac1875212 100644
--- a/prompts/selfie-agent/README.md
+++ b/prompts/selfie-agent/README.md
@@ -14,13 +14,13 @@ See [../README.md](../README.md) for where this series sits in the overall prior
## Recommended execution order
-| # | File | Ships |
-|---|---|---|
-| 01 | [01-camera-capture-ui.md](./01-camera-capture-ui.md) | `/create` route + `getUserMedia` capture, photo review, retry, upload fallback |
-| 02 | [02-avaturn-session-bridge.md](./02-avaturn-session-bridge.md) | Hand the captured image to Avaturn SDK, await the generated GLB; error / quota / timeout handling |
-| 03 | [03-glb-pin-and-store.md](./03-glb-pin-and-store.md) | Pin the finalized GLB to R2 via the existing presign flow + create an `agent_identities` row |
-| 04 | [04-name-and-description.md](./04-name-and-description.md) | Claim a short name + one-line description with per-wallet uniqueness, slug reservation, denylist |
-| 05 | [05-first-meet-moment.md](./05-first-meet-moment.md) | Post-creation scene renders, avatar waves, confetti, share CTA, redirect to `/agent/:id` |
+| # | File | Ships |
+| --- | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
+| 01 | [01-camera-capture-ui.md](./01-camera-capture-ui.md) | `/create` route + `getUserMedia` capture, photo review, retry, upload fallback |
+| 02 | [02-avaturn-session-bridge.md](./02-avaturn-session-bridge.md) | Hand the captured image to Avaturn SDK, await the generated GLB; error / quota / timeout handling |
+| 03 | [03-glb-pin-and-store.md](./03-glb-pin-and-store.md) | Pin the finalized GLB to R2 via the existing presign flow + create an `agent_identities` row |
+| 04 | [04-name-and-description.md](./04-name-and-description.md) | Claim a short name + one-line description with per-wallet uniqueness, slug reservation, denylist |
+| 05 | [05-first-meet-moment.md](./05-first-meet-moment.md) | Post-creation scene renders, avatar waves, confetti, share CTA, redirect to `/agent/:id` |
### Sequencing
@@ -36,7 +36,7 @@ See [../README.md](../README.md) for where this series sits in the overall prior
- **No TypeScript.** This codebase is vanilla JS (ESM). No `.ts` files, no `.d.ts`.
- **No new README / CLAUDE.md files** unless the task file explicitly allows them.
- **Every new or changed `.js` file must pass `node --check`** before reporting done.
-- **Every change must be followed by `npx vite build`** and the result reported. The pre-existing `@avaturn/sdk` resolution warning is expected — ignore it. Any *new* error is yours.
+- **Every change must be followed by `npx vite build`** and the result reported. The pre-existing `@avaturn/sdk` resolution warning is expected — ignore it. Any _new_ error is yours.
- **Any new route must be added to [vercel.json](../../vercel.json)** in the same task that creates it.
- **Mobile matters.** The hero demo is "take a selfie on your phone". Anything gated behind desktop-only APIs (drag-drop, hover, large modals) must have a mobile-first fallback.
- **If you discover an unrelated bug,** note it in the reporting section. Do not fix it in the same change.
diff --git a/prompts/selfie-onboarding/00-README.md b/prompts/selfie-onboarding/00-README.md
index 4373e9aa0..9e663dd28 100644
--- a/prompts/selfie-onboarding/00-README.md
+++ b/prompts/selfie-onboarding/00-README.md
@@ -6,7 +6,7 @@ A new user (signed in via wallet — band 1) is shown a camera viewfinder. They
## Why this matters
-Typing a name, picking a body type, dragging sliders — all friction. A selfie is the *magic moment* that makes the product obvious. Every downstream priority (edit, embed, on-chain) is post-creation; if creation is slow or unclear, nothing else matters.
+Typing a name, picking a body type, dragging sliders — all friction. A selfie is the _magic moment_ that makes the product obvious. Every downstream priority (edit, embed, on-chain) is post-creation; if creation is slow or unclear, nothing else matters.
## Current state
@@ -17,13 +17,13 @@ Typing a name, picking a body type, dragging sliders — all friction. A selfie
## Prompts in this band
-| # | File | Depends on |
-|---|---|---|
-| 01 | [camera-capture.md](./01-camera-capture.md) | — |
-| 02 | [avaturn-pipeline.md](./02-avaturn-pipeline.md) | 01 |
-| 03 | [readyplayerme-fallback.md](./03-readyplayerme-fallback.md) | 01 |
-| 04 | [onboarding-flow.md](./04-onboarding-flow.md) | 02 |
-| 05 | [commit-and-name.md](./05-commit-and-name.md) | 02, 04 |
+| # | File | Depends on |
+| --- | ----------------------------------------------------------- | ---------- |
+| 01 | [camera-capture.md](./01-camera-capture.md) | — |
+| 02 | [avaturn-pipeline.md](./02-avaturn-pipeline.md) | 01 |
+| 03 | [readyplayerme-fallback.md](./03-readyplayerme-fallback.md) | 01 |
+| 04 | [onboarding-flow.md](./04-onboarding-flow.md) | 02 |
+| 05 | [commit-and-name.md](./05-commit-and-name.md) | 02, 04 |
01 unblocks 02 and 03 in parallel. 04 sits on top of 02. 05 is the final mile.
diff --git a/prompts/selfie-onboarding/01-camera-capture.md b/prompts/selfie-onboarding/01-camera-capture.md
index 01061381c..7f29c17bc 100644
--- a/prompts/selfie-onboarding/01-camera-capture.md
+++ b/prompts/selfie-onboarding/01-camera-capture.md
@@ -20,11 +20,11 @@ Do not modify `src/app.js` yet.
import { CameraCapture } from './onboarding/camera-capture.js';
const cap = new CameraCapture({ container: document.querySelector('#cam') });
-await cap.start(); // request permission, show preview
+await cap.start(); // request permission, show preview
const blob = await cap.capture(); // returns a JPEG Blob (~0.9 quality, ~1024 longest side)
-cap.retake(); // goes back to preview
-cap.stop(); // releases the camera track
-cap.on('error', (err) => {}); // emits CameraError with .code in {'permission', 'no-device', 'insecure-context', 'unknown'}
+cap.retake(); // goes back to preview
+cap.stop(); // releases the camera track
+cap.on('error', (err) => {}); // emits CameraError with .code in {'permission', 'no-device', 'insecure-context', 'unknown'}
```
Expose a DOM event too: `cap.addEventListener('photo', (e) => e.detail.blob)`.
@@ -61,9 +61,9 @@ Expose a DOM event too: `cap.addEventListener('photo', (e) => e.detail.blob)`.
1. `node --check src/onboarding/camera-capture.js` passes.
2. `npx vite build` succeeds.
3. Open `public/onboarding/camera-demo.html` in Chrome:
- - Click Enable → browser prompts → allow → live preview.
- - Click shutter → freeze frame → Retake returns to preview.
- - Click "Use this photo" → demo page shows the blob size and a `<img>` preview.
+ - Click Enable → browser prompts → allow → live preview.
+ - Click shutter → freeze frame → Retake returns to preview.
+ - Click "Use this photo" → demo page shows the blob size and a `<img>` preview.
4. Repeat in Safari (desktop). Document any workarounds.
5. Toggle Chrome `camera: block` in site settings → permission-denied state renders cleanly.
6. Deny camera at the OS level (System Settings) → `no-device` or similar renders cleanly.
diff --git a/prompts/selfie-onboarding/02-avaturn-pipeline.md b/prompts/selfie-onboarding/02-avaturn-pipeline.md
index e5211a2b1..68266f85c 100644
--- a/prompts/selfie-onboarding/02-avaturn-pipeline.md
+++ b/prompts/selfie-onboarding/02-avaturn-pipeline.md
@@ -37,6 +37,7 @@ const result = await pipe.run(photoBlob);
```
Steps inside `run`:
+
1. Fetch `/api/onboarding/avaturn-session` → `{ sessionToken, url }`.
2. Initialize Avaturn SDK with the session token.
3. Upload the blob, poll for completion (SDK usually handles this — use the SDK's built-in async flow; emit progress).
@@ -46,6 +47,7 @@ Steps inside `run`:
### Error surface
Each failure throws a typed error:
+
- `AvaturnError('quota_exceeded')`
- `AvaturnError('face_not_found')` — SDK returns a known "no face detected" state
- `AvaturnError('timeout')` — >90s without completion
diff --git a/prompts/selfie-onboarding/03-readyplayerme-fallback.md b/prompts/selfie-onboarding/03-readyplayerme-fallback.md
index 2aea4efda..9086ee654 100644
--- a/prompts/selfie-onboarding/03-readyplayerme-fallback.md
+++ b/prompts/selfie-onboarding/03-readyplayerme-fallback.md
@@ -27,6 +27,7 @@ const result = await pipe.run({ photoBlob });
```
Strategy:
+
1. Embed the Ready Player Me iframe (`https://${RPM_SUBDOMAIN}/avatar?frameApi`) in a modal container the pipeline creates and tears down.
2. Pass the selfie blob to RPM via their `postMessage` API (RPM accepts `{ target: 'readyplayerme', type: 'selfie', data }` — verify against their current docs and record what you used).
3. Listen for `v1.avatar.exported` messages; pull the GLB URL from the payload.
@@ -35,9 +36,9 @@ Strategy:
### When to use fallback
- Export a helper `chooseAvatarPipeline({ preferred })` that returns either `AvaturnPipeline` or `RpmPipeline` based on:
- - explicit user choice (query param `?pipeline=rpm` or `?pipeline=avaturn`)
- - a health check against both services (1s timeout, in parallel)
- - default to Avaturn
+ - explicit user choice (query param `?pipeline=rpm` or `?pipeline=avaturn`)
+ - a health check against both services (1s timeout, in parallel)
+ - default to Avaturn
- On first-pipeline failure with `quota_exceeded | network | timeout`, automatically retry with the other and emit a user-visible toast ("Trying another service…").
Keep the selector in `src/onboarding/pipeline-selector.js`.
diff --git a/prompts/selfie-onboarding/04-onboarding-flow.md b/prompts/selfie-onboarding/04-onboarding-flow.md
index 7d2d06aba..74cdbedf6 100644
--- a/prompts/selfie-onboarding/04-onboarding-flow.md
+++ b/prompts/selfie-onboarding/04-onboarding-flow.md
@@ -32,6 +32,7 @@ Implemented in `src/onboarding/flow.js`. States: `'auth' | 'capture' | 'process'
### Progress UI
During `process`:
+
- Primary label cycles: "Analyzing your photo…" → "Building your avatar…" → "Almost ready…"
- Progress bar driven by the `progress` events from the pipeline.
- If the pipeline emits a preview image, show it at 25% opacity behind the spinner — conveys "something real is happening."
@@ -39,6 +40,7 @@ During `process`:
### Error UI
Each failure has a specific recovery path:
+
- Camera permission denied → "Upload a photo instead" button (file input, emits same Blob contract).
- Face not detected → retake + tip ("Good lighting, face the camera, no sunglasses").
- Pipeline timeout → retry button + switch-pipeline button.
diff --git a/prompts/selfie-onboarding/05-commit-and-name.md b/prompts/selfie-onboarding/05-commit-and-name.md
index e50296924..6d9268422 100644
--- a/prompts/selfie-onboarding/05-commit-and-name.md
+++ b/prompts/selfie-onboarding/05-commit-and-name.md
@@ -23,10 +23,10 @@ Single primary button: `Create agent`.
```js
export async function commitAvatar({ glbBlob, name, source = 'selfie' }) {
- // 1. Request upload URL or multipart POST, depending on the existing API.
- // 2. Upload the GLB.
- // 3. Create the avatar + agent rows.
- // 4. Return { agentId, slug, viewerUrl, editorUrl }.
+ // 1. Request upload URL or multipart POST, depending on the existing API.
+ // 2. Upload the GLB.
+ // 3. Create the avatar + agent rows.
+ // 4. Return { agentId, slug, viewerUrl, editorUrl }.
}
```
diff --git a/prompts/sprint-100/00-README.md b/prompts/sprint-100/00-README.md
index d40ea2a98..45bd94603 100644
--- a/prompts/sprint-100/00-README.md
+++ b/prompts/sprint-100/00-README.md
@@ -19,30 +19,30 @@ Every prompt in this folder is designed to run **in parallel** with every other
## Map
-| # | Band | Title | Primary file(s) |
-|---|---|---|---|
-| 01 | 1 | Wallet signin button | `src/wallet-auth.js` |
-| 02 | 1 | Session refresh + logout-all | `api/auth/session/*` |
-| 03 | 1 | Link/unlink wallet to account | `api/auth/wallet/*` |
-| 04 | 2 | Camera capture module | `src/camera-capture.js` |
-| 05 | 2 | Avaturn client bridge | `src/avaturn-client.js` |
-| 06 | 2 | Agent naming form module | `src/agent-naming.js` |
-| 07 | 2 | First-meet celebration | `src/first-meet.js` |
-| 08 | 3 | Avatar PATCH endpoint | `api/avatars/[id].js` (additive) |
-| 09 | 3 | Editor save button | `src/editor/save-back.js` |
-| 10 | 3 | Avatar version history | `api/avatars/[id]/versions.js` |
-| 11 | 4 | Share panel module | `src/share-panel.js` |
-| 12 | 4 | `agent-id` attribute resolver | `src/agent-3d-element.js` |
-| 13 | 5 | Claude.ai artifact bundle | `public/artifact.js` |
-| 14 | 5 | Idle animation loop | `src/idle-animation.js` |
-| 15 | 5 | Embed postMessage bridge | `src/embed-host-bridge.js` |
-| 16 | 5 | LobeHub plugin manifest | `public/.well-known/lobehub-plugin.json` |
-| 17 | 6 | On-chain deploy button | `src/erc8004/deploy-button.js` |
-| 18 | 6 | IPFS pinning endpoint | `api/pinning/pin.js` |
-| 19 | 6 | Address resolver API | `api/agents/by-address/[addr].js` |
-| 20 | 6 | ENS name resolver | `api/agents/ens/[name].js` |
-| 21 | 4 | OG/oEmbed polish | `api/a-og.js` (additive) |
-| 22 | 7 | CZ claim landing page | `public/cz/` |
-| 23 | 5 | Action passthrough bridge | `src/embed-action-bridge.js` |
-| 24 | 5 | `@agent` suggest endpoint | `api/agents/suggest.js` |
-| 25 | 6 | Claim transfer flow | `src/claim-transfer.js` |
+| # | Band | Title | Primary file(s) |
+| --- | ---- | ----------------------------- | ---------------------------------------- |
+| 01 | 1 | Wallet signin button | `src/wallet-auth.js` |
+| 02 | 1 | Session refresh + logout-all | `api/auth/session/*` |
+| 03 | 1 | Link/unlink wallet to account | `api/auth/wallet/*` |
+| 04 | 2 | Camera capture module | `src/camera-capture.js` |
+| 05 | 2 | Avaturn client bridge | `src/avaturn-client.js` |
+| 06 | 2 | Agent naming form module | `src/agent-naming.js` |
+| 07 | 2 | First-meet celebration | `src/first-meet.js` |
+| 08 | 3 | Avatar PATCH endpoint | `api/avatars/[id].js` (additive) |
+| 09 | 3 | Editor save button | `src/editor/save-back.js` |
+| 10 | 3 | Avatar version history | `api/avatars/[id]/versions.js` |
+| 11 | 4 | Share panel module | `src/share-panel.js` |
+| 12 | 4 | `agent-id` attribute resolver | `src/agent-3d-element.js` |
+| 13 | 5 | Claude.ai artifact bundle | `public/artifact.js` |
+| 14 | 5 | Idle animation loop | `src/idle-animation.js` |
+| 15 | 5 | Embed postMessage bridge | `src/embed-host-bridge.js` |
+| 16 | 5 | LobeHub plugin manifest | `public/.well-known/lobehub-plugin.json` |
+| 17 | 6 | On-chain deploy button | `src/erc8004/deploy-button.js` |
+| 18 | 6 | IPFS pinning endpoint | `api/pinning/pin.js` |
+| 19 | 6 | Address resolver API | `api/agents/by-address/[addr].js` |
+| 20 | 6 | ENS name resolver | `api/agents/ens/[name].js` |
+| 21 | 4 | OG/oEmbed polish | `api/a-og.js` (additive) |
+| 22 | 7 | CZ claim landing page | `public/cz/` |
+| 23 | 5 | Action passthrough bridge | `src/embed-action-bridge.js` |
+| 24 | 5 | `@agent` suggest endpoint | `api/agents/suggest.js` |
+| 25 | 6 | Claim transfer flow | `src/claim-transfer.js` |
diff --git a/prompts/sprint-100/01-wallet-signin-button.md b/prompts/sprint-100/01-wallet-signin-button.md
index 55bd30994..c924a0530 100644
--- a/prompts/sprint-100/01-wallet-signin-button.md
+++ b/prompts/sprint-100/01-wallet-signin-button.md
@@ -37,23 +37,26 @@ export function wireSigninButton(buttonEl) // attaches click handler + swaps UI
1. `connectWallet()` → `{ signer, address, chainId }`
2. `POST /api/auth/siwe/nonce` with `{ address }` — read `{ nonce }`.
3. Build EIP-4361 message string client-side:
- ```
- ${location.host} wants you to sign in with your Ethereum account:
- ${address}
-
- Sign in to 3D Agent.
-
- URI: ${location.origin}
- Version: 1
- Chain ID: ${chainId}
- Nonce: ${nonce}
- Issued At: ${new Date().toISOString()}
- ```
+
+ ```
+ ${location.host} wants you to sign in with your Ethereum account:
+ ${address}
+
+ Sign in to 3D Agent.
+
+ URI: ${location.origin}
+ Version: 1
+ Chain ID: ${chainId}
+ Nonce: ${nonce}
+ Issued At: ${new Date().toISOString()}
+ ```
+
4. `signature = await signer.signMessage(message)`
5. `POST /api/auth/siwe/verify` with `{ message, signature }`, `credentials: 'include'`.
6. On 200, resolve with the returned user. On non-200, throw with the server's `error`/`message` field.
`wireSigninButton(buttonEl)`:
+
- Calls `getCurrentUser()` on load. If signed in, replace the button with a small chip `0xabcd…1234 · sign out`. If signed out, attach the click handler.
- Click handler: disable button, show inline status text, call `signInWithWallet()`, on success reload page, on failure show the error under the button.
- If `window.ethereum` is missing AND no Privy is configured, status text: "No wallet detected — install MetaMask or use a wallet-enabled browser."
diff --git a/prompts/sprint-100/02-session-management-api.md b/prompts/sprint-100/02-session-management-api.md
index 802a19276..980685b97 100644
--- a/prompts/sprint-100/02-session-management-api.md
+++ b/prompts/sprint-100/02-session-management-api.md
@@ -6,7 +6,7 @@ Long-lived sessions need rotation and a "log out everywhere" escape hatch. Today
## Parallel-safety
-You only create NEW files under `api/auth/session/`. You do NOT edit `login.js`, `logout.js`, or `me.js`. If the existing `createSession()` helper in [api/_lib/auth.js](../../api/_lib/auth.js) already exposes what you need, import it. If it doesn't, stub a local helper in your endpoint and note the gap in the report — do not edit `_lib/auth.js`.
+You only create NEW files under `api/auth/session/`. You do NOT edit `login.js`, `logout.js`, or `me.js`. If the existing `createSession()` helper in [api/\_lib/auth.js](../../api/_lib/auth.js) already exposes what you need, import it. If it doesn't, stub a local helper in your endpoint and note the gap in the report — do not edit `_lib/auth.js`.
## Files you own
@@ -16,9 +16,9 @@ You only create NEW files under `api/auth/session/`. You do NOT edit `login.js`,
## Read first
-- [api/_lib/auth.js](../../api/_lib/auth.js) — inspect `getSessionUser`, `createSession`, and the sessions table name.
-- [api/_lib/http.js](../../api/_lib/http.js) — `wrap`, `json`, `error`, `cors`, `method`.
-- [api/_lib/db.js](../../api/_lib/db.js) — `sql` tagged template.
+- [api/\_lib/auth.js](../../api/_lib/auth.js) — inspect `getSessionUser`, `createSession`, and the sessions table name.
+- [api/\_lib/http.js](../../api/_lib/http.js) — `wrap`, `json`, `error`, `cors`, `method`.
+- [api/\_lib/db.js](../../api/_lib/db.js) — `sql` tagged template.
- [api/auth/logout.js](../../api/auth/logout.js) — reference pattern.
## Deliverable
diff --git a/prompts/sprint-100/03-wallet-link-account.md b/prompts/sprint-100/03-wallet-link-account.md
index 55c9da466..c2d1a16fa 100644
--- a/prompts/sprint-100/03-wallet-link-account.md
+++ b/prompts/sprint-100/03-wallet-link-account.md
@@ -16,8 +16,8 @@ You create two NEW endpoints. You do not touch SIWE nonce/verify or login/regist
## Read first
- [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) — confirm the `user_wallets` schema in use (`user_id`, `address`, `chain_id`, `is_primary`, `last_used_at`).
-- [api/_lib/auth.js](../../api/_lib/auth.js) — `getSessionUser`.
-- [api/_lib/db.js](../../api/_lib/db.js) — `sql` tag.
+- [api/\_lib/auth.js](../../api/_lib/auth.js) — `getSessionUser`.
+- [api/\_lib/db.js](../../api/_lib/db.js) — `sql` tag.
## Deliverable
@@ -26,12 +26,12 @@ You create two NEW endpoints. You do not touch SIWE nonce/verify or login/regist
- Requires session cookie.
- Body: `{ message, signature }` — full SIWE message + signature, same format the verify endpoint consumes.
- Steps:
- 1. Parse message, extract `address` and `nonce`.
- 2. Look up + consume the nonce exactly like [verify.js](../../api/auth/siwe/verify.js) does.
- 3. `ethers.verifyMessage(message, signature) === address` (case-insensitive).
- 4. If the address is already linked to a DIFFERENT user → `409 wallet-taken`.
- 5. Insert into `user_wallets` with `user_id = session.user.id`, `is_primary = false`.
- 6. Return `{ ok: true, address, chainId }`.
+ 1. Parse message, extract `address` and `nonce`.
+ 2. Look up + consume the nonce exactly like [verify.js](../../api/auth/siwe/verify.js) does.
+ 3. `ethers.verifyMessage(message, signature) === address` (case-insensitive).
+ 4. If the address is already linked to a DIFFERENT user → `409 wallet-taken`.
+ 5. Insert into `user_wallets` with `user_id = session.user.id`, `is_primary = false`.
+ 6. Return `{ ok: true, address, chainId }`.
- Rate limit: `10/10min per user`.
### `POST /api/auth/wallet/unlink`
@@ -39,10 +39,10 @@ You create two NEW endpoints. You do not touch SIWE nonce/verify or login/regist
- Requires session cookie.
- Body: `{ address }`.
- Steps:
- 1. Verify the wallet row exists for this user. 404 if not.
- 2. If this is the user's ONLY auth method (no password_hash AND this is the only wallet row), refuse with `409 last-auth-method`.
- 3. Delete the row.
- 4. Return `{ ok: true }`.
+ 1. Verify the wallet row exists for this user. 404 if not.
+ 2. If this is the user's ONLY auth method (no password_hash AND this is the only wallet row), refuse with `409 last-auth-method`.
+ 3. Delete the row.
+ 4. Return `{ ok: true }`.
- If `is_primary` was true and other wallets exist, promote the most-recently-used remaining wallet to primary.
## Constraints
diff --git a/prompts/sprint-100/06-agent-naming-form.md b/prompts/sprint-100/06-agent-naming-form.md
index c3d290c76..0b0c55dd1 100644
--- a/prompts/sprint-100/06-agent-naming-form.md
+++ b/prompts/sprint-100/06-agent-naming-form.md
@@ -16,7 +16,7 @@ One new JS module + one new server endpoint for uniqueness check. No route wirin
## Read first
- [api/agents/check-name.js](../../api/agents/check-name.js) — if present, understand the existing shape.
-- [api/_lib/db.js](../../api/_lib/db.js) — `sql`.
+- [api/\_lib/db.js](../../api/_lib/db.js) — `sql`.
## Deliverable
@@ -31,11 +31,13 @@ export class AgentNaming {
```
Form fields:
+
- **Name** — required, 3–32 chars, `[a-zA-Z0-9_-]+`, must not match denylist (see below), must pass server uniqueness check.
- **Description** — optional, ≤280 chars.
- **Submit** button → calls `onSubmit({ name, description })`.
Behavior:
+
- Debounce uniqueness check 400ms on name input. Show ✓ / ✗ / loading indicator inline.
- Disable submit while check is pending or name invalid.
- On submit, re-run the uniqueness check synchronously to avoid races.
@@ -45,6 +47,7 @@ Denylist (hardcode array in the module): `['admin', 'root', 'system', 'anthropic
### `GET /api/agents/check-name?name=<n>`
Response: `{ available: boolean, reason?: 'taken' | 'invalid' | 'denylisted' }`.
+
- Case-insensitive uniqueness against the `agents` (or whichever holds agent names — read the actual schema) table.
- Rate limit: `60/min per IP`.
- If the endpoint already exists and returns a compatible shape, do nothing server-side; cite the file in your report.
diff --git a/prompts/sprint-100/08-avatar-patch-endpoint.md b/prompts/sprint-100/08-avatar-patch-endpoint.md
index 354595733..b5fb3482b 100644
--- a/prompts/sprint-100/08-avatar-patch-endpoint.md
+++ b/prompts/sprint-100/08-avatar-patch-endpoint.md
@@ -16,7 +16,7 @@ The editor can export a GLB but has no server path to persist it. A `PATCH /api/
- [api/avatars/[id].js](../../api/avatars/[id].js) — the current shape.
- [api/avatars/presign.js](../../api/avatars/presign.js) — the R2 upload/presign pattern (reuse, don't reimplement).
-- [api/_lib/db.js](../../api/_lib/db.js), [api/_lib/http.js](../../api/_lib/http.js), [api/_lib/auth.js](../../api/_lib/auth.js).
+- [api/\_lib/db.js](../../api/_lib/db.js), [api/\_lib/http.js](../../api/_lib/http.js), [api/\_lib/auth.js](../../api/_lib/auth.js).
## Deliverable
@@ -25,12 +25,12 @@ The editor can export a GLB but has no server path to persist it. A `PATCH /api/
- Auth: session cookie OR bearer with `avatars:write` scope.
- Body: `{ glbUrl: string }` — a signed R2 URL the client already uploaded to via the existing presign flow. NEVER accept raw GLB bytes on this endpoint.
- Steps:
- 1. Load the avatar row. 404 if missing.
- 2. Ownership check: `avatar.owner_user_id === user.id`. Else 403.
- 3. `headObject()` the `glbUrl` key — reject if size > 25 MB or content-type is not `model/gltf-binary` (or `application/octet-stream` for R2). If the helper doesn't exist, inline a minimal HEAD via the R2 SDK already in use.
- 4. Insert a row into an `avatar_versions` table (see prompt 10; if table doesn't exist yet, try the insert inside a try/catch — on missing-table error, log a warning and continue).
- 5. Update the avatar row: `current_glb_url = glbUrl`, `updated_at = now()`.
- 6. Return `{ ok: true, avatar: { id, currentGlbUrl, updatedAt } }`.
+ 1. Load the avatar row. 404 if missing.
+ 2. Ownership check: `avatar.owner_user_id === user.id`. Else 403.
+ 3. `headObject()` the `glbUrl` key — reject if size > 25 MB or content-type is not `model/gltf-binary` (or `application/octet-stream` for R2). If the helper doesn't exist, inline a minimal HEAD via the R2 SDK already in use.
+ 4. Insert a row into an `avatar_versions` table (see prompt 10; if table doesn't exist yet, try the insert inside a try/catch — on missing-table error, log a warning and continue).
+ 5. Update the avatar row: `current_glb_url = glbUrl`, `updated_at = now()`.
+ 6. Return `{ ok: true, avatar: { id, currentGlbUrl, updatedAt } }`.
- Rate limit: `20/hour per user`.
## Constraints
diff --git a/prompts/sprint-100/09-editor-save-back.md b/prompts/sprint-100/09-editor-save-back.md
index 1e27b28b9..7038eefde 100644
--- a/prompts/sprint-100/09-editor-save-back.md
+++ b/prompts/sprint-100/09-editor-save-back.md
@@ -38,12 +38,11 @@ export async function saveEditedAvatar(session, { avatarId, onStep })
In `_addExportFolder()` add:
```js
-folder
- .add({ save: () => this._saveEdits() }, 'save')
- .name('💾 save edits');
+folder.add({ save: () => this._saveEdits() }, 'save').name('💾 save edits');
```
`_saveEdits()` on the `Editor` class:
+
- Requires `this.session.avatarId`. If missing (dropped GLB, not a saved avatar), show a toast "Not a saved avatar — use Publish instead" and return.
- Dynamic-import `./save-back.js` and call `saveEditedAvatar`.
- Show a tiny non-modal status text in the editor folder during the save ("saving… 42%"). On success, flash "saved ✓" for ~1.5s. On 401, show "Sign in to save" with a link to `/login?next=<current>`.
diff --git a/prompts/sprint-100/10-avatar-version-history.md b/prompts/sprint-100/10-avatar-version-history.md
index 68ae473c7..f8b08644c 100644
--- a/prompts/sprint-100/10-avatar-version-history.md
+++ b/prompts/sprint-100/10-avatar-version-history.md
@@ -17,7 +17,7 @@ Pure schema + two new endpoints. No client wiring.
## Read first
- [api/avatars/[id].js](../../api/avatars/[id].js) — the base avatar route + ownership pattern.
-- [api/_lib/db.js](../../api/_lib/db.js) — `sql`.
+- [api/\_lib/db.js](../../api/_lib/db.js) — `sql`.
- [scripts/](../../scripts/) — any existing migration conventions.
## Deliverable
diff --git a/prompts/sprint-100/11-share-panel.md b/prompts/sprint-100/11-share-panel.md
index 952f9ccce..631282d54 100644
--- a/prompts/sprint-100/11-share-panel.md
+++ b/prompts/sprint-100/11-share-panel.md
@@ -28,15 +28,20 @@ Renders a modal with these rows:
1. **Link** — `https://${embedOrigin}/a/${agent.slug || agent.id}` + Copy + Open-in-new-tab buttons
2. **iframe snippet**:
- ```html
- <iframe src="${embedOrigin}/agent-embed.html?id=${agent.id}"
- width="480" height="640" frameborder="0" allow="microphone; camera"></iframe>
- ```
+ ```html
+ <iframe
+ src="${embedOrigin}/agent-embed.html?id=${agent.id}"
+ width="480"
+ height="640"
+ frameborder="0"
+ allow="microphone; camera"
+ ></iframe>
+ ```
3. **Web-component snippet**:
- ```html
- <script type="module" src="${embedOrigin}/dist-lib/agent-3d.js"></script>
- <agent-3d agent-id="${agent.id}"></agent-3d>
- ```
+ ```html
+ <script type="module" src="${embedOrigin}/dist-lib/agent-3d.js"></script>
+ <agent-3d agent-id="${agent.id}"></agent-3d>
+ ```
4. **OG preview** — render an `<img src="${embedOrigin}/api/a-og?id=${agent.id}">` at 1200×630 scaled down, with copy-OG-URL button.
5. **QR code** — generate client-side (see constraint) pointing to the Link row.
diff --git a/prompts/sprint-100/12-agent-id-attribute.md b/prompts/sprint-100/12-agent-id-attribute.md
index 4259f0ec5..04904fdc8 100644
--- a/prompts/sprint-100/12-agent-id-attribute.md
+++ b/prompts/sprint-100/12-agent-id-attribute.md
@@ -26,21 +26,22 @@ You own ONE existing file, [src/agent-resolver.js](../../src/agent-resolver.js),
```js
export async function resolveByAgentId(agentId) {
- // 1. GET /api/agents/:id — returns { agent: { ..., manifestUrl } } OR 404.
- // 2. If manifestUrl is absolute, return it.
- // 3. If relative, resolve against location.origin.
- // 4. Cache results in an in-memory Map for the page lifetime (max 100 entries, LRU optional).
- // 5. On 404, throw AgentResolverError('not-found').
- // 6. Respect AbortSignal passed as second arg.
+ // 1. GET /api/agents/:id — returns { agent: { ..., manifestUrl } } OR 404.
+ // 2. If manifestUrl is absolute, return it.
+ // 3. If relative, resolve against location.origin.
+ // 4. Cache results in an in-memory Map for the page lifetime (max 100 entries, LRU optional).
+ // 5. On 404, throw AgentResolverError('not-found').
+ // 6. Respect AbortSignal passed as second arg.
}
```
### Web-component hook
Inside `connectedCallback`:
+
- If `this.hasAttribute('agent-id')` AND NOT `this.hasAttribute('manifest')`:
- - `const url = await resolveByAgentId(this.getAttribute('agent-id'))`
- - Set `this.setAttribute('manifest', url)` and continue the existing boot path.
+ - `const url = await resolveByAgentId(this.getAttribute('agent-id'))`
+ - Set `this.setAttribute('manifest', url)` and continue the existing boot path.
- If both are present, `manifest` wins and `agent-id` is ignored.
- If resolution fails, render a minimal inline error (`<div class="agent-3d-error">Agent not found</div>`) instead of throwing on the element.
diff --git a/prompts/sprint-100/13-artifact-bundle.md b/prompts/sprint-100/13-artifact-bundle.md
index ceb39c62d..c7bb4c775 100644
--- a/prompts/sprint-100/13-artifact-bundle.md
+++ b/prompts/sprint-100/13-artifact-bundle.md
@@ -26,14 +26,25 @@ Output is a new static file under `public/`. No edits to `src/app.js` or the lib
### `public/artifact-example.html`
A minimal HTML document a user can paste into a Claude.ai Artifact:
+
```html
<!doctype html>
<html>
-<head><meta charset="utf-8"><style>html,body{margin:0;height:100%;background:#111}</style></head>
-<body>
- <div data-agent-id="demo" style="width:100%;height:100vh"></div>
- <script type="module" src="https://3dagent.vercel.app/artifact.js"></script>
-</body>
+ <head>
+ <meta charset="utf-8" />
+ <style>
+ html,
+ body {
+ margin: 0;
+ height: 100%;
+ background: #111;
+ }
+ </style>
+ </head>
+ <body>
+ <div data-agent-id="demo" style="width:100%;height:100vh"></div>
+ <script type="module" src="https://3dagent.vercel.app/artifact.js"></script>
+ </body>
</html>
```
diff --git a/prompts/sprint-100/14-idle-animation-loop.md b/prompts/sprint-100/14-idle-animation-loop.md
index f0e39064b..839383524 100644
--- a/prompts/sprint-100/14-idle-animation-loop.md
+++ b/prompts/sprint-100/14-idle-animation-loop.md
@@ -33,6 +33,7 @@ export class IdleAnimation {
```
Behavior:
+
- **Breathing**: scale spine on Y by ±1% at 0.25Hz (~4s per breath).
- **Micro-sway**: ±0.5° rotation on spine root at 0.08Hz.
- **Head glance**: every 4–9s (random), rotate head yaw ±8° over 500ms, hold 200ms, return over 800ms.
diff --git a/prompts/sprint-100/15-embed-postmessage-bridge.md b/prompts/sprint-100/15-embed-postmessage-bridge.md
index b2f347edd..d332e8a8b 100644
--- a/prompts/sprint-100/15-embed-postmessage-bridge.md
+++ b/prompts/sprint-100/15-embed-postmessage-bridge.md
@@ -20,12 +20,14 @@ New standalone module. Not wired to the web component yet — sibling prompts co
Messages are JSON, always shaped `{ v: 1, type: string, id?: string, payload?: object }`.
**Host → embed:**
+
- `host.hello` → `{ hostName, hostVersion, hostOrigin, userId?: string, userName?: string }`
- `host.chat.message` → `{ role: 'user'|'assistant', text: string, messageId: string }`
- `host.action` → `{ action: string, args?: object }` (e.g., `'emote.wave'`, `'speak', { text }`)
- `host.theme` → `{ mode: 'dark'|'light' }`
**Embed → host:**
+
- `embed.ready` → `{ agentId, version, capabilities: string[] }`
- `embed.event` → `{ event: string, data?: object }`
- `embed.error` → `{ code, message }`
@@ -44,6 +46,7 @@ export class EmbedHostBridge extends EventTarget {
```
Behavior:
+
- Only messages from `window.parent` matching an allowed origin are processed.
- `addEventListener('host.chat.message', e => ...)` etc — emit a typed CustomEvent per incoming type.
- `request()` assigns an id, waits for matching `host.response`, rejects on timeout.
diff --git a/prompts/sprint-100/16-lobehub-plugin-manifest.md b/prompts/sprint-100/16-lobehub-plugin-manifest.md
index 837474ed4..6c5b15382 100644
--- a/prompts/sprint-100/16-lobehub-plugin-manifest.md
+++ b/prompts/sprint-100/16-lobehub-plugin-manifest.md
@@ -17,7 +17,7 @@ New static file + new endpoint. No edits to anything existing.
## Read first
- Skim the existing well-known files under `public/.well-known/` for conventions.
-- [api/_lib/http.js](../../api/_lib/http.js) — `wrap`, `json`, `cors`.
+- [api/\_lib/http.js](../../api/_lib/http.js) — `wrap`, `json`, `cors`.
## Deliverable
@@ -25,31 +25,31 @@ New static file + new endpoint. No edits to anything existing.
```json
{
- "$schema": "https://lobehub.com/schema/plugin.json",
- "api": [],
- "identifier": "3d-agent",
- "meta": {
- "title": "3D Agent",
- "description": "Embed any on-chain or off-chain 3D agent as an embodied avatar inside your chat.",
- "avatar": "https://3dagent.vercel.app/favicon.png",
- "tags": ["3d", "avatar", "embodied-agent", "erc-8004"]
- },
- "ui": {
- "mode": "iframe",
- "url": "https://3dagent.vercel.app/agent-embed.html",
- "height": 640,
- "settings": {
- "agentId": {
- "type": "string",
- "title": "Agent ID",
- "description": "Paste a 3D Agent ID or ENS name"
- }
- }
- },
- "author": "3d-agent",
- "createdAt": "2026-04-17",
- "homepage": "https://3dagent.vercel.app",
- "version": "1.0.0"
+ "$schema": "https://lobehub.com/schema/plugin.json",
+ "api": [],
+ "identifier": "3d-agent",
+ "meta": {
+ "title": "3D Agent",
+ "description": "Embed any on-chain or off-chain 3D agent as an embodied avatar inside your chat.",
+ "avatar": "https://3dagent.vercel.app/favicon.png",
+ "tags": ["3d", "avatar", "embodied-agent", "erc-8004"]
+ },
+ "ui": {
+ "mode": "iframe",
+ "url": "https://3dagent.vercel.app/agent-embed.html",
+ "height": 640,
+ "settings": {
+ "agentId": {
+ "type": "string",
+ "title": "Agent ID",
+ "description": "Paste a 3D Agent ID or ENS name"
+ }
+ }
+ },
+ "author": "3d-agent",
+ "createdAt": "2026-04-17",
+ "homepage": "https://3dagent.vercel.app",
+ "version": "1.0.0"
}
```
diff --git a/prompts/sprint-100/17-onchain-deploy-button.md b/prompts/sprint-100/17-onchain-deploy-button.md
index 242047d34..3728da0af 100644
--- a/prompts/sprint-100/17-onchain-deploy-button.md
+++ b/prompts/sprint-100/17-onchain-deploy-button.md
@@ -34,16 +34,16 @@ Behavior:
1. Render a button `⬢ Deploy on-chain` inside `container`.
2. If `agent.chainId` is already set (already deployed), replace the button with a chip `On-chain on Base Sepolia · view on explorer` linked to the appropriate explorer.
3. On click:
- - `connectWallet({ chainId: preferredChainId })`.
- - Show an inline progress panel: `Estimating gas... → Sign tx → Waiting confirmation → Done`.
- - Call `registerAgent({ signer, owner, agentURI })` with `agentURI` derived from the agent's manifest URL.
- - On confirmation: `POST /api/agents/:id/onchain` with `{ chainId, txHash, contractAddress }` to persist. If that endpoint doesn't exist, log a warning — the on-chain state is still authoritative.
- - Show success chip with explorer link.
+ - `connectWallet({ chainId: preferredChainId })`.
+ - Show an inline progress panel: `Estimating gas... → Sign tx → Waiting confirmation → Done`.
+ - Call `registerAgent({ signer, owner, agentURI })` with `agentURI` derived from the agent's manifest URL.
+ - On confirmation: `POST /api/agents/:id/onchain` with `{ chainId, txHash, contractAddress }` to persist. If that endpoint doesn't exist, log a warning — the on-chain state is still authoritative.
+ - Show success chip with explorer link.
4. Errors:
- - user rejected → reset silently.
- - wrong network → offer "Switch to Base Sepolia" action.
- - no contract deployed on chain → disable button with tooltip.
- - insufficient funds → show "Fund this wallet" with faucet link.
+ - user rejected → reset silently.
+ - wrong network → offer "Switch to Base Sepolia" action.
+ - no contract deployed on chain → disable button with tooltip.
+ - insufficient funds → show "Fund this wallet" with faucet link.
## CSS
diff --git a/prompts/sprint-100/18-ipfs-pinning.md b/prompts/sprint-100/18-ipfs-pinning.md
index 34d31d386..a668fac8b 100644
--- a/prompts/sprint-100/18-ipfs-pinning.md
+++ b/prompts/sprint-100/18-ipfs-pinning.md
@@ -17,7 +17,7 @@ New endpoint, no edits elsewhere.
- [api/avatars/presign.js](../../api/avatars/presign.js) — confirm the R2 URL shape.
- [.env.example](../../.env.example) — check for existing pinning creds (`PINATA_JWT`, `WEB3_STORAGE_TOKEN`, `ARWEAVE_KEY`).
-- [api/_lib/http.js](../../api/_lib/http.js), [api/_lib/auth.js](../../api/_lib/auth.js).
+- [api/\_lib/http.js](../../api/_lib/http.js), [api/\_lib/auth.js](../../api/_lib/auth.js).
## Deliverable
@@ -26,11 +26,11 @@ New endpoint, no edits elsewhere.
- Auth required (session or bearer).
- Body: `{ sourceUrl: string, kind: 'manifest' | 'glb' }`.
- Steps:
- 1. Validate `sourceUrl` is an R2 URL we own OR a `data:` URL under 10 MB.
- 2. HEAD the source — reject >50 MB.
- 3. Pin via Pinata (preferred; use `PINATA_JWT` if set) or Web3.Storage (fallback). If neither env var is present, return `503 pinning-unconfigured` with a clear message.
- 4. Return `{ ok: true, cid, gatewayUrl: 'https://ipfs.io/ipfs/' + cid, provider }`.
- 5. Record the pin in a `pins` table: `{ user_id, source_url, cid, provider, kind, created_at }` — create the table lazily via `if not exists` on first call.
+ 1. Validate `sourceUrl` is an R2 URL we own OR a `data:` URL under 10 MB.
+ 2. HEAD the source — reject >50 MB.
+ 3. Pin via Pinata (preferred; use `PINATA_JWT` if set) or Web3.Storage (fallback). If neither env var is present, return `503 pinning-unconfigured` with a clear message.
+ 4. Return `{ ok: true, cid, gatewayUrl: 'https://ipfs.io/ipfs/' + cid, provider }`.
+ 5. Record the pin in a `pins` table: `{ user_id, source_url, cid, provider, kind, created_at }` — create the table lazily via `if not exists` on first call.
- Rate limit: `30/hour per user`.
### `GET /api/pinning/status?cid=...`
diff --git a/prompts/sprint-100/19-address-resolver-api.md b/prompts/sprint-100/19-address-resolver-api.md
index 4fd1eb959..f33f4dabd 100644
--- a/prompts/sprint-100/19-address-resolver-api.md
+++ b/prompts/sprint-100/19-address-resolver-api.md
@@ -16,7 +16,7 @@ New endpoint.
- [src/erc8004/abi.js](../../src/erc8004/abi.js) — `REGISTRY_DEPLOYMENTS`, `IdentityRegistry` ABI.
- [api/agents/by-wallet.js](../../api/agents/by-wallet.js) — **read this first** — it may already do most of this. If it does, adapt this prompt to extend or redirect to it rather than duplicate. Note in report.
-- [api/_lib/db.js](../../api/_lib/db.js).
+- [api/\_lib/db.js](../../api/_lib/db.js).
## Deliverable
@@ -25,11 +25,11 @@ New endpoint.
- Public, rate-limited `120/min per IP`.
- Query params: `?chainId=<n>` (optional, default: try all known chains).
- Steps:
- 1. Normalize `addr` to lowercase, validate checksum-less hex.
- 2. DB-first: look up `agents` / `user_wallets` joined rows where the wallet owns the agent. Return if found.
- 3. Chain fallback: for each chain in `REGISTRY_DEPLOYMENTS`, call `IdentityRegistry.agentsByOwner(addr)` via an RPC read. Use the same RPC URLs `agent-registry.js` uses.
- 4. For each on-chain agentId, fetch `agentURI` and resolve the manifest.
- 5. Return `{ agents: [{ id, chainId, agentURI, manifestUrl, onChain: boolean, source: 'db'|'chain' }] }`.
+ 1. Normalize `addr` to lowercase, validate checksum-less hex.
+ 2. DB-first: look up `agents` / `user_wallets` joined rows where the wallet owns the agent. Return if found.
+ 3. Chain fallback: for each chain in `REGISTRY_DEPLOYMENTS`, call `IdentityRegistry.agentsByOwner(addr)` via an RPC read. Use the same RPC URLs `agent-registry.js` uses.
+ 4. For each on-chain agentId, fetch `agentURI` and resolve the manifest.
+ 5. Return `{ agents: [{ id, chainId, agentURI, manifestUrl, onChain: boolean, source: 'db'|'chain' }] }`.
- 404 with `{ agents: [] }` if none found (still 200, empty array, per REST convention — use 200).
## Constraints
diff --git a/prompts/sprint-100/20-ens-resolver.md b/prompts/sprint-100/20-ens-resolver.md
index 1de0c7ea9..df6841864 100644
--- a/prompts/sprint-100/20-ens-resolver.md
+++ b/prompts/sprint-100/20-ens-resolver.md
@@ -22,10 +22,10 @@ New endpoint. Does not touch the by-address resolver (sibling prompt 19).
- Public, rate-limited `60/min per IP`.
- Steps:
- 1. Validate `name` ends with `.eth` and is a sensible ENS label (`[a-z0-9-]+` across labels).
- 2. Use `ethers.getDefaultProvider('mainnet')` or a configured `MAINNET_RPC_URL` to call `provider.resolveName(name)` → address. If null, 404.
- 3. Proxy/forward to `/api/agents/by-address/:addr` logic — NOT via an HTTP hop; factor the shared logic out into a small helper if convenient, OR duplicate the read-through with a TODO to dedupe later. Note the decision in the report.
- 4. Return `{ name, address, agents: [...] }`.
+ 1. Validate `name` ends with `.eth` and is a sensible ENS label (`[a-z0-9-]+` across labels).
+ 2. Use `ethers.getDefaultProvider('mainnet')` or a configured `MAINNET_RPC_URL` to call `provider.resolveName(name)` → address. If null, 404.
+ 3. Proxy/forward to `/api/agents/by-address/:addr` logic — NOT via an HTTP hop; factor the shared logic out into a small helper if convenient, OR duplicate the read-through with a TODO to dedupe later. Note the decision in the report.
+ 4. Return `{ name, address, agents: [...] }`.
- Cache ENS → address resolution for 5 minutes in-memory.
## Constraints
diff --git a/prompts/sprint-100/21-og-meta-polish.md b/prompts/sprint-100/21-og-meta-polish.md
index e1ed7edde..754faeb12 100644
--- a/prompts/sprint-100/21-og-meta-polish.md
+++ b/prompts/sprint-100/21-og-meta-polish.md
@@ -26,22 +26,27 @@ Additive edits to two existing server files, plus optionally a new thumbnail ren
### `api/a-page.js` `<head>` must include:
```html
-<meta property="og:type" content="profile">
-<meta property="og:title" content="${agent.name} — 3D Agent">
-<meta property="og:description" content="${agent.bio || 'An embodied 3D agent'}">
-<meta property="og:image" content="${ogImageUrl}">
-<meta property="og:image:width" content="1200">
-<meta property="og:image:height" content="630">
-<meta name="twitter:card" content="summary_large_image">
-<meta name="twitter:image" content="${ogImageUrl}">
-<link rel="alternate" type="application/json+oembed"
- href="${origin}/api/agent-oembed?url=${encodedCurrentUrl}&format=json">
+<meta property="og:type" content="profile" />
+<meta property="og:title" content="${agent.name} — 3D Agent" />
+<meta property="og:description" content="${agent.bio || 'An embodied 3D agent'}" />
+<meta property="og:image" content="${ogImageUrl}" />
+<meta property="og:image:width" content="1200" />
+<meta property="og:image:height" content="630" />
+<meta name="twitter:card" content="summary_large_image" />
+<meta name="twitter:image" content="${ogImageUrl}" />
+<link
+ rel="alternate"
+ type="application/json+oembed"
+ href="${origin}/api/agent-oembed?url=${encodedCurrentUrl}&format=json"
+/>
```
### `api/a-og.js` response must include:
+
- `title`, `description`, `image`, `url`, `type`, plus new fields: `agent.name`, `agent.slug`, `agent.thumbnailUrl`, `agent.chainId?`, `agent.onChain?`.
### Dynamic OG image (if `@vercel/og` exists):
+
- 1200×630, dark background, centered square thumbnail, agent name, small chain badge if on-chain.
- 60s CDN cache.
diff --git a/prompts/sprint-100/22-cz-landing-page.md b/prompts/sprint-100/22-cz-landing-page.md
index feb8a8823..06feb366f 100644
--- a/prompts/sprint-100/22-cz-landing-page.md
+++ b/prompts/sprint-100/22-cz-landing-page.md
@@ -25,6 +25,7 @@ Entirely new folder + routes. No edits to existing app code.
### Frontend
`/cz` route:
+
- Full-bleed dark theme with a 3D agent embed front-and-center (uses `<agent-3d agent-id="cz-preview">` or similar hardcoded agent id).
- Copy: `Welcome, CZ. Claim your on-chain agent.`
- Button: `Connect wallet to claim` → uses the wallet flow from [src/wallet-auth.js](../../src/wallet-auth.js) if present, else falls back to `connectWallet()` from `erc8004/agent-registry.js`.
@@ -35,6 +36,7 @@ Entirely new folder + routes. No edits to existing app code.
### Backend
`POST /api/cz/claim`:
+
- Body: `{ signerAddress, signature, nonce }` — signer proves possession of the target address.
- Server issues a nonce via `GET /api/cz/claim?address=...` (add this branch).
- Verify signature → record claim intent in a `cz_claims` table → respond with `{ ok: true, txPayload: { to, data, value } }` so the client can broadcast the actual on-chain transfer.
diff --git a/prompts/sprint-100/23-action-passthrough.md b/prompts/sprint-100/23-action-passthrough.md
index 0f783e100..309415f7b 100644
--- a/prompts/sprint-100/23-action-passthrough.md
+++ b/prompts/sprint-100/23-action-passthrough.md
@@ -31,16 +31,17 @@ export class EmbedActionBridge {
Event map:
-| Host event | Translation to agent protocol |
-|---|---|
-| `host.chat.message {role:'user',text}` | `protocol.emit(ACTION_TYPES.SPEAK_TO_AGENT, { text })` |
+| Host event | Translation to agent protocol |
+| ------------------------------------------- | -------------------------------------------------------------------------- |
+| `host.chat.message {role:'user',text}` | `protocol.emit(ACTION_TYPES.SPEAK_TO_AGENT, { text })` |
| `host.chat.message {role:'assistant',text}` | `protocol.emit(ACTION_TYPES.AGENT_SPEAK, { text })` + optional TTS trigger |
-| `host.action {action:'emote.wave'}` | `protocol.emit(ACTION_TYPES.PLAY_ANIMATION, { clip: 'Wave' })` |
-| `host.action {action:'emote.*'}` | generic animation trigger with the suffix |
-| `host.action {action:'speak', args:{text}}` | `protocol.emit(ACTION_TYPES.AGENT_SPEAK, { text })` |
-| `host.theme {mode}` | `document.body.dataset.theme = mode` |
+| `host.action {action:'emote.wave'}` | `protocol.emit(ACTION_TYPES.PLAY_ANIMATION, { clip: 'Wave' })` |
+| `host.action {action:'emote.*'}` | generic animation trigger with the suffix |
+| `host.action {action:'speak', args:{text}}` | `protocol.emit(ACTION_TYPES.AGENT_SPEAK, { text })` |
+| `host.theme {mode}` | `document.body.dataset.theme = mode` |
Reverse (agent → host):
+
- When `protocol` emits `AGENT_EVENT` / `MEMORY_UPDATED` / `EMOTION_CHANGED` → `bridge.send('embed.event', { event, data })`.
Unknown events logged once at debug level, not propagated.
diff --git a/prompts/sprint-100/24-agent-suggest-endpoint.md b/prompts/sprint-100/24-agent-suggest-endpoint.md
index e62156c80..7bbadf4df 100644
--- a/prompts/sprint-100/24-agent-suggest-endpoint.md
+++ b/prompts/sprint-100/24-agent-suggest-endpoint.md
@@ -15,7 +15,7 @@ New endpoint, no edits elsewhere.
## Read first
- [api/agents/check-name.js](../../api/agents/check-name.js) — schema used.
-- [api/_lib/http.js](../../api/_lib/http.js), [api/_lib/db.js](../../api/_lib/db.js).
+- [api/\_lib/http.js](../../api/_lib/http.js), [api/\_lib/db.js](../../api/_lib/db.js).
## Deliverable
@@ -24,10 +24,10 @@ New endpoint, no edits elsewhere.
- Query: `q` (string, 1–32 chars), `limit` (default 8, max 20).
- Public, rate-limited `120/min per IP`.
- Ranks:
- 1. Exact name match (case-insensitive)
- 2. Prefix match on name
- 3. Prefix match on slug
- 4. Fuzzy match (trigram if available; otherwise `ILIKE '%q%'`)
+ 1. Exact name match (case-insensitive)
+ 2. Prefix match on name
+ 3. Prefix match on slug
+ 4. Fuzzy match (trigram if available; otherwise `ILIKE '%q%'`)
- Returns `{ agents: [{ id, name, slug, thumbnailUrl, chainId?: number, onChain: boolean }] }`.
- Excludes agents marked `private = true` or `hidden = true` if such columns exist.
- 60s response cache (CDN header `cache-control: public, max-age=60`).
diff --git a/prompts/sprint-100/25-claim-transfer-flow.md b/prompts/sprint-100/25-claim-transfer-flow.md
index ad8c90b12..e5bd75663 100644
--- a/prompts/sprint-100/25-claim-transfer-flow.md
+++ b/prompts/sprint-100/25-claim-transfer-flow.md
@@ -36,6 +36,7 @@ export class ClaimError extends Error {} // .code: 'wrong-owner'|'already-claime
```
Behavior:
+
- If the registry contract doesn't have a transfer entry point on the target chain, resolve by creating a new identity record on the claimer's wallet and marking the old one `superseded_by` — record that in `POST /api/cz/claim` (or the equivalent). If no server endpoint, throw `ClaimError('unsupported-chain')`.
- Never skip user signing. Every state change requires signer interaction.
diff --git a/prompts/wallet-auth/00-README.md b/prompts/wallet-auth/00-README.md
index b13b23eb9..aa771b5d0 100644
--- a/prompts/wallet-auth/00-README.md
+++ b/prompts/wallet-auth/00-README.md
@@ -15,14 +15,14 @@ A user lands on `3d.irish`, clicks **Sign in with wallet**, approves a MetaMask
## Prompts in this band
-| # | File | Depends on |
-|---|---|---|
-| 01 | [siwe-schema.md](./01-siwe-schema.md) | — |
-| 02 | [siwe-nonce-endpoint.md](./02-siwe-nonce-endpoint.md) | 01 |
-| 03 | [siwe-verify-endpoint.md](./03-siwe-verify-endpoint.md) | 01, 02 |
-| 04 | [signin-ui.md](./04-signin-ui.md) | 02, 03 |
-| 05 | [privy-backend-verify.md](./05-privy-backend-verify.md) | 03 |
-| 06 | [link-wallet-to-account.md](./06-link-wallet-to-account.md) | 03 |
+| # | File | Depends on |
+| --- | ----------------------------------------------------------- | ---------- |
+| 01 | [siwe-schema.md](./01-siwe-schema.md) | — |
+| 02 | [siwe-nonce-endpoint.md](./02-siwe-nonce-endpoint.md) | 01 |
+| 03 | [siwe-verify-endpoint.md](./03-siwe-verify-endpoint.md) | 01, 02 |
+| 04 | [signin-ui.md](./04-signin-ui.md) | 02, 03 |
+| 05 | [privy-backend-verify.md](./05-privy-backend-verify.md) | 03 |
+| 06 | [link-wallet-to-account.md](./06-link-wallet-to-account.md) | 03 |
01 → 02 → 03 → 04 is the critical path. 05 and 06 can run in parallel with 04.
diff --git a/prompts/wallet-auth/01-fix-agents-me-500.md b/prompts/wallet-auth/01-fix-agents-me-500.md
index 4eecb8d1e..f74327fc5 100644
--- a/prompts/wallet-auth/01-fix-agents-me-500.md
+++ b/prompts/wallet-auth/01-fix-agents-me-500.md
@@ -23,12 +23,12 @@ Auth is resolved in `resolveAuth()`: session cookie first, then bearer. If neith
## Deliverable
1. Modified [api/agents.js](../../api/agents.js):
- - `handleGetOrCreateMe` hardened against race on insert (two concurrent requests creating the default agent).
- - Error branches tagged in logs with a stable prefix like `[agents/me]` so future 500s are grep-able.
- - No behavior change for anonymous callers (`auth === null` → `200 { agent: null }`).
+ - `handleGetOrCreateMe` hardened against race on insert (two concurrent requests creating the default agent).
+ - Error branches tagged in logs with a stable prefix like `[agents/me]` so future 500s are grep-able.
+ - No behavior change for anonymous callers (`auth === null` → `200 { agent: null }`).
2. A minimal regression test file — plain Node, no new dev deps. Either:
- - `scripts/test-agents-me.mjs` — a standalone script that hits the endpoint with three cookie states and asserts status 200 + expected body shape; or
- - Inline `assert` block in an existing test harness if one exists in `scripts/`.
+ - `scripts/test-agents-me.mjs` — a standalone script that hits the endpoint with three cookie states and asserts status 200 + expected body shape; or
+ - Inline `assert` block in an existing test harness if one exists in `scripts/`.
3. Report the exact root cause you found. If the bug was a race, say "race on concurrent insert into `agent_identities`." If it was a schema mismatch, name the column. Don't report "hardened the handler" without a root cause.
## Audit checklist
@@ -58,7 +58,7 @@ Auth is resolved in `resolveAuth()`: session cookie first, then bearer. If neith
- **Do not change the route rewrite.** The `vercel.json` plumbing works; the bug is in the handler.
- **Do not add a new runtime dependency.** `sql` from `_lib/db.js`, `zod`, `jose` are all that's allowed.
-- **Do not silently swallow unknown errors.** The existing `42P01` swallow is the *only* acceptable silent fallback — anything else must `throw` so `wrap()` can 500 it visibly. The goal is to eliminate 500s by fixing root causes, not by hiding them.
+- **Do not silently swallow unknown errors.** The existing `42P01` swallow is the _only_ acceptable silent fallback — anything else must `throw` so `wrap()` can 500 it visibly. The goal is to eliminate 500s by fixing root causes, not by hiding them.
- Keep the file under 300 lines. If your fix balloons the file, move helpers into `_lib/`.
## Verification
@@ -66,16 +66,16 @@ Auth is resolved in `resolveAuth()`: session cookie first, then bearer. If neith
1. `node --check api/agents.js`
2. `npx vite build` — should pass (ignore pre-existing `@avaturn/sdk` warning).
3. Run your regression script against a local dev deploy:
- ```bash
- node scripts/test-agents-me.mjs
- ```
- Output should show three passing cases: anonymous → 200 null, fresh user → 200 agent, existing user → 200 agent.
+ ```bash
+ node scripts/test-agents-me.mjs
+ ```
+ Output should show three passing cases: anonymous → 200 null, fresh user → 200 agent, existing user → 200 agent.
4. Concurrency check — with `DATABASE_URL` pointed at a dev branch:
- ```bash
- for i in {1..10}; do curl -s -b "__Host-sid=$SID" https://localhost/api/agents/me & done; wait
- psql "$DATABASE_URL" -c "select count(*) from agent_identities where user_id = '<uid>' and deleted_at is null"
- ```
- Must return `1`.
+ ```bash
+ for i in {1..10}; do curl -s -b "__Host-sid=$SID" https://localhost/api/agents/me & done; wait
+ psql "$DATABASE_URL" -c "select count(*) from agent_identities where user_id = '<uid>' and deleted_at is null"
+ ```
+ Must return `1`.
## Scope boundaries — do NOT do these
diff --git a/prompts/wallet-auth/01-siwe-schema.md b/prompts/wallet-auth/01-siwe-schema.md
index a2c952352..d44d889b5 100644
--- a/prompts/wallet-auth/01-siwe-schema.md
+++ b/prompts/wallet-auth/01-siwe-schema.md
@@ -2,7 +2,7 @@
## Why this exists
-We have `users` (email + password) and `agent_identities` (per-agent wallet). We have **no** place to store the fact that a wallet address *is* a user, and no place to store single-use auth nonces. Without both, SIWE sign-in is either impossible (no user mapping) or replayable (no nonce tracking).
+We have `users` (email + password) and `agent_identities` (per-agent wallet). We have **no** place to store the fact that a wallet address _is_ a user, and no place to store single-use auth nonces. Without both, SIWE sign-in is either impossible (no user mapping) or replayable (no nonce tracking).
## Files you own
@@ -27,6 +27,7 @@ CREATE UNIQUE INDEX IF NOT EXISTS users_wallet_address_unique
```
Notes:
+
- `wallet_address` nullable — existing email users keep working.
- Case-insensitive unique — EIP-55 checksummed and all-lowercase addresses must collide.
- `wallet_chain_id` optional because SIWE can be chain-agnostic; store the chain the user signed on for audit.
@@ -47,6 +48,7 @@ CREATE INDEX IF NOT EXISTS auth_nonces_expires_idx ON auth_nonces (expires_at);
```
Notes:
+
- `nonce` is 16+ random bytes base64url'd on the server; treat it as an opaque PK.
- `used_at` is set on successful verify — never allow the same nonce twice.
- A nightly cron / lazy cleanup can prune `expires_at < now()` rows; don't build it here.
diff --git a/prompts/wallet-auth/02-siwe-flow-hardening.md b/prompts/wallet-auth/02-siwe-flow-hardening.md
index 047b2fcb6..491f4eaf4 100644
--- a/prompts/wallet-auth/02-siwe-flow-hardening.md
+++ b/prompts/wallet-auth/02-siwe-flow-hardening.md
@@ -2,7 +2,7 @@
## Context
-Repo: `/workspaces/3D`. Sign-In with Ethereum (EIP-4361) is the primary login mode for the CZ demo. Nonce issuing lives in [api/auth/siwe/nonce.js](../../api/auth/siwe/nonce.js) and verification in [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js). The client builds the SIWE message in [public/wallet-login.js](../../public/wallet-login.js). Schema: `siwe_nonces` table in [api/_lib/schema.sql](../../api/_lib/schema.sql) (lines ~130–140).
+Repo: `/workspaces/3D`. Sign-In with Ethereum (EIP-4361) is the primary login mode for the CZ demo. Nonce issuing lives in [api/auth/siwe/nonce.js](../../api/auth/siwe/nonce.js) and verification in [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js). The client builds the SIWE message in [public/wallet-login.js](../../public/wallet-login.js). Schema: `siwe_nonces` table in [api/\_lib/schema.sql](../../api/_lib/schema.sql) (lines ~130–140).
Today the flow does the right shape of things (parse → domain check → temporal check → nonce lookup → signature recover → burn nonce → create-or-link user → session). What this task covers is making every one of those steps airtight under adversarial conditions: replay, phishing domain, chainId mismatch, clock skew, nonce exhaustion, parallel verify calls with the same nonce.
@@ -25,12 +25,12 @@ After this task, a reviewer can tick every box on the audit checklist below and
- [ ] Nonce has ≥ 128 bits of entropy. Current code loops to pad to 16 alphanumeric chars ≈ 95 bits — document whether that's acceptable or bump to 22 chars (≈ 128 bits).
- [ ] Rate-limited per IP via `limits.authIp(ip)`. Confirm the preset applies; do not invent a new limiter.
- [ ] No user input is accepted — nonce endpoint is GET-only, no body echoed.
-- [ ] Response sets `Cache-Control: no-store` (via `json()` helper in [api/_lib/http.js](../../api/_lib/http.js) — confirm the helper does this).
+- [ ] Response sets `Cache-Control: no-store` (via `json()` helper in [api/\_lib/http.js](../../api/_lib/http.js) — confirm the helper does this).
**Message parsing — `parseSiweMessage` in [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js)**
- [ ] Header regex anchors both `^` and `$`. It does today — don't regress.
-- [ ] Address is validated as a 40-hex string *and* re-checksummed via `getAddress()` before comparison.
+- [ ] Address is validated as a 40-hex string _and_ re-checksummed via `getAddress()` before comparison.
- [ ] `Version` must equal `'1'`. Current parser stores it but never checks the value — **fix this**.
- [ ] `Chain ID` is required (not just present — verify it's a valid integer, not `null`). Reject if missing.
- [ ] Unknown lines are ignored silently — that's fine, but `Resources:` (multi-line) is not currently handled. Decide: either parse it or explicitly reject messages that contain `Resources:`. Document the choice.
@@ -40,7 +40,7 @@ After this task, a reviewer can tick every box on the audit checklist below and
- [ ] `fields.domain === new URL(env.APP_ORIGIN).host` — confirmed.
- [ ] `fields.uri` origin equals `env.APP_ORIGIN` — confirmed. Make sure the `new URL(fields.uri)` throw is caught (it is).
- [ ] On a mismatch, return `400 invalid_domain` / `invalid_uri` — do not 500.
-- [ ] `APP_ORIGIN` is read from `env` (not hardcoded). Check [api/_lib/env.js](../../api/_lib/env.js) that it's a required var and throws at startup if missing.
+- [ ] `APP_ORIGIN` is read from `env` (not hardcoded). Check [api/\_lib/env.js](../../api/_lib/env.js) that it's a required var and throws at startup if missing.
**Temporal checks**
@@ -89,14 +89,14 @@ After this task, a reviewer can tick every box on the audit checklist below and
1. `node --check api/auth/siwe/verify.js api/auth/siwe/nonce.js`
2. `npx vite build` — passes.
3. `node scripts/test-siwe-flow.mjs` — run against a local dev deploy:
- - Good path → 200, session cookie issued.
- - Replay with used nonce → 400 `nonce_reused`.
- - Tampered message (changed address) → 401 `invalid_signature`.
- - Wrong domain in message → 400 `invalid_domain`.
- - Expired message (`expirationTime` in the past) → 400 `expired`.
- - Clock-skewed `issuedAt` (1 day in the future) → 400 `clock_skew`.
- - Missing `Chain ID` → 400 validation-ish error.
- - Wrong signature (signer ≠ address) → 401 `invalid_signature`.
+ - Good path → 200, session cookie issued.
+ - Replay with used nonce → 400 `nonce_reused`.
+ - Tampered message (changed address) → 401 `invalid_signature`.
+ - Wrong domain in message → 400 `invalid_domain`.
+ - Expired message (`expirationTime` in the past) → 400 `expired`.
+ - Clock-skewed `issuedAt` (1 day in the future) → 400 `clock_skew`.
+ - Missing `Chain ID` → 400 validation-ish error.
+ - Wrong signature (signer ≠ address) → 401 `invalid_signature`.
4. `psql` — confirm `siwe_nonces` rows older than a day are cleaned up.
## Scope boundaries — do NOT do these
diff --git a/prompts/wallet-auth/03-link-wallet-to-user.md b/prompts/wallet-auth/03-link-wallet-to-user.md
index 77943a0c9..90cad307e 100644
--- a/prompts/wallet-auth/03-link-wallet-to-user.md
+++ b/prompts/wallet-auth/03-link-wallet-to-user.md
@@ -7,7 +7,7 @@ Repo: `/workspaces/3D`. Today there are two parallel wallet fields:
1. `users.wallet_address` — set by [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) when a brand-new user signs in with a wallet. One row per user, one wallet per user.
2. `user_wallets` table — a proper many-to-one join (`user_id`, `address`, `chain_id`, `is_primary`). Already populated by the SIWE verify path.
-See [api/_lib/schema.sql](../../api/_lib/schema.sql) lines ~10–26 (`users`) and ~143–153 (`user_wallets`).
+See [api/\_lib/schema.sql](../../api/_lib/schema.sql) lines ~10–26 (`users`) and ~143–153 (`user_wallets`).
Problems:
@@ -19,6 +19,7 @@ Problems:
## Goal
A clear data model and API where:
+
- **One user can have many wallets.** Signed message required per link.
- **One wallet belongs to exactly one user.** Attempting to link a wallet already owned by someone else returns `409 wallet_already_linked`.
- A signed-in user can list, add, set-primary, and remove wallets.
@@ -26,16 +27,16 @@ A clear data model and API where:
## Deliverable
-1. Schema patch in [api/_lib/schema.sql](../../api/_lib/schema.sql):
- - Ensure `user_wallets.address` is unique (already is — verify).
- - Add `user_wallets.label` (nullable text, for UI).
- - Add `user_wallets.linked_via` check constraint: one of `'signup_siwe' | 'link_siwe'`.
- - Decision on `users.wallet_address`: either drop the column (write a migration) or document in a comment that it's a denormalized mirror of the primary `user_wallets` row and is updated by the API. Pick one; don't leave it ambiguous.
+1. Schema patch in [api/\_lib/schema.sql](../../api/_lib/schema.sql):
+ - Ensure `user_wallets.address` is unique (already is — verify).
+ - Add `user_wallets.label` (nullable text, for UI).
+ - Add `user_wallets.linked_via` check constraint: one of `'signup_siwe' | 'link_siwe'`.
+ - Decision on `users.wallet_address`: either drop the column (write a migration) or document in a comment that it's a denormalized mirror of the primary `user_wallets` row and is updated by the API. Pick one; don't leave it ambiguous.
2. New endpoint file `api/wallets.js` (plus a route in [vercel.json](../../vercel.json)):
- - `GET /api/wallets` — list caller's wallets. Auth required.
- - `POST /api/wallets/link` — body `{ message, signature }`. Verifies SIWE signature exactly like [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) but **does not mint a new session** — it requires an existing session and adds the wallet to it. If address already belongs to another user → 409.
- - `POST /api/wallets/:address/primary` — mark as primary. Unsets `is_primary` on other rows for this user.
- - `DELETE /api/wallets/:address` — unlink. If it's the only wallet and the user has no password set → 400 `cannot_remove_sole_credential`.
+ - `GET /api/wallets` — list caller's wallets. Auth required.
+ - `POST /api/wallets/link` — body `{ message, signature }`. Verifies SIWE signature exactly like [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) but **does not mint a new session** — it requires an existing session and adds the wallet to it. If address already belongs to another user → 409.
+ - `POST /api/wallets/:address/primary` — mark as primary. Unsets `is_primary` on other rows for this user.
+ - `DELETE /api/wallets/:address` — unlink. If it's the only wallet and the user has no password set → 400 `cannot_remove_sole_credential`.
3. Factor the SIWE verification logic out of [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) into `api/_lib/siwe.js` exporting `verifySiwe(message, signature, { burnNonce }) → { address, chainId, fields }`. Both the login-verify endpoint and the new link endpoint import it. Don't duplicate parser / temporal / domain logic.
4. Update [src/agent-identity.js](../../src/agent-identity.js) and [src/account.js](../../src/account.js) if they call any now-changed endpoint shapes. Likely a no-op; check.
@@ -104,17 +105,17 @@ A clear data model and API where:
2. `psql "$DATABASE_URL" -f api/_lib/schema.sql` — idempotent, no errors.
3. `npx vite build` — passes.
4. Manual curl sequence:
- ```bash
- # sign in as user A
- curl -c a.txt -X POST /api/auth/login -d '…'
- # link wallet
- curl -b a.txt -X POST /api/wallets/link -d '{"message":"…","signature":"0x…"}'
- # list
- curl -b a.txt /api/wallets # expect 1 wallet, is_primary=true
- # sign in as user B, try to link same wallet → 409
- curl -c b.txt -X POST /api/auth/login -d '…'
- curl -b b.txt -X POST /api/wallets/link -d '{"message":"…same addr…"}' # expect 409
- ```
+ ```bash
+ # sign in as user A
+ curl -c a.txt -X POST /api/auth/login -d '…'
+ # link wallet
+ curl -b a.txt -X POST /api/wallets/link -d '{"message":"…","signature":"0x…"}'
+ # list
+ curl -b a.txt /api/wallets # expect 1 wallet, is_primary=true
+ # sign in as user B, try to link same wallet → 409
+ curl -c b.txt -X POST /api/auth/login -d '…'
+ curl -b b.txt -X POST /api/wallets/link -d '{"message":"…same addr…"}' # expect 409
+ ```
## Scope boundaries — do NOT do these
diff --git a/prompts/wallet-auth/03-siwe-verify-endpoint.md b/prompts/wallet-auth/03-siwe-verify-endpoint.md
index 7aaeb3681..0ace522b3 100644
--- a/prompts/wallet-auth/03-siwe-verify-endpoint.md
+++ b/prompts/wallet-auth/03-siwe-verify-endpoint.md
@@ -3,6 +3,7 @@
## Why this exists
The user signs the SIWE message client-side. The server must:
+
1. Recover the signing address.
2. Validate the nonce is ours, unused, unexpired.
3. Bind that address to a user row (find-or-create).
@@ -25,11 +26,12 @@ Do not touch existing auth handlers.
`POST /api/auth/siwe/verify`
Body:
+
```json
{
- "message": "<full EIP-4361 message the user signed>",
- "signature": "0x...",
- "purpose": "login"
+ "message": "<full EIP-4361 message the user signed>",
+ "signature": "0x...",
+ "purpose": "login"
}
```
@@ -37,15 +39,15 @@ Steps:
1. IP rate limit: `siweVerifyIp` (60 / 10m). On fail → 429.
2. Parse the SIWE message. Extract: `domain`, `address`, `statement`, `uri`, `version`, `chainId`, `nonce`, `issuedAt`, `expirationTime`.
- - Minimum viable parser: regex out the fields. No new dep.
+ - Minimum viable parser: regex out the fields. No new dep.
3. Reject if `domain !== new URL(env.APP_ORIGIN).host`.
4. Reject if `version !== '1'`.
5. Reject if `expirationTime` is present and past, or if `issuedAt` is >10 min old.
6. Recover signer: `ethers.verifyMessage(message, signature)` (ethers v6 is already a dep). Reject if `recovered.toLowerCase() !== address.toLowerCase()`.
7. `SELECT * FROM auth_nonces WHERE nonce = $1 FOR UPDATE` inside a transaction. Reject if row absent, `expires_at < now`, or `used_at IS NOT NULL`. Then `UPDATE auth_nonces SET used_at = now() WHERE nonce = $1`.
8. Find-or-create user:
- - `SELECT * FROM users WHERE lower(wallet_address) = lower($1)`.
- - If missing, `INSERT INTO users (id, wallet_address, wallet_chain_id, wallet_linked_at, created_at) VALUES (...)`. `email` stays NULL.
+ - `SELECT * FROM users WHERE lower(wallet_address) = lower($1)`.
+ - If missing, `INSERT INTO users (id, wallet_address, wallet_chain_id, wallet_linked_at, created_at) VALUES (...)`. `email` stays NULL.
9. Issue session: reuse `createSession({ userId, userAgent, ip })` from `api/_lib/auth.js`. Set `__Host-sid` cookie with the same attributes the email login uses.
10. Respond `200 { user: { id, walletAddress, chainId, createdAt } }`.
diff --git a/prompts/wallet-auth/04-connect-wallet-button.md b/prompts/wallet-auth/04-connect-wallet-button.md
index 788895fd4..e73d8da92 100644
--- a/prompts/wallet-auth/04-connect-wallet-button.md
+++ b/prompts/wallet-auth/04-connect-wallet-button.md
@@ -19,8 +19,8 @@ One component and one state machine that every caller uses. When the button is i
## Deliverable
1. New module `src/wallet/connect-button.js` exporting:
- - A class `ConnectWalletController` — headless state machine with the states below. Emits `change` events on state transition.
- - A factory `createConnectWalletButton(mountEl, opts)` — renders and wires a button that binds to the controller. Returns the controller.
+ - A class `ConnectWalletController` — headless state machine with the states below. Emits `change` events on state transition.
+ - A factory `createConnectWalletButton(mountEl, opts)` — renders and wires a button that binds to the controller. Returns the controller.
2. New module `src/wallet/state.js` exporting the state enum and a pure reducer for unit-testability.
3. Refactored [public/wallet-login.js](../../public/wallet-login.js) to use the controller. Strip its copy of the connect logic; keep only the page-specific redirect-after-success behavior.
4. Minimal CSS in `public/wallet-connect.css` — the button should not depend on the existing login page's CSS to render correctly when used elsewhere.
@@ -43,22 +43,22 @@ States (one active at a time):
Transitions (inputs from the reducer):
-| From | Input | To |
-|---|---|---|
-| `idle` | `connect()` | `detecting` |
-| `detecting` | no `window.ethereum` | `no_provider` |
-| `detecting` | has provider | `requesting_accounts` |
-| `requesting_accounts` | `eth_accounts` resolves | `connected` |
-| `requesting_accounts` | user rejects | `error` |
-| `connected` | chainId ∉ allowed | `wrong_chain` |
-| `connected` | `sign()` called | `signing` |
-| `wrong_chain` | user switches chain | `connected` |
-| `signing` | signature obtained | `verifying` |
-| `signing` | user rejects | `error` |
-| `verifying` | server 200 | `success` |
-| `verifying` | server 4xx/5xx | `error` |
-| any | `reset()` | `idle` |
-| any | wallet disconnect event | `idle` |
+| From | Input | To |
+| --------------------- | ----------------------- | --------------------- |
+| `idle` | `connect()` | `detecting` |
+| `detecting` | no `window.ethereum` | `no_provider` |
+| `detecting` | has provider | `requesting_accounts` |
+| `requesting_accounts` | `eth_accounts` resolves | `connected` |
+| `requesting_accounts` | user rejects | `error` |
+| `connected` | chainId ∉ allowed | `wrong_chain` |
+| `connected` | `sign()` called | `signing` |
+| `wrong_chain` | user switches chain | `connected` |
+| `signing` | signature obtained | `verifying` |
+| `signing` | user rejects | `error` |
+| `verifying` | server 200 | `success` |
+| `verifying` | server 4xx/5xx | `error` |
+| any | `reset()` | `idle` |
+| any | wallet disconnect event | `idle` |
## Audit checklist
@@ -112,11 +112,11 @@ Transitions (inputs from the reducer):
1. `node --check src/wallet/connect-button.js src/wallet/state.js public/wallet-login.js`
2. `npx vite build` — passes.
3. Open `public/wallet-connect-demo.html` in a browser with MetaMask:
- - Click "Connect wallet" on the first button → MetaMask prompt → connected state shows short address.
- - Switch MetaMask to an unsupported chain → button shows "Switch to Mainnet".
- - Click → switch prompt → returns to connected.
- - Click "Sign in" → signature prompt → server verifies → success state.
- - Disconnect in MetaMask → all three buttons return to `idle` via `accountsChanged`.
+ - Click "Connect wallet" on the first button → MetaMask prompt → connected state shows short address.
+ - Switch MetaMask to an unsupported chain → button shows "Switch to Mainnet".
+ - Click → switch prompt → returns to connected.
+ - Click "Sign in" → signature prompt → server verifies → success state.
+ - Disconnect in MetaMask → all three buttons return to `idle` via `accountsChanged`.
4. `/login` still works end-to-end: connect → sign → redirected to `/dashboard/`.
5. Reducer tests (optional but recommended) — if you add `scripts/test-connect-reducer.mjs`, assert every transition in the table above.
@@ -124,7 +124,7 @@ Transitions (inputs from the reducer):
- Do not add Privy-specific integration. Privy stays in its current code path.
- Do not add WalletConnect / QR-code flow.
-- Do not implement the "link additional wallet" endpoint — that is task 03. This component just has to *support* being pointed at that endpoint via `verifyUrl`.
+- Do not implement the "link additional wallet" endpoint — that is task 03. This component just has to _support_ being pointed at that endpoint via `verifyUrl`.
- Do not add logout / session refresh (task 05).
- Do not change [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) or [api/auth/siwe/nonce.js](../../api/auth/siwe/nonce.js).
- Do not add styling that overrides the global site theme. Component CSS must be scoped via the `[data-state]` attribute or a prefixed class.
diff --git a/prompts/wallet-auth/04-signin-ui.md b/prompts/wallet-auth/04-signin-ui.md
index 8b0b675ba..60b3ffe51 100644
--- a/prompts/wallet-auth/04-signin-ui.md
+++ b/prompts/wallet-auth/04-signin-ui.md
@@ -22,18 +22,20 @@ Exports a single async function `signInWithWallet({ chainId } = {})` that:
1. Calls `connectWallet()` from `src/erc8004/agent-registry.js` → `{ provider, signer, address, chainId: connectedChainId }`.
2. `POST /api/auth/siwe/nonce` with `{ purpose: 'login', address }` — receives `{ nonce, expiresAt, domain, statement, version }`.
3. Builds the EIP-4361 message string client-side:
- ```
- ${domain} wants you to sign in with your Ethereum account:
- ${address}
-
- ${statement}
-
- URI: ${location.origin}
- Version: ${version}
- Chain ID: ${connectedChainId}
- Nonce: ${nonce}
- Issued At: ${new Date().toISOString()}
- ```
+
+ ```
+ ${domain} wants you to sign in with your Ethereum account:
+ ${address}
+
+ ${statement}
+
+ URI: ${location.origin}
+ Version: ${version}
+ Chain ID: ${connectedChainId}
+ Nonce: ${nonce}
+ Issued At: ${new Date().toISOString()}
+ ```
+
4. `signature = await signer.signMessage(message)`.
5. `POST /api/auth/siwe/verify` with `{ message, signature, purpose: 'login' }` and `credentials: 'include'`.
6. On success: `window.location.assign('/dashboard')`.
@@ -63,9 +65,9 @@ Under the existing "email + password" form, a visual divider ("— or —") and
1. `node --check src/wallet-auth.js` passes.
2. `npx vite build` — no new warnings.
3. Manual (Chrome + MetaMask):
- - Click "Sign in with wallet" in the header → MetaMask opens with the SIWE message → approve → redirected to `/dashboard` as a signed-in user.
- - Refresh the page → stays signed in, chip shows truncated address.
- - Click sign out → cookie cleared, button returns.
+ - Click "Sign in with wallet" in the header → MetaMask opens with the SIWE message → approve → redirected to `/dashboard` as a signed-in user.
+ - Refresh the page → stays signed in, chip shows truncated address.
+ - Click sign out → cookie cleared, button returns.
4. Manual (no injected wallet): button shows a message instead of throwing.
5. DevTools Network tab shows exactly: `nonce` (POST), one `personal_sign` RPC to the wallet, `verify` (POST).
diff --git a/prompts/wallet-auth/05-privy-backend-verify.md b/prompts/wallet-auth/05-privy-backend-verify.md
index 580c29b1f..998257137 100644
--- a/prompts/wallet-auth/05-privy-backend-verify.md
+++ b/prompts/wallet-auth/05-privy-backend-verify.md
@@ -3,6 +3,7 @@
## Why this exists
Privy (already a client-side dep) gives us embedded wallets, email-based wallet login, and WalletConnect UX for free. Today it is used only on the ERC-8004 registration page. If we accept a Privy access token at the backend, we get:
+
- Users without a browser wallet can still sign in (Privy issues them an embedded wallet).
- Mobile / Brave / Safari users without MetaMask can still sign in via WalletConnect UX.
- Existing MetaMask users keep working because task 03 still accepts raw SIWE.
@@ -25,6 +26,7 @@ Do not rewrite task 03.
Body: `{ accessToken: "eyJ..." }` (Privy-issued JWT).
Steps:
+
1. If `env.PRIVY_APP_ID` or `env.PRIVY_APP_SECRET` unset → `501 { error: "privy not configured" }`.
2. Verify the JWT with Privy's JWKS. Use `jose` (already a dep). Fetch JWKS from `https://auth.privy.io/api/v1/apps/${appId}/jwks.json`, cache for 10 minutes in memory.
3. Require `aud === env.PRIVY_APP_ID` and `iss === 'privy.io'`. Reject expired tokens.
@@ -38,7 +40,7 @@ In `src/wallet-auth.js`, add:
```js
export async function signInWithPrivy() {
- // Load @privy-io/js-sdk-core lazily; get accessToken; POST to /api/auth/privy/verify.
+ // Load @privy-io/js-sdk-core lazily; get accessToken; POST to /api/auth/privy/verify.
}
```
diff --git a/prompts/wallet-auth/05-session-refresh-and-logout.md b/prompts/wallet-auth/05-session-refresh-and-logout.md
index c9bc971cb..36b265f3a 100644
--- a/prompts/wallet-auth/05-session-refresh-and-logout.md
+++ b/prompts/wallet-auth/05-session-refresh-and-logout.md
@@ -2,14 +2,16 @@
## Context
-Repo: `/workspaces/3D`. Browser sessions are implemented in [api/_lib/auth.js](../../api/_lib/auth.js) (`createSession`, `sessionCookie`, `getSessionUser`, `destroySession`). The session cookie name is `__Host-sid` with a 30-day TTL (`SESSION_TTL_SEC = 60 * 60 * 24 * 30`). Sessions are stored in the `sessions` table (see [api/_lib/schema.sql](../../api/_lib/schema.sql) lines ~156–169) with `token_hash`, `user_agent`, `ip`, `expires_at`, `revoked_at`, `last_seen_at`.
+Repo: `/workspaces/3D`. Browser sessions are implemented in [api/\_lib/auth.js](../../api/_lib/auth.js) (`createSession`, `sessionCookie`, `getSessionUser`, `destroySession`). The session cookie name is `__Host-sid` with a 30-day TTL (`SESSION_TTL_SEC = 60 * 60 * 24 * 30`). Sessions are stored in the `sessions` table (see [api/\_lib/schema.sql](../../api/_lib/schema.sql) lines ~156–169) with `token_hash`, `user_agent`, `ip`, `expires_at`, `revoked_at`, `last_seen_at`.
Today:
+
- [api/auth/login.js](../../api/auth/login.js), [api/auth/register.js](../../api/auth/register.js), and [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) mint a new session.
- [api/auth/logout.js](../../api/auth/logout.js) revokes the current session and clears the cookie.
- [api/auth/me.js](../../api/auth/me.js) returns the session user or 401.
Gaps:
+
- **No rolling refresh.** A 30-day cookie that never rotates means a stolen cookie works for 30 days regardless of activity. Active users should have their session silently extended; inactive users should be forced to reauthenticate.
- **No "log out everywhere" endpoint.** A user who suspects a stolen device can't revoke all their sessions.
- **Wallet disconnect is not wired to session.** When a user disconnects their wallet in MetaMask, the site still treats them as signed in — which is correct (SIWE is proof at time-of-sign-in, not a continuous check) but there's no UX for "you disconnected, do you want to sign out of the site too?".
@@ -21,18 +23,18 @@ A documented session lifecycle: sessions rotate on activity, users can enumerate
## Deliverable
-1. Modified [api/_lib/auth.js](../../api/_lib/auth.js):
- - `getSessionUser(req, res?)` — if `res` is provided and the session is within the refresh window (see below), issue a rolled cookie via `sessionCookie(newToken)`. Otherwise unchanged behavior.
- - New `rotateSession({ oldToken, userAgent, ip })` — issues a new row, revokes the old, returns the new secret.
+1. Modified [api/\_lib/auth.js](../../api/_lib/auth.js):
+ - `getSessionUser(req, res?)` — if `res` is provided and the session is within the refresh window (see below), issue a rolled cookie via `sessionCookie(newToken)`. Otherwise unchanged behavior.
+ - New `rotateSession({ oldToken, userAgent, ip })` — issues a new row, revokes the old, returns the new secret.
2. New endpoint `api/auth/sessions.js`:
- - `GET /api/auth/sessions` — returns the caller's non-revoked, non-expired sessions. Include `id`, `user_agent`, `ip`, `created_at`, `last_seen_at`, `expires_at`, `is_current`.
- - `DELETE /api/auth/sessions/:id` — revoke a single non-current session.
- - `DELETE /api/auth/sessions` — revoke **all** of the caller's sessions, then issue a fresh cookie for the current request (so the user stays signed in on this device). This is the "log out everywhere else" operation.
+ - `GET /api/auth/sessions` — returns the caller's non-revoked, non-expired sessions. Include `id`, `user_agent`, `ip`, `created_at`, `last_seen_at`, `expires_at`, `is_current`.
+ - `DELETE /api/auth/sessions/:id` — revoke a single non-current session.
+ - `DELETE /api/auth/sessions` — revoke **all** of the caller's sessions, then issue a fresh cookie for the current request (so the user stays signed in on this device). This is the "log out everywhere else" operation.
3. New endpoint `api/auth/logout-everywhere.js`:
- - `POST /api/auth/logout-everywhere` — revokes **every** session for the caller including the current one, clears the current cookie. Different from the above: this fully signs them out on every device including this one.
+ - `POST /api/auth/logout-everywhere` — revokes **every** session for the caller including the current one, clears the current cookie. Different from the above: this fully signs them out on every device including this one.
4. Route additions in [vercel.json](../../vercel.json) — follow the existing `/api/auth/*` wiring.
5. Client changes in [public/wallet-login.js](../../public/wallet-login.js) or a new `public/session-client.js`:
- - Listens for `accountsChanged` → if currently signed in via SIWE for that address and the wallet disconnects, show a small toast "MetaMask disconnected — you're still signed in. [Sign out]". Do not auto-sign-out.
+ - Listens for `accountsChanged` → if currently signed in via SIWE for that address and the wallet disconnects, show a small toast "MetaMask disconnected — you're still signed in. [Sign out]". Do not auto-sign-out.
6. Update [src/account.js](../../src/account.js) `getMe()` if the response shape changes — likely a no-op.
## Session refresh window — spec
@@ -96,7 +98,7 @@ A documented session lifecycle: sessions rotate on activity, users can enumerate
- **No new runtime dependencies.**
- Keep the `__Host-sid` cookie name. Don't rename. Don't change `SameSite=Lax`, `HttpOnly`, `Secure`, `Path=/`.
- Keep the 30-day TTL. The point of rotation is not a shorter TTL; it's defense against long-lived token theft for inactive cookies.
-- Do not break the legacy `sid` cookie read path in [api/_lib/auth.js](../../api/_lib/auth.js) — it's there for a deploy-cycle compat and should still be honored on read.
+- Do not break the legacy `sid` cookie read path in [api/\_lib/auth.js](../../api/_lib/auth.js) — it's there for a deploy-cycle compat and should still be honored on read.
- Do not touch the OAuth refresh-token code in the same file. That's a different grant type; the concerns don't overlap.
- Stick to [api/CLAUDE.md](../../api/CLAUDE.md) helpers: `wrap`, `json`, `error`, `method`, `cors`, `limits`.
@@ -105,30 +107,30 @@ A documented session lifecycle: sessions rotate on activity, users can enumerate
1. `node --check api/_lib/auth.js api/auth/sessions.js api/auth/logout-everywhere.js public/session-client.js` (or wherever the client code lives).
2. `npx vite build` — passes.
3. Manual rotation test:
- ```bash
- # sign in; capture cookie
- curl -c j.txt -X POST /api/auth/login -d '{"email":"…","password":"…"}'
- # force last_seen_at old via psql
- psql "$DATABASE_URL" -c "update sessions set last_seen_at = now() - interval '2 days', expires_at = now() + interval '6 days' where token_hash = '…'"
- # next request should roll
- curl -b j.txt -c j2.txt /api/auth/me -i | grep -i '^set-cookie'
- # confirm new __Host-sid value
- ```
+ ```bash
+ # sign in; capture cookie
+ curl -c j.txt -X POST /api/auth/login -d '{"email":"…","password":"…"}'
+ # force last_seen_at old via psql
+ psql "$DATABASE_URL" -c "update sessions set last_seen_at = now() - interval '2 days', expires_at = now() + interval '6 days' where token_hash = '…'"
+ # next request should roll
+ curl -b j.txt -c j2.txt /api/auth/me -i | grep -i '^set-cookie'
+ # confirm new __Host-sid value
+ ```
4. List sessions:
- ```bash
- curl -b j.txt /api/auth/sessions
- ```
- Sign in on a second browser, refresh list — new entry appears with `is_current: false`.
+ ```bash
+ curl -b j.txt /api/auth/sessions
+ ```
+ Sign in on a second browser, refresh list — new entry appears with `is_current: false`.
5. Revoke other sessions:
- ```bash
- curl -b j.txt -X DELETE /api/auth/sessions
- ```
- Second browser's `/api/auth/me` now returns 401.
+ ```bash
+ curl -b j.txt -X DELETE /api/auth/sessions
+ ```
+ Second browser's `/api/auth/me` now returns 401.
6. Logout everywhere:
- ```bash
- curl -b j.txt -X POST /api/auth/logout-everywhere
- curl -b j.txt /api/auth/me # → 401
- ```
+ ```bash
+ curl -b j.txt -X POST /api/auth/logout-everywhere
+ curl -b j.txt /api/auth/me # → 401
+ ```
7. Wallet-disconnect UX — open `/dashboard/`, disconnect MetaMask → toast appears; clicking "Sign out" logs out. Not clicking leaves the session intact.
## Scope boundaries — do NOT do these
diff --git a/prompts/wallet-auth/06-link-wallet-to-account.md b/prompts/wallet-auth/06-link-wallet-to-account.md
index e35c27557..d6957c38b 100644
--- a/prompts/wallet-auth/06-link-wallet-to-account.md
+++ b/prompts/wallet-auth/06-link-wallet-to-account.md
@@ -22,6 +22,7 @@ Requires existing session (email or wallet).
Body: `{ message, signature, purpose: "link" }` (same shape as siwe-verify).
Steps:
+
1. `getSessionUser(req)` → user. 401 if missing.
2. Do the full SIWE verification (lift the verify helper from task 03 into `api/_lib/siwe.js` and import here — if the helper wasn't extracted in 03, extract it now but keep the 03 behavior byte-identical).
3. Require `purpose === 'link'` on the nonce; reject `'login'` nonces here.
@@ -39,10 +40,11 @@ Requires existing session. Body: `{}`.
### Settings UI
A simple panel:
-- "Linked wallet: `0xABC…` (Base Mainnet) — *Unlink*"
+
+- "Linked wallet: `0xABC…` (Base Mainnet) — _Unlink_"
- Or: "No wallet linked — [Link your wallet] button"
-- The *Link* button triggers the client-side SIWE dance with `purpose: "link"`.
-- The *Unlink* button hits the unlink endpoint.
+- The _Link_ button triggers the client-side SIWE dance with `purpose: "link"`.
+- The _Unlink_ button hits the unlink endpoint.
Use the dashboard's existing CSS and layout. Do not introduce new global styles.
diff --git a/prompts/wallet-auth/README.md b/prompts/wallet-auth/README.md
index 8ccff2295..05c5b1c2d 100644
--- a/prompts/wallet-auth/README.md
+++ b/prompts/wallet-auth/README.md
@@ -2,7 +2,7 @@
Wallet auth is the base of the entire platform. Until a user can sign in with their wallet, keep that session stable across reloads, and have a single user record link to their wallet(s) deterministically, every downstream feature (selfie agent, avatar edit, onchain passport, CZ demo) is building on sand. These tasks take the existing SIWE scaffold from "works for the happy path" to "works 100%."
-Backing code that already exists: [api/auth/login.js](../../api/auth/login.js), [api/auth/logout.js](../../api/auth/logout.js), [api/auth/me.js](../../api/auth/me.js), [api/auth/register.js](../../api/auth/register.js), [api/auth/siwe/nonce.js](../../api/auth/siwe/nonce.js), [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js), [api/_lib/auth.js](../../api/_lib/auth.js), [api/_lib/schema.sql](../../api/_lib/schema.sql), [src/account.js](../../src/account.js), [src/agent-identity.js](../../src/agent-identity.js), [public/wallet-login.js](../../public/wallet-login.js).
+Backing code that already exists: [api/auth/login.js](../../api/auth/login.js), [api/auth/logout.js](../../api/auth/logout.js), [api/auth/me.js](../../api/auth/me.js), [api/auth/register.js](../../api/auth/register.js), [api/auth/siwe/nonce.js](../../api/auth/siwe/nonce.js), [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js), [api/\_lib/auth.js](../../api/_lib/auth.js), [api/\_lib/schema.sql](../../api/_lib/schema.sql), [src/account.js](../../src/account.js), [src/agent-identity.js](../../src/agent-identity.js), [public/wallet-login.js](../../public/wallet-login.js).
## Recommended execution order
diff --git a/prompts/widget-studio/00-studio-foundation.md b/prompts/widget-studio/00-studio-foundation.md
index 1c8d2c0f6..708fc2e88 100644
--- a/prompts/widget-studio/00-studio-foundation.md
+++ b/prompts/widget-studio/00-studio-foundation.md
@@ -20,17 +20,17 @@ None. This prompt assumes the current codebase state as of commit `ef3b0d4`. Rea
## Read these first (do not skip)
-| File | Why |
-|:---|:---|
-| [src/app.js](../../src/app.js) — lines 36–100, 270–340 | Understand the existing App boot sequence, URL hash parsing, `view()` method signature, and how `protocol`/`identity`/`avatar`/`runtime` are wired. You will add `hash.widget` parsing here. |
-| [src/viewer.js](../../src/viewer.js) — constructor + `load()` + `setCamera()` | The `Viewer` class is what you'll render inside the Studio preview iframe. It already supports `cameraPosition`, background color, HDR environments, animations. |
-| [src/account.js](../../src/account.js) | Existing client for avatar CRUD against `/api/avatars`. Mirror this pattern for widgets. |
-| [api/avatars/index.js](../../api/avatars/index.js) and [api/avatars/presign.js](../../api/avatars/presign.js) | Reference implementation for an authenticated Vercel serverless CRUD endpoint backed by Neon. Follow the same auth + error conventions. |
-| [api/_lib/](../../api/_lib/) | Shared helpers: auth middleware, Neon client, response helpers. Use these — do not create duplicates. |
-| [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js) — lines 1–90 | Dashboard's native-DOM rendering pattern. The Studio UI should follow the same style (no framework, no JSX runtime on the client — use `vhtml` if you want JSX, same as the validator components). |
-| [vercel.json](../../vercel.json) | Route table. You will add `/studio` and `/api/widgets/*` routes here. |
-| [style.css](../../style.css) | Existing dark theme tokens. Reuse the CSS variables and classes; do not introduce a new design system. |
-| [index.html](../../index.html) | The SPA shell. You need to understand how hash params are consumed so `#widget=<id>` can hook in without breaking existing `#model=` behavior. |
+| File | Why |
+| :------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| [src/app.js](../../src/app.js) — lines 36–100, 270–340 | Understand the existing App boot sequence, URL hash parsing, `view()` method signature, and how `protocol`/`identity`/`avatar`/`runtime` are wired. You will add `hash.widget` parsing here. |
+| [src/viewer.js](../../src/viewer.js) — constructor + `load()` + `setCamera()` | The `Viewer` class is what you'll render inside the Studio preview iframe. It already supports `cameraPosition`, background color, HDR environments, animations. |
+| [src/account.js](../../src/account.js) | Existing client for avatar CRUD against `/api/avatars`. Mirror this pattern for widgets. |
+| [api/avatars/index.js](../../api/avatars/index.js) and [api/avatars/presign.js](../../api/avatars/presign.js) | Reference implementation for an authenticated Vercel serverless CRUD endpoint backed by Neon. Follow the same auth + error conventions. |
+| [api/\_lib/](../../api/_lib/) | Shared helpers: auth middleware, Neon client, response helpers. Use these — do not create duplicates. |
+| [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js) — lines 1–90 | Dashboard's native-DOM rendering pattern. The Studio UI should follow the same style (no framework, no JSX runtime on the client — use `vhtml` if you want JSX, same as the validator components). |
+| [vercel.json](../../vercel.json) | Route table. You will add `/studio` and `/api/widgets/*` routes here. |
+| [style.css](../../style.css) | Existing dark theme tokens. Reuse the CSS variables and classes; do not introduce a new design system. |
+| [index.html](../../index.html) | The SPA shell. You need to understand how hash params are consumed so `#widget=<id>` can hook in without breaking existing `#model=` behavior. |
Also run `ls api/_lib` and open every file in there — one of them almost certainly has `requireAuth()` or equivalent. Use it. Do not hand-roll auth.
@@ -64,13 +64,13 @@ create index if not exists widgets_type_idx on widgets(type);
Create the following under `api/widgets/`:
-| File | Method + Path | Auth | Purpose |
-|:---|:---|:---|:---|
-| `api/widgets/index.js` | `GET /api/widgets` | required | List current user's widgets. |
-| `api/widgets/index.js` | `POST /api/widgets` | required | Create a widget. Returns `{ id, ... }`. |
-| `api/widgets/[id].js` | `GET /api/widgets/:id` | **public** | Fetch a widget config by id. If `is_public=false`, require auth + ownership. Increment `view_count`. |
-| `api/widgets/[id].js` | `PATCH /api/widgets/:id` | required + owner | Update config/name/is_public. |
-| `api/widgets/[id].js` | `DELETE /api/widgets/:id` | required + owner | Delete. |
+| File | Method + Path | Auth | Purpose |
+| :--------------------- | :------------------------ | :--------------- | :--------------------------------------------------------------------------------------------------- |
+| `api/widgets/index.js` | `GET /api/widgets` | required | List current user's widgets. |
+| `api/widgets/index.js` | `POST /api/widgets` | required | Create a widget. Returns `{ id, ... }`. |
+| `api/widgets/[id].js` | `GET /api/widgets/:id` | **public** | Fetch a widget config by id. If `is_public=false`, require auth + ownership. Increment `view_count`. |
+| `api/widgets/[id].js` | `PATCH /api/widgets/:id` | required + owner | Update config/name/is_public. |
+| `api/widgets/[id].js` | `DELETE /api/widgets/:id` | required + owner | Delete. |
ID format: `wdgt_` + 12 URL-safe random chars (use `crypto.randomBytes(9).toString('base64url')` and verify the length — 9 bytes → 12 base64url chars).
@@ -98,26 +98,35 @@ Create `src/widget-types.js`. Defines:
```js
export const WIDGET_TYPES = {
- 'turntable': { label: 'Turntable Showcase', status: 'ready', icon: '...', desc: '...' },
- 'animation-gallery': { label: 'Animation Gallery', status: 'pending', icon: '...', desc: '...' },
- 'talking-agent': { label: 'Talking Agent', status: 'pending', icon: '...', desc: '...' },
- 'passport': { label: 'ERC-8004 Passport', status: 'pending', icon: '...', desc: '...' },
- 'hotspot-tour': { label: 'Hotspot Tour', status: 'pending', icon: '...', desc: '...' },
+ turntable: { label: 'Turntable Showcase', status: 'ready', icon: '...', desc: '...' },
+ 'animation-gallery': {
+ label: 'Animation Gallery',
+ status: 'pending',
+ icon: '...',
+ desc: '...',
+ },
+ 'talking-agent': { label: 'Talking Agent', status: 'pending', icon: '...', desc: '...' },
+ passport: { label: 'ERC-8004 Passport', status: 'pending', icon: '...', desc: '...' },
+ 'hotspot-tour': { label: 'Hotspot Tour', status: 'pending', icon: '...', desc: '...' },
};
// Shared brand config present on every widget
export const BRAND_DEFAULTS = {
- background: '#0a0a0a',
- accent: '#00e5a0',
- caption: '',
- showControls: true,
- autoRotate: true,
- envPreset: 'neutral',
- cameraPosition: null, // [x, y, z] or null for auto-frame
+ background: '#0a0a0a',
+ accent: '#00e5a0',
+ caption: '',
+ showControls: true,
+ autoRotate: true,
+ envPreset: 'neutral',
+ cameraPosition: null, // [x, y, z] or null for auto-frame
};
-export function defaultConfig(type) { /* returns { ...BRAND_DEFAULTS, ...typeSpecificDefaults[type] } */ }
-export function validateConfig(type, config) { /* zod parse, throws on invalid */ }
+export function defaultConfig(type) {
+ /* returns { ...BRAND_DEFAULTS, ...typeSpecificDefaults[type] } */
+}
+export function validateConfig(type, config) {
+ /* zod parse, throws on invalid */
+}
```
`status: 'ready'` on type `turntable` only (per run order — the Turntable prompt will flip more to `ready` as they ship).
@@ -154,6 +163,7 @@ Column 1 calls `api.listAvatars()` (reuse `dashboard.js`'s `api`). Thumbnail car
Column 2 is an `<iframe src="/?widget-preview=1#model=<model_url>&kiosk=true&...">` that reloads whenever config changes (debounce 200ms). **Do not build a second viewer.** Reuse the existing one via URL hash params. To apply brand colors, post a message to the iframe (next section).
Column 3 is a form. All changes update in-memory state and trigger the debounced preview reload. Fields:
+
- **Name** (text, required)
- **Background color** (color picker)
- **Accent color** (color picker)
@@ -165,18 +175,20 @@ Column 3 is a form. All changes update in-memory state and trigger the debounced
- **Type-specific fields** — for `turntable`, just rotation speed. For others, show a placeholder "Configured by Widget 0X — coming soon."
Below the form:
+
- **[Save Draft]** button → `createWidget()` or `updateWidget()` if editing.
- **[Generate Embed]** button → saves, then opens a modal with:
- - Live preview
- - Shareable URL: `https://<host>/#widget=<id>`
- - Iframe snippet (600x600 default, editable dimensions)
- - One-line script snippet: `<script async src="https://<host>/embed.js" data-widget="<id>"></script>` (stub script file — create `public/embed.js` that just creates an iframe for now)
- - "Show HTML" disclosure showing the raw snippet
- - Copy-to-clipboard buttons
+ - Live preview
+ - Shareable URL: `https://<host>/#widget=<id>`
+ - Iframe snippet (600x600 default, editable dimensions)
+ - One-line script snippet: `<script async src="https://<host>/embed.js" data-widget="<id>"></script>` (stub script file — create `public/embed.js` that just creates an iframe for now)
+ - "Show HTML" disclosure showing the raw snippet
+ - Copy-to-clipboard buttons
### 6. `postMessage` bridge between Studio and preview iframe
The Studio parent sends live config updates to the preview iframe without a full reload. In `src/app.js`, add a message listener that accepts `{ type: 'widget:config', config }` and applies:
+
- Background color → `viewer.setBackgroundColor(config.background)` (add this method to `Viewer` if missing — it already supports background color via dat.gui, so the logic exists).
- Auto-rotate → `viewer.controls.autoRotate = config.autoRotate`.
- Env preset → `viewer.setEnvironment(preset)` (already exists).
@@ -192,13 +204,13 @@ In `src/app.js`, after parsing the hash:
```js
if (hash.widget) {
- const widget = await getWidget(hash.widget); // public endpoint
- // Apply widget.config to this.options before any viewer work:
- // - model URL comes from widget.avatar.model_url (server-joined or second fetch)
- // - cameraPosition, background, etc. from config
- // Then proceed with normal view() flow.
- // Also expose widget.type so later prompts can branch on it:
- window.VIEWER.widget = widget;
+ const widget = await getWidget(hash.widget); // public endpoint
+ // Apply widget.config to this.options before any viewer work:
+ // - model URL comes from widget.avatar.model_url (server-joined or second fetch)
+ // - cameraPosition, background, etc. from config
+ // Then proceed with normal view() flow.
+ // Also expose widget.type so later prompts can branch on it:
+ window.VIEWER.widget = widget;
}
```
@@ -220,11 +232,12 @@ If the widget id is unknown, show an in-page error: "Widget not found." Do not r
- Do not duplicate auth logic — reuse the helper in `api/_lib/`.
- Do not create a mock mode. If the Neon connection fails locally, document how to run Neon in dev (probably via `DATABASE_URL` env var — check how `api/avatars` does it).
- Do not hardcode the production domain. Use `location.origin` client-side and `req.headers.host` (or Vercel env vars) server-side.
-- Do not ship the widget type cards as unclickable placeholders. "Coming soon" types should be *clickable* and render a Studio form with a banner saying "This widget type isn't functional yet — you can save the config; the runtime will light up when its prompt ships." The config still saves and round-trips.
+- Do not ship the widget type cards as unclickable placeholders. "Coming soon" types should be _clickable_ and render a Studio form with a banner saying "This widget type isn't functional yet — you can save the config; the runtime will light up when its prompt ships." The config still saves and round-trips.
## Deliverables (exact file list)
**New:**
+
- `api/_lib/migrations/002_widgets.sql` (or next available number — verify first)
- `api/widgets/index.js`
- `api/widgets/[id].js`
@@ -236,6 +249,7 @@ If the widget id is unknown, show an in-page error: "Widget not found." Do not r
- `public/embed.js` (stub iframe-injector script)
**Modified:**
+
- `src/app.js` — add `hash.widget` handling + postMessage listener
- `src/viewer.js` — add `setBackgroundColor()` if not already exposed as a public method
- `vercel.json` — add `/studio`, `/api/widgets`, `/api/widgets/*` routes
@@ -265,9 +279,9 @@ You are done when **all** of these are true:
4. Click "Use current view" after orbiting — preview persists that camera.
5. Save draft. Refresh. Verify it re-loads the draft.
6. Generate embed. Copy the URL. Paste in a private window. Verify:
- - Model loads.
- - Background, camera, env are applied.
- - No dat.gui panel if `showControls=false`.
+ - Model loads.
+ - Background, camera, env are applied.
+ - No dat.gui panel if `showControls=false`.
7. Deliberately break: visit `/#widget=wdgt_does_not_exist`. Verify graceful error, not a crash.
8. Open `public/embed.js` snippet in an HTML scratch file. Verify it injects an iframe.
9. `npm run build && npm run dev` — confirm production build works.
diff --git a/prompts/widget-studio/01-turntable-widget.md b/prompts/widget-studio/01-turntable-widget.md
index db4242ff1..3a9216f61 100644
--- a/prompts/widget-studio/01-turntable-widget.md
+++ b/prompts/widget-studio/01-turntable-widget.md
@@ -13,24 +13,24 @@ This is the "look-at-my-cool-model" widget. It must feel polished. If it feels l
## Prerequisites
- Prompt 00 merged. You have:
- - `/studio` route with avatar picker, type picker, live preview, config save/load.
- - `src/widget-types.js` with `turntable` marked `status: 'ready'`.
- - `src/widgets.js` client.
- - `api/widgets/*` endpoints.
- - Public `#widget=<id>` resolution in `src/app.js`.
+ - `/studio` route with avatar picker, type picker, live preview, config save/load.
+ - `src/widget-types.js` with `turntable` marked `status: 'ready'`.
+ - `src/widgets.js` client.
+ - `api/widgets/*` endpoints.
+ - Public `#widget=<id>` resolution in `src/app.js`.
Read the PR that shipped Prompt 00 before starting so you know the exact contract.
## Read these first
-| File | Why |
-|:---|:---|
-| [src/viewer.js](../../src/viewer.js) | Find the existing auto-rotate support (OrbitControls `autoRotate`) and the background color implementation. Find how the camera is framed. Find how env presets are applied. |
-| [src/app.js](../../src/app.js) — `hash.widget` handling from Prompt 00 | You will branch on `widget.type === 'turntable'` in the public flow. |
-| [src/widget-types.js](../../src/widget-types.js) | You will extend the turntable schema here. |
-| [public/studio/studio.js](../../public/studio/studio.js) | You will add the turntable-specific form fields. |
-| [src/ipfs.js](../../src/ipfs.js) | Resolve IPFS/Arweave URIs if the avatar uses them. |
-| The existing `features.html` hero | Match visual polish level. |
+| File | Why |
+| :--------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| [src/viewer.js](../../src/viewer.js) | Find the existing auto-rotate support (OrbitControls `autoRotate`) and the background color implementation. Find how the camera is framed. Find how env presets are applied. |
+| [src/app.js](../../src/app.js) — `hash.widget` handling from Prompt 00 | You will branch on `widget.type === 'turntable'` in the public flow. |
+| [src/widget-types.js](../../src/widget-types.js) | You will extend the turntable schema here. |
+| [public/studio/studio.js](../../public/studio/studio.js) | You will add the turntable-specific form fields. |
+| [src/ipfs.js](../../src/ipfs.js) | Resolve IPFS/Arweave URIs if the avatar uses them. |
+| The existing `features.html` hero | Match visual polish level. |
## Build this
@@ -40,16 +40,16 @@ In `src/widget-types.js`, add turntable-specific fields on top of `BRAND_DEFAULT
```js
const TURNTABLE_DEFAULTS = {
- rotationSpeed: 1.0, // OrbitControls autoRotateSpeed (1.0 = ~30s/rev)
- rotationAxis: 'y', // 'x' | 'y' | 'z'
- clickToPause: true,
- loopDirection: 'cw', // 'cw' | 'ccw'
- posterUrl: null, // optional poster image (shown before load)
- captionPosition: 'bottom', // 'top' | 'bottom' | 'none'
- captionStyle: 'pill', // 'pill' | 'bar' | 'none'
- startFrame: null, // optional [x,y,z] camera start if different from cameraPosition
- fogColor: null, // optional radial fog for vignette feel
- shadow: 'contact', // 'contact' | 'ground' | 'none' — ground contact shadow
+ rotationSpeed: 1.0, // OrbitControls autoRotateSpeed (1.0 = ~30s/rev)
+ rotationAxis: 'y', // 'x' | 'y' | 'z'
+ clickToPause: true,
+ loopDirection: 'cw', // 'cw' | 'ccw'
+ posterUrl: null, // optional poster image (shown before load)
+ captionPosition: 'bottom', // 'top' | 'bottom' | 'none'
+ captionStyle: 'pill', // 'pill' | 'bar' | 'none'
+ startFrame: null, // optional [x,y,z] camera start if different from cameraPosition
+ fogColor: null, // optional radial fog for vignette feel
+ shadow: 'contact', // 'contact' | 'ground' | 'none' — ground contact shadow
};
```
@@ -76,17 +76,17 @@ Create `src/widgets/turntable.js`. This is the module that runs inside the viewe
```js
export function mountTurntable(viewer, config, container) {
- // 1. Apply brand config (already done by Prompt 00's resolver, but verify idempotence).
- // 2. Set OrbitControls.autoRotate = true, autoRotateSpeed = direction * speed.
- // 3. Lock controls based on config.clickToPause:
- // - If true: render invisible click target; pause/resume on click.
- // - If false: disable all user input (viewer.controls.enabled = false).
- // 4. Hide dat.gui, validator bar, drop zone, footer — anything not the canvas.
- // 5. Render caption overlay if config.caption && captionPosition !== 'none'.
- // 6. Apply rotationAxis by swapping OrbitControls target offset (y default is already correct; x/z require tweaking camera up vector + orbit target).
- // 7. If config.shadow !== 'none', add a ContactShadows plane under the model (use three.js ContactShadows or a simple shadow-catching plane).
- // 8. If config.posterUrl, render an <img> overlay that fades out on gltf load.
- // 9. Return { destroy, pause, resume } for cleanup.
+ // 1. Apply brand config (already done by Prompt 00's resolver, but verify idempotence).
+ // 2. Set OrbitControls.autoRotate = true, autoRotateSpeed = direction * speed.
+ // 3. Lock controls based on config.clickToPause:
+ // - If true: render invisible click target; pause/resume on click.
+ // - If false: disable all user input (viewer.controls.enabled = false).
+ // 4. Hide dat.gui, validator bar, drop zone, footer — anything not the canvas.
+ // 5. Render caption overlay if config.caption && captionPosition !== 'none'.
+ // 6. Apply rotationAxis by swapping OrbitControls target offset (y default is already correct; x/z require tweaking camera up vector + orbit target).
+ // 7. If config.shadow !== 'none', add a ContactShadows plane under the model (use three.js ContactShadows or a simple shadow-catching plane).
+ // 8. If config.posterUrl, render an <img> overlay that fades out on gltf load.
+ // 9. Return { destroy, pause, resume } for cleanup.
}
```
@@ -96,11 +96,11 @@ After the widget fetch in `hash.widget` resolution:
```js
if (window.VIEWER.widget?.type === 'turntable') {
- const { mountTurntable } = await import('./widgets/turntable.js');
- // Wait for viewer.load() to complete, then mount:
- this.view(resolvedModel, '', new Map()).then(() => {
- this._widgetRuntime = mountTurntable(this.viewer, window.VIEWER.widget.config, this.el);
- });
+ const { mountTurntable } = await import('./widgets/turntable.js');
+ // Wait for viewer.load() to complete, then mount:
+ this.view(resolvedModel, '', new Map()).then(() => {
+ this._widgetRuntime = mountTurntable(this.viewer, window.VIEWER.widget.config, this.el);
+ });
}
```
@@ -114,11 +114,18 @@ The Studio needs a "Use current frame" button. Implementation:
// In studio.js, when user clicks the button:
const iframe = document.getElementById('preview-iframe');
const canvas = iframe.contentDocument.querySelector('canvas');
-canvas.toBlob(async (blob) => {
- const { url, upload_url } = await api.presign({ kind: 'poster', content_type: 'image/png' });
- await fetch(upload_url, { method: 'PUT', body: blob });
- updateConfig({ posterUrl: url });
-}, 'image/png', 0.92);
+canvas.toBlob(
+ async (blob) => {
+ const { url, upload_url } = await api.presign({
+ kind: 'poster',
+ content_type: 'image/png',
+ });
+ await fetch(upload_url, { method: 'PUT', body: blob });
+ updateConfig({ posterUrl: url });
+ },
+ 'image/png',
+ 0.92,
+);
```
If `/api/avatars/presign` only supports GLBs today, extend it to accept `kind: 'poster' | 'thumbnail' | 'glb'` with separate R2 prefixes.
@@ -154,10 +161,12 @@ When the widget successfully mounts, POST `/api/widgets/:id/ping` once. The endp
## Deliverables
**New:**
+
- `src/widgets/turntable.js` — runtime module.
- CSS additions (either `style.css` or new `src/widgets/widgets.css` imported by the runtime modules).
**Modified:**
+
- `src/widget-types.js` — add turntable schema and defaults.
- `src/app.js` — dispatch to `mountTurntable` when widget type matches.
- `public/studio/studio.js` — turntable-specific form fieldset.
@@ -168,12 +177,12 @@ When the widget successfully mounts, POST `/api/widgets/:id/ping` once. The endp
- [ ] A signed-in user can create a turntable widget in Studio, save it, and share the resulting URL.
- [ ] The public widget URL, loaded cold in an incognito window:
- - [ ] Shows no dat.gui, no validator bar, no drop UI, no footer.
- - [ ] Auto-rotates at the configured speed in the configured direction.
- - [ ] Respects background color, accent color, caption, caption position/style.
- - [ ] Starts at the saved camera position.
- - [ ] Pauses on tap/click when `clickToPause: true`; resumes on second tap.
- - [ ] Is fully responsive — works at 300x300 and 1920x1080.
+ - [ ] Shows no dat.gui, no validator bar, no drop UI, no footer.
+ - [ ] Auto-rotates at the configured speed in the configured direction.
+ - [ ] Respects background color, accent color, caption, caption position/style.
+ - [ ] Starts at the saved camera position.
+ - [ ] Pauses on tap/click when `clickToPause: true`; resumes on second tap.
+ - [ ] Is fully responsive — works at 300x300 and 1920x1080.
- [ ] On a device with `prefers-reduced-motion: reduce`, auto-rotate is disabled.
- [ ] Off-screen widgets pause via IntersectionObserver.
- [ ] Poster image (if set) appears before the GLB loads and fades out smoothly.
diff --git a/prompts/widget-studio/02-animation-gallery-widget.md b/prompts/widget-studio/02-animation-gallery-widget.md
index a7e576006..8a0530634 100644
--- a/prompts/widget-studio/02-animation-gallery-widget.md
+++ b/prompts/widget-studio/02-animation-gallery-widget.md
@@ -8,7 +8,7 @@
Ship the Animation Gallery widget: an embedded 3D experience that turns a rigged avatar's animation clips into labeled buttons the end user can click. "Idle / Wave / Dance / Run" becomes a visible, interactive demo instead of a hidden feature buried in dat.gui.
-This is the widget that makes Mixamo-style rigs feel like *a product*. A rigged avatar with seven animations should ship as an interactive showcase in one click from Studio.
+This is the widget that makes Mixamo-style rigs feel like _a product_. A rigged avatar with seven animations should ship as an interactive showcase in one click from Studio.
## Prerequisites
@@ -17,13 +17,13 @@ This is the widget that makes Mixamo-style rigs feel like *a product*. A rigged
## Read these first
-| File | Why |
-|:---|:---|
+| File | Why |
+| :-------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------- |
| [src/viewer.js](../../src/viewer.js) — animation-related methods (`setAnimationDefs`, `playClip`, `stopClip`, `updateAnimations`) | The viewer already loads external animation GLBs via a manifest and can play them. Use this API; do not reinvent animation mixing. |
-| [src/app.js:363–410](../../src/app.js#L363-L410) | `_configureAnimations()` — the existing animation manifest loading flow. Your widget must coexist with it. |
-| [src/components/animation-panel.jsx](../../src/components/animation-panel.jsx) | Existing dat.gui animation UI. You're replacing this visually for the widget, but the logic is a reference. |
-| [public/animations/manifest.json](../../public/animations/manifest.json) (if present) | See the default animation set. |
-| Prompt 01 (`01-turntable-widget.md`) | Copy its runtime module pattern exactly — do not diverge. |
+| [src/app.js:363–410](../../src/app.js#L363-L410) | `_configureAnimations()` — the existing animation manifest loading flow. Your widget must coexist with it. |
+| [src/components/animation-panel.jsx](../../src/components/animation-panel.jsx) | Existing dat.gui animation UI. You're replacing this visually for the widget, but the logic is a reference. |
+| [public/animations/manifest.json](../../public/animations/manifest.json) (if present) | See the default animation set. |
+| Prompt 01 (`01-turntable-widget.md`) | Copy its runtime module pattern exactly — do not diverge. |
## Build this
@@ -33,15 +33,15 @@ Extend `src/widget-types.js`:
```js
const ANIMATION_GALLERY_DEFAULTS = {
- clips: [], // optional allowlist of clip names to expose; [] = all
- startClip: 'idle', // which clip plays on load (or '__none' for static)
- loopStart: true, // auto-loop start clip
- buttonStyle: 'pill', // 'pill' | 'tab' | 'grid'
- buttonPosition: 'bottom', // 'bottom' | 'top' | 'left' | 'right'
- showPlayingIndicator: true,
- allowCrossfade: true, // smooth transitions between clips
- crossfadeDurationMs: 250,
- labels: {}, // { clipName: "Custom Label" } overrides
+ clips: [], // optional allowlist of clip names to expose; [] = all
+ startClip: 'idle', // which clip plays on load (or '__none' for static)
+ loopStart: true, // auto-loop start clip
+ buttonStyle: 'pill', // 'pill' | 'tab' | 'grid'
+ buttonPosition: 'bottom', // 'bottom' | 'top' | 'left' | 'right'
+ showPlayingIndicator: true,
+ allowCrossfade: true, // smooth transitions between clips
+ crossfadeDurationMs: 250,
+ labels: {}, // { clipName: "Custom Label" } overrides
};
```
@@ -68,18 +68,18 @@ Create `src/widgets/animation-gallery.js`:
```js
export function mountAnimationGallery(viewer, config, container) {
- // 1. Hide all non-canvas UI (same as turntable).
- // 2. Read viewer.clips (built-in animations) and viewer.externalClips (from manifest).
- // Filter to config.clips if non-empty.
- // 3. Render a button bar positioned per config.buttonPosition.
- // Each button shows config.labels[name] || titleCase(name).
- // 4. Highlight the active button. If showPlayingIndicator, show a small progress bar
- // below it tracking the clip's normalized time (use mixer actions).
- // 5. On click: crossfade from current action to selected clip's action over
- // config.crossfadeDurationMs (use THREE.AnimationAction.crossFadeTo).
- // 6. If config.startClip !== '__none', play it on mount with loop.
- // 7. Handle keyboard: left/right arrows cycle clips (a11y).
- // 8. Return { destroy, play, stop }.
+ // 1. Hide all non-canvas UI (same as turntable).
+ // 2. Read viewer.clips (built-in animations) and viewer.externalClips (from manifest).
+ // Filter to config.clips if non-empty.
+ // 3. Render a button bar positioned per config.buttonPosition.
+ // Each button shows config.labels[name] || titleCase(name).
+ // 4. Highlight the active button. If showPlayingIndicator, show a small progress bar
+ // below it tracking the clip's normalized time (use mixer actions).
+ // 5. On click: crossfade from current action to selected clip's action over
+ // config.crossfadeDurationMs (use THREE.AnimationAction.crossFadeTo).
+ // 6. If config.startClip !== '__none', play it on mount with loop.
+ // 7. Handle keyboard: left/right arrows cycle clips (a11y).
+ // 8. Return { destroy, play, stop }.
}
```
@@ -89,13 +89,17 @@ Mirror the turntable dispatcher from Prompt 01:
```js
if (window.VIEWER.widget?.type === 'animation-gallery') {
- const { mountAnimationGallery } = await import('./widgets/animation-gallery.js');
- this.view(resolvedModel, '', new Map()).then(() => {
- // Wait for external animations manifest to resolve too:
- this.viewer.whenAnimationsReady().then(() => {
- this._widgetRuntime = mountAnimationGallery(this.viewer, window.VIEWER.widget.config, this.el);
- });
- });
+ const { mountAnimationGallery } = await import('./widgets/animation-gallery.js');
+ this.view(resolvedModel, '', new Map()).then(() => {
+ // Wait for external animations manifest to resolve too:
+ this.viewer.whenAnimationsReady().then(() => {
+ this._widgetRuntime = mountAnimationGallery(
+ this.viewer,
+ window.VIEWER.widget.config,
+ this.el,
+ );
+ });
+ });
}
```
@@ -134,10 +138,12 @@ Add a `whenAnimationsReady()` promise to `Viewer` if it doesn't exist — the `_
## Deliverables
**New:**
+
- `src/widgets/animation-gallery.js`
- CSS for pill/tab/grid button styles (extend turntable's widget CSS).
**Modified:**
+
- `src/widget-types.js` — mark `animation-gallery` as `ready`, add schema.
- `src/app.js` — dispatcher.
- `src/viewer.js` — `whenAnimationsReady()` promise accessor.
diff --git a/prompts/widget-studio/03-talking-agent-widget.md b/prompts/widget-studio/03-talking-agent-widget.md
index d270b81ad..36fa5ee31 100644
--- a/prompts/widget-studio/03-talking-agent-widget.md
+++ b/prompts/widget-studio/03-talking-agent-widget.md
@@ -17,18 +17,18 @@ This widget re-enables `NichAgent` (currently disabled in the widget-less viewer
## Read these first (do not skip)
-| File | Why |
-|:---|:---|
-| [src/agent-protocol.js](../../src/agent-protocol.js) | The action bus. You emit `SPEAK`, `GESTURE`, `PERFORM_SKILL`, `PRESENCE` to drive the avatar. |
-| [src/nich-agent.js](../../src/nich-agent.js) | The chat UI + speech recognition + skill router. Today it mounts unconditionally; you'll gate it to widget mode and style it to brand. |
-| [src/agent-avatar.js](../../src/agent-avatar.js) | The Empathy Layer — reacts to protocol events, drives morph targets, plays gesture clips. |
-| [src/agent-skills.js](../../src/agent-skills.js) | Built-in skill registry (greet, wave, etc.). Your widget exposes a curated subset. |
-| [src/agent-identity.js](../../src/agent-identity.js) | Agent identity + memory wiring. |
+| File | Why |
+| :-------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| [src/agent-protocol.js](../../src/agent-protocol.js) | The action bus. You emit `SPEAK`, `GESTURE`, `PERFORM_SKILL`, `PRESENCE` to drive the avatar. |
+| [src/nich-agent.js](../../src/nich-agent.js) | The chat UI + speech recognition + skill router. Today it mounts unconditionally; you'll gate it to widget mode and style it to brand. |
+| [src/agent-avatar.js](../../src/agent-avatar.js) | The Empathy Layer — reacts to protocol events, drives morph targets, plays gesture clips. |
+| [src/agent-skills.js](../../src/agent-skills.js) | Built-in skill registry (greet, wave, etc.). Your widget exposes a curated subset. |
+| [src/agent-identity.js](../../src/agent-identity.js) | Agent identity + memory wiring. |
| [src/runtime/index.js](../../src/runtime/index.js) and [src/runtime/scene.js](../../src/runtime/scene.js) | The Runtime (LLM brain + scene controller). Supports provider `'none'` (NichAgent pattern-matching), `'anthropic'` (Claude via proxy), and MCP transport. |
-| [api/mcp.js](../../api/mcp.js) | The MCP server. The widget can call tools here as an authenticated agent. |
-| [api/agent-actions.js](../../api/agent-actions.js) | How actions get logged/persisted. |
-| [src/app.js:103–192](../../src/app.js#L103-L192) | `_initAgentSystem()` — the bootstrap sequence. You will mirror parts of this in the widget path. |
-| Prompt 00's `src/app.js` widget-dispatch block | The integration point. |
+| [api/mcp.js](../../api/mcp.js) | The MCP server. The widget can call tools here as an authenticated agent. |
+| [api/agent-actions.js](../../api/agent-actions.js) | How actions get logged/persisted. |
+| [src/app.js:103–192](../../src/app.js#L103-L192) | `_initAgentSystem()` — the bootstrap sequence. You will mirror parts of this in the widget path. |
+| Prompt 00's `src/app.js` widget-dispatch block | The integration point. |
## Build this
@@ -38,33 +38,33 @@ Extend `src/widget-types.js`:
```js
const TALKING_AGENT_DEFAULTS = {
- // Identity shown to the visitor
- agentName: '', // defaults to avatar name
- agentTitle: 'AI Agent', // e.g. "Support Bot", "Portfolio Guide"
- avatar: 'embedded', // 'embedded' = avatar in canvas; 'chat-only' = hide canvas
- // Brain
- brainProvider: 'anthropic', // 'anthropic' | 'none' | 'custom'
- proxyURL: '', // MCP or proxy endpoint
- systemPrompt: '', // user-authored
- greeting: 'Hi! Ask me anything.',
- temperature: 0.7,
- maxTurns: 20, // safety limit
- // Capabilities (toggleable skill allowlist)
- skills: {
- speak: true,
- wave: true,
- lookAt: true,
- playClip: true,
- remember: false, // off by default — memory is sensitive
- },
- // UI
- showChatHistory: true,
- voiceInput: true, // enable mic button
- voiceOutput: true, // text-to-speech responses
- chatPosition: 'right', // 'right' | 'bottom' | 'overlay'
- poweredByBadge: true, // tasteful "powered by 3D Agent" badge
- // Rate limits (visitor side)
- visitorRateLimit: { msgsPerMinute: 8, msgsPerSession: 50 },
+ // Identity shown to the visitor
+ agentName: '', // defaults to avatar name
+ agentTitle: 'AI Agent', // e.g. "Support Bot", "Portfolio Guide"
+ avatar: 'embedded', // 'embedded' = avatar in canvas; 'chat-only' = hide canvas
+ // Brain
+ brainProvider: 'anthropic', // 'anthropic' | 'none' | 'custom'
+ proxyURL: '', // MCP or proxy endpoint
+ systemPrompt: '', // user-authored
+ greeting: 'Hi! Ask me anything.',
+ temperature: 0.7,
+ maxTurns: 20, // safety limit
+ // Capabilities (toggleable skill allowlist)
+ skills: {
+ speak: true,
+ wave: true,
+ lookAt: true,
+ playClip: true,
+ remember: false, // off by default — memory is sensitive
+ },
+ // UI
+ showChatHistory: true,
+ voiceInput: true, // enable mic button
+ voiceOutput: true, // text-to-speech responses
+ chatPosition: 'right', // 'right' | 'bottom' | 'overlay'
+ poweredByBadge: true, // tasteful "powered by 3D Agent" badge
+ // Rate limits (visitor side)
+ visitorRateLimit: { msgsPerMinute: 8, msgsPerSession: 50 },
};
```
@@ -90,12 +90,13 @@ When `state.type === 'talking-agent'`:
Do not ship visitor-exposed API keys. The widget owner authors a config; the brain call goes through your MCP server.
Pattern:
+
- Public widget loads `/#widget=<id>` with no auth.
- Widget runtime POSTs visitor messages to `/api/widgets/:id/chat` on the same origin.
- That endpoint looks up the widget, checks visitor rate limits (Upstash — already a dep), and relays to:
- - If `brainProvider=anthropic` → the project's MCP server (`api/mcp.js`) or the Anthropic proxy the runtime already supports.
- - If `brainProvider=custom` → the user-supplied `proxyURL` (must be HTTPS; validate).
- - If `brainProvider=none` → return a pattern-matched reply from NichAgent's built-in matcher.
+ - If `brainProvider=anthropic` → the project's MCP server (`api/mcp.js`) or the Anthropic proxy the runtime already supports.
+ - If `brainProvider=custom` → the user-supplied `proxyURL` (must be HTTPS; validate).
+ - If `brainProvider=none` → return a pattern-matched reply from NichAgent's built-in matcher.
- The endpoint streams SSE back to the widget runtime.
Create `api/widgets/[id]/chat.js`. Reuse the existing MCP auth/token flow — do not hand-roll a new LLM adapter. The Runtime class already does this; call it.
@@ -108,21 +109,21 @@ Create `src/widgets/talking-agent.js`:
```js
export async function mountTalkingAgent(viewer, config, container, widgetId) {
- // 1. Hide drop UI, validator, footer (same as other widgets).
- // 2. Boot a scoped agent system:
- // - Create an AgentIdentity (ephemeral for widget mode: id=`widget:${widgetId}`, name=config.agentName)
- // - Attach AgentAvatar to the viewer
- // - Create AgentSkills filtered by config.skills allowlist
- // - Create a Runtime with brain = { provider: 'proxy', proxyURL: `/api/widgets/${widgetId}/chat` }
- // The Runtime's existing proxy mode should just POST to that URL and consume SSE.
- // - Boot NichAgent mounted inside the widget container (not document.body) so its styles scope.
- // 3. Apply brand colors to NichAgent (accent, background). Either extend NichAgent with a `theme` option or override via CSS custom properties scoped to .widget-talking-agent.
- // 4. Render the greeting as the agent's first SPEAK action.
- // 5. On chat send:
- // - Check client-side session rate limit (instant feedback).
- // - POST to /api/widgets/:id/chat, stream the response through the Runtime.
- // - Runtime emits SPEAK + any skill actions; AgentAvatar reacts; NichAgent renders.
- // 6. Return { destroy }. Destroy tears down the avatar, closes the SSE stream, etc.
+ // 1. Hide drop UI, validator, footer (same as other widgets).
+ // 2. Boot a scoped agent system:
+ // - Create an AgentIdentity (ephemeral for widget mode: id=`widget:${widgetId}`, name=config.agentName)
+ // - Attach AgentAvatar to the viewer
+ // - Create AgentSkills filtered by config.skills allowlist
+ // - Create a Runtime with brain = { provider: 'proxy', proxyURL: `/api/widgets/${widgetId}/chat` }
+ // The Runtime's existing proxy mode should just POST to that URL and consume SSE.
+ // - Boot NichAgent mounted inside the widget container (not document.body) so its styles scope.
+ // 3. Apply brand colors to NichAgent (accent, background). Either extend NichAgent with a `theme` option or override via CSS custom properties scoped to .widget-talking-agent.
+ // 4. Render the greeting as the agent's first SPEAK action.
+ // 5. On chat send:
+ // - Check client-side session rate limit (instant feedback).
+ // - POST to /api/widgets/:id/chat, stream the response through the Runtime.
+ // - Runtime emits SPEAK + any skill actions; AgentAvatar reacts; NichAgent renders.
+ // 6. Return { destroy }. Destroy tears down the avatar, closes the SSE stream, etc.
}
```
@@ -132,13 +133,13 @@ Right now `NichAgent` mounts to `document.body` with fixed positioning. Add a se
```js
new NichAgent(containerEl, protocol, skills, identity, runtime, {
- layout: 'embedded', // new option
- position: 'right' | 'bottom' | 'overlay',
- greeting: '...',
- theme: { accent, background, caption },
- showPoweredBy: true,
- voiceInput: true,
- voiceOutput: true,
+ layout: 'embedded', // new option
+ position: 'right' | 'bottom' | 'overlay',
+ greeting: '...',
+ theme: { accent, background, caption },
+ showPoweredBy: true,
+ voiceInput: true,
+ voiceOutput: true,
});
```
@@ -155,8 +156,8 @@ Internal changes minimized: if the code currently selects `document.body` direct
### 7. "Talking" feel
- When a SPEAK action fires:
- - Open/close mouth via the avatar's viseme/morph targets (AgentAvatar should already do basic lipsync — verify; if not, add a minimal open-close cycle synced to TTS `speechStart`/`speechEnd`).
- - Run a subtle head-nod on long phrases via OrbitControls target manipulation or a tiny per-frame rotation added to the head bone.
+ - Open/close mouth via the avatar's viseme/morph targets (AgentAvatar should already do basic lipsync — verify; if not, add a minimal open-close cycle synced to TTS `speechStart`/`speechEnd`).
+ - Run a subtle head-nod on long phrases via OrbitControls target manipulation or a tiny per-frame rotation added to the head bone.
- When idle, the avatar does an "idle" breathing loop (small sinusoidal torso/head rotation). Already handled if the model has an idle clip — make sure it auto-starts.
- When the user starts typing, emit a PRESENCE 'listening' action → avatar tilts head or blinks faster. (Use existing skills if available.)
@@ -184,11 +185,13 @@ Log chat events (count, not content) to `api/agent-memory.js` or a new `api/widg
## Deliverables
**New:**
+
- `src/widgets/talking-agent.js`
- `api/widgets/[id]/chat.js` — proxy + rate limit + SSE streaming.
- `api/widgets/[id]/og.js`, `api/widgets/[id]/oembed.js` — OG/oEmbed metadata.
**Modified:**
+
- `src/widget-types.js` — mark `talking-agent` as `ready`, add schema.
- `src/app.js` — dispatcher.
- `src/nich-agent.js` — add `layout/position/theme/greeting/showPoweredBy/voiceInput/voiceOutput` options; scope DOM insertion.
@@ -201,12 +204,12 @@ Log chat events (count, not content) to `api/agent-memory.js` or a new `api/widg
- [ ] Studio preview shows an authenticated test chat that works live.
- [ ] Public widget URL:
- - [ ] Loads without auth.
- - [ ] Shows greeting as first agent message.
- - [ ] Visitor sends a message → avatar responds → lipsync + audio + text appear.
- - [ ] Voice input works (when permission granted).
- - [ ] Skills disabled in config are not callable (verify via a crafted prompt trying to elicit them).
- - [ ] Visitor hitting `msgsPerMinute` gets a polite rate-limit message, not a 500.
+ - [ ] Loads without auth.
+ - [ ] Shows greeting as first agent message.
+ - [ ] Visitor sends a message → avatar responds → lipsync + audio + text appear.
+ - [ ] Voice input works (when permission granted).
+ - [ ] Skills disabled in config are not callable (verify via a crafted prompt trying to elicit them).
+ - [ ] Visitor hitting `msgsPerMinute` gets a polite rate-limit message, not a 500.
- [ ] `prefers-reduced-motion: reduce` disables idle breathing and gesture animations.
- [ ] No API keys leak to the client (inspect network and bundle).
- [ ] OG tags resolve — paste the URL into Slack/Discord, confirm card shows.
diff --git a/prompts/widget-studio/04-erc8004-passport-widget.md b/prompts/widget-studio/04-erc8004-passport-widget.md
index bd0a6a411..bdd832424 100644
--- a/prompts/widget-studio/04-erc8004-passport-widget.md
+++ b/prompts/widget-studio/04-erc8004-passport-widget.md
@@ -6,7 +6,7 @@
## Goal
-Ship the ERC-8004 Passport widget: a public, embeddable 3D avatar *plus* its verifiable on-chain identity. Visitors see the avatar, its registered wallet, the chain it's registered on, its reputation score, and a link to the registration JSON. This is the widget that makes "agent-as-infrastructure" visible — a provable digital identity in an iframe.
+Ship the ERC-8004 Passport widget: a public, embeddable 3D avatar _plus_ its verifiable on-chain identity. Visitors see the avatar, its registered wallet, the chain it's registered on, its reputation score, and a link to the registration JSON. This is the widget that makes "agent-as-infrastructure" visible — a provable digital identity in an iframe.
This widget is what turns an ERC-8004-registered agent into a badge you can put in a GitHub README, a personal site, or an X bio.
@@ -17,16 +17,16 @@ This widget is what turns an ERC-8004-registered agent into a badge you can put
## Read these first
-| File | Why |
-|:---|:---|
-| [src/erc8004/index.js](../../src/erc8004/index.js) — all exports | Understand what's available: identity registry, reputation, validation recorder. |
-| [src/erc8004/abi.js](../../src/erc8004/abi.js) | Contract ABIs + deployment addresses. Confirm which chains are live. |
-| [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js) | `buildRegistrationJSON` and `registerAgent` — understand what's on-chain for a given token id. |
-| [src/erc8004/reputation.js](../../src/erc8004/reputation.js) | `getReputation`, `getFeedbackRange` — you'll render these. |
-| [src/erc8004/validation-recorder.js](../../src/erc8004/validation-recorder.js) | `getLatestValidation` — optional "last validated" proof. |
-| [src/erc8004/register-ui.js](../../src/erc8004/register-ui.js) | Reference for how the project currently renders identity info. |
-| [features.html](../../features.html) | Visual style for ERC-8004 presentation. Match this feel. |
-| Prompt 01 | Copy the turntable's base visual polish — this widget extends it. |
+| File | Why |
+| :----------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------- |
+| [src/erc8004/index.js](../../src/erc8004/index.js) — all exports | Understand what's available: identity registry, reputation, validation recorder. |
+| [src/erc8004/abi.js](../../src/erc8004/abi.js) | Contract ABIs + deployment addresses. Confirm which chains are live. |
+| [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js) | `buildRegistrationJSON` and `registerAgent` — understand what's on-chain for a given token id. |
+| [src/erc8004/reputation.js](../../src/erc8004/reputation.js) | `getReputation`, `getFeedbackRange` — you'll render these. |
+| [src/erc8004/validation-recorder.js](../../src/erc8004/validation-recorder.js) | `getLatestValidation` — optional "last validated" proof. |
+| [src/erc8004/register-ui.js](../../src/erc8004/register-ui.js) | Reference for how the project currently renders identity info. |
+| [features.html](../../features.html) | Visual style for ERC-8004 presentation. Match this feel. |
+| Prompt 01 | Copy the turntable's base visual polish — this widget extends it. |
## Build this
@@ -36,23 +36,23 @@ Extend `src/widget-types.js`:
```js
const PASSPORT_DEFAULTS = {
- chain: 'base', // 'base' | 'base-sepolia' | 'ethereum' | 'optimism' (whatever REGISTRY_DEPLOYMENTS supports)
- agentId: null, // on-chain token id (bigint as string)
- wallet: null, // cached address; widget also refetches from chain
- // What to show
- showReputation: true,
- showRecentFeedback: true, // last 5 feedback entries
- showValidation: false, // last validation recorder entry
- showRegistrationJSON: true, // "view passport JSON" link
- // Visual layout
- layout: 'portrait', // 'portrait' (avatar top, passport below) | 'landscape' (avatar left, passport right) | 'badge' (tiny inline card)
- badgeSize: 'medium', // 'small' (80px) | 'medium' (120px) | 'large' (200px) — badge layout only
- // Autorotate (inherits from turntable)
- autoRotate: true,
- rotationSpeed: 0.6,
- // Chain reader
- rpcURL: '', // optional owner-supplied RPC; fallback to a public one
- refreshIntervalSec: 60, // how often to re-poll reputation (0 = never after initial load)
+ chain: 'base', // 'base' | 'base-sepolia' | 'ethereum' | 'optimism' (whatever REGISTRY_DEPLOYMENTS supports)
+ agentId: null, // on-chain token id (bigint as string)
+ wallet: null, // cached address; widget also refetches from chain
+ // What to show
+ showReputation: true,
+ showRecentFeedback: true, // last 5 feedback entries
+ showValidation: false, // last validation recorder entry
+ showRegistrationJSON: true, // "view passport JSON" link
+ // Visual layout
+ layout: 'portrait', // 'portrait' (avatar top, passport below) | 'landscape' (avatar left, passport right) | 'badge' (tiny inline card)
+ badgeSize: 'medium', // 'small' (80px) | 'medium' (120px) | 'large' (200px) — badge layout only
+ // Autorotate (inherits from turntable)
+ autoRotate: true,
+ rotationSpeed: 0.6,
+ // Chain reader
+ rpcURL: '', // optional owner-supplied RPC; fallback to a public one
+ refreshIntervalSec: 60, // how often to re-poll reputation (0 = never after initial load)
};
```
@@ -75,20 +75,20 @@ Create `src/widgets/passport.js`:
```js
export async function mountPassport(viewer, config, container, widgetId) {
- // 1. Hide everything except the canvas and passport panel.
- // 2. Read chain data in parallel:
- // - ERC-721 ownerOf(tokenId) → wallet
- // - ERC-721 tokenURI(tokenId) → registration JSON URL (probably IPFS — resolve via src/ipfs.js)
- // - ReputationRegistry.getReputation(agentId)
- // - ReputationRegistry.getFeedbackRange(agentId, 0, 5) if showRecentFeedback
- // - ValidationRecorder.getLatestValidation(agentId) if showValidation
- // 3. Apply turntable-style auto-rotate.
- // 4. Render the passport panel alongside the canvas per config.layout.
- // - portrait: stacked, canvas on top (~60% height), panel below (~40%).
- // - landscape: side-by-side.
- // - badge: small circular avatar + compact card next to it.
- // 5. Poll on config.refreshIntervalSec; skip if document.hidden.
- // 6. Return { destroy }.
+ // 1. Hide everything except the canvas and passport panel.
+ // 2. Read chain data in parallel:
+ // - ERC-721 ownerOf(tokenId) → wallet
+ // - ERC-721 tokenURI(tokenId) → registration JSON URL (probably IPFS — resolve via src/ipfs.js)
+ // - ReputationRegistry.getReputation(agentId)
+ // - ReputationRegistry.getFeedbackRange(agentId, 0, 5) if showRecentFeedback
+ // - ValidationRecorder.getLatestValidation(agentId) if showValidation
+ // 3. Apply turntable-style auto-rotate.
+ // 4. Render the passport panel alongside the canvas per config.layout.
+ // - portrait: stacked, canvas on top (~60% height), panel below (~40%).
+ // - landscape: side-by-side.
+ // - badge: small circular avatar + compact card next to it.
+ // 5. Poll on config.refreshIntervalSec; skip if document.hidden.
+ // 6. Return { destroy }.
}
```
@@ -129,7 +129,7 @@ Visible information:
The badge layout is meant for embedding inline in a website header or sidebar — it's small and tasteful.
```html
-<iframe src="/#widget=<id>" width="200" height="80">
+<iframe src="/#widget=<id>" width="200" height="80"></iframe>
```
Must render cleanly at small sizes. Use CSS `container-type: inline-size` and `@container` queries to adapt layout.
@@ -160,15 +160,18 @@ The widget does NOT need to let visitors submit feedback or trigger on-chain wri
## Deliverables
**New:**
+
- `src/widgets/passport.js`
- Passport panel CSS.
**Modified:**
+
- `src/widget-types.js` — mark `passport` as `ready`, add schema.
- `src/app.js` — dispatcher.
- `public/studio/studio.js` — passport fieldset + wallet→tokenId lookup helper.
**Possibly modified:**
+
- `src/erc8004/reputation.js` / `agent-registry.js` — only if the existing API doesn't expose what you need efficiently. Favor additive, backward-compatible changes.
## Acceptance criteria
diff --git a/prompts/widget-studio/05-hotspot-tour-widget.md b/prompts/widget-studio/05-hotspot-tour-widget.md
index 46ee3ebb8..e691e6835 100644
--- a/prompts/widget-studio/05-hotspot-tour-widget.md
+++ b/prompts/widget-studio/05-hotspot-tour-widget.md
@@ -17,13 +17,13 @@ This is the "product explainer" widget — perfect for describing a rigged chara
## Read these first
-| File | Why |
-|:---|:---|
-| [src/annotations.js](../../src/annotations.js) | Existing auto-annotation system. Your widget reuses the projection math (world-space point → screen-space overlay). |
-| [src/viewer.js](../../src/viewer.js) — `buildAnnotations`, `updateAnnotations`, `projectAnnotations` references | Understand how annotations attach to world positions and track the camera. |
-| [src/viewer.js](../../src/viewer.js) — raycasting (look for `THREE.Raycaster`) | You need to cast rays from click points to find world-space mesh intersections. |
-| Prompt 00 — Studio preview iframe + postMessage bridge | You'll extend the bridge to carry click events from the preview to the Studio authoring UI. |
-| Prompt 01 | Copy the base widget runtime pattern. |
+| File | Why |
+| :-------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------ |
+| [src/annotations.js](../../src/annotations.js) | Existing auto-annotation system. Your widget reuses the projection math (world-space point → screen-space overlay). |
+| [src/viewer.js](../../src/viewer.js) — `buildAnnotations`, `updateAnnotations`, `projectAnnotations` references | Understand how annotations attach to world positions and track the camera. |
+| [src/viewer.js](../../src/viewer.js) — raycasting (look for `THREE.Raycaster`) | You need to cast rays from click points to find world-space mesh intersections. |
+| Prompt 00 — Studio preview iframe + postMessage bridge | You'll extend the bridge to carry click events from the preview to the Studio authoring UI. |
+| Prompt 01 | Copy the base widget runtime pattern. |
## Build this
@@ -63,10 +63,10 @@ Layout when `state.type === 'hotspot-tour'`:
- **Preview becomes authoring mode.** A "Place hotspot" button toggles. When active, clicking the preview model drops a hotspot at the clicked surface point.
- **Hotspot list sidebar:** shows all hotspots. Click one to:
- - Edit title, body.
- - "Recenter camera" — snapshots the current preview camera as this hotspot's `cameraFrame`.
- - Delete.
- - Reorder (drag handles).
+ - Edit title, body.
+ - "Recenter camera" — snapshots the current preview camera as this hotspot's `cameraFrame`.
+ - Delete.
+ - Reorder (drag handles).
- **Tour options:** free vs. guided, auto-advance, show controls, etc.
**The click-to-place flow requires cross-frame cooperation.** The Studio (parent) listens for a `widget:hotspot:place` message. The preview (child) runs in "author mode" when it receives `widget:author:enable { mode: 'place' }`. The preview enables a raycaster on canvas clicks, emits `{ point, normal, hitMeshName }` back up. Studio appends to `config.hotspots` and triggers a save draft.
@@ -77,20 +77,20 @@ Create `src/widgets/hotspot-tour.js`:
```js
export function mountHotspotTour(viewer, config, container) {
- // 1. Hide non-canvas UI.
- // 2. For each hotspot, create a DOM element (dot + number).
- // Project its world position to screen space each frame (mirror src/annotations.js).
- // 3. On hotspot click/tap:
- // - Show a popover near the dot with title + body.
- // - If hotspot.cameraFrame, animate viewer camera + target to that frame with an ease.
- // - In guided tour mode, show prev/next buttons in the popover.
- // 4. If autoOpenFirst, trigger hotspot 0 on mount.
- // 5. In tourAutoAdvance mode, advance every N seconds; pause on user interaction.
- // 6. Handle occlusion: if a hotspot's world position is behind geometry from the camera's view,
- // dim the dot to 40% opacity. Use a raycaster from camera to hotspot.position; if hit distance
- // < distance to hotspot, it's occluded.
- // 7. Keyboard: arrow keys cycle hotspots in guided mode.
- // 8. Return { destroy, goto(index) }.
+ // 1. Hide non-canvas UI.
+ // 2. For each hotspot, create a DOM element (dot + number).
+ // Project its world position to screen space each frame (mirror src/annotations.js).
+ // 3. On hotspot click/tap:
+ // - Show a popover near the dot with title + body.
+ // - If hotspot.cameraFrame, animate viewer camera + target to that frame with an ease.
+ // - In guided tour mode, show prev/next buttons in the popover.
+ // 4. If autoOpenFirst, trigger hotspot 0 on mount.
+ // 5. In tourAutoAdvance mode, advance every N seconds; pause on user interaction.
+ // 6. Handle occlusion: if a hotspot's world position is behind geometry from the camera's view,
+ // dim the dot to 40% opacity. Use a raycaster from camera to hotspot.position; if hit distance
+ // < distance to hotspot, it's occluded.
+ // 7. Keyboard: arrow keys cycle hotspots in guided mode.
+ // 8. Return { destroy, goto(index) }.
}
```
@@ -100,8 +100,8 @@ Use a smooth spring or `TWEEN.js`-style ease (do not pull in TWEEN — hand-roll
```js
function easeCameraTo(camera, controls, target, position, durationMs = 700) {
- // lerp controls.target toward target, camera.position toward position, over durationMs.
- // Use easeInOutCubic.
+ // lerp controls.target toward target, camera.position toward position, over durationMs.
+ // Use easeInOutCubic.
}
```
@@ -145,10 +145,12 @@ Respect `prefers-reduced-motion` (disable pulse).
## Deliverables
**New:**
+
- `src/widgets/hotspot-tour.js`
- Hotspot-related CSS (dots, popover, tour controls).
**Modified:**
+
- `src/widget-types.js` — mark `hotspot-tour` as `ready`, add schema.
- `src/app.js` — dispatcher + enable author-mode postMessage handling when a query param (e.g. `?author=1`) is present on the preview iframe.
- `public/studio/studio.js` — hotspot-tour authoring UI (click-to-place, list, editor).
diff --git a/prompts/widget-studio/06-widgets-dashboard.md b/prompts/widget-studio/06-widgets-dashboard.md
index 9c13feec8..f9cd95442 100644
--- a/prompts/widget-studio/06-widgets-dashboard.md
+++ b/prompts/widget-studio/06-widgets-dashboard.md
@@ -17,13 +17,13 @@ This is the admin UI that makes the Studio worth using repeatedly.
## Read these first
-| File | Why |
-|:---|:---|
+| File | Why |
+| :------------------------------------------------------------------- | :---------------------------------------------------------------------- |
| [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js) | Existing dashboard code. Native DOM, no framework. Follow this pattern. |
-| [public/dashboard/index.html](../../public/dashboard/index.html) | Layout + CSS. You'll add a new sidebar entry. |
-| `api/widgets/index.js` (from Prompt 00) | List/create endpoints. |
-| `api/widgets/[id].js` (from Prompt 00) | Update/delete endpoints. |
-| Prompt 03's `api/widgets/[id]/chat.js` + telemetry (if shipped) | Source for chat stats. |
+| [public/dashboard/index.html](../../public/dashboard/index.html) | Layout + CSS. You'll add a new sidebar entry. |
+| `api/widgets/index.js` (from Prompt 00) | List/create endpoints. |
+| `api/widgets/[id].js` (from Prompt 00) | Update/delete endpoints. |
+| Prompt 03's `api/widgets/[id]/chat.js` + telemetry (if shipped) | Source for chat stats. |
## Build this
@@ -33,12 +33,12 @@ In `dashboard.js`:
```js
const tabs = {
- avatars: renderAvatars,
- upload: renderUpload,
- widgets: renderWidgets, // NEW
- keys: renderKeys,
- mcp: renderMcp,
- billing: renderBilling,
+ avatars: renderAvatars,
+ upload: renderUpload,
+ widgets: renderWidgets, // NEW
+ keys: renderKeys,
+ mcp: renderMcp,
+ billing: renderBilling,
};
```
@@ -66,7 +66,7 @@ Add the duplicate + stats endpoints on the server side:
```js
async function renderWidgets(root) {
- root.innerHTML = `
+ root.innerHTML = `
<div class="widgets-header">
<h1>Your widgets</h1>
<p class="sub">Embeddable 3D experiences — each gets a stable URL.</p>
@@ -74,20 +74,20 @@ async function renderWidgets(root) {
</div>
<div id="widget-list" class="cards"></div>
`;
- // Fetch, render each as widgetCard().
- // Empty state: "No widgets yet. Create your first in the Studio."
+ // Fetch, render each as widgetCard().
+ // Empty state: "No widgets yet. Create your first in the Studio."
}
function widgetCard(w) {
- // Each card:
- // - Live preview iframe (lazy-loaded on IntersectionObserver)
- // src="/#widget=${w.id}&kiosk=true" — small fixed size, no controls.
- // - Title (editable inline — double-click to edit).
- // - Widget type pill with colored icon.
- // - Stats: view count, "updated X ago."
- // - Public/private toggle.
- // - Actions: Edit (→ /studio?edit=<id>), Duplicate, Copy URL, Copy iframe, Delete (with confirm).
- // - Expander: "Show embed code" reveals snippets.
+ // Each card:
+ // - Live preview iframe (lazy-loaded on IntersectionObserver)
+ // src="/#widget=${w.id}&kiosk=true" — small fixed size, no controls.
+ // - Title (editable inline — double-click to edit).
+ // - Widget type pill with colored icon.
+ // - Stats: view count, "updated X ago."
+ // - Public/private toggle.
+ // - Actions: Edit (→ /studio?edit=<id>), Duplicate, Copy URL, Copy iframe, Delete (with confirm).
+ // - Expander: "Show embed code" reveals snippets.
}
```
@@ -162,11 +162,13 @@ Button links to `/studio`.
## Deliverables
**New (server):**
+
- `api/widgets/[id]/duplicate.js`
- `api/widgets/[id]/stats.js`
- Optional: `api/_lib/migrations/NNN_widget_views.sql` if you add per-day granularity.
**Modified:**
+
- `public/dashboard/dashboard.js` — new tab + API calls + UI.
- `public/dashboard/index.html` — sidebar link + any new CSS classes.
- `vercel.json` — new routes for duplicate and stats.
diff --git a/prompts/widget-studio/07-embed-docs-and-polish.md b/prompts/widget-studio/07-embed-docs-and-polish.md
index a5a1969fb..62c0e3bcc 100644
--- a/prompts/widget-studio/07-embed-docs-and-polish.md
+++ b/prompts/widget-studio/07-embed-docs-and-polish.md
@@ -17,14 +17,14 @@ This prompt is where the project stops feeling like a developer tool and starts
## Read these first
-| File | Why |
-|:---|:---|
-| All `src/widgets/*.js` files | Confirm every widget mounts cleanly and exposes a consistent `mount(...)` / `destroy()` contract. |
-| [features.html](../../features.html) and [style.css](../../style.css) | Reference for the visual system. Match it. |
-| [vercel.json](../../vercel.json) | You will add new public routes. |
-| [api/agent-oembed.js](../../api/agent-oembed.js) and [api/agent-og.js](../../api/agent-og.js) | Pattern for OG/oEmbed endpoints. |
-| [scripts/](../../scripts/) | Existing build-time scripts for icons, animations. If the gallery needs prebuilt poster images, mirror this pattern. |
-| [docs/](../../docs/) | Existing developer docs. Follow the tone. |
+| File | Why |
+| :-------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------- |
+| All `src/widgets/*.js` files | Confirm every widget mounts cleanly and exposes a consistent `mount(...)` / `destroy()` contract. |
+| [features.html](../../features.html) and [style.css](../../style.css) | Reference for the visual system. Match it. |
+| [vercel.json](../../vercel.json) | You will add new public routes. |
+| [api/agent-oembed.js](../../api/agent-oembed.js) and [api/agent-og.js](../../api/agent-og.js) | Pattern for OG/oEmbed endpoints. |
+| [scripts/](../../scripts/) | Existing build-time scripts for icons, animations. If the gallery needs prebuilt poster images, mirror this pattern. |
+| [docs/](../../docs/) | Existing developer docs. Follow the tone. |
## Build this
@@ -63,10 +63,10 @@ Sections:
- **iframe embed** — snippet + size recommendations.
- **Script embed** — `embed.js` snippet + what it does.
- **postMessage API** — parent-to-iframe and iframe-to-parent events the widgets emit:
- - `widget:ready` (iframe → parent)
- - `widget:load` / `widget:load:error`
- - `widget:chat:message` (talking-agent only)
- - `widget:hotspot:open` (hotspot-tour only)
+ - `widget:ready` (iframe → parent)
+ - `widget:load` / `widget:load:error`
+ - `widget:chat:message` (talking-agent only)
+ - `widget:hotspot:open` (hotspot-tour only)
- **CSP / CORS** — what sites need to allow (usually nothing, but document if your embed requires `allow="..."`).
- **Privacy** — visitor data, rate limits, what's logged.
- **FAQ** — why no WordPress plugin, can I self-host, etc.
@@ -77,7 +77,7 @@ For each widget type, extend the OG/oEmbed endpoints so:
- **OG image** (`/api/widgets/:id/og`) returns a rendered PNG or SVG preview — title + avatar thumbnail + type badge. Use a server-side image library if one is already in deps (`sharp` is in devDependencies — check if it's available at runtime on Vercel; if not, use SVG since Slack/Discord/X will render it). Reasonable output: 1200x630.
- **OG tags** (in the widget page's HTML head when resolving `#widget=`): Open Graph + Twitter card tags. The `index.html` SPA shell needs to set these dynamically — since hash params aren't available server-side, either use a pre-render crawler check (user-agent detection for social bots; redirect them to a server-rendered metadata page) OR move the widget resolution upstream so `/widget/:id` (path, not hash) is the canonical URL.
- - **Recommendation:** add a second canonical URL pattern: `https://host/w/<id>` that's server-rendered with proper meta tags and client-redirects to `#widget=<id>` for regular browsers. Social crawlers see the meta. Regular users hit the SPA. Update Studio's share UI to prefer `/w/<id>`.
+ - **Recommendation:** add a second canonical URL pattern: `https://host/w/<id>` that's server-rendered with proper meta tags and client-redirects to `#widget=<id>` for regular browsers. Social crawlers see the meta. Regular users hit the SPA. Update Studio's share UI to prefer `/w/<id>`.
- **oEmbed** (`/api/widgets/:id/oembed`): returns the standard oEmbed JSON so WordPress, Ghost, and Notion auto-embed pasted widget URLs. Type = `rich`, `html` = an iframe snippet.
Add `<link rel="alternate" type="application/json+oembed" href="...">` to the widget HTML head.
@@ -95,15 +95,16 @@ Do not redesign the homepage. One button, one link.
Run through each widget type on each browser/device:
-| | Chrome desktop | Safari desktop | Firefox desktop | iOS Safari | Android Chrome |
-|:---|:-:|:-:|:-:|:-:|:-:|
-| Turntable | | | | | |
-| Animation Gallery | | | | | |
-| Talking Agent | | | | | |
-| Passport | | | | | |
-| Hotspot Tour | | | | | |
+| | Chrome desktop | Safari desktop | Firefox desktop | iOS Safari | Android Chrome |
+| :---------------- | :------------: | :------------: | :-------------: | :--------: | :------------: |
+| Turntable | | | | | |
+| Animation Gallery | | | | | |
+| Talking Agent | | | | | |
+| Passport | | | | | |
+| Hotspot Tour | | | | | |
Fix any browser-specific bugs found. Common ones:
+
- iOS Safari autoplay restrictions on animation clips.
- Safari `speechSynthesis.getVoices()` returning empty until a user gesture.
- Chrome/iOS intersection observer quirks on nested iframes.
@@ -120,6 +121,7 @@ Run `axe` (via `@axe-core/cli` — add as devDep if needed) on:
Fix every critical and serious violation. Document any known issues in `docs/WIDGETS.md`.
Key checks:
+
- Color contrast ≥ 4.5:1 for text.
- All interactive elements keyboard-reachable.
- ARIA labels on icon-only buttons.
@@ -173,6 +175,7 @@ Update the main `README.md` with:
## Deliverables
**New:**
+
- `public/widgets-gallery/index.html`
- `public/widgets-gallery/gallery.js`
- `public/widgets-gallery/showcase.json`
@@ -183,6 +186,7 @@ Update the main `README.md` with:
- `public/w/[id].html` + route rewrite for server-rendered metadata page.
**Modified:**
+
- `vercel.json` — new routes (`/widgets`, `/w/:id`, `/docs/widgets`, og/oembed endpoints).
- `README.md` — Widget Studio section + roadmap updates.
- `index.html` — "Make this a widget" button + Widgets nav link.
@@ -215,17 +219,17 @@ Update the main `README.md` with:
6. **a11y:** run `axe-cli` and Lighthouse a11y on each widget type URL and on Studio/Dashboard. Fix violations.
7. **Perf:** run Lighthouse perf mobile on each widget. Tune preload hints if FCP > 2s.
8. **Error simulation:**
- - Delete an avatar → load its widget → "Model unavailable."
- - Revoke a Talking Agent's brain endpoint → "Can't reach brain."
- - Point a Passport at a non-existent tokenId → "Agent not found."
- - Hit Talking Agent rate limit → polite message.
+ - Delete an avatar → load its widget → "Model unavailable."
+ - Revoke a Talking Agent's brain endpoint → "Can't reach brain."
+ - Point a Passport at a non-existent tokenId → "Agent not found."
+ - Hit Talking Agent rate limit → polite message.
9. **Analytics:** load 3 widgets, query DB, confirm view rows with correct metadata.
10. **Full flow, fresh user:** sign up → go to viewer → load model → "Make this a widget" → lands in Studio → picks turntable → saves → shares → works in incognito. No friction.
## When you finish
- PR with:
- - Screenshots of `/widgets` gallery and one OG card.
- - Lighthouse scores for each widget type.
- - A short paragraph for the project's social post.
+ - Screenshots of `/widgets` gallery and one OG card.
+ - Lighthouse scores for each widget type.
+ - A short paragraph for the project's social post.
- Then: ship it. Post about it. Send the demo link to 3 real people. Ask what they'd pay for.
diff --git a/prompts/widget-studio/README.md b/prompts/widget-studio/README.md
index 44fc5b78d..723939b79 100644
--- a/prompts/widget-studio/README.md
+++ b/prompts/widget-studio/README.md
@@ -67,15 +67,15 @@ PRs 2–6 all depend on PR 1 being merged. They can otherwise be built in parall
## Shared vocabulary
-| Term | Meaning |
-|:---|:---|
-| **Widget** | A preconfigured, embeddable viewer experience owned by one user account. |
-| **Widget Studio** | The authoring UI at `/studio` where widgets are created and edited. |
-| **Widget runtime** | The viewer code that renders a saved widget config inside an iframe. |
-| **Widget ID** | A short URL-safe ID (`wdgt_<12char>`) that resolves to a saved config. |
-| **Widget type** | One of: `turntable`, `animation-gallery`, `talking-agent`, `passport`, `hotspot-tour`. |
-| **Avatar** | A glTF/GLB model in the user's R2 account, addressable by `avatar_id`. |
-| **Embed config** | JSON document describing widget state (camera, env, brand colors, type-specific fields). Stored in Neon. |
+| Term | Meaning |
+| :----------------- | :------------------------------------------------------------------------------------------------------- |
+| **Widget** | A preconfigured, embeddable viewer experience owned by one user account. |
+| **Widget Studio** | The authoring UI at `/studio` where widgets are created and edited. |
+| **Widget runtime** | The viewer code that renders a saved widget config inside an iframe. |
+| **Widget ID** | A short URL-safe ID (`wdgt_<12char>`) that resolves to a saved config. |
+| **Widget type** | One of: `turntable`, `animation-gallery`, `talking-agent`, `passport`, `hotspot-tour`. |
+| **Avatar** | A glTF/GLB model in the user's R2 account, addressable by `avatar_id`. |
+| **Embed config** | JSON document describing widget state (camera, env, brand colors, type-specific fields). Stored in Neon. |
## After all prompts are done
diff --git a/public/.well-known/agent-card.json b/public/.well-known/agent-card.json
index 4e947a10b..bea380a9e 100644
--- a/public/.well-known/agent-card.json
+++ b/public/.well-known/agent-card.json
@@ -1,91 +1,91 @@
{
- "name": "3D Agent",
- "description": "AI-powered 3D model viewer and validation agent. Load glTF/GLB models, run validation, inspect materials, and manage avatar assets.",
- "url": "https://3dagent.vercel.app",
- "provider": {
- "organization": "3D Agent",
- "url": "https://3dagent.vercel.app"
- },
- "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 an embeddable HTML model-viewer snippet that renders the given avatar in 3D",
- "tags": ["avatar", "render", "preview"],
- "examples": ["Render my avatar in the viewer", "Preview this model"]
- },
- {
- "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"]
- },
- {
- "id": "validate-model",
- "name": "Validate glTF/GLB Model",
- "description": "Run the Khronos glTF-Validator against a remote model URL and return a structured error/warning/info/hint report",
- "tags": ["model", "validation", "gltf", "glb"],
- "examples": [
- "Validate https://example.com/model.glb",
- "Is this GLB spec-compliant?",
- "Check my model for errors"
- ]
- },
- {
- "id": "inspect-model",
- "name": "Inspect glTF/GLB Model",
- "description": "Parse a remote model and return structural stats: scene/node/mesh counts, vertex and triangle totals, material and texture summaries, extensions used",
- "tags": ["model", "inspect", "stats", "gltf", "glb"],
- "examples": [
- "How many triangles are in this model?",
- "Inspect https://example.com/scene.glb",
- "Show texture stats for this GLB"
- ]
- },
- {
- "id": "optimize-model",
- "name": "Suggest Optimizations",
- "description": "Inspect a remote model and return actionable suggestions for reducing size and draw-call overhead (Draco/Meshopt, KTX2, texture resize, reindexing, material merging)",
- "tags": ["model", "optimize", "suggestions", "performance"],
- "examples": [
- "How can I make this model smaller?",
- "Optimize this GLB for web delivery",
- "Suggest compression for https://example.com/avatar.glb"
- ]
- }
- ]
+ "name": "3D Agent",
+ "description": "AI-powered 3D model viewer and validation agent. Load glTF/GLB models, run validation, inspect materials, and manage avatar assets.",
+ "url": "https://3dagent.vercel.app",
+ "provider": {
+ "organization": "3D Agent",
+ "url": "https://3dagent.vercel.app"
+ },
+ "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 an embeddable HTML model-viewer snippet that renders the given avatar in 3D",
+ "tags": ["avatar", "render", "preview"],
+ "examples": ["Render my avatar in the viewer", "Preview this model"]
+ },
+ {
+ "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"]
+ },
+ {
+ "id": "validate-model",
+ "name": "Validate glTF/GLB Model",
+ "description": "Run the Khronos glTF-Validator against a remote model URL and return a structured error/warning/info/hint report",
+ "tags": ["model", "validation", "gltf", "glb"],
+ "examples": [
+ "Validate https://example.com/model.glb",
+ "Is this GLB spec-compliant?",
+ "Check my model for errors"
+ ]
+ },
+ {
+ "id": "inspect-model",
+ "name": "Inspect glTF/GLB Model",
+ "description": "Parse a remote model and return structural stats: scene/node/mesh counts, vertex and triangle totals, material and texture summaries, extensions used",
+ "tags": ["model", "inspect", "stats", "gltf", "glb"],
+ "examples": [
+ "How many triangles are in this model?",
+ "Inspect https://example.com/scene.glb",
+ "Show texture stats for this GLB"
+ ]
+ },
+ {
+ "id": "optimize-model",
+ "name": "Suggest Optimizations",
+ "description": "Inspect a remote model and return actionable suggestions for reducing size and draw-call overhead (Draco/Meshopt, KTX2, texture resize, reindexing, material merging)",
+ "tags": ["model", "optimize", "suggestions", "performance"],
+ "examples": [
+ "How can I make this model smaller?",
+ "Optimize this GLB for web delivery",
+ "Suggest compression for https://example.com/avatar.glb"
+ ]
+ }
+ ]
}
diff --git a/public/.well-known/agent-registration.json b/public/.well-known/agent-registration.json
index 4bee98074..6ed9f31ce 100644
--- a/public/.well-known/agent-registration.json
+++ b/public/.well-known/agent-registration.json
@@ -22,7 +22,5 @@
],
"x402Support": false,
"registrations": [],
- "supportedTrust": [
- "reputation"
- ]
+ "supportedTrust": ["reputation"]
}
diff --git a/public/.well-known/openapi.yaml b/public/.well-known/openapi.yaml
index a0c0f684d..0d65e978c 100644
--- a/public/.well-known/openapi.yaml
+++ b/public/.well-known/openapi.yaml
@@ -1,1695 +1,1709 @@
openapi: 3.0.0
info:
- title: 3D Agent API
- description: >
- AI-powered 3D avatar management platform. Supports OAuth 2.1 (with PKCE),
- session cookies, and API keys for authentication. Avatars are stored as
- glTF/GLB files on Cloudflare R2 and exposed via a Model Context Protocol
- (MCP) JSON-RPC server for AI tool integrations.
- version: 1.5.1
- contact:
- license:
- name: MIT
- url: https://opensource.org/licenses/MIT
+ title: 3D Agent API
+ description: >
+ AI-powered 3D avatar management platform. Supports OAuth 2.1 (with PKCE),
+ session cookies, and API keys for authentication. Avatars are stored as
+ glTF/GLB files on Cloudflare R2 and exposed via a Model Context Protocol
+ (MCP) JSON-RPC server for AI tool integrations.
+ version: 1.5.1
+ contact:
+ license:
+ name: MIT
+ url: https://opensource.org/licenses/MIT
servers:
- - url: https://3dagent.vercel.app
+ - url: https://3dagent.vercel.app
tags:
- - name: Auth
- description: Session-based authentication (register, login, logout)
- - name: Avatars
- description: Avatar CRUD and file upload
- - name: Keys
- description: API key management
- - name: OAuth
- description: OAuth 2.1 authorization server (RFC 6749, 7009, 7591, 7662, 8414)
- - name: MCP
- description: Model Context Protocol JSON-RPC tool server
- - name: Usage
- description: Account usage and quota statistics
- - name: Discovery
- description: Well-known discovery endpoints
+ - name: Auth
+ description: Session-based authentication (register, login, logout)
+ - name: Avatars
+ description: Avatar CRUD and file upload
+ - name: Keys
+ description: API key management
+ - name: OAuth
+ description: OAuth 2.1 authorization server (RFC 6749, 7009, 7591, 7662, 8414)
+ - name: MCP
+ description: Model Context Protocol JSON-RPC tool server
+ - name: Usage
+ description: Account usage and quota statistics
+ - name: Discovery
+ description: Well-known discovery endpoints
# ---------------------------------------------------------------------------
# Security schemes
# ---------------------------------------------------------------------------
components:
- securitySchemes:
- cookieAuth:
- type: apiKey
- in: cookie
- name: sid
- description: HttpOnly session cookie set by /api/auth/login or /api/auth/register.
+ securitySchemes:
+ cookieAuth:
+ type: apiKey
+ in: cookie
+ name: sid
+ description: HttpOnly session cookie set by /api/auth/login or /api/auth/register.
- bearerAuth:
- type: http
- scheme: bearer
- bearerFormat: JWT
- description: >
- OAuth 2.1 access token (JWT, 1 h TTL) obtained from /api/oauth/token,
- **or** an API key with prefix `sk_live_` / `sk_test_`.
+ bearerAuth:
+ type: http
+ scheme: bearer
+ bearerFormat: JWT
+ description: >
+ OAuth 2.1 access token (JWT, 1 h TTL) obtained from /api/oauth/token,
+ **or** an API key with prefix `sk_live_` / `sk_test_`.
- # -------------------------------------------------------------------------
- # Reusable schemas
- # -------------------------------------------------------------------------
- schemas:
-
- # -- Users ---------------------------------------------------------------
- User:
- type: object
- properties:
- id:
- type: string
- format: uuid
- email:
- type: string
- format: email
- display_name:
- type: string
- nullable: true
- avatar_url:
- type: string
- format: uri
- nullable: true
- plan:
- type: string
- enum: [free, pro, team, enterprise]
- created_at:
- type: string
- format: date-time
- required: [id, email, plan]
-
- # -- Avatars -------------------------------------------------------------
- Avatar:
- type: object
- properties:
- id:
- type: string
- format: uuid
- owner_id:
- type: string
- format: uuid
- slug:
- type: string
- example: my-hero
- name:
- type: string
- example: My Hero
- description:
- type: string
- nullable: true
- storage_key:
- type: string
- description: R2 object key
- size_bytes:
- type: integer
- content_type:
- type: string
- example: model/gltf-binary
- source:
- type: string
- enum: [upload, avaturn, import]
- source_meta:
- type: object
- nullable: true
- additionalProperties: true
- thumbnail_key:
- type: string
- nullable: true
- visibility:
- type: string
- enum: [private, unlisted, public]
- tags:
- type: array
- items:
- type: string
- checksum_sha256:
- type: string
- nullable: true
- description: 64-character hex SHA-256 of the file
- version:
- type: integer
- created_at:
- type: string
- format: date-time
- updated_at:
- type: string
- format: date-time
- deleted_at:
- type: string
- format: date-time
- nullable: true
- required: [id, owner_id, slug, name, visibility, version, created_at, updated_at]
-
- AvatarWithUrl:
- allOf:
- - $ref: '#/components/schemas/Avatar'
- - type: object
- properties:
- url:
- type: string
- format: uri
- description: Presigned or public CDN URL for the GLB file
- cdn:
- type: boolean
- description: True when the URL is a public CDN URL (no expiry)
- expires_in:
- type: integer
- description: Seconds until the presigned URL expires (omitted for CDN URLs)
-
- # -- API Keys ------------------------------------------------------------
- ApiKey:
- type: object
- properties:
- id:
- type: string
- format: uuid
- name:
- type: string
- prefix:
- type: string
- example: sk_live_Ab3d
- description: First 12 chars of the key (safe to display)
- scope:
- type: string
- example: avatars:read avatars:write
- last_used_at:
- type: string
- format: date-time
- nullable: true
- expires_at:
- type: string
- format: date-time
- nullable: true
- revoked_at:
- type: string
- format: date-time
- nullable: true
- created_at:
- type: string
- format: date-time
- required: [id, name, prefix, scope, created_at]
-
- # -- Usage ---------------------------------------------------------------
- PlanQuota:
- type: object
- properties:
- plan:
- type: string
- enum: [free, pro, team, enterprise]
- max_avatars:
- type: integer
- max_bytes_per_avatar:
- type: integer
- max_total_bytes:
- type: integer
- mcp_calls_per_day:
- type: integer
- required: [plan, max_avatars, max_bytes_per_avatar, max_total_bytes, mcp_calls_per_day]
-
- UsageCounts:
- type: object
- properties:
- avatars:
- type: integer
- bytes:
- type: integer
- mcp_calls_24h:
- type: integer
- events_30d:
- type: integer
- required: [avatars, bytes, mcp_calls_24h, events_30d]
-
- # -- Pagination ----------------------------------------------------------
- Cursor:
- type: string
- format: date-time
- description: ISO-8601 timestamp used as an opaque pagination cursor
-
- # -- Errors --------------------------------------------------------------
- Error:
- type: object
- properties:
- error:
- type: string
- description: Machine-readable error code
- example: validation_error
- error_description:
- type: string
- description: Human-readable message
- example: "email is required"
- required: [error, error_description]
-
- OAuthError:
- type: object
- description: RFC 6749 §5.2 error response
- properties:
- error:
- type: string
- example: invalid_grant
- error_description:
- type: string
- required: [error]
-
- # -- JSON-RPC ------------------------------------------------------------
- JsonRpcRequest:
- type: object
- required: [jsonrpc, method]
- properties:
- jsonrpc:
- type: string
- enum: ["2.0"]
- id:
- oneOf:
- - type: string
- - type: integer
- description: Omit for notifications
- method:
- type: string
- params:
- type: object
- additionalProperties: true
-
- JsonRpcResponse:
- type: object
- required: [jsonrpc, id]
- properties:
- jsonrpc:
- type: string
- enum: ["2.0"]
- id:
- oneOf:
- - type: string
- - type: integer
- - type: "null"
- result:
- description: Present on success
- error:
- type: object
- properties:
- code:
- type: integer
- message:
- type: string
- data: {}
-
- # -------------------------------------------------------------------------
- # Reusable responses
- # -------------------------------------------------------------------------
- responses:
- Unauthorized:
- description: Missing or invalid credentials
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/Error'
-
- Forbidden:
- description: Insufficient scope or ownership mismatch
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/Error'
-
- NotFound:
- description: Resource not found
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/Error'
-
- TooManyRequests:
- description: Rate limit exceeded
- headers:
- Retry-After:
- schema:
- type: integer
- description: Seconds to wait before retrying
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/Error'
-
- InternalServerError:
- description: Unexpected server error
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/Error'
-
-# ==========================================================================
-# Paths
-# ==========================================================================
-paths:
-
- # --------------------------------------------------------------------------
- # Root
- # --------------------------------------------------------------------------
- /:
- get:
- operationId: viewHomepage
- summary: Load the 3D model viewer interface
- description: >
- Returns the main viewer page where users can drag-and-drop glTF/GLB
- 3D models for instant preview.
- responses:
- "200":
- description: The 3D viewer HTML page.
-
- # --------------------------------------------------------------------------
- # Auth
- # --------------------------------------------------------------------------
- /api/auth/register:
- post:
- operationId: registerUser
- tags: [Auth]
- summary: Register a new user account
- description: >
- Creates a user account, hashes the password, opens a session, and sets
- the `sid` cookie. Rate-limited to **5 requests per IP per hour**.
- requestBody:
- required: true
- content:
- application/json:
- schema:
- type: object
- required: [email, password]
- properties:
+ # -------------------------------------------------------------------------
+ # Reusable schemas
+ # -------------------------------------------------------------------------
+ schemas:
+ # -- Users ---------------------------------------------------------------
+ User:
+ type: object
+ properties:
+ id:
+ type: string
+ format: uuid
email:
- type: string
- format: email
- maxLength: 254
- password:
- type: string
- minLength: 10
- maxLength: 200
+ type: string
+ format: email
display_name:
- type: string
- minLength: 1
- maxLength: 80
- responses:
- "201":
- description: Account created
- headers:
- Set-Cookie:
- description: HttpOnly session cookie (`sid`)
- schema:
- type: string
- content:
- application/json:
- schema:
- type: object
- properties:
- user:
- $ref: '#/components/schemas/User'
- "400":
- description: Validation error
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/Error'
- "409":
- description: Email already registered
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/Error'
- example:
- error: email_taken
- error_description: An account with that email already exists
- "429":
- $ref: '#/components/responses/TooManyRequests'
-
- /api/auth/login:
- post:
- operationId: loginUser
- tags: [Auth]
- summary: Log in with email and password
- description: >
- Verifies credentials, creates a session, and sets the `sid` cookie.
- Rate-limited to **30 requests per IP per 10 minutes**.
- requestBody:
- required: true
- content:
- application/json:
- schema:
- type: object
- required: [email, password]
- properties:
- email:
- type: string
- format: email
- password:
- type: string
- responses:
- "200":
- description: Login successful
- headers:
- Set-Cookie:
- description: HttpOnly session cookie (`sid`)
- schema:
- type: string
- content:
- application/json:
- schema:
- type: object
- properties:
- user:
- $ref: '#/components/schemas/User'
- "401":
- description: Invalid credentials
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/Error'
- "429":
- $ref: '#/components/responses/TooManyRequests'
-
- /api/auth/me:
- get:
- operationId: getCurrentUser
- tags: [Auth]
- summary: Get the currently authenticated user
- security:
- - cookieAuth: []
- responses:
- "200":
- description: Authenticated user profile
- content:
- application/json:
- schema:
- type: object
- properties:
- user:
- $ref: '#/components/schemas/User'
- "401":
- $ref: '#/components/responses/Unauthorized'
-
- /api/auth/logout:
- post:
- operationId: logoutUser
- tags: [Auth]
- summary: Invalidate the current session
- security:
- - cookieAuth: []
- responses:
- "200":
- description: Session revoked
- headers:
- Set-Cookie:
- description: Clears the `sid` cookie
- schema:
- type: string
- content:
- application/json:
- schema:
- type: object
- properties:
- ok:
- type: boolean
- example: true
- "401":
- $ref: '#/components/responses/Unauthorized'
-
- # --------------------------------------------------------------------------
- # Avatars
- # --------------------------------------------------------------------------
- /api/avatars:
- get:
- operationId: listAvatars
- tags: [Avatars]
- summary: List avatars owned by the authenticated user
- security:
- - cookieAuth: []
- - bearerAuth: []
- parameters:
- - name: limit
- in: query
- schema:
- type: integer
- minimum: 1
- maximum: 200
- default: 50
- - name: cursor
- in: query
- description: Pagination cursor (ISO-8601 timestamp from previous `next_cursor`)
- schema:
- $ref: '#/components/schemas/Cursor'
- - name: visibility
- in: query
- schema:
- type: string
- enum: [private, unlisted, public]
- - name: include_public
- in: query
- description: When `true`, also returns all public avatars
- schema:
- type: string
- enum: ['true', 'false']
- responses:
- "200":
- description: Paginated avatar list
- content:
- application/json:
- schema:
- type: object
- properties:
- avatars:
- type: array
- items:
- $ref: '#/components/schemas/Avatar'
- next_cursor:
- $ref: '#/components/schemas/Cursor'
- "401":
- $ref: '#/components/responses/Unauthorized'
+ type: string
+ nullable: true
+ avatar_url:
+ type: string
+ format: uri
+ nullable: true
+ plan:
+ type: string
+ enum: [free, pro, team, enterprise]
+ created_at:
+ type: string
+ format: date-time
+ required: [id, email, plan]
- post:
- operationId: createAvatar
- tags: [Avatars]
- summary: Create an avatar record after uploading the file to R2
- description: >
- Call `POST /api/avatars/presign` first to get a presigned upload URL,
- upload the GLB file directly to R2, then call this endpoint to register
- the avatar.
- security:
- - cookieAuth: []
- - bearerAuth: []
- requestBody:
- required: true
- content:
- application/json:
- schema:
- type: object
- required: [name, storage_key, size_bytes]
- properties:
- name:
- type: string
- minLength: 1
- maxLength: 120
+ # -- Avatars -------------------------------------------------------------
+ Avatar:
+ type: object
+ properties:
+ id:
+ type: string
+ format: uuid
+ owner_id:
+ type: string
+ format: uuid
slug:
- type: string
- minLength: 1
- maxLength: 64
- pattern: '^[a-z0-9_-]+$'
+ type: string
+ example: my-hero
+ name:
+ type: string
+ example: My Hero
description:
- type: string
- maxLength: 2000
- visibility:
- type: string
- enum: [private, unlisted, public]
- default: private
- tags:
- type: array
- maxItems: 20
- items:
type: string
- maxLength: 40
- source:
- type: string
- enum: [upload, avaturn, import]
- default: upload
- source_meta:
- type: object
- additionalProperties: true
- content_type:
- type: string
- default: model/gltf-binary
- size_bytes:
- type: integer
- minimum: 1
- maximum: 524288000
- description: File size in bytes (max 500 MB)
- checksum_sha256:
- type: string
- pattern: '^[0-9a-f]{64}$'
+ nullable: true
storage_key:
- type: string
- description: R2 object key returned by /api/avatars/presign
- responses:
- "201":
- description: Avatar record created
- content:
- application/json:
- schema:
- type: object
- properties:
- avatar:
- $ref: '#/components/schemas/Avatar'
- "400":
- description: Validation error
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/Error'
- "401":
- $ref: '#/components/responses/Unauthorized'
- "403":
- $ref: '#/components/responses/Forbidden'
- "500":
- $ref: '#/components/responses/InternalServerError'
-
- /api/avatars/public:
- get:
- operationId: searchPublicAvatars
- tags: [Avatars]
- summary: Search public avatars (no authentication required)
- description: >
- Full-text search over public avatars. Results are cached for 60 seconds.
- parameters:
- - name: q
- in: query
- description: Free-text search query
- schema:
- type: string
- - name: tag
- in: query
- description: Filter by a single tag
- schema:
- type: string
- - name: limit
- in: query
- schema:
- type: integer
- minimum: 1
- maximum: 100
- default: 24
- - name: cursor
- in: query
- description: Pagination cursor (ISO-8601 timestamp from previous `next_cursor`)
- schema:
- $ref: '#/components/schemas/Cursor'
- responses:
- "200":
- description: Paginated public avatar list
- headers:
- Cache-Control:
- schema:
- type: string
- example: public, max-age=60
- content:
- application/json:
- schema:
- type: object
- properties:
- avatars:
- type: array
- items:
- $ref: '#/components/schemas/Avatar'
- next_cursor:
- $ref: '#/components/schemas/Cursor'
-
- /api/avatars/presign:
- post:
- operationId: presignAvatarUpload
- tags: [Avatars]
- summary: Get a presigned URL for uploading a GLB file directly to R2
- description: >
- Rate-limited to **60 requests per user per hour**. Use the returned
- `upload_url` with an HTTP PUT request (include the `content-type`
- header). After the upload succeeds, call `POST /api/avatars` with
- the returned `storage_key`.
- security:
- - cookieAuth: []
- - bearerAuth: []
- requestBody:
- required: true
- content:
- application/json:
- schema:
- type: object
- required: [size_bytes]
- properties:
+ type: string
+ description: R2 object key
size_bytes:
- type: integer
- minimum: 1
- maximum: 524288000
- description: File size in bytes (max 500 MB)
+ type: integer
content_type:
- type: string
- default: model/gltf-binary
- checksum_sha256:
- type: string
- pattern: '^[0-9a-f]{64}$'
- slug:
- type: string
- minLength: 1
- maxLength: 64
- pattern: '^[a-z0-9_-]+$'
- responses:
- "200":
- description: Presigned upload details
- content:
- application/json:
- schema:
- type: object
- required: [storage_key, upload_url, method, headers, expires_in]
- properties:
- storage_key:
- type: string
- description: R2 object key to pass to POST /api/avatars
- upload_url:
type: string
- format: uri
- description: Presigned R2 PUT URL
- method:
+ example: model/gltf-binary
+ source:
type: string
- enum: [PUT]
- headers:
+ enum: [upload, avaturn, import]
+ source_meta:
type: object
- description: Headers to include in the PUT request
- additionalProperties:
- type: string
- example:
- content-type: model/gltf-binary
- expires_in:
- type: integer
- example: 300
- description: Seconds until the presigned URL expires
- "400":
- description: Validation error
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/Error'
- "401":
- $ref: '#/components/responses/Unauthorized'
- "429":
- $ref: '#/components/responses/TooManyRequests'
-
- /api/avatars/{id}:
- parameters:
- - name: id
- in: path
- required: true
- schema:
- type: string
- format: uuid
-
- get:
- operationId: getAvatar
- tags: [Avatars]
- summary: Get a single avatar by ID
- description: >
- Returns metadata plus a time-limited (or permanent CDN) URL for the
- GLB file. Private avatars are only accessible to their owner. Records a
- `avatar_fetch` usage event.
- security:
- - {}
- - cookieAuth: []
- - bearerAuth: []
- responses:
- "200":
- description: Avatar details with download URL
- content:
- application/json:
- schema:
- type: object
- properties:
- avatar:
- $ref: '#/components/schemas/AvatarWithUrl'
- "401":
- $ref: '#/components/responses/Unauthorized'
- "404":
- $ref: '#/components/responses/NotFound'
-
- patch:
- operationId: updateAvatar
- tags: [Avatars]
- summary: Update avatar metadata (partial update)
- security:
- - cookieAuth: []
- - bearerAuth: []
- requestBody:
- required: true
- content:
- application/json:
- schema:
- type: object
- properties:
- name:
- type: string
- minLength: 1
- maxLength: 120
- description:
- type: string
- maxLength: 2000
+ nullable: true
+ additionalProperties: true
+ thumbnail_key:
+ type: string
+ nullable: true
visibility:
- type: string
- enum: [private, unlisted, public]
- tags:
- type: array
- maxItems: 20
- items:
type: string
- maxLength: 40
- responses:
- "200":
- description: Updated avatar
- content:
- application/json:
- schema:
- type: object
- properties:
- avatar:
- $ref: '#/components/schemas/Avatar'
- "400":
- description: Validation error
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/Error'
- "401":
- $ref: '#/components/responses/Unauthorized'
- "404":
- $ref: '#/components/responses/NotFound'
-
- delete:
- operationId: deleteAvatar
- tags: [Avatars]
- summary: Delete an avatar (soft delete + queued R2 removal)
- security:
- - cookieAuth: []
- - bearerAuth: []
- responses:
- "200":
- description: Avatar deleted
- content:
- application/json:
- schema:
- type: object
- properties:
- ok:
- type: boolean
- example: true
- "401":
- $ref: '#/components/responses/Unauthorized'
- "404":
- $ref: '#/components/responses/NotFound'
-
- # --------------------------------------------------------------------------
- # API Keys
- # --------------------------------------------------------------------------
- /api/keys:
- get:
- operationId: listApiKeys
- tags: [Keys]
- summary: List API keys for the authenticated user
- security:
- - cookieAuth: []
- responses:
- "200":
- description: List of API keys (secrets never returned after creation)
- content:
- application/json:
- schema:
- type: object
- properties:
- keys:
+ enum: [private, unlisted, public]
+ tags:
type: array
items:
- $ref: '#/components/schemas/ApiKey'
- "401":
- $ref: '#/components/responses/Unauthorized'
-
- post:
- operationId: createApiKey
- tags: [Keys]
- summary: Create a new API key
- description: >
- The `secret` field in the response is the only time the plaintext key
- is returned — store it immediately.
- security:
- - cookieAuth: []
- requestBody:
- required: true
- content:
- application/json:
- schema:
- type: object
- required: [name]
- properties:
- name:
- type: string
- minLength: 1
- maxLength: 80
- scope:
- type: string
- default: "avatars:read avatars:write"
- description: >
- Space-separated list of scopes. Valid values:
- `avatars:read`, `avatars:write`, `avatars:delete`, `profile`.
- expires_in_days:
- type: integer
- minimum: 1
- maximum: 3650
- description: Key TTL in days (omit for no expiry)
- environment:
- type: string
- enum: [live, test]
- default: live
- responses:
- "201":
- description: API key created (secret visible only once)
- content:
- application/json:
- schema:
- type: object
- properties:
- key:
- allOf:
- - $ref: '#/components/schemas/ApiKey'
- - type: object
- properties:
- secret:
- type: string
- description: >
- Full plaintext API key (e.g. `sk_live_…`).
- Only returned on creation.
- example: sk_live_Ab3dXYZ...
- "400":
- description: Validation error
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/Error'
- "401":
- $ref: '#/components/responses/Unauthorized'
+ type: string
+ checksum_sha256:
+ type: string
+ nullable: true
+ description: 64-character hex SHA-256 of the file
+ version:
+ type: integer
+ created_at:
+ type: string
+ format: date-time
+ updated_at:
+ type: string
+ format: date-time
+ deleted_at:
+ type: string
+ format: date-time
+ nullable: true
+ required: [id, owner_id, slug, name, visibility, version, created_at, updated_at]
- /api/keys/{id}:
- delete:
- operationId: revokeApiKey
- tags: [Keys]
- summary: Revoke an API key by ID
- security:
- - cookieAuth: []
- parameters:
- - name: id
- in: path
- required: true
- schema:
- type: string
- format: uuid
- responses:
- "200":
- description: Key revoked
- content:
- application/json:
- schema:
- type: object
- properties:
- ok:
- type: boolean
- example: true
- "401":
- $ref: '#/components/responses/Unauthorized'
- "404":
- $ref: '#/components/responses/NotFound'
+ AvatarWithUrl:
+ allOf:
+ - $ref: '#/components/schemas/Avatar'
+ - type: object
+ properties:
+ url:
+ type: string
+ format: uri
+ description: Presigned or public CDN URL for the GLB file
+ cdn:
+ type: boolean
+ description: True when the URL is a public CDN URL (no expiry)
+ expires_in:
+ type: integer
+ description: Seconds until the presigned URL expires (omitted for CDN URLs)
- # --------------------------------------------------------------------------
- # OAuth 2.1
- # --------------------------------------------------------------------------
- /api/oauth/register:
- post:
- operationId: oauthDynamicClientRegistration
- tags: [OAuth]
- summary: Dynamic client registration (RFC 7591)
- description: >
- Registers a new OAuth client. Clients with `redirect_uris` pointing to
- `localhost` or with `token_endpoint_auth_method: none` are treated as
- **public** clients; all others are **confidential** and receive a
- `client_secret`.
- requestBody:
- required: true
- content:
- application/json:
- schema:
- type: object
- required: [redirect_uris]
- properties:
- redirect_uris:
- type: array
- minItems: 1
- maxItems: 10
- items:
+ # -- API Keys ------------------------------------------------------------
+ ApiKey:
+ type: object
+ properties:
+ id:
type: string
- format: uri
- client_name:
- type: string
- client_uri:
- type: string
- format: uri
- logo_uri:
- type: string
- format: uri
- scope:
- type: string
- example: avatars:read avatars:write
- grant_types:
- type: array
- items:
+ format: uuid
+ name:
type: string
- enum: [authorization_code, refresh_token]
- response_types:
- type: array
- items:
+ prefix:
type: string
- enum: [code]
- token_endpoint_auth_method:
- type: string
- enum: [none, client_secret_basic, client_secret_post]
- software_id:
- type: string
- software_version:
- type: string
- responses:
- "201":
- description: Client registered
- content:
- application/json:
- schema:
- type: object
- required: [client_id, client_id_issued_at, redirect_uris, grant_types, response_types, scope, token_endpoint_auth_method]
- properties:
- client_id:
+ example: sk_live_Ab3d
+ description: First 12 chars of the key (safe to display)
+ scope:
type: string
- example: mcp_Ab3dXYZ
- client_secret:
+ example: avatars:read avatars:write
+ last_used_at:
type: string
- description: Only present for confidential clients
- client_id_issued_at:
- type: integer
- description: Unix timestamp
- token_endpoint_auth_method:
+ format: date-time
+ nullable: true
+ expires_at:
type: string
- redirect_uris:
- type: array
- items:
- type: string
- format: uri
- grant_types:
- type: array
- items:
- type: string
- response_types:
- type: array
- items:
- type: string
- scope:
+ format: date-time
+ nullable: true
+ revoked_at:
type: string
- client_name:
+ format: date-time
+ nullable: true
+ created_at:
type: string
- "400":
- description: Invalid registration request
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/OAuthError'
-
- /api/oauth/authorize:
- get:
- operationId: oauthAuthorize
- tags: [OAuth]
- summary: Authorization endpoint — show consent screen
- description: >
- If the user is not authenticated they are redirected to the login page.
- On success, displays an HTML consent form. Requires PKCE with
- `code_challenge_method=S256`.
- parameters:
- - name: response_type
- in: query
- required: true
- schema:
- type: string
- enum: [code]
- - name: client_id
- in: query
- required: true
- schema:
- type: string
- - name: redirect_uri
- in: query
- required: true
- schema:
- type: string
- format: uri
- - name: scope
- in: query
- schema:
- type: string
- example: avatars:read avatars:write
- - name: state
- in: query
- schema:
- type: string
- - name: code_challenge
- in: query
- required: true
- schema:
- type: string
- description: Base64url-encoded SHA-256 of the code_verifier (PKCE)
- - name: code_challenge_method
- in: query
- required: true
- schema:
- type: string
- enum: [S256]
- - name: resource
- in: query
- schema:
- type: string
- format: uri
- description: RFC 8707 resource indicator
- responses:
- "200":
- description: HTML consent form
- content:
- text/html:
- schema:
- type: string
- "302":
- description: Redirect to login (if unauthenticated) or error redirect
- headers:
- Location:
- schema:
- type: string
- "400":
- description: Invalid authorization request
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/OAuthError'
-
- post:
- operationId: oauthAuthorizeDecision
- tags: [OAuth]
- summary: Submit consent form decision (allow or deny)
- security:
- - cookieAuth: []
- requestBody:
- required: true
- content:
- application/x-www-form-urlencoded:
- schema:
- type: object
- required: [decision, client_id, redirect_uri, code_challenge, code_challenge_method]
- properties:
- decision:
- type: string
- enum: [allow, deny]
- response_type:
- type: string
- enum: [code]
- client_id:
- type: string
- redirect_uri:
- type: string
- format: uri
- scope:
- type: string
- state:
- type: string
- code_challenge:
- type: string
- code_challenge_method:
- type: string
- enum: [S256]
- resource:
- type: string
- responses:
- "302":
- description: >
- Redirect to `redirect_uri?code=CODE&state=STATE` (allow) or
- `redirect_uri?error=access_denied&state=STATE` (deny)
- headers:
- Location:
- schema:
- type: string
+ format: date-time
+ required: [id, name, prefix, scope, created_at]
- /api/oauth/token:
- post:
- operationId: oauthToken
- tags: [OAuth]
- summary: Token endpoint — exchange code or refresh token
- description: >
- Supports `authorization_code` and `refresh_token` grant types.
- Confidential clients authenticate via HTTP Basic (preferred) or
- `client_id` + `client_secret` form fields.
- Rate-limited to **120 requests per client per minute**.
- requestBody:
- required: true
- content:
- application/x-www-form-urlencoded:
- schema:
- type: object
- required: [grant_type]
- properties:
- grant_type:
- type: string
- enum: [authorization_code, refresh_token]
- code:
- type: string
- description: Required for authorization_code grant
- redirect_uri:
- type: string
- format: uri
- description: Required for authorization_code grant; must match the authorization request
- code_verifier:
- type: string
- description: PKCE verifier; required for authorization_code grant
- refresh_token:
- type: string
- description: Required for refresh_token grant
- scope:
- type: string
- description: Optional subset scope for refresh_token grant
- client_id:
- type: string
- client_secret:
- type: string
- description: Required for confidential clients not using HTTP Basic
- responses:
- "200":
- description: Token response
- content:
- application/json:
- schema:
- type: object
- required: [access_token, token_type, expires_in, scope]
- properties:
- access_token:
+ # -- Usage ---------------------------------------------------------------
+ PlanQuota:
+ type: object
+ properties:
+ plan:
type: string
- description: JWT access token (1 h TTL)
- token_type:
- type: string
- enum: [Bearer]
- expires_in:
+ enum: [free, pro, team, enterprise]
+ max_avatars:
type: integer
- example: 3600
- scope:
- type: string
- refresh_token:
- type: string
- description: Opaque refresh token (30 d TTL, rotated on use)
- "400":
- description: Invalid request
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/OAuthError'
- "401":
- description: Invalid client credentials or grant
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/OAuthError'
- "429":
- $ref: '#/components/responses/TooManyRequests'
+ max_bytes_per_avatar:
+ type: integer
+ max_total_bytes:
+ type: integer
+ mcp_calls_per_day:
+ type: integer
+ required: [plan, max_avatars, max_bytes_per_avatar, max_total_bytes, mcp_calls_per_day]
- /api/oauth/revoke:
- post:
- operationId: oauthRevoke
- tags: [OAuth]
- summary: Token revocation endpoint (RFC 7009)
- description: >
- Revokes an access token or refresh token. Always returns 200 per the
- RFC, even if the token is unknown or already revoked.
- requestBody:
- required: true
- content:
- application/x-www-form-urlencoded:
- schema:
- type: object
- required: [token]
- properties:
- token:
- type: string
- token_type_hint:
- type: string
- enum: [access_token, refresh_token]
- client_id:
- type: string
- client_secret:
- type: string
- responses:
- "200":
- description: Revocation accepted (per RFC 7009, always 200)
- content:
- application/json:
- schema:
- type: object
- example: {}
+ UsageCounts:
+ type: object
+ properties:
+ avatars:
+ type: integer
+ bytes:
+ type: integer
+ mcp_calls_24h:
+ type: integer
+ events_30d:
+ type: integer
+ required: [avatars, bytes, mcp_calls_24h, events_30d]
- /api/oauth/introspect:
- post:
- operationId: oauthIntrospect
- tags: [OAuth]
- summary: Token introspection endpoint (RFC 7662)
- description: >
- Returns metadata about a token. Confidential clients authenticate via
- HTTP Basic or `client_id`/`client_secret` form fields.
- requestBody:
- required: true
- content:
- application/x-www-form-urlencoded:
- schema:
- type: object
- required: [token]
- properties:
- token:
- type: string
- client_id:
- type: string
- client_secret:
- type: string
- responses:
- "200":
- description: Token metadata
- content:
- application/json:
- schema:
- type: object
- required: [active]
- properties:
- active:
- type: boolean
- scope:
+ # -- Pagination ----------------------------------------------------------
+ Cursor:
+ type: string
+ format: date-time
+ description: ISO-8601 timestamp used as an opaque pagination cursor
+
+ # -- Errors --------------------------------------------------------------
+ Error:
+ type: object
+ properties:
+ error:
type: string
- client_id:
+ description: Machine-readable error code
+ example: validation_error
+ error_description:
type: string
- sub:
+ description: Human-readable message
+ example: 'email is required'
+ required: [error, error_description]
+
+ OAuthError:
+ type: object
+ description: RFC 6749 §5.2 error response
+ properties:
+ error:
type: string
- format: uuid
- description: User ID
- token_type:
+ example: invalid_grant
+ error_description:
type: string
- enum: [Bearer, refresh_token]
- aud:
+ required: [error]
+
+ # -- JSON-RPC ------------------------------------------------------------
+ JsonRpcRequest:
+ type: object
+ required: [jsonrpc, method]
+ properties:
+ jsonrpc:
type: string
- iss:
+ enum: ['2.0']
+ id:
+ oneOf:
+ - type: string
+ - type: integer
+ description: Omit for notifications
+ method:
type: string
- format: uri
- exp:
- type: integer
- description: Unix expiry timestamp
- iat:
- type: integer
- description: Unix issued-at timestamp
+ params:
+ type: object
+ additionalProperties: true
- # --------------------------------------------------------------------------
- # MCP (Model Context Protocol)
- # --------------------------------------------------------------------------
- /api/mcp:
- post:
- operationId: mcpJsonRpc
- tags: [MCP]
- summary: MCP JSON-RPC 2.0 endpoint
- description: >
- Stateless JSON-RPC 2.0 endpoint implementing the [Model Context
- Protocol](https://modelcontextprotocol.io). Accepts single or batched
- requests. Authenticated with an OAuth 2.1 access token **or** an API
- key in the `Authorization: Bearer …` header.
+ JsonRpcResponse:
+ type: object
+ required: [jsonrpc, id]
+ properties:
+ jsonrpc:
+ type: string
+ enum: ['2.0']
+ id:
+ oneOf:
+ - type: string
+ - type: integer
+ - type: 'null'
+ result:
+ description: Present on success
+ error:
+ type: object
+ properties:
+ code:
+ type: integer
+ message:
+ type: string
+ data: {}
+ # -------------------------------------------------------------------------
+ # Reusable responses
+ # -------------------------------------------------------------------------
+ responses:
+ Unauthorized:
+ description: Missing or invalid credentials
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
- **Supported methods:**
- `initialize`, `tools/list`, `tools/call`, `ping`,
- `notifications/initialized`, `resources/list`,
- `resources/templates/list`, `prompts/list`, `logging/setLevel`.
+ Forbidden:
+ description: Insufficient scope or ownership mismatch
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
+ NotFound:
+ description: Resource not found
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
- **Built-in tools** (via `tools/call`):
- `list_my_avatars`, `get_avatar`, `search_public_avatars`,
- `render_avatar`, `delete_avatar`.
+ TooManyRequests:
+ description: Rate limit exceeded
+ headers:
+ Retry-After:
+ schema:
+ type: integer
+ description: Seconds to wait before retrying
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
+ InternalServerError:
+ description: Unexpected server error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
- Rate limits: **600 req/min per IP**, **1 200 req/min per user**.
- security:
- - bearerAuth: []
- requestBody:
- required: true
- content:
- application/json:
- schema:
- oneOf:
- - $ref: '#/components/schemas/JsonRpcRequest'
- - type: array
- items:
- $ref: '#/components/schemas/JsonRpcRequest'
- examples:
- initialize:
- summary: initialize
- value:
- jsonrpc: "2.0"
- id: 1
- method: initialize
- params:
- protocolVersion: "2024-11-05"
- capabilities: {}
- clientInfo:
- name: my-client
- version: "1.0"
- toolsList:
- summary: tools/list
- value:
- jsonrpc: "2.0"
- id: 2
- method: tools/list
- toolCall:
- summary: tools/call — render_avatar
- value:
- jsonrpc: "2.0"
- id: 3
- method: tools/call
- params:
- name: render_avatar
- arguments:
- id: "550e8400-e29b-41d4-a716-446655440000"
- responses:
- "200":
- description: JSON-RPC response (single or batch)
- content:
- application/json:
- schema:
- oneOf:
- - $ref: '#/components/schemas/JsonRpcResponse'
- - type: array
- items:
- $ref: '#/components/schemas/JsonRpcResponse'
- "401":
- $ref: '#/components/responses/Unauthorized'
- "429":
- $ref: '#/components/responses/TooManyRequests'
+# ==========================================================================
+# Paths
+# ==========================================================================
+paths:
+ # --------------------------------------------------------------------------
+ # Root
+ # --------------------------------------------------------------------------
+ /:
+ get:
+ operationId: viewHomepage
+ summary: Load the 3D model viewer interface
+ description: >
+ Returns the main viewer page where users can drag-and-drop glTF/GLB
+ 3D models for instant preview.
+ responses:
+ '200':
+ description: The 3D viewer HTML page.
- get:
- operationId: mcpSseStream
- tags: [MCP]
- summary: MCP SSE stream (reserved — not yet implemented)
- security:
- - bearerAuth: []
- responses:
- "405":
- description: Not yet implemented
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/Error'
+ # --------------------------------------------------------------------------
+ # Auth
+ # --------------------------------------------------------------------------
+ /api/auth/register:
+ post:
+ operationId: registerUser
+ tags: [Auth]
+ summary: Register a new user account
+ description: >
+ Creates a user account, hashes the password, opens a session, and sets
+ the `sid` cookie. Rate-limited to **5 requests per IP per hour**.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [email, password]
+ properties:
+ email:
+ type: string
+ format: email
+ maxLength: 254
+ password:
+ type: string
+ minLength: 10
+ maxLength: 200
+ display_name:
+ type: string
+ minLength: 1
+ maxLength: 80
+ responses:
+ '201':
+ description: Account created
+ headers:
+ Set-Cookie:
+ description: HttpOnly session cookie (`sid`)
+ schema:
+ type: string
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ user:
+ $ref: '#/components/schemas/User'
+ '400':
+ description: Validation error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
+ '409':
+ description: Email already registered
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
+ example:
+ error: email_taken
+ error_description: An account with that email already exists
+ '429':
+ $ref: '#/components/responses/TooManyRequests'
- delete:
- operationId: mcpTerminateSession
- tags: [MCP]
- summary: Terminate MCP session (no-op — server is stateless)
- security:
- - bearerAuth: []
- responses:
- "204":
- description: Session terminated (stateless; nothing to tear down)
+ /api/auth/login:
+ post:
+ operationId: loginUser
+ tags: [Auth]
+ summary: Log in with email and password
+ description: >
+ Verifies credentials, creates a session, and sets the `sid` cookie.
+ Rate-limited to **30 requests per IP per 10 minutes**.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [email, password]
+ properties:
+ email:
+ type: string
+ format: email
+ password:
+ type: string
+ responses:
+ '200':
+ description: Login successful
+ headers:
+ Set-Cookie:
+ description: HttpOnly session cookie (`sid`)
+ schema:
+ type: string
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ user:
+ $ref: '#/components/schemas/User'
+ '401':
+ description: Invalid credentials
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
+ '429':
+ $ref: '#/components/responses/TooManyRequests'
- # --------------------------------------------------------------------------
- # Usage
- # --------------------------------------------------------------------------
- /api/usage/summary:
- get:
- operationId: getUsageSummary
- tags: [Usage]
- summary: Get usage statistics and quota limits for the current account
- security:
- - cookieAuth: []
- - bearerAuth: []
- responses:
- "200":
- description: Usage summary
- content:
- application/json:
- schema:
- type: object
- required: [plan, counts]
- properties:
- plan:
- $ref: '#/components/schemas/PlanQuota'
- counts:
- $ref: '#/components/schemas/UsageCounts'
- "401":
- $ref: '#/components/responses/Unauthorized'
+ /api/auth/me:
+ get:
+ operationId: getCurrentUser
+ tags: [Auth]
+ summary: Get the currently authenticated user
+ security:
+ - cookieAuth: []
+ responses:
+ '200':
+ description: Authenticated user profile
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ user:
+ $ref: '#/components/schemas/User'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
- # --------------------------------------------------------------------------
- # Discovery — well-known endpoints
- # --------------------------------------------------------------------------
- /.well-known/oauth-authorization-server:
- get:
- operationId: oauthAuthorizationServerMetadata
- tags: [Discovery]
- summary: OAuth 2.0 Authorization Server Metadata (RFC 8414)
- description: Cached for 300 seconds.
- responses:
- "200":
- description: Authorization server metadata
- headers:
- Cache-Control:
- schema:
- type: string
- example: public, max-age=300
- content:
- application/json:
- schema:
- type: object
- properties:
- issuer:
- type: string
- format: uri
- authorization_endpoint:
- type: string
- format: uri
- token_endpoint:
- type: string
- format: uri
- registration_endpoint:
- type: string
- format: uri
- revocation_endpoint:
- type: string
- format: uri
- introspection_endpoint:
- type: string
- format: uri
- response_types_supported:
- type: array
- items:
- type: string
- grant_types_supported:
- type: array
- items:
- type: string
- code_challenge_methods_supported:
- type: array
- items:
+ /api/auth/logout:
+ post:
+ operationId: logoutUser
+ tags: [Auth]
+ summary: Invalidate the current session
+ security:
+ - cookieAuth: []
+ responses:
+ '200':
+ description: Session revoked
+ headers:
+ Set-Cookie:
+ description: Clears the `sid` cookie
+ schema:
+ type: string
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ ok:
+ type: boolean
+ example: true
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+
+ # --------------------------------------------------------------------------
+ # Avatars
+ # --------------------------------------------------------------------------
+ /api/avatars:
+ get:
+ operationId: listAvatars
+ tags: [Avatars]
+ summary: List avatars owned by the authenticated user
+ security:
+ - cookieAuth: []
+ - bearerAuth: []
+ parameters:
+ - name: limit
+ in: query
+ schema:
+ type: integer
+ minimum: 1
+ maximum: 200
+ default: 50
+ - name: cursor
+ in: query
+ description: Pagination cursor (ISO-8601 timestamp from previous `next_cursor`)
+ schema:
+ $ref: '#/components/schemas/Cursor'
+ - name: visibility
+ in: query
+ schema:
type: string
- token_endpoint_auth_methods_supported:
- type: array
- items:
+ enum: [private, unlisted, public]
+ - name: include_public
+ in: query
+ description: When `true`, also returns all public avatars
+ schema:
type: string
- scopes_supported:
- type: array
- items:
+ enum: ['true', 'false']
+ responses:
+ '200':
+ description: Paginated avatar list
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ avatars:
+ type: array
+ items:
+ $ref: '#/components/schemas/Avatar'
+ next_cursor:
+ $ref: '#/components/schemas/Cursor'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+
+ post:
+ operationId: createAvatar
+ tags: [Avatars]
+ summary: Create an avatar record after uploading the file to R2
+ description: >
+ Call `POST /api/avatars/presign` first to get a presigned upload URL,
+ upload the GLB file directly to R2, then call this endpoint to register
+ the avatar.
+ security:
+ - cookieAuth: []
+ - bearerAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [name, storage_key, size_bytes]
+ properties:
+ name:
+ type: string
+ minLength: 1
+ maxLength: 120
+ slug:
+ type: string
+ minLength: 1
+ maxLength: 64
+ pattern: '^[a-z0-9_-]+$'
+ description:
+ type: string
+ maxLength: 2000
+ visibility:
+ type: string
+ enum: [private, unlisted, public]
+ default: private
+ tags:
+ type: array
+ maxItems: 20
+ items:
+ type: string
+ maxLength: 40
+ source:
+ type: string
+ enum: [upload, avaturn, import]
+ default: upload
+ source_meta:
+ type: object
+ additionalProperties: true
+ content_type:
+ type: string
+ default: model/gltf-binary
+ size_bytes:
+ type: integer
+ minimum: 1
+ maximum: 524288000
+ description: File size in bytes (max 500 MB)
+ checksum_sha256:
+ type: string
+ pattern: '^[0-9a-f]{64}$'
+ storage_key:
+ type: string
+ description: R2 object key returned by /api/avatars/presign
+ responses:
+ '201':
+ description: Avatar record created
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ avatar:
+ $ref: '#/components/schemas/Avatar'
+ '400':
+ description: Validation error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '403':
+ $ref: '#/components/responses/Forbidden'
+ '500':
+ $ref: '#/components/responses/InternalServerError'
+
+ /api/avatars/public:
+ get:
+ operationId: searchPublicAvatars
+ tags: [Avatars]
+ summary: Search public avatars (no authentication required)
+ description: >
+ Full-text search over public avatars. Results are cached for 60 seconds.
+ parameters:
+ - name: q
+ in: query
+ description: Free-text search query
+ schema:
type: string
- service_documentation:
- type: string
- format: uri
- ui_locales_supported:
- type: array
- items:
+ - name: tag
+ in: query
+ description: Filter by a single tag
+ schema:
type: string
+ - name: limit
+ in: query
+ schema:
+ type: integer
+ minimum: 1
+ maximum: 100
+ default: 24
+ - name: cursor
+ in: query
+ description: Pagination cursor (ISO-8601 timestamp from previous `next_cursor`)
+ schema:
+ $ref: '#/components/schemas/Cursor'
+ responses:
+ '200':
+ description: Paginated public avatar list
+ headers:
+ Cache-Control:
+ schema:
+ type: string
+ example: public, max-age=60
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ avatars:
+ type: array
+ items:
+ $ref: '#/components/schemas/Avatar'
+ next_cursor:
+ $ref: '#/components/schemas/Cursor'
- /.well-known/oauth-protected-resource:
- get:
- operationId: oauthProtectedResourceMetadata
- tags: [Discovery]
- summary: OAuth 2.0 Protected Resource Metadata (RFC 9728)
- description: Cached for 300 seconds.
- responses:
- "200":
- description: Protected resource metadata
- headers:
- Cache-Control:
- schema:
- type: string
- example: public, max-age=300
- content:
- application/json:
+ /api/avatars/presign:
+ post:
+ operationId: presignAvatarUpload
+ tags: [Avatars]
+ summary: Get a presigned URL for uploading a GLB file directly to R2
+ description: >
+ Rate-limited to **60 requests per user per hour**. Use the returned
+ `upload_url` with an HTTP PUT request (include the `content-type`
+ header). After the upload succeeds, call `POST /api/avatars` with
+ the returned `storage_key`.
+ security:
+ - cookieAuth: []
+ - bearerAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [size_bytes]
+ properties:
+ size_bytes:
+ type: integer
+ minimum: 1
+ maximum: 524288000
+ description: File size in bytes (max 500 MB)
+ content_type:
+ type: string
+ default: model/gltf-binary
+ checksum_sha256:
+ type: string
+ pattern: '^[0-9a-f]{64}$'
+ slug:
+ type: string
+ minLength: 1
+ maxLength: 64
+ pattern: '^[a-z0-9_-]+$'
+ responses:
+ '200':
+ description: Presigned upload details
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [storage_key, upload_url, method, headers, expires_in]
+ properties:
+ storage_key:
+ type: string
+ description: R2 object key to pass to POST /api/avatars
+ upload_url:
+ type: string
+ format: uri
+ description: Presigned R2 PUT URL
+ method:
+ type: string
+ enum: [PUT]
+ headers:
+ type: object
+ description: Headers to include in the PUT request
+ additionalProperties:
+ type: string
+ example:
+ content-type: model/gltf-binary
+ expires_in:
+ type: integer
+ example: 300
+ description: Seconds until the presigned URL expires
+ '400':
+ description: Validation error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '429':
+ $ref: '#/components/responses/TooManyRequests'
+
+ /api/avatars/{id}:
+ parameters:
+ - name: id
+ in: path
+ required: true
schema:
- type: object
- properties:
- resource:
- type: string
- format: uri
- authorization_servers:
- type: array
- items:
+ type: string
+ format: uuid
+
+ get:
+ operationId: getAvatar
+ tags: [Avatars]
+ summary: Get a single avatar by ID
+ description: >
+ Returns metadata plus a time-limited (or permanent CDN) URL for the
+ GLB file. Private avatars are only accessible to their owner. Records a
+ `avatar_fetch` usage event.
+ security:
+ - {}
+ - cookieAuth: []
+ - bearerAuth: []
+ responses:
+ '200':
+ description: Avatar details with download URL
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ avatar:
+ $ref: '#/components/schemas/AvatarWithUrl'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '404':
+ $ref: '#/components/responses/NotFound'
+
+ patch:
+ operationId: updateAvatar
+ tags: [Avatars]
+ summary: Update avatar metadata (partial update)
+ security:
+ - cookieAuth: []
+ - bearerAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ name:
+ type: string
+ minLength: 1
+ maxLength: 120
+ description:
+ type: string
+ maxLength: 2000
+ visibility:
+ type: string
+ enum: [private, unlisted, public]
+ tags:
+ type: array
+ maxItems: 20
+ items:
+ type: string
+ maxLength: 40
+ responses:
+ '200':
+ description: Updated avatar
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ avatar:
+ $ref: '#/components/schemas/Avatar'
+ '400':
+ description: Validation error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '404':
+ $ref: '#/components/responses/NotFound'
+
+ delete:
+ operationId: deleteAvatar
+ tags: [Avatars]
+ summary: Delete an avatar (soft delete + queued R2 removal)
+ security:
+ - cookieAuth: []
+ - bearerAuth: []
+ responses:
+ '200':
+ description: Avatar deleted
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ ok:
+ type: boolean
+ example: true
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '404':
+ $ref: '#/components/responses/NotFound'
+
+ # --------------------------------------------------------------------------
+ # API Keys
+ # --------------------------------------------------------------------------
+ /api/keys:
+ get:
+ operationId: listApiKeys
+ tags: [Keys]
+ summary: List API keys for the authenticated user
+ security:
+ - cookieAuth: []
+ responses:
+ '200':
+ description: List of API keys (secrets never returned after creation)
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ keys:
+ type: array
+ items:
+ $ref: '#/components/schemas/ApiKey'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+
+ post:
+ operationId: createApiKey
+ tags: [Keys]
+ summary: Create a new API key
+ description: >
+ The `secret` field in the response is the only time the plaintext key
+ is returned — store it immediately.
+ security:
+ - cookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [name]
+ properties:
+ name:
+ type: string
+ minLength: 1
+ maxLength: 80
+ scope:
+ type: string
+ default: 'avatars:read avatars:write'
+ description: >
+ Space-separated list of scopes. Valid values:
+ `avatars:read`, `avatars:write`, `avatars:delete`, `profile`.
+ expires_in_days:
+ type: integer
+ minimum: 1
+ maximum: 3650
+ description: Key TTL in days (omit for no expiry)
+ environment:
+ type: string
+ enum: [live, test]
+ default: live
+ responses:
+ '201':
+ description: API key created (secret visible only once)
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ key:
+ allOf:
+ - $ref: '#/components/schemas/ApiKey'
+ - type: object
+ properties:
+ secret:
+ type: string
+ description: >
+ Full plaintext API key (e.g. `sk_live_…`).
+ Only returned on creation.
+ example: sk_live_Ab3dXYZ...
+ '400':
+ description: Validation error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+
+ /api/keys/{id}:
+ delete:
+ operationId: revokeApiKey
+ tags: [Keys]
+ summary: Revoke an API key by ID
+ security:
+ - cookieAuth: []
+ parameters:
+ - name: id
+ in: path
+ required: true
+ schema:
+ type: string
+ format: uuid
+ responses:
+ '200':
+ description: Key revoked
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ ok:
+ type: boolean
+ example: true
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '404':
+ $ref: '#/components/responses/NotFound'
+
+ # --------------------------------------------------------------------------
+ # OAuth 2.1
+ # --------------------------------------------------------------------------
+ /api/oauth/register:
+ post:
+ operationId: oauthDynamicClientRegistration
+ tags: [OAuth]
+ summary: Dynamic client registration (RFC 7591)
+ description: >
+ Registers a new OAuth client. Clients with `redirect_uris` pointing to
+ `localhost` or with `token_endpoint_auth_method: none` are treated as
+ **public** clients; all others are **confidential** and receive a
+ `client_secret`.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [redirect_uris]
+ properties:
+ redirect_uris:
+ type: array
+ minItems: 1
+ maxItems: 10
+ items:
+ type: string
+ format: uri
+ client_name:
+ type: string
+ client_uri:
+ type: string
+ format: uri
+ logo_uri:
+ type: string
+ format: uri
+ scope:
+ type: string
+ example: avatars:read avatars:write
+ grant_types:
+ type: array
+ items:
+ type: string
+ enum: [authorization_code, refresh_token]
+ response_types:
+ type: array
+ items:
+ type: string
+ enum: [code]
+ token_endpoint_auth_method:
+ type: string
+ enum: [none, client_secret_basic, client_secret_post]
+ software_id:
+ type: string
+ software_version:
+ type: string
+ responses:
+ '201':
+ description: Client registered
+ content:
+ application/json:
+ schema:
+ type: object
+ required:
+ [
+ client_id,
+ client_id_issued_at,
+ redirect_uris,
+ grant_types,
+ response_types,
+ scope,
+ token_endpoint_auth_method,
+ ]
+ properties:
+ client_id:
+ type: string
+ example: mcp_Ab3dXYZ
+ client_secret:
+ type: string
+ description: Only present for confidential clients
+ client_id_issued_at:
+ type: integer
+ description: Unix timestamp
+ token_endpoint_auth_method:
+ type: string
+ redirect_uris:
+ type: array
+ items:
+ type: string
+ format: uri
+ grant_types:
+ type: array
+ items:
+ type: string
+ response_types:
+ type: array
+ items:
+ type: string
+ scope:
+ type: string
+ client_name:
+ type: string
+ '400':
+ description: Invalid registration request
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/OAuthError'
+
+ /api/oauth/authorize:
+ get:
+ operationId: oauthAuthorize
+ tags: [OAuth]
+ summary: Authorization endpoint — show consent screen
+ description: >
+ If the user is not authenticated they are redirected to the login page.
+ On success, displays an HTML consent form. Requires PKCE with
+ `code_challenge_method=S256`.
+ parameters:
+ - name: response_type
+ in: query
+ required: true
+ schema:
+ type: string
+ enum: [code]
+ - name: client_id
+ in: query
+ required: true
+ schema:
+ type: string
+ - name: redirect_uri
+ in: query
+ required: true
+ schema:
type: string
format: uri
- bearer_methods_supported:
- type: array
- items:
+ - name: scope
+ in: query
+ schema:
type: string
- resource_documentation:
- type: string
- format: uri
- scopes_supported:
- type: array
- items:
+ example: avatars:read avatars:write
+ - name: state
+ in: query
+ schema:
+ type: string
+ - name: code_challenge
+ in: query
+ required: true
+ schema:
+ type: string
+ description: Base64url-encoded SHA-256 of the code_verifier (PKCE)
+ - name: code_challenge_method
+ in: query
+ required: true
+ schema:
type: string
+ enum: [S256]
+ - name: resource
+ in: query
+ schema:
+ type: string
+ format: uri
+ description: RFC 8707 resource indicator
+ responses:
+ '200':
+ description: HTML consent form
+ content:
+ text/html:
+ schema:
+ type: string
+ '302':
+ description: Redirect to login (if unauthenticated) or error redirect
+ headers:
+ Location:
+ schema:
+ type: string
+ '400':
+ description: Invalid authorization request
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/OAuthError'
- /.well-known/agent-card.json:
- get:
- operationId: getAgentCard
- tags: [Discovery]
- summary: Agent Card — A2A protocol agent description
- responses:
- "200":
- description: Agent card JSON
- content:
- application/json:
- schema:
- type: object
- additionalProperties: true
+ post:
+ operationId: oauthAuthorizeDecision
+ tags: [OAuth]
+ summary: Submit consent form decision (allow or deny)
+ security:
+ - cookieAuth: []
+ requestBody:
+ required: true
+ content:
+ application/x-www-form-urlencoded:
+ schema:
+ type: object
+ required:
+ [
+ decision,
+ client_id,
+ redirect_uri,
+ code_challenge,
+ code_challenge_method,
+ ]
+ properties:
+ decision:
+ type: string
+ enum: [allow, deny]
+ response_type:
+ type: string
+ enum: [code]
+ client_id:
+ type: string
+ redirect_uri:
+ type: string
+ format: uri
+ scope:
+ type: string
+ state:
+ type: string
+ code_challenge:
+ type: string
+ code_challenge_method:
+ type: string
+ enum: [S256]
+ resource:
+ type: string
+ responses:
+ '302':
+ description: >
+ Redirect to `redirect_uri?code=CODE&state=STATE` (allow) or
+ `redirect_uri?error=access_denied&state=STATE` (deny)
+ headers:
+ Location:
+ schema:
+ type: string
- /.well-known/agent-registration.json:
- get:
- operationId: getAgentRegistration
- tags: [Discovery]
- summary: Agent registration manifest
- responses:
- "200":
- description: Agent registration JSON
- content:
- application/json:
- schema:
- type: object
- additionalProperties: true
+ /api/oauth/token:
+ post:
+ operationId: oauthToken
+ tags: [OAuth]
+ summary: Token endpoint — exchange code or refresh token
+ description: >
+ Supports `authorization_code` and `refresh_token` grant types.
+ Confidential clients authenticate via HTTP Basic (preferred) or
+ `client_id` + `client_secret` form fields.
+ Rate-limited to **120 requests per client per minute**.
+ requestBody:
+ required: true
+ content:
+ application/x-www-form-urlencoded:
+ schema:
+ type: object
+ required: [grant_type]
+ properties:
+ grant_type:
+ type: string
+ enum: [authorization_code, refresh_token]
+ code:
+ type: string
+ description: Required for authorization_code grant
+ redirect_uri:
+ type: string
+ format: uri
+ description: Required for authorization_code grant; must match the authorization request
+ code_verifier:
+ type: string
+ description: PKCE verifier; required for authorization_code grant
+ refresh_token:
+ type: string
+ description: Required for refresh_token grant
+ scope:
+ type: string
+ description: Optional subset scope for refresh_token grant
+ client_id:
+ type: string
+ client_secret:
+ type: string
+ description: Required for confidential clients not using HTTP Basic
+ responses:
+ '200':
+ description: Token response
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [access_token, token_type, expires_in, scope]
+ properties:
+ access_token:
+ type: string
+ description: JWT access token (1 h TTL)
+ token_type:
+ type: string
+ enum: [Bearer]
+ expires_in:
+ type: integer
+ example: 3600
+ scope:
+ type: string
+ refresh_token:
+ type: string
+ description: Opaque refresh token (30 d TTL, rotated on use)
+ '400':
+ description: Invalid request
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/OAuthError'
+ '401':
+ description: Invalid client credentials or grant
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/OAuthError'
+ '429':
+ $ref: '#/components/responses/TooManyRequests'
- /.well-known/ai-plugin.json:
- get:
- operationId: getAiPlugin
- tags: [Discovery]
- summary: AI plugin manifest (ChatGPT / OpenAI plugin format)
- responses:
- "200":
- description: Plugin manifest JSON
- content:
- application/json:
- schema:
- type: object
- additionalProperties: true
+ /api/oauth/revoke:
+ post:
+ operationId: oauthRevoke
+ tags: [OAuth]
+ summary: Token revocation endpoint (RFC 7009)
+ description: >
+ Revokes an access token or refresh token. Always returns 200 per the
+ RFC, even if the token is unknown or already revoked.
+ requestBody:
+ required: true
+ content:
+ application/x-www-form-urlencoded:
+ schema:
+ type: object
+ required: [token]
+ properties:
+ token:
+ type: string
+ token_type_hint:
+ type: string
+ enum: [access_token, refresh_token]
+ client_id:
+ type: string
+ client_secret:
+ type: string
+ responses:
+ '200':
+ description: Revocation accepted (per RFC 7009, always 200)
+ content:
+ application/json:
+ schema:
+ type: object
+ example: {}
- /.well-known/openapi.yaml:
- get:
- operationId: getOpenApiSpec
- tags: [Discovery]
- summary: This OpenAPI specification
- responses:
- "200":
- description: OpenAPI 3.0 YAML document
- content:
- application/yaml:
- schema:
- type: string
+ /api/oauth/introspect:
+ post:
+ operationId: oauthIntrospect
+ tags: [OAuth]
+ summary: Token introspection endpoint (RFC 7662)
+ description: >
+ Returns metadata about a token. Confidential clients authenticate via
+ HTTP Basic or `client_id`/`client_secret` form fields.
+ requestBody:
+ required: true
+ content:
+ application/x-www-form-urlencoded:
+ schema:
+ type: object
+ required: [token]
+ properties:
+ token:
+ type: string
+ client_id:
+ type: string
+ client_secret:
+ type: string
+ responses:
+ '200':
+ description: Token metadata
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [active]
+ properties:
+ active:
+ type: boolean
+ scope:
+ type: string
+ client_id:
+ type: string
+ sub:
+ type: string
+ format: uuid
+ description: User ID
+ token_type:
+ type: string
+ enum: [Bearer, refresh_token]
+ aud:
+ type: string
+ iss:
+ type: string
+ format: uri
+ exp:
+ type: integer
+ description: Unix expiry timestamp
+ iat:
+ type: integer
+ description: Unix issued-at timestamp
+
+ # --------------------------------------------------------------------------
+ # MCP (Model Context Protocol)
+ # --------------------------------------------------------------------------
+ /api/mcp:
+ post:
+ operationId: mcpJsonRpc
+ tags: [MCP]
+ summary: MCP JSON-RPC 2.0 endpoint
+ description: >
+ Stateless JSON-RPC 2.0 endpoint implementing the [Model Context
+ Protocol](https://modelcontextprotocol.io). Accepts single or batched
+ requests. Authenticated with an OAuth 2.1 access token **or** an API
+ key in the `Authorization: Bearer …` header.
+
+
+ **Supported methods:**
+ `initialize`, `tools/list`, `tools/call`, `ping`,
+ `notifications/initialized`, `resources/list`,
+ `resources/templates/list`, `prompts/list`, `logging/setLevel`.
+
+
+ **Built-in tools** (via `tools/call`):
+ `list_my_avatars`, `get_avatar`, `search_public_avatars`,
+ `render_avatar`, `delete_avatar`.
+
+
+ Rate limits: **600 req/min per IP**, **1 200 req/min per user**.
+ security:
+ - bearerAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ oneOf:
+ - $ref: '#/components/schemas/JsonRpcRequest'
+ - type: array
+ items:
+ $ref: '#/components/schemas/JsonRpcRequest'
+ examples:
+ initialize:
+ summary: initialize
+ value:
+ jsonrpc: '2.0'
+ id: 1
+ method: initialize
+ params:
+ protocolVersion: '2024-11-05'
+ capabilities: {}
+ clientInfo:
+ name: my-client
+ version: '1.0'
+ toolsList:
+ summary: tools/list
+ value:
+ jsonrpc: '2.0'
+ id: 2
+ method: tools/list
+ toolCall:
+ summary: tools/call — render_avatar
+ value:
+ jsonrpc: '2.0'
+ id: 3
+ method: tools/call
+ params:
+ name: render_avatar
+ arguments:
+ id: '550e8400-e29b-41d4-a716-446655440000'
+ responses:
+ '200':
+ description: JSON-RPC response (single or batch)
+ content:
+ application/json:
+ schema:
+ oneOf:
+ - $ref: '#/components/schemas/JsonRpcResponse'
+ - type: array
+ items:
+ $ref: '#/components/schemas/JsonRpcResponse'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+ '429':
+ $ref: '#/components/responses/TooManyRequests'
+
+ get:
+ operationId: mcpSseStream
+ tags: [MCP]
+ summary: MCP SSE stream (reserved — not yet implemented)
+ security:
+ - bearerAuth: []
+ responses:
+ '405':
+ description: Not yet implemented
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Error'
+
+ delete:
+ operationId: mcpTerminateSession
+ tags: [MCP]
+ summary: Terminate MCP session (no-op — server is stateless)
+ security:
+ - bearerAuth: []
+ responses:
+ '204':
+ description: Session terminated (stateless; nothing to tear down)
+
+ # --------------------------------------------------------------------------
+ # Usage
+ # --------------------------------------------------------------------------
+ /api/usage/summary:
+ get:
+ operationId: getUsageSummary
+ tags: [Usage]
+ summary: Get usage statistics and quota limits for the current account
+ security:
+ - cookieAuth: []
+ - bearerAuth: []
+ responses:
+ '200':
+ description: Usage summary
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [plan, counts]
+ properties:
+ plan:
+ $ref: '#/components/schemas/PlanQuota'
+ counts:
+ $ref: '#/components/schemas/UsageCounts'
+ '401':
+ $ref: '#/components/responses/Unauthorized'
+
+ # --------------------------------------------------------------------------
+ # Discovery — well-known endpoints
+ # --------------------------------------------------------------------------
+ /.well-known/oauth-authorization-server:
+ get:
+ operationId: oauthAuthorizationServerMetadata
+ tags: [Discovery]
+ summary: OAuth 2.0 Authorization Server Metadata (RFC 8414)
+ description: Cached for 300 seconds.
+ responses:
+ '200':
+ description: Authorization server metadata
+ headers:
+ Cache-Control:
+ schema:
+ type: string
+ example: public, max-age=300
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ issuer:
+ type: string
+ format: uri
+ authorization_endpoint:
+ type: string
+ format: uri
+ token_endpoint:
+ type: string
+ format: uri
+ registration_endpoint:
+ type: string
+ format: uri
+ revocation_endpoint:
+ type: string
+ format: uri
+ introspection_endpoint:
+ type: string
+ format: uri
+ response_types_supported:
+ type: array
+ items:
+ type: string
+ grant_types_supported:
+ type: array
+ items:
+ type: string
+ code_challenge_methods_supported:
+ type: array
+ items:
+ type: string
+ token_endpoint_auth_methods_supported:
+ type: array
+ items:
+ type: string
+ scopes_supported:
+ type: array
+ items:
+ type: string
+ service_documentation:
+ type: string
+ format: uri
+ ui_locales_supported:
+ type: array
+ items:
+ type: string
+
+ /.well-known/oauth-protected-resource:
+ get:
+ operationId: oauthProtectedResourceMetadata
+ tags: [Discovery]
+ summary: OAuth 2.0 Protected Resource Metadata (RFC 9728)
+ description: Cached for 300 seconds.
+ responses:
+ '200':
+ description: Protected resource metadata
+ headers:
+ Cache-Control:
+ schema:
+ type: string
+ example: public, max-age=300
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ resource:
+ type: string
+ format: uri
+ authorization_servers:
+ type: array
+ items:
+ type: string
+ format: uri
+ bearer_methods_supported:
+ type: array
+ items:
+ type: string
+ resource_documentation:
+ type: string
+ format: uri
+ scopes_supported:
+ type: array
+ items:
+ type: string
+
+ /.well-known/agent-card.json:
+ get:
+ operationId: getAgentCard
+ tags: [Discovery]
+ summary: Agent Card — A2A protocol agent description
+ responses:
+ '200':
+ description: Agent card JSON
+ content:
+ application/json:
+ schema:
+ type: object
+ additionalProperties: true
+
+ /.well-known/agent-registration.json:
+ get:
+ operationId: getAgentRegistration
+ tags: [Discovery]
+ summary: Agent registration manifest
+ responses:
+ '200':
+ description: Agent registration JSON
+ content:
+ application/json:
+ schema:
+ type: object
+ additionalProperties: true
+
+ /.well-known/ai-plugin.json:
+ get:
+ operationId: getAiPlugin
+ tags: [Discovery]
+ summary: AI plugin manifest (ChatGPT / OpenAI plugin format)
+ responses:
+ '200':
+ description: Plugin manifest JSON
+ content:
+ application/json:
+ schema:
+ type: object
+ additionalProperties: true
+
+ /.well-known/openapi.yaml:
+ get:
+ operationId: getOpenApiSpec
+ tags: [Discovery]
+ summary: This OpenAPI specification
+ responses:
+ '200':
+ description: OpenAPI 3.0 YAML document
+ content:
+ application/yaml:
+ schema:
+ type: string
diff --git a/public/agent-edit/edit.js b/public/agent-edit/edit.js
index 8e5b045f2..79cfbf0cd 100644
--- a/public/agent-edit/edit.js
+++ b/public/agent-edit/edit.js
@@ -18,11 +18,11 @@ let _saveDebounce = null;
// Voice picker state — managed separately from persona so changes survive
// template resets.
-let _voiceProvider = 'web'; // 'web' | 'eleven'
-let _voiceId = null; // voice name (web) or voice_id (eleven)
+let _voiceProvider = 'web'; // 'web' | 'eleven'
+let _voiceId = null; // voice name (web) or voice_id (eleven)
let _elevenEnabled = false;
-let _elevenLoaded = false;
-let _webVoices = [];
+let _elevenLoaded = false;
+let _webVoices = [];
// ── Bootstrap ──────────────────────────────────────────────────────────────
@@ -56,7 +56,7 @@ async function main() {
// Restore voice config from meta
const voiceMeta = agent.meta?.voice || {};
_voiceProvider = voiceMeta.provider === 'eleven' ? 'eleven' : 'web';
- _voiceId = voiceMeta.voiceId || null;
+ _voiceId = voiceMeta.voiceId || null;
// Render
document.getElementById('loading-screen').style.display = 'none';
@@ -271,7 +271,9 @@ function initVoicePicker() {
function setVoiceProvider(p) {
if (p === 'eleven' && !_elevenEnabled) return;
_voiceProvider = p;
- document.querySelectorAll('.vp-toggle-btn').forEach((b) => b.classList.toggle('active', b.dataset.vp === p));
+ document
+ .querySelectorAll('.vp-toggle-btn')
+ .forEach((b) => b.classList.toggle('active', b.dataset.vp === p));
renderVoiceSection();
}
@@ -279,7 +281,7 @@ function renderVoiceSection() {
const wrap = document.getElementById('vp-list-wrap');
if (!wrap) return;
wrap.innerHTML = '';
- if (_voiceProvider === 'web') renderWebVoices(wrap);
+ if (_voiceProvider === 'web') renderWebVoices(wrap);
if (_voiceProvider === 'eleven') renderElevenVoices(wrap);
}
@@ -303,16 +305,20 @@ function renderWebVoices(wrap) {
const list = document.createElement('div');
list.className = 'vp-list';
- for (const [lang, voices] of Object.entries(groups).sort(([a], [b]) => a.localeCompare(b))) {
+ for (const [lang, voices] of Object.entries(groups).sort(([a], [b]) =>
+ a.localeCompare(b),
+ )) {
const label = document.createElement('div');
label.className = 'vp-group-label';
label.textContent = lang;
list.appendChild(label);
for (const v of voices) {
const selected = _voiceProvider === 'web' && _voiceId === v.name;
- list.appendChild(buildVoiceItem(v.name, v.name, v.lang, selected, (btn) => {
- previewWebVoice(v.name, btn);
- }));
+ list.appendChild(
+ buildVoiceItem(v.name, v.name, v.lang, selected, (btn) => {
+ previewWebVoice(v.name, btn);
+ }),
+ );
}
}
wrap.innerHTML = '';
@@ -320,7 +326,10 @@ function renderWebVoices(wrap) {
};
const voices = window.speechSynthesis.getVoices();
- if (voices.length) { doRender(); return; }
+ if (voices.length) {
+ doRender();
+ return;
+ }
window.speechSynthesis.addEventListener('voiceschanged', doRender, { once: true });
setTimeout(doRender, 250); // fallback for browsers that don't fire voiceschanged
}
@@ -328,7 +337,8 @@ function renderWebVoices(wrap) {
// ElevenLabs
async function renderElevenVoices(wrap) {
if (!_elevenEnabled) {
- wrap.innerHTML = '<div class="vp-empty">ElevenLabs API key not configured on this server.</div>';
+ wrap.innerHTML =
+ '<div class="vp-empty">ElevenLabs API key not configured on this server.</div>';
return;
}
@@ -353,11 +363,15 @@ async function renderElevenVoices(wrap) {
list.id = 'vp-eleven-list';
for (const v of data.voices) {
- const meta = [v.category, v.labels?.accent, v.labels?.gender].filter(Boolean).join(' · ');
+ const meta = [v.category, v.labels?.accent, v.labels?.gender]
+ .filter(Boolean)
+ .join(' · ');
const selected = _voiceProvider === 'eleven' && _voiceId === v.voice_id;
- list.appendChild(buildVoiceItem(v.voice_id, v.name, meta, selected, (btn) => {
- previewElevenVoice(v.voice_id, btn);
- }));
+ list.appendChild(
+ buildVoiceItem(v.voice_id, v.name, meta, selected, (btn) => {
+ previewElevenVoice(v.voice_id, btn);
+ }),
+ );
}
wrap.innerHTML = '';
@@ -400,7 +414,9 @@ function buildVoiceItem(vid, displayName, meta, selected, previewFn) {
}
function selectVoiceItem(el, vid) {
- el.closest('.vp-list').querySelectorAll('.vp-item').forEach((i) => i.classList.remove('selected'));
+ el.closest('.vp-list')
+ .querySelectorAll('.vp-item')
+ .forEach((i) => i.classList.remove('selected'));
el.classList.add('selected');
_voiceId = vid;
}
@@ -413,8 +429,12 @@ function previewWebVoice(name, btn) {
if (voice) utter.voice = voice;
if (btn) {
btn.disabled = true;
- utter.onend = () => { btn.disabled = false; };
- utter.onerror = () => { btn.disabled = false; };
+ utter.onend = () => {
+ btn.disabled = false;
+ };
+ utter.onerror = () => {
+ btn.disabled = false;
+ };
}
window.speechSynthesis.speak(utter);
}
@@ -423,10 +443,10 @@ async function previewElevenVoice(voiceId, btn) {
if (btn) btn.disabled = true;
try {
const res = await fetch('/api/tts/eleven', {
- method: 'POST',
+ method: 'POST',
credentials: 'include',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ voiceId, text: "Hi, I'm your agent." }),
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ voiceId, text: "Hi, I'm your agent." }),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
@@ -434,9 +454,12 @@ async function previewElevenVoice(voiceId, btn) {
return;
}
const blob = await res.blob();
- const url = URL.createObjectURL(blob);
+ const url = URL.createObjectURL(blob);
const audio = new Audio(url);
- const cleanup = () => { URL.revokeObjectURL(url); if (btn) btn.disabled = false; };
+ const cleanup = () => {
+ URL.revokeObjectURL(url);
+ if (btn) btn.disabled = false;
+ };
audio.addEventListener('ended', cleanup, { once: true });
audio.addEventListener('error', cleanup, { once: true });
await audio.play();
@@ -492,9 +515,9 @@ async function save() {
await apiFetch(`/api/agents/${encodeURIComponent(agentId)}`, {
method: 'PUT',
body: JSON.stringify({
- name: persona.name,
+ name: persona.name,
description: persona.bio,
- meta: newMeta,
+ meta: newMeta,
}),
});
@@ -594,7 +617,11 @@ function toast(msg, isError = false) {
}
function esc(s) {
- return String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
+ return String(s ?? '')
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;');
}
// ── Boot ───────────────────────────────────────────────────────────────────
diff --git a/public/agent-edit/index.html b/public/agent-edit/index.html
index 536c4fb69..90907bb07 100644
--- a/public/agent-edit/index.html
+++ b/public/agent-edit/index.html
@@ -1,208 +1,661 @@
<!doctype html>
<html lang="en">
-<head>
-<meta charset="utf-8">
-<meta name="viewport" content="width=device-width,initial-scale=1">
-<title>Edit Persona · 3D Agent</title>
-<link rel="icon" href="/favicon.ico">
-<style>
- :root { color-scheme: dark; --accent:#6a5cff; --accent2:#ff5ca8; --border:#22222e; --bg:#0b0b10; --panel:#14141c; }
- * { box-sizing: border-box; }
- body { font:15px/1.55 -apple-system,system-ui,Segoe UI,Roboto,sans-serif; color:#eee; margin:0; background:var(--bg); min-height:100vh; }
- a { color:#9a8cff; text-decoration:none; }
-
- header { display:flex; align-items:center; justify-content:space-between; padding:12px 24px; border-bottom:1px solid var(--border); position:sticky; top:0; background:var(--bg); z-index:10; }
- .header-left { display:flex; align-items:center; gap:14px; }
- .brand { font-weight:600; letter-spacing:-.01em; color:#eee; text-decoration:none; }
- .header-title { font-size:14px; color:#888; }
- .header-actions { display:flex; gap:8px; align-items:center; }
-
- .layout { display:grid; grid-template-columns:1fr 440px; height:calc(100vh - 53px); }
- .preview-pane { border-right:1px solid var(--border); position:relative; background:#080810; }
- .preview-pane iframe { width:100%; height:100%; border:0; display:block; }
- .preview-loading { position:absolute; inset:0; display:grid; place-items:center; color:#555; font-size:13px; }
-
- .editor-pane { overflow-y:auto; padding:22px 24px 60px; }
-
- h2 { font-size:16px; font-weight:600; margin:0 0 4px; }
- .sub { color:#888; font-size:13px; margin:0 0 20px; }
-
- .form-group { margin-bottom:18px; }
- label { display:block; font-size:13px; font-weight:500; color:#bbb; margin-bottom:6px; }
- .label-row { display:flex; justify-content:space-between; align-items:baseline; }
- .char-count { font-size:11px; color:#555; }
- input[type="text"], textarea, select {
- width:100%; background:#0f0f17; border:1px solid var(--border); color:#eee;
- padding:9px 11px; border-radius:8px; font-size:14px; font-family:inherit;
- }
- input[type="text"]:focus, textarea:focus, select:focus { outline:none; border-color:var(--accent); }
- textarea { resize:vertical; }
- textarea.mono { font-family: ui-monospace, SF Mono, Menlo, monospace; font-size:13px; }
-
- .slider-wrap { display:flex; align-items:center; gap:10px; }
- .slider-label { font-size:11px; color:#666; white-space:nowrap; }
- input[type="range"] { flex:1; accent-color:var(--accent); }
- .slider-value { font-size:12px; color:#aaa; min-width:36px; text-align:right; }
-
- .radio-group { display:flex; gap:10px; }
- .radio-group label { display:flex; align-items:center; gap:6px; font-weight:400; color:#ccc; cursor:pointer; }
- .radio-group input { width:auto; accent-color:var(--accent); }
-
- .catchphrase-list { display:flex; flex-direction:column; gap:6px; }
- .catchphrase-row { display:flex; gap:6px; }
- .catchphrase-row input { flex:1; }
- .catchphrase-row button { padding:0 10px; background:#1a1a24; border:1px solid var(--border); color:#888; border-radius:8px; cursor:pointer; font-size:16px; line-height:1; }
- .catchphrase-row button:hover { color:#fff; border-color:#444; }
- .add-catchphrase { margin-top:6px; background:none; border:1px dashed var(--border); color:#666; border-radius:8px; padding:7px; width:100%; cursor:pointer; font-size:13px; }
- .add-catchphrase:hover { border-color:#555; color:#aaa; }
-
- .chip-input-wrap { display:flex; flex-wrap:wrap; gap:6px; background:#0f0f17; border:1px solid var(--border); border-radius:8px; padding:7px 9px; min-height:40px; }
- .chip-input-wrap:focus-within { border-color:var(--accent); }
- .chip { display:inline-flex; align-items:center; gap:4px; background:#20202c; border:1px solid #2c2c3e; border-radius:99px; padding:2px 8px 2px 10px; font-size:12px; color:#ccc; }
- .chip button { background:none; border:0; color:#888; cursor:pointer; font-size:13px; line-height:1; padding:0 1px; }
- .chip button:hover { color:#ff5c5c; }
- .chip-text-input { flex:1; min-width:80px; background:none; border:0; color:#eee; font-size:13px; padding:2px 3px; outline:none; }
-
- .templates { display:flex; gap:8px; margin-bottom:20px; flex-wrap:wrap; }
- .template-btn { padding:7px 13px; background:#14141c; border:1px solid var(--border); color:#aaa; border-radius:99px; cursor:pointer; font-size:13px; font-family:inherit; }
- .template-btn:hover { border-color:#6a5cff; color:#fff; }
-
- .section-divider { border:0; border-top:1px solid var(--border); margin:22px 0; }
-
- .btn { padding:9px 18px; border-radius:9px; border:0; font-size:13px; font-weight:600; cursor:pointer; background:var(--accent); color:#fff; }
- .btn:hover { filter:brightness(1.1); }
- .btn:disabled { opacity:.5; cursor:not-allowed; filter:none; }
- .btn.sec { background:#1e1e2c; color:#ccc; border:1px solid var(--border); }
- .btn.sec:hover { background:#252534; }
-
- .toast { position:fixed; bottom:24px; left:50%; transform:translateX(-50%); background:#1a1a2e; border:1px solid var(--accent); color:#eee; padding:10px 20px; border-radius:10px; font-size:13px; z-index:100; opacity:0; transition:opacity .2s; pointer-events:none; }
- .toast.show { opacity:1; }
- .toast.err { border-color:#cc4040; background:#1e1010; }
-
- .forbidden { display:grid; place-items:center; height:100%; color:#888; font-size:14px; text-align:center; padding:40px; }
- .forbidden h2 { color:#ff5c5c; margin-bottom:8px; }
-
- .reset-btn { font-size:12px; color:#888; background:none; border:0; cursor:pointer; text-decoration:underline; }
- .reset-btn:hover { color:#aaa; }
-
- /* ── Voice picker ──────────────────────────────────────────────────────── */
- .vp-toggle { display:flex; gap:6px; margin-bottom:10px; }
- .vp-toggle-btn { flex:1; padding:7px; background:#0f0f17; border:1px solid var(--border); color:#888; border-radius:8px; cursor:pointer; font-size:13px; font-family:inherit; text-align:center; transition:background .15s,border-color .15s,color .15s; }
- .vp-toggle-btn.active { background:rgba(106,92,255,.15); border-color:rgba(106,92,255,.5); color:#eee; }
- .vp-toggle-btn:disabled { opacity:.35; cursor:not-allowed; }
- .vp-list { border:1px solid var(--border); border-radius:8px; max-height:260px; overflow-y:auto; }
- .vp-group-label { padding:4px 10px; font-size:11px; color:rgba(255,255,255,.2); text-transform:uppercase; letter-spacing:.07em; background:rgba(255,255,255,.02); border-bottom:1px solid rgba(255,255,255,.04); }
- .vp-item { display:flex; align-items:center; gap:8px; padding:8px 10px; border-bottom:1px solid rgba(255,255,255,.04); cursor:pointer; transition:background .1s; }
- .vp-item:last-child { border-bottom:none; }
- .vp-item:hover { background:rgba(255,255,255,.04); }
- .vp-item.selected { background:rgba(106,92,255,.1); }
- .vp-radio { width:13px; height:13px; border-radius:50%; border:1.5px solid #555; flex-shrink:0; position:relative; }
- .vp-item.selected .vp-radio { border-color:var(--accent); background:var(--accent); }
- .vp-item.selected .vp-radio::after { content:''; width:5px; height:5px; border-radius:50%; background:#fff; position:absolute; top:50%; left:50%; transform:translate(-50%,-50%); }
- .vp-name { flex:1; font-size:13px; color:#ccc; }
- .vp-meta { font-size:11px; color:#555; }
- .vp-preview-btn { background:none; border:1px solid var(--border); color:#666; font-size:11px; padding:3px 8px; border-radius:5px; cursor:pointer; font-family:inherit; white-space:nowrap; }
- .vp-preview-btn:hover { color:#ccc; border-color:#444; }
- .vp-preview-btn:disabled { opacity:.4; cursor:not-allowed; }
- .vp-empty { padding:18px; text-align:center; color:#555; font-size:13px; }
-</style>
-</head>
-<body>
-<header>
- <div class="header-left">
- <a class="brand" href="/">3D Agent</a>
- <span class="header-title" id="header-title">Edit Persona</span>
- </div>
- <div class="header-actions">
- <a id="view-link" href="#" class="btn sec" style="text-decoration:none">View page →</a>
- <button id="save-btn" class="btn" disabled>Save</button>
- </div>
-</header>
-
-<div class="layout" id="layout" style="display:none">
- <div class="preview-pane">
- <div class="preview-loading" id="preview-loading">Loading preview…</div>
- <iframe id="preview-frame" title="Agent preview" style="display:none"></iframe>
- </div>
- <div class="editor-pane" id="editor-pane">
- <h2>Persona</h2>
- <p class="sub">Shape how your agent speaks, thinks, and presents itself.</p>
-
- <div class="templates" id="templates-row"></div>
-
- <div class="form-group">
- <div class="label-row">
- <label for="f-name">Name</label>
- <span class="char-count" id="cnt-name">0/40</span>
- </div>
- <input type="text" id="f-name" maxlength="40" placeholder="My Agent" autocomplete="off">
- </div>
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>Edit Persona · 3D Agent</title>
+ <link rel="icon" href="/favicon.ico" />
+ <style>
+ :root {
+ color-scheme: dark;
+ --accent: #6a5cff;
+ --accent2: #ff5ca8;
+ --border: #22222e;
+ --bg: #0b0b10;
+ --panel: #14141c;
+ }
+ * {
+ box-sizing: border-box;
+ }
+ body {
+ font:
+ 15px/1.55 -apple-system,
+ system-ui,
+ Segoe UI,
+ Roboto,
+ sans-serif;
+ color: #eee;
+ margin: 0;
+ background: var(--bg);
+ min-height: 100vh;
+ }
+ a {
+ color: #9a8cff;
+ text-decoration: none;
+ }
+
+ header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 12px 24px;
+ border-bottom: 1px solid var(--border);
+ position: sticky;
+ top: 0;
+ background: var(--bg);
+ z-index: 10;
+ }
+ .header-left {
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ }
+ .brand {
+ font-weight: 600;
+ letter-spacing: -0.01em;
+ color: #eee;
+ text-decoration: none;
+ }
+ .header-title {
+ font-size: 14px;
+ color: #888;
+ }
+ .header-actions {
+ display: flex;
+ gap: 8px;
+ align-items: center;
+ }
+
+ .layout {
+ display: grid;
+ grid-template-columns: 1fr 440px;
+ height: calc(100vh - 53px);
+ }
+ .preview-pane {
+ border-right: 1px solid var(--border);
+ position: relative;
+ background: #080810;
+ }
+ .preview-pane iframe {
+ width: 100%;
+ height: 100%;
+ border: 0;
+ display: block;
+ }
+ .preview-loading {
+ position: absolute;
+ inset: 0;
+ display: grid;
+ place-items: center;
+ color: #555;
+ font-size: 13px;
+ }
+
+ .editor-pane {
+ overflow-y: auto;
+ padding: 22px 24px 60px;
+ }
+
+ h2 {
+ font-size: 16px;
+ font-weight: 600;
+ margin: 0 0 4px;
+ }
+ .sub {
+ color: #888;
+ font-size: 13px;
+ margin: 0 0 20px;
+ }
+
+ .form-group {
+ margin-bottom: 18px;
+ }
+ label {
+ display: block;
+ font-size: 13px;
+ font-weight: 500;
+ color: #bbb;
+ margin-bottom: 6px;
+ }
+ .label-row {
+ display: flex;
+ justify-content: space-between;
+ align-items: baseline;
+ }
+ .char-count {
+ font-size: 11px;
+ color: #555;
+ }
+ input[type='text'],
+ textarea,
+ select {
+ width: 100%;
+ background: #0f0f17;
+ border: 1px solid var(--border);
+ color: #eee;
+ padding: 9px 11px;
+ border-radius: 8px;
+ font-size: 14px;
+ font-family: inherit;
+ }
+ input[type='text']:focus,
+ textarea:focus,
+ select:focus {
+ outline: none;
+ border-color: var(--accent);
+ }
+ textarea {
+ resize: vertical;
+ }
+ textarea.mono {
+ font-family:
+ ui-monospace,
+ SF Mono,
+ Menlo,
+ monospace;
+ font-size: 13px;
+ }
+
+ .slider-wrap {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ }
+ .slider-label {
+ font-size: 11px;
+ color: #666;
+ white-space: nowrap;
+ }
+ input[type='range'] {
+ flex: 1;
+ accent-color: var(--accent);
+ }
+ .slider-value {
+ font-size: 12px;
+ color: #aaa;
+ min-width: 36px;
+ text-align: right;
+ }
+
+ .radio-group {
+ display: flex;
+ gap: 10px;
+ }
+ .radio-group label {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-weight: 400;
+ color: #ccc;
+ cursor: pointer;
+ }
+ .radio-group input {
+ width: auto;
+ accent-color: var(--accent);
+ }
+
+ .catchphrase-list {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ }
+ .catchphrase-row {
+ display: flex;
+ gap: 6px;
+ }
+ .catchphrase-row input {
+ flex: 1;
+ }
+ .catchphrase-row button {
+ padding: 0 10px;
+ background: #1a1a24;
+ border: 1px solid var(--border);
+ color: #888;
+ border-radius: 8px;
+ cursor: pointer;
+ font-size: 16px;
+ line-height: 1;
+ }
+ .catchphrase-row button:hover {
+ color: #fff;
+ border-color: #444;
+ }
+ .add-catchphrase {
+ margin-top: 6px;
+ background: none;
+ border: 1px dashed var(--border);
+ color: #666;
+ border-radius: 8px;
+ padding: 7px;
+ width: 100%;
+ cursor: pointer;
+ font-size: 13px;
+ }
+ .add-catchphrase:hover {
+ border-color: #555;
+ color: #aaa;
+ }
+
+ .chip-input-wrap {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ background: #0f0f17;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 7px 9px;
+ min-height: 40px;
+ }
+ .chip-input-wrap:focus-within {
+ border-color: var(--accent);
+ }
+ .chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ background: #20202c;
+ border: 1px solid #2c2c3e;
+ border-radius: 99px;
+ padding: 2px 8px 2px 10px;
+ font-size: 12px;
+ color: #ccc;
+ }
+ .chip button {
+ background: none;
+ border: 0;
+ color: #888;
+ cursor: pointer;
+ font-size: 13px;
+ line-height: 1;
+ padding: 0 1px;
+ }
+ .chip button:hover {
+ color: #ff5c5c;
+ }
+ .chip-text-input {
+ flex: 1;
+ min-width: 80px;
+ background: none;
+ border: 0;
+ color: #eee;
+ font-size: 13px;
+ padding: 2px 3px;
+ outline: none;
+ }
+
+ .templates {
+ display: flex;
+ gap: 8px;
+ margin-bottom: 20px;
+ flex-wrap: wrap;
+ }
+ .template-btn {
+ padding: 7px 13px;
+ background: #14141c;
+ border: 1px solid var(--border);
+ color: #aaa;
+ border-radius: 99px;
+ cursor: pointer;
+ font-size: 13px;
+ font-family: inherit;
+ }
+ .template-btn:hover {
+ border-color: #6a5cff;
+ color: #fff;
+ }
+
+ .section-divider {
+ border: 0;
+ border-top: 1px solid var(--border);
+ margin: 22px 0;
+ }
+
+ .btn {
+ padding: 9px 18px;
+ border-radius: 9px;
+ border: 0;
+ font-size: 13px;
+ font-weight: 600;
+ cursor: pointer;
+ background: var(--accent);
+ color: #fff;
+ }
+ .btn:hover {
+ filter: brightness(1.1);
+ }
+ .btn:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+ filter: none;
+ }
+ .btn.sec {
+ background: #1e1e2c;
+ color: #ccc;
+ border: 1px solid var(--border);
+ }
+ .btn.sec:hover {
+ background: #252534;
+ }
+
+ .toast {
+ position: fixed;
+ bottom: 24px;
+ left: 50%;
+ transform: translateX(-50%);
+ background: #1a1a2e;
+ border: 1px solid var(--accent);
+ color: #eee;
+ padding: 10px 20px;
+ border-radius: 10px;
+ font-size: 13px;
+ z-index: 100;
+ opacity: 0;
+ transition: opacity 0.2s;
+ pointer-events: none;
+ }
+ .toast.show {
+ opacity: 1;
+ }
+ .toast.err {
+ border-color: #cc4040;
+ background: #1e1010;
+ }
+
+ .forbidden {
+ display: grid;
+ place-items: center;
+ height: 100%;
+ color: #888;
+ font-size: 14px;
+ text-align: center;
+ padding: 40px;
+ }
+ .forbidden h2 {
+ color: #ff5c5c;
+ margin-bottom: 8px;
+ }
- <div class="form-group">
- <div class="label-row">
- <label for="f-bio">Bio</label>
- <span class="char-count" id="cnt-bio">0/280</span>
+ .reset-btn {
+ font-size: 12px;
+ color: #888;
+ background: none;
+ border: 0;
+ cursor: pointer;
+ text-decoration: underline;
+ }
+ .reset-btn:hover {
+ color: #aaa;
+ }
+
+ /* ── Voice picker ──────────────────────────────────────────────────────── */
+ .vp-toggle {
+ display: flex;
+ gap: 6px;
+ margin-bottom: 10px;
+ }
+ .vp-toggle-btn {
+ flex: 1;
+ padding: 7px;
+ background: #0f0f17;
+ border: 1px solid var(--border);
+ color: #888;
+ border-radius: 8px;
+ cursor: pointer;
+ font-size: 13px;
+ font-family: inherit;
+ text-align: center;
+ transition:
+ background 0.15s,
+ border-color 0.15s,
+ color 0.15s;
+ }
+ .vp-toggle-btn.active {
+ background: rgba(106, 92, 255, 0.15);
+ border-color: rgba(106, 92, 255, 0.5);
+ color: #eee;
+ }
+ .vp-toggle-btn:disabled {
+ opacity: 0.35;
+ cursor: not-allowed;
+ }
+ .vp-list {
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ max-height: 260px;
+ overflow-y: auto;
+ }
+ .vp-group-label {
+ padding: 4px 10px;
+ font-size: 11px;
+ color: rgba(255, 255, 255, 0.2);
+ text-transform: uppercase;
+ letter-spacing: 0.07em;
+ background: rgba(255, 255, 255, 0.02);
+ border-bottom: 1px solid rgba(255, 255, 255, 0.04);
+ }
+ .vp-item {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 8px 10px;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.04);
+ cursor: pointer;
+ transition: background 0.1s;
+ }
+ .vp-item:last-child {
+ border-bottom: none;
+ }
+ .vp-item:hover {
+ background: rgba(255, 255, 255, 0.04);
+ }
+ .vp-item.selected {
+ background: rgba(106, 92, 255, 0.1);
+ }
+ .vp-radio {
+ width: 13px;
+ height: 13px;
+ border-radius: 50%;
+ border: 1.5px solid #555;
+ flex-shrink: 0;
+ position: relative;
+ }
+ .vp-item.selected .vp-radio {
+ border-color: var(--accent);
+ background: var(--accent);
+ }
+ .vp-item.selected .vp-radio::after {
+ content: '';
+ width: 5px;
+ height: 5px;
+ border-radius: 50%;
+ background: #fff;
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ transform: translate(-50%, -50%);
+ }
+ .vp-name {
+ flex: 1;
+ font-size: 13px;
+ color: #ccc;
+ }
+ .vp-meta {
+ font-size: 11px;
+ color: #555;
+ }
+ .vp-preview-btn {
+ background: none;
+ border: 1px solid var(--border);
+ color: #666;
+ font-size: 11px;
+ padding: 3px 8px;
+ border-radius: 5px;
+ cursor: pointer;
+ font-family: inherit;
+ white-space: nowrap;
+ }
+ .vp-preview-btn:hover {
+ color: #ccc;
+ border-color: #444;
+ }
+ .vp-preview-btn:disabled {
+ opacity: 0.4;
+ cursor: not-allowed;
+ }
+ .vp-empty {
+ padding: 18px;
+ text-align: center;
+ color: #555;
+ font-size: 13px;
+ }
+ </style>
+ </head>
+ <body>
+ <header>
+ <div class="header-left">
+ <a class="brand" href="/">3D Agent</a>
+ <span class="header-title" id="header-title">Edit Persona</span>
</div>
- <textarea id="f-bio" rows="3" maxlength="280" placeholder="A short description shown on your agent's public page."></textarea>
- </div>
+ <div class="header-actions">
+ <a id="view-link" href="#" class="btn sec" style="text-decoration: none"
+ >View page →</a
+ >
+ <button id="save-btn" class="btn" disabled>Save</button>
+ </div>
+ </header>
- <div class="form-group">
- <div class="label-row">
- <label for="f-system-prompt">System prompt</label>
- <span>
- <span class="char-count" id="cnt-system-prompt">0/2000</span>
- <button class="reset-btn" id="reset-prompt-btn" style="margin-left:8px">Reset to template</button>
- </span>
+ <div class="layout" id="layout" style="display: none">
+ <div class="preview-pane">
+ <div class="preview-loading" id="preview-loading">Loading preview…</div>
+ <iframe id="preview-frame" title="Agent preview" style="display: none"></iframe>
</div>
- <textarea id="f-system-prompt" class="mono" rows="7" maxlength="2000" placeholder="Instructions for how the agent should behave. Prepended to the LLM system prompt."></textarea>
- </div>
+ <div class="editor-pane" id="editor-pane">
+ <h2>Persona</h2>
+ <p class="sub">Shape how your agent speaks, thinks, and presents itself.</p>
- <div class="form-group">
- <label>Catchphrases <span style="color:#555;font-weight:400">(≤ 5)</span></label>
- <div class="catchphrase-list" id="catchphrase-list"></div>
- <button class="add-catchphrase" id="add-catchphrase-btn" style="display:none">+ Add catchphrase</button>
- </div>
+ <div class="templates" id="templates-row"></div>
- <hr class="section-divider">
+ <div class="form-group">
+ <div class="label-row">
+ <label for="f-name">Name</label>
+ <span class="char-count" id="cnt-name">0/40</span>
+ </div>
+ <input
+ type="text"
+ id="f-name"
+ maxlength="40"
+ placeholder="My Agent"
+ autocomplete="off"
+ />
+ </div>
- <div class="form-group">
- <label>Sentiment bias</label>
- <div class="slider-wrap">
- <span class="slider-label">stoic</span>
- <input type="range" id="f-sentiment-bias" min="-1" max="1" step="0.05" value="0">
- <span class="slider-label">effusive</span>
- <span class="slider-value" id="bias-value">0.00</span>
- </div>
- </div>
+ <div class="form-group">
+ <div class="label-row">
+ <label for="f-bio">Bio</label>
+ <span class="char-count" id="cnt-bio">0/280</span>
+ </div>
+ <textarea
+ id="f-bio"
+ rows="3"
+ maxlength="280"
+ placeholder="A short description shown on your agent's public page."
+ ></textarea>
+ </div>
- <div class="form-group" id="voice-picker-group">
- <label>Voice</label>
- <!-- populated by initVoicePicker() in edit.js -->
- </div>
+ <div class="form-group">
+ <div class="label-row">
+ <label for="f-system-prompt">System prompt</label>
+ <span>
+ <span class="char-count" id="cnt-system-prompt">0/2000</span>
+ <button
+ class="reset-btn"
+ id="reset-prompt-btn"
+ style="margin-left: 8px"
+ >
+ Reset to template
+ </button>
+ </span>
+ </div>
+ <textarea
+ id="f-system-prompt"
+ class="mono"
+ rows="7"
+ maxlength="2000"
+ placeholder="Instructions for how the agent should behave. Prepended to the LLM system prompt."
+ ></textarea>
+ </div>
- <div class="form-group">
- <label>Do-not-say list</label>
- <div class="chip-input-wrap" id="dns-wrap">
- <input class="chip-text-input" id="dns-input" placeholder="Type a word and press Enter…">
+ <div class="form-group">
+ <label
+ >Catchphrases
+ <span style="color: #555; font-weight: 400">(≤ 5)</span></label
+ >
+ <div class="catchphrase-list" id="catchphrase-list"></div>
+ <button class="add-catchphrase" id="add-catchphrase-btn" style="display: none">
+ + Add catchphrase
+ </button>
+ </div>
+
+ <hr class="section-divider" />
+
+ <div class="form-group">
+ <label>Sentiment bias</label>
+ <div class="slider-wrap">
+ <span class="slider-label">stoic</span>
+ <input
+ type="range"
+ id="f-sentiment-bias"
+ min="-1"
+ max="1"
+ step="0.05"
+ value="0"
+ />
+ <span class="slider-label">effusive</span>
+ <span class="slider-value" id="bias-value">0.00</span>
+ </div>
+ </div>
+
+ <div class="form-group" id="voice-picker-group">
+ <label>Voice</label>
+ <!-- populated by initVoicePicker() in edit.js -->
+ </div>
+
+ <div class="form-group">
+ <label>Do-not-say list</label>
+ <div class="chip-input-wrap" id="dns-wrap">
+ <input
+ class="chip-text-input"
+ id="dns-input"
+ placeholder="Type a word and press Enter…"
+ />
+ </div>
+ </div>
</div>
</div>
- </div>
-</div>
-<div id="forbidden-screen" style="display:none" class="forbidden">
- <div>
- <h2>Access denied</h2>
- <p>You don't own this agent.</p>
- <a href="/dashboard">← Back to dashboard</a>
- </div>
-</div>
+ <div id="forbidden-screen" style="display: none" class="forbidden">
+ <div>
+ <h2>Access denied</h2>
+ <p>You don't own this agent.</p>
+ <a href="/dashboard">← Back to dashboard</a>
+ </div>
+ </div>
-<div id="loading-screen" style="display:grid;place-items:center;height:calc(100vh - 53px);color:#555;font-size:14px;">
- Loading…
-</div>
+ <div
+ id="loading-screen"
+ style="
+ display: grid;
+ place-items: center;
+ height: calc(100vh - 53px);
+ color: #555;
+ font-size: 14px;
+ "
+ >
+ Loading…
+ </div>
-<div class="toast" id="toast"></div>
+ <div class="toast" id="toast"></div>
-<script type="module" src="./edit.js"></script>
-</body>
+ <script type="module" src="./edit.js"></script>
+ </body>
</html>
diff --git a/public/agent-edit/templates.json b/public/agent-edit/templates.json
index a502cf222..12f0cab76 100644
--- a/public/agent-edit/templates.json
+++ b/public/agent-edit/templates.json
@@ -37,7 +37,11 @@
"name": "Researcher",
"bio": "A methodical investigator who digs into details and questions assumptions.",
"systemPrompt": "You are a careful, inquisitive researcher. Ask clarifying questions before concluding. Surface trade-offs and edge cases. Prefer precision over brevity. Acknowledge uncertainty explicitly.",
- "catchphrases": ["Interesting — let me look closer", "What's the underlying assumption here?", "That depends on…"],
+ "catchphrases": [
+ "Interesting — let me look closer",
+ "What's the underlying assumption here?",
+ "That depends on…"
+ ],
"sentimentBias": -0.1,
"voiceProvider": "web",
"voiceId": null,
diff --git a/public/agent/embed.html b/public/agent/embed.html
index 1390d26ce..a9b287fc4 100644
--- a/public/agent/embed.html
+++ b/public/agent/embed.html
@@ -1,255 +1,322 @@
<!doctype html>
<html lang="en">
-<head>
- <meta charset="utf-8" />
- <title>Agent</title>
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <meta name="description" content="Embedded 3D agent avatar." />
- <meta name="robots" content="noindex" />
- <style>
- html, body { margin: 0; padding: 0; height: 100%; width: 100%; background: transparent; overflow: hidden; font-family: system-ui, sans-serif; }
- #stage { position: absolute; inset: 0; }
- #stage canvas { display: block; width: 100% !important; height: 100% !important; }
- #stage .gui-wrap, #stage .gui-toggle, #stage .annotation-canvas { display: none !important; }
- #stage .model-info { display: none !important; }
- #name-plate {
- position: absolute; left: 12px; bottom: 10px; z-index: 2; pointer-events: none;
- font-size: 11px; color: rgba(255,255,255,0.55); letter-spacing: 0.04em;
- text-shadow: 0 1px 2px rgba(0,0,0,0.6);
- }
- #error {
- position: absolute; inset: 0; display: none; align-items: center; justify-content: center;
- color: rgba(255,255,255,0.4); font-size: 12px; padding: 1rem; text-align: center;
- }
- body.bg-dark { background: #0b0d10; }
- body.bg-light { background: #f5f5f5; }
- </style>
-</head>
-<body>
- <div id="stage"></div>
- <div id="name-plate"></div>
- <div id="error"></div>
-
- <script type="module">
- /*
- * ─── Host ↔ agent postMessage bridge — v1 (FROZEN) ───────────────────
- *
- * Wire format. All payloads are JSON-serializable. All messages MUST
- * include `agentId` so a single host page with multiple iframes can
- * route deterministically. Unknown `type` values are ignored.
- *
- * Host → iframe:
- * { type: 'agent:hello', agentId, host? } Handshake. Iframe replies
- * with agent:ready (now or
- * when init completes).
- * { type: 'agent:action', agentId, action } Forward action onto the
- * iframe's protocol bus.
- * See src/agent-protocol.js
- * for action.type vocabulary.
- * { type: 'agent:ping', agentId, id } Liveness probe; iframe
- * replies with agent:pong{id}.
- *
- * Iframe → host:
- * { type: 'agent:ready', agentId, version, capabilities: [string] }
- * Sent once init succeeds and
- * in response to agent:hello.
- * { type: 'agent:action', agentId, action } Echo of every protocol
- * action the iframe emits.
- * { type: 'agent:resize', agentId, height } Preferred CSS pixel height
- * of the iframe content box.
- * { type: 'agent:pong', agentId, id } Reply to agent:ping.
- *
- * Legacy envelope `{ __agent, type: 'action'|'ready'|'blocked' }` is still
- * accepted on input and emitted on output for backwards compatibility with
- * pre-v1 hosts. New consumers SHOULD prefer the v1 envelope above.
- *
- * Future bumps go to v2 — DO NOT change v1 wire shapes in place.
- */
-
- import { Viewer } from '/src/viewer.js';
- import { AgentIdentity } from '/src/agent-identity.js';
- import { AgentAvatar } from '/src/agent-avatar.js';
- import { protocol } from '/src/agent-protocol.js';
-
- const BRIDGE_VERSION = '1';
- const CAPABILITIES = ['speak', 'gesture', 'look-at', 'emote', 'present-model'];
-
- const params = new URL(location.href).searchParams;
- const bg = params.get('bg') || 'transparent';
- if (bg === 'dark') document.body.classList.add('bg-dark');
- if (bg === 'light') document.body.classList.add('bg-light');
-
- const plateOn = params.get('name') !== '0';
- const preview = params.get('preview') === '1';
- const parts = location.pathname.split('/').filter(Boolean);
- const agentId = parts[parts.indexOf('agent') + 1];
-
- function hostMatches(host, pattern) {
- if (!host || !pattern) return false;
- host = host.toLowerCase();
- pattern = pattern.toLowerCase();
- if (pattern.startsWith('*.')) {
- const suffix = pattern.slice(2);
- return host === suffix || host.endsWith('.' + suffix);
- }
- return host === pattern;
- }
-
- function embeddingHost() {
- // Prefer ancestorOrigins (Chromium/Safari) for the true top-level origin;
- // fall back to document.referrer which is the cross-browser signal for a
- // first-party iframe's parent. Firefox has no ancestorOrigins today.
- try {
- const anc = window.location.ancestorOrigins;
- if (anc && anc.length) return new URL(anc[0]).hostname;
- } catch {}
- try {
- if (document.referrer) return new URL(document.referrer).hostname;
- } catch {}
- return null;
- }
-
- async function checkPolicy() {
- if (preview) return true;
- // Same-origin (top-level or iframed from ourselves) is always allowed.
- const sameOrigin = !window.parent || window.parent === window
- || (() => { try { return window.parent.location.origin === location.origin; } catch { return false; } })();
- let policy = null;
- try {
- const r = await fetch(`/api/agents/${agentId}/embed-policy`, { credentials: 'omit' });
- if (r.ok) policy = (await r.json()).policy;
- } catch {}
- if (policy === null || policy === undefined) return true;
- if (sameOrigin) return true;
- const host = embeddingHost();
- const hosts = Array.isArray(policy.hosts) ? policy.hosts : [];
- const matched = host ? hosts.some((p) => hostMatches(host, p)) : false;
- if (policy.mode === 'allowlist') return matched;
- if (policy.mode === 'denylist') return !matched;
- return true;
- }
-
- // ── Bridge state. The handshake handler is installed *before* main()
- // runs so a host that sends agent:hello early gets a reply once we're
- // ready, even if init takes a few seconds (network + GLB parse).
- let bridgeReady = false;
- let identityName = null;
- const pendingHellos = [];
-
- function postReady() {
- parent?.postMessage({
- type: 'agent:ready', agentId, version: BRIDGE_VERSION, capabilities: CAPABILITIES,
- name: identityName,
- }, '*');
- // Legacy envelope for pre-v1 hosts.
- parent?.postMessage({ __agent: agentId, type: 'ready', name: identityName }, '*');
- }
-
- function postResize(height) {
- parent?.postMessage({ type: 'agent:resize', agentId, height }, '*');
- }
-
- function handleAction(action) {
- if (!action || typeof action !== 'object') return;
- protocol.emit(action);
- }
-
- // Installed eagerly so the host's hello during boot is captured.
- window.addEventListener('message', (ev) => {
- const msg = ev.data;
- if (!msg || typeof msg !== 'object') return;
-
- // v1 envelope
- if (msg.agentId && msg.agentId === agentId && typeof msg.type === 'string') {
- switch (msg.type) {
- case 'agent:hello':
- if (bridgeReady) postReady(); else pendingHellos.push(true);
- return;
- case 'agent:action':
- if (bridgeReady) handleAction(msg.action);
- return;
- case 'agent:ping':
- if (bridgeReady) parent?.postMessage({ type: 'agent:pong', agentId, id: msg.id }, '*');
- return;
+ <head>
+ <meta charset="utf-8" />
+ <title>Agent</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta name="description" content="Embedded 3D agent avatar." />
+ <meta name="robots" content="noindex" />
+ <style>
+ html,
+ body {
+ margin: 0;
+ padding: 0;
+ height: 100%;
+ width: 100%;
+ background: transparent;
+ overflow: hidden;
+ font-family: system-ui, sans-serif;
+ }
+ #stage {
+ position: absolute;
+ inset: 0;
+ }
+ #stage canvas {
+ display: block;
+ width: 100% !important;
+ height: 100% !important;
+ }
+ #stage .gui-wrap,
+ #stage .gui-toggle,
+ #stage .annotation-canvas {
+ display: none !important;
+ }
+ #stage .model-info {
+ display: none !important;
+ }
+ #name-plate {
+ position: absolute;
+ left: 12px;
+ bottom: 10px;
+ z-index: 2;
+ pointer-events: none;
+ font-size: 11px;
+ color: rgba(255, 255, 255, 0.55);
+ letter-spacing: 0.04em;
+ text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
+ }
+ #error {
+ position: absolute;
+ inset: 0;
+ display: none;
+ align-items: center;
+ justify-content: center;
+ color: rgba(255, 255, 255, 0.4);
+ font-size: 12px;
+ padding: 1rem;
+ text-align: center;
+ }
+ body.bg-dark {
+ background: #0b0d10;
+ }
+ body.bg-light {
+ background: #f5f5f5;
+ }
+ </style>
+ </head>
+ <body>
+ <div id="stage"></div>
+ <div id="name-plate"></div>
+ <div id="error"></div>
+
+ <script type="module">
+ /*
+ * ─── Host ↔ agent postMessage bridge — v1 (FROZEN) ───────────────────
+ *
+ * Wire format. All payloads are JSON-serializable. All messages MUST
+ * include `agentId` so a single host page with multiple iframes can
+ * route deterministically. Unknown `type` values are ignored.
+ *
+ * Host → iframe:
+ * { type: 'agent:hello', agentId, host? } Handshake. Iframe replies
+ * with agent:ready (now or
+ * when init completes).
+ * { type: 'agent:action', agentId, action } Forward action onto the
+ * iframe's protocol bus.
+ * See src/agent-protocol.js
+ * for action.type vocabulary.
+ * { type: 'agent:ping', agentId, id } Liveness probe; iframe
+ * replies with agent:pong{id}.
+ *
+ * Iframe → host:
+ * { type: 'agent:ready', agentId, version, capabilities: [string] }
+ * Sent once init succeeds and
+ * in response to agent:hello.
+ * { type: 'agent:action', agentId, action } Echo of every protocol
+ * action the iframe emits.
+ * { type: 'agent:resize', agentId, height } Preferred CSS pixel height
+ * of the iframe content box.
+ * { type: 'agent:pong', agentId, id } Reply to agent:ping.
+ *
+ * Legacy envelope `{ __agent, type: 'action'|'ready'|'blocked' }` is still
+ * accepted on input and emitted on output for backwards compatibility with
+ * pre-v1 hosts. New consumers SHOULD prefer the v1 envelope above.
+ *
+ * Future bumps go to v2 — DO NOT change v1 wire shapes in place.
+ */
+
+ import { Viewer } from '/src/viewer.js';
+ import { AgentIdentity } from '/src/agent-identity.js';
+ import { AgentAvatar } from '/src/agent-avatar.js';
+ import { protocol } from '/src/agent-protocol.js';
+
+ const BRIDGE_VERSION = '1';
+ const CAPABILITIES = ['speak', 'gesture', 'look-at', 'emote', 'present-model'];
+
+ const params = new URL(location.href).searchParams;
+ const bg = params.get('bg') || 'transparent';
+ if (bg === 'dark') document.body.classList.add('bg-dark');
+ if (bg === 'light') document.body.classList.add('bg-light');
+
+ const plateOn = params.get('name') !== '0';
+ const preview = params.get('preview') === '1';
+ const parts = location.pathname.split('/').filter(Boolean);
+ const agentId = parts[parts.indexOf('agent') + 1];
+
+ function hostMatches(host, pattern) {
+ if (!host || !pattern) return false;
+ host = host.toLowerCase();
+ pattern = pattern.toLowerCase();
+ if (pattern.startsWith('*.')) {
+ const suffix = pattern.slice(2);
+ return host === suffix || host.endsWith('.' + suffix);
}
+ return host === pattern;
}
- // Legacy envelope. Kept until all known hosts migrate.
- if (msg.__agent === agentId) {
- if (msg.type === 'action' && msg.action) handleAction(msg.action);
+ function embeddingHost() {
+ // Prefer ancestorOrigins (Chromium/Safari) for the true top-level origin;
+ // fall back to document.referrer which is the cross-browser signal for a
+ // first-party iframe's parent. Firefox has no ancestorOrigins today.
+ try {
+ const anc = window.location.ancestorOrigins;
+ if (anc && anc.length) return new URL(anc[0]).hostname;
+ } catch {}
+ try {
+ if (document.referrer) return new URL(document.referrer).hostname;
+ } catch {}
+ return null;
}
- });
- async function main() {
- if (!(await checkPolicy())) {
- const el = document.getElementById('error');
- el.textContent = 'This agent can only be embedded on approved sites.';
- el.style.display = 'flex';
- parent?.postMessage({ type: 'agent:blocked', agentId }, '*');
- parent?.postMessage({ __agent: agentId, type: 'blocked' }, '*');
- return;
+ async function checkPolicy() {
+ if (preview) return true;
+ // Same-origin (top-level or iframed from ourselves) is always allowed.
+ const sameOrigin =
+ !window.parent ||
+ window.parent === window ||
+ (() => {
+ try {
+ return window.parent.location.origin === location.origin;
+ } catch {
+ return false;
+ }
+ })();
+ let policy = null;
+ try {
+ const r = await fetch(`/api/agents/${agentId}/embed-policy`, {
+ credentials: 'omit',
+ });
+ if (r.ok) policy = (await r.json()).policy;
+ } catch {}
+ if (policy === null || policy === undefined) return true;
+ if (sameOrigin) return true;
+ const host = embeddingHost();
+ const hosts = Array.isArray(policy.hosts) ? policy.hosts : [];
+ const matched = host ? hosts.some((p) => hostMatches(host, p)) : false;
+ if (policy.mode === 'allowlist') return matched;
+ if (policy.mode === 'denylist') return !matched;
+ return true;
}
- const identity = new AgentIdentity({ agentId, autoLoad: false });
- await identity.load();
- identityName = identity.name;
+ // ── Bridge state. The handshake handler is installed *before* main()
+ // runs so a host that sends agent:hello early gets a reply once we're
+ // ready, even if init takes a few seconds (network + GLB parse).
+ let bridgeReady = false;
+ let identityName = null;
+ const pendingHellos = [];
- if (plateOn && identity.name) {
- document.getElementById('name-plate').textContent = identity.name;
+ function postReady() {
+ parent?.postMessage(
+ {
+ type: 'agent:ready',
+ agentId,
+ version: BRIDGE_VERSION,
+ capabilities: CAPABILITIES,
+ name: identityName,
+ },
+ '*',
+ );
+ // Legacy envelope for pre-v1 hosts.
+ parent?.postMessage({ __agent: agentId, type: 'ready', name: identityName }, '*');
}
- if (!identity.avatarId) throw new Error('agent has no avatar body');
-
- const resp = await fetch(`/api/avatars/${identity.avatarId}`, { credentials: 'include' });
- if (!resp.ok) throw new Error(`avatar ${resp.status}`);
- const { avatar } = await resp.json();
- const glbUrl = avatar?.url;
- if (!glbUrl) throw new Error('no avatar url');
+ function postResize(height) {
+ parent?.postMessage({ type: 'agent:resize', agentId, height }, '*');
+ }
- const stage = document.getElementById('stage');
- const viewer = new Viewer(stage, { kiosk: true });
- if (bg === 'transparent') {
- viewer.renderer?.setClearAlpha(0);
- if (viewer.scene) viewer.scene.background = null;
+ function handleAction(action) {
+ if (!action || typeof action !== 'object') return;
+ protocol.emit(action);
}
- await viewer.load(glbUrl, '', new Map());
- const avatarCtl = new AgentAvatar(viewer, protocol, identity);
- avatarCtl.attach();
+ // Installed eagerly so the host's hello during boot is captured.
+ window.addEventListener('message', (ev) => {
+ const msg = ev.data;
+ if (!msg || typeof msg !== 'object') return;
+
+ // v1 envelope
+ if (msg.agentId && msg.agentId === agentId && typeof msg.type === 'string') {
+ switch (msg.type) {
+ case 'agent:hello':
+ if (bridgeReady) postReady();
+ else pendingHellos.push(true);
+ return;
+ case 'agent:action':
+ if (bridgeReady) handleAction(msg.action);
+ return;
+ case 'agent:ping':
+ if (bridgeReady)
+ parent?.postMessage(
+ { type: 'agent:pong', agentId, id: msg.id },
+ '*',
+ );
+ return;
+ }
+ }
- // Echo every protocol action onto the bridge so hosts can mirror state
- // (chat UIs, telemetry, host-side animation triggers).
- protocol.on('*', (action) => {
- parent?.postMessage({ type: 'agent:action', agentId, action }, '*');
+ // Legacy envelope. Kept until all known hosts migrate.
+ if (msg.__agent === agentId) {
+ if (msg.type === 'action' && msg.action) handleAction(msg.action);
+ }
});
- // Report content height to host so embed-sdk can auto-fit the iframe.
- // Coalesce into rAF so a runaway resize observer can't flood the host.
- let pendingPost = false;
- const reportSize = () => {
- if (pendingPost) return;
- pendingPost = true;
- requestAnimationFrame(() => {
- pendingPost = false;
- const h = Math.ceil(document.documentElement.scrollHeight || stage.clientHeight || 0);
- if (h > 0) postResize(h);
+ async function main() {
+ if (!(await checkPolicy())) {
+ const el = document.getElementById('error');
+ el.textContent = 'This agent can only be embedded on approved sites.';
+ el.style.display = 'flex';
+ parent?.postMessage({ type: 'agent:blocked', agentId }, '*');
+ parent?.postMessage({ __agent: agentId, type: 'blocked' }, '*');
+ return;
+ }
+
+ const identity = new AgentIdentity({ agentId, autoLoad: false });
+ await identity.load();
+ identityName = identity.name;
+
+ if (plateOn && identity.name) {
+ document.getElementById('name-plate').textContent = identity.name;
+ }
+
+ if (!identity.avatarId) throw new Error('agent has no avatar body');
+
+ const resp = await fetch(`/api/avatars/${identity.avatarId}`, {
+ credentials: 'include',
});
- };
- if (typeof ResizeObserver !== 'undefined') {
- new ResizeObserver(reportSize).observe(document.documentElement);
- }
- reportSize();
-
- bridgeReady = true;
- postReady();
- while (pendingHellos.length) { pendingHellos.pop(); postReady(); }
- }
-
- main().catch(err => {
- const el = document.getElementById('error');
- el.textContent = err.message || 'Could not load agent';
- el.style.display = 'flex';
- });
- </script>
-</body>
+ if (!resp.ok) throw new Error(`avatar ${resp.status}`);
+ const { avatar } = await resp.json();
+ const glbUrl = avatar?.url;
+ if (!glbUrl) throw new Error('no avatar url');
+
+ const stage = document.getElementById('stage');
+ const viewer = new Viewer(stage, { kiosk: true });
+ if (bg === 'transparent') {
+ viewer.renderer?.setClearAlpha(0);
+ if (viewer.scene) viewer.scene.background = null;
+ }
+ await viewer.load(glbUrl, '', new Map());
+
+ const avatarCtl = new AgentAvatar(viewer, protocol, identity);
+ avatarCtl.attach();
+
+ // Echo every protocol action onto the bridge so hosts can mirror state
+ // (chat UIs, telemetry, host-side animation triggers).
+ protocol.on('*', (action) => {
+ parent?.postMessage({ type: 'agent:action', agentId, action }, '*');
+ });
+
+ // Report content height to host so embed-sdk can auto-fit the iframe.
+ // Coalesce into rAF so a runaway resize observer can't flood the host.
+ let pendingPost = false;
+ const reportSize = () => {
+ if (pendingPost) return;
+ pendingPost = true;
+ requestAnimationFrame(() => {
+ pendingPost = false;
+ const h = Math.ceil(
+ document.documentElement.scrollHeight || stage.clientHeight || 0,
+ );
+ if (h > 0) postResize(h);
+ });
+ };
+ if (typeof ResizeObserver !== 'undefined') {
+ new ResizeObserver(reportSize).observe(document.documentElement);
+ }
+ reportSize();
+
+ bridgeReady = true;
+ postReady();
+ while (pendingHellos.length) {
+ pendingHellos.pop();
+ postReady();
+ }
+ }
+
+ main().catch((err) => {
+ const el = document.getElementById('error');
+ el.textContent = err.message || 'Could not load agent';
+ el.style.display = 'flex';
+ });
+ </script>
+ </body>
</html>
diff --git a/public/agent/index.html b/public/agent/index.html
index 51a0be609..11517c91a 100644
--- a/public/agent/index.html
+++ b/public/agent/index.html
@@ -1,583 +1,649 @@
<!doctype html>
<html lang="en">
-<head>
- <meta charset="utf-8" />
- <title>Agent Home — 3D Agent</title>
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <meta name="description" content="An embodied 3D AI agent — body, place, identity, memory." />
- <meta name="theme-color" content="#000000" />
-
- <link rel="shortcut icon" href="/favicon.ico" />
- <link rel="preconnect" href="https://fonts.googleapis.com" />
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
- <link rel="stylesheet" href="/style.css" />
- <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500&display=swap" rel="stylesheet" />
-
- <!-- unfurl (populated at runtime from identity) -->
- <meta property="og:type" content="website" />
- <meta property="og:title" content="Agent" id="og-title" />
- <meta property="og:description" content="An embodied 3D agent." id="og-description" />
- <meta property="og:image" content="" id="og-image" />
- <meta property="og:url" content="" id="og-url" />
- <meta name="twitter:card" content="summary_large_image" />
- <meta name="twitter:title" content="Agent" id="tw-title" />
- <meta name="twitter:description" content="" id="tw-description" />
- <meta name="twitter:image" content="" id="tw-image" />
- <link rel="alternate" type="application/json+oembed" href="" id="oembed-link" title="Agent oEmbed" />
-
- <style>
- body {
- overflow: auto;
- display: flex;
- flex-direction: column;
- }
-
- .agent-page-header {
- display: flex;
- align-items: center;
- gap: 1rem;
- padding: 1rem 1.618rem;
- border-bottom: 1px solid rgba(255,255,255,0.06);
- }
-
- .agent-page-header a {
- color: rgba(255,255,255,0.4);
- text-decoration: none;
- font-size: 0.764rem;
- }
-
- .agent-page-header a:hover {
- color: rgba(255,255,255,0.8);
- }
-
- .agent-page-hero {
- max-width: 520px;
- margin: 4rem auto 2rem;
- padding: 0 1rem;
- text-align: center;
- }
-
- .agent-page-title {
- font-size: 1.618rem;
- font-weight: 300;
- color: #e5e5e5;
- letter-spacing: -0.02em;
- margin: 0 0 0.618rem;
- }
-
- .agent-page-subtitle {
- font-size: 0.764rem;
- color: rgba(255,255,255,0.35);
- line-height: 1.618;
- }
-
- .agent-page-card-wrap {
- max-width: 420px;
- margin: 0 auto;
- padding: 0 1rem 4rem;
- }
-
- /* Expand the timeline on standalone page */
- .agent-page-card-wrap .agent-home-timeline {
- max-height: 320px;
- }
-
- /* Expand the panel to fill the card */
- .agent-page-card-wrap .agent-home-panel {
- background: rgba(12, 12, 18, 0.98);
- border: 1px solid rgba(255,255,255,0.08);
- border-radius: 12px;
- }
-
- .agent-embed-hint {
- max-width: 420px;
- margin: 1.618rem auto 0;
- padding: 0 1rem;
- }
-
- .agent-embed-tabs {
- display: flex;
- gap: 0.382rem;
- margin-bottom: 0.618rem;
- }
-
- .agent-embed-tab {
- background: transparent;
- border: 1px solid rgba(255,255,255,0.1);
- color: rgba(255,255,255,0.5);
- font-size: 0.618rem;
- padding: 0.236rem 0.618rem;
- border-radius: 999px;
- cursor: pointer;
- font-family: inherit;
- }
-
- .agent-embed-tab.active {
- background: rgba(255,255,255,0.08);
- color: rgba(255,255,255,0.9);
- border-color: rgba(255,255,255,0.2);
- }
-
- .agent-embed-code-wrap {
- position: relative;
- }
-
- .agent-embed-code {
- background: rgba(255,255,255,0.04);
- border: 1px solid rgba(255,255,255,0.08);
- border-radius: 8px;
- padding: 0.618rem 1rem;
- padding-right: 3.8rem;
- font-family: monospace;
- font-size: 0.618rem;
- color: rgba(255,255,255,0.55);
- word-break: break-all;
- line-height: 1.5;
- }
-
- .agent-embed-copy {
- position: absolute;
- top: 0.382rem;
- right: 0.382rem;
- background: rgba(255,255,255,0.06);
- border: 1px solid rgba(255,255,255,0.1);
- color: rgba(255,255,255,0.6);
- font-size: 0.618rem;
- padding: 0.236rem 0.618rem;
- border-radius: 6px;
- cursor: pointer;
- font-family: inherit;
- }
-
- .agent-embed-copy:hover { color: rgba(255,255,255,0.9); background: rgba(255,255,255,0.1); }
- .agent-embed-copy.copied { color: #86efac; border-color: rgba(134,239,172,0.3); }
-
- .agent-embed-label {
- font-size: 0.618rem;
- color: rgba(255,255,255,0.25);
- margin-bottom: 0.382rem;
- }
-
- .agent-embed-preview-link {
- display: inline-block;
- margin-top: 0.618rem;
- font-size: 0.618rem;
- color: rgba(255,255,255,0.35);
- text-decoration: none;
- }
-
- .agent-embed-preview-link:hover { color: rgba(255,255,255,0.7); }
-
- .agent-skills-full {
- max-width: 420px;
- margin: 1.618rem auto 0;
- padding: 0 1rem;
- }
-
- .agent-skills-title {
- font-size: 0.618rem;
- color: rgba(255,255,255,0.25);
- margin-bottom: 0.618rem;
- text-transform: uppercase;
- letter-spacing: 0.08em;
- }
-
- .agent-skills-grid {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
- gap: 0.618rem;
- }
-
- .agent-skill-card {
- background: rgba(255,255,255,0.04);
- border: 1px solid rgba(255,255,255,0.07);
- border-radius: 8px;
- padding: 0.618rem;
- }
-
- .agent-skill-card-name {
- font-size: 0.764rem;
- font-weight: 500;
- color: rgba(255,255,255,0.7);
- margin-bottom: 0.236rem;
- }
-
- .agent-skill-card-desc {
- font-size: 0.618rem;
- color: rgba(255,255,255,0.3);
- line-height: 1.382;
- }
-
- .loading-placeholder {
- color: rgba(255,255,255,0.2);
- font-size: 0.764rem;
- text-align: center;
- padding: 2rem;
- }
-
- /* ── Hub actions row ────────────────────────────────────────────────── */
-
- .agent-hub-actions {
- display: flex;
- gap: 0.5rem;
- flex-wrap: wrap;
- padding: 0.75rem 1rem;
- border-top: 1px solid rgba(255,255,255,0.06);
- border-bottom: 1px solid rgba(255,255,255,0.06);
- }
-
- .agent-hub-btn {
- display: inline-flex;
- align-items: center;
- gap: 0.382rem;
- background: rgba(255,255,255,0.05);
- border: 1px solid rgba(255,255,255,0.1);
- color: rgba(255,255,255,0.7);
- font-size: 0.718rem;
- font-family: inherit;
- padding: 0.382rem 0.75rem;
- border-radius: 999px;
- cursor: pointer;
- transition: background 0.15s, border-color 0.15s, color 0.15s;
- white-space: nowrap;
- }
-
- .agent-hub-btn:hover:not(:disabled) {
- background: rgba(255,255,255,0.1);
- border-color: rgba(255,255,255,0.2);
- color: rgba(255,255,255,0.95);
- }
-
- .agent-hub-btn:disabled {
- opacity: 0.5;
- cursor: default;
- }
-
- .agent-hub-btn svg {
- flex-shrink: 0;
- opacity: 0.7;
- }
-
- .agent-hub-opt {
- font-size: 0.618rem;
- opacity: 0.45;
- }
-
- .hub-btn--deployed {
- border-color: rgba(134,239,172,0.25);
- color: #86efac;
- }
-
- .hub-btn--deployed svg {
- opacity: 0.9;
- }
-
- /* ── Embed modal ────────────────────────────────────────────────────── */
-
- .aem-overlay {
- position: fixed;
- inset: 0;
- background: rgba(0,0,0,0.65);
- display: flex;
- align-items: center;
- justify-content: center;
- z-index: 9000;
- opacity: 0;
- transition: opacity 0.15s;
- }
-
- .aem-overlay.aem-open {
- opacity: 1;
- }
-
- .aem-modal {
- background: #0f0f18;
- border: 1px solid rgba(255,255,255,0.1);
- border-radius: 12px;
- width: min(480px, calc(100vw - 2rem));
- max-height: calc(100vh - 4rem);
- overflow: hidden;
- display: flex;
- flex-direction: column;
- box-shadow: 0 24px 80px rgba(0,0,0,0.6);
- }
-
- .aem-header {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 1rem 1.25rem;
- border-bottom: 1px solid rgba(255,255,255,0.07);
- }
-
- .aem-title {
- font-size: 0.875rem;
- font-weight: 500;
- color: rgba(255,255,255,0.85);
- }
-
- .aem-close {
- background: none;
- border: none;
- color: rgba(255,255,255,0.4);
- font-size: 1.25rem;
- line-height: 1;
- cursor: pointer;
- padding: 0.25rem;
- border-radius: 4px;
- }
-
- .aem-close:hover { color: rgba(255,255,255,0.8); }
-
- .aem-body {
- padding: 1rem 1.25rem 1.25rem;
- display: flex;
- flex-direction: column;
- gap: 0.75rem;
- }
-
- .aem-tabs {
- display: flex;
- gap: 0.382rem;
- }
-
- .aem-tab {
- background: transparent;
- border: 1px solid rgba(255,255,255,0.1);
- color: rgba(255,255,255,0.45);
- font-size: 0.618rem;
- padding: 0.236rem 0.618rem;
- border-radius: 999px;
- cursor: pointer;
- font-family: inherit;
- transition: background 0.12s, color 0.12s;
- }
-
- .aem-tab.active {
- background: rgba(255,255,255,0.08);
- color: rgba(255,255,255,0.9);
- border-color: rgba(255,255,255,0.2);
- }
-
- .aem-snippet-wrap {
- position: relative;
- }
-
- .aem-snippet {
- background: rgba(255,255,255,0.04);
- border: 1px solid rgba(255,255,255,0.08);
- border-radius: 8px;
- padding: 0.75rem 1rem;
- padding-right: 4rem;
- font-family: monospace;
- font-size: 0.618rem;
- color: rgba(255,255,255,0.6);
- white-space: pre-wrap;
- word-break: break-all;
- line-height: 1.6;
- margin: 0;
- }
-
- .aem-copy {
- position: absolute;
- top: 0.382rem;
- right: 0.382rem;
- background: rgba(255,255,255,0.06);
- border: 1px solid rgba(255,255,255,0.1);
- color: rgba(255,255,255,0.6);
- font-size: 0.618rem;
- padding: 0.236rem 0.618rem;
- border-radius: 6px;
- cursor: pointer;
- font-family: inherit;
- transition: background 0.12s, color 0.12s;
- }
-
- .aem-copy:hover { color: rgba(255,255,255,0.9); background: rgba(255,255,255,0.1); }
- .aem-copy.aem-copied { color: #86efac; border-color: rgba(134,239,172,0.3); }
-
- .aem-note {
- font-size: 0.618rem;
- color: rgba(255,255,255,0.25);
- margin: 0;
- line-height: 1.5;
- }
- </style>
-</head>
-<body>
- <div class="agent-page-header">
- <a href="/">← 3D Agent</a>
- </div>
-
- <div class="agent-page-hero">
- <h1 class="agent-page-title" id="page-agent-name">Agent</h1>
- <p class="agent-page-subtitle" id="page-agent-desc">
- Embodied. Present. Persistent.
- </p>
- </div>
-
- <!-- Agent home card rendered by AgentHome -->
- <div class="agent-page-card-wrap">
- <div id="agent-home-container">
- <div class="loading-placeholder">Loading agent…</div>
+ <head>
+ <meta charset="utf-8" />
+ <title>Agent Home — 3D Agent</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta
+ name="description"
+ content="An embodied 3D AI agent — body, place, identity, memory."
+ />
+ <meta name="theme-color" content="#000000" />
+
+ <link rel="shortcut icon" href="/favicon.ico" />
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
+ <link rel="stylesheet" href="/style.css" />
+ <link
+ href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500&display=swap"
+ rel="stylesheet"
+ />
+
+ <!-- unfurl (populated at runtime from identity) -->
+ <meta property="og:type" content="website" />
+ <meta property="og:title" content="Agent" id="og-title" />
+ <meta property="og:description" content="An embodied 3D agent." id="og-description" />
+ <meta property="og:image" content="" id="og-image" />
+ <meta property="og:url" content="" id="og-url" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:title" content="Agent" id="tw-title" />
+ <meta name="twitter:description" content="" id="tw-description" />
+ <meta name="twitter:image" content="" id="tw-image" />
+ <link
+ rel="alternate"
+ type="application/json+oembed"
+ href=""
+ id="oembed-link"
+ title="Agent oEmbed"
+ />
+
+ <style>
+ body {
+ overflow: auto;
+ display: flex;
+ flex-direction: column;
+ }
+
+ .agent-page-header {
+ display: flex;
+ align-items: center;
+ gap: 1rem;
+ padding: 1rem 1.618rem;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);
+ }
+
+ .agent-page-header a {
+ color: rgba(255, 255, 255, 0.4);
+ text-decoration: none;
+ font-size: 0.764rem;
+ }
+
+ .agent-page-header a:hover {
+ color: rgba(255, 255, 255, 0.8);
+ }
+
+ .agent-page-hero {
+ max-width: 520px;
+ margin: 4rem auto 2rem;
+ padding: 0 1rem;
+ text-align: center;
+ }
+
+ .agent-page-title {
+ font-size: 1.618rem;
+ font-weight: 300;
+ color: #e5e5e5;
+ letter-spacing: -0.02em;
+ margin: 0 0 0.618rem;
+ }
+
+ .agent-page-subtitle {
+ font-size: 0.764rem;
+ color: rgba(255, 255, 255, 0.35);
+ line-height: 1.618;
+ }
+
+ .agent-page-card-wrap {
+ max-width: 420px;
+ margin: 0 auto;
+ padding: 0 1rem 4rem;
+ }
+
+ /* Expand the timeline on standalone page */
+ .agent-page-card-wrap .agent-home-timeline {
+ max-height: 320px;
+ }
+
+ /* Expand the panel to fill the card */
+ .agent-page-card-wrap .agent-home-panel {
+ background: rgba(12, 12, 18, 0.98);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 12px;
+ }
+
+ .agent-embed-hint {
+ max-width: 420px;
+ margin: 1.618rem auto 0;
+ padding: 0 1rem;
+ }
+
+ .agent-embed-tabs {
+ display: flex;
+ gap: 0.382rem;
+ margin-bottom: 0.618rem;
+ }
+
+ .agent-embed-tab {
+ background: transparent;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ color: rgba(255, 255, 255, 0.5);
+ font-size: 0.618rem;
+ padding: 0.236rem 0.618rem;
+ border-radius: 999px;
+ cursor: pointer;
+ font-family: inherit;
+ }
+
+ .agent-embed-tab.active {
+ background: rgba(255, 255, 255, 0.08);
+ color: rgba(255, 255, 255, 0.9);
+ border-color: rgba(255, 255, 255, 0.2);
+ }
+
+ .agent-embed-code-wrap {
+ position: relative;
+ }
+
+ .agent-embed-code {
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 8px;
+ padding: 0.618rem 1rem;
+ padding-right: 3.8rem;
+ font-family: monospace;
+ font-size: 0.618rem;
+ color: rgba(255, 255, 255, 0.55);
+ word-break: break-all;
+ line-height: 1.5;
+ }
+
+ .agent-embed-copy {
+ position: absolute;
+ top: 0.382rem;
+ right: 0.382rem;
+ background: rgba(255, 255, 255, 0.06);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ color: rgba(255, 255, 255, 0.6);
+ font-size: 0.618rem;
+ padding: 0.236rem 0.618rem;
+ border-radius: 6px;
+ cursor: pointer;
+ font-family: inherit;
+ }
+
+ .agent-embed-copy:hover {
+ color: rgba(255, 255, 255, 0.9);
+ background: rgba(255, 255, 255, 0.1);
+ }
+ .agent-embed-copy.copied {
+ color: #86efac;
+ border-color: rgba(134, 239, 172, 0.3);
+ }
+
+ .agent-embed-label {
+ font-size: 0.618rem;
+ color: rgba(255, 255, 255, 0.25);
+ margin-bottom: 0.382rem;
+ }
+
+ .agent-embed-preview-link {
+ display: inline-block;
+ margin-top: 0.618rem;
+ font-size: 0.618rem;
+ color: rgba(255, 255, 255, 0.35);
+ text-decoration: none;
+ }
+
+ .agent-embed-preview-link:hover {
+ color: rgba(255, 255, 255, 0.7);
+ }
+
+ .agent-skills-full {
+ max-width: 420px;
+ margin: 1.618rem auto 0;
+ padding: 0 1rem;
+ }
+
+ .agent-skills-title {
+ font-size: 0.618rem;
+ color: rgba(255, 255, 255, 0.25);
+ margin-bottom: 0.618rem;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ }
+
+ .agent-skills-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
+ gap: 0.618rem;
+ }
+
+ .agent-skill-card {
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid rgba(255, 255, 255, 0.07);
+ border-radius: 8px;
+ padding: 0.618rem;
+ }
+
+ .agent-skill-card-name {
+ font-size: 0.764rem;
+ font-weight: 500;
+ color: rgba(255, 255, 255, 0.7);
+ margin-bottom: 0.236rem;
+ }
+
+ .agent-skill-card-desc {
+ font-size: 0.618rem;
+ color: rgba(255, 255, 255, 0.3);
+ line-height: 1.382;
+ }
+
+ .loading-placeholder {
+ color: rgba(255, 255, 255, 0.2);
+ font-size: 0.764rem;
+ text-align: center;
+ padding: 2rem;
+ }
+
+ /* ── Hub actions row ────────────────────────────────────────────────── */
+
+ .agent-hub-actions {
+ display: flex;
+ gap: 0.5rem;
+ flex-wrap: wrap;
+ padding: 0.75rem 1rem;
+ border-top: 1px solid rgba(255, 255, 255, 0.06);
+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);
+ }
+
+ .agent-hub-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.382rem;
+ background: rgba(255, 255, 255, 0.05);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ color: rgba(255, 255, 255, 0.7);
+ font-size: 0.718rem;
+ font-family: inherit;
+ padding: 0.382rem 0.75rem;
+ border-radius: 999px;
+ cursor: pointer;
+ transition:
+ background 0.15s,
+ border-color 0.15s,
+ color 0.15s;
+ white-space: nowrap;
+ }
+
+ .agent-hub-btn:hover:not(:disabled) {
+ background: rgba(255, 255, 255, 0.1);
+ border-color: rgba(255, 255, 255, 0.2);
+ color: rgba(255, 255, 255, 0.95);
+ }
+
+ .agent-hub-btn:disabled {
+ opacity: 0.5;
+ cursor: default;
+ }
+
+ .agent-hub-btn svg {
+ flex-shrink: 0;
+ opacity: 0.7;
+ }
+
+ .agent-hub-opt {
+ font-size: 0.618rem;
+ opacity: 0.45;
+ }
+
+ .hub-btn--deployed {
+ border-color: rgba(134, 239, 172, 0.25);
+ color: #86efac;
+ }
+
+ .hub-btn--deployed svg {
+ opacity: 0.9;
+ }
+
+ /* ── Embed modal ────────────────────────────────────────────────────── */
+
+ .aem-overlay {
+ position: fixed;
+ inset: 0;
+ background: rgba(0, 0, 0, 0.65);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ z-index: 9000;
+ opacity: 0;
+ transition: opacity 0.15s;
+ }
+
+ .aem-overlay.aem-open {
+ opacity: 1;
+ }
+
+ .aem-modal {
+ background: #0f0f18;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ border-radius: 12px;
+ width: min(480px, calc(100vw - 2rem));
+ max-height: calc(100vh - 4rem);
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+ box-shadow: 0 24px 80px rgba(0, 0, 0, 0.6);
+ }
+
+ .aem-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 1rem 1.25rem;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.07);
+ }
+
+ .aem-title {
+ font-size: 0.875rem;
+ font-weight: 500;
+ color: rgba(255, 255, 255, 0.85);
+ }
+
+ .aem-close {
+ background: none;
+ border: none;
+ color: rgba(255, 255, 255, 0.4);
+ font-size: 1.25rem;
+ line-height: 1;
+ cursor: pointer;
+ padding: 0.25rem;
+ border-radius: 4px;
+ }
+
+ .aem-close:hover {
+ color: rgba(255, 255, 255, 0.8);
+ }
+
+ .aem-body {
+ padding: 1rem 1.25rem 1.25rem;
+ display: flex;
+ flex-direction: column;
+ gap: 0.75rem;
+ }
+
+ .aem-tabs {
+ display: flex;
+ gap: 0.382rem;
+ }
+
+ .aem-tab {
+ background: transparent;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ color: rgba(255, 255, 255, 0.45);
+ font-size: 0.618rem;
+ padding: 0.236rem 0.618rem;
+ border-radius: 999px;
+ cursor: pointer;
+ font-family: inherit;
+ transition:
+ background 0.12s,
+ color 0.12s;
+ }
+
+ .aem-tab.active {
+ background: rgba(255, 255, 255, 0.08);
+ color: rgba(255, 255, 255, 0.9);
+ border-color: rgba(255, 255, 255, 0.2);
+ }
+
+ .aem-snippet-wrap {
+ position: relative;
+ }
+
+ .aem-snippet {
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 8px;
+ padding: 0.75rem 1rem;
+ padding-right: 4rem;
+ font-family: monospace;
+ font-size: 0.618rem;
+ color: rgba(255, 255, 255, 0.6);
+ white-space: pre-wrap;
+ word-break: break-all;
+ line-height: 1.6;
+ margin: 0;
+ }
+
+ .aem-copy {
+ position: absolute;
+ top: 0.382rem;
+ right: 0.382rem;
+ background: rgba(255, 255, 255, 0.06);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ color: rgba(255, 255, 255, 0.6);
+ font-size: 0.618rem;
+ padding: 0.236rem 0.618rem;
+ border-radius: 6px;
+ cursor: pointer;
+ font-family: inherit;
+ transition:
+ background 0.12s,
+ color 0.12s;
+ }
+
+ .aem-copy:hover {
+ color: rgba(255, 255, 255, 0.9);
+ background: rgba(255, 255, 255, 0.1);
+ }
+ .aem-copy.aem-copied {
+ color: #86efac;
+ border-color: rgba(134, 239, 172, 0.3);
+ }
+
+ .aem-note {
+ font-size: 0.618rem;
+ color: rgba(255, 255, 255, 0.25);
+ margin: 0;
+ line-height: 1.5;
+ }
+ </style>
+ </head>
+ <body>
+ <div class="agent-page-header">
+ <a href="/">← 3D Agent</a>
</div>
- </div>
-
- <!-- Skills catalog -->
- <div class="agent-skills-full" id="agent-skills-section" style="display:none">
- <div class="agent-skills-title">Skills</div>
- <div class="agent-skills-grid" id="agent-skills-grid"></div>
- </div>
-
- <!-- Embed code -->
- <div class="agent-embed-hint" id="agent-embed-section" style="display:none">
- <div class="agent-embed-label">Share &amp; embed</div>
- <div class="agent-embed-tabs" role="tablist">
- <button class="agent-embed-tab active" data-tab="iframe">iframe</button>
- <button class="agent-embed-tab" data-tab="link">link</button>
- <button class="agent-embed-tab" data-tab="webcomponent">&lt;agent-3d&gt;</button>
+
+ <div class="agent-page-hero">
+ <h1 class="agent-page-title" id="page-agent-name">Agent</h1>
+ <p class="agent-page-subtitle" id="page-agent-desc">Embodied. Present. Persistent.</p>
+ </div>
+
+ <!-- Agent home card rendered by AgentHome -->
+ <div class="agent-page-card-wrap">
+ <div id="agent-home-container">
+ <div class="loading-placeholder">Loading agent…</div>
+ </div>
+ </div>
+
+ <!-- Skills catalog -->
+ <div class="agent-skills-full" id="agent-skills-section" style="display: none">
+ <div class="agent-skills-title">Skills</div>
+ <div class="agent-skills-grid" id="agent-skills-grid"></div>
</div>
- <div class="agent-embed-code-wrap">
- <div class="agent-embed-code" id="agent-embed-code"></div>
- <button class="agent-embed-copy" id="agent-embed-copy">copy</button>
+
+ <!-- Embed code -->
+ <div class="agent-embed-hint" id="agent-embed-section" style="display: none">
+ <div class="agent-embed-label">Share &amp; embed</div>
+ <div class="agent-embed-tabs" role="tablist">
+ <button class="agent-embed-tab active" data-tab="iframe">iframe</button>
+ <button class="agent-embed-tab" data-tab="link">link</button>
+ <button class="agent-embed-tab" data-tab="webcomponent">&lt;agent-3d&gt;</button>
+ </div>
+ <div class="agent-embed-code-wrap">
+ <div class="agent-embed-code" id="agent-embed-code"></div>
+ <button class="agent-embed-copy" id="agent-embed-copy">copy</button>
+ </div>
+ <a
+ class="agent-embed-preview-link"
+ id="agent-embed-preview"
+ target="_blank"
+ rel="noopener"
+ >preview embed →</a
+ >
+ <a
+ class="agent-embed-preview-link"
+ id="agent-embed-settings"
+ href=""
+ target="_blank"
+ rel="noopener"
+ >embed settings →</a
+ >
</div>
- <a class="agent-embed-preview-link" id="agent-embed-preview" target="_blank" rel="noopener">preview embed →</a>
- <a class="agent-embed-preview-link" id="agent-embed-settings" href="" target="_blank" rel="noopener">embed settings →</a>
- </div>
-
- <script type="module">
- import { AgentIdentity } from '/src/agent-identity.js';
- import { AgentMemory } from '/src/agent-memory.js';
- import { AgentSkills } from '/src/agent-skills.js';
- import { AgentHome } from '/src/agent-home.js';
- import { protocol } from '/src/agent-protocol.js';
- import { renderHubActions } from '/src/agent-hub-actions.js';
-
- // Pull agent id from URL: /agent/:id
- const agentId = location.pathname.split('/').filter(Boolean).pop();
-
- async function main() {
- // Fetch raw API response first — it includes user_id only for owners.
- let rawAgent = null;
- if (agentId) {
- try {
- const resp = await fetch(`/api/agents/${agentId}`, { credentials: 'include' });
- if (resp.ok) {
- const data = await resp.json();
- rawAgent = data.agent || null;
- }
- } catch {}
- }
-
- const identity = new AgentIdentity({ agentId: agentId || undefined, autoLoad: false });
- await identity.load();
-
- // Update hero
- document.getElementById('page-agent-name').textContent = identity.name;
- if (identity.description) {
- document.getElementById('page-agent-desc').textContent = identity.description;
- }
-
- // Render the agent home card
- const container = document.getElementById('agent-home-container');
- container.innerHTML = '';
- const home = new AgentHome(container, identity, protocol, null);
- await home.render();
-
- // Inject hub actions if the viewer is the owner (user_id present = owner)
- const isOwner = Boolean(rawAgent?.user_id);
- if (isOwner) {
- const panel = container.querySelector('.agent-home-panel');
- if (panel) renderHubActions(panel, identity, rawAgent);
- }
-
- // Render skills catalog
- if (identity.skills?.length) {
- const skills = new AgentSkills(protocol, identity.memory);
- const section = document.getElementById('agent-skills-section');
- const grid = document.getElementById('agent-skills-grid');
- section.style.display = '';
- skills.list().filter(s => identity.skills.includes(s.name)).forEach(skill => {
- const card = document.createElement('div');
- card.className = 'agent-skill-card';
- card.innerHTML = `
+
+ <script type="module">
+ import { AgentIdentity } from '/src/agent-identity.js';
+ import { AgentMemory } from '/src/agent-memory.js';
+ import { AgentSkills } from '/src/agent-skills.js';
+ import { AgentHome } from '/src/agent-home.js';
+ import { protocol } from '/src/agent-protocol.js';
+ import { renderHubActions } from '/src/agent-hub-actions.js';
+
+ // Pull agent id from URL: /agent/:id
+ const agentId = location.pathname.split('/').filter(Boolean).pop();
+
+ async function main() {
+ // Fetch raw API response first — it includes user_id only for owners.
+ let rawAgent = null;
+ if (agentId) {
+ try {
+ const resp = await fetch(`/api/agents/${agentId}`, {
+ credentials: 'include',
+ });
+ if (resp.ok) {
+ const data = await resp.json();
+ rawAgent = data.agent || null;
+ }
+ } catch {}
+ }
+
+ const identity = new AgentIdentity({
+ agentId: agentId || undefined,
+ autoLoad: false,
+ });
+ await identity.load();
+
+ // Update hero
+ document.getElementById('page-agent-name').textContent = identity.name;
+ if (identity.description) {
+ document.getElementById('page-agent-desc').textContent = identity.description;
+ }
+
+ // Render the agent home card
+ const container = document.getElementById('agent-home-container');
+ container.innerHTML = '';
+ const home = new AgentHome(container, identity, protocol, null);
+ await home.render();
+
+ // Inject hub actions if the viewer is the owner (user_id present = owner)
+ const isOwner = Boolean(rawAgent?.user_id);
+ if (isOwner) {
+ const panel = container.querySelector('.agent-home-panel');
+ if (panel) renderHubActions(panel, identity, rawAgent);
+ }
+
+ // Render skills catalog
+ if (identity.skills?.length) {
+ const skills = new AgentSkills(protocol, identity.memory);
+ const section = document.getElementById('agent-skills-section');
+ const grid = document.getElementById('agent-skills-grid');
+ section.style.display = '';
+ skills
+ .list()
+ .filter((s) => identity.skills.includes(s.name))
+ .forEach((skill) => {
+ const card = document.createElement('div');
+ card.className = 'agent-skill-card';
+ card.innerHTML = `
<div class="agent-skill-card-name">${skill.name}</div>
<div class="agent-skill-card-desc">${skill.description}</div>
`;
- grid.appendChild(card);
+ grid.appendChild(card);
+ });
+ }
+
+ // Embed code
+ const embedSection = document.getElementById('agent-embed-section');
+ const embedCode = document.getElementById('agent-embed-code');
+ const embedCopy = document.getElementById('agent-embed-copy');
+ const embedPreview = document.getElementById('agent-embed-preview');
+ const origin = location.origin;
+ const embedUrl = `${origin}/agent/${identity.id}/embed`;
+ const agentUrl = `${origin}/agent/${identity.id}`;
+
+ const snippets = {
+ iframe: `<iframe src="${embedUrl}" width="420" height="520" style="border:0;border-radius:12px" allow="autoplay; xr-spatial-tracking"></iframe>`,
+ link: agentUrl,
+ webcomponent: `<script type="module" src="${origin}/dist-lib/agent-3d.js"><\/script>\n<agent-3d agent-id="${identity.id}" style="width:420px;height:520px"></agent-3d>`,
+ };
+
+ let current = 'iframe';
+ const render = () => {
+ embedCode.textContent = snippets[current];
+ };
+ render();
+ // Hide the bottom embed section for owners — they have the modal via the hub Embed button.
+ if (!isOwner) embedSection.style.display = '';
+ embedPreview.href = embedUrl;
+ document.getElementById('agent-embed-settings').href =
+ '/dashboard/embed-policy?agent=' + identity.id;
+
+ document.querySelectorAll('.agent-embed-tab').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ current = btn.dataset.tab;
+ document
+ .querySelectorAll('.agent-embed-tab')
+ .forEach((b) => b.classList.toggle('active', b === btn));
+ render();
+ });
});
- }
- // Embed code
- const embedSection = document.getElementById('agent-embed-section');
- const embedCode = document.getElementById('agent-embed-code');
- const embedCopy = document.getElementById('agent-embed-copy');
- const embedPreview = document.getElementById('agent-embed-preview');
- const origin = location.origin;
- const embedUrl = `${origin}/agent/${identity.id}/embed`;
- const agentUrl = `${origin}/agent/${identity.id}`;
-
- const snippets = {
- iframe: `<iframe src="${embedUrl}" width="420" height="520" style="border:0;border-radius:12px" allow="autoplay; xr-spatial-tracking"></iframe>`,
- link: agentUrl,
- webcomponent: `<script type="module" src="${origin}/dist-lib/agent-3d.js"><\/script>\n<agent-3d agent-id="${identity.id}" style="width:420px;height:520px"></agent-3d>`,
- };
-
- let current = 'iframe';
- const render = () => { embedCode.textContent = snippets[current]; };
- render();
- // Hide the bottom embed section for owners — they have the modal via the hub Embed button.
- if (!isOwner) embedSection.style.display = '';
- embedPreview.href = embedUrl;
- document.getElementById('agent-embed-settings').href = '/dashboard/embed-policy?agent=' + identity.id;
-
- document.querySelectorAll('.agent-embed-tab').forEach(btn => {
- btn.addEventListener('click', () => {
- current = btn.dataset.tab;
- document.querySelectorAll('.agent-embed-tab').forEach(b => b.classList.toggle('active', b === btn));
- render();
+ embedCopy.addEventListener('click', async () => {
+ try {
+ await navigator.clipboard.writeText(snippets[current]);
+ embedCopy.textContent = 'copied';
+ embedCopy.classList.add('copied');
+ setTimeout(() => {
+ embedCopy.textContent = 'copy';
+ embedCopy.classList.remove('copied');
+ }, 1400);
+ } catch {}
});
- });
- embedCopy.addEventListener('click', async () => {
- try {
- await navigator.clipboard.writeText(snippets[current]);
- embedCopy.textContent = 'copied';
- embedCopy.classList.add('copied');
- setTimeout(() => { embedCopy.textContent = 'copy'; embedCopy.classList.remove('copied'); }, 1400);
- } catch {}
- });
+ populateUnfurlMeta(identity);
+ }
- populateUnfurlMeta(identity);
- }
-
- function populateUnfurlMeta(identity) {
- const id = identity?.id;
- if (!id) return;
- const origin = location.origin;
- const name = identity.name || 'Agent';
- const desc = identity.description || 'An embodied 3D agent.';
- const agentUrl = `${origin}/agent/${id}`;
- const img = `${origin}/api/agent/${id}/og`;
- const setAttr = (elId, attr, value) => {
- const el = document.getElementById(elId);
- if (el) el.setAttribute(attr, value);
- };
- setAttr('og-title', 'content', name);
- setAttr('og-description', 'content', desc);
- setAttr('og-image', 'content', img);
- setAttr('og-url', 'content', agentUrl);
- setAttr('tw-title', 'content', name);
- setAttr('tw-description', 'content', desc);
- setAttr('tw-image', 'content', img);
- setAttr('oembed-link', 'href', `${origin}/api/oembed?url=${encodeURIComponent(agentUrl)}`);
- document.title = `${name} — 3D Agent`;
- }
-
- main().catch(err => {
- document.getElementById('agent-home-container').innerHTML =
- `<div class="loading-placeholder">Could not load agent: ${err.message}</div>`;
- });
- </script>
-</body>
+ function populateUnfurlMeta(identity) {
+ const id = identity?.id;
+ if (!id) return;
+ const origin = location.origin;
+ const name = identity.name || 'Agent';
+ const desc = identity.description || 'An embodied 3D agent.';
+ const agentUrl = `${origin}/agent/${id}`;
+ const img = `${origin}/api/agent/${id}/og`;
+ const setAttr = (elId, attr, value) => {
+ const el = document.getElementById(elId);
+ if (el) el.setAttribute(attr, value);
+ };
+ setAttr('og-title', 'content', name);
+ setAttr('og-description', 'content', desc);
+ setAttr('og-image', 'content', img);
+ setAttr('og-url', 'content', agentUrl);
+ setAttr('tw-title', 'content', name);
+ setAttr('tw-description', 'content', desc);
+ setAttr('tw-image', 'content', img);
+ setAttr(
+ 'oembed-link',
+ 'href',
+ `${origin}/api/oembed?url=${encodeURIComponent(agentUrl)}`,
+ );
+ document.title = `${name} — 3D Agent`;
+ }
+
+ main().catch((err) => {
+ document.getElementById('agent-home-container').innerHTML =
+ `<div class="loading-placeholder">Could not load agent: ${err.message}</div>`;
+ });
+ </script>
+ </body>
</html>
diff --git a/public/artifact-example.html b/public/artifact-example.html
index ec34788e0..ca09ab9d1 100644
--- a/public/artifact-example.html
+++ b/public/artifact-example.html
@@ -1,17 +1,24 @@
<!doctype html>
<html lang="en">
-<head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <title>3D Agent — Artifact Example</title>
- <style>html, body { margin: 0; height: 100%; background: #111; }</style>
-</head>
-<body>
- <!--
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>3D Agent — Artifact Example</title>
+ <style>
+ html,
+ body {
+ margin: 0;
+ height: 100%;
+ background: #111;
+ }
+ </style>
+ </head>
+ <body>
+ <!--
Replace "demo" with your agent's ID from https://3dagent.vercel.app.
The agent's avatar must have visibility set to "public" or "unlisted".
-->
- <div data-agent-id="demo" style="width:100%;height:100vh"></div>
- <script type="module" src="https://3dagent.vercel.app/artifact.js"></script>
-</body>
+ <div data-agent-id="demo" style="width: 100%; height: 100vh"></div>
+ <script type="module" src="https://3dagent.vercel.app/artifact.js"></script>
+ </body>
</html>
diff --git a/public/artifact/README.md b/public/artifact/README.md
index b72a7ee94..b0cd2f07d 100644
--- a/public/artifact/README.md
+++ b/public/artifact/README.md
@@ -15,13 +15,13 @@ Claude will embed the artifact and display the live 3D character.
## Parameters
-| Param | Description |
-|---|---|
-| `agent` | Agent ID (required unless `model` is set) |
+| Param | Description |
+| ------- | ------------------------------------------------------- |
+| `agent` | Agent ID (required unless `model` is set) |
| `model` | Absolute `https://` URL to a GLB from a whitelisted CDN |
-| `theme` | `dark` (default) or `light` |
-| `idle` | Animation clip name to play while idle |
-| `bg` | Background hex colour (without `#`), e.g. `bg=1a0533` |
+| `theme` | `dark` (default) or `light` |
+| `idle` | Animation clip name to play while idle |
+| `bg` | Background hex colour (without `#`), e.g. `bg=1a0533` |
## Notes
diff --git a/public/artifact/index.html b/public/artifact/index.html
index 95a0a2d8c..f0353fb8a 100644
--- a/public/artifact/index.html
+++ b/public/artifact/index.html
@@ -1,4 +1,4 @@
-<!DOCTYPE html>
+<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
@@ -12,7 +12,10 @@
}
body {
- font-family: system-ui, -apple-system, sans-serif;
+ font-family:
+ system-ui,
+ -apple-system,
+ sans-serif;
background: #0a0e27;
color: #fff;
display: flex;
diff --git a/public/cz/README.md b/public/cz/README.md
index 7719d6556..a9b588405 100644
--- a/public/cz/README.md
+++ b/public/cz/README.md
@@ -80,9 +80,7 @@ Example for `vercel.json`:
```json
{
- "rewrites": [
- { "source": "/cz", "destination": "/cz/" }
- ]
+ "rewrites": [{ "source": "/cz", "destination": "/cz/" }]
}
```
diff --git a/public/cz/offline/README.md b/public/cz/offline/README.md
index 103548d5e..8175c8303 100644
--- a/public/cz/offline/README.md
+++ b/public/cz/offline/README.md
@@ -17,30 +17,34 @@ This directory contains the offline fallback for the CZ demo — a self-containe
## How It Works
### Avatar Loading
+
- Tries to load `/avatars/cz.glb` from the origin (served from `public/avatars/cz.glb`)
- If available, renders with Three.js (if loaded on the page)
- If unavailable or WebGL fails, falls back to a canvas-drawn placeholder
- **No external CDN calls; no IPFS gateway requests**
### Claim Flow
+
- User clicks "Claim Agent" button
- Modal plays a simulated claim sequence:
- 1. "Initializing claim flow…" (800ms)
- 2. "Connecting wallet…" (800ms)
- 3. "Submitting claim…" (800ms)
- 4. "Waiting for confirmation…" (800ms)
- 5. "Claim Successful!" + confetti (no delay)
+ 1. "Initializing claim flow…" (800ms)
+ 2. "Connecting wallet…" (800ms)
+ 3. "Submitting claim…" (800ms)
+ 4. "Waiting for confirmation…" (800ms)
+ 5. "Claim Successful!" + confetti (no delay)
- **No blockchain calls; no MetaMask interaction**
- No transaction is actually submitted; this is purely visual
### State Display
+
- Footer shows static values:
- - Agent ID: `0x1234567` (placeholder)
- - Chain: `Base Sepolia`
- - Owner: Not displayed (since no real onchain state)
+ - Agent ID: `0x1234567` (placeholder)
+ - Chain: `Base Sepolia`
+ - Owner: Not displayed (since no real onchain state)
- **All values are hardcoded; no API calls**
### Cache & Service Worker
+
- Page registers a service worker at `/cz/sw.js` (if available)
- If the page is cached, it loads instantly even if origin is unreachable
- Service worker is optional; page works without it
@@ -50,6 +54,7 @@ This directory contains the offline fallback for the CZ demo — a self-containe
## Testing the Offline Fallback
### Test 1: Network Throttling
+
```bash
# Open DevTools → Network tab
# Set throttling to "Offline"
@@ -58,6 +63,7 @@ This directory contains the offline fallback for the CZ demo — a self-containe
```
### Test 2: Hard Offline (Kill WiFi)
+
```bash
# Open /cz/offline/ in a browser
# Physically unplug ethernet or disable WiFi
@@ -65,6 +71,7 @@ This directory contains the offline fallback for the CZ demo — a self-containe
```
### Test 3: Origin Unreachable
+
```bash
# Open /cz/offline/ normally
# Block the origin in DevTools (DevTools → Network → Disable)
@@ -73,6 +80,7 @@ This directory contains the offline fallback for the CZ demo — a self-containe
```
### Test 4: Timing (Dry Run)
+
```bash
# Open /cz/offline/
# Click "Claim Agent" button
@@ -88,39 +96,46 @@ This directory contains the offline fallback for the CZ demo — a self-containe
## Integration with Live Demo
### When to Switch to Offline
+
- Avatar fails to load for > 30 seconds
- RPC node is down or extremely congested (claim stuck > 2 minutes)
- Entire staging server is unreachable (502/503)
- WiFi drops mid-demo
### How to Switch
+
1. **In the browser:** Open a new tab or window to `/cz/offline/`
2. **Say to audience:** "We're in offline mode now, but the agent is fully cached and ready."
3. **Run the demo:** Same 9-step sequence, but the claim is instant (no real tx)
4. **Be honest:** If asked, say "This is a pre-rendered demo version—on mainnet, this would be live."
### Before/After Behavior
-| Aspect | Live (`/cz`) | Offline (`/cz/offline/`) |
-|---|---|---|
-| Avatar | Loaded from `/avatars/cz.glb` (live) | Loaded from `/avatars/cz.glb` (cached) or fallback image |
-| Claim TX | Real signature + submit to RPC | Fake modal, no tx |
-| State | From `/api/cz/identity` (live API) | Hardcoded placeholder |
-| Claim Time | 30–60 seconds | ~4 seconds |
-| Network | Requires live staging + RPC | Zero external calls |
+
+| Aspect | Live (`/cz`) | Offline (`/cz/offline/`) |
+| ---------- | ------------------------------------ | -------------------------------------------------------- |
+| Avatar | Loaded from `/avatars/cz.glb` (live) | Loaded from `/avatars/cz.glb` (cached) or fallback image |
+| Claim TX | Real signature + submit to RPC | Fake modal, no tx |
+| State | From `/api/cz/identity` (live API) | Hardcoded placeholder |
+| Claim Time | 30–60 seconds | ~4 seconds |
+| Network | Requires live staging + RPC | Zero external calls |
---
## Customization
### Change Hardcoded Values
+
In `index.html`, search for these and update:
+
```javascript
Agent ID: 0x1234567 // Change to real agentId
Chain: Base Sepolia // Keep or update
```
### Change Claim Timing
+
In `index.html`, `handleClaimClick()` function:
+
```javascript
setTimeout(() => { ... }, 800) // First modal at 800ms
setTimeout(() => { ... }, 1600) // Second modal at 1600ms
@@ -128,32 +143,38 @@ setTimeout(() => { ... }, 1600) // Second modal at 1600ms
```
### Change Colors / Styling
+
In the `<style>` section:
+
```css
-background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%); /* bg color */
-background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); /* button color */
+background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%); /* bg color */
+background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); /* button color */
```
### Add a Real Screenshot Fallback
+
If Three.js is unavailable, the fallback currently draws a placeholder on canvas. To add a real screenshot:
+
1. Take a screenshot of the live demo (`/cz`) with avatar rendered
2. Save as `fallback.png` in this directory
3. Update `loadFallback()` in `index.html` to use the image:
- ```javascript
- fallback.src = '/cz/offline/fallback.png';
- ```
+ ```javascript
+ fallback.src = '/cz/offline/fallback.png';
+ ```
---
## Limitations & Future Work
### Current Limitations
+
- Avatar rendering is a placeholder (no Three.js integration yet)
- Claim flow is purely visual (no real blockchain state)
- State values are hardcoded (no dynamic data from API)
- Service worker (`/cz/sw.js`) is not yet implemented
### Future Enhancements
+
- [ ] Embed actual GLB file as base64 in HTML (self-contained binary)
- [ ] Integrate Three.js for full 3D avatar rendering
- [ ] Implement `/cz/sw.js` for offline caching
@@ -173,21 +194,25 @@ If Three.js is unavailable, the fallback currently draws a placeholder on canvas
## Troubleshooting
### Avatar shows as placeholder, not 3D
+
- Check DevTools Console for errors
- Verify `/avatars/cz.glb` is being loaded (Network tab)
- Confirm Three.js is available (try `typeof THREE` in console)
### Claim button doesn't respond
+
- Check DevTools Console for JavaScript errors
- Refresh the page
- Try in incognito mode (clear cookies)
### Service worker not registered
+
- `/cz/sw.js` may not exist yet (that's ok; page still works)
- Check DevTools → Application → Service Workers for status
- This is optional for offline demo to work
### Page is slow or jittery
+
- Close other browser tabs (free up memory)
- Disable browser extensions
- Try a different browser (Chrome, Firefox, Safari, Edge)
@@ -199,6 +224,7 @@ If Three.js is unavailable, the fallback currently draws a placeholder on canvas
If the offline fallback isn't working or needs updates, file an issue or reach out to the team.
For live demo day:
+
- **Backup operator:** Have a second laptop with offline page pre-loaded
- **Screenshot:** Keep a static screenshot of the success state as a final fallback
- **Notes:** Write down any issues encountered for post-mortem
diff --git a/public/cz/offline/index.html b/public/cz/offline/index.html
index d40525829..33c3f7571 100644
--- a/public/cz/offline/index.html
+++ b/public/cz/offline/index.html
@@ -1,310 +1,311 @@
-<!DOCTYPE html>
+<!doctype html>
<html lang="en">
-<head>
- <meta charset="UTF-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>CZ Agent — Offline Demo</title>
- <style>
- * {
- margin: 0;
- padding: 0;
- box-sizing: border-box;
- }
-
- body {
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
- background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
- color: #fff;
- overflow: hidden;
- height: 100vh;
- }
-
- .container {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- height: 100vh;
- position: relative;
- }
-
- .header {
- position: absolute;
- top: 24px;
- left: 24px;
- right: 24px;
- z-index: 10;
- }
-
- .offline-badge {
- display: inline-block;
- background: rgba(255, 255, 255, 0.1);
- border: 1px solid rgba(255, 255, 255, 0.2);
- padding: 8px 16px;
- border-radius: 8px;
- font-size: 12px;
- font-weight: 600;
- letter-spacing: 0.5px;
- text-transform: uppercase;
- }
-
- .badge-dot {
- display: inline-block;
- width: 6px;
- height: 6px;
- background: #fbbf24;
- border-radius: 50%;
- margin-right: 6px;
- animation: pulse 2s infinite;
- }
-
- @keyframes pulse {
- 0%, 100% {
- opacity: 1;
- }
- 50% {
- opacity: 0.5;
- }
- }
-
- .avatar-container {
- width: 100%;
- height: 100%;
- display: flex;
- align-items: center;
- justify-content: center;
- position: relative;
- }
-
- #viewer {
- width: 100%;
- height: 100%;
- }
-
- .fallback-image {
- width: 100%;
- height: 100%;
- object-fit: cover;
- display: none;
- }
-
- .modal {
- position: fixed;
- top: 0;
- left: 0;
- right: 0;
- bottom: 0;
- background: rgba(0, 0, 0, 0.6);
- display: none;
- align-items: center;
- justify-content: center;
- z-index: 100;
- }
-
- .modal.active {
- display: flex;
- }
-
- .modal-content {
- background: #16213e;
- border: 1px solid rgba(255, 255, 255, 0.1);
- border-radius: 12px;
- padding: 40px;
- max-width: 400px;
- text-align: center;
- box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
- }
-
- .modal-content h2 {
- font-size: 24px;
- margin-bottom: 16px;
- color: #fff;
- }
-
- .modal-content p {
- font-size: 14px;
- color: rgba(255, 255, 255, 0.7);
- line-height: 1.6;
- margin-bottom: 24px;
- }
-
- .button {
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
- color: white;
- border: none;
- padding: 12px 24px;
- border-radius: 8px;
- font-size: 14px;
- font-weight: 600;
- cursor: pointer;
- transition: transform 0.2s, box-shadow 0.2s;
- }
-
- .button:hover {
- transform: translateY(-2px);
- box-shadow: 0 8px 16px rgba(102, 126, 234, 0.4);
- }
-
- .button:active {
- transform: translateY(0);
- }
-
- .spinner {
- width: 40px;
- height: 40px;
- border: 3px solid rgba(255, 255, 255, 0.1);
- border-top-color: #667eea;
- border-radius: 50%;
- animation: spin 1s linear infinite;
- margin: 0 auto 24px;
- }
-
- @keyframes spin {
- to {
- transform: rotate(360deg);
- }
- }
-
- .footer {
- position: absolute;
- bottom: 24px;
- left: 24px;
- right: 24px;
- font-size: 12px;
- color: rgba(255, 255, 255, 0.5);
- text-align: center;
- }
-
- .footer-item {
- display: inline-block;
- margin: 0 8px;
- }
-
- .code {
- font-family: 'Monaco', 'Courier New', monospace;
- background: rgba(255, 255, 255, 0.1);
- padding: 2px 6px;
- border-radius: 3px;
- font-size: 11px;
- }
-
- .confetti {
- position: fixed;
- pointer-events: none;
- }
- </style>
-</head>
-<body>
- <div class="header">
- <div class="offline-badge">
- <span class="badge-dot"></span>
- Offline Demo Mode
- </div>
- </div>
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>CZ Agent — Offline Demo</title>
+ <style>
+ * {
+ margin: 0;
+ padding: 0;
+ box-sizing: border-box;
+ }
+
+ body {
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
+ background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
+ color: #fff;
+ overflow: hidden;
+ height: 100vh;
+ }
+
+ .container {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ height: 100vh;
+ position: relative;
+ }
- <div class="container">
- <div class="avatar-container">
- <canvas id="viewer"></canvas>
- <img id="fallback" class="fallback-image" alt="CZ Avatar" />
+ .header {
+ position: absolute;
+ top: 24px;
+ left: 24px;
+ right: 24px;
+ z-index: 10;
+ }
+
+ .offline-badge {
+ display: inline-block;
+ background: rgba(255, 255, 255, 0.1);
+ border: 1px solid rgba(255, 255, 255, 0.2);
+ padding: 8px 16px;
+ border-radius: 8px;
+ font-size: 12px;
+ font-weight: 600;
+ letter-spacing: 0.5px;
+ text-transform: uppercase;
+ }
+
+ .badge-dot {
+ display: inline-block;
+ width: 6px;
+ height: 6px;
+ background: #fbbf24;
+ border-radius: 50%;
+ margin-right: 6px;
+ animation: pulse 2s infinite;
+ }
+
+ @keyframes pulse {
+ 0%,
+ 100% {
+ opacity: 1;
+ }
+ 50% {
+ opacity: 0.5;
+ }
+ }
+
+ .avatar-container {
+ width: 100%;
+ height: 100%;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ position: relative;
+ }
+
+ #viewer {
+ width: 100%;
+ height: 100%;
+ }
+
+ .fallback-image {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: none;
+ }
+
+ .modal {
+ position: fixed;
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ background: rgba(0, 0, 0, 0.6);
+ display: none;
+ align-items: center;
+ justify-content: center;
+ z-index: 100;
+ }
+
+ .modal.active {
+ display: flex;
+ }
+
+ .modal-content {
+ background: #16213e;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ border-radius: 12px;
+ padding: 40px;
+ max-width: 400px;
+ text-align: center;
+ box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
+ }
+
+ .modal-content h2 {
+ font-size: 24px;
+ margin-bottom: 16px;
+ color: #fff;
+ }
+
+ .modal-content p {
+ font-size: 14px;
+ color: rgba(255, 255, 255, 0.7);
+ line-height: 1.6;
+ margin-bottom: 24px;
+ }
+
+ .button {
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
+ color: white;
+ border: none;
+ padding: 12px 24px;
+ border-radius: 8px;
+ font-size: 14px;
+ font-weight: 600;
+ cursor: pointer;
+ transition:
+ transform 0.2s,
+ box-shadow 0.2s;
+ }
+
+ .button:hover {
+ transform: translateY(-2px);
+ box-shadow: 0 8px 16px rgba(102, 126, 234, 0.4);
+ }
+
+ .button:active {
+ transform: translateY(0);
+ }
+
+ .spinner {
+ width: 40px;
+ height: 40px;
+ border: 3px solid rgba(255, 255, 255, 0.1);
+ border-top-color: #667eea;
+ border-radius: 50%;
+ animation: spin 1s linear infinite;
+ margin: 0 auto 24px;
+ }
+
+ @keyframes spin {
+ to {
+ transform: rotate(360deg);
+ }
+ }
+
+ .footer {
+ position: absolute;
+ bottom: 24px;
+ left: 24px;
+ right: 24px;
+ font-size: 12px;
+ color: rgba(255, 255, 255, 0.5);
+ text-align: center;
+ }
+
+ .footer-item {
+ display: inline-block;
+ margin: 0 8px;
+ }
+
+ .code {
+ font-family: 'Monaco', 'Courier New', monospace;
+ background: rgba(255, 255, 255, 0.1);
+ padding: 2px 6px;
+ border-radius: 3px;
+ font-size: 11px;
+ }
+
+ .confetti {
+ position: fixed;
+ pointer-events: none;
+ }
+ </style>
+ </head>
+ <body>
+ <div class="header">
+ <div class="offline-badge">
+ <span class="badge-dot"></span>
+ Offline Demo Mode
+ </div>
</div>
- </div>
- <div class="modal" id="modal">
- <div class="modal-content">
- <div id="modal-body"></div>
+ <div class="container">
+ <div class="avatar-container">
+ <canvas id="viewer"></canvas>
+ <img id="fallback" class="fallback-image" alt="CZ Avatar" />
+ </div>
</div>
- </div>
- <div class="footer">
- <div class="footer-item">CZ Agent</div>
- <div class="footer-item">•</div>
- <div class="footer-item">
- Agent ID: <span class="code">0x1234567</span>
+ <div class="modal" id="modal">
+ <div class="modal-content">
+ <div id="modal-body"></div>
+ </div>
</div>
- <div class="footer-item">•</div>
- <div class="footer-item">
- Chain: <span class="code">Base Sepolia</span>
+
+ <div class="footer">
+ <div class="footer-item">CZ Agent</div>
+ <div class="footer-item">•</div>
+ <div class="footer-item">Agent ID: <span class="code">0x1234567</span></div>
+ <div class="footer-item">•</div>
+ <div class="footer-item">Chain: <span class="code">Base Sepolia</span></div>
</div>
- </div>
- <script>
- // Offline demo mode: loads avatar GLB from origin, shows pre-rendered claim flow
- // Falls back to static image if WebGL unavailable or network fails
+ <script>
+ // Offline demo mode: loads avatar GLB from origin, shows pre-rendered claim flow
+ // Falls back to static image if WebGL unavailable or network fails
- const modal = document.getElementById('modal');
- const modalBody = document.getElementById('modal-body');
- const viewer = document.getElementById('viewer');
- const fallback = document.getElementById('fallback');
+ const modal = document.getElementById('modal');
+ const modalBody = document.getElementById('modal-body');
+ const viewer = document.getElementById('viewer');
+ const fallback = document.getElementById('fallback');
- // Initialize Three.js viewer (optional: gracefully degrade if not available)
- // For now, we'll load the avatar and render it with a simple viewer
- // If Three.js is not available, the fallback image will be shown
+ // Initialize Three.js viewer (optional: gracefully degrade if not available)
+ // For now, we'll load the avatar and render it with a simple viewer
+ // If Three.js is not available, the fallback image will be shown
- function showModal(html) {
- modalBody.innerHTML = html;
- modal.classList.add('active');
- }
+ function showModal(html) {
+ modalBody.innerHTML = html;
+ modal.classList.add('active');
+ }
- function hideModal() {
- modal.classList.remove('active');
- }
+ function hideModal() {
+ modal.classList.remove('active');
+ }
- // Simulate claim flow
- function handleClaimClick() {
- showModal(`
+ // Simulate claim flow
+ function handleClaimClick() {
+ showModal(`
<div class="spinner"></div>
<p>Initializing claim flow...</p>
`);
- setTimeout(() => {
- showModal(`
+ setTimeout(() => {
+ showModal(`
<div class="spinner"></div>
<p>Connecting wallet...</p>
`);
- }, 800);
+ }, 800);
- setTimeout(() => {
- showModal(`
+ setTimeout(() => {
+ showModal(`
<div class="spinner"></div>
<p>Submitting claim...</p>
`);
- }, 1600);
+ }, 1600);
- setTimeout(() => {
- showModal(`
+ setTimeout(() => {
+ showModal(`
<div class="spinner"></div>
<p>Waiting for confirmation...</p>
`);
- }, 2400);
+ }, 2400);
- setTimeout(() => {
- playConfetti();
- showModal(`
+ setTimeout(() => {
+ playConfetti();
+ showModal(`
<h2>Claim Successful!</h2>
<p>Your agent is now registered on Base Sepolia.</p>
<p>Transaction: <span class="code">0xabc123…</span></p>
<button class="button" onclick="document.getElementById('modal').classList.remove('active')">Close</button>
`);
- }, 3200);
- }
-
- // Confetti animation
- function playConfetti() {
- const count = 50;
- for (let i = 0; i < count; i++) {
- const confetti = document.createElement('div');
- confetti.className = 'confetti';
- confetti.style.left = Math.random() * 100 + '%';
- confetti.style.top = '-10px';
- confetti.style.backgroundColor = ['#667eea', '#764ba2', '#f093fb', '#4facfe'][Math.floor(Math.random() * 4)];
- confetti.style.width = Math.random() * 10 + 5 + 'px';
- confetti.style.height = confetti.style.width;
- confetti.style.borderRadius = '50%';
-
- document.body.appendChild(confetti);
-
- const duration = Math.random() * 2 + 2; // 2-4 seconds
- const keyframes = `
+ }, 3200);
+ }
+
+ // Confetti animation
+ function playConfetti() {
+ const count = 50;
+ for (let i = 0; i < count; i++) {
+ const confetti = document.createElement('div');
+ confetti.className = 'confetti';
+ confetti.style.left = Math.random() * 100 + '%';
+ confetti.style.top = '-10px';
+ confetti.style.backgroundColor = ['#667eea', '#764ba2', '#f093fb', '#4facfe'][
+ Math.floor(Math.random() * 4)
+ ];
+ confetti.style.width = Math.random() * 10 + 5 + 'px';
+ confetti.style.height = confetti.style.width;
+ confetti.style.borderRadius = '50%';
+
+ document.body.appendChild(confetti);
+
+ const duration = Math.random() * 2 + 2; // 2-4 seconds
+ const keyframes = `
@keyframes fall-${i} {
to {
transform: translateY(${window.innerHeight + 20}px) rotate(720deg);
@@ -312,134 +313,143 @@
}
}
`;
- const style = document.createElement('style');
- style.textContent = keyframes;
- document.head.appendChild(style);
+ const style = document.createElement('style');
+ style.textContent = keyframes;
+ document.head.appendChild(style);
- confetti.style.animation = `fall-${i} ${duration}s ease-in forwards`;
+ confetti.style.animation = `fall-${i} ${duration}s ease-in forwards`;
- setTimeout(() => confetti.remove(), duration * 1000);
+ setTimeout(() => confetti.remove(), duration * 1000);
+ }
}
- }
- // Try to load Three.js and render the avatar
- async function initViewer() {
- try {
- // Check if Three.js is available
- if (typeof THREE === 'undefined') {
- console.warn('Three.js not available, using fallback image');
- loadFallback();
- return;
- }
+ // Try to load Three.js and render the avatar
+ async function initViewer() {
+ try {
+ // Check if Three.js is available
+ if (typeof THREE === 'undefined') {
+ console.warn('Three.js not available, using fallback image');
+ loadFallback();
+ return;
+ }
+
+ // Load GLB from origin
+ const glbUrl = '/avatars/cz.glb';
+ const response = await fetch(glbUrl);
+ if (!response.ok) {
+ console.warn(
+ `Failed to load GLB: ${response.status}`,
+ 'falling back to image',
+ );
+ loadFallback();
+ return;
+ }
- // Load GLB from origin
- const glbUrl = '/avatars/cz.glb';
- const response = await fetch(glbUrl);
- if (!response.ok) {
- console.warn(`Failed to load GLB: ${response.status}`, 'falling back to image');
+ // If we have Three.js and the GLB, render it
+ // This is a simplified viewer; full implementation would use three-std or similar
+ console.log('GLB loaded successfully, could render with Three.js');
+
+ // For now, just show a placeholder
+ viewer.style.background =
+ 'radial-gradient(ellipse at center, #2d3d5c 0%, #1a1a2e 100%)';
+ const ctx = viewer.getContext('2d');
+ if (ctx) {
+ ctx.fillStyle = '#667eea';
+ ctx.font = '14px sans-serif';
+ ctx.textAlign = 'center';
+ ctx.fillText('CZ Avatar', viewer.width / 2, viewer.height / 2 - 10);
+ ctx.font = '12px sans-serif';
+ ctx.fillStyle = 'rgba(255, 255, 255, 0.5)';
+ ctx.fillText(
+ '(3D rendering requires Three.js)',
+ viewer.width / 2,
+ viewer.height / 2 + 20,
+ );
+ }
+ } catch (err) {
+ console.error('Avatar initialization error:', err);
loadFallback();
- return;
}
+ }
- // If we have Three.js and the GLB, render it
- // This is a simplified viewer; full implementation would use three-std or similar
- console.log('GLB loaded successfully, could render with Three.js');
-
+ function loadFallback() {
+ // In production, this would be a pre-rendered screenshot of the avatar
// For now, just show a placeholder
- viewer.style.background = 'radial-gradient(ellipse at center, #2d3d5c 0%, #1a1a2e 100%)';
- const ctx = viewer.getContext('2d');
- if (ctx) {
- ctx.fillStyle = '#667eea';
- ctx.font = '14px sans-serif';
- ctx.textAlign = 'center';
- ctx.fillText('CZ Avatar', viewer.width / 2, viewer.height / 2 - 10);
- ctx.font = '12px sans-serif';
- ctx.fillStyle = 'rgba(255, 255, 255, 0.5)';
- ctx.fillText('(3D rendering requires Three.js)', viewer.width / 2, viewer.height / 2 + 20);
+ fallback.style.display = 'block';
+ fallback.style.background =
+ 'radial-gradient(ellipse at center, #2d3d5c 0%, #1a1a2e 100%)';
+
+ // Create a canvas fallback
+ const canvas = document.createElement('canvas');
+ canvas.width = window.innerWidth;
+ canvas.height = window.innerHeight;
+ const ctx = canvas.getContext('2d');
+ ctx.fillStyle = '#1a1a2e';
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
+ ctx.fillStyle = '#667eea';
+ ctx.font = 'bold 48px sans-serif';
+ ctx.textAlign = 'center';
+ ctx.fillText('CZ', canvas.width / 2, canvas.height / 2);
+ ctx.font = '14px sans-serif';
+ ctx.fillStyle = 'rgba(255, 255, 255, 0.5)';
+ ctx.fillText('Offline Demo Mode', canvas.width / 2, canvas.height / 2 + 60);
+
+ fallback.src = canvas.toDataURL();
+ }
+
+ // Handle window resize
+ function handleResize() {
+ if (viewer) {
+ viewer.width = viewer.offsetWidth;
+ viewer.height = viewer.offsetHeight;
}
- } catch (err) {
- console.error('Avatar initialization error:', err);
- loadFallback();
- }
- }
-
- function loadFallback() {
- // In production, this would be a pre-rendered screenshot of the avatar
- // For now, just show a placeholder
- fallback.style.display = 'block';
- fallback.style.background = 'radial-gradient(ellipse at center, #2d3d5c 0%, #1a1a2e 100%)';
-
- // Create a canvas fallback
- const canvas = document.createElement('canvas');
- canvas.width = window.innerWidth;
- canvas.height = window.innerHeight;
- const ctx = canvas.getContext('2d');
- ctx.fillStyle = '#1a1a2e';
- ctx.fillRect(0, 0, canvas.width, canvas.height);
- ctx.fillStyle = '#667eea';
- ctx.font = 'bold 48px sans-serif';
- ctx.textAlign = 'center';
- ctx.fillText('CZ', canvas.width / 2, canvas.height / 2);
- ctx.font = '14px sans-serif';
- ctx.fillStyle = 'rgba(255, 255, 255, 0.5)';
- ctx.fillText('Offline Demo Mode', canvas.width / 2, canvas.height / 2 + 60);
-
- fallback.src = canvas.toDataURL();
- }
-
- // Handle window resize
- function handleResize() {
- if (viewer) {
- viewer.width = viewer.offsetWidth;
- viewer.height = viewer.offsetHeight;
- }
- }
-
- window.addEventListener('resize', handleResize);
- handleResize();
-
- // Create a claim button in the overlay
- function createUI() {
- const ui = document.createElement('div');
- ui.style.position = 'fixed';
- ui.style.bottom = '100px';
- ui.style.left = '50%';
- ui.style.transform = 'translateX(-50%)';
- ui.style.zIndex = '50';
- ui.innerHTML = `
+ }
+
+ window.addEventListener('resize', handleResize);
+ handleResize();
+
+ // Create a claim button in the overlay
+ function createUI() {
+ const ui = document.createElement('div');
+ ui.style.position = 'fixed';
+ ui.style.bottom = '100px';
+ ui.style.left = '50%';
+ ui.style.transform = 'translateX(-50%)';
+ ui.style.zIndex = '50';
+ ui.innerHTML = `
<button class="button" style="font-size: 16px; padding: 16px 32px;" onclick="window.handleClaimClick()">
Claim Agent
</button>
`;
- document.body.appendChild(ui);
- }
-
- // Export for global access
- window.handleClaimClick = handleClaimClick;
-
- // Initialize when page loads
- document.addEventListener('DOMContentLoaded', () => {
- createUI();
- initViewer();
- });
-
- // Handle visibility change (pause/resume animations)
- document.addEventListener('visibilitychange', () => {
- if (document.hidden) {
- console.log('Demo paused');
- } else {
- console.log('Demo resumed');
- }
- });
-
- // Service worker registration (for cache awareness)
- if ('serviceWorker' in navigator) {
- navigator.serviceWorker.register('/cz/sw.js').catch(err => {
- console.log('Service Worker registration failed:', err);
+ document.body.appendChild(ui);
+ }
+
+ // Export for global access
+ window.handleClaimClick = handleClaimClick;
+
+ // Initialize when page loads
+ document.addEventListener('DOMContentLoaded', () => {
+ createUI();
+ initViewer();
});
- }
- console.log('CZ Offline Demo initialized');
- </script>
-</body>
+ // Handle visibility change (pause/resume animations)
+ document.addEventListener('visibilitychange', () => {
+ if (document.hidden) {
+ console.log('Demo paused');
+ } else {
+ console.log('Demo resumed');
+ }
+ });
+
+ // Service worker registration (for cache awareness)
+ if ('serviceWorker' in navigator) {
+ navigator.serviceWorker.register('/cz/sw.js').catch((err) => {
+ console.log('Service Worker registration failed:', err);
+ });
+ }
+
+ console.log('CZ Offline Demo initialized');
+ </script>
+ </body>
</html>
diff --git a/public/dashboard/avaturn-sdk.js b/public/dashboard/avaturn-sdk.js
new file mode 100644
index 000000000..8133d66ea
--- /dev/null
+++ b/public/dashboard/avaturn-sdk.js
@@ -0,0 +1 @@
+function e(t,s){return e=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},e(t,s)}var t,s;!function(e){e.AuthError="auth_error",e.AvatarLoadError="avatar_load_error",e.SceneError="scene_error"}(t||(t={})),function(e){e.AskForDefaults="ask_for_defaults",e.SDKHandshake="sdk_handshake",e.SDKHandshakeConfirmation="sdk_handshake_confirmation",e.CallbackEvent="callback_event",e.ReportError="report_error",e.GetAssetList="get_assets_list",e.GetActiveAssets="get_active_assets",e.SetAvailableAssets="set_assets_list",e.SetActiveAsset="set_active_asset",e.GetBodyList="get_bodies_list",e.GetActiveBody="get_avatar_info",e.SetAvailableBodies="set_bodies_list",e.SetActiveBody="set_active_body",e.GetAnimationList="get_animation_list",e.GetActiveAnimation="get_animation_info",e.SetActiveAnimation="set_active_animation",e.ExportAvatar="export_avatar",e.GenerateThumbnail="generate_thumbnail",e.SetParam="set_param",e.SetEyeColor="set_eye_color",e.SetHairColor="set_hair_color",e.SetEyewearColor="set_eyewear_color",e.SetBodyProportions="set_body_proportions",e.SetSkinTone="set_skin_tone",e.GetEyeColor="get_eye_color",e.GetHairColor="get_hair_color",e.GetEyewearColor="get_eyewear_color",e.GetBodyProportions="get_body_proportions",e.GetSkinTone="get_skin_tone",e.GetAvatarId="get_avatar_id"}(s||(s={}));var r=/*#__PURE__*/function(){function e(){this.listeners={}}var t=e.prototype;return t.watch=function(e,t){this.listeners[e]=t},t.unwatch=function(e){delete this.listeners[e]},e}(),n=/*#__PURE__*/function(){function e(e,t){this.handshakeData={},this.recipient=void 0,this.thisSourceName="v1.avaturn-sdk",this.expectedIncomingSourceName="v1.avaturn-sdk-server",this._queue=new r,this._messageHandler=this.messageHandler.bind(this),e&&(this.thisSourceName=e),t&&(this.expectedIncomingSourceName=t)}var t=e.prototype;return t.sendMessage=function(e,t,s,r){var n=this;return void 0===r&&(r=!0),new Promise(function(o,i){var a,c=Date.now(),u=s||e+c;r&&n._queue.watch(u,function(e,t){var s=null!=t?t:null;e?o(s):i(s),n._queue.unwatch(u)}),null==(a=n.recipient)||a.postMessage({type:"MESSAGE",source:n.thisSourceName,eventName:e,key:u,date:c,data:t,isOk:!0},"*"),r||o(null)})},t.messageHandler=function(e){var t=e.data;this.expectedIncomingSourceName==t.source&&("RESPONSE"===t.type&&("sdk_handshake"===t.key&&this.sendMessage(s.SDKHandshakeConfirmation,this.handshakeData,void 0,!1),this._queue.listeners[t.key]&&this._queue.listeners[t.key](t.isOk,t.data)),"MESSAGE"===t.type&&this.handleMessage(t))},t.setupMessaging=function(){window.addEventListener("message",this._messageHandler)},t.destroyMessaging=function(){console.log("destroy"),window.removeEventListener("message",this._messageHandler)},t.sendResponse=function(e,t,s){var r,n=void 0===s?{isOk:!0}:s,o=n.isOk,i=n.data;if(this.recipient){var a={type:"RESPONSE",source:this.thisSourceName,eventName:e,key:t,date:Date.now(),data:i,isOk:o};null==(r=this.recipient)||r.postMessage(a,"*")}else console.log("Recipient is not set.")},t.handleMessage=function(e){},e}(),o=/*#__PURE__*/function(t){function r(){var e;return(e=t.call(this)||this)._version="1.1.4",e.defaultAssets=void 0,e.sceneRef=null,e.callbacks={},e.suppressCallbacks=void 0,e}var n,o;o=t,(n=r).prototype=Object.create(o.prototype),n.prototype.constructor=n,e(n,o);var i=r.prototype;return i.applyStyles=function(e){e.style.width="100%",e.style.height="100%"},i.validateDefaultAssets=function(e){return"object"==typeof e&&"boolean"==typeof e.overrideSaved&&!!Array.isArray(e.assets)},i.setupDOM=function(e,t,s){var r,n=document.querySelector("#avaturn-sdk-iframe");n&&n.remove();var o=document.createElement("iframe");o.setAttribute("src",t),o.setAttribute("id","avaturn-sdk-iframe"),o.setAttribute("allow","camera *; clipboard-write"),o.setAttribute("allowfullscreen",""),o.setAttribute("frameborder","0"),s?o.setAttribute("class",s):this.applyStyles(o),e.appendChild(o),this.sceneRef=document.querySelector("#avaturn-sdk-iframe"),this.recipient=null==(r=this.sceneRef)?void 0:r.contentWindow},i.handleMessage=function(e){var t,r,n,o;switch(e.eventName){case s.AskForDefaults:this.sendResponse(s.AskForDefaults,e.key,{isOk:!0,data:this.defaultAssets});break;case s.CallbackEvent:null==(t=(r=this.callbacks)[e.key])||t.call(r,e.data);break;case s.ReportError:null==(n=(o=this.callbacks).error)||n.call(o,e.data)}},i.init=function(e,t){var r=t.url,n=t.iframeClassName,o=t.disableUi,i=t.defaultAssets;try{var a=this;if(a.suppressCallbacks=o,i&&!a.validateDefaultAssets(i))throw new Error("Field 'defaultAssets' has an invalid format");a.defaultAssets=i;var c=new URL(r||"https://preview.avaturn.dev/editor?avatar_link=https%3A%2F%2Fassets.avaturn.me%2Feditor_resources%2Fdefault_male.glb");return c.searchParams.append("sdk","true"),o&&c.searchParams.append("noui","true"),e?a.setupDOM(e,c.toString(),n):a.recipient=window,a.handshakeData={url:document.location.href,environment:window.avaturnSDKEnvironment,version:a._version},a.setupMessaging(),Promise.resolve(a.sendMessage(s.SDKHandshake,a.handshakeData,"sdk_handshake").then(function(){try{return Promise.resolve(a.sendMessage(s.SDKHandshakeConfirmation,a.handshakeData,void 0,!1)).then(function(){return a})}catch(e){return Promise.reject(e)}}).catch(function(e){throw new Error(e)}))}catch(e){return Promise.reject(e)}},i.destroy=function(){this.destroyMessaging(),this.callbacks={}},i.on=function(e,t){return this.suppressCallbacks&&"load"!=e?(console.log("Can't use callbacks for "+e+" in disableUi mode. Use <action>.then(...) instead."),this):(this.callbacks[e]=t,this)},i.getAssetList=function(){try{return Promise.resolve(this.sendMessage(s.GetAssetList))}catch(e){return Promise.reject(e)}},i.setAvailableAssets=function(e){try{return Promise.resolve(this.sendMessage(s.SetAvailableAssets,e))}catch(e){return Promise.reject(e)}},i.getActiveAssets=function(){try{return Promise.resolve(this.sendMessage(s.GetActiveAssets))}catch(e){return Promise.reject(e)}},i.setActiveAsset=function(e){try{return Promise.resolve(this.sendMessage(s.SetActiveAsset,e))}catch(e){return Promise.reject(e)}},i.setActiveBody=function(e){try{return Promise.resolve(this.sendMessage(s.SetActiveBody,e))}catch(e){return Promise.reject(e)}},i.getBodyList=function(){try{return Promise.resolve(this.sendMessage(s.GetBodyList))}catch(e){return Promise.reject(e)}},i.getActiveBody=function(){try{return Promise.resolve(this.sendMessage(s.GetActiveBody))}catch(e){return Promise.reject(e)}},i.setActiveAnimation=function(e){try{return Promise.resolve(this.sendMessage(s.SetActiveAnimation,e))}catch(e){return Promise.reject(e)}},i.getActiveAnimation=function(){try{return Promise.resolve(this.sendMessage(s.GetActiveAnimation))}catch(e){return Promise.reject(e)}},i.getAnimationList=function(){try{return Promise.resolve(this.sendMessage(s.GetAnimationList))}catch(e){return Promise.reject(e)}},i.exportAvatar=function(){try{return Promise.resolve(this.sendMessage(s.ExportAvatar,void 0,"export_avatar"))}catch(e){return Promise.reject(e)}},i.setEyeColor=function(e){try{return Promise.resolve(this.sendMessage(s.SetEyeColor,e))}catch(e){return Promise.reject(e)}},i.setHairColor=function(e){try{return Promise.resolve(this.sendMessage(s.SetHairColor,e))}catch(e){return Promise.reject(e)}},i.setEyewearColor=function(e){try{return Promise.resolve(this.sendMessage(s.SetEyewearColor,e))}catch(e){return Promise.reject(e)}},i.setBodyProportions=function(e,t){try{return Promise.resolve(this.sendMessage(s.SetBodyProportions,{key:e,value:t}))}catch(e){return Promise.reject(e)}},i.setSkinToneCorrection=function(e){try{return Promise.resolve(this.sendMessage(s.SetSkinTone,e))}catch(e){return Promise.reject(e)}},i.getEyeColor=function(){try{return Promise.resolve(this.sendMessage(s.GetEyeColor))}catch(e){return Promise.reject(e)}},i.getHairColor=function(){try{return Promise.resolve(this.sendMessage(s.GetHairColor))}catch(e){return Promise.reject(e)}},i.getEyewearColor=function(){try{return Promise.resolve(this.sendMessage(s.GetEyewearColor))}catch(e){return Promise.reject(e)}},i.getBodyProportions=function(){try{return Promise.resolve(this.sendMessage(s.GetBodyProportions))}catch(e){return Promise.reject(e)}},i.getSkinToneCorrection=function(){try{return Promise.resolve(this.sendMessage(s.GetSkinTone))}catch(e){return Promise.reject(e)}},i.getAvatarId=function(){return this.sendMessage(s.GetAvatarId)},r}(n);export{o as AvaturnSDK,s as MessageType,n as Messaging,t as SDKErrors};
diff --git a/public/docs-widgets.html b/public/docs-widgets.html
index 103458f3b..b671b445a 100644
--- a/public/docs-widgets.html
+++ b/public/docs-widgets.html
@@ -1,178 +1,287 @@
<!doctype html>
<html lang="en">
-<head>
- <meta charset="utf-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <title>Widget Docs — 3D Agent</title>
- <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
- <meta name="description" content="Embed 3D widgets on any site. URL params, iframe + script embeds, postMessage API, oEmbed, privacy.">
- <meta name="theme-color" content="#0a0a0a">
-
- <meta property="og:type" content="article">
- <meta property="og:title" content="3D Agent — Widget Docs">
- <meta property="og:description" content="Embed 3D widgets on any site. URL params, postMessage API, oEmbed, privacy.">
- <meta property="og:url" content="https://3dagent.vercel.app/docs/widgets">
-
- <link rel="canonical" href="https://3dagent.vercel.app/docs/widgets">
- <link rel="shortcut icon" href="/favicon.ico">
- <link rel="preconnect" href="https://fonts.googleapis.com">
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
- <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap" rel="stylesheet">
- <link rel="stylesheet" href="/style.css">
- <link rel="stylesheet" href="/widgets-gallery/gallery.css">
- <style>
- .docs-main {
- max-width: 760px;
- margin: 0 auto;
- padding: var(--space-2xl) var(--space-lg);
- line-height: var(--leading-normal);
- }
- .docs-main h1 {
- font-family: var(--font-display);
- font-weight: 300;
- font-size: var(--text-2xl);
- letter-spacing: -1px;
- margin: 0 0 var(--space-md);
- }
- .docs-main h2 {
- font-family: var(--font-display);
- font-weight: 400;
- font-size: var(--text-xl);
- margin: var(--space-2xl) 0 var(--space-sm);
- padding-bottom: var(--space-xs);
- border-bottom: 1px solid rgba(255,255,255,0.08);
- }
- .docs-main h3 {
- font-weight: 500;
- font-size: var(--text-lg);
- margin: var(--space-xl) 0 var(--space-sm);
- }
- .docs-main p, .docs-main li { color: rgba(229,229,229,0.85); }
- .docs-main ul, .docs-main ol { padding-left: var(--space-lg); }
- .docs-main code {
- font-family: var(--font-mono);
- font-size: 0.92em;
- background: rgba(255,255,255,0.06);
- padding: 1px 5px;
- border-radius: 3px;
- color: #e5e5e5;
- }
- .docs-main pre {
- background: #0a0a0a;
- border: 1px solid rgba(255,255,255,0.08);
- border-radius: var(--radius-md);
- padding: var(--space-md);
- overflow-x: auto;
- line-height: 1.5;
- font-family: var(--font-mono);
- font-size: var(--text-sm);
- }
- .docs-main pre code {
- background: transparent;
- padding: 0;
- }
- .docs-main table {
- width: 100%;
- border-collapse: collapse;
- margin: var(--space-md) 0;
- font-size: var(--text-sm);
- }
- .docs-main th, .docs-main td {
- text-align: left;
- padding: var(--space-xs) var(--space-sm);
- border-bottom: 1px solid rgba(255,255,255,0.06);
- }
- .docs-main th { color: rgba(229,229,229,0.6); font-weight: 500; }
- .docs-main a { color: var(--accent); }
- .docs-main hr { border: 0; border-top: 1px solid rgba(255,255,255,0.08); margin: var(--space-xl) 0; }
- .docs-toc {
- padding: var(--space-md);
- background: rgba(255,255,255,0.025);
- border: 1px solid rgba(255,255,255,0.06);
- border-radius: var(--radius-md);
- margin-bottom: var(--space-xl);
- }
- .docs-toc ul { margin: var(--space-xs) 0; padding-left: var(--space-md); }
- </style>
-</head>
-<body class="gallery-body">
- <header class="gallery-header">
- <h1><a href="/"><span class="wordmark-dot" aria-hidden="true"></span>3D Agent</a></h1>
- <nav class="features-nav">
- <a href="/">Viewer</a>
- <a href="/features">Features</a>
- <a href="/widgets">Widgets</a>
- <a href="/docs/widgets" class="active" aria-current="page">Docs</a>
- <a href="/dashboard" class="nav-dashboard">Dashboard</a>
- </nav>
- </header>
-
- <main class="docs-main">
- <h1>Widgets</h1>
- <p>Embeddable 3D — a configured, shareable view of an avatar that any site can drop in with one line of HTML.</p>
- <p>A widget is a saved bundle of: an avatar (GLB stored in R2), a widget type (turntable, animation gallery, talking agent, ERC-8004 passport, hotspot tour), and brand config (background, accent, caption, controls, camera). Widgets are created in the <a href="/studio">Widget Studio</a> and shared via short URLs.</p>
-
- <div class="docs-toc">
- <strong>On this page:</strong>
- <ul>
- <li><a href="#quick-start">Quick start</a></li>
- <li><a href="#widget-types">Widget types</a></li>
- <li><a href="#urls">URLs</a></li>
- <li><a href="#embedding">Embedding</a></li>
- <li><a href="#postmessage-api">postMessage API</a></li>
- <li><a href="#og-oembed">OG / oEmbed</a></li>
- <li><a href="#csp-cors">CSP / CORS</a></li>
- <li><a href="#privacy">Privacy &amp; analytics</a></li>
- <li><a href="#faq">FAQ</a></li>
- </ul>
- </div>
-
- <h2 id="quick-start">Quick start</h2>
- <ol>
- <li>Sign in at <a href="/">3dagent.vercel.app</a>.</li>
- <li>Open the <a href="/studio">Studio</a>.</li>
- <li>Pick an avatar, pick a widget type, tweak brand colors and controls, click <strong>Generate Embed</strong>.</li>
- <li>Copy the iframe snippet into any HTML page, blog post, Notion doc, or CMS.</li>
- </ol>
-
- <h2 id="widget-types">Widget types</h2>
- <table>
- <thead><tr><th>Type</th><th>Best for</th><th>Default size</th></tr></thead>
- <tbody>
- <tr><td><code>turntable</code></td><td>Hero banners, product showcases. Auto-rotate, no UI.</td><td>600 × 600</td></tr>
- <tr><td><code>animation-gallery</code></td><td>Showcasing a rigged avatar's animation library.</td><td>720 × 720</td></tr>
- <tr><td><code>talking-agent</code></td><td>Embodied chat — your agent on your site.</td><td>420 × 600</td></tr>
- <tr><td><code>passport</code></td><td>On-chain identity card backed by ERC-8004.</td><td>480 × 560</td></tr>
- <tr><td><code>hotspot-tour</code></td><td>Annotated 3D scenes with clickable POIs.</td><td>800 × 600</td></tr>
- </tbody>
- </table>
-
- <h2 id="urls">URLs</h2>
- <p>Every widget has three canonical URLs.</p>
- <table>
- <thead><tr><th>URL</th><th>Use it for</th></tr></thead>
- <tbody>
- <tr><td><code>/w/&lt;id&gt;</code></td><td>Sharing in Slack/Discord/X — server-rendered with rich OG card.</td></tr>
- <tr><td><code>/#widget=&lt;id&gt;</code></td><td>The SPA viewer with the widget config applied.</td></tr>
- <tr><td><code>/api/widgets/&lt;id&gt;/og</code></td><td>The 1200×630 preview image.</td></tr>
- </tbody>
- </table>
-
- <h3>Hash parameters</h3>
- <table>
- <thead><tr><th>Param</th><th>Type</th><th>Description</th></tr></thead>
- <tbody>
- <tr><td><code>widget</code></td><td>string</td><td>Loads a saved widget by id.</td></tr>
- <tr><td><code>model</code></td><td>string</td><td>Loads a raw GLB by URL (mutually exclusive with <code>widget</code>).</td></tr>
- <tr><td><code>kiosk</code></td><td>boolean</td><td>Hides the header chrome for clean iframe embeds.</td></tr>
- <tr><td><code>cameraPosition</code></td><td>x,y,z</td><td>Comma-separated camera position override.</td></tr>
- <tr><td><code>preset</code></td><td>string</td><td>HDR environment preset name.</td></tr>
- </tbody>
- </table>
-
- <h2 id="embedding">Embedding</h2>
- <h3>iframe (recommended)</h3>
-<pre><code>&lt;iframe
+ <head>
+ <meta charset="utf-8" />
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+ <title>Widget Docs — 3D Agent</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
+ <meta
+ name="description"
+ content="Embed 3D widgets on any site. URL params, iframe + script embeds, postMessage API, oEmbed, privacy."
+ />
+ <meta name="theme-color" content="#0a0a0a" />
+
+ <meta property="og:type" content="article" />
+ <meta property="og:title" content="3D Agent — Widget Docs" />
+ <meta
+ property="og:description"
+ content="Embed 3D widgets on any site. URL params, postMessage API, oEmbed, privacy."
+ />
+ <meta property="og:url" content="https://3dagent.vercel.app/docs/widgets" />
+
+ <link rel="canonical" href="https://3dagent.vercel.app/docs/widgets" />
+ <link rel="shortcut icon" href="/favicon.ico" />
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
+ <link
+ href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap"
+ rel="stylesheet"
+ />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/widgets-gallery/gallery.css" />
+ <style>
+ .docs-main {
+ max-width: 760px;
+ margin: 0 auto;
+ padding: var(--space-2xl) var(--space-lg);
+ line-height: var(--leading-normal);
+ }
+ .docs-main h1 {
+ font-family: var(--font-display);
+ font-weight: 300;
+ font-size: var(--text-2xl);
+ letter-spacing: -1px;
+ margin: 0 0 var(--space-md);
+ }
+ .docs-main h2 {
+ font-family: var(--font-display);
+ font-weight: 400;
+ font-size: var(--text-xl);
+ margin: var(--space-2xl) 0 var(--space-sm);
+ padding-bottom: var(--space-xs);
+ border-bottom: 1px solid rgba(255, 255, 255, 0.08);
+ }
+ .docs-main h3 {
+ font-weight: 500;
+ font-size: var(--text-lg);
+ margin: var(--space-xl) 0 var(--space-sm);
+ }
+ .docs-main p,
+ .docs-main li {
+ color: rgba(229, 229, 229, 0.85);
+ }
+ .docs-main ul,
+ .docs-main ol {
+ padding-left: var(--space-lg);
+ }
+ .docs-main code {
+ font-family: var(--font-mono);
+ font-size: 0.92em;
+ background: rgba(255, 255, 255, 0.06);
+ padding: 1px 5px;
+ border-radius: 3px;
+ color: #e5e5e5;
+ }
+ .docs-main pre {
+ background: #0a0a0a;
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: var(--radius-md);
+ padding: var(--space-md);
+ overflow-x: auto;
+ line-height: 1.5;
+ font-family: var(--font-mono);
+ font-size: var(--text-sm);
+ }
+ .docs-main pre code {
+ background: transparent;
+ padding: 0;
+ }
+ .docs-main table {
+ width: 100%;
+ border-collapse: collapse;
+ margin: var(--space-md) 0;
+ font-size: var(--text-sm);
+ }
+ .docs-main th,
+ .docs-main td {
+ text-align: left;
+ padding: var(--space-xs) var(--space-sm);
+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);
+ }
+ .docs-main th {
+ color: rgba(229, 229, 229, 0.6);
+ font-weight: 500;
+ }
+ .docs-main a {
+ color: var(--accent);
+ }
+ .docs-main hr {
+ border: 0;
+ border-top: 1px solid rgba(255, 255, 255, 0.08);
+ margin: var(--space-xl) 0;
+ }
+ .docs-toc {
+ padding: var(--space-md);
+ background: rgba(255, 255, 255, 0.025);
+ border: 1px solid rgba(255, 255, 255, 0.06);
+ border-radius: var(--radius-md);
+ margin-bottom: var(--space-xl);
+ }
+ .docs-toc ul {
+ margin: var(--space-xs) 0;
+ padding-left: var(--space-md);
+ }
+ </style>
+ </head>
+ <body class="gallery-body">
+ <header class="gallery-header">
+ <h1>
+ <a href="/"><span class="wordmark-dot" aria-hidden="true"></span>3D Agent</a>
+ </h1>
+ <nav class="features-nav">
+ <a href="/">Viewer</a>
+ <a href="/features">Features</a>
+ <a href="/widgets">Widgets</a>
+ <a href="/docs/widgets" class="active" aria-current="page">Docs</a>
+ <a href="/dashboard" class="nav-dashboard">Dashboard</a>
+ </nav>
+ </header>
+
+ <main class="docs-main">
+ <h1>Widgets</h1>
+ <p>
+ Embeddable 3D — a configured, shareable view of an avatar that any site can drop in
+ with one line of HTML.
+ </p>
+ <p>
+ A widget is a saved bundle of: an avatar (GLB stored in R2), a widget type
+ (turntable, animation gallery, talking agent, ERC-8004 passport, hotspot tour), and
+ brand config (background, accent, caption, controls, camera). Widgets are created in
+ the <a href="/studio">Widget Studio</a> and shared via short URLs.
+ </p>
+
+ <div class="docs-toc">
+ <strong>On this page:</strong>
+ <ul>
+ <li><a href="#quick-start">Quick start</a></li>
+ <li><a href="#widget-types">Widget types</a></li>
+ <li><a href="#urls">URLs</a></li>
+ <li><a href="#embedding">Embedding</a></li>
+ <li><a href="#postmessage-api">postMessage API</a></li>
+ <li><a href="#og-oembed">OG / oEmbed</a></li>
+ <li><a href="#csp-cors">CSP / CORS</a></li>
+ <li><a href="#privacy">Privacy &amp; analytics</a></li>
+ <li><a href="#faq">FAQ</a></li>
+ </ul>
+ </div>
+
+ <h2 id="quick-start">Quick start</h2>
+ <ol>
+ <li>Sign in at <a href="/">3dagent.vercel.app</a>.</li>
+ <li>Open the <a href="/studio">Studio</a>.</li>
+ <li>
+ Pick an avatar, pick a widget type, tweak brand colors and controls, click
+ <strong>Generate Embed</strong>.
+ </li>
+ <li>Copy the iframe snippet into any HTML page, blog post, Notion doc, or CMS.</li>
+ </ol>
+
+ <h2 id="widget-types">Widget types</h2>
+ <table>
+ <thead>
+ <tr>
+ <th>Type</th>
+ <th>Best for</th>
+ <th>Default size</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td><code>turntable</code></td>
+ <td>Hero banners, product showcases. Auto-rotate, no UI.</td>
+ <td>600 × 600</td>
+ </tr>
+ <tr>
+ <td><code>animation-gallery</code></td>
+ <td>Showcasing a rigged avatar's animation library.</td>
+ <td>720 × 720</td>
+ </tr>
+ <tr>
+ <td><code>talking-agent</code></td>
+ <td>Embodied chat — your agent on your site.</td>
+ <td>420 × 600</td>
+ </tr>
+ <tr>
+ <td><code>passport</code></td>
+ <td>On-chain identity card backed by ERC-8004.</td>
+ <td>480 × 560</td>
+ </tr>
+ <tr>
+ <td><code>hotspot-tour</code></td>
+ <td>Annotated 3D scenes with clickable POIs.</td>
+ <td>800 × 600</td>
+ </tr>
+ </tbody>
+ </table>
+
+ <h2 id="urls">URLs</h2>
+ <p>Every widget has three canonical URLs.</p>
+ <table>
+ <thead>
+ <tr>
+ <th>URL</th>
+ <th>Use it for</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td><code>/w/&lt;id&gt;</code></td>
+ <td>Sharing in Slack/Discord/X — server-rendered with rich OG card.</td>
+ </tr>
+ <tr>
+ <td><code>/#widget=&lt;id&gt;</code></td>
+ <td>The SPA viewer with the widget config applied.</td>
+ </tr>
+ <tr>
+ <td><code>/api/widgets/&lt;id&gt;/og</code></td>
+ <td>The 1200×630 preview image.</td>
+ </tr>
+ </tbody>
+ </table>
+
+ <h3>Hash parameters</h3>
+ <table>
+ <thead>
+ <tr>
+ <th>Param</th>
+ <th>Type</th>
+ <th>Description</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td><code>widget</code></td>
+ <td>string</td>
+ <td>Loads a saved widget by id.</td>
+ </tr>
+ <tr>
+ <td><code>model</code></td>
+ <td>string</td>
+ <td>
+ Loads a raw GLB by URL (mutually exclusive with <code>widget</code>).
+ </td>
+ </tr>
+ <tr>
+ <td><code>kiosk</code></td>
+ <td>boolean</td>
+ <td>Hides the header chrome for clean iframe embeds.</td>
+ </tr>
+ <tr>
+ <td><code>cameraPosition</code></td>
+ <td>x,y,z</td>
+ <td>Comma-separated camera position override.</td>
+ </tr>
+ <tr>
+ <td><code>preset</code></td>
+ <td>string</td>
+ <td>HDR environment preset name.</td>
+ </tr>
+ </tbody>
+ </table>
+
+ <h2 id="embedding">Embedding</h2>
+ <h3>iframe (recommended)</h3>
+ <pre><code>&lt;iframe
src="https://3dagent.vercel.app/#widget=wdgt_abc123def456&amp;kiosk=true"
width="600"
height="600"
@@ -180,69 +289,152 @@
allow="autoplay; xr-spatial-tracking; clipboard-write"
loading="lazy"&gt;&lt;/iframe&gt;</code></pre>
- <h3>Script embed</h3>
-<pre><code>&lt;script async src="https://3dagent.vercel.app/embed.js" data-widget="wdgt_abc123def456"&gt;&lt;/script&gt;</code></pre>
-
- <h3>oEmbed (WordPress, Ghost, Notion)</h3>
- <p>Most CMSes auto-detect oEmbed. Paste a <code>/w/&lt;id&gt;</code> URL on its own line and the editor should turn it into a live embed automatically.</p>
-
- <h2 id="postmessage-api">postMessage API</h2>
- <p>Widgets communicate with the parent page via <code>window.postMessage</code>. <strong>Always check <code>event.origin</code> before trusting any message.</strong></p>
-
- <h3>iframe → parent</h3>
- <table>
- <thead><tr><th>Event</th><th>Payload</th><th>When</th></tr></thead>
- <tbody>
- <tr><td><code>widget:ready</code></td><td><code>{ id, type }</code></td><td>Widget runtime has booted.</td></tr>
- <tr><td><code>widget:load</code></td><td><code>{ id, model_url }</code></td><td>Underlying GLB loaded successfully.</td></tr>
- <tr><td><code>widget:load:error</code></td><td><code>{ id, error }</code></td><td>GLB or config failed to load.</td></tr>
- <tr><td><code>widget:chat:message</code></td><td><code>{ role, content }</code></td><td>Talking-agent only.</td></tr>
- <tr><td><code>widget:hotspot:open</code></td><td><code>{ id, label }</code></td><td>Hotspot-tour only.</td></tr>
- <tr><td><code>widget:resize</code></td><td><code>{ width, height }</code></td><td>Widget reports preferred size.</td></tr>
- </tbody>
- </table>
-
-<pre><code>window.addEventListener('message', (e) =&gt; {
+ <h3>Script embed</h3>
+ <pre><code>&lt;script async src="https://3dagent.vercel.app/embed.js" data-widget="wdgt_abc123def456"&gt;&lt;/script&gt;</code></pre>
+
+ <h3>oEmbed (WordPress, Ghost, Notion)</h3>
+ <p>
+ Most CMSes auto-detect oEmbed. Paste a <code>/w/&lt;id&gt;</code> URL on its own
+ line and the editor should turn it into a live embed automatically.
+ </p>
+
+ <h2 id="postmessage-api">postMessage API</h2>
+ <p>
+ Widgets communicate with the parent page via <code>window.postMessage</code>.
+ <strong>Always check <code>event.origin</code> before trusting any message.</strong>
+ </p>
+
+ <h3>iframe → parent</h3>
+ <table>
+ <thead>
+ <tr>
+ <th>Event</th>
+ <th>Payload</th>
+ <th>When</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td><code>widget:ready</code></td>
+ <td><code>{ id, type }</code></td>
+ <td>Widget runtime has booted.</td>
+ </tr>
+ <tr>
+ <td><code>widget:load</code></td>
+ <td><code>{ id, model_url }</code></td>
+ <td>Underlying GLB loaded successfully.</td>
+ </tr>
+ <tr>
+ <td><code>widget:load:error</code></td>
+ <td><code>{ id, error }</code></td>
+ <td>GLB or config failed to load.</td>
+ </tr>
+ <tr>
+ <td><code>widget:chat:message</code></td>
+ <td><code>{ role, content }</code></td>
+ <td>Talking-agent only.</td>
+ </tr>
+ <tr>
+ <td><code>widget:hotspot:open</code></td>
+ <td><code>{ id, label }</code></td>
+ <td>Hotspot-tour only.</td>
+ </tr>
+ <tr>
+ <td><code>widget:resize</code></td>
+ <td><code>{ width, height }</code></td>
+ <td>Widget reports preferred size.</td>
+ </tr>
+ </tbody>
+ </table>
+
+ <pre><code>window.addEventListener('message', (e) =&gt; {
if (e.origin !== 'https://3dagent.vercel.app') return;
if (e.data?.type === 'widget:ready') {
console.log('Widget mounted:', e.data.id);
}
});</code></pre>
- <h3>parent → iframe</h3>
- <table>
- <thead><tr><th>Event</th><th>Payload</th><th>Effect</th></tr></thead>
- <tbody>
- <tr><td><code>widget:config</code></td><td><code>{ background, accent, autoRotate, … }</code></td><td>Live-update brand config.</td></tr>
- <tr><td><code>widget:command</code></td><td><code>{ command, args }</code></td><td>Trigger a runtime action.</td></tr>
- </tbody>
- </table>
-
- <h2 id="og-oembed">OG / oEmbed</h2>
- <p>Every widget URL serves rich-preview metadata. <code>/w/&lt;id&gt;</code> is server-rendered with Open Graph + Twitter card tags and a <code>&lt;link rel="alternate" type="application/json+oembed"&gt;</code> pointer.</p>
-<pre><code>GET /api/widgets/oembed?url=&lt;widget-url&gt;&amp;format=json</code></pre>
- <p>Returns standard <a href="https://oembed.com">oEmbed v1.0</a> JSON, type <code>rich</code>. Accepts both <code>/w/&lt;id&gt;</code> and <code>/#widget=&lt;id&gt;</code> forms.</p>
-
- <h2 id="csp-cors">CSP / CORS</h2>
- <p>Widgets run in a sandboxed iframe with these <code>allow</code> flags: <code>autoplay</code>, <code>xr-spatial-tracking</code>, <code>clipboard-write</code>. If your site uses strict CSP, allow:</p>
-<pre><code>frame-src https://3dagent.vercel.app;
+ <h3>parent → iframe</h3>
+ <table>
+ <thead>
+ <tr>
+ <th>Event</th>
+ <th>Payload</th>
+ <th>Effect</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td><code>widget:config</code></td>
+ <td><code>{ background, accent, autoRotate, … }</code></td>
+ <td>Live-update brand config.</td>
+ </tr>
+ <tr>
+ <td><code>widget:command</code></td>
+ <td><code>{ command, args }</code></td>
+ <td>Trigger a runtime action.</td>
+ </tr>
+ </tbody>
+ </table>
+
+ <h2 id="og-oembed">OG / oEmbed</h2>
+ <p>
+ Every widget URL serves rich-preview metadata. <code>/w/&lt;id&gt;</code> is
+ server-rendered with Open Graph + Twitter card tags and a
+ <code>&lt;link rel="alternate" type="application/json+oembed"&gt;</code> pointer.
+ </p>
+ <pre><code>GET /api/widgets/oembed?url=&lt;widget-url&gt;&amp;format=json</code></pre>
+ <p>
+ Returns standard <a href="https://oembed.com">oEmbed v1.0</a> JSON, type
+ <code>rich</code>. Accepts both <code>/w/&lt;id&gt;</code> and
+ <code>/#widget=&lt;id&gt;</code> forms.
+ </p>
+
+ <h2 id="csp-cors">CSP / CORS</h2>
+ <p>
+ Widgets run in a sandboxed iframe with these <code>allow</code> flags:
+ <code>autoplay</code>, <code>xr-spatial-tracking</code>,
+ <code>clipboard-write</code>. If your site uses strict CSP, allow:
+ </p>
+ <pre><code>frame-src https://3dagent.vercel.app;
img-src https://3dagent.vercel.app data:;</code></pre>
- <h2 id="privacy">Privacy &amp; analytics</h2>
- <p>We log a minimal first-party event per widget load: <code>widget_id</code>, <code>type</code>, <code>country</code> (Vercel edge header), <code>referer_host</code> (hostname only), <code>created_at</code>. No IPs. No cookies. No user agents. No chat content. No cross-widget tracking.</p>
+ <h2 id="privacy">Privacy &amp; analytics</h2>
+ <p>
+ We log a minimal first-party event per widget load: <code>widget_id</code>,
+ <code>type</code>, <code>country</code> (Vercel edge header),
+ <code>referer_host</code> (hostname only), <code>created_at</code>. No IPs. No
+ cookies. No user agents. No chat content. No cross-widget tracking.
+ </p>
- <h2 id="faq">FAQ</h2>
- <p><strong>Can I self-host?</strong> The runtime is open source. The Studio + saved-widgets API depends on Neon + R2; you'd need to wire those yourself. See <a href="/docs/deployment">deployment guide</a>.</p>
- <p><strong>Why no WordPress plugin?</strong> The oEmbed endpoint already does what a plugin would.</p>
- <p><strong>How big is the bundle?</strong> Cold load ~400KB JS + the GLB itself.</p>
- <p><strong>Mobile?</strong> Yes — every widget type works on iOS Safari and Android Chrome.</p>
+ <h2 id="faq">FAQ</h2>
+ <p>
+ <strong>Can I self-host?</strong> The runtime is open source. The Studio +
+ saved-widgets API depends on Neon + R2; you'd need to wire those yourself. See
+ <a href="/docs/deployment">deployment guide</a>.
+ </p>
+ <p>
+ <strong>Why no WordPress plugin?</strong> The oEmbed endpoint already does what a
+ plugin would.
+ </p>
+ <p><strong>How big is the bundle?</strong> Cold load ~400KB JS + the GLB itself.</p>
+ <p>
+ <strong>Mobile?</strong> Yes — every widget type works on iOS Safari and Android
+ Chrome.
+ </p>
- <hr>
- <p><a href="/widgets">← Back to gallery</a> · <a href="/studio">Open the Studio →</a></p>
- </main>
+ <hr />
+ <p>
+ <a href="/widgets">← Back to gallery</a> · <a href="/studio">Open the Studio →</a>
+ </p>
+ </main>
- <footer class="gallery-footer">
- <p>3D Agent · <a href="/">Viewer</a> · <a href="/widgets">Widgets</a> · <a href="/docs/widgets">Docs</a> · <a href="https://github.com/nirholas/3D">GitHub</a></p>
- </footer>
-</body>
+ <footer class="gallery-footer">
+ <p>
+ 3D Agent · <a href="/">Viewer</a> · <a href="/widgets">Widgets</a> ·
+ <a href="/docs/widgets">Docs</a> ·
+ <a href="https://github.com/nirholas/3D">GitHub</a>
+ </p>
+ </footer>
+ </body>
</html>
diff --git a/public/explore/explore.js b/public/explore/explore.js
index 0b8556578..5f522311f 100644
--- a/public/explore/explore.js
+++ b/public/explore/explore.js
@@ -159,8 +159,7 @@ function renderCard(item) {
badges.push(
`<span class="explore-badge explore-badge--chain">${escapeHtml(item.chainName)}</span>`,
);
- if (item.has3d)
- badges.push(`<span class="explore-badge explore-badge--3d">3D</span>`);
+ if (item.has3d) badges.push(`<span class="explore-badge explore-badge--3d">3D</span>`);
if (item.x402Support)
badges.push(`<span class="explore-badge explore-badge--x402">x402</span>`);
@@ -300,7 +299,9 @@ function openEmbedModal({ chainId, agentId, name }) {
if (e.key === 'Escape') close();
};
document.addEventListener('keydown', onEsc);
- modal.querySelectorAll('[data-role="close"]').forEach((el) => el.addEventListener('click', close));
+ modal
+ .querySelectorAll('[data-role="close"]')
+ .forEach((el) => el.addEventListener('click', close));
modal.querySelectorAll('.embed-tab').forEach((tab) => {
tab.addEventListener('click', () => {
@@ -324,7 +325,10 @@ function openEmbedModal({ chainId, agentId, name }) {
setTimeout(() => (btn.textContent = 'Copy'), 1400);
};
if (navigator.clipboard?.writeText) {
- navigator.clipboard.writeText(text).then(() => done(true), () => done(false));
+ navigator.clipboard.writeText(text).then(
+ () => done(true),
+ () => done(false),
+ );
} else {
const ta = modal.querySelector(`[data-pane="${key}"] .embed-snippet`);
ta?.select();
diff --git a/public/explore/index.html b/public/explore/index.html
index 5d38da558..a1907ff4b 100644
--- a/public/explore/index.html
+++ b/public/explore/index.html
@@ -4,10 +4,7 @@
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Explore · 3D Agent</title>
- <meta
- name="viewport"
- content="width=device-width, initial-scale=1.0, viewport-fit=cover"
- />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta
name="description"
content="Browse every ERC-8004 agent registered on-chain across 20+ EVM networks. Filter by 3D avatar, chain, and keywords."
@@ -46,8 +43,8 @@
</div>
<h2>Every agent, every chain.</h2>
<p class="explore-sub">
- The complete on-chain index of ERC-8004 agents. Click a 3D avatar to load
- it in the viewer. Click any card for its on-chain passport.
+ The complete on-chain index of ERC-8004 agents. Click a 3D avatar to load it in
+ the viewer. Click any card for its on-chain passport.
</p>
<div class="explore-stats" data-role="stats">
diff --git a/public/hydrate/index.html b/public/hydrate/index.html
index 93e9d4ac8..76e5fb1aa 100644
--- a/public/hydrate/index.html
+++ b/public/hydrate/index.html
@@ -1,4 +1,4 @@
-<!DOCTYPE html>
+<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
@@ -278,9 +278,7 @@
</div>
<h1>Import My Agents</h1>
- <p class="subtitle">
- Discover and import agents you've already registered on-chain
- </p>
+ <p class="subtitle">Discover and import agents you've already registered on-chain</p>
<div id="alert" class="alert"></div>
@@ -301,7 +299,8 @@
<div id="emptyState" class="empty-state" style="display: none">
<p>No on-chain agents found for your wallets.</p>
<p style="font-size: 12px; color: #999">
- Register a new agent at <a href="/deploy" style="color: var(--primary)">Deploy</a>
+ Register a new agent at
+ <a href="/deploy" style="color: var(--primary)">Deploy</a>
</p>
</div>
</div>
@@ -387,22 +386,14 @@
(agent) => `
<div class="agent-card">
<div class="agent-image">
- ${
- agent.image
- ? `<img src="${escapeHtml(agent.image)}" alt="${escapeHtml(agent.name)}" />`
- : '📦'
- }
+ ${agent.image ? `<img src="${escapeHtml(agent.image)}" alt="${escapeHtml(agent.name)}" />` : '📦'}
</div>
<div class="agent-info">
<div class="agent-header">
<div class="agent-name">${escapeHtml(agent.name)}</div>
<span class="chain-badge">Chain ${agent.chainId}</span>
</div>
- ${
- agent.description
- ? `<p class="agent-description">${escapeHtml(agent.description)}</p>`
- : ''
- }
+ ${agent.description ? `<p class="agent-description">${escapeHtml(agent.description)}</p>` : ''}
<div class="agent-id">Agent ID: ${escapeHtml(agent.agentId)}</div>
</div>
<div class="agent-actions">
diff --git a/public/lobehub/iframe/boot.js b/public/lobehub/iframe/boot.js
index 54e0011bf..d8bda8edb 100644
--- a/public/lobehub/iframe/boot.js
+++ b/public/lobehub/iframe/boot.js
@@ -1,12 +1,16 @@
-// LobeHub iframe postMessage bridge for 3D Agent.
-// Envelope: { v: 1, ns: '3d-agent', type, id?, payload }
-// See public/lobehub/README.md for full contract.
-
-const NS = '3d-agent';
-const V = 1;
-const EMBED_VERSION = '0.1.0';
-
-// Origins trusted unconditionally (no ?host= needed).
+// LobeHub iframe bridge for 3D Agent.
+//
+// Primary protocol: v1 spec envelope
+// { v: 1, source: 'agent-host'|'agent-3d', id, inReplyTo?, kind, op, payload }
+// See prompts/final-integration/01-embed-bridges.md for the canonical contract.
+//
+// Backward-compat layer also accepts the legacy format:
+// { v: 1, ns: '3d-agent', type: 'host:xxx', id?, payload }
+
+const EMBED_VERSION = '1.0.0';
+const CAPABILITIES = ['speak', 'gesture', 'emote', 'look', 'setAgent', 'subscribe', 'ping'];
+
+// Origins unconditionally trusted.
const KNOWN_ORIGINS = new Set(['https://chat.lobehub.com', 'https://lobechat.ai']);
function isDev(origin) {
@@ -21,14 +25,14 @@ function isDev(origin) {
const params = new URL(location.href).searchParams;
const agentId = params.get('agent') || '';
-// ?host=<encoded-origin> narrows the allowed parent to a single origin.
+// ?host=<encoded-origin> restricts accepted parent to one origin.
let allowedOrigin = null;
const hostParam = params.get('host');
if (hostParam) {
try {
allowedOrigin = new URL(decodeURIComponent(hostParam)).origin;
} catch {
- console.warn('[3d-agent:bridge] invalid ?host param');
+ console.warn('[3d-agent] invalid ?host param');
}
}
@@ -37,18 +41,34 @@ function isAllowedOrigin(origin) {
if (allowedOrigin) return origin === allowedOrigin;
if (KNOWN_ORIGINS.has(origin)) return true;
if (isDev(origin)) return true;
- // Permit unlisted origins but log — public agents may embed anywhere.
- console.warn('[3d-agent:bridge] message from unlisted origin', origin);
+ // Permit unknown origins with a warning — public agents may embed anywhere.
+ console.warn('[3d-agent] message from unlisted origin', origin);
return true;
}
-function postToHost(type, payload, replyId) {
- const msg = { v: V, ns: NS, type, payload: payload ?? {} };
- if (replyId !== undefined) msg.id = replyId;
- const target = allowedOrigin || '*';
+function newId() {
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
+ return crypto.randomUUID();
+ }
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
+}
+
+// ── Outgoing ─────────────────────────────────────────────────────────────────
+
+function post(op, payload, inReplyTo) {
+ const msg = {
+ v: 1,
+ source: 'agent-3d',
+ id: newId(),
+ kind: inReplyTo ? 'response' : 'event',
+ op,
+ payload: payload ?? {},
+ };
+ if (inReplyTo) msg.inReplyTo = inReplyTo;
+ const target = allowedOrigin ?? '*';
try {
window.parent.postMessage(msg, target);
- } catch {}
+ } catch (_) {}
}
// ── Element wiring ────────────────────────────────────────────────────────────
@@ -69,31 +89,32 @@ if (agentId) {
el.addEventListener('agent:ready', (ev) => {
const { manifest } = ev.detail || {};
if (statusEl) statusEl.style.display = 'none';
- postToHost('embed:ready', {
+ post('ready', {
agentId,
+ embedVersion: EMBED_VERSION,
+ capabilities: CAPABILITIES,
name: manifest?.meta?.name || manifest?.name || '',
- avatarUrl: manifest?.body?.url || '',
});
});
el.addEventListener('agent:error', (ev) => {
const { phase, error: err } = ev.detail || {};
setStatus(err?.message || 'Error loading agent');
- postToHost('embed:error', {
+ post('error', {
code: err?.code || 'load_error',
message: err?.message || 'Agent failed to load',
phase: phase || 'boot',
});
});
-// ── ResizeObserver → embed:resize (debounced 100ms) ──────────────────────────
+// ── ResizeObserver → resize event (debounced 100 ms) ─────────────────────────
if (typeof ResizeObserver !== 'undefined') {
let resizeTimer;
const ro = new ResizeObserver(() => {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => {
- postToHost('embed:resize', {
+ post('resize', {
width: el.offsetWidth,
height: el.offsetHeight,
contentHeight: el.scrollHeight,
@@ -105,136 +126,144 @@ if (typeof ResizeObserver !== 'undefined') {
// ── Action dispatch ───────────────────────────────────────────────────────────
-async function dispatchAction(action) {
- if (!action || !action.type) return;
+let subscribed = false;
+
+async function dispatchAction(op, payload, replyId) {
try {
- switch (action.type) {
+ switch (op) {
case 'speak':
- await el.say?.(action.payload?.text || '', {
- sentiment: action.payload?.sentiment,
- });
+ await el.say?.(payload.text || '', { sentiment: payload.sentiment });
break;
case 'gesture':
- if (action.payload?.name === 'wave') {
+ if (payload.name === 'wave') {
await el.wave?.();
} else {
- await el.play?.(action.payload?.name, { duration: action.payload?.duration });
+ await el.play?.(payload.name, { duration: payload.duration });
}
break;
case 'emote':
- // TODO(lobehub-spec): <agent-3d> has no direct emote() public method.
- // Dispatching as a CustomEvent; element.js may not consume it without
- // a corresponding listener. Confirm with src/element.js maintainer.
- el.dispatchEvent(new CustomEvent('agent:action', { detail: action }));
+ // <agent-3d> has no public emote() method; dispatch as a CustomEvent
+ // for the runtime's empathy-layer listener (src/agent-avatar.js).
+ el.dispatchEvent(
+ new CustomEvent('agent:action', { detail: { type: 'emote', payload } }),
+ );
+ break;
+ case 'look':
+ el.dispatchEvent(
+ new CustomEvent('agent:action', { detail: { type: 'look', payload } }),
+ );
+ break;
+ case 'setAgent':
+ if (payload.agentId && payload.agentId !== agentId) {
+ const url = new URL(location.href);
+ url.searchParams.set('agent', payload.agentId);
+ location.replace(url.toString());
+ }
break;
- default:
- el.dispatchEvent(new CustomEvent('agent:action', { detail: action }));
}
- // Mirror action up to host so it can log what the avatar did.
- postToHost('embed:action', {
- action: { ...action, timestamp: Date.now(), agentId },
- });
+ if (replyId) post('pong', { ok: true }, replyId);
+ if (subscribed) {
+ post('action', { op, payload, timestamp: Date.now(), agentId });
+ }
} catch (err) {
- console.warn('[3d-agent:bridge] action dispatch failed', err);
+ console.warn('[3d-agent] action dispatch failed', err);
+ if (replyId) post('error', { code: 'dispatch_error', message: String(err) }, replyId);
}
}
-// ── Theme ─────────────────────────────────────────────────────────────────────
-
-function applyTheme({ mode, accent } = {}) {
- if (mode === 'dark') document.body.style.background = '#0b0d10';
- else if (mode === 'light') document.body.style.background = '#f5f5f5';
- else if (mode === 'transparent') document.body.style.background = 'transparent';
- if (accent) document.documentElement.style.setProperty('--agent-accent', accent);
-}
-
// ── postMessage handler ───────────────────────────────────────────────────────
function onMessage(ev) {
const { origin, data } = ev;
if (!data || typeof data !== 'object') return;
- // Acceptance-test handshake: { type: 'handshake' } → { type: 'ready' }
+ // Dev-harness handshake shortcut.
if (data.type === 'handshake') {
try {
window.parent.postMessage({ type: 'ready', agentId }, ev.origin || '*');
- } catch {}
+ } catch (_) {}
return;
}
- // Legacy compat: { __agent, type: 'action', action } — deprecated, one version support.
- if (data.__agent !== undefined) {
- if (data.__agent === agentId && data.type === 'action' && data.action) {
- console.warn('[3d-agent:bridge] legacy message format — migrate to v1 envelope');
- dispatchAction(data.action);
+ if (!isAllowedOrigin(origin)) return;
+
+ // ── v1 spec envelope ──────────────────────────────────────────────────────
+ if (data.v === 1 && data.source === 'agent-host' && data.kind && data.op) {
+ const { id, kind, op, payload = {} } = data;
+ if (kind !== 'request') return;
+
+ switch (op) {
+ case 'ping':
+ post('pong', { agentId }, id);
+ break;
+ case 'subscribe':
+ subscribed = true;
+ post('pong', { ok: true }, id);
+ break;
+ case 'speak':
+ case 'gesture':
+ case 'emote':
+ case 'look':
+ case 'setAgent':
+ dispatchAction(op, payload, id);
+ break;
+ default:
+ post('error', { code: 'unknown_op', op }, id);
}
return;
}
- if (!isAllowedOrigin(origin)) return;
-
- // v1 envelope validation
- if (data.v !== V || data.ns !== NS || !data.type) return;
- const { type, id, payload = {} } = data;
- console.log('[3d-agent:bridge] recv', type, payload);
-
- switch (type) {
- case 'host:hello':
- postToHost(
- 'embed:hello',
- {
- embedVersion: EMBED_VERSION,
- agentId,
- capabilities: [
- 'speak',
- 'gesture',
- 'emote',
- 'theme',
- 'resize',
- 'pause',
- 'resume',
- 'set-agent',
- ],
- },
- id,
- );
- break;
-
- case 'host:ping':
- postToHost('embed:pong', {}, id);
- break;
-
- case 'host:action':
- if (payload.action) dispatchAction(payload.action);
- break;
-
- case 'host:pause':
- el.pause?.();
- break;
-
- case 'host:resume':
- el.resume?.();
- break;
-
- case 'host:theme':
- applyTheme(payload);
- break;
-
- case 'host:set-agent':
- if (payload.agentId && payload.agentId !== agentId) {
- const url = new URL(location.href);
- url.searchParams.set('agent', payload.agentId);
- location.replace(url.toString());
- }
- break;
+ // ── Legacy envelope: { v:1, ns:'3d-agent', type:'host:xxx', ... } ─────────
+ if (data.v === 1 && data.ns === '3d-agent' && typeof data.type === 'string') {
+ const { type, id, payload = {} } = data;
+ switch (type) {
+ case 'host:hello':
+ post(
+ 'ready',
+ { agentId, embedVersion: EMBED_VERSION, capabilities: CAPABILITIES },
+ id,
+ );
+ break;
+ case 'host:ping':
+ post('pong', {}, id);
+ break;
+ case 'host:action':
+ if (payload.action) {
+ const a = payload.action;
+ dispatchAction(a.type, a.payload || {}, null);
+ }
+ break;
+ case 'host:pause':
+ el.pause?.();
+ break;
+ case 'host:resume':
+ el.resume?.();
+ break;
+ case 'host:theme':
+ applyTheme(payload);
+ break;
+ case 'host:set-agent':
+ dispatchAction('setAgent', payload, null);
+ break;
+ }
}
}
+// ── Theme ─────────────────────────────────────────────────────────────────────
+
+function applyTheme({ mode, accent } = {}) {
+ if (mode === 'dark') document.body.style.background = '#0b0d10';
+ else if (mode === 'light') document.body.style.background = '#f5f5f5';
+ else if (mode === 'transparent') document.body.style.background = 'transparent';
+ if (accent) document.documentElement.style.setProperty('--agent-accent', accent);
+}
+
window.addEventListener('message', onMessage);
-// Fire initial hello so host knows the iframe is alive.
-postToHost('embed:hello', {
- embedVersion: EMBED_VERSION,
+// Fire initial ready event so the host knows the iframe is alive.
+// The host should respond with a ping to complete the handshake.
+post('ready', {
agentId,
- capabilities: ['speak', 'gesture', 'emote', 'theme', 'resize', 'pause', 'resume', 'set-agent'],
+ embedVersion: EMBED_VERSION,
+ capabilities: CAPABILITIES,
});
diff --git a/public/lobehub/iframe/index.html b/public/lobehub/iframe/index.html
index c15054522..285a7033e 100644
--- a/public/lobehub/iframe/index.html
+++ b/public/lobehub/iframe/index.html
@@ -34,11 +34,10 @@
}
</style>
<!--
- TODO(lobehub-sdk): Replace with versioned CDN URL once agent-3d releases are
- published to /agent-3d/latest/. Dev: run `npm run build:lib` then serve
- dist-lib/ under /agent-3d/latest/.
- TODO(lobehub-spec): Confirm LobeHub sandbox CSP allows module scripts from
- cross-origin CDN, or switch to a bundled inline approach.
+ Loads the <agent-3d> web component from the 3D Agent CDN.
+ For local development, run `npm run build:lib` and serve dist-lib/ under
+ /agent-3d/latest/ so this path resolves without hitting the CDN.
+ LobeChat's sandbox CSP must allow module scripts from this origin.
-->
<script
type="module"
@@ -48,7 +47,7 @@
</head>
<body>
<div id="status">Loading…</div>
- <!-- agent-id is set dynamically by boot.js from ?agent= param -->
+ <!-- agent-id is set dynamically by boot.js from ?agent= query param -->
<agent-3d id="agent" kiosk eager></agent-3d>
<script type="module" src="./boot.js"></script>
</body>
diff --git a/public/login.html b/public/login.html
index 6899653f6..72e521536 100644
--- a/public/login.html
+++ b/public/login.html
@@ -1,93 +1,261 @@
<!doctype html>
<html lang="en">
-<head>
-<meta charset="utf-8">
-<meta name="viewport" content="width=device-width,initial-scale=1">
-<title>Sign in · 3D Agent</title>
-<link rel="icon" href="/favicon.ico">
-<meta name="privy-app-id" content="">
-<style>
- :root { color-scheme: dark; --accent:#6a5cff; --accent2:#ff5ca8; }
- * { box-sizing: border-box; }
- body { font: 15px/1.5 -apple-system,system-ui,Segoe UI,Roboto,sans-serif; background:radial-gradient(1200px 600px at 50% -100px,#1a1a2e 0,#080814 60%); color:#eee; margin:0; min-height:100vh; display:grid; place-items:center; padding:24px; }
- a { color:#9a8cff; }
- .card { background:#14141c; border:1px solid #2a2a36; border-radius:16px; padding:32px; max-width:400px; width:100%; box-shadow:0 10px 40px rgba(0,0,0,.5); }
- h1 { font-size:22px; margin:0 0 4px; letter-spacing:-0.01em; }
- .sub { color:#888; margin:0 0 24px; font-size:14px; }
- label { display:block; font-size:13px; color:#aaa; margin:14px 0 6px; }
- input { width:100%; padding:11px 13px; background:#0f0f17; border:1px solid #2a2a36; border-radius:9px; color:#eee; font-size:15px; }
- input:focus { outline:none; border-color:var(--accent); box-shadow:0 0 0 3px rgba(106,92,255,.15); }
- button { width:100%; margin-top:20px; padding:12px 16px; border:0; border-radius:10px; background:linear-gradient(135deg,var(--accent),var(--accent2)); color:#fff; font-weight:600; font-size:15px; cursor:pointer; }
- button:disabled { opacity:.6; cursor:default; }
- .err { margin-top:14px; padding:10px 12px; background:rgba(255,92,92,.1); border:1px solid rgba(255,92,92,.3); border-radius:8px; color:#ffb3b3; font-size:13px; display:none; }
- .foot { margin-top:20px; text-align:center; font-size:13px; color:#888; }
- .brand { font-size:12px; letter-spacing:.1em; text-transform:uppercase; color:var(--accent); margin:0 0 8px; }
- .wallet-btn { background:#1c1c28; border:1px solid #2a2a36; color:#eee; font-weight:500; margin-top:12px; display:flex; align-items:center; justify-content:center; gap:8px; }
- .wallet-btn:hover { background:#22222e; border-color:var(--accent); }
- .divider { display:flex; align-items:center; gap:12px; margin:22px 0 4px; color:#555; font-size:12px; text-transform:uppercase; letter-spacing:.08em; }
- .divider::before, .divider::after { content:''; flex:1; height:1px; background:#2a2a36; }
- .wallet-icon { width:18px; height:18px; }
-</style>
-</head>
-<body>
-<form class="card" id="f">
- <p class="brand">3D Agent</p>
- <h1>Welcome back</h1>
- <p class="sub">Sign in to manage your avatars.</p>
- <label for="email">Email or username</label>
- <input id="email" type="text" autocomplete="username email" required>
- <label for="password">Password</label>
- <input id="password" type="password" autocomplete="current-password" required minlength="10">
- <button id="submit" type="submit">Sign in</button>
- <div class="divider">or</div>
- <button id="privy" type="button" class="wallet-btn" style="background:linear-gradient(135deg,var(--accent),var(--accent2)); border-color:transparent; color:#fff">
- <svg class="wallet-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="8" r="4"/><path d="M20 21a8 8 0 0 0-16 0"/></svg>
- Sign in with Privy
- </button>
- <button id="wallet" type="button" class="wallet-btn">
- <svg class="wallet-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="6" width="20" height="14" rx="2"/><path d="M16 12h2"/></svg>
- Sign in with MetaMask
- </button>
- <div class="err" id="err"></div>
- <p class="foot">No account? <a href="/register">Create one</a></p>
-</form>
-<script type="module" src="/wallet-login.js"></script>
-<script>
-const params = new URLSearchParams(location.search);
-const next = params.get('next') || '/dashboard/';
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>Sign in · 3D Agent</title>
+ <link rel="icon" href="/favicon.ico" />
+ <meta name="privy-app-id" content="" />
+ <style>
+ :root {
+ color-scheme: dark;
+ --accent: #6a5cff;
+ --accent2: #ff5ca8;
+ }
+ * {
+ box-sizing: border-box;
+ }
+ body {
+ font:
+ 15px/1.5 -apple-system,
+ system-ui,
+ Segoe UI,
+ Roboto,
+ sans-serif;
+ background: radial-gradient(1200px 600px at 50% -100px, #1a1a2e 0, #080814 60%);
+ color: #eee;
+ margin: 0;
+ min-height: 100vh;
+ display: grid;
+ place-items: center;
+ padding: 24px;
+ }
+ a {
+ color: #9a8cff;
+ }
+ .card {
+ background: #14141c;
+ border: 1px solid #2a2a36;
+ border-radius: 16px;
+ padding: 32px;
+ max-width: 400px;
+ width: 100%;
+ box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
+ }
+ h1 {
+ font-size: 22px;
+ margin: 0 0 4px;
+ letter-spacing: -0.01em;
+ }
+ .sub {
+ color: #888;
+ margin: 0 0 24px;
+ font-size: 14px;
+ }
+ label {
+ display: block;
+ font-size: 13px;
+ color: #aaa;
+ margin: 14px 0 6px;
+ }
+ input {
+ width: 100%;
+ padding: 11px 13px;
+ background: #0f0f17;
+ border: 1px solid #2a2a36;
+ border-radius: 9px;
+ color: #eee;
+ font-size: 15px;
+ }
+ input:focus {
+ outline: none;
+ border-color: var(--accent);
+ box-shadow: 0 0 0 3px rgba(106, 92, 255, 0.15);
+ }
+ button {
+ width: 100%;
+ margin-top: 20px;
+ padding: 12px 16px;
+ border: 0;
+ border-radius: 10px;
+ background: linear-gradient(135deg, var(--accent), var(--accent2));
+ color: #fff;
+ font-weight: 600;
+ font-size: 15px;
+ cursor: pointer;
+ }
+ button:disabled {
+ opacity: 0.6;
+ cursor: default;
+ }
+ .err {
+ margin-top: 14px;
+ padding: 10px 12px;
+ background: rgba(255, 92, 92, 0.1);
+ border: 1px solid rgba(255, 92, 92, 0.3);
+ border-radius: 8px;
+ color: #ffb3b3;
+ font-size: 13px;
+ display: none;
+ }
+ .foot {
+ margin-top: 20px;
+ text-align: center;
+ font-size: 13px;
+ color: #888;
+ }
+ .brand {
+ font-size: 12px;
+ letter-spacing: 0.1em;
+ text-transform: uppercase;
+ color: var(--accent);
+ margin: 0 0 8px;
+ }
+ .wallet-btn {
+ background: #1c1c28;
+ border: 1px solid #2a2a36;
+ color: #eee;
+ font-weight: 500;
+ margin-top: 12px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ }
+ .wallet-btn:hover {
+ background: #22222e;
+ border-color: var(--accent);
+ }
+ .divider {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ margin: 22px 0 4px;
+ color: #555;
+ font-size: 12px;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ }
+ .divider::before,
+ .divider::after {
+ content: '';
+ flex: 1;
+ height: 1px;
+ background: #2a2a36;
+ }
+ .wallet-icon {
+ width: 18px;
+ height: 18px;
+ }
+ </style>
+ </head>
+ <body>
+ <form class="card" id="f">
+ <p class="brand">3D Agent</p>
+ <h1>Welcome back</h1>
+ <p class="sub">Sign in to manage your avatars.</p>
+ <label for="email">Email or username</label>
+ <input id="email" type="text" autocomplete="username email" required />
+ <label for="password">Password</label>
+ <input
+ id="password"
+ type="password"
+ autocomplete="current-password"
+ required
+ minlength="10"
+ />
+ <button id="submit" type="submit">Sign in</button>
+ <div class="divider">or</div>
+ <button
+ id="privy"
+ type="button"
+ class="wallet-btn"
+ style="
+ background: linear-gradient(135deg, var(--accent), var(--accent2));
+ border-color: transparent;
+ color: #fff;
+ "
+ >
+ <svg
+ class="wallet-icon"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ >
+ <circle cx="12" cy="8" r="4" />
+ <path d="M20 21a8 8 0 0 0-16 0" />
+ </svg>
+ Sign in with Privy
+ </button>
+ <button id="wallet" type="button" class="wallet-btn">
+ <svg
+ class="wallet-icon"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ >
+ <rect x="2" y="6" width="20" height="14" rx="2" />
+ <path d="M16 12h2" />
+ </svg>
+ Sign in with MetaMask
+ </button>
+ <div class="err" id="err"></div>
+ <p class="foot">No account? <a href="/register">Create one</a></p>
+ </form>
+ <script type="module" src="/wallet-login.js"></script>
+ <script>
+ const params = new URLSearchParams(location.search);
+ const next = params.get('next') || '/dashboard/';
-// If already signed in, skip the login form entirely.
-fetch('/api/auth/me', { credentials: 'include' })
- .then(r => { if (r.ok) location.replace(next); })
- .catch(() => {});
+ // If already signed in, skip the login form entirely.
+ fetch('/api/auth/me', { credentials: 'include' })
+ .then((r) => {
+ if (r.ok) location.replace(next);
+ })
+ .catch(() => {});
-const form = document.getElementById('f');
-const err = document.getElementById('err');
-const btn = document.getElementById('submit');
-form.addEventListener('submit', async (e) => {
- e.preventDefault();
- err.style.display = 'none';
- btn.disabled = true; btn.textContent = 'Signing in…';
- try {
- const res = await fetch('/api/auth/login', {
- method: 'POST',
- credentials: 'include',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({
- email: document.getElementById('email').value,
- password: document.getElementById('password').value,
- }),
- });
- const data = await res.json();
- if (!res.ok) throw new Error(data.error_description || 'Sign-in failed');
- try { localStorage.setItem('3dagent:auth-hint', JSON.stringify({ authed: true, ts: Date.now() })); } catch { /* ignore */ }
- location.href = next;
- } catch (e) {
- err.textContent = e.message;
- err.style.display = 'block';
- btn.disabled = false; btn.textContent = 'Sign in';
- }
-});
-</script>
-</body>
+ const form = document.getElementById('f');
+ const err = document.getElementById('err');
+ const btn = document.getElementById('submit');
+ form.addEventListener('submit', async (e) => {
+ e.preventDefault();
+ err.style.display = 'none';
+ btn.disabled = true;
+ btn.textContent = 'Signing in…';
+ try {
+ const res = await fetch('/api/auth/login', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ email: document.getElementById('email').value,
+ password: document.getElementById('password').value,
+ }),
+ });
+ const data = await res.json();
+ if (!res.ok) throw new Error(data.error_description || 'Sign-in failed');
+ try {
+ localStorage.setItem(
+ '3dagent:auth-hint',
+ JSON.stringify({ authed: true, ts: Date.now() }),
+ );
+ } catch {
+ /* ignore */
+ }
+ location.href = next;
+ } catch (e) {
+ err.textContent = e.message;
+ err.style.display = 'block';
+ btn.disabled = false;
+ btn.textContent = 'Sign in';
+ }
+ });
+ </script>
+ </body>
</html>
diff --git a/public/register.html b/public/register.html
index 00e445dfb..fefc9720f 100644
--- a/public/register.html
+++ b/public/register.html
@@ -1,74 +1,192 @@
<!doctype html>
<html lang="en">
-<head>
-<meta charset="utf-8">
-<meta name="viewport" content="width=device-width,initial-scale=1">
-<title>Create account · 3D Agent</title>
-<link rel="icon" href="/favicon.ico">
-<style>
- :root { color-scheme: dark; --accent:#6a5cff; --accent2:#ff5ca8; }
- * { box-sizing: border-box; }
- body { font: 15px/1.5 -apple-system,system-ui,Segoe UI,Roboto,sans-serif; background:radial-gradient(1200px 600px at 50% -100px,#1a1a2e 0,#080814 60%); color:#eee; margin:0; min-height:100vh; display:grid; place-items:center; padding:24px; }
- a { color:#9a8cff; }
- .card { background:#14141c; border:1px solid #2a2a36; border-radius:16px; padding:32px; max-width:400px; width:100%; box-shadow:0 10px 40px rgba(0,0,0,.5); }
- h1 { font-size:22px; margin:0 0 4px; letter-spacing:-0.01em; }
- .sub { color:#888; margin:0 0 24px; font-size:14px; }
- label { display:block; font-size:13px; color:#aaa; margin:14px 0 6px; }
- input { width:100%; padding:11px 13px; background:#0f0f17; border:1px solid #2a2a36; border-radius:9px; color:#eee; font-size:15px; }
- input:focus { outline:none; border-color:var(--accent); box-shadow:0 0 0 3px rgba(106,92,255,.15); }
- .hint { font-size:12px; color:#666; margin-top:4px; }
- button { width:100%; margin-top:20px; padding:12px 16px; border:0; border-radius:10px; background:linear-gradient(135deg,var(--accent),var(--accent2)); color:#fff; font-weight:600; font-size:15px; cursor:pointer; }
- button:disabled { opacity:.6; cursor:default; }
- .err { margin-top:14px; padding:10px 12px; background:rgba(255,92,92,.1); border:1px solid rgba(255,92,92,.3); border-radius:8px; color:#ffb3b3; font-size:13px; display:none; }
- .foot { margin-top:20px; text-align:center; font-size:13px; color:#888; }
- .brand { font-size:12px; letter-spacing:.1em; text-transform:uppercase; color:var(--accent); margin:0 0 8px; }
-</style>
-</head>
-<body>
-<form class="card" id="f">
- <p class="brand">3D Agent</p>
- <h1>Create account</h1>
- <p class="sub">Pick a username and password — no email needed.</p>
- <label for="username">Username</label>
- <input id="username" type="text" autocomplete="username" required minlength="3" maxlength="30" pattern="[a-zA-Z0-9_-]+" placeholder="e.g. cool_agent">
- <p class="hint">3–30 characters, letters, numbers, _ or -</p>
- <label for="password">Password</label>
- <input id="password" type="password" autocomplete="new-password" required minlength="10" maxlength="200">
- <p class="hint">Minimum 10 characters</p>
- <button id="submit" type="submit">Create account</button>
- <div class="err" id="err"></div>
- <p class="foot">Already have an account? <a href="/login">Sign in</a></p>
-</form>
-<script>
-const params = new URLSearchParams(location.search);
-const next = params.get('next') || '/dashboard/';
-const form = document.getElementById('f');
-const err = document.getElementById('err');
-const btn = document.getElementById('submit');
-form.addEventListener('submit', async (e) => {
- e.preventDefault();
- err.style.display = 'none';
- btn.disabled = true; btn.textContent = 'Creating account…';
- try {
- const res = await fetch('/api/auth/register', {
- method: 'POST',
- credentials: 'include',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({
- username: document.getElementById('username').value,
- password: document.getElementById('password').value,
- }),
- });
- const data = await res.json();
- if (!res.ok) throw new Error(data.error_description || 'Registration failed');
- try { localStorage.setItem('3dagent:auth-hint', JSON.stringify({ authed: true, ts: Date.now() })); } catch { /* ignore */ }
- location.href = next;
- } catch (e) {
- err.textContent = e.message;
- err.style.display = 'block';
- btn.disabled = false; btn.textContent = 'Create account';
- }
-});
-</script>
-</body>
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>Create account · 3D Agent</title>
+ <link rel="icon" href="/favicon.ico" />
+ <style>
+ :root {
+ color-scheme: dark;
+ --accent: #6a5cff;
+ --accent2: #ff5ca8;
+ }
+ * {
+ box-sizing: border-box;
+ }
+ body {
+ font:
+ 15px/1.5 -apple-system,
+ system-ui,
+ Segoe UI,
+ Roboto,
+ sans-serif;
+ background: radial-gradient(1200px 600px at 50% -100px, #1a1a2e 0, #080814 60%);
+ color: #eee;
+ margin: 0;
+ min-height: 100vh;
+ display: grid;
+ place-items: center;
+ padding: 24px;
+ }
+ a {
+ color: #9a8cff;
+ }
+ .card {
+ background: #14141c;
+ border: 1px solid #2a2a36;
+ border-radius: 16px;
+ padding: 32px;
+ max-width: 400px;
+ width: 100%;
+ box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
+ }
+ h1 {
+ font-size: 22px;
+ margin: 0 0 4px;
+ letter-spacing: -0.01em;
+ }
+ .sub {
+ color: #888;
+ margin: 0 0 24px;
+ font-size: 14px;
+ }
+ label {
+ display: block;
+ font-size: 13px;
+ color: #aaa;
+ margin: 14px 0 6px;
+ }
+ input {
+ width: 100%;
+ padding: 11px 13px;
+ background: #0f0f17;
+ border: 1px solid #2a2a36;
+ border-radius: 9px;
+ color: #eee;
+ font-size: 15px;
+ }
+ input:focus {
+ outline: none;
+ border-color: var(--accent);
+ box-shadow: 0 0 0 3px rgba(106, 92, 255, 0.15);
+ }
+ .hint {
+ font-size: 12px;
+ color: #666;
+ margin-top: 4px;
+ }
+ button {
+ width: 100%;
+ margin-top: 20px;
+ padding: 12px 16px;
+ border: 0;
+ border-radius: 10px;
+ background: linear-gradient(135deg, var(--accent), var(--accent2));
+ color: #fff;
+ font-weight: 600;
+ font-size: 15px;
+ cursor: pointer;
+ }
+ button:disabled {
+ opacity: 0.6;
+ cursor: default;
+ }
+ .err {
+ margin-top: 14px;
+ padding: 10px 12px;
+ background: rgba(255, 92, 92, 0.1);
+ border: 1px solid rgba(255, 92, 92, 0.3);
+ border-radius: 8px;
+ color: #ffb3b3;
+ font-size: 13px;
+ display: none;
+ }
+ .foot {
+ margin-top: 20px;
+ text-align: center;
+ font-size: 13px;
+ color: #888;
+ }
+ .brand {
+ font-size: 12px;
+ letter-spacing: 0.1em;
+ text-transform: uppercase;
+ color: var(--accent);
+ margin: 0 0 8px;
+ }
+ </style>
+ </head>
+ <body>
+ <form class="card" id="f">
+ <p class="brand">3D Agent</p>
+ <h1>Create account</h1>
+ <p class="sub">Pick a username and password — no email needed.</p>
+ <label for="username">Username</label>
+ <input
+ id="username"
+ type="text"
+ autocomplete="username"
+ required
+ minlength="3"
+ maxlength="30"
+ pattern="[a-zA-Z0-9_-]+"
+ placeholder="e.g. cool_agent"
+ />
+ <p class="hint">3–30 characters, letters, numbers, _ or -</p>
+ <label for="password">Password</label>
+ <input
+ id="password"
+ type="password"
+ autocomplete="new-password"
+ required
+ minlength="10"
+ maxlength="200"
+ />
+ <p class="hint">Minimum 10 characters</p>
+ <button id="submit" type="submit">Create account</button>
+ <div class="err" id="err"></div>
+ <p class="foot">Already have an account? <a href="/login">Sign in</a></p>
+ </form>
+ <script>
+ const params = new URLSearchParams(location.search);
+ const next = params.get('next') || '/dashboard/';
+ const form = document.getElementById('f');
+ const err = document.getElementById('err');
+ const btn = document.getElementById('submit');
+ form.addEventListener('submit', async (e) => {
+ e.preventDefault();
+ err.style.display = 'none';
+ btn.disabled = true;
+ btn.textContent = 'Creating account…';
+ try {
+ const res = await fetch('/api/auth/register', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ username: document.getElementById('username').value,
+ password: document.getElementById('password').value,
+ }),
+ });
+ const data = await res.json();
+ if (!res.ok) throw new Error(data.error_description || 'Registration failed');
+ try {
+ localStorage.setItem(
+ '3dagent:auth-hint',
+ JSON.stringify({ authed: true, ts: Date.now() }),
+ );
+ } catch {
+ /* ignore */
+ }
+ location.href = next;
+ } catch (e) {
+ err.textContent = e.message;
+ err.style.display = 'block';
+ btn.disabled = false;
+ btn.textContent = 'Create account';
+ }
+ });
+ </script>
+ </body>
</html>
diff --git a/public/reputation/index.html b/public/reputation/index.html
index 86fe7af1c..34fe899de 100644
--- a/public/reputation/index.html
+++ b/public/reputation/index.html
@@ -11,7 +11,10 @@
<link rel="shortcut icon" href="/favicon.ico" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
- <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap" rel="stylesheet" />
+ <link
+ href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap"
+ rel="stylesheet"
+ />
<style>
* {
diff --git a/public/reputation/reputation.js b/public/reputation/reputation.js
index 913d2a334..91be3d42e 100644
--- a/public/reputation/reputation.js
+++ b/public/reputation/reputation.js
@@ -294,7 +294,9 @@ async function main() {
btn.textContent = i >= 0 ? `+${i}` : `${i}`;
btn.dataset.value = i;
btn.addEventListener('click', () => {
- document.querySelectorAll('#rating-input button').forEach(b => b.classList.remove('selected'));
+ document
+ .querySelectorAll('#rating-input button')
+ .forEach((b) => b.classList.remove('selected'));
btn.classList.add('selected');
document.getElementById('rep-rating').value = i;
submitBtn.disabled = false;
@@ -318,7 +320,9 @@ async function main() {
connectedAddress = accounts[0];
// Check if already reviewed
- const hasReviewed = recentReviews.some(r => r.from.toLowerCase() === connectedAddress.toLowerCase());
+ const hasReviewed = recentReviews.some(
+ (r) => r.from.toLowerCase() === connectedAddress.toLowerCase(),
+ );
if (hasReviewed) {
walletStatus.innerHTML = `
<div class="rep-error">
diff --git a/public/studio/index.html b/public/studio/index.html
index 839368efd..d619c564d 100644
--- a/public/studio/index.html
+++ b/public/studio/index.html
@@ -1,154 +1,213 @@
<!doctype html>
<html lang="en">
-<head>
- <meta charset="utf-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <title>Widget Studio · 3D Agent</title>
- <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
- <meta name="description" content="Turn any avatar into an embeddable 3D widget. Five types, brand controls, one-line embed.">
- <meta name="theme-color" content="#0a0a0a">
- <meta name="robots" content="noindex">
- <link rel="shortcut icon" href="/favicon.ico">
- <link rel="preconnect" href="https://fonts.googleapis.com">
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
- <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap" rel="stylesheet">
- <link rel="stylesheet" href="/style.css">
- <link rel="stylesheet" href="/studio/studio.css">
-</head>
-<body class="studio-body">
- <header class="studio-header">
- <h1><a href="/"><span class="wordmark-dot" aria-hidden="true"></span>3D Agent</a><span class="studio-tag">Studio</span></h1>
- <nav>
- <a href="/widgets">Gallery</a>
- <a href="/docs/widgets">Docs</a>
- <a href="/dashboard#widgets">My widgets</a>
- <button class="btn-ghost" id="signout-btn" type="button">Sign out</button>
- </nav>
- </header>
+ <head>
+ <meta charset="utf-8" />
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+ <title>Widget Studio · 3D Agent</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
+ <meta
+ name="description"
+ content="Turn any avatar into an embeddable 3D widget. Five types, brand controls, one-line embed."
+ />
+ <meta name="theme-color" content="#0a0a0a" />
+ <meta name="robots" content="noindex" />
+ <link rel="shortcut icon" href="/favicon.ico" />
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
+ <link
+ href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap"
+ rel="stylesheet"
+ />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/studio/studio.css" />
+ </head>
+ <body class="studio-body">
+ <header class="studio-header">
+ <h1>
+ <a href="/"><span class="wordmark-dot" aria-hidden="true"></span>3D Agent</a
+ ><span class="studio-tag">Studio</span>
+ </h1>
+ <nav>
+ <a href="/widgets">Gallery</a>
+ <a href="/docs/widgets">Docs</a>
+ <a href="/dashboard#widgets">My widgets</a>
+ <button class="btn-ghost" id="signout-btn" type="button">Sign out</button>
+ </nav>
+ </header>
- <main class="studio-layout" id="studio-layout" hidden>
- <section class="studio-col-left" aria-label="Pick avatar and widget type">
- <div class="panel">
- <h2>1. Pick avatar</h2>
- <div class="avatar-list" id="avatar-list" aria-busy="true"></div>
- </div>
- <div class="panel">
- <h2>2. Pick widget type</h2>
- <div class="type-grid" id="type-grid"></div>
- </div>
- </section>
-
- <section class="studio-col-mid" aria-label="Preview">
- <div class="preview-shell">
- <div class="preview-frame" id="preview-frame">
- <iframe id="preview-iframe" title="Live widget preview" allow="autoplay; xr-spatial-tracking" loading="eager"></iframe>
+ <main class="studio-layout" id="studio-layout" hidden>
+ <section class="studio-col-left" aria-label="Pick avatar and widget type">
+ <div class="panel">
+ <h2>1. Pick avatar</h2>
+ <div class="avatar-list" id="avatar-list" aria-busy="true"></div>
</div>
- <div class="preview-meta">
- <span id="preview-status" class="muted">Pick an avatar to preview</span>
- <button class="btn-ghost btn-sm" id="capture-camera-btn" type="button" disabled>Use current view</button>
+ <div class="panel">
+ <h2>2. Pick widget type</h2>
+ <div class="type-grid" id="type-grid"></div>
</div>
- </div>
- </section>
-
- <section class="studio-col-right" aria-label="Brand and config">
- <div class="panel">
- <h2>3. Brand</h2>
- <form id="config-form" class="config-form" autocomplete="off" onsubmit="return false">
- <label class="field">
- <span>Name</span>
- <input type="text" name="name" maxlength="120" required placeholder="My turntable widget">
- </label>
- <label class="field">
- <span>Background</span>
- <input type="color" name="background" value="#0a0a0a">
- </label>
- <label class="field">
- <span>Accent</span>
- <input type="color" name="accent" value="#8b5cf6">
- </label>
- <label class="field">
- <span>Caption (optional)</span>
- <input type="text" name="caption" maxlength="280" placeholder="Hello, world.">
- </label>
- <label class="field row">
- <input type="checkbox" name="showControls" checked>
- <span>Show controls</span>
- </label>
- <label class="field row">
- <input type="checkbox" name="autoRotate" checked>
- <span>Auto-rotate</span>
- </label>
- <label class="field">
- <span>Environment</span>
- <select name="envPreset">
- <option value="none">None</option>
- <option value="neutral" selected>Neutral</option>
- <option value="venice-sunset">Venice sunset</option>
- <option value="footprint-court">Footprint court</option>
- </select>
- </label>
- <label class="field row">
- <input type="checkbox" name="is_public" checked>
- <span>Public widget (anyone with the URL can load it)</span>
- </label>
+ </section>
- <div id="type-fields" class="type-fields"></div>
- </form>
- </div>
+ <section class="studio-col-mid" aria-label="Preview">
+ <div class="preview-shell">
+ <div class="preview-frame" id="preview-frame">
+ <iframe
+ id="preview-iframe"
+ title="Live widget preview"
+ allow="autoplay; xr-spatial-tracking"
+ loading="eager"
+ ></iframe>
+ </div>
+ <div class="preview-meta">
+ <span id="preview-status" class="muted">Pick an avatar to preview</span>
+ <button
+ class="btn-ghost btn-sm"
+ id="capture-camera-btn"
+ type="button"
+ disabled
+ >
+ Use current view
+ </button>
+ </div>
+ </div>
+ </section>
- <div class="action-row">
- <button type="button" class="btn-ghost" id="save-draft-btn">Save draft</button>
- <button type="button" class="btn-primary" id="generate-btn">Generate embed</button>
- </div>
- <p id="form-error" class="form-error" hidden></p>
- </section>
- </main>
+ <section class="studio-col-right" aria-label="Brand and config">
+ <div class="panel">
+ <h2>3. Brand</h2>
+ <form
+ id="config-form"
+ class="config-form"
+ autocomplete="off"
+ onsubmit="return false"
+ >
+ <label class="field">
+ <span>Name</span>
+ <input
+ type="text"
+ name="name"
+ maxlength="120"
+ required
+ placeholder="My turntable widget"
+ />
+ </label>
+ <label class="field">
+ <span>Background</span>
+ <input type="color" name="background" value="#0a0a0a" />
+ </label>
+ <label class="field">
+ <span>Accent</span>
+ <input type="color" name="accent" value="#8b5cf6" />
+ </label>
+ <label class="field">
+ <span>Caption (optional)</span>
+ <input
+ type="text"
+ name="caption"
+ maxlength="280"
+ placeholder="Hello, world."
+ />
+ </label>
+ <label class="field row">
+ <input type="checkbox" name="showControls" checked />
+ <span>Show controls</span>
+ </label>
+ <label class="field row">
+ <input type="checkbox" name="autoRotate" checked />
+ <span>Auto-rotate</span>
+ </label>
+ <label class="field">
+ <span>Environment</span>
+ <select name="envPreset">
+ <option value="none">None</option>
+ <option value="neutral" selected>Neutral</option>
+ <option value="venice-sunset">Venice sunset</option>
+ <option value="footprint-court">Footprint court</option>
+ </select>
+ </label>
+ <label class="field row">
+ <input type="checkbox" name="is_public" checked />
+ <span>Public widget (anyone with the URL can load it)</span>
+ </label>
- <div class="auth-blocker" id="auth-blocker">
- <div class="auth-blocker-card">
- <p>Sign in to use the Studio.</p>
- <a class="btn-primary" href="#" id="signin-link">Sign in →</a>
- </div>
- </div>
+ <div id="type-fields" class="type-fields"></div>
+ </form>
+ </div>
- <div class="modal-overlay" id="embed-modal" hidden>
- <div class="modal" role="dialog" aria-labelledby="embed-modal-title" aria-modal="true">
- <button type="button" class="modal-close" id="embed-modal-close" aria-label="Close">×</button>
- <h2 id="embed-modal-title">Your widget is live</h2>
- <p class="muted">Share the URL or paste the snippet anywhere.</p>
+ <div class="action-row">
+ <button type="button" class="btn-ghost" id="save-draft-btn">Save draft</button>
+ <button type="button" class="btn-primary" id="generate-btn">
+ Generate embed
+ </button>
+ </div>
+ <p id="form-error" class="form-error" hidden></p>
+ </section>
+ </main>
- <div class="embed-preview">
- <iframe id="embed-preview-iframe" title="Embed preview" allow="autoplay; xr-spatial-tracking"></iframe>
+ <div class="auth-blocker" id="auth-blocker">
+ <div class="auth-blocker-card">
+ <p>Sign in to use the Studio.</p>
+ <a class="btn-primary" href="#" id="signin-link">Sign in →</a>
</div>
+ </div>
- <label class="field">
- <span>Shareable URL</span>
- <div class="copy-row">
- <input type="text" id="embed-share-url" readonly>
- <button type="button" class="btn-ghost btn-sm" data-copy="#embed-share-url">Copy</button>
- </div>
- </label>
+ <div class="modal-overlay" id="embed-modal" hidden>
+ <div class="modal" role="dialog" aria-labelledby="embed-modal-title" aria-modal="true">
+ <button type="button" class="modal-close" id="embed-modal-close" aria-label="Close">
+ ×
+ </button>
+ <h2 id="embed-modal-title">Your widget is live</h2>
+ <p class="muted">Share the URL or paste the snippet anywhere.</p>
- <label class="field">
- <span>iframe snippet</span>
- <div class="copy-row">
- <textarea id="embed-iframe-snippet" rows="3" readonly></textarea>
- <button type="button" class="btn-ghost btn-sm" data-copy="#embed-iframe-snippet">Copy</button>
+ <div class="embed-preview">
+ <iframe
+ id="embed-preview-iframe"
+ title="Embed preview"
+ allow="autoplay; xr-spatial-tracking"
+ ></iframe>
</div>
- </label>
- <details>
- <summary>Script-tag embed</summary>
- <div class="copy-row">
- <textarea id="embed-script-snippet" rows="2" readonly></textarea>
- <button type="button" class="btn-ghost btn-sm" data-copy="#embed-script-snippet">Copy</button>
- </div>
- </details>
+ <label class="field">
+ <span>Shareable URL</span>
+ <div class="copy-row">
+ <input type="text" id="embed-share-url" readonly />
+ <button type="button" class="btn-ghost btn-sm" data-copy="#embed-share-url">
+ Copy
+ </button>
+ </div>
+ </label>
+
+ <label class="field">
+ <span>iframe snippet</span>
+ <div class="copy-row">
+ <textarea id="embed-iframe-snippet" rows="3" readonly></textarea>
+ <button
+ type="button"
+ class="btn-ghost btn-sm"
+ data-copy="#embed-iframe-snippet"
+ >
+ Copy
+ </button>
+ </div>
+ </label>
+
+ <details>
+ <summary>Script-tag embed</summary>
+ <div class="copy-row">
+ <textarea id="embed-script-snippet" rows="2" readonly></textarea>
+ <button
+ type="button"
+ class="btn-ghost btn-sm"
+ data-copy="#embed-script-snippet"
+ >
+ Copy
+ </button>
+ </div>
+ </details>
+ </div>
</div>
- </div>
- <div class="toast" id="toast" hidden></div>
+ <div class="toast" id="toast" hidden></div>
- <script type="module" src="/studio/studio.js"></script>
-</body>
+ <script type="module" src="/studio/studio.js"></script>
+ </body>
</html>
diff --git a/public/studio/studio.css b/public/studio/studio.css
index 413d8d056..4a4b394e7 100644
--- a/public/studio/studio.css
+++ b/public/studio/studio.css
@@ -1,6 +1,7 @@
/* Widget Studio — dark, three-column. Reuses tokens from /style.css. */
-html, body.studio-body {
+html,
+body.studio-body {
height: 100%;
overflow: hidden;
}
@@ -48,7 +49,9 @@ html, body.studio-body {
color: rgba(229, 229, 229, 0.7);
text-decoration: none;
}
-.studio-header nav a:hover { color: #fff; }
+.studio-header nav a:hover {
+ color: #fff;
+}
.studio-layout {
display: grid;
@@ -59,11 +62,20 @@ html, body.studio-body {
overflow: hidden;
}
@media (max-width: 1024px) {
- .studio-layout { grid-template-columns: 1fr; height: auto; overflow: auto; }
- html, body.studio-body { overflow: auto; height: auto; }
+ .studio-layout {
+ grid-template-columns: 1fr;
+ height: auto;
+ overflow: auto;
+ }
+ html,
+ body.studio-body {
+ overflow: auto;
+ height: auto;
+ }
}
-.studio-col-left, .studio-col-right {
+.studio-col-left,
+.studio-col-right {
display: flex;
flex-direction: column;
gap: var(--space-md);
@@ -109,14 +121,24 @@ html, body.studio-body {
flex-direction: column;
gap: 4px;
font-size: var(--text-sm);
- transition: border-color 0.15s, background 0.15s;
+ transition:
+ border-color 0.15s,
+ background 0.15s;
text-align: left;
color: inherit;
font-family: inherit;
}
-.avatar-card:hover { border-color: rgba(139, 92, 246, 0.5); }
-.avatar-card.selected { border-color: var(--accent); background: rgba(139, 92, 246, 0.08); }
-.avatar-card:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+.avatar-card:hover {
+ border-color: rgba(139, 92, 246, 0.5);
+}
+.avatar-card.selected {
+ border-color: var(--accent);
+ background: rgba(139, 92, 246, 0.08);
+}
+.avatar-card:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+}
.avatar-card .thumb {
aspect-ratio: 1 / 1;
background: #050505;
@@ -127,11 +149,32 @@ html, body.studio-body {
font-size: 22px;
overflow: hidden;
}
-.avatar-card .thumb img { width: 100%; height: 100%; object-fit: cover; }
-.avatar-card .name { font-size: var(--text-sm); color: #ddd; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
-.avatar-card .meta { font-size: var(--text-xs); color: #777; }
-.avatar-list .empty { grid-column: 1 / -1; padding: var(--space-md); text-align: center; color: #777; font-size: var(--text-sm); }
-.avatar-list .empty a { color: var(--accent); }
+.avatar-card .thumb img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+}
+.avatar-card .name {
+ font-size: var(--text-sm);
+ color: #ddd;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.avatar-card .meta {
+ font-size: var(--text-xs);
+ color: #777;
+}
+.avatar-list .empty {
+ grid-column: 1 / -1;
+ padding: var(--space-md);
+ text-align: center;
+ color: #777;
+ font-size: var(--text-sm);
+}
+.avatar-list .empty a {
+ color: var(--accent);
+}
.type-grid {
display: grid;
@@ -150,15 +193,35 @@ html, body.studio-body {
display: flex;
flex-direction: column;
gap: 4px;
- transition: border-color 0.15s, background 0.15s;
+ transition:
+ border-color 0.15s,
+ background 0.15s;
position: relative;
}
-.type-card:hover { border-color: rgba(139, 92, 246, 0.5); }
-.type-card.selected { border-color: var(--accent); background: rgba(139, 92, 246, 0.08); }
-.type-card:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
-.type-card .icon { font-size: 18px; opacity: 0.8; }
-.type-card .label { font-size: var(--text-sm); color: #ddd; }
-.type-card .desc { font-size: var(--text-xs); color: #888; line-height: 1.4; }
+.type-card:hover {
+ border-color: rgba(139, 92, 246, 0.5);
+}
+.type-card.selected {
+ border-color: var(--accent);
+ background: rgba(139, 92, 246, 0.08);
+}
+.type-card:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+}
+.type-card .icon {
+ font-size: 18px;
+ opacity: 0.8;
+}
+.type-card .label {
+ font-size: var(--text-sm);
+ color: #ddd;
+}
+.type-card .desc {
+ font-size: var(--text-xs);
+ color: #888;
+ line-height: 1.4;
+}
.type-card .pending {
font-size: 10px;
letter-spacing: 1px;
@@ -201,7 +264,9 @@ html, body.studio-body {
justify-content: space-between;
font-size: var(--text-sm);
}
-.muted { color: rgba(229, 229, 229, 0.55); }
+.muted {
+ color: rgba(229, 229, 229, 0.55);
+}
.config-form {
display: flex;
@@ -221,7 +286,10 @@ html, body.studio-body {
gap: var(--space-xs);
cursor: pointer;
}
-.field input[type="text"], .field select, .field textarea, .field input[type="color"] {
+.field input[type='text'],
+.field select,
+.field textarea,
+.field input[type='color'] {
background: #0a0a0a;
border: 1px solid rgba(255, 255, 255, 0.1);
color: #e5e5e5;
@@ -230,12 +298,22 @@ html, body.studio-body {
font-size: var(--text-sm);
font-family: inherit;
}
-.field input[type="color"] { padding: 2px; height: 32px; cursor: pointer; }
-.field input:focus, .field select:focus, .field textarea:focus {
+.field input[type='color'] {
+ padding: 2px;
+ height: 32px;
+ cursor: pointer;
+}
+.field input:focus,
+.field select:focus,
+.field textarea:focus {
outline: none;
border-color: var(--accent);
}
-.field input[type="checkbox"] { width: 16px; height: 16px; accent-color: var(--accent); }
+.field input[type='checkbox'] {
+ width: 16px;
+ height: 16px;
+ accent-color: var(--accent);
+}
.type-fields {
display: flex;
@@ -260,9 +338,12 @@ html, body.studio-body {
gap: var(--space-xs);
margin-top: var(--space-sm);
}
-.action-row button { flex: 1; }
+.action-row button {
+ flex: 1;
+}
-.btn-primary, .btn-ghost {
+.btn-primary,
+.btn-ghost {
display: inline-flex;
align-items: center;
justify-content: center;
@@ -275,20 +356,36 @@ html, body.studio-body {
border: 1px solid transparent;
cursor: pointer;
text-decoration: none;
- transition: background 0.15s, border-color 0.15s;
+ transition:
+ background 0.15s,
+ border-color 0.15s;
+}
+.btn-primary {
+ background: var(--accent);
+ color: #fff;
+}
+.btn-primary:hover {
+ background: #7c3aed;
}
-.btn-primary { background: var(--accent); color: #fff; }
-.btn-primary:hover { background: #7c3aed; }
.btn-ghost {
background: transparent;
color: rgba(229, 229, 229, 0.85);
border-color: rgba(255, 255, 255, 0.15);
}
-.btn-ghost:hover { background: rgba(255, 255, 255, 0.05); }
-.btn-ghost:disabled { opacity: 0.4; cursor: not-allowed; }
-.btn-sm { padding: 4px 10px; font-size: var(--text-xs); }
+.btn-ghost:hover {
+ background: rgba(255, 255, 255, 0.05);
+}
+.btn-ghost:disabled {
+ opacity: 0.4;
+ cursor: not-allowed;
+}
+.btn-sm {
+ padding: 4px 10px;
+ font-size: var(--text-xs);
+}
-.btn-primary:focus-visible, .btn-ghost:focus-visible {
+.btn-primary:focus-visible,
+.btn-ghost:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
@@ -314,7 +411,10 @@ html, body.studio-body {
opacity: 0;
transition: opacity 0.15s;
}
-.auth-blocker.visible { visibility: visible; opacity: 1; }
+.auth-blocker.visible {
+ visibility: visible;
+ opacity: 1;
+}
.auth-blocker-card {
background: #14141c;
border: 1px solid rgba(255, 255, 255, 0.1);
@@ -335,7 +435,9 @@ html, body.studio-body {
z-index: 90;
padding: var(--space-md);
}
-.modal-overlay[hidden] { display: none; }
+.modal-overlay[hidden] {
+ display: none;
+}
.modal {
background: #14141c;
border: 1px solid rgba(255, 255, 255, 0.08);
@@ -349,8 +451,16 @@ html, body.studio-body {
gap: var(--space-md);
position: relative;
}
-.modal h2 { margin: 0; font-family: var(--font-display); font-weight: 400; font-size: var(--text-lg); }
-.modal .muted { font-size: var(--text-sm); margin: 0; }
+.modal h2 {
+ margin: 0;
+ font-family: var(--font-display);
+ font-weight: 400;
+ font-size: var(--text-lg);
+}
+.modal .muted {
+ font-size: var(--text-sm);
+ margin: 0;
+}
.modal-close {
position: absolute;
top: 10px;
@@ -363,7 +473,9 @@ html, body.studio-body {
line-height: 1;
padding: 4px 8px;
}
-.modal-close:hover { color: #fff; }
+.modal-close:hover {
+ color: #fff;
+}
.embed-preview {
aspect-ratio: 1 / 1;
@@ -371,14 +483,19 @@ html, body.studio-body {
border-radius: var(--radius-md);
overflow: hidden;
}
-.embed-preview iframe { width: 100%; height: 100%; border: 0; }
+.embed-preview iframe {
+ width: 100%;
+ height: 100%;
+ border: 0;
+}
.copy-row {
display: flex;
gap: var(--space-xs);
align-items: stretch;
}
-.copy-row input, .copy-row textarea {
+.copy-row input,
+.copy-row textarea {
flex: 1;
background: #0a0a0a;
border: 1px solid rgba(255, 255, 255, 0.08);
@@ -390,7 +507,9 @@ html, body.studio-body {
resize: vertical;
min-height: 32px;
}
-.copy-row button { flex-shrink: 0; }
+.copy-row button {
+ flex-shrink: 0;
+}
.toast {
position: fixed;
@@ -406,10 +525,26 @@ html, body.studio-body {
z-index: 100;
animation: toast-in 0.18s;
}
-.toast[hidden] { display: none; }
-@keyframes toast-in { from { opacity: 0; transform: translate(-50%, 8px); } to { opacity: 1; transform: translateX(-50%); } }
+.toast[hidden] {
+ display: none;
+}
+@keyframes toast-in {
+ from {
+ opacity: 0;
+ transform: translate(-50%, 8px);
+ }
+ to {
+ opacity: 1;
+ transform: translateX(-50%);
+ }
+}
@media (prefers-reduced-motion: reduce) {
- .toast { animation: none; }
- .btn-primary, .btn-ghost { transition: none; }
+ .toast {
+ animation: none;
+ }
+ .btn-primary,
+ .btn-ghost {
+ transition: none;
+ }
}
diff --git a/public/studio/studio.js b/public/studio/studio.js
index ce0038258..6a6d3c80f 100644
--- a/public/studio/studio.js
+++ b/public/studio/studio.js
@@ -6,24 +6,62 @@
// Keep this list in sync with src/widget-types.js as new types light up.
const WIDGET_TYPES = {
- 'turntable': { label: 'Turntable Showcase', desc: 'Hero banner — auto-rotate, no UI, just the avatar.', status: 'ready', icon: '◎' },
- 'animation-gallery': { label: 'Animation Gallery', desc: 'Click through every clip on a rigged avatar.', status: 'pending', icon: '▶' },
- 'talking-agent': { label: 'Talking Agent', desc: 'Embodied chat — your agent on your site.', status: 'pending', icon: '◐' },
- 'passport': { label: 'ERC-8004 Passport', desc: 'On-chain identity card for any agent.', status: 'ready', icon: '◊' },
- 'hotspot-tour': { label: 'Hotspot Tour', desc: 'Annotated 3D scene with clickable POIs.', status: 'pending', icon: '⌖' },
+ turntable: {
+ label: 'Turntable Showcase',
+ desc: 'Hero banner — auto-rotate, no UI, just the avatar.',
+ status: 'ready',
+ icon: '◎',
+ },
+ 'animation-gallery': {
+ label: 'Animation Gallery',
+ desc: 'Click through every clip on a rigged avatar.',
+ status: 'pending',
+ icon: '▶',
+ },
+ 'talking-agent': {
+ label: 'Talking Agent',
+ desc: 'Embodied chat — your agent on your site.',
+ status: 'pending',
+ icon: '◐',
+ },
+ passport: {
+ label: 'ERC-8004 Passport',
+ desc: 'On-chain identity card for any agent.',
+ status: 'ready',
+ icon: '◊',
+ },
+ 'hotspot-tour': {
+ label: 'Hotspot Tour',
+ desc: 'Annotated 3D scene with clickable POIs.',
+ status: 'pending',
+ icon: '⌖',
+ },
};
const BRAND_DEFAULTS = Object.freeze({
- background: '#0a0a0a', accent: '#8b5cf6', caption: '',
- showControls: true, autoRotate: true, envPreset: 'neutral', cameraPosition: null,
+ background: '#0a0a0a',
+ accent: '#8b5cf6',
+ caption: '',
+ showControls: true,
+ autoRotate: true,
+ envPreset: 'neutral',
+ cameraPosition: null,
});
const TYPE_DEFAULTS = {
- 'turntable': { rotationSpeed: 0.5 },
+ turntable: { rotationSpeed: 0.5 },
'animation-gallery': { defaultClip: '', loopAll: false, showClipPicker: true },
- 'talking-agent': { greeting: 'Hi! What would you like to know?', brain: 'none', proxyURL: '' },
- 'passport': { chain: 'base-sepolia', agentId: null, wallet: null, showReputation: true, showRecentFeedback: true, layout: 'portrait', rotationSpeed: 0.6 },
- 'hotspot-tour': { hotspots: [] },
+ 'talking-agent': { greeting: 'Hi! What would you like to know?', brain: 'none', proxyURL: '' },
+ passport: {
+ chain: 'base-sepolia',
+ agentId: null,
+ wallet: null,
+ showReputation: true,
+ showRecentFeedback: true,
+ layout: 'portrait',
+ rotationSpeed: 0.6,
+ },
+ 'hotspot-tour': { hotspots: [] },
};
function defaultConfig(type) {
@@ -32,33 +70,33 @@ function defaultConfig(type) {
const $ = (sel, root = document) => root.querySelector(sel);
-const layoutEl = $('#studio-layout');
-const blockerEl = $('#auth-blocker');
+const layoutEl = $('#studio-layout');
+const blockerEl = $('#auth-blocker');
const signinLink = $('#signin-link');
-const formEl = $('#config-form');
-const errEl = $('#form-error');
+const formEl = $('#config-form');
+const errEl = $('#form-error');
const previewIfr = $('#preview-iframe');
-const previewSt = $('#preview-status');
+const previewSt = $('#preview-status');
const captureBtn = $('#capture-camera-btn');
-const saveBtn = $('#save-draft-btn');
-const generateBtn= $('#generate-btn');
-const toastEl = $('#toast');
+const saveBtn = $('#save-draft-btn');
+const generateBtn = $('#generate-btn');
+const toastEl = $('#toast');
const state = {
- user: null,
- avatars: [],
- avatarId: null,
- type: 'turntable',
- editingId: null,
- config: defaultConfig('turntable'),
- name: '',
- is_public: true,
+ user: null,
+ avatars: [],
+ avatarId: null,
+ type: 'turntable',
+ editingId: null,
+ config: defaultConfig('turntable'),
+ name: '',
+ is_public: true,
preselectedModel: null,
};
const params = new URLSearchParams(location.search);
-const editId = params.get('edit');
-const tplId = params.get('template');
+const editId = params.get('edit');
+const tplId = params.get('template');
const pickType = params.get('type');
const preModel = params.get('model');
@@ -96,7 +134,9 @@ async function fetchMe() {
if (!res.ok) return null;
const { user } = await res.json();
return user || null;
- } catch { return null; }
+ } catch {
+ return null;
+ }
}
async function loadAvatars() {
@@ -116,20 +156,24 @@ async function loadAvatars() {
async function loadForEdit(id) {
try {
- const res = await fetch(`/api/widgets/${encodeURIComponent(id)}`, { credentials: 'include' });
+ const res = await fetch(`/api/widgets/${encodeURIComponent(id)}`, {
+ credentials: 'include',
+ });
if (!res.ok) return;
const { widget } = await res.json();
state.editingId = widget.id;
- state.type = widget.type;
- state.avatarId = widget.avatar_id;
- state.name = widget.name || '';
- state.config = { ...defaultConfig(widget.type), ...(widget.config || {}) };
+ state.type = widget.type;
+ state.avatarId = widget.avatar_id;
+ state.name = widget.name || '';
+ state.config = { ...defaultConfig(widget.type), ...(widget.config || {}) };
state.is_public = widget.is_public;
hydrateForm();
renderTypeGrid();
renderAvatarList();
renderTypeFields();
- } catch (err) { console.warn('[studio] edit load failed', err); }
+ } catch (err) {
+ console.warn('[studio] edit load failed', err);
+ }
}
async function cloneTemplate(id) {
@@ -137,14 +181,16 @@ async function cloneTemplate(id) {
const res = await fetch(`/api/widgets/${encodeURIComponent(id)}`);
if (!res.ok) return;
const { widget } = await res.json();
- state.type = widget.type;
- state.config = { ...defaultConfig(widget.type), ...(widget.config || {}) };
- state.name = `Copy of ${widget.name}`;
+ state.type = widget.type;
+ state.config = { ...defaultConfig(widget.type), ...(widget.config || {}) };
+ state.name = `Copy of ${widget.name}`;
// avatarId stays unset — user must pick their own
hydrateForm();
renderTypeGrid();
renderTypeFields();
- } catch { /* ignore */ }
+ } catch {
+ /* ignore */
+ }
}
// ── rendering ────────────────────────────────────────────────────────────────
@@ -201,7 +247,13 @@ function renderTypeFields() {
return;
}
if (state.type === 'turntable') {
- wrap.appendChild(numberField('rotationSpeed', 'Rotation speed', state.config.rotationSpeed ?? 0.5, { min: 0, max: 10, step: 0.1 }));
+ wrap.appendChild(
+ numberField('rotationSpeed', 'Rotation speed', state.config.rotationSpeed ?? 0.5, {
+ min: 0,
+ max: 10,
+ step: 0.1,
+ }),
+ );
}
}
@@ -229,11 +281,21 @@ function selectAvatar(id) {
}
function selectByModelUrl(url) {
- const urlPath = (() => { try { return new URL(url, location.origin).pathname; } catch { return url; } })();
+ const urlPath = (() => {
+ try {
+ return new URL(url, location.origin).pathname;
+ } catch {
+ return url;
+ }
+ })();
const found = state.avatars.find((a) => {
if (!a.model_url) return false;
if (a.model_url === url) return true;
- try { return new URL(a.model_url).pathname === urlPath; } catch { return false; }
+ try {
+ return new URL(a.model_url).pathname === urlPath;
+ } catch {
+ return false;
+ }
});
if (found) selectAvatar(found.id);
}
@@ -271,9 +333,9 @@ function wireForm() {
function hydrateForm() {
for (const el of formEl.elements) {
if (!el.name) continue;
- if (el.name === 'name') el.value = state.name || '';
+ if (el.name === 'name') el.value = state.name || '';
else if (el.name === 'is_public') el.checked = !!state.is_public;
- else if (el.type === 'checkbox') el.checked = !!state.config[el.name];
+ else if (el.type === 'checkbox') el.checked = !!state.config[el.name];
else if (state.config[el.name] !== undefined) el.value = state.config[el.name];
}
}
@@ -281,7 +343,11 @@ function hydrateForm() {
function wireButtons() {
$('#signout-btn').addEventListener('click', async () => {
await fetch('/api/auth/logout', { method: 'POST', credentials: 'include' }).catch(() => {});
- try { localStorage.removeItem('3dagent:auth-hint'); } catch { /* ignore */ }
+ try {
+ localStorage.removeItem('3dagent:auth-hint');
+ } catch {
+ /* ignore */
+ }
location.href = '/';
});
@@ -293,7 +359,9 @@ function wireButtons() {
state.config.cameraPosition = [cam.position.x, cam.position.y, cam.position.z];
toast('Camera captured');
updatePreview(true);
- } catch { toast('Could not read camera'); }
+ } catch {
+ toast('Could not read camera');
+ }
});
saveBtn.addEventListener('click', () => save({ generate: false }));
@@ -328,14 +396,18 @@ function updatePreview(forceReload) {
previewSt.textContent = 'Avatar has no public URL — make it public/unlisted to preview';
return;
}
- previewSt.textContent = state.avatarId ? 'Live preview' : 'Preview only — pick an avatar from your library to save';
+ previewSt.textContent = state.avatarId
+ ? 'Live preview'
+ : 'Preview only — pick an avatar from your library to save';
if (!state.avatarId) captureBtn.disabled = false;
const camStr = Array.isArray(state.config.cameraPosition)
? `&cameraPosition=${state.config.cameraPosition.map((n) => n.toFixed(3)).join(',')}`
: '';
- const presetStr = state.config.envPreset && state.config.envPreset !== 'none'
- ? `&preset=${encodeURIComponent(state.config.envPreset)}` : '';
+ const presetStr =
+ state.config.envPreset && state.config.envPreset !== 'none'
+ ? `&preset=${encodeURIComponent(state.config.envPreset)}`
+ : '';
const src = `/?widget-preview=1#model=${encodeURIComponent(modelUrl)}&kiosk=true${camStr}${presetStr}`;
const key = src;
if (forceReload || key !== previewSrcKey) {
@@ -352,7 +424,9 @@ function postConfigToPreview() {
{ type: 'widget:config', config: { ...state.config } },
location.origin,
);
- } catch { /* iframe may not be ready yet — full reload covers it */ }
+ } catch {
+ /* iframe may not be ready yet — full reload covers it */
+ }
}
// ── save / generate ──────────────────────────────────────────────────────────
@@ -360,22 +434,32 @@ async function save({ generate }) {
errEl.hidden = true;
if (!state.name?.trim()) return showError('Name is required');
- if (!state.avatarId) return showError('Pick an avatar first');
+ if (!state.avatarId) return showError('Pick an avatar first');
if (!WIDGET_TYPES[state.type]) return showError('Pick a widget type');
const body = {
- type: state.type,
- name: state.name.trim(),
+ type: state.type,
+ name: state.name.trim(),
avatar_id: state.avatarId,
is_public: state.is_public,
- config: state.config,
+ config: state.config,
};
- const url = state.editingId ? `/api/widgets/${encodeURIComponent(state.editingId)}` : '/api/widgets';
+ const url = state.editingId
+ ? `/api/widgets/${encodeURIComponent(state.editingId)}`
+ : '/api/widgets';
const method = state.editingId ? 'PATCH' : 'POST';
- const sendBody = state.editingId ? { name: body.name, avatar_id: body.avatar_id, is_public: body.is_public, config: body.config } : body;
-
- saveBtn.disabled = true; generateBtn.disabled = true;
+ const sendBody = state.editingId
+ ? {
+ name: body.name,
+ avatar_id: body.avatar_id,
+ is_public: body.is_public,
+ config: body.config,
+ }
+ : body;
+
+ saveBtn.disabled = true;
+ generateBtn.disabled = true;
try {
const res = await fetch(url, {
method,
@@ -400,7 +484,8 @@ async function save({ generate }) {
} catch (err) {
showError(err.message);
} finally {
- saveBtn.disabled = false; generateBtn.disabled = false;
+ saveBtn.disabled = false;
+ generateBtn.disabled = false;
}
}
@@ -409,8 +494,10 @@ function openEmbedModal(widget) {
const shareUrl = `${origin}/w/${widget.id}`;
const embedUrl = `${origin}/#widget=${widget.id}&kiosk=true`;
$('#embed-share-url').value = shareUrl;
- $('#embed-iframe-snippet').value = `<iframe src="${embedUrl}" width="600" height="600" style="border:0;border-radius:12px" allow="autoplay; xr-spatial-tracking" loading="lazy"></iframe>`;
- $('#embed-script-snippet').value = `<script async src="${origin}/embed.js" data-widget="${widget.id}"></` + 'script>';
+ $('#embed-iframe-snippet').value =
+ `<iframe src="${embedUrl}" width="600" height="600" style="border:0;border-radius:12px" allow="autoplay; xr-spatial-tracking" loading="lazy"></iframe>`;
+ $('#embed-script-snippet').value =
+ `<script async src="${origin}/embed.js" data-widget="${widget.id}"></` + 'script>';
$('#embed-preview-iframe').src = embedUrl;
$('#embed-modal').hidden = false;
}
@@ -420,7 +507,11 @@ function copyFromSelector(sel, btn) {
if (!el) return;
el.select?.();
navigator.clipboard.writeText(el.value).then(
- () => { const o = btn.textContent; btn.textContent = 'Copied'; setTimeout(() => btn.textContent = o, 1200); },
+ () => {
+ const o = btn.textContent;
+ btn.textContent = 'Copied';
+ setTimeout(() => (btn.textContent = o), 1200);
+ },
() => toast('Copy failed'),
);
}
@@ -435,10 +526,15 @@ function toast(msg) {
toastEl.textContent = msg;
toastEl.hidden = false;
clearTimeout(toastTimer);
- toastTimer = setTimeout(() => toastEl.hidden = true, 1800);
+ toastTimer = setTimeout(() => (toastEl.hidden = true), 1800);
}
function escapeHtml(s) {
- return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' }[c]));
+ return String(s ?? '').replace(
+ /[&<>"']/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
+ );
+}
+function attr(s) {
+ return escapeHtml(s);
}
-function attr(s) { return escapeHtml(s); }
diff --git a/public/validation/REPORT_FORMAT.md b/public/validation/REPORT_FORMAT.md
index 0b1c2ce2d..079fcd562 100644
--- a/public/validation/REPORT_FORMAT.md
+++ b/public/validation/REPORT_FORMAT.md
@@ -8,69 +8,71 @@ An **agent validation report** is a JSON document that captures the results of t
```json
{
- "type": "agent-validation-report/0.1",
- "agentId": 1,
- "chainId": 84532,
- "validator": "0x1234567890123456789012345678901234567890",
- "ranAt": "2026-04-17T14:30:00Z",
- "suites": [
- {
- "name": "glb-schema",
- "status": "pass",
- "details": "GLB structure valid, all required chunks present"
- },
- {
- "name": "manifest-integrity",
- "status": "pass",
- "details": null
- },
- {
- "name": "skill-handlers-load",
- "status": "warn",
- "details": "Skill 'sing' references missing dependency @soundfont/npm"
- }
- ],
- "verdict": "pass",
- "notes": "Agent passes baseline validation. Minor warnings on external deps."
+ "type": "agent-validation-report/0.1",
+ "agentId": 1,
+ "chainId": 84532,
+ "validator": "0x1234567890123456789012345678901234567890",
+ "ranAt": "2026-04-17T14:30:00Z",
+ "suites": [
+ {
+ "name": "glb-schema",
+ "status": "pass",
+ "details": "GLB structure valid, all required chunks present"
+ },
+ {
+ "name": "manifest-integrity",
+ "status": "pass",
+ "details": null
+ },
+ {
+ "name": "skill-handlers-load",
+ "status": "warn",
+ "details": "Skill 'sing' references missing dependency @soundfont/npm"
+ }
+ ],
+ "verdict": "pass",
+ "notes": "Agent passes baseline validation. Minor warnings on external deps."
}
```
## Field Definitions
-| Field | Type | Required | Notes |
-|-------|------|----------|-------|
-| `type` | string | ✓ | Always `"agent-validation-report/0.1"`. Versioned for forward compatibility. |
-| `agentId` | number | ✓ | The agent token ID (from Identity Registry). |
-| `chainId` | number | ✓ | The blockchain chain ID (e.g., 84532 for Base Sepolia). |
-| `validator` | string | ✓ | The Ethereum address of the validator (0x-prefixed hex). |
-| `ranAt` | string (ISO 8601) | ✓ | UTC timestamp when tests ran. Format: `YYYY-MM-DDTHH:mm:ssZ`. |
-| `suites` | array | ✓ | Array of test suite results (see below). |
-| `verdict` | enum | ✓ | One of `"pass"`, `"warn"`, `"fail"`. Typically `"fail"` if any suite fails. |
-| `notes` | string | ✗ | Human-readable summary or recommendations (up to 500 chars). |
+| Field | Type | Required | Notes |
+| ----------- | ----------------- | -------- | ---------------------------------------------------------------------------- |
+| `type` | string | ✓ | Always `"agent-validation-report/0.1"`. Versioned for forward compatibility. |
+| `agentId` | number | ✓ | The agent token ID (from Identity Registry). |
+| `chainId` | number | ✓ | The blockchain chain ID (e.g., 84532 for Base Sepolia). |
+| `validator` | string | ✓ | The Ethereum address of the validator (0x-prefixed hex). |
+| `ranAt` | string (ISO 8601) | ✓ | UTC timestamp when tests ran. Format: `YYYY-MM-DDTHH:mm:ssZ`. |
+| `suites` | array | ✓ | Array of test suite results (see below). |
+| `verdict` | enum | ✓ | One of `"pass"`, `"warn"`, `"fail"`. Typically `"fail"` if any suite fails. |
+| `notes` | string | ✗ | Human-readable summary or recommendations (up to 500 chars). |
## Suite Object
Each suite in the `suites` array represents a category of validation tests:
-| Field | Type | Required | Notes |
-|-------|------|----------|-------|
-| `name` | string | ✓ | Unique identifier (e.g., `glb-schema`, `manifest-integrity`, `skill-handlers-load`). |
-| `status` | enum | ✓ | One of `"pass"`, `"warn"`, `"fail"`. |
-| `details` | string \| null | ✗ | Optional failure/warning message (up to 200 chars). Null if passing. |
+| Field | Type | Required | Notes |
+| --------- | -------------- | -------- | ------------------------------------------------------------------------------------ |
+| `name` | string | ✓ | Unique identifier (e.g., `glb-schema`, `manifest-integrity`, `skill-handlers-load`). |
+| `status` | enum | ✓ | One of `"pass"`, `"warn"`, `"fail"`. |
+| `details` | string \| null | ✗ | Optional failure/warning message (up to 200 chars). Null if passing. |
## Validation Rules
- **GLB Schema** (`glb-schema`): Confirms the GLB file structure is valid per glTF 2.0 spec.
- - Fails if: corrupted file, missing required chunks (glTF JSON, bin).
- - Warns if: unsupported extensions, non-standard materials.
+
+ - Fails if: corrupted file, missing required chunks (glTF JSON, bin).
+ - Warns if: unsupported extensions, non-standard materials.
- **Manifest Integrity** (`manifest-integrity`): Checks the agent's on-chain metadata JSON.
- - Fails if: `agentId`, `chainId`, or registry address mismatch.
- - Warns if: fields are missing or malformed.
+
+ - Fails if: `agentId`, `chainId`, or registry address mismatch.
+ - Warns if: fields are missing or malformed.
- **Skill Handlers Load** (`skill-handlers-load`): Verifies that all declared skills can initialize.
- - Fails if: skill `handlers.js` has syntax errors or required imports are unavailable.
- - Warns if: optional dependencies are missing but fallbacks exist.
+ - Fails if: skill `handlers.js` has syntax errors or required imports are unavailable.
+ - Warns if: optional dependencies are missing but fallbacks exist.
## Example
@@ -81,8 +83,8 @@ See [`example-report.json`](./example-report.json) for a complete, valid example
1. **Client-side hash**: The dashboard computes `keccak256(JSON.stringify(report))` to create the proof hash.
2. **IPFS pinning**: The full report JSON is uploaded to IPFS (via Pinata or `/api/erc8004/pin`).
3. **On-chain record**: The contract stores `(agentId, verdict, proofHash, proofURI, kind)`, where:
- - `proofHash` is the keccak256 hash.
- - `proofURI` is the IPFS URI (e.g., `ipfs://QmXyz...`).
+ - `proofHash` is the keccak256 hash.
+ - `proofURI` is the IPFS URI (e.g., `ipfs://QmXyz...`).
Validators can verify the hash by fetching the report from IPFS and recomputing the hash locally.
diff --git a/public/validation/example-report.json b/public/validation/example-report.json
index ec44a49d5..bbbb2b7d3 100644
--- a/public/validation/example-report.json
+++ b/public/validation/example-report.json
@@ -1,26 +1,26 @@
{
- "type": "agent-validation-report/0.1",
- "agentId": 42,
- "chainId": 84532,
- "validator": "0x1234567890123456789012345678901234567890",
- "ranAt": "2026-04-17T14:30:00Z",
- "suites": [
- {
- "name": "glb-schema",
- "status": "pass",
- "details": null
- },
- {
- "name": "manifest-integrity",
- "status": "pass",
- "details": null
- },
- {
- "name": "skill-handlers-load",
- "status": "pass",
- "details": null
- }
- ],
- "verdict": "pass",
- "notes": "Agent passes baseline validation. Ready for deployment."
+ "type": "agent-validation-report/0.1",
+ "agentId": 42,
+ "chainId": 84532,
+ "validator": "0x1234567890123456789012345678901234567890",
+ "ranAt": "2026-04-17T14:30:00Z",
+ "suites": [
+ {
+ "name": "glb-schema",
+ "status": "pass",
+ "details": null
+ },
+ {
+ "name": "manifest-integrity",
+ "status": "pass",
+ "details": null
+ },
+ {
+ "name": "skill-handlers-load",
+ "status": "pass",
+ "details": null
+ }
+ ],
+ "verdict": "pass",
+ "notes": "Agent passes baseline validation. Ready for deployment."
}
diff --git a/public/validation/index.html b/public/validation/index.html
index c50a9b343..fa8053892 100644
--- a/public/validation/index.html
+++ b/public/validation/index.html
@@ -18,7 +18,12 @@
box-sizing: border-box;
}
body {
- font: 15px/1.55 -apple-system, system-ui, Segoe UI, Roboto, sans-serif;
+ font:
+ 15px/1.55 -apple-system,
+ system-ui,
+ Segoe UI,
+ Roboto,
+ sans-serif;
color: #eee;
margin: 0;
background: var(--bg);
@@ -115,7 +120,11 @@
}
textarea {
resize: vertical;
- font-family: ui-monospace, SF Mono, Menlo, monospace;
+ font-family:
+ ui-monospace,
+ SF Mono,
+ Menlo,
+ monospace;
font-size: 13px;
}
.btn {
@@ -225,7 +234,11 @@
}
.record-meta-value {
color: #ccc;
- font-family: ui-monospace, SF Mono, Menlo, monospace;
+ font-family:
+ ui-monospace,
+ SF Mono,
+ Menlo,
+ monospace;
font-size: 13px;
word-break: break-all;
}
@@ -371,7 +384,11 @@
max-height: 200px;
}
code {
- font-family: ui-monospace, SF Mono, Menlo, monospace;
+ font-family:
+ ui-monospace,
+ SF Mono,
+ Menlo,
+ monospace;
}
</style>
</head>
@@ -387,7 +404,9 @@
<main id="main">
<h1>Validation Records</h1>
- <p class="sub">Browse validation reports for this agent to verify trust and integrity.</p>
+ <p class="sub">
+ Browse validation reports for this agent to verify trust and integrity.
+ </p>
<div class="toolbar">
<input
@@ -426,13 +445,19 @@
📄 Click to select or drag a JSON report file
</label>
</div>
- <div id="file-status" style="font-size: 12px; color: #888; margin-top: 8px"></div>
+ <div
+ id="file-status"
+ style="font-size: 12px; color: #888; margin-top: 8px"
+ ></div>
</div>
<div id="preview-section" style="display: none" class="section">
<div class="section-title">Preview</div>
<pre id="preview-json"></pre>
- <div id="preview-error" style="color: #ffb3b3; font-size: 12px; margin-top: 8px"></div>
+ <div
+ id="preview-error"
+ style="color: #ffb3b3; font-size: 12px; margin-top: 8px"
+ ></div>
</div>
<div id="hash-section" style="display: none" class="form-group">
@@ -441,7 +466,14 @@
type="text"
id="report-hash"
readonly
- style="font-family: ui-monospace, SF Mono, Menlo, monospace; font-size: 12px"
+ style="
+ font-family:
+ ui-monospace,
+ SF Mono,
+ Menlo,
+ monospace;
+ font-size: 12px;
+ "
/>
<div style="font-size: 12px; color: #888; margin-top: 6px">
Computed via keccak256(JSON.stringify(report))
diff --git a/public/widgets-gallery/gallery.css b/public/widgets-gallery/gallery.css
index de85b4c84..3a38b91bb 100644
--- a/public/widgets-gallery/gallery.css
+++ b/public/widgets-gallery/gallery.css
@@ -1,6 +1,7 @@
/* Widget gallery — matches root style.css tokens. No new design system. */
-html, body.gallery-body {
+html,
+body.gallery-body {
overflow: auto;
height: auto;
min-height: 100vh;
@@ -11,8 +12,8 @@ html, body.gallery-body {
align-items: center;
justify-content: space-between;
padding: var(--space-md) var(--space-lg);
- border-bottom: 1px solid rgba(255,255,255,0.06);
- background: rgba(0,0,0,0.5);
+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);
+ background: rgba(0, 0, 0, 0.5);
backdrop-filter: blur(8px);
position: sticky;
top: 0;
@@ -37,16 +38,18 @@ html, body.gallery-body {
font-size: var(--text-sm);
}
.gallery-header .features-nav a {
- color: rgba(229,229,229,0.65);
+ color: rgba(229, 229, 229, 0.65);
text-decoration: none;
padding: var(--space-xs) var(--space-sm);
border-radius: var(--radius-md);
- transition: color 0.15s, background 0.15s;
+ transition:
+ color 0.15s,
+ background 0.15s;
}
.gallery-header .features-nav a:hover,
.gallery-header .features-nav a.active {
color: #fff;
- background: rgba(255,255,255,0.06);
+ background: rgba(255, 255, 255, 0.06);
}
.gallery-main {
@@ -85,7 +88,7 @@ html, body.gallery-body {
max-width: 60ch;
margin: 0;
font-size: var(--text-lg);
- color: rgba(229,229,229,0.7);
+ color: rgba(229, 229, 229, 0.7);
line-height: var(--leading-normal);
}
.cta-row {
@@ -108,7 +111,10 @@ html, body.gallery-body {
text-decoration: none;
border: 1px solid transparent;
cursor: pointer;
- transition: transform 0.15s, background 0.15s, border-color 0.15s;
+ transition:
+ transform 0.15s,
+ background 0.15s,
+ border-color 0.15s;
}
.btn:focus-visible {
outline: 2px solid var(--accent);
@@ -118,13 +124,18 @@ html, body.gallery-body {
background: var(--accent);
color: #fff;
}
-.btn-primary:hover { transform: translateY(-1px); background: #7c3aed; }
+.btn-primary:hover {
+ transform: translateY(-1px);
+ background: #7c3aed;
+}
.btn-ghost {
background: transparent;
- color: rgba(229,229,229,0.85);
- border-color: rgba(255,255,255,0.18);
+ color: rgba(229, 229, 229, 0.85);
+ border-color: rgba(255, 255, 255, 0.18);
+}
+.btn-ghost:hover {
+ background: rgba(255, 255, 255, 0.06);
}
-.btn-ghost:hover { background: rgba(255,255,255,0.06); }
.gallery-grid {
display: flex;
@@ -132,7 +143,7 @@ html, body.gallery-body {
gap: var(--space-2xl);
}
.gallery-grid .loading {
- color: rgba(229,229,229,0.55);
+ color: rgba(229, 229, 229, 0.55);
text-align: center;
}
@@ -142,12 +153,14 @@ html, body.gallery-body {
gap: var(--space-xl);
align-items: start;
padding: var(--space-xl);
- background: rgba(255,255,255,0.025);
- border: 1px solid rgba(255,255,255,0.06);
+ background: rgba(255, 255, 255, 0.025);
+ border: 1px solid rgba(255, 255, 255, 0.06);
border-radius: var(--radius-lg);
}
@media (max-width: 820px) {
- .showcase { grid-template-columns: 1fr; }
+ .showcase {
+ grid-template-columns: 1fr;
+ }
}
.showcase-frame {
@@ -188,24 +201,26 @@ html, body.gallery-body {
}
.showcase-meta p {
margin: 0;
- color: rgba(229,229,229,0.7);
+ color: rgba(229, 229, 229, 0.7);
line-height: var(--leading-normal);
}
.snippet {
position: relative;
background: #0a0a0a;
- border: 1px solid rgba(255,255,255,0.08);
+ border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: var(--radius-md);
padding: var(--space-sm);
font-family: var(--font-mono);
font-size: var(--text-sm);
- color: rgba(229,229,229,0.85);
+ color: rgba(229, 229, 229, 0.85);
white-space: pre-wrap;
word-break: break-all;
overflow-x: auto;
}
-.snippet code { display: block; }
+.snippet code {
+ display: block;
+}
.snippet-row {
display: flex;
gap: var(--space-xs);
@@ -218,8 +233,8 @@ html, body.gallery-body {
min-width: 120px;
padding: var(--space-xs) var(--space-sm);
font-size: var(--text-sm);
- background: rgba(255,255,255,0.05);
- border: 1px solid rgba(255,255,255,0.1);
+ background: rgba(255, 255, 255, 0.05);
+ border: 1px solid rgba(255, 255, 255, 0.1);
color: #e5e5e5;
border-radius: var(--radius-md);
cursor: pointer;
@@ -229,28 +244,33 @@ html, body.gallery-body {
transition: background 0.15s;
}
.snippet-row button:hover,
-.snippet-row a:hover { background: rgba(255,255,255,0.1); }
+.snippet-row a:hover {
+ background: rgba(255, 255, 255, 0.1);
+}
.snippet-row button:focus-visible,
.snippet-row a:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
-.snippet-row .copied { background: var(--accent-soft); border-color: var(--accent); }
+.snippet-row .copied {
+ background: var(--accent-soft);
+ border-color: var(--accent);
+}
.error-state {
padding: var(--space-md);
- background: rgba(255,80,80,0.06);
- border: 1px solid rgba(255,80,80,0.2);
+ background: rgba(255, 80, 80, 0.06);
+ border: 1px solid rgba(255, 80, 80, 0.2);
border-radius: var(--radius-md);
- color: rgba(255,200,200,0.9);
+ color: rgba(255, 200, 200, 0.9);
font-size: var(--text-sm);
}
.gallery-cta {
text-align: center;
padding: var(--space-2xl) var(--space-lg);
- background: rgba(139,92,246,0.06);
- border: 1px solid rgba(139,92,246,0.15);
+ background: rgba(139, 92, 246, 0.06);
+ border: 1px solid rgba(139, 92, 246, 0.15);
border-radius: var(--radius-lg);
display: flex;
flex-direction: column;
@@ -263,23 +283,34 @@ html, body.gallery-body {
font-size: var(--text-xl);
font-weight: 400;
}
-.gallery-cta p { margin: 0; color: rgba(229,229,229,0.7); }
+.gallery-cta p {
+ margin: 0;
+ color: rgba(229, 229, 229, 0.7);
+}
.gallery-footer {
padding: var(--space-lg);
text-align: center;
- color: rgba(229,229,229,0.5);
+ color: rgba(229, 229, 229, 0.5);
font-size: var(--text-sm);
- border-top: 1px solid rgba(255,255,255,0.06);
+ border-top: 1px solid rgba(255, 255, 255, 0.06);
}
.gallery-footer a {
- color: rgba(229,229,229,0.7);
+ color: rgba(229, 229, 229, 0.7);
text-decoration: none;
margin: 0 var(--space-xs);
}
-.gallery-footer a:hover { color: #fff; }
+.gallery-footer a:hover {
+ color: #fff;
+}
@media (prefers-reduced-motion: reduce) {
- .btn, .snippet-row button, .snippet-row a { transition: none; }
- .btn-primary:hover { transform: none; }
+ .btn,
+ .snippet-row button,
+ .snippet-row a {
+ transition: none;
+ }
+ .btn-primary:hover {
+ transform: none;
+ }
}
diff --git a/public/widgets-gallery/gallery.js b/public/widgets-gallery/gallery.js
index 8b376d46d..8734b85b4 100644
--- a/public/widgets-gallery/gallery.js
+++ b/public/widgets-gallery/gallery.js
@@ -33,8 +33,8 @@ function renderShowcase(w) {
root.setAttribute('aria-labelledby', `sc-${w.id}-title`);
const widgetUrl = `${ORIGIN}/#widget=${encodeURIComponent(w.id)}&kiosk=true`;
- const pageUrl = `${ORIGIN}/w/${encodeURIComponent(w.id)}`;
- const snippet = `<iframe src="${widgetUrl}" width="${w.width}" height="${w.height}" style="border:0;border-radius:12px;max-width:100%" allow="autoplay; xr-spatial-tracking; clipboard-write" loading="lazy"></iframe>`;
+ const pageUrl = `${ORIGIN}/w/${encodeURIComponent(w.id)}`;
+ const snippet = `<iframe src="${widgetUrl}" width="${w.width}" height="${w.height}" style="border:0;border-radius:12px;max-width:100%" allow="autoplay; xr-spatial-tracking; clipboard-write" loading="lazy"></iframe>`;
const frame = document.createElement('div');
frame.className = 'showcase-frame';
@@ -113,7 +113,9 @@ async function copy(text, btn) {
ta.style.opacity = '0';
document.body.appendChild(ta);
ta.select();
- try { document.execCommand('copy'); } catch {}
+ try {
+ document.execCommand('copy');
+ } catch {}
ta.remove();
}
const orig = btn.textContent;
diff --git a/public/widgets-gallery/index.html b/public/widgets-gallery/index.html
index 9e494d317..7fc6aa717 100644
--- a/public/widgets-gallery/index.html
+++ b/public/widgets-gallery/index.html
@@ -1,65 +1,83 @@
<!doctype html>
<html lang="en">
-<head>
- <meta charset="utf-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <title>Widgets — 3D Agent</title>
- <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
- <meta name="description" content="Embeddable 3D, no code. Drop a widget into any site, blog, or Notion doc.">
- <meta name="theme-color" content="#0a0a0a">
+ <head>
+ <meta charset="utf-8" />
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+ <title>Widgets — 3D Agent</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
+ <meta
+ name="description"
+ content="Embeddable 3D, no code. Drop a widget into any site, blog, or Notion doc."
+ />
+ <meta name="theme-color" content="#0a0a0a" />
- <meta property="og:type" content="website">
- <meta property="og:site_name" content="3D Agent">
- <meta property="og:title" content="3D Agent — Widgets">
- <meta property="og:description" content="Embeddable 3D, no code. Drop a widget into any site, blog, or Notion doc.">
- <meta property="og:url" content="https://3dagent.vercel.app/widgets">
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="3D Agent" />
+ <meta property="og:title" content="3D Agent — Widgets" />
+ <meta
+ property="og:description"
+ content="Embeddable 3D, no code. Drop a widget into any site, blog, or Notion doc."
+ />
+ <meta property="og:url" content="https://3dagent.vercel.app/widgets" />
- <link rel="canonical" href="https://3dagent.vercel.app/widgets">
- <link rel="shortcut icon" href="/favicon.ico">
- <link rel="preconnect" href="https://fonts.googleapis.com">
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
- <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap" rel="stylesheet">
- <link rel="stylesheet" href="/style.css">
- <link rel="stylesheet" href="/widgets-gallery/gallery.css">
-</head>
-<body class="gallery-body">
- <header class="gallery-header">
- <h1><a href="/"><span class="wordmark-dot" aria-hidden="true"></span>3D Agent</a></h1>
- <nav class="features-nav">
- <a href="/">Viewer</a>
- <a href="/features">Features</a>
- <a href="/widgets" class="active" aria-current="page">Widgets</a>
- <a href="/docs/widgets">Docs</a>
- <a href="/dashboard" class="nav-dashboard">Dashboard</a>
- </nav>
- </header>
+ <link rel="canonical" href="https://3dagent.vercel.app/widgets" />
+ <link rel="shortcut icon" href="/favicon.ico" />
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
+ <link
+ href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap"
+ rel="stylesheet"
+ />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/widgets-gallery/gallery.css" />
+ </head>
+ <body class="gallery-body">
+ <header class="gallery-header">
+ <h1>
+ <a href="/"><span class="wordmark-dot" aria-hidden="true"></span>3D Agent</a>
+ </h1>
+ <nav class="features-nav">
+ <a href="/">Viewer</a>
+ <a href="/features">Features</a>
+ <a href="/widgets" class="active" aria-current="page">Widgets</a>
+ <a href="/docs/widgets">Docs</a>
+ <a href="/dashboard" class="nav-dashboard">Dashboard</a>
+ </nav>
+ </header>
- <main class="gallery-main" id="gallery-main">
- <section class="gallery-hero">
- <p class="eyebrow">Widget Studio</p>
- <h2>Embeddable 3D, no code.</h2>
- <p class="lede">Drop a 3D agent — turntable, talking head, on-chain passport, or guided tour — into any site, blog, or Notion doc with one line of HTML.</p>
- <div class="cta-row">
- <a class="btn btn-primary" href="/studio">Create yours — it's free</a>
- <a class="btn btn-ghost" href="/docs/widgets">Read the docs</a>
- </div>
- </section>
+ <main class="gallery-main" id="gallery-main">
+ <section class="gallery-hero">
+ <p class="eyebrow">Widget Studio</p>
+ <h2>Embeddable 3D, no code.</h2>
+ <p class="lede">
+ Drop a 3D agent — turntable, talking head, on-chain passport, or guided tour —
+ into any site, blog, or Notion doc with one line of HTML.
+ </p>
+ <div class="cta-row">
+ <a class="btn btn-primary" href="/studio">Create yours — it's free</a>
+ <a class="btn btn-ghost" href="/docs/widgets">Read the docs</a>
+ </div>
+ </section>
- <section class="gallery-grid" id="gallery-grid" aria-busy="true">
- <p class="loading">Loading showcase widgets…</p>
- </section>
+ <section class="gallery-grid" id="gallery-grid" aria-busy="true">
+ <p class="loading">Loading showcase widgets…</p>
+ </section>
- <section class="gallery-cta">
- <h3>Make your own.</h3>
- <p>Pick an avatar, pick a widget type, paste the snippet. Free for personal use.</p>
- <a class="btn btn-primary" href="/studio">Open the Studio</a>
- </section>
- </main>
+ <section class="gallery-cta">
+ <h3>Make your own.</h3>
+ <p>Pick an avatar, pick a widget type, paste the snippet. Free for personal use.</p>
+ <a class="btn btn-primary" href="/studio">Open the Studio</a>
+ </section>
+ </main>
- <footer class="gallery-footer">
- <p>3D Agent · <a href="/">Viewer</a> · <a href="/widgets">Widgets</a> · <a href="/docs/widgets">Docs</a> · <a href="https://github.com/nirholas/3D">GitHub</a></p>
- </footer>
+ <footer class="gallery-footer">
+ <p>
+ 3D Agent · <a href="/">Viewer</a> · <a href="/widgets">Widgets</a> ·
+ <a href="/docs/widgets">Docs</a> ·
+ <a href="https://github.com/nirholas/3D">GitHub</a>
+ </p>
+ </footer>
- <script type="module" src="/widgets-gallery/gallery.js"></script>
-</body>
+ <script type="module" src="/widgets-gallery/gallery.js"></script>
+ </body>
</html>
diff --git a/scripts/apply-schema.mjs b/scripts/apply-schema.mjs
index 62c5da449..9db5a7cb4 100644
--- a/scripts/apply-schema.mjs
+++ b/scripts/apply-schema.mjs
@@ -13,7 +13,11 @@ const root = resolve(__dirname, '..');
function loadEnvFile(path) {
let raw;
- try { raw = readFileSync(path, 'utf8'); } catch { return; }
+ try {
+ raw = readFileSync(path, 'utf8');
+ } catch {
+ return;
+ }
for (const line of raw.split('\n')) {
const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*?)\s*$/i);
if (!m) continue;
diff --git a/scripts/download-animations.mjs b/scripts/download-animations.mjs
index 91f230cd6..19aece21e 100644
--- a/scripts/download-animations.mjs
+++ b/scripts/download-animations.mjs
@@ -41,11 +41,11 @@ async function download(url, dest) {
function parseGlbAnimations(buf) {
// GLB header: magic(4) + version(4) + length(4)
const magic = buf.readUInt32LE(0);
- if (magic !== 0x46546C67) return []; // 'glTF'
+ if (magic !== 0x46546c67) return []; // 'glTF'
const chunkLength = buf.readUInt32LE(12);
const chunkType = buf.readUInt32LE(16);
- if (chunkType !== 0x4E4F534A) return []; // 'JSON'
+ if (chunkType !== 0x4e4f534a) return []; // 'JSON'
const jsonStr = buf.slice(20, 20 + chunkLength).toString('utf8');
const gltf = JSON.parse(jsonStr);
@@ -99,14 +99,27 @@ async function main() {
const soldier = downloaded.find((d) => d.name === 'Soldier');
const ICONS = {
- idle: '🧍', Idle: '🧍',
- Walking: '🚶', Walk: '🚶', walking: '🚶',
- Running: '🏃', Run: '🏃', running: '🏃',
- Wave: '👋', Waving: '👋', waving: '👋',
- Dance: '💃', Dancing: '💃', dancing: '💃',
- Sitting: '🪑', sitting: '🪑',
- Jump: '🦘', Jumping: '🦘', jumping: '🦘',
- Punch: '👊', punching: '👊',
+ idle: '🧍',
+ Idle: '🧍',
+ Walking: '🚶',
+ Walk: '🚶',
+ walking: '🚶',
+ Running: '🏃',
+ Run: '🏃',
+ running: '🏃',
+ Wave: '👋',
+ Waving: '👋',
+ waving: '👋',
+ Dance: '💃',
+ Dancing: '💃',
+ dancing: '💃',
+ Sitting: '🪑',
+ sitting: '🪑',
+ Jump: '🦘',
+ Jumping: '🦘',
+ jumping: '🦘',
+ Punch: '👊',
+ punching: '👊',
Standing: '🧍',
ThumbsUp: '👍',
Yes: '✅',
@@ -115,7 +128,15 @@ async function main() {
};
const LOOPS = new Set([
- 'Idle', 'Walking', 'Running', 'Dance', 'Sitting', 'Standing', 'idle', 'walking', 'running',
+ 'Idle',
+ 'Walking',
+ 'Running',
+ 'Dance',
+ 'Sitting',
+ 'Standing',
+ 'idle',
+ 'walking',
+ 'running',
]);
const manifest = [];
@@ -146,7 +167,9 @@ async function main() {
const czInfo = parseGlbAnimations(czBuf);
console.log(`\n🧬 cz.glb skeleton: ${czInfo.jointCount} joints`);
console.log(` Bones: ${czInfo.boneNames.join(', ')}`);
- console.log(` Existing animations: ${czInfo.anims.length ? czInfo.anims.join(', ') : '(none)'}`);
+ console.log(
+ ` Existing animations: ${czInfo.anims.length ? czInfo.anims.join(', ') : '(none)'}`,
+ );
}
// ── Summary ──────────────────────────────────────────────────────────────
diff --git a/scripts/download-mixamo-animations.js b/scripts/download-mixamo-animations.js
index 0ffb8999d..816de514e 100644
--- a/scripts/download-mixamo-animations.js
+++ b/scripts/download-mixamo-animations.js
@@ -13,10 +13,10 @@
(async function downloadMixamoAnimations() {
const ANIMATIONS = [
- { name: 'Idle', query: 'Breathing Idle' },
+ { name: 'Idle', query: 'Breathing Idle' },
{ name: 'Walking', query: 'Walking' },
{ name: 'Running', query: 'Running' },
- { name: 'Waving', query: 'Waving' },
+ { name: 'Waving', query: 'Waving' },
{ name: 'Dancing', query: 'Hip Hop Dancing' },
{ name: 'Sitting', query: 'Sitting' },
{ name: 'Jumping', query: 'Jump' },
@@ -25,8 +25,8 @@
// Grab auth token from the page
const token = document.cookie
.split(';')
- .map(c => c.trim())
- .find(c => c.startsWith('access_token='));
+ .map((c) => c.trim())
+ .find((c) => c.startsWith('access_token='));
// Try bearer token from localStorage or existing fetch headers
let bearer = null;
@@ -37,14 +37,17 @@
// Fallback: intercept from meta or global state
if (!bearer) {
// Mixamo stores auth in window state
- const state = window.__NEXT_DATA__?.props?.pageProps?.accessToken
- || document.querySelector('meta[name="csrf-token"]')?.content;
+ const state =
+ window.__NEXT_DATA__?.props?.pageProps?.accessToken ||
+ document.querySelector('meta[name="csrf-token"]')?.content;
if (state) bearer = state;
}
if (!bearer) {
console.error('❌ Could not find auth token. Make sure you are signed in to Mixamo.');
- console.log('💡 Try: copy a Bearer token from any Network request to mixamo.com and set it manually:');
+ console.log(
+ '💡 Try: copy a Bearer token from any Network request to mixamo.com and set it manually:',
+ );
console.log(' window.__MIXAMO_TOKEN = "your-token-here"');
console.log(' Then re-run this script.');
if (window.__MIXAMO_TOKEN) {
@@ -55,9 +58,9 @@
}
const headers = {
- 'Accept': 'application/json',
+ Accept: 'application/json',
'Content-Type': 'application/json',
- 'Authorization': `Bearer ${bearer}`,
+ Authorization: `Bearer ${bearer}`,
'X-Api-Key': 'mixamo2',
};
@@ -70,7 +73,10 @@
if (!characterId) {
// Search for Y Bot as fallback
- const searchRes = await fetch('https://www.mixamo.com/api/v1/characters?page=1&limit=1&query=y+bot', { headers });
+ const searchRes = await fetch(
+ 'https://www.mixamo.com/api/v1/characters?page=1&limit=1&query=y+bot',
+ { headers },
+ );
const searchData = await searchRes.json();
characterId = searchData.results?.[0]?.id;
}
@@ -91,11 +97,13 @@
// Search for the animation
const searchRes = await fetch(
`https://www.mixamo.com/api/v1/products?page=1&limit=10&query=${encodeURIComponent(anim.query)}&type=Motion`,
- { headers }
+ { headers },
);
if (!searchRes.ok) {
- console.error(` ❌ Search failed (${searchRes.status}). Token may be expired — refresh the page and try again.`);
+ console.error(
+ ` ❌ Search failed (${searchRes.status}). Token may be expired — refresh the page and try again.`,
+ );
return;
}
@@ -130,11 +138,11 @@
console.log(` ⏳ Processing...`);
let downloadUrl = null;
for (let i = 0; i < 30; i++) {
- await new Promise(r => setTimeout(r, 2000));
+ await new Promise((r) => setTimeout(r, 2000));
const statusRes = await fetch(
`https://www.mixamo.com/api/v1/animations/export/${product.id}?character_id=${characterId}`,
- { headers }
+ { headers },
);
const statusData = await statusRes.json();
@@ -165,13 +173,14 @@
console.log(` ✅ ${anim.name}.fbx downloaded!`);
// Small delay between downloads to be polite
- await new Promise(r => setTimeout(r, 1500));
-
+ await new Promise((r) => setTimeout(r, 1500));
} catch (err) {
console.error(` ❌ Error with "${anim.query}":`, err.message);
}
}
console.log('\n🎉 Done! Convert with:');
- console.log(' python3 scripts/convert-fbx-to-glb.py ~/Downloads/Idle.fbx ~/Downloads/Walking.fbx ~/Downloads/Running.fbx ~/Downloads/Waving.fbx ~/Downloads/Dancing.fbx ~/Downloads/Sitting.fbx ~/Downloads/Jumping.fbx');
+ console.log(
+ ' python3 scripts/convert-fbx-to-glb.py ~/Downloads/Idle.fbx ~/Downloads/Walking.fbx ~/Downloads/Running.fbx ~/Downloads/Waving.fbx ~/Downloads/Dancing.fbx ~/Downloads/Sitting.fbx ~/Downloads/Jumping.fbx',
+ );
})();
diff --git a/sdk/CHANGELOG.md b/sdk/CHANGELOG.md
index 69fc3d656..325670475 100644
--- a/sdk/CHANGELOG.md
+++ b/sdk/CHANGELOG.md
@@ -9,6 +9,7 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
Initial public release.
### Added
+
- `AgentKit` — one-call class to ship an ERC-8004 agent (panel + registration + manifests).
- `AgentPanel` — standalone floating chat UI with voice I/O. Bring your own `onMessage` handler.
- ERC-8004 wallet + IPFS + on-chain registration flow via `registerAgent()`.
diff --git a/sdk/README.md b/sdk/README.md
index e2d179024..f27f84473 100644
--- a/sdk/README.md
+++ b/sdk/README.md
@@ -17,10 +17,10 @@ import { AgentKit } from '@nirholas/agent-kit';
import '@nirholas/agent-kit/styles';
const agent = new AgentKit({
- name: 'My Agent',
- description: 'Does cool stuff',
- endpoint: 'https://myapp.com',
- onMessage: async (text) => `You said: ${text}`,
+ name: 'My Agent',
+ description: 'Does cool stuff',
+ endpoint: 'https://myapp.com',
+ onMessage: async (text) => `You said: ${text}`,
});
agent.mount(document.body);
@@ -32,9 +32,9 @@ That's it — you now have a floating chat panel with voice I/O in the bottom-le
```js
await agent.register({
- ipfsToken: 'your-web3storage-token',
- imageFile: someFile, // optional
- onStatus: (msg) => console.log(msg),
+ ipfsToken: 'your-web3storage-token',
+ imageFile: someFile, // optional
+ onStatus: (msg) => console.log(msg),
});
```
@@ -44,11 +44,12 @@ Needs MetaMask (or any injected wallet) and a [web3.storage](https://web3.storag
```js
const { agentRegistration, agentCard, aiPlugin } = agent.manifests({
- openapiUrl: 'https://myapp.com/.well-known/openapi.yaml',
+ openapiUrl: 'https://myapp.com/.well-known/openapi.yaml',
});
```
Serve these JSON documents from:
+
- `/.well-known/agent-registration.json` — ERC-8004 discovery
- `/.well-known/agent-card.json` — A2A protocol
- `/.well-known/ai-plugin.json` — OpenAI plugin manifest
@@ -57,19 +58,19 @@ Serve these JSON documents from:
### `new AgentKit(options)`
-| Option | Type | Description |
-|---|---|---|
-| `name` | `string` **(required)** | Agent display name |
-| `endpoint` | `string` **(required)** | Your agent's public URL |
-| `description` | `string` | What the agent does |
-| `image` | `string` | Public URL to logo/avatar |
-| `version` | `string` | Semver version (default: `1.0.0`) |
-| `org` | `string` | Organization name for `agent-card.json` |
-| `skills` | `Array` | A2A skill definitions |
-| `services` | `Array` | Extra service entries (A2A, MCP endpoints) |
-| `onMessage` | `async (text) => string` | Your response handler |
-| `welcome` | `string` | Panel welcome message |
-| `voice` | `boolean` | Enable TTS on replies (default: `true`) |
+| Option | Type | Description |
+| ------------- | ------------------------ | ------------------------------------------ |
+| `name` | `string` **(required)** | Agent display name |
+| `endpoint` | `string` **(required)** | Your agent's public URL |
+| `description` | `string` | What the agent does |
+| `image` | `string` | Public URL to logo/avatar |
+| `version` | `string` | Semver version (default: `1.0.0`) |
+| `org` | `string` | Organization name for `agent-card.json` |
+| `skills` | `Array` | A2A skill definitions |
+| `services` | `Array` | Extra service entries (A2A, MCP endpoints) |
+| `onMessage` | `async (text) => string` | Your response handler |
+| `welcome` | `string` | Panel welcome message |
+| `voice` | `boolean` | Enable TTS on replies (default: `true`) |
### Methods
@@ -86,16 +87,16 @@ For direct control:
```js
import {
- AgentPanel,
- connectWallet,
- registerAgent,
- pinToIPFS,
- buildRegistrationJSON,
- agentRegistration,
- agentCard,
- aiPlugin,
- IDENTITY_REGISTRY_ABI,
- REGISTRY_DEPLOYMENTS,
+ AgentPanel,
+ connectWallet,
+ registerAgent,
+ pinToIPFS,
+ buildRegistrationJSON,
+ agentRegistration,
+ agentCard,
+ aiPlugin,
+ IDENTITY_REGISTRY_ABI,
+ REGISTRY_DEPLOYMENTS,
} from '@nirholas/agent-kit';
```
@@ -105,8 +106,8 @@ Before calling `register()`, set your Identity Registry address in `sdk/src/erc8
```js
export const REGISTRY_DEPLOYMENTS = {
- 8453: { identityRegistry: '0xYourBaseMainnetAddress' },
- 84532: { identityRegistry: '0xYourBaseSepoliaAddress' },
+ 8453: { identityRegistry: '0xYourBaseMainnetAddress' },
+ 84532: { identityRegistry: '0xYourBaseSepoliaAddress' },
};
```
diff --git a/sdk/example/index.html b/sdk/example/index.html
index 11b30ba1d..40e63ea8c 100644
--- a/sdk/example/index.html
+++ b/sdk/example/index.html
@@ -1,131 +1,150 @@
-<!DOCTYPE html>
+<!doctype html>
<html lang="en">
-<head>
- <meta charset="UTF-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>@nirholas/agent-kit — demo</title>
- <link rel="stylesheet" href="../src/styles.css" />
- <style>
- * { box-sizing: border-box; }
- body {
- margin: 0;
- min-height: 100vh;
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
- background: radial-gradient(ellipse at top, #1a1a2e 0%, #0a0a0a 60%);
- color: #fff;
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- padding: 32px;
- text-align: center;
- }
- h1 {
- font-size: 2rem;
- margin: 0 0 12px;
- font-weight: 500;
- letter-spacing: -0.02em;
- }
- p {
- max-width: 520px;
- color: rgba(255, 255, 255, 0.6);
- line-height: 1.6;
- margin: 0 0 24px;
- }
- code {
- background: rgba(255, 255, 255, 0.08);
- padding: 2px 8px;
- border-radius: 6px;
- font-size: 0.85em;
- }
- .row { display: flex; gap: 12px; flex-wrap: wrap; justify-content: center; }
- button.demo {
- background: rgba(255, 255, 255, 0.08);
- border: 1px solid rgba(255, 255, 255, 0.14);
- color: #fff;
- padding: 10px 18px;
- border-radius: 10px;
- font-family: inherit;
- font-size: 13px;
- cursor: pointer;
- transition: all 0.2s ease;
- }
- button.demo:hover { background: rgba(255, 255, 255, 0.14); }
- pre {
- background: rgba(0, 0, 0, 0.5);
- border: 1px solid rgba(255, 255, 255, 0.08);
- border-radius: 10px;
- padding: 16px;
- text-align: left;
- max-width: 640px;
- width: 100%;
- overflow-x: auto;
- font-size: 12px;
- color: rgba(255, 255, 255, 0.85);
- }
- </style>
-</head>
-<body>
- <h1>agent-kit demo</h1>
- <p>
- Click the chat icon in the bottom-left to talk to the agent.
- Try asking "what can you do" or "hello".
- </p>
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>@nirholas/agent-kit — demo</title>
+ <link rel="stylesheet" href="../src/styles.css" />
+ <style>
+ * {
+ box-sizing: border-box;
+ }
+ body {
+ margin: 0;
+ min-height: 100vh;
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
+ background: radial-gradient(ellipse at top, #1a1a2e 0%, #0a0a0a 60%);
+ color: #fff;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ padding: 32px;
+ text-align: center;
+ }
+ h1 {
+ font-size: 2rem;
+ margin: 0 0 12px;
+ font-weight: 500;
+ letter-spacing: -0.02em;
+ }
+ p {
+ max-width: 520px;
+ color: rgba(255, 255, 255, 0.6);
+ line-height: 1.6;
+ margin: 0 0 24px;
+ }
+ code {
+ background: rgba(255, 255, 255, 0.08);
+ padding: 2px 8px;
+ border-radius: 6px;
+ font-size: 0.85em;
+ }
+ .row {
+ display: flex;
+ gap: 12px;
+ flex-wrap: wrap;
+ justify-content: center;
+ }
+ button.demo {
+ background: rgba(255, 255, 255, 0.08);
+ border: 1px solid rgba(255, 255, 255, 0.14);
+ color: #fff;
+ padding: 10px 18px;
+ border-radius: 10px;
+ font-family: inherit;
+ font-size: 13px;
+ cursor: pointer;
+ transition: all 0.2s ease;
+ }
+ button.demo:hover {
+ background: rgba(255, 255, 255, 0.14);
+ }
+ pre {
+ background: rgba(0, 0, 0, 0.5);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 10px;
+ padding: 16px;
+ text-align: left;
+ max-width: 640px;
+ width: 100%;
+ overflow-x: auto;
+ font-size: 12px;
+ color: rgba(255, 255, 255, 0.85);
+ }
+ </style>
+ </head>
+ <body>
+ <h1>agent-kit demo</h1>
+ <p>
+ Click the chat icon in the bottom-left to talk to the agent. Try asking "what can you
+ do" or "hello".
+ </p>
- <div class="row">
- <button class="demo" id="open-btn">Open panel</button>
- <button class="demo" id="manifest-btn">Log manifests</button>
- <button class="demo" id="say-btn">Inject message</button>
- </div>
+ <div class="row">
+ <button class="demo" id="open-btn">Open panel</button>
+ <button class="demo" id="manifest-btn">Log manifests</button>
+ <button class="demo" id="say-btn">Inject message</button>
+ </div>
- <pre id="out">// Click "Log manifests" to see the .well-known JSON this agent produces.</pre>
+ <pre id="out">
+// Click "Log manifests" to see the .well-known JSON this agent produces.</pre
+ >
- <script type="module">
- import { AgentKit } from '../src/index.js';
+ <script type="module">
+ import { AgentKit } from '../src/index.js';
- const agent = new AgentKit({
- name: 'Demo Agent',
- description: 'A demo of @nirholas/agent-kit — the fastest way to ship an ERC-8004 agent.',
- endpoint: 'https://demo.example.com',
- image: 'https://demo.example.com/logo.png',
- version: '0.1.0',
- org: 'nirholas',
- skills: [
- {
- id: 'greet',
- name: 'Greet User',
- description: 'Say hello',
- tags: ['demo'],
- examples: ['hello', 'hi'],
+ const agent = new AgentKit({
+ name: 'Demo Agent',
+ description:
+ 'A demo of @nirholas/agent-kit — the fastest way to ship an ERC-8004 agent.',
+ endpoint: 'https://demo.example.com',
+ image: 'https://demo.example.com/logo.png',
+ version: '0.1.0',
+ org: 'nirholas',
+ skills: [
+ {
+ id: 'greet',
+ name: 'Greet User',
+ description: 'Say hello',
+ tags: ['demo'],
+ examples: ['hello', 'hi'],
+ },
+ ],
+ onMessage: async (text) => {
+ const lower = text.toLowerCase();
+ if (/hello|hi|hey/.test(lower))
+ return 'Hey! This panel is powered by agent-kit.';
+ if (/what.*do|help/.test(lower))
+ return 'I can demo the SDK — try asking me about ERC-8004, manifests, or the chat panel.';
+ if (/erc|8004|chain|register/.test(lower))
+ return 'Call agent.register() to mint an on-chain identity via ERC-8004. Needs MetaMask + an IPFS token.';
+ if (/manifest|well.?known/.test(lower))
+ return 'agent.manifests() returns the 3 .well-known JSONs: agent-registration, agent-card, and ai-plugin.';
+ return `You said: "${text}". I'm just a demo — drop in your own onMessage handler for real logic.`;
},
- ],
- onMessage: async (text) => {
- const lower = text.toLowerCase();
- if (/hello|hi|hey/.test(lower)) return 'Hey! This panel is powered by agent-kit.';
- if (/what.*do|help/.test(lower)) return 'I can demo the SDK — try asking me about ERC-8004, manifests, or the chat panel.';
- if (/erc|8004|chain|register/.test(lower)) return 'Call agent.register() to mint an on-chain identity via ERC-8004. Needs MetaMask + an IPFS token.';
- if (/manifest|well.?known/.test(lower)) return 'agent.manifests() returns the 3 .well-known JSONs: agent-registration, agent-card, and ai-plugin.';
- return `You said: "${text}". I'm just a demo — drop in your own onMessage handler for real logic.`;
- },
- });
+ });
- agent.mount(document.body);
+ agent.mount(document.body);
- document.getElementById('open-btn').addEventListener('click', () => agent.open());
+ document.getElementById('open-btn').addEventListener('click', () => agent.open());
- document.getElementById('manifest-btn').addEventListener('click', () => {
- const manifests = agent.manifests({
- openapiUrl: 'https://demo.example.com/.well-known/openapi.yaml',
+ document.getElementById('manifest-btn').addEventListener('click', () => {
+ const manifests = agent.manifests({
+ openapiUrl: 'https://demo.example.com/.well-known/openapi.yaml',
+ });
+ document.getElementById('out').textContent = JSON.stringify(manifests, null, 2);
});
- document.getElementById('out').textContent = JSON.stringify(manifests, null, 2);
- });
- document.getElementById('say-btn').addEventListener('click', () => {
- agent.open();
- agent.addMessage('ak-agent', 'This message was injected from the host page via agent.addMessage().');
- });
+ document.getElementById('say-btn').addEventListener('click', () => {
+ agent.open();
+ agent.addMessage(
+ 'ak-agent',
+ 'This message was injected from the host page via agent.addMessage().',
+ );
+ });
- window.agent = agent;
- </script>
-</body>
+ window.agent = agent;
+ </script>
+ </body>
</html>
diff --git a/sdk/package.json b/sdk/package.json
index 8743902c6..e88ba4ef3 100644
--- a/sdk/package.json
+++ b/sdk/package.json
@@ -1,39 +1,39 @@
{
- "name": "@nirholas/agent-kit",
- "version": "0.1.0",
- "description": "Ship an ERC-8004 agent with on-chain identity, a chat panel, and discoverable .well-known endpoints in minutes.",
- "type": "module",
- "main": "./src/index.js",
- "module": "./src/index.js",
- "types": "./src/index.d.ts",
- "exports": {
- ".": {
- "types": "./src/index.d.ts",
- "import": "./src/index.js",
- "default": "./src/index.js"
- },
- "./styles": "./src/styles.css"
- },
- "files": [
- "src"
- ],
- "keywords": [
- "erc-8004",
- "agent",
- "blockchain",
- "a2a",
- "mcp",
- "ethereum",
- "web3",
- "identity"
- ],
- "license": "MIT",
- "peerDependencies": {
- "ethers": "^6.0.0"
- },
- "peerDependenciesMeta": {
- "ethers": {
- "optional": true
- }
- }
+ "name": "@nirholas/agent-kit",
+ "version": "0.1.0",
+ "description": "Ship an ERC-8004 agent with on-chain identity, a chat panel, and discoverable .well-known endpoints in minutes.",
+ "type": "module",
+ "main": "./src/index.js",
+ "module": "./src/index.js",
+ "types": "./src/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./src/index.d.ts",
+ "import": "./src/index.js",
+ "default": "./src/index.js"
+ },
+ "./styles": "./src/styles.css"
+ },
+ "files": [
+ "src"
+ ],
+ "keywords": [
+ "erc-8004",
+ "agent",
+ "blockchain",
+ "a2a",
+ "mcp",
+ "ethereum",
+ "web3",
+ "identity"
+ ],
+ "license": "MIT",
+ "peerDependencies": {
+ "ethers": "^6.0.0"
+ },
+ "peerDependenciesMeta": {
+ "ethers": {
+ "optional": true
+ }
+ }
}
diff --git a/sdk/src/erc8004/abi.js b/sdk/src/erc8004/abi.js
index f1ad701d7..6e01b6887 100644
--- a/sdk/src/erc8004/abi.js
+++ b/sdk/src/erc8004/abi.js
@@ -86,13 +86,13 @@ export const VALIDATION_REGISTRY_ABI = [
export const REGISTRY_DEPLOYMENTS = {
// Base mainnet (chain 8453)
8453: {
- identityRegistry: '', // TODO: fill once deployed
+ identityRegistry: '', // TODO: fill once deployed
reputationRegistry: '', // TODO: fill once deployed
validationRegistry: '', // TODO: fill once deployed
},
// Base Sepolia testnet (chain 84532)
84532: {
- identityRegistry: '', // TODO: fill in from Deploy.s.sol broadcast output
+ identityRegistry: '', // TODO: fill in from Deploy.s.sol broadcast output
reputationRegistry: '',
validationRegistry: '',
},
diff --git a/sdk/src/erc8004/registry.js b/sdk/src/erc8004/registry.js
index 4fcf651e6..8f9f77690 100644
--- a/sdk/src/erc8004/registry.js
+++ b/sdk/src/erc8004/registry.js
@@ -84,7 +84,15 @@ export async function pinToIPFS(blob, apiToken) {
* @param {Array} [opts.services] Additional service entries
* @returns {object}
*/
-export function buildRegistrationJSON({ name, description, imageCID, agentId, chainId, registryAddr, services = [] }) {
+export function buildRegistrationJSON({
+ name,
+ description,
+ imageCID,
+ agentId,
+ chainId,
+ registryAddr,
+ services = [],
+}) {
return {
type: 'https://eips.ethereum.org/EIPS/eip-8004#registration-v1',
name,
@@ -117,7 +125,7 @@ export function getIdentityRegistry(chainId, signer) {
if (!deployment?.identityRegistry) {
throw new Error(
`No Identity Registry configured for chain ${chainId}. ` +
- `Set REGISTRY_DEPLOYMENTS[${chainId}].identityRegistry in sdk/src/erc8004/abi.js`,
+ `Set REGISTRY_DEPLOYMENTS[${chainId}].identityRegistry in sdk/src/erc8004/abi.js`,
);
}
return new Contract(deployment.identityRegistry, IDENTITY_REGISTRY_ABI, signer);
@@ -147,7 +155,15 @@ export function getIdentityRegistry(chainId, signer) {
* @param {Function} [opts.onStatus] Progress callback (message: string) => void
* @returns {Promise<{agentId: number, registrationCID: string, txHash: string}>}
*/
-export async function registerAgent({ name, description, endpoint, imageFile, services = [], apiToken, onStatus }) {
+export async function registerAgent({
+ name,
+ description,
+ endpoint,
+ imageFile,
+ services = [],
+ apiToken,
+ onStatus,
+}) {
const log = onStatus || (() => {});
log('Connecting wallet...');
@@ -168,7 +184,13 @@ export async function registerAgent({ name, description, endpoint, imageFile, se
const receipt = await tx.wait();
const registeredEvent = receipt.logs
- .map((l) => { try { return registry.interface.parseLog(l); } catch { return null; } })
+ .map((l) => {
+ try {
+ return registry.interface.parseLog(l);
+ } catch {
+ return null;
+ }
+ })
.find((e) => e?.name === 'Registered');
if (!registeredEvent) {
@@ -178,10 +200,7 @@ export async function registerAgent({ name, description, endpoint, imageFile, se
const agentId = Number(registeredEvent.args.agentId);
log(`Agent minted — agentId: ${agentId}`);
- const allServices = [
- { name: 'web', endpoint },
- ...services,
- ];
+ const allServices = [{ name: 'web', endpoint }, ...services];
const registrationJSON = buildRegistrationJSON({
name,
@@ -194,7 +213,9 @@ export async function registerAgent({ name, description, endpoint, imageFile, se
});
log('Pinning registration metadata to IPFS...');
- const jsonBlob = new Blob([JSON.stringify(registrationJSON, null, 2)], { type: 'application/json' });
+ const jsonBlob = new Blob([JSON.stringify(registrationJSON, null, 2)], {
+ type: 'application/json',
+ });
const registrationCID = await pinToIPFS(jsonBlob, apiToken);
log(`Registration JSON pinned: ipfs://${registrationCID}`);
diff --git a/sdk/src/index.js b/sdk/src/index.js
index d52199ec1..0d0f6ffd5 100644
--- a/sdk/src/index.js
+++ b/sdk/src/index.js
@@ -27,7 +27,13 @@
export { AgentPanel } from './panel.js';
export { agentRegistration, agentCard, aiPlugin } from './manifests.js';
-export { connectWallet, registerAgent, pinToIPFS, buildRegistrationJSON, getIdentityRegistry } from './erc8004/registry.js';
+export {
+ connectWallet,
+ registerAgent,
+ pinToIPFS,
+ buildRegistrationJSON,
+ getIdentityRegistry,
+} from './erc8004/registry.js';
export { IDENTITY_REGISTRY_ABI, REGISTRY_DEPLOYMENTS, agentRegistryId } from './erc8004/abi.js';
import { AgentPanel } from './panel.js';
@@ -90,16 +96,27 @@ export class AgentKit {
}
/** Open the chat panel. */
- open() { this._panel.open(); return this; }
+ open() {
+ this._panel.open();
+ return this;
+ }
/** Close the chat panel. */
- close() { this._panel.close(); return this; }
+ close() {
+ this._panel.close();
+ return this;
+ }
/** Add a message to the panel. */
- addMessage(role, text) { this._panel.addMessage(role, text); return this; }
+ addMessage(role, text) {
+ this._panel.addMessage(role, text);
+ return this;
+ }
/** Remove the panel from the DOM. */
- dispose() { this._panel.dispose(); }
+ dispose() {
+ this._panel.dispose();
+ }
// ---------------------------------------------------------------------------
// Blockchain registration
diff --git a/sdk/src/manifests.js b/sdk/src/manifests.js
index 79e4a7ec9..3c5181eae 100644
--- a/sdk/src/manifests.js
+++ b/sdk/src/manifests.js
@@ -19,17 +19,21 @@
* @param {Array} [opts.registrations] On-chain registration records
* @returns {object}
*/
-export function agentRegistration({ name, description, endpoint, image = '', services = [], registrations = [] }) {
+export function agentRegistration({
+ name,
+ description,
+ endpoint,
+ image = '',
+ services = [],
+ registrations = [],
+}) {
return {
type: 'https://eips.ethereum.org/EIPS/eip-8004#registration-v1',
name,
description,
image,
active: true,
- services: [
- { name: 'web', endpoint },
- ...services,
- ],
+ services: [{ name: 'web', endpoint }, ...services],
registrations,
supportedTrust: ['reputation'],
};
@@ -84,7 +88,14 @@ export function agentCard({ name, description, url, version = '1.0.0', org = '',
* @param {string} [opts.legalUrl]
* @returns {object}
*/
-export function aiPlugin({ name, description, openapiUrl, logoUrl = '', contactEmail = '', legalUrl = '' }) {
+export function aiPlugin({
+ name,
+ description,
+ openapiUrl,
+ logoUrl = '',
+ contactEmail = '',
+ legalUrl = '',
+}) {
const modelName = name.toLowerCase().replace(/[^a-z0-9_]/g, '_');
return {
schema_version: 'v1',
diff --git a/sdk/src/panel.js b/sdk/src/panel.js
index a96871aba..fb2b79a3e 100644
--- a/sdk/src/panel.js
+++ b/sdk/src/panel.js
@@ -25,7 +25,13 @@ export class AgentPanel {
* @param {Function} [opts.onMessage] async (text: string) => string — your response handler
* @param {boolean} [opts.voice] Enable text-to-speech on agent responses (default: true)
*/
- constructor({ title = 'Agent', welcome = 'Hi! How can I help?', placeholder = 'Ask anything...', onMessage, voice = true } = {}) {
+ constructor({
+ title = 'Agent',
+ welcome = 'Hi! How can I help?',
+ placeholder = 'Ask anything...',
+ onMessage,
+ voice = true,
+ } = {}) {
this.title = title;
this.welcome = welcome;
this.placeholder = placeholder;
diff --git a/sdk/src/styles.css b/sdk/src/styles.css
index db44f630c..f7d81081f 100644
--- a/sdk/src/styles.css
+++ b/sdk/src/styles.css
@@ -4,210 +4,210 @@
*/
.ak-toggle {
- position: fixed;
- bottom: 24px;
- left: 24px;
- width: 48px;
- height: 48px;
- border-radius: 50%;
- border: 1px solid rgba(255, 255, 255, 0.1);
- background: rgba(10, 10, 10, 0.9);
- backdrop-filter: blur(12px);
- -webkit-backdrop-filter: blur(12px);
- color: rgba(255, 255, 255, 0.6);
- cursor: pointer;
- display: flex;
- align-items: center;
- justify-content: center;
- transition: all 0.25s ease;
- z-index: 9999;
- box-shadow: 0 4px 16px rgba(0, 0, 0, 0.4);
+ position: fixed;
+ bottom: 24px;
+ left: 24px;
+ width: 48px;
+ height: 48px;
+ border-radius: 50%;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ background: rgba(10, 10, 10, 0.9);
+ backdrop-filter: blur(12px);
+ -webkit-backdrop-filter: blur(12px);
+ color: rgba(255, 255, 255, 0.6);
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ transition: all 0.25s ease;
+ z-index: 9999;
+ box-shadow: 0 4px 16px rgba(0, 0, 0, 0.4);
}
.ak-toggle:hover {
- background: rgba(255, 255, 255, 0.08);
- color: #fff;
- border-color: rgba(255, 255, 255, 0.25);
- transform: scale(1.05);
+ background: rgba(255, 255, 255, 0.08);
+ color: #fff;
+ border-color: rgba(255, 255, 255, 0.25);
+ transform: scale(1.05);
}
.ak-toggle.ak-active {
- color: #fff;
- border-color: rgba(255, 255, 255, 0.3);
+ color: #fff;
+ border-color: rgba(255, 255, 255, 0.3);
}
.ak-panel {
- position: fixed;
- bottom: 84px;
- left: 24px;
- width: 320px;
- max-height: 480px;
- flex-direction: column;
- background: rgba(10, 10, 10, 0.95);
- backdrop-filter: blur(20px);
- -webkit-backdrop-filter: blur(20px);
- border: 1px solid rgba(255, 255, 255, 0.08);
- border-radius: 16px;
- overflow: hidden;
- z-index: 9999;
- box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
- font-size: 14px;
+ position: fixed;
+ bottom: 84px;
+ left: 24px;
+ width: 320px;
+ max-height: 480px;
+ flex-direction: column;
+ background: rgba(10, 10, 10, 0.95);
+ backdrop-filter: blur(20px);
+ -webkit-backdrop-filter: blur(20px);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 16px;
+ overflow: hidden;
+ z-index: 9999;
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
+ font-size: 14px;
}
.ak-header {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 10px 14px;
- border-bottom: 1px solid rgba(255, 255, 255, 0.06);
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 10px 14px;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);
}
.ak-title {
- font-size: 13px;
- font-weight: 500;
- color: rgba(255, 255, 255, 0.8);
- letter-spacing: 0.03em;
+ font-size: 13px;
+ font-weight: 500;
+ color: rgba(255, 255, 255, 0.8);
+ letter-spacing: 0.03em;
}
.ak-close {
- background: none;
- border: none;
- color: rgba(255, 255, 255, 0.4);
- font-size: 18px;
- cursor: pointer;
- padding: 0;
- line-height: 1;
- transition: color 0.2s ease;
+ background: none;
+ border: none;
+ color: rgba(255, 255, 255, 0.4);
+ font-size: 18px;
+ cursor: pointer;
+ padding: 0;
+ line-height: 1;
+ transition: color 0.2s ease;
}
.ak-close:hover {
- color: #fff;
+ color: #fff;
}
.ak-messages {
- flex: 1;
- overflow-y: auto;
- padding: 8px;
- display: flex;
- flex-direction: column;
- gap: 6px;
- min-height: 200px;
- max-height: 300px;
+ flex: 1;
+ overflow-y: auto;
+ padding: 8px;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ min-height: 200px;
+ max-height: 300px;
}
.ak-message {
- font-size: 13px;
- line-height: 1.5;
- padding: 6px 10px;
- border-radius: 12px;
- max-width: 85%;
- word-wrap: break-word;
+ font-size: 13px;
+ line-height: 1.5;
+ padding: 6px 10px;
+ border-radius: 12px;
+ max-width: 85%;
+ word-wrap: break-word;
}
.ak-message.ak-agent {
- background: rgba(255, 255, 255, 0.06);
- color: rgba(255, 255, 255, 0.7);
- align-self: flex-start;
- border-bottom-left-radius: 4px;
+ background: rgba(255, 255, 255, 0.06);
+ color: rgba(255, 255, 255, 0.7);
+ align-self: flex-start;
+ border-bottom-left-radius: 4px;
}
.ak-message.ak-user {
- background: rgba(255, 255, 255, 0.12);
- color: #fff;
- align-self: flex-end;
- border-bottom-right-radius: 4px;
+ background: rgba(255, 255, 255, 0.12);
+ color: #fff;
+ align-self: flex-end;
+ border-bottom-right-radius: 4px;
}
.ak-controls {
- display: flex;
- gap: 6px;
- padding: 8px;
- border-top: 1px solid rgba(255, 255, 255, 0.06);
+ display: flex;
+ gap: 6px;
+ padding: 8px;
+ border-top: 1px solid rgba(255, 255, 255, 0.06);
}
.ak-input {
- flex: 1;
- background: rgba(255, 255, 255, 0.05);
- border: 1px solid rgba(255, 255, 255, 0.08);
- border-radius: 12px;
- padding: 6px 10px;
- color: #fff;
- font-family: inherit;
- font-size: 13px;
- outline: none;
- transition: border-color 0.2s ease;
+ flex: 1;
+ background: rgba(255, 255, 255, 0.05);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 12px;
+ padding: 6px 10px;
+ color: #fff;
+ font-family: inherit;
+ font-size: 13px;
+ outline: none;
+ transition: border-color 0.2s ease;
}
.ak-input::placeholder {
- color: rgba(255, 255, 255, 0.25);
+ color: rgba(255, 255, 255, 0.25);
}
.ak-input:focus {
- border-color: rgba(255, 255, 255, 0.2);
+ border-color: rgba(255, 255, 255, 0.2);
}
.ak-send {
- background: rgba(255, 255, 255, 0.06);
- border: 1px solid rgba(255, 255, 255, 0.08);
- border-radius: 12px;
- color: rgba(255, 255, 255, 0.5);
- cursor: pointer;
- padding: 6px 10px;
- display: flex;
- align-items: center;
- transition: all 0.2s ease;
+ background: rgba(255, 255, 255, 0.06);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 12px;
+ color: rgba(255, 255, 255, 0.5);
+ cursor: pointer;
+ padding: 6px 10px;
+ display: flex;
+ align-items: center;
+ transition: all 0.2s ease;
}
.ak-send:hover {
- background: rgba(255, 255, 255, 0.1);
- color: #fff;
+ background: rgba(255, 255, 255, 0.1);
+ color: #fff;
}
.ak-mic-row {
- display: flex;
- justify-content: center;
- padding: 0 8px 8px;
+ display: flex;
+ justify-content: center;
+ padding: 0 8px 8px;
}
.ak-mic {
- background: rgba(255, 255, 255, 0.04);
- border: 1px solid rgba(255, 255, 255, 0.06);
- border-radius: 50%;
- width: 32px;
- height: 32px;
- display: flex;
- align-items: center;
- justify-content: center;
- color: rgba(255, 255, 255, 0.35);
- cursor: pointer;
- transition: all 0.2s ease;
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid rgba(255, 255, 255, 0.06);
+ border-radius: 50%;
+ width: 32px;
+ height: 32px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: rgba(255, 255, 255, 0.35);
+ cursor: pointer;
+ transition: all 0.2s ease;
}
.ak-mic:hover {
- background: rgba(255, 255, 255, 0.08);
- color: rgba(255, 255, 255, 0.7);
+ background: rgba(255, 255, 255, 0.08);
+ color: rgba(255, 255, 255, 0.7);
}
.ak-mic.ak-active {
- background: rgba(255, 80, 80, 0.15);
- border-color: rgba(255, 80, 80, 0.3);
- color: #ff5050;
+ background: rgba(255, 80, 80, 0.15);
+ border-color: rgba(255, 80, 80, 0.3);
+ color: #ff5050;
}
@media (max-width: 480px) {
- .ak-toggle {
- bottom: 16px;
- left: 16px;
- width: 42px;
- height: 42px;
- }
-
- .ak-panel {
- bottom: 72px;
- left: 8px;
- right: 8px;
- width: auto;
- max-height: 60vh;
- }
+ .ak-toggle {
+ bottom: 16px;
+ left: 16px;
+ width: 42px;
+ height: 42px;
+ }
+
+ .ak-panel {
+ bottom: 72px;
+ left: 8px;
+ right: 8px;
+ width: auto;
+ max-height: 60vh;
+ }
}
diff --git a/specs/AGENT_MANIFEST.md b/specs/AGENT_MANIFEST.md
index 56aec4f34..a3bc88510 100644
--- a/specs/AGENT_MANIFEST.md
+++ b/specs/AGENT_MANIFEST.md
@@ -33,108 +33,110 @@ Everything is optional except `manifest.json` and a `body` reference.
```jsonc
{
- "$schema": "https://3d-agent.io/schemas/manifest/0.1.json",
- "spec": "agent-manifest/0.1",
-
- // Identity — filled in after on-chain registration
- "id": {
- "chain": "base", // "base" | "base-sepolia" | "ethereum" | "local"
- "registry": "0x...", // ERC-8004 Identity Registry address
- "agentId": "1234", // assigned by the registry
- "owner": "0x..." // wallet that controls the agent
- },
-
- // Display
- "name": "Coach Leo",
- "description": "A football coach who reviews your form.",
- "image": "ipfs://Qm.../poster.webp",
- "tags": ["coach", "sports", "argentina"],
-
- // Body — the 3D embodiment
- "body": {
- "uri": "ipfs://Qm.../body.glb",
- "format": "gltf-binary", // "gltf-binary" | "gltf" | "vrm"
- "validator": "attestations/gltf-validator.json",
- "rig": "mixamo", // "mixamo" | "vrm" | "custom" — drives animation retargeting
- "boundingBoxHeight": 1.78 // meters, for scale normalization
- },
-
- // Brain — LLM runtime binding
- "brain": {
- "provider": "anthropic", // "anthropic" | "openai" | "local" | "none"
- "model": "claude-opus-4-6",
- "instructions": "instructions.md",
- "temperature": 0.7,
- "maxTokens": 4096,
- "thinking": "auto" // "auto" | "always" | "never"
- },
-
- // Voice — I/O
- "voice": {
- "tts": {
- "provider": "browser", // "browser" | "elevenlabs" | "openai" | "none"
- "voiceId": "default",
- "rate": 1.0,
- "pitch": 1.0
- },
- "stt": {
- "provider": "browser", // "browser" | "whisper" | "none"
- "language": "en-US",
- "continuous": false
- }
- },
-
- // Skills — capability bundles, composable, content-addressed
- "skills": [
- { "uri": "skills/wave/", "version": "0.1.0" },
- { "uri": "ipfs://Qm.../dance/", "version": "1.2.0" },
- { "uri": "https://skills.3d-agent.io/[email protected]" }
- ],
-
- // Memory — persistent state
- "memory": {
- "mode": "local", // "local" | "ipfs" | "encrypted-ipfs" | "none"
- "index": "memory/MEMORY.md",
- "maxTokens": 8192 // budget for memory context injection
- },
-
- // Scene-tools — what the LLM can do in the 3D world
- // Tools declared here are always available; skills add more.
- "tools": [
- "wave", "lookAt", "pointAt", "play_clip",
- "setExpression", "moveTo", "speak"
- ],
-
- // Provenance — signed attestations
- "attestations": [
- {
- "type": "gltf-validator",
- "uri": "attestations/gltf-validator.json",
- "issuer": "0x...",
- "signature": "0x..."
- }
- ],
-
- // Lifecycle
- "created": "2026-04-14T12:00:00Z",
- "updated": "2026-04-14T12:00:00Z",
- "version": "0.1.0"
+ "$schema": "https://3d-agent.io/schemas/manifest/0.1.json",
+ "spec": "agent-manifest/0.1",
+
+ // Identity — filled in after on-chain registration
+ "id": {
+ "chain": "base", // "base" | "base-sepolia" | "ethereum" | "local"
+ "registry": "0x...", // ERC-8004 Identity Registry address
+ "agentId": "1234", // assigned by the registry
+ "owner": "0x...", // wallet that controls the agent
+ },
+
+ // Display
+ "name": "Coach Leo",
+ "description": "A football coach who reviews your form.",
+ "image": "ipfs://Qm.../poster.webp",
+ "tags": ["coach", "sports", "argentina"],
+
+ // Body — the 3D embodiment
+ "body": {
+ "uri": "ipfs://Qm.../body.glb",
+ "format": "gltf-binary", // "gltf-binary" | "gltf" | "vrm"
+ "validator": "attestations/gltf-validator.json",
+ "rig": "mixamo", // "mixamo" | "vrm" | "custom" — drives animation retargeting
+ "boundingBoxHeight": 1.78, // meters, for scale normalization
+ },
+
+ // Brain — LLM runtime binding
+ "brain": {
+ "provider": "anthropic", // "anthropic" | "openai" | "local" | "none"
+ "model": "claude-opus-4-6",
+ "instructions": "instructions.md",
+ "temperature": 0.7,
+ "maxTokens": 4096,
+ "thinking": "auto", // "auto" | "always" | "never"
+ },
+
+ // Voice — I/O
+ "voice": {
+ "tts": {
+ "provider": "browser", // "browser" | "elevenlabs" | "openai" | "none"
+ "voiceId": "default",
+ "rate": 1.0,
+ "pitch": 1.0,
+ },
+ "stt": {
+ "provider": "browser", // "browser" | "whisper" | "none"
+ "language": "en-US",
+ "continuous": false,
+ },
+ },
+
+ // Skills — capability bundles, composable, content-addressed
+ "skills": [
+ { "uri": "skills/wave/", "version": "0.1.0" },
+ { "uri": "ipfs://Qm.../dance/", "version": "1.2.0" },
+ { "uri": "https://skills.3d-agent.io/[email protected]" },
+ ],
+
+ // Memory — persistent state
+ "memory": {
+ "mode": "local", // "local" | "ipfs" | "encrypted-ipfs" | "none"
+ "index": "memory/MEMORY.md",
+ "maxTokens": 8192, // budget for memory context injection
+ },
+
+ // Scene-tools — what the LLM can do in the 3D world
+ // Tools declared here are always available; skills add more.
+ "tools": ["wave", "lookAt", "pointAt", "play_clip", "setExpression", "moveTo", "speak"],
+
+ // Provenance — signed attestations
+ "attestations": [
+ {
+ "type": "gltf-validator",
+ "uri": "attestations/gltf-validator.json",
+ "issuer": "0x...",
+ "signature": "0x...",
+ },
+ ],
+
+ // Lifecycle
+ "created": "2026-04-14T12:00:00Z",
+ "updated": "2026-04-14T12:00:00Z",
+ "version": "0.1.0",
}
```
## Field semantics
### `id`
+
The on-chain identity. When absent, the agent is unregistered (local-only). When present, `agent://{chain}/{agentId}` resolves to this manifest via the registry's `tokenURI(agentId)` call.
### `body`
+
Only `uri` and `format` are required. `rig` lets skills retarget animations across compatible rigs (Mixamo-to-Mixamo skill bundles are portable). `boundingBoxHeight` lets the scene normalize scale — a 20-meter model and a 0.2-meter model both render at consistent human size.
### `brain`
+
`provider: "none"` is valid — a purely reactive avatar with no LLM, controlled only by skill triggers. `instructions` is a relative path to a markdown file; its frontmatter can override `brain.*` fields per-prompt.
### `skills`
+
Three URI forms:
+
- **Relative** (`skills/wave/`) — bundled in the manifest.
- **IPFS** (`ipfs://Qm.../`) — resolved via gateway fallback.
- **HTTPS** (`https://skills.3d-agent.io/...`) — centrally hosted skill registry (optional, for discoverability).
@@ -142,49 +144,51 @@ Three URI forms:
Skills load lazily. The `<agent-3d>` element emits `skill:loaded` events as each comes online.
### `memory`
+
`local` persists in `localStorage` keyed by agentId. `ipfs` pins after each write (slow, durable). `encrypted-ipfs` wraps with the owner wallet's pubkey. See [MEMORY_SPEC.md](./MEMORY_SPEC.md).
### `tools`
+
Built-in scene-tools available without any skill installed. Additional tools come from skills' `tools.json`. Tool names are merged; skill tools override built-ins if names collide (with a console warning).
## Worked example: Coach Leo
```json
{
- "spec": "agent-manifest/0.1",
- "id": {
- "chain": "base-sepolia",
- "registry": "0xAbC...123",
- "agentId": "42",
- "owner": "0xDeadBeef..."
- },
- "name": "Coach Leo",
- "description": "Football coach. Reviews your form, cheers you on.",
- "image": "ipfs://bafy.../poster.webp",
- "tags": ["coach", "football", "argentina"],
- "body": {
- "uri": "ipfs://bafy.../cz.glb",
- "format": "gltf-binary",
- "rig": "mixamo",
- "boundingBoxHeight": 1.78
- },
- "brain": {
- "provider": "anthropic",
- "model": "claude-opus-4-6",
- "instructions": "instructions.md",
- "temperature": 0.8
- },
- "voice": {
- "tts": { "provider": "browser", "rate": 1.1 },
- "stt": { "provider": "browser", "language": "en-US" }
- },
- "skills": [
- { "uri": "skills/wave/", "version": "0.1.0" },
- { "uri": "ipfs://bafy.../football-drills/", "version": "1.0.0" }
- ],
- "memory": { "mode": "local", "index": "memory/MEMORY.md", "maxTokens": 8192 },
- "tools": ["wave", "lookAt", "play_clip", "setExpression", "speak"],
- "version": "0.1.0"
+ "spec": "agent-manifest/0.1",
+ "id": {
+ "chain": "base-sepolia",
+ "registry": "0xAbC...123",
+ "agentId": "42",
+ "owner": "0xDeadBeef..."
+ },
+ "name": "Coach Leo",
+ "description": "Football coach. Reviews your form, cheers you on.",
+ "image": "ipfs://bafy.../poster.webp",
+ "tags": ["coach", "football", "argentina"],
+ "body": {
+ "uri": "ipfs://bafy.../cz.glb",
+ "format": "gltf-binary",
+ "rig": "mixamo",
+ "boundingBoxHeight": 1.78
+ },
+ "brain": {
+ "provider": "anthropic",
+ "model": "claude-opus-4-6",
+ "instructions": "instructions.md",
+ "temperature": 0.8
+ },
+ "voice": {
+ "tts": { "provider": "browser", "rate": 1.1 },
+ "stt": { "provider": "browser", "language": "en-US" }
+ },
+ "skills": [
+ { "uri": "skills/wave/", "version": "0.1.0" },
+ { "uri": "ipfs://bafy.../football-drills/", "version": "1.0.0" }
+ ],
+ "memory": { "mode": "local", "index": "memory/MEMORY.md", "maxTokens": 8192 },
+ "tools": ["wave", "lookAt", "play_clip", "setExpression", "speak"],
+ "version": "0.1.0"
}
```
diff --git a/specs/CLAUDE_ARTIFACT.md b/specs/CLAUDE_ARTIFACT.md
index 3eec008b0..d8628937d 100644
--- a/specs/CLAUDE_ARTIFACT.md
+++ b/specs/CLAUDE_ARTIFACT.md
@@ -10,13 +10,13 @@ GET https://3dagent.vercel.app/api/artifact
### Parameters
-| Param | Required | Pattern | Notes |
-|---|---|---|---|
-| `agent` | one of | `/^[a-z0-9_-]{3,64}$/i` | Agent ID; looked up in `agent_identities` |
-| `model` | one of | `https://` URL, whitelisted origin | GLB URL; viewer-only, no persona |
-| `theme` | no | `dark` \| `light` | Default `dark` |
-| `idle` | no | string | Animation clip name |
-| `bg` | no | hex string (no `#`) | Background colour |
+| Param | Required | Pattern | Notes |
+| ------- | -------- | ---------------------------------- | ----------------------------------------- |
+| `agent` | one of | `/^[a-z0-9_-]{3,64}$/i` | Agent ID; looked up in `agent_identities` |
+| `model` | one of | `https://` URL, whitelisted origin | GLB URL; viewer-only, no persona |
+| `theme` | no | `dark` \| `light` | Default `dark` |
+| `idle` | no | string | Animation clip name |
+| `bg` | no | hex string (no `#`) | Background colour |
Exactly one of `agent` or `model` must be supplied; both or neither → 400.
@@ -55,12 +55,12 @@ frame-ancestors *
All errors are `application/json` in the standard `{ error, error_description }` envelope:
-| Status | Code | Cause |
-|---|---|---|
-| 400 | `invalid_request` | Bad agent ID pattern, bad model URL, or missing both params |
-| 404 | `not_found` | Agent ID not found or deleted |
-| 405 | `method_not_allowed` | Non-GET/HEAD request |
-| 429 | `rate_limited` | Exceeded `widgetRead` preset (600/min per IP) |
+| Status | Code | Cause |
+| ------ | -------------------- | ----------------------------------------------------------- |
+| 400 | `invalid_request` | Bad agent ID pattern, bad model URL, or missing both params |
+| 404 | `not_found` | Agent ID not found or deleted |
+| 405 | `method_not_allowed` | Non-GET/HEAD request |
+| 429 | `rate_limited` | Exceeded `widgetRead` preset (600/min per IP) |
## Browser compat
diff --git a/specs/EDITOR_SPEC.md b/specs/EDITOR_SPEC.md
index 255ef4423..a4bead2a3 100644
--- a/specs/EDITOR_SPEC.md
+++ b/specs/EDITOR_SPEC.md
@@ -1,8 +1,7 @@
# Editor Spec v0.1 — `<agent-3d editor>` & `src/editor/`
-> **Format ID:** `agent-editor/0.1`
-> **Stability:** draft — breaking changes may occur before 1.0
-> **Relationship to EMBED_SPEC:** EMBED_SPEC defines how a finished agent is played back. This spec defines the surface for *authoring* one. The `editor` attribute switches the same `<agent-3d>` element from playback mode into editing mode. The "Copy Embed" output of the editor is a plain `<agent-3d>` element with no `editor` attribute — a clean embed the user pastes anywhere.
+> **Format ID:** `agent-editor/0.1` > **Stability:** draft — breaking changes may occur before 1.0
+> **Relationship to EMBED_SPEC:** EMBED*SPEC defines how a finished agent is played back. This spec defines the surface for \_authoring* one. The `editor` attribute switches the same `<agent-3d>` element from playback mode into editing mode. The "Copy Embed" output of the editor is a plain `<agent-3d>` element with no `editor` attribute — a clean embed the user pastes anywhere.
---
@@ -21,9 +20,11 @@ The editor layer lives in [`src/editor/`](../src/editor/) and is orchestrated by
### `editor` attribute (boolean)
**Documented contract** (see EMBED_SPEC.md line 109):
+
```html
<agent-3d editor src="agent://base/42"></agent-3d>
```
+
Replaces the live agent runtime with the embed editor. Intended to be a boolean presence attribute — no value required.
**Current state:** not handled by `observedAttributes` in [`src/element.js:211`](../src/element.js#L211). Manual integration required (see §6).
@@ -32,18 +33,18 @@ Replaces the live agent runtime with the embed editor. Intended to be a boolean
These are standard embed attributes that the editor reads or writes to its output snippet. They are fully handled by [`src/element.js`](../src/element.js):
-| Attribute | Type | Role in editor context |
-|---|---|---|
-| `src` | URI | Source agent URI; echoed into "Copy Embed" snippet |
-| `agent-id` | string | Backend UUID or on-chain ref; echoed into snippet |
-| `manifest` | URL | Manifest URL; echoed into snippet |
-| `body` | URL | Bare GLB URI; the editor's primary input when no manifest exists |
-| `mode` | `inline`\|`floating`\|`section`\|`fullscreen` | Layout mode selector in embed-editor UI |
-| `position` | string | Floating mode anchor — `bottom-right`, etc. |
-| `width` | CSS length | Configurable in embed-editor |
-| `height` | CSS length | Configurable in embed-editor |
-| `responsive` | boolean | Toggleable in embed-editor |
-| `kiosk` | boolean | Suppresses chat chrome — not editor-specific but affects embed output |
+| Attribute | Type | Role in editor context |
+| ------------ | --------------------------------------------- | --------------------------------------------------------------------- |
+| `src` | URI | Source agent URI; echoed into "Copy Embed" snippet |
+| `agent-id` | string | Backend UUID or on-chain ref; echoed into snippet |
+| `manifest` | URL | Manifest URL; echoed into snippet |
+| `body` | URL | Bare GLB URI; the editor's primary input when no manifest exists |
+| `mode` | `inline`\|`floating`\|`section`\|`fullscreen` | Layout mode selector in embed-editor UI |
+| `position` | string | Floating mode anchor — `bottom-right`, etc. |
+| `width` | CSS length | Configurable in embed-editor |
+| `height` | CSS length | Configurable in embed-editor |
+| `responsive` | boolean | Toggleable in embed-editor |
+| `kiosk` | boolean | Suppresses chat chrome — not editor-specific but affects embed output |
---
@@ -55,15 +56,15 @@ The central shared state object. All panels read from and write to it.
**State owned:**
-| Field | Type | Description |
-|---|---|---|
-| `sourceURL` | `string\|null` | URL of the loaded model |
-| `sourceFile` | `File\|null` | Dropped File object |
-| `sourceBuffer` | `ArrayBuffer\|null` | Lazily cached bytes (fetched or read from File) |
-| `sourceName` | `string` | Display name, derived from URL basename or File.name |
-| `materialEdits` | `{ [uuid]: MaterialEditPatch }` | Keyed by Three.js `material.uuid` |
-| `transformEdits` | `{ [uuid]: TransformEditPatch }` | Keyed by Three.js `Object3D.uuid` |
-| `visibilityEdits` | `{ [uuid]: { name, visible } }` | Keyed by Three.js `Object3D.uuid` |
+| Field | Type | Description |
+| ----------------- | -------------------------------- | ---------------------------------------------------- |
+| `sourceURL` | `string\|null` | URL of the loaded model |
+| `sourceFile` | `File\|null` | Dropped File object |
+| `sourceBuffer` | `ArrayBuffer\|null` | Lazily cached bytes (fetched or read from File) |
+| `sourceName` | `string` | Display name, derived from URL basename or File.name |
+| `materialEdits` | `{ [uuid]: MaterialEditPatch }` | Keyed by Three.js `material.uuid` |
+| `transformEdits` | `{ [uuid]: TransformEditPatch }` | Keyed by Three.js `Object3D.uuid` |
+| `visibilityEdits` | `{ [uuid]: { name, visible } }` | Keyed by Three.js `Object3D.uuid` |
**Patch shapes:**
@@ -94,18 +95,18 @@ The central shared state object. All panels read from and write to it.
**Methods:**
-| Method | Returns | Description |
-|---|---|---|
-| `reset({ url, file, name })` | void | Clears all edits; sets new source |
-| `isExportReady()` | boolean | True when any source is set |
-| `isDirty()` | boolean | True when any edit map is non-empty |
-| `onChange(fn)` | unsubscribe fn | Fires after any edit or reset |
-| `recordMaterialEdit(material, patch)` | void | Merges patch into materialEdits |
-| `clearMaterialEdit(material)` | void | Removes entry from materialEdits |
-| `recordTransformEdit(node)` | void | Writes current position/rotation/scale |
-| `recordVisibilityEdit(node, visible)` | void | Writes visibility state |
-| `restoreEdits(edits)` | void | Re-applies a saved edit set by name-matching |
-| `getSourceBuffer()` | `Promise<ArrayBuffer>` | Fetches or reads bytes; caches result |
+| Method | Returns | Description |
+| ------------------------------------- | ---------------------- | -------------------------------------------- |
+| `reset({ url, file, name })` | void | Clears all edits; sets new source |
+| `isExportReady()` | boolean | True when any source is set |
+| `isDirty()` | boolean | True when any edit map is non-empty |
+| `onChange(fn)` | unsubscribe fn | Fires after any edit or reset |
+| `recordMaterialEdit(material, patch)` | void | Merges patch into materialEdits |
+| `clearMaterialEdit(material)` | void | Removes entry from materialEdits |
+| `recordTransformEdit(node)` | void | Writes current position/rotation/scale |
+| `recordVisibilityEdit(node, visible)` | void | Writes visibility state |
+| `restoreEdits(edits)` | void | Re-applies a saved edit set by name-matching |
+| `getSourceBuffer()` | `Promise<ArrayBuffer>` | Fetches or reads bytes; caches result |
**Failure modes:** `getSourceBuffer()` throws if no source is set. `reset()` with no source logs a warning but does not throw.
@@ -117,20 +118,20 @@ The central shared state object. All panels read from and write to it.
**Editable properties per material:**
-| Property | Range | Notes |
-|---|---|---|
-| base color | hex color | `mat.color` |
-| metalness | 0–1 | |
-| roughness | 0–1 | |
-| emissive color | hex color | `mat.emissive` |
-| emissive intensity | 0–4 | **Not recorded to session** (pre-1.0 rough edge #2) |
-| opacity | 0–1 | Sets `mat.transparent` automatically when < 1 |
-| transparent | boolean | |
-| alpha test | 0–1 | |
-| wireframe | boolean | Not recorded to session (viewport-only preview) |
-| flat shading | boolean | Not recorded to session (viewport-only preview) |
-| env map intensity | 0–4 | If present on material; not recorded to session |
-| side | Front/Back/Double | Maps to three.js `FrontSide`/`BackSide`/`DoubleSide` |
+| Property | Range | Notes |
+| ------------------ | ----------------- | ---------------------------------------------------- |
+| base color | hex color | `mat.color` |
+| metalness | 0–1 | |
+| roughness | 0–1 | |
+| emissive color | hex color | `mat.emissive` |
+| emissive intensity | 0–4 | **Not recorded to session** (pre-1.0 rough edge #2) |
+| opacity | 0–1 | Sets `mat.transparent` automatically when < 1 |
+| transparent | boolean | |
+| alpha test | 0–1 | |
+| wireframe | boolean | Not recorded to session (viewport-only preview) |
+| flat shading | boolean | Not recorded to session (viewport-only preview) |
+| env map intensity | 0–4 | If present on material; not recorded to session |
+| side | Front/Back/Double | Maps to three.js `FrontSide`/`BackSide`/`DoubleSide` |
**Inputs:** `viewer.content` (Three.js scene graph), `viewer.gui` (dat.GUI instance), `EditorSession`.
@@ -141,6 +142,7 @@ The central shared state object. All panels read from and write to it.
**Reset:** `↺ reset` button per subfolder restores the snapshot captured at `rebuild()` time and calls `session.clearMaterialEdit(mat)`.
**Failure modes:**
+
- If `viewer.gui` is null, no UI is built (silent no-op).
- If the scene has no standard/physical materials, the `Materials` folder is not created.
@@ -155,6 +157,7 @@ The central shared state object. All panels read from and write to it.
**What it is:** A side panel appended to `viewer.el` showing the full Three.js scene tree, a node inspector, and a TransformControls gizmo.
**Tree shape:** Recursive DOM tree mirroring `viewer.content` hierarchy. Root is auto-expanded. Each node row shows:
+
- Expand/collapse arrow (if children present)
- Type icon (mesh, skinned mesh, group, bone, light, camera, etc.)
- Node name or type
@@ -163,16 +166,19 @@ The central shared state object. All panels read from and write to it.
Nodes are identified in the tree DOM by `data-uuid` attribute.
**Selection semantics:**
+
- Click on a row selects the node → `this.selectedNode`, highlights the row with `.selected` class, attaches TransformControls.
- Double-click frames the node in the camera.
- Left-click on the canvas raycasts against `viewer.content`; hit object is selected (walks up to the nearest Mesh/Light/Camera ancestor).
- `Escape` key detaches TransformControls and clears selection.
**Visibility toggle:**
+
- Per-row ● button sets `node.visible` and calls `session.recordVisibilityEdit(node, visible)`.
- Inspector "Hide"/"Show" button does the same.
**Transform editing:**
+
- Gizmo keys: `W` translate, `E` rotate, `R` scale.
- Inspector shows editable numeric inputs for pos/rot°/scale; changes call `session.recordTransformEdit(node)`.
- TransformControls `objectChange` event also calls `session.recordTransformEdit`.
@@ -181,12 +187,12 @@ Nodes are identified in the tree DOM by `data-uuid` attribute.
**Keyboard shortcuts** (when not in an input):
-| Key | Action |
-|---|---|
-| `T` | Toggle panel open/closed |
-| `W` | Switch gizmo to translate |
-| `E` | Switch gizmo to rotate |
-| `R` | Switch gizmo to scale |
+| Key | Action |
+| -------- | --------------------------- |
+| `T` | Toggle panel open/closed |
+| `W` | Switch gizmo to translate |
+| `E` | Switch gizmo to rotate |
+| `R` | Switch gizmo to scale |
| `Escape` | Detach gizmo, deselect node |
**Inputs:** `viewer` (Viewer instance), `EditorSession`.
@@ -210,6 +216,7 @@ Nodes are identified in the tree DOM by `data-uuid` attribute.
**Thumbnail grid panel** (`.texture-inspector`): Opens appended to `document.body`. Close button or `X` key toggles.
**Lightbox** (`.texture-lightbox`): Opens on card click. Provides:
+
- RGB / R / G / B / A channel extraction (requires same-origin or CORS-readable image for channel modes)
- Alpha-over-checkerboard mode
- UV wireframe overlay (renders triangle edges from mesh UV attributes)
@@ -225,6 +232,7 @@ Nodes are identified in the tree DOM by `data-uuid` attribute.
**Events:** none emitted.
**Failure modes:**
+
- Channel extraction calls `ctx.getImageData()` — this will throw (CORS) for cross-origin textures. The lightbox shows "channel extraction blocked (CORS)" in place of extracted data.
- If no textures are found, the `Textures` dat.gui folder is not created.
@@ -235,6 +243,7 @@ Nodes are identified in the tree DOM by `data-uuid` attribute.
**Export format:** GLB (`model/gltf-binary`) via `@gltf-transform/core` `WebIO` + all extensions (`@gltf-transform/extensions`).
**What is included:** The full original GLB/GLTF content, with the following edits applied:
+
- Material properties: base color factor, metallic factor, roughness factor, emissive factor, alpha mode, alpha cutoff, double-sided.
- Node transforms: translation, rotation (converted from Euler XYZ to quaternion), scale.
- Node visibility: hidden nodes are written with `scale = [0, 0, 0]` (no glTF `extras.hidden` — see rough edge #3).
@@ -248,6 +257,7 @@ Nodes are identified in the tree DOM by `data-uuid` attribute.
**Output filename:** `<sourceName>.edited.glb` where `sourceName` strips query strings and `.glb`/`.gltf` extensions.
**Failure modes:**
+
- `exportEditedGLB(session)` throws `Error('No source buffer for export')` if `session.getSourceBuffer()` returns nothing.
- `getSourceBuffer()` throws if no source URL or File is set.
- Caller in `Editor._exportGLB()` catches and shows `window.alert`.
@@ -266,17 +276,18 @@ Both material edits and transform/visibility edits match by the first occurrence
Turns an in-progress `EditorSession` into a live shareable widget. Five sequential steps:
-| Step | Operation | Endpoint |
-|---|---|---|
-| `export` | `exportEditedGLB(session)` → `Uint8Array` | (client-side) |
-| `presign` | POST metadata, get signed PUT URL | `POST /api/avatars/presign` |
-| `upload` | PUT raw bytes to presigned URL | R2 (presigned URL) |
-| `register` | Create avatar metadata record | `POST /api/avatars` |
-| `widget` | Create turntable widget | `POST /api/widgets` |
+| Step | Operation | Endpoint |
+| ---------- | ----------------------------------------- | --------------------------- |
+| `export` | `exportEditedGLB(session)` → `Uint8Array` | (client-side) |
+| `presign` | POST metadata, get signed PUT URL | `POST /api/avatars/presign` |
+| `upload` | PUT raw bytes to presigned URL | R2 (presigned URL) |
+| `register` | Create avatar metadata record | `POST /api/avatars` |
+| `widget` | Create turntable widget | `POST /api/widgets` |
**Progress callback:** `onStep({ step, pct })` fired at each step boundary. Steps: `'export'`, `'presign'`, `'upload'`, `'register'`, `'widget'`.
**Return value on success:**
+
```js
{
widget: { id, ... },
@@ -291,12 +302,12 @@ Turns an in-progress `EditorSession` into a live shareable widget. Five sequenti
**Error classes exported** (importable from `./publish.js`):
-| Class | When thrown |
-|---|---|
-| `AuthRequiredError` | 401 from any fetch step |
+| Class | When thrown |
+| ------------------- | ------------------------------------------------ |
+| `AuthRequiredError` | 401 from any fetch step |
| `SizeTooLargeError` | Client-side size check or 413 from register step |
-| `ExportFailedError` | `exportEditedGLB` throws |
-| `PublishError` | Any non-401/non-413 non-2xx response |
+| `ExportFailedError` | `exportEditedGLB` throws |
+| `PublishError` | Any non-401/non-413 non-2xx response |
**Client-side size limit:** `MAX_BYTES = 25 * 1024 * 1024` (25 MB) — enforced before upload. Server-side schema allows up to 500 MB ([`api/_lib/validate.js:58`](../api/_lib/validate.js#L58)); the client is the stricter limit here.
@@ -323,6 +334,7 @@ UI wrapper over `publishEditedGLB`. Manages three states: **working** (step prog
A separate "place, scale, preview, copy" UX. Mounted by calling `mountEmbedEditor(rootEl, { src, defaults })`. Renders a split view: a live iframe preview on the left, a control panel on the right.
Controls exposed:
+
- Mode selector (floating, inline, section, fullscreen)
- Position selector for floating mode (6 anchors)
- Width/height inputs
@@ -341,13 +353,15 @@ Controls exposed:
Wires MaterialEditor, TextureInspector, SceneExplorer, and GLB export/publish into the Viewer via dat.gui.
**Entry point:**
+
```js
const editor = new Editor(viewer);
-editor.attach(); // once, after viewer constructed
+editor.attach(); // once, after viewer constructed
editor.onContentChanged({ url, file, name }); // every time a new model loads
```
**dat.gui folder added:** `Editor` — contains:
+
- `💾 download GLB` (count badge when edits exist; disabled when no source)
- `📤 publish as embed`
- `🗂 scene panel [T]`
@@ -361,13 +375,13 @@ editor.onContentChanged({ url, file, name }); // every time a new model loads
### Who can edit
-| Actor | Can view model | Can edit materials/transforms | Can export GLB | Can publish |
-|---|---|---|---|---|
-| Anonymous visitor | Yes | Yes (viewport only) | Yes (download only) | No — 401 → login redirect |
-| Authenticated user | Yes | Yes | Yes | Yes — creates under their account |
-| Owner of the agent | Yes | Yes | Yes | Yes |
+| Actor | Can view model | Can edit materials/transforms | Can export GLB | Can publish |
+| ------------------ | -------------- | ----------------------------- | ------------------- | --------------------------------- |
+| Anonymous visitor | Yes | Yes (viewport only) | Yes (download only) | No — 401 → login redirect |
+| Authenticated user | Yes | Yes | Yes | Yes — creates under their account |
+| Owner of the agent | Yes | Yes | Yes | Yes |
-The editor itself is entirely client-side; there is no server-side ownership gate on the *editing* phase. Ownership is enforced only at **publish time** (API).
+The editor itself is entirely client-side; there is no server-side ownership gate on the _editing_ phase. Ownership is enforced only at **publish time** (API).
### Ownership check at publish
@@ -381,6 +395,7 @@ Client-side auth hint via `readAuthHint()` from [`src/account.js:43`](../src/acc
### Unauthed user save path
When `publishEditedGLB` catches `AuthRequiredError`, `PublishModal.showAuthRequired()` is called. The user clicks "Sign in" — `_signInAndReturn()`:
+
1. Serializes current `EditorSession` edits + source to `sessionStorage`/IndexedDB via `stashSession()` ([`src/editor/edit-persistence.js`](../src/editor/edit-persistence.js)).
2. Redirects to `/login?next=<current URL with ?resume=<token>&publish=1>`.
3. Post-login, the caller is expected to detect `?resume` and call `restoreEdits()` on a fresh session.
@@ -395,26 +410,26 @@ When `publishEditedGLB` catches `AuthRequiredError`, `PublishModal.showAuthRequi
`EditorSession` uses a listener set, not DOM events. Subscribe via `session.onChange(fn)`.
-| Trigger | When fired |
-|---|---|
-| `session.reset()` | New model loaded |
-| `session.recordMaterialEdit()` | Any material property change |
-| `session.clearMaterialEdit()` | Material reset |
-| `session.recordTransformEdit()` | Any node transform change |
-| `session.recordVisibilityEdit()` | Visibility toggle |
-| `session.restoreEdits()` | Edits restored from stash |
+| Trigger | When fired |
+| -------------------------------- | ---------------------------- |
+| `session.reset()` | New model loaded |
+| `session.recordMaterialEdit()` | Any material property change |
+| `session.clearMaterialEdit()` | Material reset |
+| `session.recordTransformEdit()` | Any node transform change |
+| `session.recordVisibilityEdit()` | Visibility toggle |
+| `session.restoreEdits()` | Edits restored from stash |
### Publish progress events
Passed to `publishEditedGLB({ onStep })` as a callback, not DOM events.
-| `step` value | `pct` range | When |
-|---|---|---|
-| `'export'` | 0 → 1 | GLB serialization start → done |
-| `'presign'` | — → 1 | Presign response received |
-| `'upload'` | 0 → 1 | XHR upload progress |
-| `'register'` | — → 1 | Avatar record created |
-| `'widget'` | — → 1 | Widget record created |
+| `step` value | `pct` range | When |
+| ------------ | ----------- | ------------------------------ |
+| `'export'` | 0 → 1 | GLB serialization start → done |
+| `'presign'` | — → 1 | Presign response received |
+| `'upload'` | 0 → 1 | XHR upload progress |
+| `'register'` | — → 1 | Avatar record created |
+| `'widget'` | — → 1 | Widget record created |
(`PublishModal.onStep` maps `'presign'` → `'upload'` bucket for UI display.)
@@ -447,6 +462,7 @@ async function exportEditedGLB(session: EditorSession): Promise<Uint8Array>
```
A custom exporter can be dropped in by:
+
1. Reading `await session.getSourceBuffer()` for the original bytes.
2. Reading `session.materialEdits`, `session.transformEdits`, `session.visibilityEdits` for the accumulated changes.
3. Returning a `Uint8Array` of any desired format.
@@ -471,11 +487,11 @@ No formal exporter plugin contract exists; the `Editor._exportGLB()` method ([`s
### Size limits
-| Limit | Value | Enforced by |
-|---|---|---|
-| Client-side publish limit | 25 MB | [`src/editor/publish.js:17`](../src/editor/publish.js#L17) `MAX_BYTES` |
-| Server-side schema max | 500 MB | [`api/_lib/validate.js:58,63`](../api/_lib/validate.js#L58) |
-| Rate limit (uploads) | 60 per hour per user | `limits.upload(userId)` in presign |
+| Limit | Value | Enforced by |
+| ------------------------- | -------------------- | ---------------------------------------------------------------------- |
+| Client-side publish limit | 25 MB | [`src/editor/publish.js:17`](../src/editor/publish.js#L17) `MAX_BYTES` |
+| Server-side schema max | 500 MB | [`api/_lib/validate.js:58,63`](../api/_lib/validate.js#L58) |
+| Rate limit (uploads) | 60 per hour per user | `limits.upload(userId)` in presign |
The client enforces 25 MB; the server allows up to 500 MB. A caller bypassing the client library can upload up to 500 MB.
@@ -498,12 +514,14 @@ The presign flow issues a PUT URL for direct browser-to-R2 upload; the server ne
This document covers `agent-editor/0.1`. Breaking changes bump the minor until 1.0; after 1.0 they bump the major.
A **breaking change** is:
+
- Removing or renaming a published export from any `src/editor/*.js` module.
- Changing the shape of `materialEdits`, `transformEdits`, or `visibilityEdits` in a way that breaks `restoreEdits()` round-trips.
- Changing the publish API endpoints or their response shapes.
- Removing an attribute that the embed editor reads or writes.
A **non-breaking change** is:
+
- Adding new optional fields to patch objects.
- Adding new dat.gui controls.
- New `onStep` step names (callers should ignore unknown steps).
@@ -521,13 +539,13 @@ Until then, feature-detect by checking whether the `Editor` class is exported fr
## Pre-1.0 rough edges — summary
-| # | Location | Issue |
-|---|---|---|
-| 1 | [`src/element.js:211`](../src/element.js#L211) | `editor` boolean attribute not wired — `<agent-3d editor>` does not activate the editor |
-| 2 | [`src/editor/material-editor.js:100`](../src/editor/material-editor.js#L100) | `emissiveIntensity` changes are not recorded to session — lost on export |
-| 3 | [`src/editor/glb-export.js:106`](../src/editor/glb-export.js#L106) | Hidden nodes written as `scale=[0,0,0]` instead of `KHR_node_visibility` |
-| 4 | [`src/editor/glb-export.js:53`](../src/editor/glb-export.js#L53) | Duplicate material/node names resolve to first match only — no warning |
-| 5 | [`src/editor/index.js`](../src/editor/index.js) | No DOM `CustomEvent` emitted — external hosts cannot observe edit activity without accessing `session.onChange()` directly |
+| # | Location | Issue |
+| --- | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
+| 1 | [`src/element.js:211`](../src/element.js#L211) | `editor` boolean attribute not wired — `<agent-3d editor>` does not activate the editor |
+| 2 | [`src/editor/material-editor.js:100`](../src/editor/material-editor.js#L100) | `emissiveIntensity` changes are not recorded to session — lost on export |
+| 3 | [`src/editor/glb-export.js:106`](../src/editor/glb-export.js#L106) | Hidden nodes written as `scale=[0,0,0]` instead of `KHR_node_visibility` |
+| 4 | [`src/editor/glb-export.js:53`](../src/editor/glb-export.js#L53) | Duplicate material/node names resolve to first match only — no warning |
+| 5 | [`src/editor/index.js`](../src/editor/index.js) | No DOM `CustomEvent` emitted — external hosts cannot observe edit activity without accessing `session.onChange()` directly |
---
diff --git a/specs/EMBED_HOST_PROTOCOL.md b/specs/EMBED_HOST_PROTOCOL.md
index b80fb3835..8949a0f7b 100644
--- a/specs/EMBED_HOST_PROTOCOL.md
+++ b/specs/EMBED_HOST_PROTOCOL.md
@@ -12,12 +12,12 @@ Every message is a JSON object:
{ "v": 1, "type": "<direction>.<category>", "id": "<optional>", "payload": { ... } }
```
-| Field | Required | Description |
-|---|---|---|
-| `v` | yes | Protocol version integer. Current: `1`. |
-| `type` | yes | Dot-namespaced string. `host.*` or `embed.*`. |
-| `id` | request/response only | Correlation token for request–response pairs. |
-| `payload` | conditional | Type-specific data object. |
+| Field | Required | Description |
+| --------- | --------------------- | --------------------------------------------- |
+| `v` | yes | Protocol version integer. Current: `1`. |
+| `type` | yes | Dot-namespaced string. `host.*` or `embed.*`. |
+| `id` | request/response only | Correlation token for request–response pairs. |
+| `payload` | conditional | Type-specific data object. |
Messages missing `v: 1` or `type` are malformed and MUST be ignored by the receiver (embed sends one `embed.error` diagnostic; host should log and discard).
@@ -31,25 +31,25 @@ Sent once after the iframe load event. Initiates the handshake.
```json
{
- "v": 1,
- "type": "host.hello",
- "payload": {
- "hostName": "claude.ai",
- "hostVersion": "2024-11",
- "hostOrigin": "https://claude.ai",
- "userId": "u_abc123",
- "userName": "Alice"
- }
+ "v": 1,
+ "type": "host.hello",
+ "payload": {
+ "hostName": "claude.ai",
+ "hostVersion": "2024-11",
+ "hostOrigin": "https://claude.ai",
+ "userId": "u_abc123",
+ "userName": "Alice"
+ }
}
```
-| Field | Required | Type |
-|---|---|---|
-| `hostName` | yes | string |
-| `hostVersion` | yes | string |
-| `hostOrigin` | yes | string (origin URL) |
-| `userId` | no | string |
-| `userName` | no | string |
+| Field | Required | Type |
+| ------------- | -------- | ------------------- |
+| `hostName` | yes | string |
+| `hostVersion` | yes | string |
+| `hostOrigin` | yes | string (origin URL) |
+| `userId` | no | string |
+| `userName` | no | string |
---
@@ -59,21 +59,21 @@ Delivers a chat turn into the agent.
```json
{
- "v": 1,
- "type": "host.chat.message",
- "payload": {
- "role": "user",
- "text": "Hello, tell me about yourself.",
- "messageId": "msg_001"
- }
+ "v": 1,
+ "type": "host.chat.message",
+ "payload": {
+ "role": "user",
+ "text": "Hello, tell me about yourself.",
+ "messageId": "msg_001"
+ }
}
```
-| Field | Required | Type |
-|---|---|---|
-| `role` | yes | `"user"` \| `"assistant"` |
-| `text` | yes | string |
-| `messageId` | yes | string (unique per message) |
+| Field | Required | Type |
+| ----------- | -------- | --------------------------- |
+| `role` | yes | `"user"` \| `"assistant"` |
+| `text` | yes | string |
+| `messageId` | yes | string (unique per message) |
---
@@ -83,30 +83,30 @@ Triggers a named action on the agent (emotes, speech, etc.).
```json
{
- "v": 1,
- "type": "host.action",
- "payload": {
- "action": "emote.wave",
- "args": {}
- }
+ "v": 1,
+ "type": "host.action",
+ "payload": {
+ "action": "emote.wave",
+ "args": {}
+ }
}
```
```json
{
- "v": 1,
- "type": "host.action",
- "payload": {
- "action": "speak",
- "args": { "text": "Welcome back!" }
- }
+ "v": 1,
+ "type": "host.action",
+ "payload": {
+ "action": "speak",
+ "args": { "text": "Welcome back!" }
+ }
}
```
-| Field | Required | Type |
-|---|---|---|
-| `action` | yes | string |
-| `args` | no | object |
+| Field | Required | Type |
+| -------- | -------- | ------ |
+| `action` | yes | string |
+| `args` | no | object |
---
@@ -116,17 +116,17 @@ Updates the embed's visual theme.
```json
{
- "v": 1,
- "type": "host.theme",
- "payload": {
- "mode": "dark"
- }
+ "v": 1,
+ "type": "host.theme",
+ "payload": {
+ "mode": "dark"
+ }
}
```
-| Field | Required | Type |
-|---|---|---|
-| `mode` | yes | `"dark"` \| `"light"` |
+| Field | Required | Type |
+| ------ | -------- | --------------------- |
+| `mode` | yes | `"dark"` \| `"light"` |
---
@@ -149,12 +149,12 @@ On error:
```json
{
- "v": 1,
- "type": "host.response",
- "id": "<same id>",
- "payload": {
- "error": { "code": "NOT_FOUND", "message": "resource not found" }
- }
+ "v": 1,
+ "type": "host.response",
+ "id": "<same id>",
+ "payload": {
+ "error": { "code": "NOT_FOUND", "message": "resource not found" }
+ }
}
```
@@ -168,21 +168,21 @@ Sent by the embed after `start()` to announce the agent is live.
```json
{
- "v": 1,
- "type": "embed.ready",
- "payload": {
- "agentId": "agent_xyz",
- "version": "1.0.0",
- "capabilities": ["chat", "emote", "speak"]
- }
+ "v": 1,
+ "type": "embed.ready",
+ "payload": {
+ "agentId": "agent_xyz",
+ "version": "1.0.0",
+ "capabilities": ["chat", "emote", "speak"]
+ }
}
```
-| Field | Required | Type |
-|---|---|---|
-| `agentId` | yes | string |
-| `version` | yes | semver string |
-| `capabilities` | yes | string[] |
+| Field | Required | Type |
+| -------------- | -------- | ------------- |
+| `agentId` | yes | string |
+| `version` | yes | semver string |
+| `capabilities` | yes | string[] |
---
@@ -192,19 +192,19 @@ Generic agent lifecycle or interaction event stream.
```json
{
- "v": 1,
- "type": "embed.event",
- "payload": {
- "event": "agent.speaking",
- "data": { "text": "Hello!" }
- }
+ "v": 1,
+ "type": "embed.event",
+ "payload": {
+ "event": "agent.speaking",
+ "data": { "text": "Hello!" }
+ }
}
```
-| Field | Required | Type |
-|---|---|---|
-| `event` | yes | string |
-| `data` | no | object |
+| Field | Required | Type |
+| ------- | -------- | ------ |
+| `event` | yes | string |
+| `data` | no | object |
Common event names: `agent.speaking`, `agent.idle`, `agent.emote`, `agent.error`.
@@ -216,19 +216,19 @@ Reports a protocol-level error to the host (malformed message received, unsuppor
```json
{
- "v": 1,
- "type": "embed.error",
- "payload": {
- "code": "MALFORMED_MESSAGE",
- "message": "missing v:1 or type"
- }
+ "v": 1,
+ "type": "embed.error",
+ "payload": {
+ "code": "MALFORMED_MESSAGE",
+ "message": "missing v:1 or type"
+ }
}
```
-| Field | Required | Type |
-|---|---|---|
-| `code` | yes | UPPER_SNAKE string |
-| `message` | yes | string |
+| Field | Required | Type |
+| --------- | -------- | ------------------ |
+| `code` | yes | UPPER_SNAKE string |
+| `message` | yes | string |
---
@@ -238,21 +238,21 @@ Ask the host for data or an action. Host replies with `host.response` matching `
```json
{
- "v": 1,
- "type": "embed.request",
- "id": "req_abc",
- "payload": {
- "method": "host.getUser",
- "params": {}
- }
+ "v": 1,
+ "type": "embed.request",
+ "id": "req_abc",
+ "payload": {
+ "method": "host.getUser",
+ "params": {}
+ }
}
```
-| Field | Required | Type |
-|---|---|---|
-| `id` | yes | string (unique per request) |
-| `payload.method` | yes | string |
-| `payload.params` | no | object |
+| Field | Required | Type |
+| ---------------- | -------- | --------------------------- |
+| `id` | yes | string (unique per request) |
+| `payload.method` | yes | string |
+| `payload.params` | no | object |
Default timeout: 5 000 ms. After timeout the pending request rejects with a timeout error.
@@ -281,10 +281,10 @@ The embed sends `embed.ready` immediately on `start()`. The host may send `host.
`EmbedHostBridge` accepts an `allowedOrigins` constructor option:
-| Value | Behaviour |
-|---|---|
-| `'*'` (default) | Accept messages from any `window.parent` origin. |
-| `string[]` | Accept only listed origins (exact match). Example: `['https://claude.ai', 'https://lobehub.com']`. |
+| Value | Behaviour |
+| --------------- | -------------------------------------------------------------------------------------------------- |
+| `'*'` (default) | Accept messages from any `window.parent` origin. |
+| `string[]` | Accept only listed origins (exact match). Example: `['https://claude.ai', 'https://lobehub.com']`. |
Messages from non-parent frames are always rejected regardless of allowlist.
diff --git a/specs/MEMORY_SPEC.md b/specs/MEMORY_SPEC.md
index 68810e9e0..f531456ea 100644
--- a/specs/MEMORY_SPEC.md
+++ b/specs/MEMORY_SPEC.md
@@ -30,18 +30,22 @@ No frontmatter. One line per memory: `- [Title](file.md) — one-line hook`.
# Coach Leo's Memory
## User
+
- [Role](user_role.md) — Argentina fan, plays weekly 5-a-side on Saturdays
- [Preferences](user_preferences.md) — terse feedback, no emojis
## Feedback
+
- [Tone](feedback_tone.md) — stay warm but don't coddle; user asked for direct critique
- [Drill pacing](feedback_pacing.md) — 3 drills per session max
## Project
+
- [Season goal](project_season.md) — user is training for a tournament in June 2026
- [Recovery](project_recovery.md) — knee injury from March; avoid high-impact drills until May
## Reference
+
- [Highlight reel](reference_reel.md) — shared Drive folder where user stores match clips
```
@@ -68,15 +72,15 @@ genuine wins, not every message.
### Frontmatter fields
-| Field | Required | Purpose |
-|---|---|---|
-| `name` | yes | Human-readable title |
-| `description` | yes | One-line, used by the retrieval layer to judge relevance |
-| `type` | yes | `user` \| `feedback` \| `project` \| `reference` |
-| `created` | yes | ISO date |
-| `updated` | yes | ISO date — bump on every edit |
-| `source` | no | What conversation/event produced this memory |
-| `decay` | no | `never` \| `30d` \| `90d` — retrieval-layer decay hint |
+| Field | Required | Purpose |
+| ------------- | -------- | -------------------------------------------------------- |
+| `name` | yes | Human-readable title |
+| `description` | yes | One-line, used by the retrieval layer to judge relevance |
+| `type` | yes | `user` \| `feedback` \| `project` \| `reference` |
+| `created` | yes | ISO date |
+| `updated` | yes | ISO date — bump on every edit |
+| `source` | no | What conversation/event produced this memory |
+| `decay` | no | `never` \| `30d` \| `90d` — retrieval-layer decay hint |
### Types
@@ -140,14 +144,14 @@ Skills and the runtime both write via `ctx.memory.*`:
```js
ctx.memory.write('feedback_tone', {
- name: 'Tone',
- description: 'user wants direct critique, not encouragement-first',
- type: 'feedback',
- body: 'User prefers direct critique...\n\n**Why:** ...\n**How to apply:** ...'
+ name: 'Tone',
+ description: 'user wants direct critique, not encouragement-first',
+ type: 'feedback',
+ body: 'User prefers direct critique...\n\n**Why:** ...\n**How to apply:** ...',
});
-ctx.memory.note('waved', { style: 'casual' }); // timeline
-ctx.memory.read('feedback_tone'); // read single
+ctx.memory.note('waved', { style: 'casual' }); // timeline
+ctx.memory.read('feedback_tone'); // read single
await ctx.memory.recall('how does the user prefer feedback'); // semantic search
```
@@ -175,8 +179,8 @@ Automatic decay (per frontmatter `decay`): retrieval layer down-weights; files a
## Export / import
```js
-const blob = await agent.memory.export(); // tarball of memory/
-await otherAgent.memory.import(blob); // merges with conflict resolution
+const blob = await agent.memory.export(); // tarball of memory/
+await otherAgent.memory.import(blob); // merges with conflict resolution
```
Enables memory-as-inheritance: fork an agent, carry the memories forward.
diff --git a/specs/SKILL_SPEC.md b/specs/SKILL_SPEC.md
index 3e0645cc7..8edf0c516 100644
--- a/specs/SKILL_SPEC.md
+++ b/specs/SKILL_SPEC.md
@@ -31,38 +31,38 @@ skill-name/
```jsonc
{
- "spec": "skill/0.1",
- "name": "wave",
- "version": "0.1.0",
- "description": "Wave at the user with context-appropriate enthusiasm.",
- "author": "0xDeadBeef...", // optional wallet
- "license": "MIT",
- "tags": ["greeting", "gesture", "mixamo-compatible"],
-
- // Compatibility
- "requires": {
- "rig": ["mixamo", "any"], // rigs this skill works with
- "runtime": ">=0.1.0",
- "tools": ["play_clip"] // built-in tools this skill depends on
- },
-
- // Dependencies on other skills (composition)
- "dependencies": {
- "ipfs://bafy.../gesture-base/": "^1.0.0"
- },
-
- // What this skill adds
- "provides": {
- "tools": ["wave"], // declared in tools.json
- "triggers": ["greeting"] // semantic tags for skill discovery
- },
-
- // Content-addressed integrity (optional but recommended)
- "integrity": {
- "SKILL.md": "sha256-...",
- "tools.json": "sha256-...",
- "clips/wave-casual.glb": "sha256-..."
- }
+ "spec": "skill/0.1",
+ "name": "wave",
+ "version": "0.1.0",
+ "description": "Wave at the user with context-appropriate enthusiasm.",
+ "author": "0xDeadBeef...", // optional wallet
+ "license": "MIT",
+ "tags": ["greeting", "gesture", "mixamo-compatible"],
+
+ // Compatibility
+ "requires": {
+ "rig": ["mixamo", "any"], // rigs this skill works with
+ "runtime": ">=0.1.0",
+ "tools": ["play_clip"], // built-in tools this skill depends on
+ },
+
+ // Dependencies on other skills (composition)
+ "dependencies": {
+ "ipfs://bafy.../gesture-base/": "^1.0.0",
+ },
+
+ // What this skill adds
+ "provides": {
+ "tools": ["wave"], // declared in tools.json
+ "triggers": ["greeting"], // semantic tags for skill discovery
+ },
+
+ // Content-addressed integrity (optional but recommended)
+ "integrity": {
+ "SKILL.md": "sha256-...",
+ "tools.json": "sha256-...",
+ "clips/wave-casual.glb": "sha256-...",
+ },
}
```
@@ -75,9 +75,9 @@ Frontmatter + markdown. The LLM sees this as a system-prompt fragment whenever t
name: wave
description: Wave at the user with context-appropriate enthusiasm.
triggers:
- - user_greeting
- - user_farewell
- - introduction
+ - user_greeting
+ - user_farewell
+ - introduction
cost: low
---
@@ -97,12 +97,12 @@ Do not wave more than once per turn. Do not wave if you just waved.
Frontmatter fields:
-| Field | Type | Purpose |
-|---|---|---|
-| `name` | string | Must match `manifest.json` |
-| `description` | string | One-line, used in skill discovery UIs |
-| `triggers` | string[] | Semantic tags — when LLM router sees these, it surfaces the skill |
-| `cost` | `low` \| `medium` \| `high` | Latency/token hint for the runtime to decide eager vs. lazy load |
+| Field | Type | Purpose |
+| ------------- | --------------------------- | ----------------------------------------------------------------- |
+| `name` | string | Must match `manifest.json` |
+| `description` | string | One-line, used in skill discovery UIs |
+| `triggers` | string[] | Semantic tags — when LLM router sees these, it surfaces the skill |
+| `cost` | `low` \| `medium` \| `high` | Latency/token hint for the runtime to decide eager vs. lazy load |
## tools.json
@@ -110,29 +110,29 @@ Standard tool-use schema (Anthropic / OpenAI compatible). This is what the LLM s
```jsonc
{
- "tools": [
- {
- "name": "wave",
- "description": "Wave at the user.",
- "input_schema": {
- "type": "object",
- "properties": {
- "style": {
- "type": "string",
- "enum": ["casual", "enthusiastic", "subtle"],
- "default": "casual"
- },
- "duration_ms": {
- "type": "integer",
- "minimum": 500,
- "maximum": 5000,
- "default": 1500
- }
- },
- "required": []
- }
- }
- ]
+ "tools": [
+ {
+ "name": "wave",
+ "description": "Wave at the user.",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "style": {
+ "type": "string",
+ "enum": ["casual", "enthusiastic", "subtle"],
+ "default": "casual",
+ },
+ "duration_ms": {
+ "type": "integer",
+ "minimum": 500,
+ "maximum": 5000,
+ "default": 1500,
+ },
+ },
+ "required": [],
+ },
+ },
+ ],
}
```
@@ -143,20 +143,21 @@ ES module exporting one function per tool. Receives `(args, context)` where `con
```js
// skills/wave/handlers.js
export async function wave(args, ctx) {
- const { style = 'casual', duration_ms = 1500 } = args;
- const clipUri = new URL(`clips/wave-${style}.glb`, ctx.skillBaseURI).href;
+ const { style = 'casual', duration_ms = 1500 } = args;
+ const clipUri = new URL(`clips/wave-${style}.glb`, ctx.skillBaseURI).href;
- const clip = await ctx.loadClip(clipUri);
- ctx.viewer.play(clip, { duration: duration_ms, blend: 0.2 });
+ const clip = await ctx.loadClip(clipUri);
+ ctx.viewer.play(clip, { duration: duration_ms, blend: 0.2 });
- // Optional — annotate memory so the LLM doesn't double-wave
- ctx.memory.note('just_waved', { at: Date.now(), style });
+ // Optional — annotate memory so the LLM doesn't double-wave
+ ctx.memory.note('just_waved', { at: Date.now(), style });
- return { ok: true, played: style };
+ return { ok: true, played: style };
}
```
Handlers run in a sandboxed scope with a fixed `context` API. **They cannot**:
+
- Import arbitrary modules (only `ctx.*` is available)
- Touch `window` directly
- Make network calls outside `ctx.fetch` (which enforces CORS + IPFS gateway policy)
@@ -166,45 +167,45 @@ Handlers run in a sandboxed scope with a fixed `context` API. **They cannot**:
```ts
interface SkillContext {
- // Scene control
- viewer: {
- play(clip: AnimationClip, opts?: PlayOptions): void;
- stop(clipName?: string): void;
- setExpression(preset: string): void;
- lookAt(target: Vector3 | 'user' | 'camera'): void;
- moveTo(position: Vector3, opts?: MoveOptions): void;
- scene: Scene; // read-only reference
- };
-
- // LLM
- llm: {
- complete(prompt: string, opts?: CompleteOpts): Promise<string>;
- embed(text: string): Promise<Float32Array>;
- };
-
- // Memory
- memory: {
- read(key: string): any;
- write(key: string, value: any): void;
- note(type: string, data: any): void; // appends to a timeline
- recall(query: string): Promise<MemoryEntry[]>;
- };
-
- // Asset loading
- loadClip(uri: string): Promise<AnimationClip>;
- loadGLB(uri: string): Promise<GLTF>;
- loadJSON(uri: string): Promise<any>;
- skillBaseURI: string; // base for relative asset resolution
-
- // Safe network
- fetch(uri: string, opts?: FetchOpts): Promise<Response>;
-
- // Cross-skill calls
- call(toolName: string, args: any): Promise<any>;
-
- // User interaction
- speak(text: string): Promise<void>;
- listen(opts?: ListenOpts): Promise<string>;
+ // Scene control
+ viewer: {
+ play(clip: AnimationClip, opts?: PlayOptions): void;
+ stop(clipName?: string): void;
+ setExpression(preset: string): void;
+ lookAt(target: Vector3 | 'user' | 'camera'): void;
+ moveTo(position: Vector3, opts?: MoveOptions): void;
+ scene: Scene; // read-only reference
+ };
+
+ // LLM
+ llm: {
+ complete(prompt: string, opts?: CompleteOpts): Promise<string>;
+ embed(text: string): Promise<Float32Array>;
+ };
+
+ // Memory
+ memory: {
+ read(key: string): any;
+ write(key: string, value: any): void;
+ note(type: string, data: any): void; // appends to a timeline
+ recall(query: string): Promise<MemoryEntry[]>;
+ };
+
+ // Asset loading
+ loadClip(uri: string): Promise<AnimationClip>;
+ loadGLB(uri: string): Promise<GLTF>;
+ loadJSON(uri: string): Promise<any>;
+ skillBaseURI: string; // base for relative asset resolution
+
+ // Safe network
+ fetch(uri: string, opts?: FetchOpts): Promise<Response>;
+
+ // Cross-skill calls
+ call(toolName: string, args: any): Promise<any>;
+
+ // User interaction
+ speak(text: string): Promise<void>;
+ listen(opts?: ListenOpts): Promise<string>;
}
```
@@ -256,9 +257,9 @@ A skill without `handlers.js` is valid — it's pure prompt engineering + assets
- `ctx.fetch` and `ctx.loadJSON` use the worker's native `fetch` — no main-thread proxy is needed. Standard CORS rules apply (same-origin and credentialed-CORS requests work; cross-origin without CORS headers are blocked by the browser as usual).
- Individual `ctx.*` calls time out after **30 seconds**. A timed-out or errored handler surfaces as `{ error: "..." }` to the runtime without crashing the worker.
- Agent owners set a **skill trust policy** per agent: `trust: "any" | "whitelist" | "owned-only"`.
- - `owned-only` (default) — only run skills signed by the agent's owner wallet.
- - `whitelist` — allow a list of publisher wallets.
- - `any` — wild west, allowed for kiosks/demos.
+ - `owned-only` (default) — only run skills signed by the agent's owner wallet.
+ - `whitelist` — allow a list of publisher wallets.
+ - `any` — wild west, allowed for kiosks/demos.
- Integrity hashes are verified before handlers execute.
### Opt-out: `sandboxPolicy: "trusted-main-thread"`
@@ -267,7 +268,7 @@ Owner-signed skills that require main-thread capabilities (Three.js direct acces
```jsonc
{
- "sandboxPolicy": "trusted-main-thread"
+ "sandboxPolicy": "trusted-main-thread",
}
```
diff --git a/specs/STAGE_SPEC.md b/specs/STAGE_SPEC.md
index 50df91237..5a6e51bd2 100644
--- a/specs/STAGE_SPEC.md
+++ b/specs/STAGE_SPEC.md
@@ -13,9 +13,9 @@ A single-child stage is valid; a zero-child stage is valid (empty room). Stages
## Attributes
-| Attribute | Values | Default | Notes |
-|---|---|---|---|
-| `formation` | `row` \| `circle` \| `freeform` | `row` | Arrangement of children in 3D + screen-space sub-rects. |
+| Attribute | Values | Default | Notes |
+| ----------- | ------------------------------- | ------- | ------------------------------------------------------- |
+| `formation` | `row` \| `circle` \| `freeform` | `row` | Arrangement of children in 3D + screen-space sub-rects. |
Additional scene attributes (`environment`, `camera-controls`, `shadows`, …) mirror `<agent-3d>` and may be added in a later version.
@@ -35,11 +35,11 @@ An `<agent-3d>` outside any `<agent-stage>` falls back to solo mode and behaves
## Formations
-| Value | 3D layout | DOM sub-rect layout |
-|---|---|---|
-| `row` | evenly spaced along the X axis (`spacing = 1.1m`) | vertical slices, equal width |
-| `circle` | evenly spaced around the Y axis on a radius scaled by agent count | vertical slices, equal width |
-| `freeform` | all groups at origin — caller positions via JS | each child fills the stage |
+| Value | 3D layout | DOM sub-rect layout |
+| ---------- | ----------------------------------------------------------------- | ---------------------------- |
+| `row` | evenly spaced along the X axis (`spacing = 1.1m`) | vertical slices, equal width |
+| `circle` | evenly spaced around the Y axis on a radius scaled by agent count | vertical slices, equal width |
+| `freeform` | all groups at origin — caller positions via JS | each child fills the stage |
The `row` and `circle` values are sufficient for most meeting-style layouts. A `grid` value may be added if 6+ agent scenes become common — propose it with a demo.
@@ -48,12 +48,12 @@ The `row` and `circle` values are sufficient for most meeting-style layouts. A `
```ts
interface AgentStageElement extends HTMLElement {
formation: 'row' | 'circle' | 'freeform';
- viewer: Viewer; // the shared three.js Viewer
+ viewer: Viewer; // the shared three.js Viewer
addAgent(manifest: object): Promise<HTMLElement>;
removeAgent(agentId: string): void;
- getAgents(): Array<{ agentId, name, position: [x,y,z], element }>;
- broadcast(fromId: string, event: unknown): void; // fires 'stage:message' on siblings
- routeMessage(fromId, toId, text): Promise<{ ok, reply?, error? }>;
+ getAgents(): Array<{ agentId; name; position: [x, y, z]; element }>;
+ broadcast(fromId: string, event: unknown): void; // fires 'stage:message' on siblings
+ routeMessage(fromId, toId, text): Promise<{ ok; reply?; error? }>;
}
```
@@ -63,11 +63,11 @@ interface AgentStageElement extends HTMLElement {
All events bubble and are `composed: true`.
-| Type | Detail | Fired on |
-|---|---|---|
-| `stage:agent-joined` | `{ agentId, element, manifest }` | stage |
-| `stage:agent-left` | `{ agentId, element }` | stage |
-| `stage:message` | `{ from, event }` | stage (and each non-sender child when using `broadcast`) |
+| Type | Detail | Fired on |
+| -------------------- | -------------------------------- | -------------------------------------------------------- |
+| `stage:agent-joined` | `{ agentId, element, manifest }` | stage |
+| `stage:agent-left` | `{ agentId, element }` | stage |
+| `stage:message` | `{ from, event }` | stage (and each non-sender child when using `broadcast`) |
`broadcast(fromId, event)` fires `stage:message` on every `<agent-3d>` except the sender, and once on the stage itself. The payload is opaque — the message protocol is whatever the agents in the stage agree on.
@@ -76,9 +76,11 @@ All events bubble and are `composed: true`.
When a `Runtime` is attached to a stage, two extra tools are appended to its tool list automatically. They are not present in solo mode.
### `observe_agents`
+
Returns `{ ok: true, agents: [{ agentId, name, position }] }` listing every other agent on the stage (the caller is excluded).
### `say_to_agent(agentId, text)`
+
Routes `text` into the target agent's runtime as a user turn formatted `[from <callerId>] <text>`. Also fires a `stage:message` broadcast with `{ kind: 'direct', to: agentId, text }` so spectators can observe the exchange.
Returns `{ ok: true, reply }` where `reply` is the target's final text, or `{ ok: false, error }` on a bad id.
diff --git a/src/account.js b/src/account.js
index 2eb8a15d2..509857dcd 100644
--- a/src/account.js
+++ b/src/account.js
@@ -46,17 +46,25 @@ export function readAuthHint() {
const { authed, ts } = JSON.parse(raw);
if (!ts || Date.now() - ts > AUTH_HINT_TTL_MS) return null;
return authed ? 'true' : 'false';
- } catch { return null; }
+ } catch {
+ return null;
+ }
}
function writeAuthHint(authed) {
try {
localStorage.setItem(AUTH_HINT_KEY, JSON.stringify({ authed: !!authed, ts: Date.now() }));
- } catch { /* quota or disabled storage */ }
+ } catch {
+ /* quota or disabled storage */
+ }
}
export function clearAuthHint() {
- try { localStorage.removeItem(AUTH_HINT_KEY); } catch { /* ignore */ }
+ try {
+ localStorage.removeItem(AUTH_HINT_KEY);
+ } catch {
+ /* ignore */
+ }
}
export async function getMe() {
@@ -134,8 +142,14 @@ async function postJson(path, body) {
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
});
- const data = res.headers.get('content-type')?.includes('application/json') ? await res.json() : null;
- if (!res.ok) throw Object.assign(new Error(data?.error_description || res.statusText), { status: res.status, data });
+ const data = res.headers.get('content-type')?.includes('application/json')
+ ? await res.json()
+ : null;
+ if (!res.ok)
+ throw Object.assign(new Error(data?.error_description || res.statusText), {
+ status: res.status,
+ data,
+ });
return data;
}
diff --git a/src/agent-accessories.js b/src/agent-accessories.js
index 0bc74870f..92ced53d8 100644
--- a/src/agent-accessories.js
+++ b/src/agent-accessories.js
@@ -124,7 +124,9 @@ export class AccessoryManager {
const bone = _findBone(this.viewer?.content, preset.attachBone);
if (!bone) {
- console.warn(`[accessories] bone not found: ${preset.attachBone} (preset: ${preset.id})`);
+ console.warn(
+ `[accessories] bone not found: ${preset.attachBone} (preset: ${preset.id})`,
+ );
// Still record as applied so list() and removePreset() work correctly
this._applied.set(preset.id, { preset, object: null });
return;
diff --git a/src/agent-home.js b/src/agent-home.js
index 16498fb0f..fc30cbd9b 100644
--- a/src/agent-home.js
+++ b/src/agent-home.js
@@ -9,27 +9,27 @@
*/
import { ACTION_TYPES } from './agent-protocol.js';
-import { MEMORY_TYPES } from './agent-memory.js';
+import { MEMORY_TYPES } from './agent-memory.js';
const ACTION_ICONS = {
- [ACTION_TYPES.SPEAK]: '💬',
- [ACTION_TYPES.REMEMBER]: '🧠',
- [ACTION_TYPES.SIGN]: '✍️',
+ [ACTION_TYPES.SPEAK]: '💬',
+ [ACTION_TYPES.REMEMBER]: '🧠',
+ [ACTION_TYPES.SIGN]: '✍️',
[ACTION_TYPES.PERFORM_SKILL]: '⚡',
- [ACTION_TYPES.SKILL_DONE]: '✓',
- [ACTION_TYPES.SKILL_ERROR]: '⚠',
- [ACTION_TYPES.LOAD_END]: '📦',
- [ACTION_TYPES.VALIDATE]: '🔍',
- default: '·',
+ [ACTION_TYPES.SKILL_DONE]: '✓',
+ [ACTION_TYPES.SKILL_ERROR]: '⚠',
+ [ACTION_TYPES.LOAD_END]: '📦',
+ [ACTION_TYPES.VALIDATE]: '🔍',
+ default: '·',
};
const EMOTION_LABELS = {
- neutral: 'calm',
- concern: 'focused',
+ neutral: 'calm',
+ concern: 'focused',
celebration: 'excited',
- patience: 'patient',
- curiosity: 'curious',
- empathy: 'empathetic',
+ patience: 'patient',
+ curiosity: 'curious',
+ empathy: 'empathetic',
};
export class AgentHome {
@@ -41,11 +41,11 @@ export class AgentHome {
*/
constructor(containerEl, identity, protocol, avatar = null) {
this.container = containerEl;
- this.identity = identity;
- this.protocol = protocol;
- this.avatar = avatar;
+ this.identity = identity;
+ this.protocol = protocol;
+ this.avatar = avatar;
- this._panel = null;
+ this._panel = null;
this._timeline = [];
this._maxTimeline = 30;
this._emotionInterval = null;
@@ -69,11 +69,11 @@ export class AgentHome {
// ── Identity Card ─────────────────────────────────────────────────────────
_buildPanel() {
- const id = this.identity;
+ const id = this.identity;
const skills = id.skills || [];
- const panel = document.createElement('div');
- panel.className = 'agent-home-panel';
- panel.innerHTML = `
+ const panel = document.createElement('div');
+ panel.className = 'agent-home-panel';
+ panel.innerHTML = `
<div class="agent-home-identity">
<div class="agent-home-avatar-ring" id="agent-avatar-ring">
<div class="agent-home-avatar-inner" id="agent-avatar-inner">
@@ -83,10 +83,14 @@ export class AgentHome {
<div class="agent-home-info">
<div class="agent-home-name-row">
<span class="agent-home-name" id="agent-home-name">${_esc(id.name)}</span>
- ${id.isRegistered ? `
+ ${
+ id.isRegistered
+ ? `
<span class="agent-home-badge erc8004" title="Registered on-chain (ERC-8004)">
<svg width="9" height="9" viewBox="0 0 24 24" fill="currentColor"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/></svg>
- </span>` : ''}
+ </span>`
+ : ''
+ }
</div>
<div class="agent-home-status" id="agent-home-status">
<span class="agent-home-dot online"></span>
@@ -100,7 +104,9 @@ export class AgentHome {
</button>
</div>
- ${skills.length ? `
+ ${
+ skills.length
+ ? `
<details class="agent-home-skills" id="agent-skills-details">
<summary class="agent-home-skills-summary">
<span class="agent-home-skills-label">Skills</span>
@@ -108,10 +114,12 @@ export class AgentHome {
<svg class="agent-home-chevron" width="10" height="10" viewBox="0 0 24 24" fill="currentColor"><path d="M7.41 8.59L12 13.17l4.59-4.58L18 10l-6 6-6-6z"/></svg>
</summary>
<div class="agent-home-skills-strip" id="agent-skills-strip">
- ${skills.map(s => `<span class="agent-skill-chip">${_esc(s)}</span>`).join('')}
+ ${skills.map((s) => `<span class="agent-skill-chip">${_esc(s)}</span>`).join('')}
</div>
</details>
- ` : ''}
+ `
+ : ''
+ }
<div class="agent-home-memory-bar" id="agent-memory-bar">
${this._renderMemoryBar()}
@@ -144,14 +152,19 @@ export class AgentHome {
const stats = this.identity.memory.stats;
if (!stats.total) return '<span class="agent-mem-empty">no memories yet</span>';
- return Object.entries(stats)
- .filter(([k]) => k !== 'total')
- .filter(([, v]) => v > 0)
- .map(([type, count]) => `
+ return (
+ Object.entries(stats)
+ .filter(([k]) => k !== 'total')
+ .filter(([, v]) => v > 0)
+ .map(
+ ([type, count]) => `
<span class="agent-mem-chip" data-type="${type}" title="${count} ${type} ${count === 1 ? 'memory' : 'memories'}">
${_memIcon(type)} ${count}
</span>
- `).join('') + `<span class="agent-mem-total">${stats.total}</span>`;
+ `,
+ )
+ .join('') + `<span class="agent-mem-total">${stats.total}</span>`
+ );
}
_refreshMemoryBar() {
@@ -208,15 +221,18 @@ export class AgentHome {
// Update the emotion label in the status bar every second
this._emotionInterval = setInterval(() => {
if (!this.avatar) return;
- const state = this.avatar.emotionState;
- const dominant = Object.entries(state).reduce((a, b) => b[1] > a[1] ? b : a, ['neutral', 0]);
- const label = EMOTION_LABELS[dominant[0]] || 'present';
+ const state = this.avatar.emotionState;
+ const dominant = Object.entries(state).reduce(
+ (a, b) => (b[1] > a[1] ? b : a),
+ ['neutral', 0],
+ );
+ const label = EMOTION_LABELS[dominant[0]] || 'present';
const el = this._panel?.querySelector('#agent-home-emotion-label');
if (el && el.textContent !== label) {
el.style.opacity = '0';
setTimeout(() => {
- el.textContent = label;
+ el.textContent = label;
el.style.opacity = '1';
}, 150);
}
@@ -241,15 +257,18 @@ export class AgentHome {
if (!btn) return;
const orig = btn.innerHTML;
btn.textContent = text;
- setTimeout(() => { btn.innerHTML = orig; }, 1500);
+ setTimeout(() => {
+ btn.innerHTML = orig;
+ }, 1500);
}
}
// ── Rendering Helpers ─────────────────────────────────────────────────────────
function _esc(str) {
- return String(str || '').replace(/[<>&"]/g, c =>
- ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' }[c])
+ return String(str || '').replace(
+ /[<>&"]/g,
+ (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' })[c],
);
}
@@ -264,7 +283,7 @@ function _memIcon(type) {
function _relTime(ts) {
const diff = Date.now() - ts;
- if (diff < 60_000) return 'just now';
+ if (diff < 60_000) return 'just now';
if (diff < 3_600_000) return `${Math.floor(diff / 60_000)}m ago`;
if (diff < 86_400_000) return `${Math.floor(diff / 3_600_000)}h ago`;
return new Date(ts).toLocaleDateString();
@@ -274,7 +293,7 @@ function _timelineText(action) {
const p = action.payload || {};
switch (action.type) {
case ACTION_TYPES.SPEAK:
- return _esc((p.text || '').slice(0, 80) + ((p.text?.length > 80) ? '…' : ''));
+ return _esc((p.text || '').slice(0, 80) + (p.text?.length > 80 ? '…' : ''));
case ACTION_TYPES.REMEMBER:
return _esc(`Remembered: ${(p.content || '').slice(0, 60)}`);
case ACTION_TYPES.PERFORM_SKILL:
diff --git a/src/agent-identity.js b/src/agent-identity.js
index 2eb265890..f95351a7f 100644
--- a/src/agent-identity.js
+++ b/src/agent-identity.js
@@ -33,10 +33,10 @@ export class AgentIdentity {
* @param {{ userId?: string, agentId?: string, autoLoad?: boolean }} [opts]
*/
constructor({ userId = null, agentId = null, autoLoad = true } = {}) {
- this.userId = userId;
+ this.userId = userId;
this._record = null;
this._loaded = false;
- this.memory = null;
+ this.memory = null;
// Pre-seed agentId from arg or storage so callers can use it synchronously
this._agentId = agentId || this._readStoredId();
@@ -46,17 +46,39 @@ export class AgentIdentity {
// ── Public getters ────────────────────────────────────────────────────────
- get id() { return this._record?.id || this._agentId; }
- get name() { return this._record?.name || 'Agent'; }
- get description() { return this._record?.description || ''; }
- get avatarId() { return this._record?.avatarId || null; }
- get homeUrl() { return this._record?.homeUrl || (this.id ? `/agent/${this.id}` : null); }
- get walletAddress() { return this._record?.walletAddress || null; }
- get chainId() { return this._record?.chainId || null; }
- get skills() { return this._record?.skills || []; }
- get meta() { return this._record?.meta || {}; }
- get isLoaded() { return this._loaded; }
- get isRegistered() { return Boolean(this._record?.isRegistered); }
+ get id() {
+ return this._record?.id || this._agentId;
+ }
+ get name() {
+ return this._record?.name || 'Agent';
+ }
+ get description() {
+ return this._record?.description || '';
+ }
+ get avatarId() {
+ return this._record?.avatarId || null;
+ }
+ get homeUrl() {
+ return this._record?.homeUrl || (this.id ? `/agent/${this.id}` : null);
+ }
+ get walletAddress() {
+ return this._record?.walletAddress || null;
+ }
+ get chainId() {
+ return this._record?.chainId || null;
+ }
+ get skills() {
+ return this._record?.skills || [];
+ }
+ get meta() {
+ return this._record?.meta || {};
+ }
+ get isLoaded() {
+ return this._loaded;
+ }
+ get isRegistered() {
+ return Boolean(this._record?.isRegistered);
+ }
// ── Load + Save ───────────────────────────────────────────────────────────
@@ -73,11 +95,11 @@ export class AgentIdentity {
headers: { 'content-type': 'application/json' },
credentials: 'include',
body: JSON.stringify({
- name: this._record.name,
+ name: this._record.name,
description: this._record.description,
- avatar_id: this._record.avatarId,
- skills: this._record.skills,
- meta: this._record.meta,
+ avatar_id: this._record.avatarId,
+ skills: this._record.skills,
+ meta: this._record.meta,
}),
});
if (resp.ok) {
@@ -85,7 +107,9 @@ export class AgentIdentity {
this._record = _normalise(agent);
this._persist();
}
- } catch { /* localStorage is authoritative */ }
+ } catch {
+ /* localStorage is authoritative */
+ }
}
/**
@@ -135,9 +159,9 @@ export class AgentIdentity {
headers: { 'content-type': 'application/json' },
credentials: 'include',
body: JSON.stringify({
- agent_id: this.id,
- type: action.type,
- payload: action.payload,
+ agent_id: this.id,
+ type: action.type,
+ payload: action.payload,
source_skill: action.sourceSkill || null,
}),
}).catch(() => {}); // non-critical
@@ -186,26 +210,26 @@ export class AgentIdentity {
// 1. Try localStorage first (instant)
const local = this._readLocal();
if (local) {
- this._record = local;
+ this._record = local;
this._agentId = local.id;
- this._loaded = true;
- this.memory = new AgentMemory(local.id, { backendSync: true });
+ this._loaded = true;
+ this.memory = new AgentMemory(local.id, { backendSync: true });
}
// 2. Try backend (authoritative if user is signed in)
try {
const agentId = this._agentId;
- const url = agentId ? `/api/agents/${agentId}` : '/api/agents/me';
- const resp = await fetch(url, { credentials: 'include' });
+ const url = agentId ? `/api/agents/${agentId}` : '/api/agents/me';
+ const resp = await fetch(url, { credentials: 'include' });
if (resp.ok) {
const { agent } = await resp.json();
// Server returns { agent: null } for anonymous /me — treat as
// "no server identity" and fall through to local-only.
if (agent) {
- this._record = _normalise(agent);
+ this._record = _normalise(agent);
this._agentId = this._record.id;
- this._loaded = true;
+ this._loaded = true;
this._persist();
if (!this.memory) {
this.memory = new AgentMemory(this._record.id, { backendSync: true });
@@ -218,20 +242,20 @@ export class AgentIdentity {
// one, otherwise synthesize a local-only identity. Tolerant of 5xx
// so a backend blip doesn't brick the avatar for the visitor.
if (!this._record) {
- this._record = _makeDefault(this._agentId);
+ this._record = _makeDefault(this._agentId);
this._agentId = this._record.id;
- this._loaded = true;
+ this._loaded = true;
this._persist();
- this.memory = new AgentMemory(this._agentId, { backendSync: false });
+ this.memory = new AgentMemory(this._agentId, { backendSync: false });
}
} catch {
// Offline — use local record if we have one
if (!this._record) {
- this._record = _makeDefault(this._agentId);
+ this._record = _makeDefault(this._agentId);
this._agentId = this._record.id;
- this._loaded = true;
+ this._loaded = true;
this._persist();
- this.memory = new AgentMemory(this._agentId, { backendSync: false });
+ this.memory = new AgentMemory(this._agentId, { backendSync: false });
}
}
}
@@ -264,7 +288,7 @@ export class AgentIdentity {
function _uuid() {
if (typeof crypto !== 'undefined' && crypto.randomUUID) return crypto.randomUUID();
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0;
return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
});
@@ -272,34 +296,34 @@ function _uuid() {
function _makeDefault(existingId) {
return {
- id: existingId || _uuid(),
- name: 'Agent',
- description: 'A 3D AI agent',
- avatarId: null,
- homeUrl: null,
+ id: existingId || _uuid(),
+ name: 'Agent',
+ description: 'A 3D AI agent',
+ avatarId: null,
+ homeUrl: null,
walletAddress: null,
- chainId: null,
- skills: ['greet', 'present-model', 'validate-model', 'remember', 'think'],
- meta: {},
- createdAt: Date.now(),
+ chainId: null,
+ skills: ['greet', 'present-model', 'validate-model', 'remember', 'think'],
+ meta: {},
+ createdAt: Date.now(),
isRegistered: false,
};
}
function _normalise(apiRecord) {
return {
- id: apiRecord.id,
- name: apiRecord.name || 'Agent',
- description: apiRecord.description || '',
- avatarId: apiRecord.avatar_id || apiRecord.avatarId || null,
- homeUrl: apiRecord.home_url || apiRecord.homeUrl || `/agent/${apiRecord.id}`,
+ id: apiRecord.id,
+ name: apiRecord.name || 'Agent',
+ description: apiRecord.description || '',
+ avatarId: apiRecord.avatar_id || apiRecord.avatarId || null,
+ homeUrl: apiRecord.home_url || apiRecord.homeUrl || `/agent/${apiRecord.id}`,
walletAddress: apiRecord.wallet_address || apiRecord.walletAddress || null,
- chainId: apiRecord.chain_id || apiRecord.chainId || null,
- skills: apiRecord.skills || [],
- meta: apiRecord.meta || {},
- createdAt: apiRecord.created_at
+ chainId: apiRecord.chain_id || apiRecord.chainId || null,
+ skills: apiRecord.skills || [],
+ meta: apiRecord.meta || {},
+ createdAt: apiRecord.created_at
? new Date(apiRecord.created_at).getTime()
- : (apiRecord.createdAt || Date.now()),
- isRegistered: Boolean(apiRecord.erc8004_agent_id || apiRecord.isRegistered),
+ : apiRecord.createdAt || Date.now(),
+ isRegistered: Boolean(apiRecord.erc8004_agent_id || apiRecord.isRegistered),
};
}
diff --git a/src/agent-memory.js b/src/agent-memory.js
index 6f2ad11b4..8a702eceb 100644
--- a/src/agent-memory.js
+++ b/src/agent-memory.js
@@ -12,9 +12,9 @@
*/
export const MEMORY_TYPES = {
- USER: 'user',
- FEEDBACK: 'feedback',
- PROJECT: 'project',
+ USER: 'user',
+ FEEDBACK: 'feedback',
+ PROJECT: 'project',
REFERENCE: 'reference',
};
@@ -36,11 +36,11 @@ export class AgentMemory {
* @param {{ backendSync?: boolean }} [opts]
*/
constructor(agentId, { backendSync = false } = {}) {
- this.agentId = agentId;
+ this.agentId = agentId;
this.backendSync = backendSync;
- this._entries = [];
- this._dirty = false;
- this._syncTimer = null;
+ this._entries = [];
+ this._dirty = false;
+ this._syncTimer = null;
this._hydrate();
}
@@ -57,11 +57,11 @@ export class AgentMemory {
const now = Date.now();
const mem = {
id,
- type: entry.type || MEMORY_TYPES.PROJECT,
- content: String(entry.content).trim(),
- tags: Array.isArray(entry.tags) ? entry.tags : [],
- context: entry.context || {},
- salience: _computeSalience(entry, now),
+ type: entry.type || MEMORY_TYPES.PROJECT,
+ content: String(entry.content).trim(),
+ tags: Array.isArray(entry.tags) ? entry.tags : [],
+ context: entry.context || {},
+ salience: _computeSalience(entry, now),
createdAt: now,
expiresAt: entry.expiresAt || null,
};
@@ -77,12 +77,12 @@ export class AgentMemory {
*/
query({ type, tags, limit = 50, since = 0 } = {}) {
const now = Date.now();
- let results = this._entries.filter(m => {
- if (m.expiresAt && m.expiresAt < now) return false;
- if (m.createdAt < since) return false;
- if (type && m.type !== type) return false;
+ let results = this._entries.filter((m) => {
+ if (m.expiresAt && m.expiresAt < now) return false;
+ if (m.createdAt < since) return false;
+ if (type && m.type !== type) return false;
if (tags && tags.length) {
- const hasTags = tags.every(t => m.tags.includes(t));
+ const hasTags = tags.every((t) => m.tags.includes(t));
if (!hasTags) return false;
}
return true;
@@ -103,7 +103,7 @@ export class AgentMemory {
* @param {string} id
*/
forget(id) {
- const idx = this._entries.findIndex(m => m.id === id);
+ const idx = this._entries.findIndex((m) => m.id === id);
if (idx !== -1) {
this._entries.splice(idx, 1);
this._persist();
@@ -117,7 +117,7 @@ export class AgentMemory {
*/
clear(type) {
if (type) {
- this._entries = this._entries.filter(m => m.type !== type);
+ this._entries = this._entries.filter((m) => m.type !== type);
} else {
this._entries = [];
}
@@ -133,7 +133,7 @@ export class AgentMemory {
get stats() {
const s = {};
for (const t of Object.values(MEMORY_TYPES)) {
- s[t] = this._entries.filter(m => m.type === t).length;
+ s[t] = this._entries.filter((m) => m.type === t).length;
}
s.total = this._entries.length;
return s;
@@ -166,14 +166,16 @@ export class AgentMemory {
} catch {
// localStorage quota exceeded — prune oldest low-salience entries
this._prune();
- try { localStorage.setItem(this._storageKey(), JSON.stringify(this._entries)); } catch {}
+ try {
+ localStorage.setItem(this._storageKey(), JSON.stringify(this._entries));
+ } catch {}
}
}
_prune() {
// Remove expired, then lowest salience until we're under 150 entries
const now = Date.now();
- this._entries = this._entries.filter(m => !m.expiresAt || m.expiresAt > now);
+ this._entries = this._entries.filter((m) => !m.expiresAt || m.expiresAt > now);
if (this._entries.length > 150) {
this._entries.sort((a, b) => b.salience - a.salience);
this._entries = this._entries.slice(0, 150);
@@ -195,7 +197,9 @@ export class AgentMemory {
credentials: 'include',
body: JSON.stringify({ agentId: this.agentId, entry }),
});
- } catch { /* non-critical — localStorage is authoritative */ }
+ } catch {
+ /* non-critical — localStorage is authoritative */
+ }
}
async _syncForget(id) {
@@ -217,8 +221,8 @@ export class AgentMemory {
if (!Array.isArray(entries)) return;
// Merge: backend entries that don't exist locally win
- const localIds = new Set(this._entries.map(m => m.id));
- const newEntries = entries.filter(m => !localIds.has(m.id));
+ const localIds = new Set(this._entries.map((m) => m.id));
+ const newEntries = entries.filter((m) => !localIds.has(m.id));
if (newEntries.length) {
this._entries.push(...newEntries);
this._persist();
@@ -231,7 +235,7 @@ export class AgentMemory {
function _uuid() {
if (typeof crypto !== 'undefined' && crypto.randomUUID) return crypto.randomUUID();
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0;
return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
});
@@ -250,7 +254,7 @@ function _computeSalience(entry, now) {
function _recencyBoost(createdAt, now) {
// Exponential decay with 7-day half-life
- const ageMs = now - createdAt;
+ const ageMs = now - createdAt;
const halfLife = 7 * 24 * 60 * 60 * 1000;
- return Math.exp(-0.693 * ageMs / halfLife);
+ return Math.exp((-0.693 * ageMs) / halfLife);
}
diff --git a/src/agent-protocol.js b/src/agent-protocol.js
index 7a8dbac91..4e3535e3f 100644
--- a/src/agent-protocol.js
+++ b/src/agent-protocol.js
@@ -8,20 +8,20 @@
*/
export const ACTION_TYPES = {
- SPEAK: 'speak', // agent says something (text + sentiment)
- THINK: 'think', // agent is processing (internal monologue)
- GESTURE: 'gesture', // named body gesture (point, wave, nod, shrug)
- EMOTE: 'emote', // direct emotion injection (concern, celebrate…)
- LOOK_AT: 'look-at', // agent looks at a world position or object
+ SPEAK: 'speak', // agent says something (text + sentiment)
+ THINK: 'think', // agent is processing (internal monologue)
+ GESTURE: 'gesture', // named body gesture (point, wave, nod, shrug)
+ EMOTE: 'emote', // direct emotion injection (concern, celebrate…)
+ LOOK_AT: 'look-at', // agent looks at a world position or object
PERFORM_SKILL: 'perform-skill', // a skill is starting execution
- SKILL_DONE: 'skill-done', // a skill finished (success + result payload)
- SKILL_ERROR: 'skill-error', // a skill failed
- REMEMBER: 'remember', // agent stored a memory
- SIGN: 'sign', // agent signs an action with its wallet
- LOAD_START: 'load-start', // model/asset loading started
- LOAD_END: 'load-end', // model/asset loading finished
- VALIDATE: 'validate', // validation result (errors, warnings, hints)
- PRESENCE: 'presence', // agent came online / went idle
+ SKILL_DONE: 'skill-done', // a skill finished (success + result payload)
+ SKILL_ERROR: 'skill-error', // a skill failed
+ REMEMBER: 'remember', // agent stored a memory
+ SIGN: 'sign', // agent signs an action with its wallet
+ LOAD_START: 'load-start', // model/asset loading started
+ LOAD_END: 'load-end', // model/asset loading finished
+ VALIDATE: 'validate', // validation result (errors, warnings, hints)
+ PRESENCE: 'presence', // agent came online / went idle
};
/**
@@ -46,10 +46,10 @@ class AgentProtocol extends EventTarget {
*/
emit(action) {
const full = {
- type: action.type,
- payload: action.payload || {},
- timestamp: Date.now(),
- agentId: action.agentId || 'default',
+ type: action.type,
+ payload: action.payload || {},
+ timestamp: Date.now(),
+ agentId: action.agentId || 'default',
sourceSkill: action.sourceSkill || null,
};
@@ -102,7 +102,7 @@ class AgentProtocol extends EventTarget {
/** Returns last N actions of a given type */
recent(type, n = 10) {
- return this._history.filter(a => a.type === type).slice(-n);
+ return this._history.filter((a) => a.type === type).slice(-n);
}
_wrap(type, handler, once) {
diff --git a/src/agent-resolver.js b/src/agent-resolver.js
index cd8cb8350..5215a3309 100644
--- a/src/agent-resolver.js
+++ b/src/agent-resolver.js
@@ -17,16 +17,25 @@ async function fetchJSON(url, { fetchFn }) {
try {
res = await fetchFn(url, { credentials: 'include' });
} catch (err) {
- throw new AgentResolveError('network', `network error fetching ${url}: ${err.message || err}`);
+ throw new AgentResolveError(
+ 'network',
+ `network error fetching ${url}: ${err.message || err}`,
+ );
}
if (res.status === 401 || res.status === 403) {
- throw new AgentResolveError('unauthorized', `unauthorized fetching ${url} (${res.status})`, { status: res.status });
+ throw new AgentResolveError(
+ 'unauthorized',
+ `unauthorized fetching ${url} (${res.status})`,
+ { status: res.status },
+ );
}
if (res.status === 404) {
throw new AgentResolveError('not_found', `resource not found: ${url}`, { status: 404 });
}
if (!res.ok) {
- throw new AgentResolveError('network', `request failed: ${url} (${res.status})`, { status: res.status });
+ throw new AgentResolveError('network', `request failed: ${url} (${res.status})`, {
+ status: res.status,
+ });
}
try {
return await res.json();
@@ -60,15 +69,22 @@ export async function resolveByAgentId(agentId, signal) {
res = await fetch(endpoint, { credentials: 'include', signal });
} catch (err) {
if (err?.name === 'AbortError') throw err;
- throw new AgentResolveError('network', `network error fetching ${endpoint}: ${err.message || err}`);
+ throw new AgentResolveError(
+ 'network',
+ `network error fetching ${endpoint}: ${err.message || err}`,
+ );
}
if (res.status === 404)
throw new AgentResolveError('not-found', `agent ${agentId} not found`, { status: 404 });
if (res.status === 401 || res.status === 403)
- throw new AgentResolveError('unauthorized', `unauthorized (${res.status})`, { status: res.status });
+ throw new AgentResolveError('unauthorized', `unauthorized (${res.status})`, {
+ status: res.status,
+ });
if (!res.ok)
- throw new AgentResolveError('network', `request failed (${res.status})`, { status: res.status });
+ throw new AgentResolveError('network', `request failed (${res.status})`, {
+ status: res.status,
+ });
let data;
try {
@@ -93,12 +109,17 @@ export async function resolveByAgentId(agentId, signal) {
return resolved;
}
-export async function resolveAgentById(agentId, { origin = typeof location !== 'undefined' ? location.origin : '', fetchFn = fetch } = {}) {
+export async function resolveAgentById(
+ agentId,
+ { origin = typeof location !== 'undefined' ? location.origin : '', fetchFn = fetch } = {},
+) {
if (!agentId) throw new AgentResolveError('not_found', 'agentId required');
const boundFetch = fetchFn.bind(typeof globalThis !== 'undefined' ? globalThis : undefined);
- const agentRes = await fetchJSON(`${origin}/api/agents/${encodeURIComponent(agentId)}`, { fetchFn: boundFetch });
+ const agentRes = await fetchJSON(`${origin}/api/agents/${encodeURIComponent(agentId)}`, {
+ fetchFn: boundFetch,
+ });
const agent = agentRes?.agent;
if (!agent) throw new AgentResolveError('not_found', `agent ${agentId} not found`);
@@ -106,7 +127,10 @@ export async function resolveAgentById(agentId, { origin = typeof location !== '
throw new AgentResolveError('no_avatar', `agent ${agentId} has no avatar bound`);
}
- const avatarRes = await fetchJSON(`${origin}/api/avatars/${encodeURIComponent(agent.avatar_id)}`, { fetchFn: boundFetch });
+ const avatarRes = await fetchJSON(
+ `${origin}/api/avatars/${encodeURIComponent(agent.avatar_id)}`,
+ { fetchFn: boundFetch },
+ );
const avatar = avatarRes?.avatar;
if (!avatar || !avatar.url) {
throw new AgentResolveError('no_avatar', `avatar ${agent.avatar_id} has no url`);
diff --git a/src/agent-skills.js b/src/agent-skills.js
index 4a3bd0017..205e8ebcc 100644
--- a/src/agent-skills.js
+++ b/src/agent-skills.js
@@ -11,7 +11,7 @@
*/
import { ACTION_TYPES } from './agent-protocol.js';
-import { MEMORY_TYPES } from './agent-memory.js';
+import { MEMORY_TYPES } from './agent-memory.js';
/**
* @typedef {Object} SkillContext
@@ -49,8 +49,8 @@ export class AgentSkills {
*/
constructor(protocol, memory) {
this.protocol = protocol;
- this.memory = memory;
- this._skills = new Map();
+ this.memory = memory;
+ this._skills = new Map();
this._registerBuiltins();
}
@@ -80,9 +80,9 @@ export class AgentSkills {
/** Returns MCP-compatible tool definitions for exposed skills */
toMcpTools() {
return this.list()
- .filter(s => s.mcpExposed)
- .map(s => ({
- name: `skill_${s.name.replace(/-/g, '_')}`,
+ .filter((s) => s.mcpExposed)
+ .map((s) => ({
+ name: `skill_${s.name.replace(/-/g, '_')}`,
description: s.description,
inputSchema: s.inputSchema || { type: 'object', properties: {} },
}));
@@ -104,48 +104,53 @@ export class AgentSkills {
}
const fullCtx = {
- protocol: this.protocol,
- memory: this.memory,
- identity: ctx.identity || null,
- viewer: ctx.viewer || (typeof window !== 'undefined' ? window.VIEWER?.app?.viewer : null),
+ protocol: this.protocol,
+ memory: this.memory,
+ identity: ctx.identity || null,
+ viewer:
+ ctx.viewer || (typeof window !== 'undefined' ? window.VIEWER?.app?.viewer : null),
isBrowser: typeof window !== 'undefined',
...ctx,
};
// Announce the skill is starting
this.protocol.emit({
- type: ACTION_TYPES.PERFORM_SKILL,
- payload: { skill: name, args, animationHint: skill.animationHint },
- agentId: fullCtx.identity?.id || 'default',
+ type: ACTION_TYPES.PERFORM_SKILL,
+ payload: { skill: name, args, animationHint: skill.animationHint },
+ agentId: fullCtx.identity?.id || 'default',
sourceSkill: name,
});
try {
const result = await skill.handler(args, fullCtx);
this.protocol.emit({
- type: ACTION_TYPES.SKILL_DONE,
- payload: { skill: name, result },
- agentId: fullCtx.identity?.id || 'default',
+ type: ACTION_TYPES.SKILL_DONE,
+ payload: { skill: name, result },
+ agentId: fullCtx.identity?.id || 'default',
sourceSkill: name,
});
// Auto-speak the result if it has output text
if (result.output && fullCtx.isBrowser) {
this.protocol.emit({
- type: ACTION_TYPES.SPEAK,
- payload: { text: result.output, sentiment: result.sentiment ?? 0 },
- agentId: fullCtx.identity?.id || 'default',
+ type: ACTION_TYPES.SPEAK,
+ payload: { text: result.output, sentiment: result.sentiment ?? 0 },
+ agentId: fullCtx.identity?.id || 'default',
sourceSkill: name,
});
}
return result;
} catch (err) {
- const errResult = { success: false, output: `Skill failed: ${err.message}`, sentiment: -0.5 };
+ const errResult = {
+ success: false,
+ output: `Skill failed: ${err.message}`,
+ sentiment: -0.5,
+ };
this.protocol.emit({
- type: ACTION_TYPES.SKILL_ERROR,
- payload: { skill: name, error: err.message },
- agentId: fullCtx.identity?.id || 'default',
+ type: ACTION_TYPES.SKILL_ERROR,
+ payload: { skill: name, error: err.message },
+ agentId: fullCtx.identity?.id || 'default',
sourceSkill: name,
});
return errResult;
@@ -157,19 +162,19 @@ export class AgentSkills {
_registerBuiltins() {
// ── greet ──────────────────────────────────────────────────────────
this.register({
- name: 'greet',
- description: 'Greet the user and introduce the agent',
- instruction: 'Say hello warmly, offer to help with 3D models or agent configuration',
+ name: 'greet',
+ description: 'Greet the user and introduce the agent',
+ instruction: 'Say hello warmly, offer to help with 3D models or agent configuration',
animationHint: 'wave',
- voicePattern: 'Hey! I\'m {{name}}, your 3D agent. Drop a model or ask me anything.',
- mcpExposed: true,
- inputSchema: { type: 'object', properties: { userName: { type: 'string' } } },
+ voicePattern: "Hey! I'm {{name}}, your 3D agent. Drop a model or ask me anything.",
+ mcpExposed: true,
+ inputSchema: { type: 'object', properties: { userName: { type: 'string' } } },
handler: async (args, ctx) => {
- const name = ctx.identity?.name || 'Agent';
+ const name = ctx.identity?.name || 'Agent';
const userName = args.userName ? `, ${args.userName}` : '';
return {
- success: true,
- output: `Hey${userName}! I'm ${name}. Drop a 3D model in or ask me anything — I can validate, present, and remember things about your work.`,
+ success: true,
+ output: `Hey${userName}! I'm ${name}. Drop a 3D model in or ask me anything — I can validate, present, and remember things about your work.`,
sentiment: 0.8,
};
},
@@ -177,76 +182,91 @@ export class AgentSkills {
// ── present-model ─────────────────────────────────────────────────
this.register({
- name: 'present-model',
- description: 'Narrate and present the currently loaded 3D model',
- instruction: 'Look at the model, describe its properties, gestures toward interesting features',
+ name: 'present-model',
+ description: 'Narrate and present the currently loaded 3D model',
+ instruction:
+ 'Look at the model, describe its properties, gestures toward interesting features',
animationHint: 'present',
- voicePattern: 'This model has {{vertices}} vertices, {{materials}} materials.',
- mcpExposed: true,
- inputSchema: { type: 'object', properties: {} },
+ voicePattern: 'This model has {{vertices}} vertices, {{materials}} materials.',
+ mcpExposed: true,
+ inputSchema: { type: 'object', properties: {} },
handler: async (_args, ctx) => {
const viewer = ctx.viewer;
if (!viewer || !viewer.content) {
- return { success: false, output: 'No model loaded yet. Drop a glTF or GLB file to get started.', sentiment: -0.1 };
+ return {
+ success: false,
+ output: 'No model loaded yet. Drop a glTF or GLB file to get started.',
+ sentiment: -0.1,
+ };
}
- let verts = 0, meshes = 0, mats = new Set();
- viewer.content.traverse(node => {
+ let verts = 0,
+ meshes = 0,
+ mats = new Set();
+ viewer.content.traverse((node) => {
if (node.isMesh) {
meshes++;
if (node.geometry?.attributes?.position) {
verts += node.geometry.attributes.position.count;
}
if (node.material) {
- const m = Array.isArray(node.material) ? node.material : [node.material];
- m.forEach(mat => mats.add(mat.name || mat.uuid));
+ const m = Array.isArray(node.material)
+ ? node.material
+ : [node.material];
+ m.forEach((mat) => mats.add(mat.name || mat.uuid));
}
}
});
- const clips = viewer.clips?.length || 0;
- const bones = (viewer.content.animations || []).length;
+ const clips = viewer.clips?.length || 0;
+ const bones = (viewer.content.animations || []).length;
const output = [
`I'm looking at your model now.`,
`It has ${verts.toLocaleString()} vertices across ${meshes} mesh${meshes !== 1 ? 'es' : ''},`,
`${mats.size} material${mats.size !== 1 ? 's' : ''},`,
- clips ? `and ${clips} animation clip${clips !== 1 ? 's' : ''}.` : 'with no animations.',
+ clips
+ ? `and ${clips} animation clip${clips !== 1 ? 's' : ''}.`
+ : 'with no animations.',
].join(' ');
// Look at model
if (ctx.isBrowser) {
ctx.protocol.emit({
- type: ACTION_TYPES.LOOK_AT,
+ type: ACTION_TYPES.LOOK_AT,
payload: { target: 'model' },
agentId: ctx.identity?.id || 'default',
});
}
return {
- success: true,
+ success: true,
output,
sentiment: 0.4,
- data: { vertices: verts, meshes, materials: mats.size, clips },
+ data: { vertices: verts, meshes, materials: mats.size, clips },
};
},
});
// ── validate-model ────────────────────────────────────────────────
this.register({
- name: 'validate-model',
- description: 'Run glTF validation and report results',
- instruction: 'Trigger the validator, summarise errors and warnings with empathy',
+ name: 'validate-model',
+ description: 'Run glTF validation and report results',
+ instruction: 'Trigger the validator, summarise errors and warnings with empathy',
animationHint: 'inspect',
- voicePattern: 'Validation found {{errors}} errors and {{warnings}} warnings.',
- mcpExposed: true,
- inputSchema: {
+ voicePattern: 'Validation found {{errors}} errors and {{warnings}} warnings.',
+ mcpExposed: true,
+ inputSchema: {
type: 'object',
properties: { url: { type: 'string', description: 'Model URL to validate' } },
},
handler: async (_args, ctx) => {
const viewer = ctx.viewer;
if (!viewer || !viewer.content) {
- return { success: false, output: 'Load a model first and I\'ll validate it.', sentiment: -0.1 };
+ return {
+ success: false,
+ output: "Load a model first and I'll validate it.",
+ sentiment: -0.1,
+ };
}
// The validator runs automatically after load — read the last result from the DOM
@@ -255,8 +275,8 @@ export class AgentSkills {
const text = reportEl.textContent?.trim();
const hasErrors = reportEl.classList.contains('errors');
return {
- success: !hasErrors,
- output: text
+ success: !hasErrors,
+ output: text
? `Validation result: ${text}`
: 'Validator is still running — check the bar at the bottom of the screen.',
sentiment: hasErrors ? -0.5 : 0.6,
@@ -264,8 +284,8 @@ export class AgentSkills {
}
return {
- success: true,
- output: 'The model loaded successfully. For detailed validation, check the bottom of the screen after loading.',
+ success: true,
+ output: 'The model loaded successfully. For detailed validation, check the bottom of the screen after loading.',
sentiment: 0.3,
};
},
@@ -273,19 +293,19 @@ export class AgentSkills {
// ── remember ─────────────────────────────────────────────────────
this.register({
- name: 'remember',
- description: 'Store a memory about the user, session, or project',
- instruction: 'Save important information for future conversations',
+ name: 'remember',
+ description: 'Store a memory about the user, session, or project',
+ instruction: 'Save important information for future conversations',
animationHint: 'nod',
- voicePattern: 'Got it. I\'ll remember that.',
- mcpExposed: true,
- inputSchema: {
+ voicePattern: "Got it. I'll remember that.",
+ mcpExposed: true,
+ inputSchema: {
type: 'object',
required: ['content'],
properties: {
content: { type: 'string', description: 'What to remember' },
- type: { type: 'string', enum: ['user', 'feedback', 'project', 'reference'] },
- tags: { type: 'array', items: { type: 'string' } },
+ type: { type: 'string', enum: ['user', 'feedback', 'project', 'reference'] },
+ tags: { type: 'array', items: { type: 'string' } },
},
},
handler: async (args, ctx) => {
@@ -294,88 +314,88 @@ export class AgentSkills {
}
const id = ctx.memory?.add({
- type: args.type || MEMORY_TYPES.PROJECT,
+ type: args.type || MEMORY_TYPES.PROJECT,
content: args.content,
- tags: args.tags || [],
+ tags: args.tags || [],
});
if (ctx.isBrowser) {
ctx.protocol.emit({
- type: ACTION_TYPES.REMEMBER,
+ type: ACTION_TYPES.REMEMBER,
payload: { content: args.content, memoryId: id },
agentId: ctx.identity?.id || 'default',
});
}
return {
- success: true,
- output: `Got it — I'll remember that.`,
+ success: true,
+ output: `Got it — I'll remember that.`,
sentiment: 0.5,
- data: { memoryId: id },
+ data: { memoryId: id },
};
},
});
// ── think ─────────────────────────────────────────────────────────
this.register({
- name: 'think',
- description: 'Retrieve relevant memories and reason about a question',
- instruction: 'Search memory, synthesise context, respond thoughtfully',
+ name: 'think',
+ description: 'Retrieve relevant memories and reason about a question',
+ instruction: 'Search memory, synthesise context, respond thoughtfully',
animationHint: 'think',
- voicePattern: 'Let me think about that...',
- mcpExposed: false,
- inputSchema: {
+ voicePattern: 'Let me think about that...',
+ mcpExposed: false,
+ inputSchema: {
type: 'object',
required: ['query'],
properties: { query: { type: 'string' } },
},
handler: async (args, ctx) => {
- const query = args.query || '';
+ const query = args.query || '';
const memories = ctx.memory?.query({ limit: 5 }) || [];
if (!memories.length) {
return {
- success: true,
- output: `I don't have any stored context yet. As we work together, I'll build up memory to give you better answers.`,
+ success: true,
+ output: `I don't have any stored context yet. As we work together, I'll build up memory to give you better answers.`,
sentiment: 0.1,
};
}
- const context = memories.map(m => `- ${m.content}`).join('\n');
+ const context = memories.map((m) => `- ${m.content}`).join('\n');
return {
- success: true,
- output: `Based on what I remember: ${memories[0].content}`,
+ success: true,
+ output: `Based on what I remember: ${memories[0].content}`,
sentiment: 0.3,
- data: { memories, context },
+ data: { memories, context },
};
},
});
// ── sign-action ───────────────────────────────────────────────────
this.register({
- name: 'sign-action',
- description: 'Sign the most recent action with the agent\'s linked wallet',
- instruction: 'Use ERC-191 personal_sign to create a verifiable proof of the action',
+ name: 'sign-action',
+ description: "Sign the most recent action with the agent's linked wallet",
+ instruction: 'Use ERC-191 personal_sign to create a verifiable proof of the action',
animationHint: 'sign',
- voicePattern: 'Signing action {{actionId}} with my wallet.',
- mcpExposed: true,
- inputSchema: {
+ voicePattern: 'Signing action {{actionId}} with my wallet.',
+ mcpExposed: true,
+ inputSchema: {
type: 'object',
properties: { actionId: { type: 'string' } },
},
handler: async (args, ctx) => {
if (!ctx.identity?.walletAddress) {
return {
- success: false,
- output: 'No wallet linked. Connect a wallet first to sign actions.',
+ success: false,
+ output: 'No wallet linked. Connect a wallet first to sign actions.',
sentiment: -0.2,
};
}
if (!ctx.isBrowser || !window.ethereum) {
return {
- success: false,
- output: 'No web3 wallet detected. Install MetaMask or a compatible wallet.',
+ success: false,
+ output: 'No web3 wallet detected. Install MetaMask or a compatible wallet.',
sentiment: -0.2,
};
}
@@ -383,40 +403,44 @@ export class AgentSkills {
try {
const { ethers } = await import('ethers');
const provider = new ethers.BrowserProvider(window.ethereum);
- const signer = await provider.getSigner();
- const message = `Agent action: ${args.actionId || 'latest'} at ${Date.now()}`;
- const sig = await signer.signMessage(message);
+ const signer = await provider.getSigner();
+ const message = `Agent action: ${args.actionId || 'latest'} at ${Date.now()}`;
+ const sig = await signer.signMessage(message);
ctx.protocol.emit({
- type: ACTION_TYPES.SIGN,
+ type: ACTION_TYPES.SIGN,
payload: { message, signature: sig, actionId: args.actionId },
agentId: ctx.identity?.id || 'default',
});
return {
- success: true,
- output: `Action signed. Signature: ${sig.slice(0, 20)}…`,
+ success: true,
+ output: `Action signed. Signature: ${sig.slice(0, 20)}…`,
sentiment: 0.6,
- data: { signature: sig, message },
+ data: { signature: sig, message },
};
} catch (err) {
- return { success: false, output: `Signing failed: ${err.message}`, sentiment: -0.4 };
+ return {
+ success: false,
+ output: `Signing failed: ${err.message}`,
+ sentiment: -0.4,
+ };
}
},
});
// ── help ──────────────────────────────────────────────────────────
this.register({
- name: 'help',
- description: 'List available skills and controls',
- instruction: 'Summarise what the agent can do',
+ name: 'help',
+ description: 'List available skills and controls',
+ instruction: 'Summarise what the agent can do',
animationHint: 'gesture',
- voicePattern: 'Here\'s what I can do.',
- mcpExposed: false,
+ voicePattern: "Here's what I can do.",
+ mcpExposed: false,
handler: async (_args, _ctx) => {
return {
- success: true,
- output: 'I can present and validate 3D models, remember things about your work, sign actions with a wallet, and answer questions. Try dropping a GLB file in, or ask me to present what\'s loaded.',
+ success: true,
+ output: "I can present and validate 3D models, remember things about your work, sign actions with a wallet, and answer questions. Try dropping a GLB file in, or ask me to present what's loaded.",
sentiment: 0.5,
};
},
diff --git a/src/animation-manager.js b/src/animation-manager.js
index c27dba619..7ab4df931 100644
--- a/src/animation-manager.js
+++ b/src/animation-manager.js
@@ -130,7 +130,9 @@ export class AnimationManager {
if (options.clipName) {
clip = animations.find((a) => a.name === options.clipName);
if (!clip) {
- console.warn(`[AnimationManager] Clip "${options.clipName}" not found in ${url}, using first clip`);
+ console.warn(
+ `[AnimationManager] Clip "${options.clipName}" not found in ${url}, using first clip`,
+ );
clip = animations[0];
}
} else {
diff --git a/src/annotations.js b/src/annotations.js
index 0b7fe8b27..c3a964c2f 100644
--- a/src/annotations.js
+++ b/src/annotations.js
@@ -33,9 +33,7 @@ export function buildAnnotations(object) {
const matType = mat ? mat.type.replace('Material', '') : '';
// Rich inline: mesh name (bold) + vertex count (light)
- const items = [
- { text: node.name, font: FONT_NAME },
- ];
+ const items = [{ text: node.name, font: FONT_NAME }];
if (vertCount > 0) {
items.push({ text: ' ' + formatShort(vertCount) + ' verts', font: FONT_DETAIL });
}
@@ -120,7 +118,8 @@ export function renderAnnotationCanvas(annotation) {
x += frag.gapBefore;
const item = items[frag.itemIndex];
ctx.font = item.font;
- ctx.fillStyle = frag.itemIndex === 0 ? 'rgba(255, 255, 255, 0.9)' : 'rgba(255, 255, 255, 0.45)';
+ ctx.fillStyle =
+ frag.itemIndex === 0 ? 'rgba(255, 255, 255, 0.9)' : 'rgba(255, 255, 255, 0.45)';
ctx.fillText(frag.text, x, y);
x += frag.occupiedWidth;
});
diff --git a/src/artifact/entry.js b/src/artifact/entry.js
index 2015a8b0c..424260a90 100644
--- a/src/artifact/entry.js
+++ b/src/artifact/entry.js
@@ -9,7 +9,8 @@
if (!container) return;
// Setup container
- container.style.cssText = 'position: relative; width: 100%; height: 100%; min-height: 400px; background: #000;';
+ container.style.cssText =
+ 'position: relative; width: 100%; height: 100%; min-height: 400px; background: #000;';
// Add caption
const caption = document.createElement('div');
@@ -31,7 +32,9 @@
container.appendChild(caption);
// Get agent ID from config or data attributes
- const scriptTag = document.querySelector('script[type="application/json"][id="agent3d-config"]');
+ const scriptTag = document.querySelector(
+ 'script[type="application/json"][id="agent3d-config"]',
+ );
const config = scriptTag ? JSON.parse(scriptTag.textContent) : {};
const agentId = config.agentId || container.dataset.agentId;
const origin = config.origin || container.dataset.origin || 'https://3dagent.vercel.app';
@@ -44,7 +47,9 @@
try {
// Load three.js modules from CDN
const THREE = await import('https://esm.sh/[email protected]');
- const { GLTFLoader } = await import('https://esm.sh/[email protected]/examples/jsm/loaders/GLTFLoader.js');
+ const { GLTFLoader } = await import(
+ 'https://esm.sh/[email protected]/examples/jsm/loaders/GLTFLoader.js'
+ );
const { OrbitControls } = await import(
'https://esm.sh/[email protected]/examples/jsm/controls/OrbitControls.js'
);
diff --git a/src/attestations/gltf.js b/src/attestations/gltf.js
index f640c1cb7..cd0163d12 100644
--- a/src/attestations/gltf.js
+++ b/src/attestations/gltf.js
@@ -105,7 +105,11 @@ export async function verifyGlTFAttestation({ attestation, glbBlob, trustedIssue
// 2. Recover signer from signature — catches any field tampering
// Note: we sign against the *attested* glbSha256 and summary so that
// the hash mismatch above is independent of signature failure.
- const message = await buildMessage(attestation.agentId, attestation.glbSha256, attestation.summary);
+ const message = await buildMessage(
+ attestation.agentId,
+ attestation.glbSha256,
+ attestation.summary,
+ );
let recoveredAddress;
try {
recoveredAddress = verifyMessage(message, attestation.signature).toLowerCase();
@@ -115,7 +119,9 @@ export async function verifyGlTFAttestation({ attestation, glbBlob, trustedIssue
}
if (recoveredAddress !== attestation.issuer) {
- reasons.push(`Issuer mismatch: attested ${attestation.issuer}, recovered ${recoveredAddress}`);
+ reasons.push(
+ `Issuer mismatch: attested ${attestation.issuer}, recovered ${recoveredAddress}`,
+ );
}
// 3. Optional: enforce a caller-supplied trusted-issuer list
diff --git a/src/auth/README.md b/src/auth/README.md
index 601413339..137de1460 100644
--- a/src/auth/README.md
+++ b/src/auth/README.md
@@ -26,9 +26,9 @@ https://esm.sh/@walletconnect/[email protected]
```js
import {
- signInWithWalletConnect,
- getWalletConnectProvider,
- disconnectWalletConnect,
+ signInWithWalletConnect,
+ getWalletConnectProvider,
+ disconnectWalletConnect,
} from './auth/walletconnect-bridge.js';
// Opens WC modal, signs SIWE message, verifies with server, sets session cookie.
@@ -45,16 +45,16 @@ await disconnectWalletConnect();
All errors have an `err.code` of the form `wc/<stage>`:
-| Code | Meaning |
-|---|---|
-| `wc/no_project_id` | `VITE_WALLETCONNECT_PROJECT_ID` not set |
-| `wc/load_failed` | CDN import failed (network / CSP) |
-| `wc/init_failed` | EthereumProvider.init() threw |
-| `wc/connect_rejected` | User closed modal or rejected session |
-| `wc/no_accounts` | Provider returned no accounts after connect |
-| `wc/nonce_failed` | `/api/auth/siwe/nonce` request failed |
-| `wc/sign_rejected` | User rejected personal_sign |
-| `wc/verify_failed` | `/api/auth/siwe/verify` returned an error |
+| Code | Meaning |
+| --------------------- | ------------------------------------------- |
+| `wc/no_project_id` | `VITE_WALLETCONNECT_PROJECT_ID` not set |
+| `wc/load_failed` | CDN import failed (network / CSP) |
+| `wc/init_failed` | EthereumProvider.init() threw |
+| `wc/connect_rejected` | User closed modal or rejected session |
+| `wc/no_accounts` | Provider returned no accounts after connect |
+| `wc/nonce_failed` | `/api/auth/siwe/nonce` request failed |
+| `wc/sign_rejected` | User rejected personal_sign |
+| `wc/verify_failed` | `/api/auth/siwe/verify` returned an error |
## Known issues
diff --git a/src/auth/walletconnect-bridge.js b/src/auth/walletconnect-bridge.js
index ac8fe4b81..634ded381 100644
--- a/src/auth/walletconnect-bridge.js
+++ b/src/auth/walletconnect-bridge.js
@@ -26,7 +26,9 @@ async function _resolveProjectId(override) {
const cfg = await res.json();
if (cfg.walletConnectProjectId) return cfg.walletConnectProjectId;
}
- } catch { /* network failure — fall through */ }
+ } catch {
+ /* network failure — fall through */
+ }
return null;
}
@@ -114,7 +116,10 @@ export async function signInWithWalletConnect({ projectId, chains } = {}) {
// 5. Sign.
let signature;
try {
- signature = await _provider.request({ method: 'personal_sign', params: [message, address] });
+ signature = await _provider.request({
+ method: 'personal_sign',
+ params: [message, address],
+ });
} catch (e) {
throw _wcError('sign_rejected', `User rejected signing: ${e.message}`);
}
@@ -138,7 +143,9 @@ export async function signInWithWalletConnect({ projectId, chains } = {}) {
try {
const { getMe } = await import('../account.js');
await getMe();
- } catch { /* non-fatal: hint just won't be refreshed */ }
+ } catch {
+ /* non-fatal: hint just won't be refreshed */
+ }
return {
user: result.user,
diff --git a/src/auth/walletconnect-bridge.test.html b/src/auth/walletconnect-bridge.test.html
index f029dbc80..10b243d68 100644
--- a/src/auth/walletconnect-bridge.test.html
+++ b/src/auth/walletconnect-bridge.test.html
@@ -1,73 +1,101 @@
<!doctype html>
<html lang="en">
-<head>
- <meta charset="UTF-8" />
- <title>WalletConnect Bridge — smoke test</title>
- <style>
- body { font-family: monospace; max-width: 640px; margin: 2rem auto; padding: 0 1rem; }
- button { margin: .25rem; padding: .5rem 1rem; cursor: pointer; }
- #log { margin-top: 1rem; white-space: pre-wrap; border: 1px solid #ccc; padding: .75rem; min-height: 6rem; }
- .ok { color: green; }
- .err { color: red; }
- </style>
-</head>
-<body>
- <h2>WalletConnect → SIWE smoke test</h2>
- <p>Requires <code>VITE_WALLETCONNECT_PROJECT_ID</code> to be set in <code>.env.local</code>.</p>
-
- <button id="btn-connect">Connect + Sign In</button>
- <button id="btn-me">GET /api/auth/me</button>
- <button id="btn-disconnect">Disconnect</button>
-
- <div id="log">Ready.</div>
+ <head>
+ <meta charset="UTF-8" />
+ <title>WalletConnect Bridge — smoke test</title>
+ <style>
+ body {
+ font-family: monospace;
+ max-width: 640px;
+ margin: 2rem auto;
+ padding: 0 1rem;
+ }
+ button {
+ margin: 0.25rem;
+ padding: 0.5rem 1rem;
+ cursor: pointer;
+ }
+ #log {
+ margin-top: 1rem;
+ white-space: pre-wrap;
+ border: 1px solid #ccc;
+ padding: 0.75rem;
+ min-height: 6rem;
+ }
+ .ok {
+ color: green;
+ }
+ .err {
+ color: red;
+ }
+ </style>
+ </head>
+ <body>
+ <h2>WalletConnect → SIWE smoke test</h2>
+ <p>
+ Requires <code>VITE_WALLETCONNECT_PROJECT_ID</code> to be set in
+ <code>.env.local</code>.
+ </p>
- <script type="module">
- import { signInWithWalletConnect, getWalletConnectProvider, disconnectWalletConnect }
- from './walletconnect-bridge.js';
+ <button id="btn-connect">Connect + Sign In</button>
+ <button id="btn-me">GET /api/auth/me</button>
+ <button id="btn-disconnect">Disconnect</button>
- const log = document.getElementById('log');
+ <div id="log">Ready.</div>
- function write(msg, cls = '') {
- const ts = new Date().toISOString().slice(11, 23);
- log.innerHTML += `<span class="${cls}">[${ts}] ${escHtml(msg)}\n</span>`;
- log.scrollTop = log.scrollHeight;
- }
+ <script type="module">
+ import {
+ signInWithWalletConnect,
+ getWalletConnectProvider,
+ disconnectWalletConnect,
+ } from './walletconnect-bridge.js';
- function escHtml(s) {
- return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
- }
+ const log = document.getElementById('log');
- document.getElementById('btn-connect').addEventListener('click', async () => {
- write('Starting WalletConnect sign-in…');
- try {
- const { user, address } = await signInWithWalletConnect();
- write(`Signed in — address: ${address}`, 'ok');
- write(`User: ${JSON.stringify(user, null, 2)}`, 'ok');
- } catch (err) {
- write(`Error [${err.code}]: ${err.message}`, 'err');
+ function write(msg, cls = '') {
+ const ts = new Date().toISOString().slice(11, 23);
+ log.innerHTML += `<span class="${cls}">[${ts}] ${escHtml(msg)}\n</span>`;
+ log.scrollTop = log.scrollHeight;
}
- });
- document.getElementById('btn-me').addEventListener('click', async () => {
- write('GET /api/auth/me…');
- try {
- const res = await fetch('/api/auth/me', { credentials: 'include' });
- const body = await res.json();
- write(`${res.status} → ${JSON.stringify(body, null, 2)}`, res.ok ? 'ok' : 'err');
- } catch (err) {
- write(`Fetch error: ${err.message}`, 'err');
+ function escHtml(s) {
+ return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
- });
- document.getElementById('btn-disconnect').addEventListener('click', async () => {
- write('Disconnecting…');
- try {
- await disconnectWalletConnect();
- write('Disconnected.', 'ok');
- } catch (err) {
- write(`Disconnect error: ${err.message}`, 'err');
- }
- });
- </script>
-</body>
+ document.getElementById('btn-connect').addEventListener('click', async () => {
+ write('Starting WalletConnect sign-in…');
+ try {
+ const { user, address } = await signInWithWalletConnect();
+ write(`Signed in — address: ${address}`, 'ok');
+ write(`User: ${JSON.stringify(user, null, 2)}`, 'ok');
+ } catch (err) {
+ write(`Error [${err.code}]: ${err.message}`, 'err');
+ }
+ });
+
+ document.getElementById('btn-me').addEventListener('click', async () => {
+ write('GET /api/auth/me…');
+ try {
+ const res = await fetch('/api/auth/me', { credentials: 'include' });
+ const body = await res.json();
+ write(
+ `${res.status} → ${JSON.stringify(body, null, 2)}`,
+ res.ok ? 'ok' : 'err',
+ );
+ } catch (err) {
+ write(`Fetch error: ${err.message}`, 'err');
+ }
+ });
+
+ document.getElementById('btn-disconnect').addEventListener('click', async () => {
+ write('Disconnecting…');
+ try {
+ await disconnectWalletConnect();
+ write('Disconnected.', 'ok');
+ } catch (err) {
+ write(`Disconnect error: ${err.message}`, 'err');
+ }
+ });
+ </script>
+ </body>
</html>
diff --git a/src/avatar-creator.js b/src/avatar-creator.js
index 978ca05fd..86b279610 100644
--- a/src/avatar-creator.js
+++ b/src/avatar-creator.js
@@ -11,7 +11,6 @@ function getStudioUrl() {
return 'http://localhost:5173';
}
-
export class AvatarCreator {
/**
* @param {Element} containerEl - Parent element to mount the modal into
@@ -174,7 +173,9 @@ export class AvatarCreator {
});
}
- this.modal.querySelector('.avatar-creator-close').addEventListener('click', () => this.close());
+ this.modal
+ .querySelector('.avatar-creator-close')
+ .addEventListener('click', () => this.close());
this.modal.addEventListener('click', (e) => {
if (e.target === this.modal) this.close();
});
diff --git a/src/avaturn-client.js b/src/avaturn-client.js
index cbf4aa278..4142e1b82 100644
--- a/src/avaturn-client.js
+++ b/src/avaturn-client.js
@@ -81,9 +81,14 @@ export async function createAvaturnSession({ front, left, right }) {
if (!res.ok) {
const payload = await res.json().catch(() => ({}));
const code = payload?.error;
- if (res.status === 401 || res.status === 403) throw new AvaturnError(payload?.error_description || 'unauthorized', 'auth');
- if (res.status === 429) throw new AvaturnError(payload?.error_description || 'rate limited', 'quota');
- throw new AvaturnError(payload?.error_description || `http ${res.status}`, code === 'not_configured' ? 'auth' : 'network');
+ if (res.status === 401 || res.status === 403)
+ throw new AvaturnError(payload?.error_description || 'unauthorized', 'auth');
+ if (res.status === 429)
+ throw new AvaturnError(payload?.error_description || 'rate limited', 'quota');
+ throw new AvaturnError(
+ payload?.error_description || `http ${res.status}`,
+ code === 'not_configured' ? 'auth' : 'network',
+ );
}
const data = await res.json();
@@ -156,7 +161,10 @@ export async function awaitAvatarGLB({ sessionUrl, onProgress, signal }) {
// base set because it may open OAuth flows in a new window.
iframe = document.createElement('iframe');
iframe.style.display = 'none';
- iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox');
+ iframe.setAttribute(
+ 'sandbox',
+ 'allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox',
+ );
iframe.setAttribute('title', 'Avaturn avatar export');
iframe.setAttribute('aria-hidden', 'true');
@@ -193,7 +201,8 @@ export async function awaitAvatarGLB({ sessionUrl, onProgress, signal }) {
} catch (err) {
throw new AvaturnError(`GLB fetch failed: ${err?.message}`, 'network');
}
- if (!fetchRes.ok) throw new AvaturnError(`GLB fetch ${fetchRes.status}`, 'network');
+ if (!fetchRes.ok)
+ throw new AvaturnError(`GLB fetch ${fetchRes.status}`, 'network');
const glbBytes = await fetchRes.arrayBuffer();
progress({ step: 'glb-fetch', pct: 100 });
@@ -208,16 +217,24 @@ export async function awaitAvatarGLB({ sessionUrl, onProgress, signal }) {
} catch (err) {
cleanup();
signal?.removeEventListener('abort', onAbort);
- reject(err instanceof AvaturnError ? err : new AvaturnError(err?.message ?? 'unknown', 'network'));
+ reject(
+ err instanceof AvaturnError
+ ? err
+ : new AvaturnError(err?.message ?? 'unknown', 'network'),
+ );
}
}
};
window.addEventListener('message', messageListener);
- iframe.addEventListener('load', () => {
- progress({ step: 'iframe-load', pct: 5 });
- }, { once: true });
+ iframe.addEventListener(
+ 'load',
+ () => {
+ progress({ step: 'iframe-load', pct: 5 });
+ },
+ { once: true },
+ );
document.body.appendChild(iframe);
progress({ step: 'iframe-load', pct: 0 });
diff --git a/src/claim-transfer.js b/src/claim-transfer.js
index a35f5d9bd..4de1b88f3 100644
--- a/src/claim-transfer.js
+++ b/src/claim-transfer.js
@@ -54,10 +54,7 @@ async function _ensureChain(chainId) {
});
} catch (err) {
// 4902 = chain not added to wallet — surface as network error
- throw new ClaimError(
- `Wallet chain switch failed (${err.message})`,
- 'network',
- );
+ throw new ClaimError(`Wallet chain switch failed (${err.message})`, 'network');
}
}
@@ -119,7 +116,10 @@ export async function claimAgent({ agentId, fromAddress, toAddress, signer, onSt
try {
currentOwner = await registry.ownerOf(agentId);
} catch (err) {
- throw new ClaimError(`Could not fetch owner for agentId ${agentId}: ${err.message}`, 'network');
+ throw new ClaimError(
+ `Could not fetch owner for agentId ${agentId}: ${err.message}`,
+ 'network',
+ );
}
const normalize = (a) => a.toLowerCase();
@@ -132,7 +132,10 @@ export async function claimAgent({ agentId, fromAddress, toAddress, signer, onSt
}
if (normalize(currentOwner) === normalize(toAddress)) {
- throw new ClaimError(`Agent ${agentId} is already owned by ${toAddress}`, 'already-claimed');
+ throw new ClaimError(
+ `Agent ${agentId} is already owned by ${toAddress}`,
+ 'already-claimed',
+ );
}
step('sign', 25);
diff --git a/src/components/ModelViewerElement.js b/src/components/ModelViewerElement.js
index c26c91177..4a8e891b4 100644
--- a/src/components/ModelViewerElement.js
+++ b/src/components/ModelViewerElement.js
@@ -122,7 +122,9 @@ export class ModelViewerElement extends HTMLElement {
if (typeof this._viewer.dispose === 'function') {
this._viewer.dispose();
} else {
- console.warn('[mv-viewer] Viewer.dispose() not available — disconnect will leak resources.');
+ console.warn(
+ '[mv-viewer] Viewer.dispose() not available — disconnect will leak resources.',
+ );
}
this._viewer = null;
this._stageEl = null;
diff --git a/src/components/footer.jsx b/src/components/footer.jsx
index cb4e20c74..74fa33d2a 100644
--- a/src/components/footer.jsx
+++ b/src/components/footer.jsx
@@ -6,18 +6,22 @@ export function Footer() {
return (
<footer>
<a class="item" target="_blank" href="https://x.com/nichxbt" aria-label="Follow on X">
- <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="16"
+ height="16"
+ viewBox="0 0 24 24"
+ fill="currentColor"
+ >
+ <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
+ </svg>
</a>
<span class="separator" aria-hidden="true">
|
</span>
- <a
- class="item"
- target="_blank"
- href="https://github.com/nirholas/3d-agent/issues/new"
- >
+ <a class="item" target="_blank" href="https://github.com/nirholas/3d-agent/issues/new">
help & feedback
</a>
@@ -25,8 +29,21 @@ export function Footer() {
|
</span>
- <a class="item" target="_blank" href="https://github.com/nirholas/3d-agent" aria-label="GitHub">
- <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z"/></svg>
+ <a
+ class="item"
+ target="_blank"
+ href="https://github.com/nirholas/3d-agent"
+ aria-label="GitHub"
+ >
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="16"
+ height="16"
+ viewBox="0 0 24 24"
+ fill="currentColor"
+ >
+ <path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z" />
+ </svg>
</a>
</footer>
);
diff --git a/src/components/validator-report.jsx b/src/components/validator-report.jsx
index 206964c89..5a4ab7499 100644
--- a/src/components/validator-report.jsx
+++ b/src/components/validator-report.jsx
@@ -24,8 +24,7 @@ export function ValidatorReport({
</li>
{info?.extras?.title && (
<li>
- <b>Title:</b>{' '}
- <span>{info.extras.title}</span>
+ <b>Title:</b> <span>{info.extras.title}</span>
</li>
)}
{info?.extras?.author && (
diff --git a/src/cz-flow.js b/src/cz-flow.js
index 7c271e8ac..12276ee79 100644
--- a/src/cz-flow.js
+++ b/src/cz-flow.js
@@ -27,7 +27,8 @@ export async function startClaim({ state, onProgress }) {
// Step 2: Check state
if (state.status === 'pre-onchain') {
log('check_state', 'pre_onchain', {
- message: 'CZ is not yet registered on-chain. Claiming opens once registration is complete.',
+ message:
+ 'CZ is not yet registered on-chain. Claiming opens once registration is complete.',
});
return { ok: true, message: 'pre_onchain' };
}
@@ -92,7 +93,10 @@ export function mountEmbedCopy(container, { state }) {
await navigator.clipboard.writeText(snippet);
const orig = button.textContent;
button.textContent = 'Copied!';
- fireAnalytics('embed_copied', { hasChainId: !!state.chainId, hasAgentId: !!state.agentId });
+ fireAnalytics('embed_copied', {
+ hasChainId: !!state.chainId,
+ hasAgentId: !!state.agentId,
+ });
setTimeout(() => {
button.textContent = orig;
}, 2000);
diff --git a/src/editor/apply-overrides.js b/src/editor/apply-overrides.js
index 4842137a4..2a3d5a3c4 100644
--- a/src/editor/apply-overrides.js
+++ b/src/editor/apply-overrides.js
@@ -9,10 +9,10 @@ export function applyMaterialOverrides(model, overrides) {
traverseMaterials(model, (mat) => {
const p = overrides[mat.name];
if (!p) return;
- if (p.color !== undefined) mat.color.set(p.color);
+ if (p.color !== undefined) mat.color.set(p.color);
if (p.metalness !== undefined) mat.metalness = Number(p.metalness);
if (p.roughness !== undefined) mat.roughness = Number(p.roughness);
- if (p.emissive !== undefined) mat.emissive.set(p.emissive);
+ if (p.emissive !== undefined) mat.emissive.set(p.emissive);
mat.needsUpdate = true;
});
}
@@ -23,11 +23,11 @@ export function listMaterials(model) {
traverseMaterials(model, (mat) => {
if (mat.isMeshStandardMaterial || mat.isMeshPhysicalMaterial) {
result.push({
- name: mat.name,
- color: '#' + mat.color.getHexString(),
+ name: mat.name,
+ color: '#' + mat.color.getHexString(),
metalness: mat.metalness,
roughness: mat.roughness,
- emissive: '#' + mat.emissive.getHexString(),
+ emissive: '#' + mat.emissive.getHexString(),
});
}
});
diff --git a/src/editor/embed-editor.js b/src/editor/embed-editor.js
index fa96e990c..e4b313910 100644
--- a/src/editor/embed-editor.js
+++ b/src/editor/embed-editor.js
@@ -389,7 +389,11 @@ export function mountEmbedEditor(root, options = {}) {
btn.dataset.device = d.id;
btn.setAttribute('aria-pressed', String(d.id === state.device));
btn.textContent = d.label;
- btn.addEventListener('click', () => { state.device = d.id; syncDevice(); writeSnippet(); });
+ btn.addEventListener('click', () => {
+ state.device = d.id;
+ syncDevice();
+ writeSnippet();
+ });
deviceBar.appendChild(btn);
}
@@ -415,7 +419,10 @@ export function mountEmbedEditor(root, options = {}) {
card.setAttribute('aria-pressed', String(m.id === state.mode));
card.tabIndex = 0;
card.innerHTML = `<div class="ml">${m.label}</div><div class="mh">${m.hint}</div>`;
- card.addEventListener('click', () => { state.mode = m.id; sync(); });
+ card.addEventListener('click', () => {
+ state.mode = m.id;
+ sync();
+ });
modeGrid.appendChild(card);
}
@@ -427,18 +434,42 @@ export function mountEmbedEditor(root, options = {}) {
btn.dataset.pos = p.id;
btn.setAttribute('aria-pressed', String(p.id === state.position));
btn.textContent = p.label;
- btn.addEventListener('click', () => { state.position = p.id; sync(); });
+ btn.addEventListener('click', () => {
+ state.position = p.id;
+ sync();
+ });
posGrid.appendChild(btn);
}
// Input bindings
- srcInput.addEventListener('change', () => { state.src = srcInput.value; sync(); });
- wInput.addEventListener('change', () => { state.width = wInput.value; sync(); });
- hInput.addEventListener('change', () => { state.height = hInput.value; sync(); });
- $('#voice-select').addEventListener('change', (e) => { state.voice = e.target.value === 'off' ? false : true; sync(); });
- $('#camera-select').addEventListener('change', (e) => { state.cameraControls = e.target.value === 'on'; sync(); });
- $('#ar-select').addEventListener('change', (e) => { state.ar = e.target.value === 'on'; sync(); });
- $('#responsive-select').addEventListener('change', (e) => { state.responsivePreset = e.target.value; writeSnippet(); });
+ srcInput.addEventListener('change', () => {
+ state.src = srcInput.value;
+ sync();
+ });
+ wInput.addEventListener('change', () => {
+ state.width = wInput.value;
+ sync();
+ });
+ hInput.addEventListener('change', () => {
+ state.height = hInput.value;
+ sync();
+ });
+ $('#voice-select').addEventListener('change', (e) => {
+ state.voice = e.target.value === 'off' ? false : true;
+ sync();
+ });
+ $('#camera-select').addEventListener('change', (e) => {
+ state.cameraControls = e.target.value === 'on';
+ sync();
+ });
+ $('#ar-select').addEventListener('change', (e) => {
+ state.ar = e.target.value === 'on';
+ sync();
+ });
+ $('#responsive-select').addEventListener('change', (e) => {
+ state.responsivePreset = e.target.value;
+ writeSnippet();
+ });
// URL preview
const urlInput = $('#url-input');
@@ -499,7 +530,14 @@ export function mountEmbedEditor(root, options = {}) {
if (dragState.kind === 'move') {
const x = e.clientX - rect.left - dragState.offsetX;
const y = e.clientY - rect.top - dragState.offsetY;
- const snapped = snapToCorner(x, y, agentWrap.offsetWidth, agentWrap.offsetHeight, rect.width, rect.height);
+ const snapped = snapToCorner(
+ x,
+ y,
+ agentWrap.offsetWidth,
+ agentWrap.offsetHeight,
+ rect.width,
+ rect.height,
+ );
agentWrap.style.left = snapped.x + 'px';
agentWrap.style.top = snapped.y + 'px';
if (snapped.corner) {
@@ -511,13 +549,22 @@ export function mountEmbedEditor(root, options = {}) {
} else if (dragState.kind === 'resize') {
const dx = e.clientX - dragState.startX;
const dy = e.clientY - dragState.startY;
- let w = dragState.startW, h = dragState.startH;
- let left = dragState.startLeft, top = dragState.startTop;
+ let w = dragState.startW,
+ h = dragState.startH;
+ let left = dragState.startLeft,
+ top = dragState.startTop;
if (dragState.handle.includes('e')) w = dragState.startW + dx;
if (dragState.handle.includes('s')) h = dragState.startH + dy;
- if (dragState.handle.includes('w')) { w = dragState.startW - dx; left = dragState.startLeft + dx; }
- if (dragState.handle.includes('n')) { h = dragState.startH - dy; top = dragState.startTop + dy; }
- w = Math.max(160, w); h = Math.max(200, h);
+ if (dragState.handle.includes('w')) {
+ w = dragState.startW - dx;
+ left = dragState.startLeft + dx;
+ }
+ if (dragState.handle.includes('n')) {
+ h = dragState.startH - dy;
+ top = dragState.startTop + dy;
+ }
+ w = Math.max(160, w);
+ h = Math.max(200, h);
agentWrap.style.width = w + 'px';
agentWrap.style.height = h + 'px';
agentWrap.style.left = left + 'px';
@@ -559,10 +606,12 @@ export function mountEmbedEditor(root, options = {}) {
// Show appropriate resize handles based on position
function syncPositionButtons() {
- for (const btn of $$('.pos-btn')) btn.setAttribute('aria-pressed', String(btn.dataset.pos === state.position));
+ for (const btn of $$('.pos-btn'))
+ btn.setAttribute('aria-pressed', String(btn.dataset.pos === state.position));
}
function syncModeCards() {
- for (const card of $$('.mode-card')) card.setAttribute('aria-pressed', String(card.dataset.mode === state.mode));
+ for (const card of $$('.mode-card'))
+ card.setAttribute('aria-pressed', String(card.dataset.mode === state.mode));
}
function applyToPreview() {
@@ -572,7 +621,11 @@ export function mountEmbedEditor(root, options = {}) {
readout.textContent = `${state.width} × ${state.height}`;
// Position — place the wrap inside the stage per mode + position
- agentWrap.style.left = agentWrap.style.right = agentWrap.style.top = agentWrap.style.bottom = '';
+ agentWrap.style.left =
+ agentWrap.style.right =
+ agentWrap.style.top =
+ agentWrap.style.bottom =
+ '';
if (state.mode === 'floating') {
const [vOff, hOff] = (state.offset || '24px 24px').split(/\s+/);
if (state.position.includes('top')) agentWrap.style.top = vOff;
@@ -600,7 +653,8 @@ export function mountEmbedEditor(root, options = {}) {
}
// Agent attrs
- if (state.src) agentEl.setAttribute('src', state.src); else agentEl.removeAttribute('src');
+ if (state.src) agentEl.setAttribute('src', state.src);
+ else agentEl.removeAttribute('src');
}
function buildSnippet() {
@@ -609,7 +663,8 @@ export function mountEmbedEditor(root, options = {}) {
if (state.mode && state.mode !== 'inline') attrs.push(`mode="${state.mode}"`);
if (state.mode === 'floating') {
if (state.position !== 'bottom-right') attrs.push(`position="${state.position}"`);
- if (state.offset && state.offset !== '24px 24px') attrs.push(`offset="${state.offset}"`);
+ if (state.offset && state.offset !== '24px 24px')
+ attrs.push(`offset="${state.offset}"`);
}
const wPx = parsePx(state.width);
@@ -723,17 +778,23 @@ export function mountEmbedEditor(root, options = {}) {
for (const c of corners) {
if (Math.abs(x - c.cx) < SNAP && Math.abs(y - c.cy) < SNAP) {
// Compute offsets from nearest edge
- const offV = c.corner.startsWith('top') ? `${Math.round(c.cy)}px` : `${Math.round(stageH - h - c.cy)}px`;
- const offH = c.corner.endsWith('left') ? `${Math.round(c.cx)}px`
- : c.corner.endsWith('right') ? `${Math.round(stageW - w - c.cx)}px`
- : '0px';
+ const offV = c.corner.startsWith('top')
+ ? `${Math.round(c.cy)}px`
+ : `${Math.round(stageH - h - c.cy)}px`;
+ const offH = c.corner.endsWith('left')
+ ? `${Math.round(c.cx)}px`
+ : c.corner.endsWith('right')
+ ? `${Math.round(stageW - w - c.cx)}px`
+ : '0px';
return { x: c.cx, y: c.cy, corner: c.corner, offsetV: offV, offsetH: offH };
}
}
return { x, y };
}
- function escapeAttr(s) { return String(s).replace(/"/g, '&quot;'); }
+ function escapeAttr(s) {
+ return String(s).replace(/"/g, '&quot;');
+ }
sync();
return { state, host };
diff --git a/src/editor/glb-export.js b/src/editor/glb-export.js
index 41a228b06..4b3907404 100644
--- a/src/editor/glb-export.js
+++ b/src/editor/glb-export.js
@@ -63,7 +63,7 @@ function applyMaterialEdits(root, edits) {
if (edit.baseColor) {
const [r, g, b] = edit.baseColor;
const alpha =
- edit.opacity !== undefined ? edit.opacity : mat.getBaseColorFactor()[3] ?? 1;
+ edit.opacity !== undefined ? edit.opacity : (mat.getBaseColorFactor()[3] ?? 1);
mat.setBaseColorFactor([r, g, b, alpha]);
} else if (edit.opacity !== undefined) {
const f = mat.getBaseColorFactor() || [1, 1, 1, 1];
diff --git a/src/editor/index.js b/src/editor/index.js
index a41365755..94e564952 100644
--- a/src/editor/index.js
+++ b/src/editor/index.js
@@ -125,7 +125,9 @@ export class Editor {
async _saveEdits() {
if (this._saveNeedsAuth) {
- window.location.href = '/login?next=' + encodeURIComponent(location.pathname + location.search + location.hash);
+ window.location.href =
+ '/login?next=' +
+ encodeURIComponent(location.pathname + location.search + location.hash);
return;
}
const avatarId =
@@ -139,7 +141,14 @@ export class Editor {
const stepPct = { export: 0, presign: 0.25, upload: 0.4, patch: 0.9 };
const onStep = ({ step, pct }) => {
const base = stepPct[step] ?? 0;
- const span = step === 'upload' ? 0.5 : step === 'export' ? 0.25 : step === 'presign' ? 0.15 : 0.1;
+ const span =
+ step === 'upload'
+ ? 0.5
+ : step === 'export'
+ ? 0.25
+ : step === 'presign'
+ ? 0.15
+ : 0.1;
const overall = Math.round((base + pct * span) * 100);
this._saveCtrl?.name(`saving… ${overall}%`);
};
diff --git a/src/editor/manifest-builder.js b/src/editor/manifest-builder.js
index f30683a84..6d479150d 100644
--- a/src/editor/manifest-builder.js
+++ b/src/editor/manifest-builder.js
@@ -18,60 +18,74 @@ const OPENAI_MODELS = [
{ id: 'gpt-4-turbo', label: 'GPT-4 Turbo' },
];
const BRAIN_PROVIDERS = ['anthropic', 'openai', 'local', 'none'];
-const TTS_PROVIDERS = ['browser', 'elevenlabs', 'openai', 'none'];
-const STT_PROVIDERS = ['browser', 'whisper', 'none'];
-const MEMORY_MODES = ['local', 'ipfs', 'encrypted-ipfs', 'none'];
-const RIG_TYPES = ['mixamo', 'vrm', 'custom'];
-const BODY_FORMATS = ['gltf-binary', 'gltf', 'vrm'];
-const THINKING_OPTS = ['auto', 'always', 'never'];
+const TTS_PROVIDERS = ['browser', 'elevenlabs', 'openai', 'none'];
+const STT_PROVIDERS = ['browser', 'whisper', 'none'];
+const MEMORY_MODES = ['local', 'ipfs', 'encrypted-ipfs', 'none'];
+const RIG_TYPES = ['mixamo', 'vrm', 'custom'];
+const BODY_FORMATS = ['gltf-binary', 'gltf', 'vrm'];
+const THINKING_OPTS = ['auto', 'always', 'never'];
const DRAFT_KEY = 'manifest-builder-draft';
// ─── Zod schema ───────────────────────────────────────────────────────────────
const ManifestSchema = z.object({
- spec: z.literal('agent-manifest/0.1'),
- name: z.string().min(1, 'Name is required').max(100, 'Max 100 chars'),
+ spec: z.literal('agent-manifest/0.1'),
+ name: z.string().min(1, 'Name is required').max(100, 'Max 100 chars'),
description: z.string().max(1000).optional(),
- image: z.string().optional(),
- tags: z.array(z.string()).optional(),
+ image: z.string().optional(),
+ tags: z.array(z.string()).optional(),
body: z.object({
- uri: z.string().min(1, 'Body URI is required'),
- format: z.enum(['gltf-binary', 'gltf', 'vrm']),
- rig: z.enum(['mixamo', 'vrm', 'custom']).optional(),
+ uri: z.string().min(1, 'Body URI is required'),
+ format: z.enum(['gltf-binary', 'gltf', 'vrm']),
+ rig: z.enum(['mixamo', 'vrm', 'custom']).optional(),
boundingBoxHeight: z.number().positive().optional(),
}),
- brain: z.object({
- provider: z.enum(['anthropic', 'openai', 'local', 'none']),
- model: z.string().optional(),
- instructions:z.string().optional(),
- temperature: z.number().min(0).max(2).optional(),
- maxTokens: z.number().int().positive().optional(),
- thinking: z.enum(['auto', 'always', 'never']).optional(),
- }).optional(),
- voice: z.object({
- tts: z.object({
- provider: z.enum(['browser', 'elevenlabs', 'openai', 'none']),
- voiceId: z.string().optional(),
- rate: z.number().min(0.5).max(2).optional(),
- pitch: z.number().min(0).max(2).optional(),
- }).optional(),
- stt: z.object({
- provider: z.enum(['browser', 'whisper', 'none']),
- language: z.string().optional(),
- continuous: z.boolean().optional(),
- }).optional(),
- }).optional(),
- skills: z.array(z.object({
- uri: z.string(),
- version: z.string().optional(),
- })).optional(),
- memory: z.object({
- mode: z.enum(['local', 'ipfs', 'encrypted-ipfs', 'none']),
- index: z.string().optional(),
- maxTokens: z.number().int().positive().optional(),
- }).optional(),
- tools: z.array(z.string()).optional(),
+ brain: z
+ .object({
+ provider: z.enum(['anthropic', 'openai', 'local', 'none']),
+ model: z.string().optional(),
+ instructions: z.string().optional(),
+ temperature: z.number().min(0).max(2).optional(),
+ maxTokens: z.number().int().positive().optional(),
+ thinking: z.enum(['auto', 'always', 'never']).optional(),
+ })
+ .optional(),
+ voice: z
+ .object({
+ tts: z
+ .object({
+ provider: z.enum(['browser', 'elevenlabs', 'openai', 'none']),
+ voiceId: z.string().optional(),
+ rate: z.number().min(0.5).max(2).optional(),
+ pitch: z.number().min(0).max(2).optional(),
+ })
+ .optional(),
+ stt: z
+ .object({
+ provider: z.enum(['browser', 'whisper', 'none']),
+ language: z.string().optional(),
+ continuous: z.boolean().optional(),
+ })
+ .optional(),
+ })
+ .optional(),
+ skills: z
+ .array(
+ z.object({
+ uri: z.string(),
+ version: z.string().optional(),
+ }),
+ )
+ .optional(),
+ memory: z
+ .object({
+ mode: z.enum(['local', 'ipfs', 'encrypted-ipfs', 'none']),
+ index: z.string().optional(),
+ maxTokens: z.number().int().positive().optional(),
+ })
+ .optional(),
+ tools: z.array(z.string()).optional(),
version: z.string().optional(),
});
@@ -79,14 +93,32 @@ const ManifestSchema = z.object({
function defaultState() {
return {
- name: '', description: '', tags: '', image: '',
- glbFile: null, glbUri: '', bodyFormat: 'gltf-binary', rig: 'mixamo', boundingBoxHeight: 1.78,
- brainProvider: 'anthropic', brainModel: 'claude-opus-4-6',
- temperature: 0.7, maxTokens: 4096, thinking: 'auto',
- ttsProvider: 'browser', voiceId: '', ttsRate: 1.0, ttsPitch: 1.0,
- sttProvider: 'browser', sttLanguage: 'en-US', sttContinuous: false,
- installedSkills: {}, customSkills: [],
- memoryMode: 'local', memoryMaxTokens: 8192, memoryRetentionDays: 90,
+ name: '',
+ description: '',
+ tags: '',
+ image: '',
+ glbFile: null,
+ glbUri: '',
+ bodyFormat: 'gltf-binary',
+ rig: 'mixamo',
+ boundingBoxHeight: 1.78,
+ brainProvider: 'anthropic',
+ brainModel: 'claude-opus-4-6',
+ temperature: 0.7,
+ maxTokens: 4096,
+ thinking: 'auto',
+ ttsProvider: 'browser',
+ voiceId: '',
+ ttsRate: 1.0,
+ ttsPitch: 1.0,
+ sttProvider: 'browser',
+ sttLanguage: 'en-US',
+ sttContinuous: false,
+ installedSkills: {},
+ customSkills: [],
+ memoryMode: 'local',
+ memoryMaxTokens: 8192,
+ memoryRetentionDays: 90,
instructions: '',
version: '0.1.0',
};
@@ -236,12 +268,12 @@ export function mountManifestBuilder(rootEl, options = {}) {
const shadow = host.attachShadow({ mode: 'open' });
rootEl.appendChild(host);
- let glbBlobUrl = null;
- let allSkills = [];
- let validReport = null;
- let ipfsCid = null;
- let _draftTimer = null;
- let _prevTimer = null;
+ let glbBlobUrl = null;
+ let allSkills = [];
+ let validReport = null;
+ let ipfsCid = null;
+ let _draftTimer = null;
+ let _prevTimer = null;
shadow.innerHTML = `
<style>${STYLE}</style>
@@ -298,17 +330,19 @@ export function mountManifestBuilder(rootEl, options = {}) {
shadow.querySelectorAll('.tab-btn').forEach((btn) => {
btn.addEventListener('click', () => {
const tab = btn.dataset.tab;
- shadow.querySelectorAll('.tab-btn').forEach((b) =>
- b.setAttribute('aria-selected', String(b.dataset.tab === tab)));
- shadow.querySelectorAll('.tab-panel').forEach((p) =>
- p.classList.toggle('active', p.dataset.panel === tab));
+ shadow
+ .querySelectorAll('.tab-btn')
+ .forEach((b) => b.setAttribute('aria-selected', String(b.dataset.tab === tab)));
+ shadow
+ .querySelectorAll('.tab-panel')
+ .forEach((p) => p.classList.toggle('active', p.dataset.panel === tab));
if (tab === 'raw') syncRawJson();
});
});
// Raw JSON tab
- const rawTa = $('#raw-ta');
- const rawErr = $('#raw-err');
+ const rawTa = $('#raw-ta');
+ const rawErr = $('#raw-err');
const rawApply = $('#raw-apply');
rawTa.addEventListener('input', () => {
@@ -345,10 +379,13 @@ export function mountManifestBuilder(rootEl, options = {}) {
});
// Fetch skills index
- fetch('/skills-index.json').then((r) => r.json()).then((data) => {
- allSkills = data;
- refreshSkillsList();
- }).catch(() => {});
+ fetch('/skills-index.json')
+ .then((r) => r.json())
+ .then((data) => {
+ allSkills = data;
+ refreshSkillsList();
+ })
+ .catch(() => {});
schedulePreview();
@@ -440,7 +477,8 @@ export function mountManifestBuilder(rootEl, options = {}) {
}
function brainHtml() {
- const modelOpts = (models) => models.map((m) => `<option value="${m.id}">${m.label}</option>`).join('');
+ const modelOpts = (models) =>
+ models.map((m) => `<option value="${m.id}">${m.label}</option>`).join('');
return `<details>
<summary>Brain</summary>
<div class="section-body">
@@ -603,66 +641,146 @@ export function mountManifestBuilder(rootEl, options = {}) {
// ── Event binding ──────────────────────────────────────────────────────────
function bindEvents() {
- const on = (id, ev, fn) => { const el = $(id); if (el) el.addEventListener(ev, fn); };
+ const on = (id, ev, fn) => {
+ const el = $(id);
+ if (el) el.addEventListener(ev, fn);
+ };
- on('#f-name', 'input', (e) => { state.name = e.target.value; showFieldError('#err-name', ''); scheduleDraft(); schedulePreview(); });
- on('#f-desc', 'input', (e) => { state.description = e.target.value; scheduleDraft(); });
- on('#f-tags', 'input', (e) => { state.tags = e.target.value; scheduleDraft(); });
- on('#f-image', 'input', (e) => { state.image = e.target.value; scheduleDraft(); });
+ on('#f-name', 'input', (e) => {
+ state.name = e.target.value;
+ showFieldError('#err-name', '');
+ scheduleDraft();
+ schedulePreview();
+ });
+ on('#f-desc', 'input', (e) => {
+ state.description = e.target.value;
+ scheduleDraft();
+ });
+ on('#f-tags', 'input', (e) => {
+ state.tags = e.target.value;
+ scheduleDraft();
+ });
+ on('#f-image', 'input', (e) => {
+ state.image = e.target.value;
+ scheduleDraft();
+ });
// Body drop zone
- const drop = $('#glb-drop');
+ const drop = $('#glb-drop');
const input = $('#glb-input');
drop.addEventListener('click', () => input.click());
- drop.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') input.click(); });
- drop.addEventListener('dragover', (e) => { e.preventDefault(); drop.classList.add('drag'); });
+ drop.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' || e.key === ' ') input.click();
+ });
+ drop.addEventListener('dragover', (e) => {
+ e.preventDefault();
+ drop.classList.add('drag');
+ });
drop.addEventListener('dragleave', () => drop.classList.remove('drag'));
- drop.addEventListener('drop', (e) => { e.preventDefault(); drop.classList.remove('drag'); handleGlbFile(e.dataTransfer.files[0]); });
+ drop.addEventListener('drop', (e) => {
+ e.preventDefault();
+ drop.classList.remove('drag');
+ handleGlbFile(e.dataTransfer.files[0]);
+ });
input.addEventListener('change', (e) => handleGlbFile(e.target.files[0]));
- on('#f-body-uri', 'input', (e) => { state.glbUri = e.target.value; scheduleDraft(); schedulePreview(); });
- on('#f-body-format', 'change', (e) => { state.bodyFormat = e.target.value; scheduleDraft(); });
- on('#f-body-rig', 'change', (e) => { state.rig = e.target.value; scheduleDraft(); });
- on('#f-body-height', 'input', (e) => {
+ on('#f-body-uri', 'input', (e) => {
+ state.glbUri = e.target.value;
+ scheduleDraft();
+ schedulePreview();
+ });
+ on('#f-body-format', 'change', (e) => {
+ state.bodyFormat = e.target.value;
+ scheduleDraft();
+ });
+ on('#f-body-rig', 'change', (e) => {
+ state.rig = e.target.value;
+ scheduleDraft();
+ });
+ on('#f-body-height', 'input', (e) => {
state.boundingBoxHeight = parseFloat(e.target.value) || 1.78;
- const v = $('#f-body-height-val'); if (v) v.textContent = state.boundingBoxHeight.toFixed(2);
+ const v = $('#f-body-height-val');
+ if (v) v.textContent = state.boundingBoxHeight.toFixed(2);
scheduleDraft();
});
- on('#f-brain-provider', 'change', (e) => { state.brainProvider = e.target.value; refreshModelDropdown(); scheduleDraft(); });
- on('#f-brain-model', 'change', (e) => { state.brainModel = e.target.value; scheduleDraft(); });
- on('#f-brain-temp', 'input', (e) => {
+ on('#f-brain-provider', 'change', (e) => {
+ state.brainProvider = e.target.value;
+ refreshModelDropdown();
+ scheduleDraft();
+ });
+ on('#f-brain-model', 'change', (e) => {
+ state.brainModel = e.target.value;
+ scheduleDraft();
+ });
+ on('#f-brain-temp', 'input', (e) => {
state.temperature = parseFloat(e.target.value);
- const v = $('#f-brain-temp-val'); if (v) v.textContent = state.temperature.toFixed(2);
+ const v = $('#f-brain-temp-val');
+ if (v) v.textContent = state.temperature.toFixed(2);
+ scheduleDraft();
+ });
+ on('#f-brain-maxtokens', 'change', (e) => {
+ state.maxTokens = parseInt(e.target.value) || 4096;
+ scheduleDraft();
+ });
+ on('#f-brain-thinking', 'change', (e) => {
+ state.thinking = e.target.value;
scheduleDraft();
});
- on('#f-brain-maxtokens', 'change', (e) => { state.maxTokens = parseInt(e.target.value) || 4096; scheduleDraft(); });
- on('#f-brain-thinking', 'change', (e) => { state.thinking = e.target.value; scheduleDraft(); });
- on('#f-tts-provider', 'change', (e) => { state.ttsProvider = e.target.value; refreshTtsSecondary(); scheduleDraft(); });
- on('#f-tts-voiceid', 'input', (e) => { state.voiceId = e.target.value; scheduleDraft(); });
+ on('#f-tts-provider', 'change', (e) => {
+ state.ttsProvider = e.target.value;
+ refreshTtsSecondary();
+ scheduleDraft();
+ });
+ on('#f-tts-voiceid', 'input', (e) => {
+ state.voiceId = e.target.value;
+ scheduleDraft();
+ });
on('#f-tts-rate', 'input', (e) => {
state.ttsRate = parseFloat(e.target.value);
- const v = $('#f-tts-rate-val'); if (v) v.textContent = state.ttsRate.toFixed(1);
+ const v = $('#f-tts-rate-val');
+ if (v) v.textContent = state.ttsRate.toFixed(1);
scheduleDraft();
});
on('#f-tts-pitch', 'input', (e) => {
state.ttsPitch = parseFloat(e.target.value);
- const v = $('#f-tts-pitch-val'); if (v) v.textContent = state.ttsPitch.toFixed(1);
+ const v = $('#f-tts-pitch-val');
+ if (v) v.textContent = state.ttsPitch.toFixed(1);
scheduleDraft();
});
- on('#f-stt-provider', 'change', (e) => { state.sttProvider = e.target.value; refreshSttSecondary(); scheduleDraft(); });
- on('#f-stt-lang', 'input', (e) => { state.sttLanguage = e.target.value; scheduleDraft(); });
- on('#f-stt-continuous', 'change', (e) => { state.sttContinuous = e.target.checked; scheduleDraft(); });
+ on('#f-stt-provider', 'change', (e) => {
+ state.sttProvider = e.target.value;
+ refreshSttSecondary();
+ scheduleDraft();
+ });
+ on('#f-stt-lang', 'input', (e) => {
+ state.sttLanguage = e.target.value;
+ scheduleDraft();
+ });
+ on('#f-stt-continuous', 'change', (e) => {
+ state.sttContinuous = e.target.checked;
+ scheduleDraft();
+ });
- on('#f-mem-mode', 'change', (e) => { state.memoryMode = e.target.value; scheduleDraft(); });
- on('#f-mem-maxtokens', 'change', (e) => { state.memoryMaxTokens = parseInt(e.target.value) || 8192; scheduleDraft(); });
- on('#f-mem-retention', 'change', (e) => { state.memoryRetentionDays = parseInt(e.target.value) || 90; scheduleDraft(); });
+ on('#f-mem-mode', 'change', (e) => {
+ state.memoryMode = e.target.value;
+ scheduleDraft();
+ });
+ on('#f-mem-maxtokens', 'change', (e) => {
+ state.memoryMaxTokens = parseInt(e.target.value) || 8192;
+ scheduleDraft();
+ });
+ on('#f-mem-retention', 'change', (e) => {
+ state.memoryRetentionDays = parseInt(e.target.value) || 90;
+ scheduleDraft();
+ });
on('#f-instructions', 'input', (e) => {
state.instructions = e.target.value;
- const c = $('#instructions-counter'); if (c) c.textContent = `${e.target.value.length} chars`;
+ const c = $('#instructions-counter');
+ if (c) c.textContent = `${e.target.value.length} chars`;
refreshMdPreview();
scheduleDraft();
});
@@ -681,8 +799,14 @@ export function mountManifestBuilder(rootEl, options = {}) {
}
function hydrateForm() {
- const set = (id, val) => { const el = $(id); if (el && val != null) el.value = String(val); };
- const setChk = (id, val) => { const el = $(id); if (el) el.checked = !!val; };
+ const set = (id, val) => {
+ const el = $(id);
+ if (el && val != null) el.value = String(val);
+ };
+ const setChk = (id, val) => {
+ const el = $(id);
+ if (el) el.checked = !!val;
+ };
set('#f-name', state.name);
set('#f-desc', state.description);
@@ -692,22 +816,26 @@ export function mountManifestBuilder(rootEl, options = {}) {
set('#f-body-format', state.bodyFormat);
set('#f-body-rig', state.rig);
set('#f-body-height', state.boundingBoxHeight);
- const hv = $('#f-body-height-val'); if (hv) hv.textContent = Number(state.boundingBoxHeight).toFixed(2);
+ const hv = $('#f-body-height-val');
+ if (hv) hv.textContent = Number(state.boundingBoxHeight).toFixed(2);
set('#f-brain-provider', state.brainProvider);
refreshModelDropdown();
set('#f-brain-model', state.brainModel);
set('#f-brain-temp', state.temperature);
- const tv = $('#f-brain-temp-val'); if (tv) tv.textContent = Number(state.temperature).toFixed(2);
+ const tv = $('#f-brain-temp-val');
+ if (tv) tv.textContent = Number(state.temperature).toFixed(2);
set('#f-brain-maxtokens', state.maxTokens);
set('#f-brain-thinking', state.thinking);
set('#f-tts-provider', state.ttsProvider);
set('#f-tts-voiceid', state.voiceId);
set('#f-tts-rate', state.ttsRate);
- const rv = $('#f-tts-rate-val'); if (rv) rv.textContent = Number(state.ttsRate).toFixed(1);
+ const rv = $('#f-tts-rate-val');
+ if (rv) rv.textContent = Number(state.ttsRate).toFixed(1);
set('#f-tts-pitch', state.ttsPitch);
- const pv = $('#f-tts-pitch-val'); if (pv) pv.textContent = Number(state.ttsPitch).toFixed(1);
+ const pv = $('#f-tts-pitch-val');
+ if (pv) pv.textContent = Number(state.ttsPitch).toFixed(1);
refreshTtsSecondary();
set('#f-stt-provider', state.sttProvider);
@@ -764,7 +892,10 @@ export function mountManifestBuilder(rootEl, options = {}) {
if (!list) return;
const q = query.toLowerCase();
const filtered = q
- ? allSkills.filter((s) => s.name.toLowerCase().includes(q) || s.description.toLowerCase().includes(q))
+ ? allSkills.filter(
+ (s) =>
+ s.name.toLowerCase().includes(q) || s.description.toLowerCase().includes(q),
+ )
: allSkills;
if (filtered.length === 0) {
list.innerHTML = `<div style="font-size:12px;color:#4b5563;padding:4px 0">No skills found</div>`;
@@ -861,9 +992,15 @@ export function mountManifestBuilder(rootEl, options = {}) {
const result = await validateBytes(bytes);
validReport = result;
const { numErrors: ne, numWarnings: nw } = result.issues;
- const errBadge = ne > 0 ? `<span class="badge badge-err">${ne} error${ne !== 1 ? 's' : ''}</span>` : '';
- const warnBadge = nw > 0 ? `<span class="badge badge-warn">${nw} warning${nw !== 1 ? 's' : ''}</span>` : '';
- const okBadge = ne === 0 && nw === 0 ? `<span class="badge badge-ok">Clean</span>` : '';
+ const errBadge =
+ ne > 0
+ ? `<span class="badge badge-err">${ne} error${ne !== 1 ? 's' : ''}</span>`
+ : '';
+ const warnBadge =
+ nw > 0
+ ? `<span class="badge badge-warn">${nw} warning${nw !== 1 ? 's' : ''}</span>`
+ : '';
+ const okBadge = ne === 0 && nw === 0 ? `<span class="badge badge-ok">Clean</span>` : '';
vc.innerHTML = `
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
${errBadge}${warnBadge}${okBadge}
@@ -883,7 +1020,9 @@ export function mountManifestBuilder(rootEl, options = {}) {
function buildValidatorDetail(result) {
const msgs = result.issues.messages.slice(0, 50);
if (msgs.length === 0) return 'No issues found.';
- return msgs.map((m) => `[${m.severity === 0 ? 'ERR' : 'WARN'}] ${esc(m.message)}`).join('\n');
+ return msgs
+ .map((m) => `[${m.severity === 0 ? 'ERR' : 'WARN'}] ${esc(m.message)}`)
+ .join('\n');
}
// ── Preview ────────────────────────────────────────────────────────────────
@@ -894,7 +1033,7 @@ export function mountManifestBuilder(rootEl, options = {}) {
}
function updatePreview() {
- const wrap = $('#prev-wrap');
+ const wrap = $('#prev-wrap');
const empty = $('#prev-empty');
const label = $('#prev-label');
const agent = $('#prev-agent');
@@ -916,61 +1055,68 @@ export function mountManifestBuilder(rootEl, options = {}) {
function buildManifest(forExport = false) {
const tags = state.tags
- ? state.tags.split(',').map((t) => t.trim()).filter(Boolean)
+ ? state.tags
+ .split(',')
+ .map((t) => t.trim())
+ .filter(Boolean)
: undefined;
const bodyUri = forExport
- ? (state.glbFile ? 'body.glb' : state.glbUri || 'body.glb')
- : (glbBlobUrl || state.glbUri || 'body.glb');
+ ? state.glbFile
+ ? 'body.glb'
+ : state.glbUri || 'body.glb'
+ : glbBlobUrl || state.glbUri || 'body.glb';
const m = {
$schema: 'https://3d-agent.io/schemas/manifest/0.1.json',
- spec: 'agent-manifest/0.1',
- name: state.name || 'Unnamed Agent',
+ spec: 'agent-manifest/0.1',
+ name: state.name || 'Unnamed Agent',
};
if (state.description) m.description = state.description;
- if (state.image) m.image = state.image;
- if (tags?.length) m.tags = tags;
+ if (state.image) m.image = state.image;
+ if (tags?.length) m.tags = tags;
m.body = {
- uri: bodyUri,
+ uri: bodyUri,
format: state.bodyFormat,
- rig: state.rig,
+ rig: state.rig,
boundingBoxHeight: state.boundingBoxHeight,
};
if (state.brainProvider !== 'none') {
m.brain = {
- provider: state.brainProvider,
- model: state.brainModel,
+ provider: state.brainProvider,
+ model: state.brainModel,
instructions: 'instructions.md',
- temperature: state.temperature,
- maxTokens: state.maxTokens,
- thinking: state.thinking,
+ temperature: state.temperature,
+ maxTokens: state.maxTokens,
+ thinking: state.thinking,
};
}
const tts = { provider: state.ttsProvider };
if (state.ttsProvider === 'elevenlabs' && state.voiceId) tts.voiceId = state.voiceId;
- if (state.ttsRate !== 1.0) tts.rate = state.ttsRate;
+ if (state.ttsRate !== 1.0) tts.rate = state.ttsRate;
if (state.ttsPitch !== 1.0) tts.pitch = state.ttsPitch;
const stt = { provider: state.sttProvider, language: state.sttLanguage };
if (state.sttContinuous) stt.continuous = true;
m.voice = { tts, stt };
const skills = [
- ...Object.entries(state.installedSkills).map(([id, cfg]) => {
- const sk = allSkills.find((s) => s.id === id);
- if (!sk) return null;
- return { uri: sk.uri, ...(cfg.version ? { version: cfg.version } : {}) };
- }).filter(Boolean),
+ ...Object.entries(state.installedSkills)
+ .map(([id, cfg]) => {
+ const sk = allSkills.find((s) => s.id === id);
+ if (!sk) return null;
+ return { uri: sk.uri, ...(cfg.version ? { version: cfg.version } : {}) };
+ })
+ .filter(Boolean),
...state.customSkills,
];
if (skills.length) m.skills = skills;
if (state.memoryMode !== 'none') {
m.memory = {
- mode: state.memoryMode,
- index: 'memory/MEMORY.md',
+ mode: state.memoryMode,
+ index: 'memory/MEMORY.md',
maxTokens: state.memoryMaxTokens,
};
}
@@ -995,36 +1141,38 @@ export function mountManifestBuilder(rootEl, options = {}) {
}
function hydrateFromManifest(m) {
- if (typeof m.name === 'string') state.name = m.name;
+ if (typeof m.name === 'string') state.name = m.name;
if (typeof m.description === 'string') state.description = m.description;
- if (Array.isArray(m.tags)) state.tags = m.tags.join(', ');
- if (typeof m.image === 'string') state.image = m.image;
+ if (Array.isArray(m.tags)) state.tags = m.tags.join(', ');
+ if (typeof m.image === 'string') state.image = m.image;
if (m.body) {
- if (!glbBlobUrl && m.body.uri) state.glbUri = m.body.uri;
- if (m.body.format) state.bodyFormat = m.body.format;
- if (m.body.rig) state.rig = m.body.rig;
- if (m.body.boundingBoxHeight != null) state.boundingBoxHeight = m.body.boundingBoxHeight;
+ if (!glbBlobUrl && m.body.uri) state.glbUri = m.body.uri;
+ if (m.body.format) state.bodyFormat = m.body.format;
+ if (m.body.rig) state.rig = m.body.rig;
+ if (m.body.boundingBoxHeight != null)
+ state.boundingBoxHeight = m.body.boundingBoxHeight;
}
if (m.brain) {
- if (m.brain.provider) state.brainProvider = m.brain.provider;
- if (m.brain.model) state.brainModel = m.brain.model;
+ if (m.brain.provider) state.brainProvider = m.brain.provider;
+ if (m.brain.model) state.brainModel = m.brain.model;
if (typeof m.brain.temperature === 'number') state.temperature = m.brain.temperature;
- if (typeof m.brain.maxTokens === 'number') state.maxTokens = m.brain.maxTokens;
- if (m.brain.thinking) state.thinking = m.brain.thinking;
+ if (typeof m.brain.maxTokens === 'number') state.maxTokens = m.brain.maxTokens;
+ if (m.brain.thinking) state.thinking = m.brain.thinking;
}
if (m.voice?.tts) {
- if (m.voice.tts.provider) state.ttsProvider = m.voice.tts.provider;
- if (m.voice.tts.voiceId) state.voiceId = m.voice.tts.voiceId;
- if (typeof m.voice.tts.rate === 'number') state.ttsRate = m.voice.tts.rate;
+ if (m.voice.tts.provider) state.ttsProvider = m.voice.tts.provider;
+ if (m.voice.tts.voiceId) state.voiceId = m.voice.tts.voiceId;
+ if (typeof m.voice.tts.rate === 'number') state.ttsRate = m.voice.tts.rate;
if (typeof m.voice.tts.pitch === 'number') state.ttsPitch = m.voice.tts.pitch;
}
if (m.voice?.stt) {
- if (m.voice.stt.provider) state.sttProvider = m.voice.stt.provider;
- if (m.voice.stt.language) state.sttLanguage = m.voice.stt.language;
- if (typeof m.voice.stt.continuous === 'boolean') state.sttContinuous = m.voice.stt.continuous;
+ if (m.voice.stt.provider) state.sttProvider = m.voice.stt.provider;
+ if (m.voice.stt.language) state.sttLanguage = m.voice.stt.language;
+ if (typeof m.voice.stt.continuous === 'boolean')
+ state.sttContinuous = m.voice.stt.continuous;
}
if (m.memory) {
- if (m.memory.mode) state.memoryMode = m.memory.mode;
+ if (m.memory.mode) state.memoryMode = m.memory.mode;
if (m.memory.maxTokens) state.memoryMaxTokens = m.memory.maxTokens;
}
if (typeof m.version === 'string') state.version = m.version;
@@ -1039,7 +1187,9 @@ export function mountManifestBuilder(rootEl, options = {}) {
function saveDraft() {
const toSave = { ...state, glbFile: null };
- try { localStorage.setItem(DRAFT_KEY, JSON.stringify(toSave)); } catch {}
+ try {
+ localStorage.setItem(DRAFT_KEY, JSON.stringify(toSave));
+ } catch {}
}
// ── Raw JSON sync ──────────────────────────────────────────────────────────
@@ -1067,15 +1217,21 @@ export function mountManifestBuilder(rootEl, options = {}) {
const files = [
{ name: 'manifest.json', data: enc.encode(JSON.stringify(manifest, null, 2)) },
{ name: 'instructions.md', data: enc.encode(buildInstructionsMd()) },
- { name: 'memory/MEMORY.md', data: enc.encode('# Memory\n\n<!-- Auto-generated memory seed -->\n') },
+ {
+ name: 'memory/MEMORY.md',
+ data: enc.encode('# Memory\n\n<!-- Auto-generated memory seed -->\n'),
+ },
];
if (state.glbFile) {
- files.push({ name: 'body.glb', data: new Uint8Array(await state.glbFile.arrayBuffer()) });
+ files.push({
+ name: 'body.glb',
+ data: new Uint8Array(await state.glbFile.arrayBuffer()),
+ });
}
const zip = buildZip(files);
const blob = new Blob([zip], { type: 'application/zip' });
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
a.href = url;
a.download = `${(state.name || 'agent').toLowerCase().replace(/\s+/g, '-')}-manifest.zip`;
document.body.appendChild(a);
@@ -1091,8 +1247,8 @@ export function mountManifestBuilder(rootEl, options = {}) {
function buildInstructionsMd() {
const lines = [
'---',
- state.name ? `name: ${state.name}` : null,
- state.brainModel ? `model: ${state.brainModel}` : null,
+ state.name ? `name: ${state.name}` : null,
+ state.brainModel ? `model: ${state.brainModel}` : null,
`temperature: ${state.temperature}`,
'---',
'',
@@ -1112,7 +1268,9 @@ export function mountManifestBuilder(rootEl, options = {}) {
if (!pinner) throw new Error('No IPFS pinner (window.__agent3dPinner not configured)');
const manifest = buildManifest(true);
- const jsonBlob = new Blob([JSON.stringify(manifest, null, 2)], { type: 'application/json' });
+ const jsonBlob = new Blob([JSON.stringify(manifest, null, 2)], {
+ type: 'application/json',
+ });
const cid = await pinner.pin(jsonBlob, 'manifest.json');
ipfsCid = cid;
@@ -1157,13 +1315,35 @@ function renderMarkdown(src) {
let inPre = false;
for (let i = 0; i < lines.length; i++) {
let l = lines[i];
- if (l.startsWith('```')) { inPre = !inPre; html += inPre ? '<pre>' : '</pre>'; continue; }
- if (inPre) { html += esc(l) + '\n'; continue; }
- if (/^### /.test(l)) { html += `<h3>${inlineHtml(l.slice(4))}</h3>`; continue; }
- if (/^## /.test(l)) { html += `<h2>${inlineHtml(l.slice(3))}</h2>`; continue; }
- if (/^# /.test(l)) { html += `<h1>${inlineHtml(l.slice(2))}</h1>`; continue; }
- if (/^> /.test(l)) { html += `<blockquote>${inlineHtml(l.slice(2))}</blockquote>`; continue; }
- if (l.trim() === '') { html += '<br>'; continue; }
+ if (l.startsWith('```')) {
+ inPre = !inPre;
+ html += inPre ? '<pre>' : '</pre>';
+ continue;
+ }
+ if (inPre) {
+ html += esc(l) + '\n';
+ continue;
+ }
+ if (/^### /.test(l)) {
+ html += `<h3>${inlineHtml(l.slice(4))}</h3>`;
+ continue;
+ }
+ if (/^## /.test(l)) {
+ html += `<h2>${inlineHtml(l.slice(3))}</h2>`;
+ continue;
+ }
+ if (/^# /.test(l)) {
+ html += `<h1>${inlineHtml(l.slice(2))}</h1>`;
+ continue;
+ }
+ if (/^> /.test(l)) {
+ html += `<blockquote>${inlineHtml(l.slice(2))}</blockquote>`;
+ continue;
+ }
+ if (l.trim() === '') {
+ html += '<br>';
+ continue;
+ }
html += `<p>${inlineHtml(l)}</p>`;
}
return html;
@@ -1198,36 +1378,35 @@ function buildZip(files) {
centralParts.push(centralHeader(f.nameBytes, f.data.length, f.crc, f.offset));
}
- const centralSize = centralParts.reduce((s, p) => s + p.length, 0);
+ const centralSize = centralParts.reduce((s, p) => s + p.length, 0);
const centralOffset = offset;
- const eocd = endRecord(localParts.length, centralSize, centralOffset);
+ const eocd = endRecord(localParts.length, centralSize, centralOffset);
- const chunks = [
- ...localParts.flatMap((f) => [f.local, f.data]),
- ...centralParts,
- eocd,
- ];
+ const chunks = [...localParts.flatMap((f) => [f.local, f.data]), ...centralParts, eocd];
const total = chunks.reduce((s, c) => s + c.length, 0);
- const out = new Uint8Array(total);
+ const out = new Uint8Array(total);
let pos = 0;
- for (const c of chunks) { out.set(c, pos); pos += c.length; }
+ for (const c of chunks) {
+ out.set(c, pos);
+ pos += c.length;
+ }
return out;
}
function localHeader(nameBytes, size, crc) {
const h = new Uint8Array(30 + nameBytes.length);
const v = new DataView(h.buffer);
- v.setUint32(0, 0x04034b50, true); // signature
- v.setUint16(4, 20, true); // version needed
- v.setUint16(6, 0, true); // flags
- v.setUint16(8, 0, true); // compression = stored
- v.setUint16(10, 0, true); // mod time
- v.setUint16(12, 0, true); // mod date
- v.setUint32(14, crc, true); // crc-32
- v.setUint32(18, size, true); // compressed size
- v.setUint32(22, size, true); // uncompressed size
+ v.setUint32(0, 0x04034b50, true); // signature
+ v.setUint16(4, 20, true); // version needed
+ v.setUint16(6, 0, true); // flags
+ v.setUint16(8, 0, true); // compression = stored
+ v.setUint16(10, 0, true); // mod time
+ v.setUint16(12, 0, true); // mod date
+ v.setUint32(14, crc, true); // crc-32
+ v.setUint32(18, size, true); // compressed size
+ v.setUint32(22, size, true); // uncompressed size
v.setUint16(26, nameBytes.length, true);
- v.setUint16(28, 0, true); // extra length
+ v.setUint16(28, 0, true); // extra length
h.set(nameBytes, 30);
return h;
}
@@ -1235,23 +1414,23 @@ function localHeader(nameBytes, size, crc) {
function centralHeader(nameBytes, size, crc, localOffset) {
const h = new Uint8Array(46 + nameBytes.length);
const v = new DataView(h.buffer);
- v.setUint32(0, 0x02014b50, true);
- v.setUint16(4, 0x031e, true); // version made by
- v.setUint16(6, 20, true); // version needed
- v.setUint16(8, 0, true); // flags
- v.setUint16(10, 0, true); // compression
- v.setUint16(12, 0, true); // mod time
- v.setUint16(14, 0, true); // mod date
- v.setUint32(16, crc, true);
- v.setUint32(20, size, true); // compressed
- v.setUint32(24, size, true); // uncompressed
+ v.setUint32(0, 0x02014b50, true);
+ v.setUint16(4, 0x031e, true); // version made by
+ v.setUint16(6, 20, true); // version needed
+ v.setUint16(8, 0, true); // flags
+ v.setUint16(10, 0, true); // compression
+ v.setUint16(12, 0, true); // mod time
+ v.setUint16(14, 0, true); // mod date
+ v.setUint32(16, crc, true);
+ v.setUint32(20, size, true); // compressed
+ v.setUint32(24, size, true); // uncompressed
v.setUint16(28, nameBytes.length, true);
- v.setUint16(30, 0, true); // extra
- v.setUint16(32, 0, true); // comment
- v.setUint16(34, 0, true); // disk start
- v.setUint16(36, 0, true); // internal attr
- v.setUint32(38, 0, true); // external attr
- v.setUint32(42, localOffset,true); // local header offset
+ v.setUint16(30, 0, true); // extra
+ v.setUint16(32, 0, true); // comment
+ v.setUint16(34, 0, true); // disk start
+ v.setUint16(36, 0, true); // internal attr
+ v.setUint32(38, 0, true); // external attr
+ v.setUint32(42, localOffset, true); // local header offset
h.set(nameBytes, 46);
return h;
}
@@ -1259,14 +1438,14 @@ function centralHeader(nameBytes, size, crc, localOffset) {
function endRecord(count, centralSize, centralOffset) {
const h = new Uint8Array(22);
const v = new DataView(h.buffer);
- v.setUint32(0, 0x06054b50, true);
- v.setUint16(4, 0, true); // disk number
- v.setUint16(6, 0, true); // disk with central dir
- v.setUint16(8, count, true);
- v.setUint16(10, count, true);
- v.setUint32(12, centralSize, true);
- v.setUint32(16, centralOffset,true);
- v.setUint16(20, 0, true); // comment length
+ v.setUint32(0, 0x06054b50, true);
+ v.setUint16(4, 0, true); // disk number
+ v.setUint16(6, 0, true); // disk with central dir
+ v.setUint16(8, count, true);
+ v.setUint16(10, count, true);
+ v.setUint32(12, centralSize, true);
+ v.setUint32(16, centralOffset, true);
+ v.setUint16(20, 0, true); // comment length
return h;
}
@@ -1289,6 +1468,8 @@ function crc32(tbl, data) {
// ─── Escape helper ────────────────────────────────────────────────────────────
function esc(s) {
- return String(s ?? '').replace(/[&<>"']/g, (c) =>
- ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+ return String(s ?? '').replace(
+ /[&<>"']/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
+ );
}
diff --git a/src/editor/material-editor.js b/src/editor/material-editor.js
index b26be0e34..ec243b941 100644
--- a/src/editor/material-editor.js
+++ b/src/editor/material-editor.js
@@ -75,11 +75,7 @@ export class MaterialEditor {
roughness: mat.roughness,
emissive: [mat.emissive.r, mat.emissive.g, mat.emissive.b],
opacity: mat.opacity,
- alphaMode: mat.transparent
- ? 'BLEND'
- : mat.alphaTest > 0
- ? 'MASK'
- : 'OPAQUE',
+ alphaMode: mat.transparent ? 'BLEND' : mat.alphaTest > 0 ? 'MASK' : 'OPAQUE',
alphaCutoff: mat.alphaTest,
doubleSided: mat.side === DoubleSide,
});
@@ -87,20 +83,26 @@ export class MaterialEditor {
this.viewer.invalidate();
};
- folder.addColor(proxy, 'color').name('base color').onChange((v) => {
- mat.color.set(v);
- record();
- });
+ folder
+ .addColor(proxy, 'color')
+ .name('base color')
+ .onChange((v) => {
+ mat.color.set(v);
+ record();
+ });
folder.add(mat, 'metalness', 0, 1, 0.01).onChange(record);
folder.add(mat, 'roughness', 0, 1, 0.01).onChange(record);
folder.addColor(proxy, 'emissive').onChange((v) => {
mat.emissive.set(v);
record();
});
- folder.add(mat, 'emissiveIntensity', 0, 4, 0.01).name('emissive int').onChange(() => {
- mat.needsUpdate = true;
- this.viewer.invalidate();
- });
+ folder
+ .add(mat, 'emissiveIntensity', 0, 4, 0.01)
+ .name('emissive int')
+ .onChange(() => {
+ mat.needsUpdate = true;
+ this.viewer.invalidate();
+ });
folder.add(mat, 'opacity', 0, 1, 0.01).onChange(() => {
mat.transparent = mat.opacity < 1;
record();
@@ -111,14 +113,20 @@ export class MaterialEditor {
mat.needsUpdate = true;
this.viewer.invalidate();
});
- folder.add(mat, 'flatShading').name('flat shading').onChange(() => {
- mat.needsUpdate = true;
- this.viewer.invalidate();
- });
- if (mat.envMapIntensity !== undefined) {
- folder.add(mat, 'envMapIntensity', 0, 4, 0.01).name('env map int').onChange(() => {
+ folder
+ .add(mat, 'flatShading')
+ .name('flat shading')
+ .onChange(() => {
+ mat.needsUpdate = true;
this.viewer.invalidate();
});
+ if (mat.envMapIntensity !== undefined) {
+ folder
+ .add(mat, 'envMapIntensity', 0, 4, 0.01)
+ .name('env map int')
+ .onChange(() => {
+ this.viewer.invalidate();
+ });
}
folder.add(proxy, 'side', Object.keys(SIDES)).onChange((v) => {
mat.side = SIDES[v];
diff --git a/src/editor/save-back.js b/src/editor/save-back.js
index e789d1742..87a60e0e7 100644
--- a/src/editor/save-back.js
+++ b/src/editor/save-back.js
@@ -26,7 +26,8 @@ export async function saveEditedAvatar(session, { avatarId, onStep = () => {} }
throw new SaveError('server', 'GLB export failed: ' + (e?.message || e));
}
if (!bytes?.byteLength) throw new SaveError('server', 'Empty GLB buffer');
- if (bytes.byteLength > MAX_BYTES) throw new SaveError('oversize', `GLB too large (${bytes.byteLength} bytes)`);
+ if (bytes.byteLength > MAX_BYTES)
+ throw new SaveError('oversize', `GLB too large (${bytes.byteLength} bytes)`);
onStep({ step: 'export', pct: 1 });
// 2. Presign
@@ -37,7 +38,10 @@ export async function saveEditedAvatar(session, { avatarId, onStep = () => {} }
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ size_bytes: bytes.byteLength, content_type: 'model/gltf-binary' }),
+ body: JSON.stringify({
+ size_bytes: bytes.byteLength,
+ content_type: 'model/gltf-binary',
+ }),
});
if (res.status === 401) throw new SaveError('auth', 'Not signed in');
if (!res.ok) {
@@ -58,7 +62,8 @@ export async function saveEditedAvatar(session, { avatarId, onStep = () => {} }
xhr.open('PUT', presign.upload_url, true);
for (const [k, v] of Object.entries(presign.headers || {})) xhr.setRequestHeader(k, v);
xhr.upload.onprogress = (e) => {
- if (e.lengthComputable) onStep({ step: 'upload', pct: Math.max(0, Math.min(1, e.loaded / e.total)) });
+ if (e.lengthComputable)
+ onStep({ step: 'upload', pct: Math.max(0, Math.min(1, e.loaded / e.total)) });
};
xhr.onerror = () => reject(new SaveError('network', 'Upload network error'));
xhr.onabort = () => reject(new SaveError('network', 'Upload aborted'));
diff --git a/src/editor/scene-explorer.js b/src/editor/scene-explorer.js
index 6496ee412..73936c6d4 100644
--- a/src/editor/scene-explorer.js
+++ b/src/editor/scene-explorer.js
@@ -70,7 +70,9 @@ export class SceneExplorer {
}
if (this.transformControls) {
this.transformControls.detach();
- const helper = this.transformControls.getHelper ? this.transformControls.getHelper() : this.transformControls;
+ const helper = this.transformControls.getHelper
+ ? this.transformControls.getHelper()
+ : this.transformControls;
this.viewer.scene.remove(helper);
this.transformControls.dispose?.();
this.transformControls = null;
@@ -217,10 +219,10 @@ export class SceneExplorer {
if (!this.inspectorEl) return;
const rad2deg = 180 / Math.PI;
const parts = [];
+ parts.push(`<div class="inspector__title">${escapeHTML(node.name || node.type)}</div>`);
parts.push(
- `<div class="inspector__title">${escapeHTML(node.name || node.type)}</div>`,
+ `<div class="inspector__sub">${node.type} · uuid: ${node.uuid.slice(0, 8)}</div>`,
);
- parts.push(`<div class="inspector__sub">${node.type} · uuid: ${node.uuid.slice(0, 8)}</div>`);
parts.push('<div class="inspector__section">Transform</div>');
parts.push(this._vec3Row('pos', [node.position.x, node.position.y, node.position.z]));
@@ -299,9 +301,9 @@ export class SceneExplorer {
inp.addEventListener('change', () => this._onVec3Change(node));
});
- this.inspectorEl.querySelector('[data-act="frame"]')?.addEventListener('click', () =>
- this._frameNode(node),
- );
+ this.inspectorEl
+ .querySelector('[data-act="frame"]')
+ ?.addEventListener('click', () => this._frameNode(node));
this.inspectorEl.querySelector('[data-act="hide"]')?.addEventListener('click', () => {
node.visible = !node.visible;
this.session.recordVisibilityEdit(node, node.visible);
@@ -404,7 +406,10 @@ export class SceneExplorer {
}
_setupTransformControls() {
- const tc = new TransformControls(this.viewer.defaultCamera, this.viewer.renderer.domElement);
+ const tc = new TransformControls(
+ this.viewer.defaultCamera,
+ this.viewer.renderer.domElement,
+ );
tc.addEventListener('dragging-changed', (e) => {
this.viewer.controls.enabled = !e.value;
});
diff --git a/src/editor/texture-inspector.js b/src/editor/texture-inspector.js
index 09328ff08..6b43ce15c 100644
--- a/src/editor/texture-inspector.js
+++ b/src/editor/texture-inspector.js
@@ -358,9 +358,12 @@ export class TextureInspector {
const by = (1 - uvAttr.getY(b)) * h;
const cx = uvAttr.getX(c) * w;
const cy = (1 - uvAttr.getY(c)) * h;
- uctx.moveTo(ax, ay); uctx.lineTo(bx, by);
- uctx.moveTo(bx, by); uctx.lineTo(cx, cy);
- uctx.moveTo(cx, cy); uctx.lineTo(ax, ay);
+ uctx.moveTo(ax, ay);
+ uctx.lineTo(bx, by);
+ uctx.moveTo(bx, by);
+ uctx.lineTo(cx, cy);
+ uctx.moveTo(cx, cy);
+ uctx.lineTo(ax, ay);
};
if (index) {
const arr = index.array;
@@ -387,19 +390,23 @@ export class TextureInspector {
};
applyTransform();
- viewport.addEventListener('wheel', (e) => {
- e.preventDefault();
- const factor = e.deltaY < 0 ? 1.15 : 1 / 1.15;
- const next = Math.max(0.1, Math.min(12, zoom * factor));
- // zoom toward cursor
- const rect = viewport.getBoundingClientRect();
- const cx = e.clientX - rect.left - rect.width / 2;
- const cy = e.clientY - rect.top - rect.height / 2;
- tx = cx - (cx - tx) * (next / zoom);
- ty = cy - (cy - ty) * (next / zoom);
- zoom = next;
- applyTransform();
- }, { passive: false });
+ viewport.addEventListener(
+ 'wheel',
+ (e) => {
+ e.preventDefault();
+ const factor = e.deltaY < 0 ? 1.15 : 1 / 1.15;
+ const next = Math.max(0.1, Math.min(12, zoom * factor));
+ // zoom toward cursor
+ const rect = viewport.getBoundingClientRect();
+ const cx = e.clientX - rect.left - rect.width / 2;
+ const cy = e.clientY - rect.top - rect.height / 2;
+ tx = cx - (cx - tx) * (next / zoom);
+ ty = cy - (cy - ty) * (next / zoom);
+ zoom = next;
+ applyTransform();
+ },
+ { passive: false },
+ );
viewport.addEventListener('mousedown', (e) => {
dragging = true;
@@ -421,7 +428,9 @@ export class TextureInspector {
});
const fit = () => {
- zoom = 1; tx = 0; ty = 0;
+ zoom = 1;
+ tx = 0;
+ ty = 0;
applyTransform();
};
diff --git a/src/erc8004/chain-meta.js b/src/erc8004/chain-meta.js
index 7a6acf7cd..778ee78d6 100644
--- a/src/erc8004/chain-meta.js
+++ b/src/erc8004/chain-meta.js
@@ -16,30 +16,184 @@ import { REGISTRY_DEPLOYMENTS } from './abi.js';
/** @type {Record<number, { name: string, shortName: string, currency: { name: string, symbol: string, decimals: number }, rpcUrl: string, explorer: string, testnet: boolean }>} */
export const CHAIN_META = {
// ── Mainnets ──────────────────────────────────────────────────────────
- 1: { name: 'Ethereum', shortName: 'ETH', currency: { name: 'Ether', symbol: 'ETH', decimals: 18 }, rpcUrl: 'https://ethereum-rpc.publicnode.com', explorer: 'https://etherscan.io', testnet: false },
- 10: { name: 'Optimism', shortName: 'OP', currency: { name: 'Ether', symbol: 'ETH', decimals: 18 }, rpcUrl: 'https://mainnet.optimism.io', explorer: 'https://optimistic.etherscan.io', testnet: false },
- 56: { name: 'BNB Chain', shortName: 'BSC', currency: { name: 'BNB', symbol: 'BNB', decimals: 18 }, rpcUrl: 'https://bsc-dataseed.bnbchain.org', explorer: 'https://bscscan.com', testnet: false },
- 100: { name: 'Gnosis', shortName: 'GNO', currency: { name: 'xDAI', symbol: 'xDAI', decimals: 18 }, rpcUrl: 'https://rpc.gnosischain.com', explorer: 'https://gnosisscan.io', testnet: false },
- 137: { name: 'Polygon', shortName: 'POL', currency: { name: 'POL', symbol: 'POL', decimals: 18 }, rpcUrl: 'https://polygon-rpc.com', explorer: 'https://polygonscan.com', testnet: false },
- 250: { name: 'Fantom', shortName: 'FTM', currency: { name: 'Fantom', symbol: 'FTM', decimals: 18 }, rpcUrl: 'https://rpc.ftm.tools', explorer: 'https://ftmscan.com', testnet: false },
- 324: { name: 'zkSync Era', shortName: 'zkSync', currency: { name: 'Ether', symbol: 'ETH', decimals: 18 }, rpcUrl: 'https://mainnet.era.zksync.io', explorer: 'https://explorer.zksync.io', testnet: false },
- 1284: { name: 'Moonbeam', shortName: 'GLMR', currency: { name: 'Glimmer', symbol: 'GLMR', decimals: 18 }, rpcUrl: 'https://rpc.api.moonbeam.network', explorer: 'https://moonbeam.moonscan.io', testnet: false },
- 5000: { name: 'Mantle', shortName: 'MNT', currency: { name: 'Mantle', symbol: 'MNT', decimals: 18 }, rpcUrl: 'https://rpc.mantle.xyz', explorer: 'https://explorer.mantle.xyz', testnet: false },
- 8453: { name: 'Base', shortName: 'Base', currency: { name: 'Ether', symbol: 'ETH', decimals: 18 }, rpcUrl: 'https://mainnet.base.org', explorer: 'https://basescan.org', testnet: false },
- 42161: { name: 'Arbitrum One', shortName: 'ARB', currency: { name: 'Ether', symbol: 'ETH', decimals: 18 }, rpcUrl: 'https://arb1.arbitrum.io/rpc', explorer: 'https://arbiscan.io', testnet: false },
- 42220: { name: 'Celo', shortName: 'CELO', currency: { name: 'Celo', symbol: 'CELO', decimals: 18 }, rpcUrl: 'https://forno.celo.org', explorer: 'https://celoscan.io', testnet: false },
- 43114: { name: 'Avalanche', shortName: 'AVAX', currency: { name: 'Avax', symbol: 'AVAX', decimals: 18 }, rpcUrl: 'https://api.avax.network/ext/bc/C/rpc', explorer: 'https://snowtrace.io', testnet: false },
- 59144: { name: 'Linea', shortName: 'Linea', currency: { name: 'Ether', symbol: 'ETH', decimals: 18 }, rpcUrl: 'https://rpc.linea.build', explorer: 'https://lineascan.build', testnet: false },
- 534352: { name: 'Scroll', shortName: 'Scroll', currency: { name: 'Ether', symbol: 'ETH', decimals: 18 }, rpcUrl: 'https://rpc.scroll.io', explorer: 'https://scrollscan.com', testnet: false },
+ 1: {
+ name: 'Ethereum',
+ shortName: 'ETH',
+ currency: { name: 'Ether', symbol: 'ETH', decimals: 18 },
+ rpcUrl: 'https://ethereum-rpc.publicnode.com',
+ explorer: 'https://etherscan.io',
+ testnet: false,
+ },
+ 10: {
+ name: 'Optimism',
+ shortName: 'OP',
+ currency: { name: 'Ether', symbol: 'ETH', decimals: 18 },
+ rpcUrl: 'https://mainnet.optimism.io',
+ explorer: 'https://optimistic.etherscan.io',
+ testnet: false,
+ },
+ 56: {
+ name: 'BNB Chain',
+ shortName: 'BSC',
+ currency: { name: 'BNB', symbol: 'BNB', decimals: 18 },
+ rpcUrl: 'https://bsc-dataseed.bnbchain.org',
+ explorer: 'https://bscscan.com',
+ testnet: false,
+ },
+ 100: {
+ name: 'Gnosis',
+ shortName: 'GNO',
+ currency: { name: 'xDAI', symbol: 'xDAI', decimals: 18 },
+ rpcUrl: 'https://rpc.gnosischain.com',
+ explorer: 'https://gnosisscan.io',
+ testnet: false,
+ },
+ 137: {
+ name: 'Polygon',
+ shortName: 'POL',
+ currency: { name: 'POL', symbol: 'POL', decimals: 18 },
+ rpcUrl: 'https://polygon-rpc.com',
+ explorer: 'https://polygonscan.com',
+ testnet: false,
+ },
+ 250: {
+ name: 'Fantom',
+ shortName: 'FTM',
+ currency: { name: 'Fantom', symbol: 'FTM', decimals: 18 },
+ rpcUrl: 'https://rpc.ftm.tools',
+ explorer: 'https://ftmscan.com',
+ testnet: false,
+ },
+ 324: {
+ name: 'zkSync Era',
+ shortName: 'zkSync',
+ currency: { name: 'Ether', symbol: 'ETH', decimals: 18 },
+ rpcUrl: 'https://mainnet.era.zksync.io',
+ explorer: 'https://explorer.zksync.io',
+ testnet: false,
+ },
+ 1284: {
+ name: 'Moonbeam',
+ shortName: 'GLMR',
+ currency: { name: 'Glimmer', symbol: 'GLMR', decimals: 18 },
+ rpcUrl: 'https://rpc.api.moonbeam.network',
+ explorer: 'https://moonbeam.moonscan.io',
+ testnet: false,
+ },
+ 5000: {
+ name: 'Mantle',
+ shortName: 'MNT',
+ currency: { name: 'Mantle', symbol: 'MNT', decimals: 18 },
+ rpcUrl: 'https://rpc.mantle.xyz',
+ explorer: 'https://explorer.mantle.xyz',
+ testnet: false,
+ },
+ 8453: {
+ name: 'Base',
+ shortName: 'Base',
+ currency: { name: 'Ether', symbol: 'ETH', decimals: 18 },
+ rpcUrl: 'https://mainnet.base.org',
+ explorer: 'https://basescan.org',
+ testnet: false,
+ },
+ 42161: {
+ name: 'Arbitrum One',
+ shortName: 'ARB',
+ currency: { name: 'Ether', symbol: 'ETH', decimals: 18 },
+ rpcUrl: 'https://arb1.arbitrum.io/rpc',
+ explorer: 'https://arbiscan.io',
+ testnet: false,
+ },
+ 42220: {
+ name: 'Celo',
+ shortName: 'CELO',
+ currency: { name: 'Celo', symbol: 'CELO', decimals: 18 },
+ rpcUrl: 'https://forno.celo.org',
+ explorer: 'https://celoscan.io',
+ testnet: false,
+ },
+ 43114: {
+ name: 'Avalanche',
+ shortName: 'AVAX',
+ currency: { name: 'Avax', symbol: 'AVAX', decimals: 18 },
+ rpcUrl: 'https://api.avax.network/ext/bc/C/rpc',
+ explorer: 'https://snowtrace.io',
+ testnet: false,
+ },
+ 59144: {
+ name: 'Linea',
+ shortName: 'Linea',
+ currency: { name: 'Ether', symbol: 'ETH', decimals: 18 },
+ rpcUrl: 'https://rpc.linea.build',
+ explorer: 'https://lineascan.build',
+ testnet: false,
+ },
+ 534352: {
+ name: 'Scroll',
+ shortName: 'Scroll',
+ currency: { name: 'Ether', symbol: 'ETH', decimals: 18 },
+ rpcUrl: 'https://rpc.scroll.io',
+ explorer: 'https://scrollscan.com',
+ testnet: false,
+ },
// ── Testnets ──────────────────────────────────────────────────────────
- 97: { name: 'BSC Testnet', shortName: 'BSCt', currency: { name: 'tBNB', symbol: 'tBNB', decimals: 18 }, rpcUrl: 'https://bsc-testnet-rpc.publicnode.com', explorer: 'https://testnet.bscscan.com', testnet: true },
- 11155111: { name: 'Ethereum Sepolia', shortName: 'Sep', currency: { name: 'SepETH',symbol: 'ETH', decimals: 18 }, rpcUrl: 'https://ethereum-sepolia-rpc.publicnode.com', explorer: 'https://sepolia.etherscan.io', testnet: true },
- 84532: { name: 'Base Sepolia', shortName: 'BaseSep', currency: { name: 'SepETH',symbol: 'ETH', decimals: 18 }, rpcUrl: 'https://sepolia.base.org', explorer: 'https://sepolia.basescan.org', testnet: true },
- 421614: { name: 'Arbitrum Sepolia', shortName: 'ArbSep', currency: { name: 'SepETH',symbol: 'ETH', decimals: 18 }, rpcUrl: 'https://sepolia-rollup.arbitrum.io/rpc', explorer: 'https://sepolia.arbiscan.io', testnet: true },
- 11155420: { name: 'Optimism Sepolia', shortName: 'OpSep', currency: { name: 'SepETH',symbol: 'ETH', decimals: 18 }, rpcUrl: 'https://sepolia.optimism.io', explorer: 'https://sepolia-optimism.etherscan.io', testnet: true },
- 80002: { name: 'Polygon Amoy', shortName: 'Amoy', currency: { name: 'POL', symbol: 'POL', decimals: 18 }, rpcUrl: 'https://rpc-amoy.polygon.technology', explorer: 'https://amoy.polygonscan.com', testnet: true },
- 43113: { name: 'Avalanche Fuji', shortName: 'Fuji', currency: { name: 'Avax', symbol: 'AVAX', decimals: 18 }, rpcUrl: 'https://api.avax-test.network/ext/bc/C/rpc', explorer: 'https://testnet.snowtrace.io', testnet: true },
+ 97: {
+ name: 'BSC Testnet',
+ shortName: 'BSCt',
+ currency: { name: 'tBNB', symbol: 'tBNB', decimals: 18 },
+ rpcUrl: 'https://bsc-testnet-rpc.publicnode.com',
+ explorer: 'https://testnet.bscscan.com',
+ testnet: true,
+ },
+ 11155111: {
+ name: 'Ethereum Sepolia',
+ shortName: 'Sep',
+ currency: { name: 'SepETH', symbol: 'ETH', decimals: 18 },
+ rpcUrl: 'https://ethereum-sepolia-rpc.publicnode.com',
+ explorer: 'https://sepolia.etherscan.io',
+ testnet: true,
+ },
+ 84532: {
+ name: 'Base Sepolia',
+ shortName: 'BaseSep',
+ currency: { name: 'SepETH', symbol: 'ETH', decimals: 18 },
+ rpcUrl: 'https://sepolia.base.org',
+ explorer: 'https://sepolia.basescan.org',
+ testnet: true,
+ },
+ 421614: {
+ name: 'Arbitrum Sepolia',
+ shortName: 'ArbSep',
+ currency: { name: 'SepETH', symbol: 'ETH', decimals: 18 },
+ rpcUrl: 'https://sepolia-rollup.arbitrum.io/rpc',
+ explorer: 'https://sepolia.arbiscan.io',
+ testnet: true,
+ },
+ 11155420: {
+ name: 'Optimism Sepolia',
+ shortName: 'OpSep',
+ currency: { name: 'SepETH', symbol: 'ETH', decimals: 18 },
+ rpcUrl: 'https://sepolia.optimism.io',
+ explorer: 'https://sepolia-optimism.etherscan.io',
+ testnet: true,
+ },
+ 80002: {
+ name: 'Polygon Amoy',
+ shortName: 'Amoy',
+ currency: { name: 'POL', symbol: 'POL', decimals: 18 },
+ rpcUrl: 'https://rpc-amoy.polygon.technology',
+ explorer: 'https://amoy.polygonscan.com',
+ testnet: true,
+ },
+ 43113: {
+ name: 'Avalanche Fuji',
+ shortName: 'Fuji',
+ currency: { name: 'Avax', symbol: 'AVAX', decimals: 18 },
+ rpcUrl: 'https://api.avax-test.network/ext/bc/C/rpc',
+ explorer: 'https://testnet.snowtrace.io',
+ testnet: true,
+ },
};
export const DEFAULT_CHAIN_ID = 97; // BSC Testnet
@@ -74,16 +228,22 @@ export async function switchChain(chainId, provider) {
try {
await eth.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: hex }] });
} catch (err) {
- if (err && (err.code === 4902 || /Unrecognized chain|not added|add.*chain/i.test(err.message || ''))) {
+ if (
+ err &&
+ (err.code === 4902 ||
+ /Unrecognized chain|not added|add.*chain/i.test(err.message || ''))
+ ) {
await eth.request({
method: 'wallet_addEthereumChain',
- params: [{
- chainId: hex,
- chainName: meta.name,
- nativeCurrency: meta.currency,
- rpcUrls: [meta.rpcUrl],
- blockExplorerUrls: [meta.explorer],
- }],
+ params: [
+ {
+ chainId: hex,
+ chainName: meta.name,
+ nativeCurrency: meta.currency,
+ rpcUrls: [meta.rpcUrl],
+ blockExplorerUrls: [meta.explorer],
+ },
+ ],
});
// wallet_addEthereumChain usually auto-switches, but force it to be safe.
await eth.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: hex }] });
diff --git a/src/erc8004/chains.js b/src/erc8004/chains.js
index 71da19c85..af6384079 100644
--- a/src/erc8004/chains.js
+++ b/src/erc8004/chains.js
@@ -21,30 +21,206 @@ import { REGISTRY_DEPLOYMENTS } from './abi.js';
/** @type {Record<number, ChainInfo>} */
export const CHAIN_INFO = {
// ── Mainnets ──────────────────────────────────────────────────────────
- 1: { chainId: 1, name: 'Ethereum', short: 'ETH', symbol: 'ETH', explorer: 'https://etherscan.io', rpc: 'https://eth.llamarpc.com', kind: 'mainnet' },
- 10: { chainId: 10, name: 'Optimism', short: 'OP', symbol: 'ETH', explorer: 'https://optimistic.etherscan.io', rpc: 'https://mainnet.optimism.io', kind: 'mainnet' },
- 56: { chainId: 56, name: 'BNB Chain', short: 'BSC', symbol: 'BNB', explorer: 'https://bscscan.com', rpc: 'https://bsc-dataseed.bnbchain.org', kind: 'mainnet' },
- 100: { chainId: 100, name: 'Gnosis', short: 'GNO', symbol: 'xDAI', explorer: 'https://gnosisscan.io', rpc: 'https://rpc.gnosischain.com', kind: 'mainnet' },
- 137: { chainId: 137, name: 'Polygon', short: 'MATIC', symbol: 'POL', explorer: 'https://polygonscan.com', rpc: 'https://polygon-rpc.com', kind: 'mainnet' },
- 250: { chainId: 250, name: 'Fantom', short: 'FTM', symbol: 'FTM', explorer: 'https://ftmscan.com', rpc: 'https://rpc.ftm.tools', kind: 'mainnet' },
- 324: { chainId: 324, name: 'zkSync Era', short: 'zkSync', symbol: 'ETH', explorer: 'https://explorer.zksync.io', rpc: 'https://mainnet.era.zksync.io', kind: 'mainnet' },
- 1284: { chainId: 1284, name: 'Moonbeam', short: 'GLMR', symbol: 'GLMR', explorer: 'https://moonscan.io', rpc: 'https://rpc.api.moonbeam.network', kind: 'mainnet' },
- 5000: { chainId: 5000, name: 'Mantle', short: 'MNT', symbol: 'MNT', explorer: 'https://explorer.mantle.xyz', rpc: 'https://rpc.mantle.xyz', kind: 'mainnet' },
- 8453: { chainId: 8453, name: 'Base', short: 'BASE', symbol: 'ETH', explorer: 'https://basescan.org', rpc: 'https://mainnet.base.org', kind: 'mainnet' },
- 42161: { chainId: 42161, name: 'Arbitrum One', short: 'ARB', symbol: 'ETH', explorer: 'https://arbiscan.io', rpc: 'https://arb1.arbitrum.io/rpc', kind: 'mainnet' },
- 42220: { chainId: 42220, name: 'Celo', short: 'CELO', symbol: 'CELO', explorer: 'https://celoscan.io', rpc: 'https://forno.celo.org', kind: 'mainnet' },
- 43114: { chainId: 43114, name: 'Avalanche', short: 'AVAX', symbol: 'AVAX', explorer: 'https://snowtrace.io', rpc: 'https://api.avax.network/ext/bc/C/rpc', kind: 'mainnet' },
- 59144: { chainId: 59144, name: 'Linea', short: 'LINEA', symbol: 'ETH', explorer: 'https://lineascan.build', rpc: 'https://rpc.linea.build', kind: 'mainnet' },
- 534352: { chainId: 534352, name: 'Scroll', short: 'SCR', symbol: 'ETH', explorer: 'https://scrollscan.com', rpc: 'https://rpc.scroll.io', kind: 'mainnet' },
+ 1: {
+ chainId: 1,
+ name: 'Ethereum',
+ short: 'ETH',
+ symbol: 'ETH',
+ explorer: 'https://etherscan.io',
+ rpc: 'https://eth.llamarpc.com',
+ kind: 'mainnet',
+ },
+ 10: {
+ chainId: 10,
+ name: 'Optimism',
+ short: 'OP',
+ symbol: 'ETH',
+ explorer: 'https://optimistic.etherscan.io',
+ rpc: 'https://mainnet.optimism.io',
+ kind: 'mainnet',
+ },
+ 56: {
+ chainId: 56,
+ name: 'BNB Chain',
+ short: 'BSC',
+ symbol: 'BNB',
+ explorer: 'https://bscscan.com',
+ rpc: 'https://bsc-dataseed.bnbchain.org',
+ kind: 'mainnet',
+ },
+ 100: {
+ chainId: 100,
+ name: 'Gnosis',
+ short: 'GNO',
+ symbol: 'xDAI',
+ explorer: 'https://gnosisscan.io',
+ rpc: 'https://rpc.gnosischain.com',
+ kind: 'mainnet',
+ },
+ 137: {
+ chainId: 137,
+ name: 'Polygon',
+ short: 'MATIC',
+ symbol: 'POL',
+ explorer: 'https://polygonscan.com',
+ rpc: 'https://polygon-rpc.com',
+ kind: 'mainnet',
+ },
+ 250: {
+ chainId: 250,
+ name: 'Fantom',
+ short: 'FTM',
+ symbol: 'FTM',
+ explorer: 'https://ftmscan.com',
+ rpc: 'https://rpc.ftm.tools',
+ kind: 'mainnet',
+ },
+ 324: {
+ chainId: 324,
+ name: 'zkSync Era',
+ short: 'zkSync',
+ symbol: 'ETH',
+ explorer: 'https://explorer.zksync.io',
+ rpc: 'https://mainnet.era.zksync.io',
+ kind: 'mainnet',
+ },
+ 1284: {
+ chainId: 1284,
+ name: 'Moonbeam',
+ short: 'GLMR',
+ symbol: 'GLMR',
+ explorer: 'https://moonscan.io',
+ rpc: 'https://rpc.api.moonbeam.network',
+ kind: 'mainnet',
+ },
+ 5000: {
+ chainId: 5000,
+ name: 'Mantle',
+ short: 'MNT',
+ symbol: 'MNT',
+ explorer: 'https://explorer.mantle.xyz',
+ rpc: 'https://rpc.mantle.xyz',
+ kind: 'mainnet',
+ },
+ 8453: {
+ chainId: 8453,
+ name: 'Base',
+ short: 'BASE',
+ symbol: 'ETH',
+ explorer: 'https://basescan.org',
+ rpc: 'https://mainnet.base.org',
+ kind: 'mainnet',
+ },
+ 42161: {
+ chainId: 42161,
+ name: 'Arbitrum One',
+ short: 'ARB',
+ symbol: 'ETH',
+ explorer: 'https://arbiscan.io',
+ rpc: 'https://arb1.arbitrum.io/rpc',
+ kind: 'mainnet',
+ },
+ 42220: {
+ chainId: 42220,
+ name: 'Celo',
+ short: 'CELO',
+ symbol: 'CELO',
+ explorer: 'https://celoscan.io',
+ rpc: 'https://forno.celo.org',
+ kind: 'mainnet',
+ },
+ 43114: {
+ chainId: 43114,
+ name: 'Avalanche',
+ short: 'AVAX',
+ symbol: 'AVAX',
+ explorer: 'https://snowtrace.io',
+ rpc: 'https://api.avax.network/ext/bc/C/rpc',
+ kind: 'mainnet',
+ },
+ 59144: {
+ chainId: 59144,
+ name: 'Linea',
+ short: 'LINEA',
+ symbol: 'ETH',
+ explorer: 'https://lineascan.build',
+ rpc: 'https://rpc.linea.build',
+ kind: 'mainnet',
+ },
+ 534352: {
+ chainId: 534352,
+ name: 'Scroll',
+ short: 'SCR',
+ symbol: 'ETH',
+ explorer: 'https://scrollscan.com',
+ rpc: 'https://rpc.scroll.io',
+ kind: 'mainnet',
+ },
// ── Testnets ──────────────────────────────────────────────────────────
- 97: { chainId: 97, name: 'BSC Testnet', short: 'tBSC', symbol: 'tBNB', explorer: 'https://testnet.bscscan.com', rpc: 'https://data-seed-prebsc-1-s1.bnbchain.org:8545', kind: 'testnet' },
- 11155111: { chainId: 11155111, name: 'Ethereum Sepolia', short: 'SEP', symbol: 'ETH', explorer: 'https://sepolia.etherscan.io', rpc: 'https://rpc.sepolia.org', kind: 'testnet' },
- 84532: { chainId: 84532, name: 'Base Sepolia', short: 'baseSep', symbol: 'ETH', explorer: 'https://sepolia.basescan.org', rpc: 'https://sepolia.base.org', kind: 'testnet' },
- 421614: { chainId: 421614, name: 'Arbitrum Sepolia', short: 'arbSep', symbol: 'ETH', explorer: 'https://sepolia.arbiscan.io', rpc: 'https://sepolia-rollup.arbitrum.io/rpc', kind: 'testnet' },
- 11155420: { chainId: 11155420, name: 'Optimism Sepolia', short: 'opSep', symbol: 'ETH', explorer: 'https://sepolia-optimism.etherscan.io', rpc: 'https://sepolia.optimism.io', kind: 'testnet' },
- 80002: { chainId: 80002, name: 'Polygon Amoy', short: 'Amoy', symbol: 'POL', explorer: 'https://amoy.polygonscan.com', rpc: 'https://rpc-amoy.polygon.technology', kind: 'testnet' },
- 43113: { chainId: 43113, name: 'Avalanche Fuji', short: 'Fuji', symbol: 'AVAX', explorer: 'https://testnet.snowtrace.io', rpc: 'https://api.avax-test.network/ext/bc/C/rpc', kind: 'testnet' },
+ 97: {
+ chainId: 97,
+ name: 'BSC Testnet',
+ short: 'tBSC',
+ symbol: 'tBNB',
+ explorer: 'https://testnet.bscscan.com',
+ rpc: 'https://data-seed-prebsc-1-s1.bnbchain.org:8545',
+ kind: 'testnet',
+ },
+ 11155111: {
+ chainId: 11155111,
+ name: 'Ethereum Sepolia',
+ short: 'SEP',
+ symbol: 'ETH',
+ explorer: 'https://sepolia.etherscan.io',
+ rpc: 'https://rpc.sepolia.org',
+ kind: 'testnet',
+ },
+ 84532: {
+ chainId: 84532,
+ name: 'Base Sepolia',
+ short: 'baseSep',
+ symbol: 'ETH',
+ explorer: 'https://sepolia.basescan.org',
+ rpc: 'https://sepolia.base.org',
+ kind: 'testnet',
+ },
+ 421614: {
+ chainId: 421614,
+ name: 'Arbitrum Sepolia',
+ short: 'arbSep',
+ symbol: 'ETH',
+ explorer: 'https://sepolia.arbiscan.io',
+ rpc: 'https://sepolia-rollup.arbitrum.io/rpc',
+ kind: 'testnet',
+ },
+ 11155420: {
+ chainId: 11155420,
+ name: 'Optimism Sepolia',
+ short: 'opSep',
+ symbol: 'ETH',
+ explorer: 'https://sepolia-optimism.etherscan.io',
+ rpc: 'https://sepolia.optimism.io',
+ kind: 'testnet',
+ },
+ 80002: {
+ chainId: 80002,
+ name: 'Polygon Amoy',
+ short: 'Amoy',
+ symbol: 'POL',
+ explorer: 'https://amoy.polygonscan.com',
+ rpc: 'https://rpc-amoy.polygon.technology',
+ kind: 'testnet',
+ },
+ 43113: {
+ chainId: 43113,
+ name: 'Avalanche Fuji',
+ short: 'Fuji',
+ symbol: 'AVAX',
+ explorer: 'https://testnet.snowtrace.io',
+ rpc: 'https://api.avax-test.network/ext/bc/C/rpc',
+ kind: 'testnet',
+ },
};
/** Default chain presented to new users. */
@@ -111,13 +287,15 @@ export async function requestSwitchChain(chainId) {
if (err?.code === 4902 || /unrecognized chain/i.test(err?.message || '')) {
await window.ethereum.request({
method: 'wallet_addEthereumChain',
- params: [{
- chainId: hex,
- chainName: info.name,
- nativeCurrency: { name: info.symbol, symbol: info.symbol, decimals: 18 },
- rpcUrls: [info.rpc],
- blockExplorerUrls: [info.explorer],
- }],
+ params: [
+ {
+ chainId: hex,
+ chainName: info.name,
+ nativeCurrency: { name: info.symbol, symbol: info.symbol, decimals: 18 },
+ rpcUrls: [info.rpc],
+ blockExplorerUrls: [info.explorer],
+ },
+ ],
});
} else {
throw err;
@@ -136,9 +314,13 @@ export function explorerUrl(chainId, kind, value) {
const info = getChainInfo(chainId);
if (!info) return '';
switch (kind) {
- case 'tx': return `${info.explorer}/tx/${value}`;
- case 'address': return `${info.explorer}/address/${value}`;
- case 'token': return `${info.explorer}/token/${value}`;
- default: return info.explorer;
+ case 'tx':
+ return `${info.explorer}/tx/${value}`;
+ case 'address':
+ return `${info.explorer}/address/${value}`;
+ case 'token':
+ return `${info.explorer}/token/${value}`;
+ default:
+ return info.explorer;
}
}
diff --git a/src/erc8004/enumeration.js b/src/erc8004/enumeration.js
index a1593be7a..f03d066f8 100644
--- a/src/erc8004/enumeration.js
+++ b/src/erc8004/enumeration.js
@@ -26,7 +26,7 @@ const IPFS_GATEWAYS = [
export function uriToHttp(uri) {
if (!uri) return '';
if (uri.startsWith('ipfs://')) return IPFS_GATEWAYS[0](uri.slice(7));
- if (uri.startsWith('ar://')) return `https://arweave.net/${uri.slice(5)}`;
+ if (uri.startsWith('ar://')) return `https://arweave.net/${uri.slice(5)}`;
return uri;
}
@@ -82,7 +82,9 @@ export async function getAgentsByOwner(registry, address, opts = {}) {
try {
const currentOwner = await registry.ownerOf(id);
if (currentOwner.toLowerCase() === address.toLowerCase()) tokenIds.push(id);
- } catch { /* burned — skip */ }
+ } catch {
+ /* burned — skip */
+ }
}
return { tokenIds, balance, strategy: 'event-scan' };
}
@@ -99,8 +101,16 @@ export async function fetchTokenMeta(registry, tokenId) {
let meta = null;
let owner = null;
- try { uri = await registry.tokenURI(tokenId); } catch { /* no URI set */ }
- try { owner = await registry.ownerOf(tokenId); } catch { /* burned */ }
+ try {
+ uri = await registry.tokenURI(tokenId);
+ } catch {
+ /* no URI set */
+ }
+ try {
+ owner = await registry.ownerOf(tokenId);
+ } catch {
+ /* burned */
+ }
if (uri) {
const urls = ipfsFallbackUrls(uri);
@@ -112,7 +122,9 @@ export async function fetchTokenMeta(registry, tokenId) {
meta = await r.json();
break;
}
- } catch { /* try next gateway */ }
+ } catch {
+ /* try next gateway */
+ }
}
}
return { id: tokenId, uri, meta, owner };
diff --git a/src/erc8004/explore.js b/src/erc8004/explore.js
index 5d06328b7..59cb5343a 100644
--- a/src/erc8004/explore.js
+++ b/src/erc8004/explore.js
@@ -197,7 +197,8 @@ class ExplorePage {
}
const type = detectInputType(v);
const label = INPUT_TYPE_LABEL[type];
- const cls = type === INPUT_TYPES.UNKNOWN ? 'explore-inputmeta--warn' : 'explore-inputmeta--ok';
+ const cls =
+ type === INPUT_TYPES.UNKNOWN ? 'explore-inputmeta--warn' : 'explore-inputmeta--ok';
el.className = `explore-input-meta ${cls}`;
el.textContent = `Detected: ${label}`;
}
@@ -440,7 +441,8 @@ class ExplorePage {
? `Agent #${esc(this._query)} not found on any selected chain`
: `Agent #${esc(this._query)} on ${n} chain${n === 1 ? '' : 's'}`;
} else if (type === INPUT_TYPES.AGENT_URI) {
- title = n === 0 ? `Agent not found` : `Agent on ${esc(this._results[0]?.chainName || '?')}`;
+ title =
+ n === 0 ? `Agent not found` : `Agent on ${esc(this._results[0]?.chainName || '?')}`;
sub = `<code>${esc(this._query)}</code>`;
}
@@ -789,7 +791,9 @@ function openEmbedModal({ chainId, agentId, name }) {
if (e.key === 'Escape') close();
};
document.addEventListener('keydown', onEsc);
- modal.querySelectorAll('[data-role="close"]').forEach((el) => el.addEventListener('click', close));
+ modal
+ .querySelectorAll('[data-role="close"]')
+ .forEach((el) => el.addEventListener('click', close));
modal.querySelectorAll('.embed-tab').forEach((tab) => {
tab.addEventListener('click', () => {
diff --git a/src/erc8004/index.js b/src/erc8004/index.js
index 60f5981be..0fa7ad001 100644
--- a/src/erc8004/index.js
+++ b/src/erc8004/index.js
@@ -5,8 +5,24 @@ export {
REGISTRY_DEPLOYMENTS,
agentRegistryId,
} from './abi.js';
-export { connectWallet, registerAgent, buildRegistrationJSON, pinToIPFS } from './agent-registry.js';
+export {
+ connectWallet,
+ registerAgent,
+ buildRegistrationJSON,
+ pinToIPFS,
+} from './agent-registry.js';
export { RegisterUI } from './register-ui.js';
export { submitReputation, submitFeedback, getReputation, getRecentReviews } from './reputation.js';
-export { recordValidation, getLatestValidation, reportPassed, hashReport } from './validation-recorder.js';
-export { initPrivy, loginWithPrivy, connectWithPrivy, logoutPrivy, isPrivyConfigured } from './privy.js';
+export {
+ recordValidation,
+ getLatestValidation,
+ reportPassed,
+ hashReport,
+} from './validation-recorder.js';
+export {
+ initPrivy,
+ loginWithPrivy,
+ connectWithPrivy,
+ logoutPrivy,
+ isPrivyConfigured,
+} from './privy.js';
diff --git a/src/erc8004/privy.js b/src/erc8004/privy.js
index ff161461b..f1f38f545 100644
--- a/src/erc8004/privy.js
+++ b/src/erc8004/privy.js
@@ -27,7 +27,10 @@ const BUILD_APP_ID = import.meta.env.VITE_PRIVY_APP_ID || '';
*/
async function resolveAppId() {
if (_resolvedAppId !== null) return _resolvedAppId;
- if (BUILD_APP_ID) { _resolvedAppId = BUILD_APP_ID; return _resolvedAppId; }
+ if (BUILD_APP_ID) {
+ _resolvedAppId = BUILD_APP_ID;
+ return _resolvedAppId;
+ }
if (_appIdPromise) return _appIdPromise;
_appIdPromise = (async () => {
diff --git a/src/erc8004/queries.js b/src/erc8004/queries.js
index 96eab6f19..5387e14c7 100644
--- a/src/erc8004/queries.js
+++ b/src/erc8004/queries.js
@@ -90,7 +90,9 @@ export async function listAgentsByOwner({ chainId, owner, ethProvider, eventScan
ids.push(id);
}
return { ids, count, partial: false, mode: 'enumerable' };
- } catch { /* fall through */ }
+ } catch {
+ /* fall through */
+ }
// 2. Event-scan fallback
try {
@@ -107,15 +109,19 @@ export async function listAgentsByOwner({ chainId, owner, ethProvider, eventScan
try {
const currentOwner = await registry.ownerOf(id);
if (currentOwner.toLowerCase() === owner.toLowerCase()) idsFromEvents.push(id);
- } catch { /* ignore burned/missing */ }
+ } catch {
+ /* ignore burned/missing */
+ }
}
return {
- ids: idsFromEvents,
+ ids: idsFromEvents,
count,
partial: idsFromEvents.length < count,
- mode: 'events',
+ mode: 'events',
};
- } catch { /* fall through */ }
+ } catch {
+ /* fall through */
+ }
// 3. Count-only
return { ids: [], count, partial: true, mode: 'count-only' };
@@ -133,7 +139,13 @@ export async function listAgentsByOwner({ chainId, owner, ethProvider, eventScan
* @param {number} [opts.limit] Max events returned (newest first)
* @returns {Promise<Array<{ agentId: bigint, agentURI: string, owner: string, blockNumber: number, txHash: string }>>}
*/
-export async function listRegisteredEvents({ chainId, owner, ethProvider, blocks = 500000, limit = 100 }) {
+export async function listRegisteredEvents({
+ chainId,
+ owner,
+ ethProvider,
+ blocks = 500000,
+ limit = 100,
+}) {
const registry = getReadRegistry(chainId, ethProvider);
const provider = registry.runner.provider || registry.runner;
const latest = await provider.getBlockNumber();
@@ -148,11 +160,11 @@ export async function listRegisteredEvents({ chainId, owner, ethProvider, blocks
.reverse()
.slice(0, limit)
.map((ev) => ({
- agentId: ev.args.agentId,
- agentURI: ev.args.agentURI,
- owner: ev.args.owner,
+ agentId: ev.args.agentId,
+ agentURI: ev.args.agentURI,
+ owner: ev.args.owner,
blockNumber: ev.blockNumber,
- txHash: ev.transactionHash,
+ txHash: ev.transactionHash,
}));
return out;
}
diff --git a/src/erc8004/resolve-avatar.js b/src/erc8004/resolve-avatar.js
index 924ecd537..d5801ab6e 100644
--- a/src/erc8004/resolve-avatar.js
+++ b/src/erc8004/resolve-avatar.js
@@ -146,7 +146,8 @@ export async function hydrateAgent({ chainId, agentId, ethProvider }) {
x402: false,
serviceTypes: [],
viewerUrl: `/a/${chainId}/${String(agentId)}`,
- tokenExplorerUrl: registry && meta ? `${meta.explorer}/token/${registry}?a=${String(agentId)}` : '',
+ tokenExplorerUrl:
+ registry && meta ? `${meta.explorer}/token/${registry}?a=${String(agentId)}` : '',
ownerExplorerUrl: '',
registry,
};
@@ -412,7 +413,12 @@ export async function autoResolve({
return { type, results };
}
case INPUT_TYPES.TX_HASH: {
- const results = await resolveByTxHash({ txHash: trimmed, chainIds, ethProvider, onProgress });
+ const results = await resolveByTxHash({
+ txHash: trimmed,
+ chainIds,
+ ethProvider,
+ onProgress,
+ });
return { type, results };
}
case INPUT_TYPES.ADDRESS: {
@@ -439,7 +445,9 @@ export async function autoResolve({
return { type, resolvedAddress: address, results };
}
default:
- throw new Error(`Unrecognized input: "${trimmed}". Paste an address, ENS name, tx hash, or agent ID.`);
+ throw new Error(
+ `Unrecognized input: "${trimmed}". Paste an address, ENS name, tx hash, or agent ID.`,
+ );
}
}
diff --git a/src/erc8004/showcase.js b/src/erc8004/showcase.js
index a2f19cd59..c291d4fc0 100644
--- a/src/erc8004/showcase.js
+++ b/src/erc8004/showcase.js
@@ -33,7 +33,9 @@ function loadNet() {
return 'mainnet';
}
function saveNet(v) {
- try { localStorage.setItem(NET_KEY, v); } catch {}
+ try {
+ localStorage.setItem(NET_KEY, v);
+ } catch {}
}
function loadSort() {
@@ -44,7 +46,9 @@ function loadSort() {
return 'newest';
}
function saveSort(v) {
- try { localStorage.setItem(SORT_KEY, v); } catch {}
+ try {
+ localStorage.setItem(SORT_KEY, v);
+ } catch {}
}
function loadChains() {
@@ -59,7 +63,9 @@ function loadChains() {
}
}
function saveChains(ids) {
- try { localStorage.setItem(CHAINS_KEY, JSON.stringify(ids)); } catch {}
+ try {
+ localStorage.setItem(CHAINS_KEY, JSON.stringify(ids));
+ } catch {}
}
function splitChains() {
@@ -277,7 +283,12 @@ class ShowcasePage {
_renderChainChips() {
const root = this.container.querySelector('[data-role="chainChips"]');
const { mainnet, testnet } = splitChains();
- const pool = this._net === 'mainnet' ? mainnet : this._net === 'testnet' ? testnet : [...mainnet, ...testnet];
+ const pool =
+ this._net === 'mainnet'
+ ? mainnet
+ : this._net === 'testnet'
+ ? testnet
+ : [...mainnet, ...testnet];
const chip = (id) => {
const m = CHAIN_META[id];
@@ -392,13 +403,16 @@ class ShowcasePage {
if (skeleton) {
out.innerHTML = `
<div class="showcase-grid" aria-busy="true">
- ${Array.from({ length: 8 }, () => `
+ ${Array.from(
+ { length: 8 },
+ () => `
<div class="showcase-card showcase-card--skel">
<div class="showcase-skel-img"></div>
<div class="showcase-skel-line"></div>
<div class="showcase-skel-line showcase-skel-line--short"></div>
</div>
- `).join('')}
+ `,
+ ).join('')}
</div>
`;
return;
@@ -436,7 +450,9 @@ class ShowcasePage {
<button type="button" class="showcase-btn" data-role="retry">Retry</button>
</div>
`;
- out.querySelector('[data-role="retry"]').addEventListener('click', () => this._resetAndLoad());
+ out.querySelector('[data-role="retry"]').addEventListener('click', () =>
+ this._resetAndLoad(),
+ );
}
_wireCardShare(root) {
diff --git a/src/erc8004/validation-recorder.js b/src/erc8004/validation-recorder.js
index d3cb4e7a4..a7538123e 100644
--- a/src/erc8004/validation-recorder.js
+++ b/src/erc8004/validation-recorder.js
@@ -74,11 +74,7 @@ export async function recordValidation({
proofURI = `ipfs://${cid}`;
}
- const contract = new Contract(
- deployment.validationRegistry,
- VALIDATION_REGISTRY_ABI,
- signer,
- );
+ const contract = new Contract(deployment.validationRegistry, VALIDATION_REGISTRY_ABI, signer);
const tx = await contract.recordValidation(agentId, passed, proofHash, proofURI, kind);
await tx.wait();
@@ -98,10 +94,6 @@ export async function getLatestValidation({ agentId, runner, chainId, kind = KIN
if (!deployment || !deployment.validationRegistry) {
throw new Error(`No Validation Registry deployed on chain ${chainId}.`);
}
- const contract = new Contract(
- deployment.validationRegistry,
- VALIDATION_REGISTRY_ABI,
- runner,
- );
+ const contract = new Contract(deployment.validationRegistry, VALIDATION_REGISTRY_ABI, runner);
return contract.getLatestByKind(agentId, kind);
}
diff --git a/src/features/hero-dragon.js b/src/features/hero-dragon.js
index 80b229c83..626ea0b8c 100644
--- a/src/features/hero-dragon.js
+++ b/src/features/hero-dragon.js
@@ -11,56 +11,60 @@
// Auto-downgrade: if mean reflow cost over a 30-frame window exceeds
// COST_BUDGET_MS, disable per-frame relayout and keep the chase running.
-const STIFFNESS = 120;
-const DAMPING = 20;
-const MASS = 1;
-const RETURN_EPS_POS = 0.5; // px
-const RETURN_EPS_VEL = 5; // px/s
+const STIFFNESS = 120;
+const DAMPING = 20;
+const MASS = 1;
+const RETURN_EPS_POS = 0.5; // px
+const RETURN_EPS_VEL = 5; // px/s
const COST_BUDGET_MS = 8;
-const COST_WINDOW = 30;
-const HERO_INSET = 16; // px — keep avatar fully inside hero
+const COST_WINDOW = 30;
+const HERO_INSET = 16; // px — keep avatar fully inside hero
function prefersReducedMotion() {
- return typeof window !== 'undefined'
- && window.matchMedia
- && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+ return (
+ typeof window !== 'undefined' &&
+ window.matchMedia &&
+ window.matchMedia('(prefers-reduced-motion: reduce)').matches
+ );
}
function hasHover() {
- return typeof window !== 'undefined'
- && window.matchMedia
- && window.matchMedia('(hover: hover)').matches;
+ return (
+ typeof window !== 'undefined' &&
+ window.matchMedia &&
+ window.matchMedia('(hover: hover)').matches
+ );
}
export class HeroDragon {
constructor(hero) {
- this.hero = hero;
- this.root = hero.root;
- this.avatar = hero.avatar;
+ this.hero = hero;
+ this.root = hero.root;
+ this.avatar = hero.avatar;
this.modelViewer = hero.modelViewer;
this._targetX = 0;
this._targetY = 0;
- this._x = 0;
- this._y = 0;
+ this._x = 0;
+ this._y = 0;
this._vx = 0;
this._vy = 0;
- this._homeRect = null;
- this._heroRect = null;
- this._lastTs = 0;
- this._rafId = null;
- this._attached = false;
+ this._homeRect = null;
+ this._heroRect = null;
+ this._lastTs = 0;
+ this._rafId = null;
+ this._attached = false;
this._returning = false;
this._costSamples = [];
- this._downgraded = false;
+ this._downgraded = false;
- this._onPointerMove = this._onPointerMove.bind(this);
+ this._onPointerMove = this._onPointerMove.bind(this);
this._onPointerLeave = this._onPointerLeave.bind(this);
- this._onResize = this._onResize.bind(this);
- this._onVisibility = this._onVisibility.bind(this);
- this._tick = this._tick.bind(this);
+ this._onResize = this._onResize.bind(this);
+ this._onVisibility = this._onVisibility.bind(this);
+ this._tick = this._tick.bind(this);
}
attach() {
@@ -82,14 +86,14 @@ export class HeroDragon {
this.hero.recomputeContext?.();
this._paint();
- this.root.addEventListener('pointermove', this._onPointerMove, { passive: true });
+ this.root.addEventListener('pointermove', this._onPointerMove, { passive: true });
this.root.addEventListener('pointerleave', this._onPointerLeave);
window.addEventListener('resize', this._onResize, { passive: true });
window.addEventListener('scroll', this._onResize, { passive: true });
document.addEventListener('visibilitychange', this._onVisibility);
this._lastTs = performance.now();
- this._rafId = requestAnimationFrame(this._tick);
+ this._rafId = requestAnimationFrame(this._tick);
});
}
@@ -97,7 +101,7 @@ export class HeroDragon {
if (!this._attached) return;
this._attached = false;
- this.root.removeEventListener('pointermove', this._onPointerMove);
+ this.root.removeEventListener('pointermove', this._onPointerMove);
this.root.removeEventListener('pointerleave', this._onPointerLeave);
window.removeEventListener('resize', this._onResize);
window.removeEventListener('scroll', this._onResize);
@@ -108,7 +112,7 @@ export class HeroDragon {
this.root.classList.remove('hero--dragon');
if (this.avatar) {
- this.avatar.style.transform = '';
+ this.avatar.style.transform = '';
this.avatar.style.willChange = '';
}
this._setAutoRotate(true);
@@ -133,8 +137,8 @@ export class HeroDragon {
// but using the avatar's home rect.
const r = this._homeRect ?? ctx.avatarRect;
return {
- x: (r.left + r.width / 2) - ctx.subtitleLeftPage,
- y: (r.top + r.height / 2) - ctx.subtitleTopPage,
+ x: r.left + r.width / 2 - ctx.subtitleLeftPage,
+ y: r.top + r.height / 2 - ctx.subtitleTopPage,
r: ctx.circleBaseR,
};
}
@@ -155,7 +159,7 @@ export class HeroDragon {
this._rafId = null;
} else if (this._attached && this._rafId == null) {
this._lastTs = performance.now();
- this._rafId = requestAnimationFrame(this._tick);
+ this._rafId = requestAnimationFrame(this._tick);
}
}
@@ -164,15 +168,15 @@ export class HeroDragon {
const hero = this._heroRect;
if (!home || !hero) return;
- const homeCx = home.left + home.width / 2;
- const homeCy = home.top + home.height / 2;
+ const homeCx = home.left + home.width / 2;
+ const homeCy = home.top + home.height / 2;
// Clamp so the avatar rect stays within the hero rect (minus inset).
- const halfW = home.width / 2;
+ const halfW = home.width / 2;
const halfH = home.height / 2;
- const minCx = hero.left + halfW + HERO_INSET;
- const maxCx = hero.right - halfW - HERO_INSET;
- const minCy = hero.top + halfH + HERO_INSET;
+ const minCx = hero.left + halfW + HERO_INSET;
+ const maxCx = hero.right - halfW - HERO_INSET;
+ const minCy = hero.top + halfH + HERO_INSET;
const maxCy = hero.bottom - halfH - HERO_INSET;
const cx = Math.min(maxCx, Math.max(minCx, e.clientX));
@@ -202,8 +206,8 @@ export class HeroDragon {
const ay = (STIFFNESS * (this._targetY - this._y) - DAMPING * this._vy) / MASS;
this._vx += ax * dt;
this._vy += ay * dt;
- this._x += this._vx * dt;
- this._y += this._vy * dt;
+ this._x += this._vx * dt;
+ this._y += this._vy * dt;
this.avatar.style.transform = `translate3d(${this._x.toFixed(2)}px, ${this._y.toFixed(2)}px, 0)`;
@@ -213,8 +217,8 @@ export class HeroDragon {
// the static wrap and auto-rotate resume.
if (this._returning) {
const settled =
- Math.abs(this._x) < RETURN_EPS_POS &&
- Math.abs(this._y) < RETURN_EPS_POS &&
+ Math.abs(this._x) < RETURN_EPS_POS &&
+ Math.abs(this._y) < RETURN_EPS_POS &&
Math.abs(this._vx) < RETURN_EPS_VEL &&
Math.abs(this._vy) < RETURN_EPS_VEL;
if (settled) {
@@ -234,10 +238,10 @@ export class HeroDragon {
const home = this._homeRect;
if (!home) return;
- const homeCxPage = home.left + home.width / 2;
- const homeCyPage = home.top + home.height / 2;
- const cx = (homeCxPage + this._x) - ctx.subtitleLeftPage;
- const cy = (homeCyPage + this._y) - ctx.subtitleTopPage;
+ const homeCxPage = home.left + home.width / 2;
+ const homeCyPage = home.top + home.height / 2;
+ const cx = homeCxPage + this._x - ctx.subtitleLeftPage;
+ const cy = homeCyPage + this._y - ctx.subtitleTopPage;
const cost = this.hero.paintCircle?.(cx, cy, ctx.circleBaseR) ?? 0;
@@ -256,6 +260,6 @@ export class HeroDragon {
_setAutoRotate(on) {
if (!this.modelViewer) return;
if (on) this.modelViewer.setAttribute('auto-rotate', '');
- else this.modelViewer.removeAttribute('auto-rotate');
+ else this.modelViewer.removeAttribute('auto-rotate');
}
}
diff --git a/src/features/hero-gaze.js b/src/features/hero-gaze.js
index 61a1efa4e..5e8b54988 100644
--- a/src/features/hero-gaze.js
+++ b/src/features/hero-gaze.js
@@ -10,49 +10,53 @@
// orbit and auto-rotate resumes.
// Defaults must match features.html's camera-orbit attribute.
-const BASE_THETA_DEG = 20;
-const BASE_PHI_DEG = 68;
-const BASE_RADIUS = '3.4m';
-const THETA_RANGE_DEG = 15; // ±15° azimuth — subtle but legible
-const PHI_RANGE_DEG = 8; // ±8° polar
-const IDLE_MS = 1200; // Resume auto-rotate after this quiet
-const SMOOTH = 0.12; // Lerp alpha toward target per frame (~60fps)
-const SETTLE_EPSILON = 0.05; // Degrees — below this we consider the return complete
+const BASE_THETA_DEG = 20;
+const BASE_PHI_DEG = 68;
+const BASE_RADIUS = '3.4m';
+const THETA_RANGE_DEG = 15; // ±15° azimuth — subtle but legible
+const PHI_RANGE_DEG = 8; // ±8° polar
+const IDLE_MS = 1200; // Resume auto-rotate after this quiet
+const SMOOTH = 0.12; // Lerp alpha toward target per frame (~60fps)
+const SETTLE_EPSILON = 0.05; // Degrees — below this we consider the return complete
function prefersReducedMotion() {
- return typeof window !== 'undefined'
- && window.matchMedia
- && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+ return (
+ typeof window !== 'undefined' &&
+ window.matchMedia &&
+ window.matchMedia('(prefers-reduced-motion: reduce)').matches
+ );
}
function hasHover() {
- return typeof window !== 'undefined'
- && window.matchMedia
- && window.matchMedia('(hover: hover)').matches;
+ return (
+ typeof window !== 'undefined' &&
+ window.matchMedia &&
+ window.matchMedia('(hover: hover)').matches
+ );
}
export class HeroGaze {
constructor(hero) {
- this.hero = hero;
- this.root = hero.root;
- this.avatar = hero.avatar;
+ this.hero = hero;
+ this.root = hero.root;
+ this.avatar = hero.avatar;
this.modelViewer = hero.modelViewer;
- this._targetTheta = BASE_THETA_DEG;
- this._targetPhi = BASE_PHI_DEG;
+ this._targetTheta = BASE_THETA_DEG;
+ this._targetPhi = BASE_PHI_DEG;
this._currentTheta = BASE_THETA_DEG;
- this._currentPhi = BASE_PHI_DEG;
+ this._currentPhi = BASE_PHI_DEG;
this._avatarRect = null;
this._lastMoveAt = 0;
- this._rafId = null;
- this._tracking = false;
- this._attached = false;
+ this._rafId = null;
+ this._tracking = false;
+ this._attached = false;
- this._onPointerMove = this._onPointerMove.bind(this);
+ this._onPointerMove = this._onPointerMove.bind(this);
this._onPointerLeave = this._onPointerLeave.bind(this);
- this._onResize = this._onResize.bind(this);
- this._tick = this._tick.bind(this);
+ this._onResize = this._onResize.bind(this);
+ this._tick = this._tick.bind(this);
}
attach() {
@@ -66,7 +70,7 @@ export class HeroGaze {
this._attached = true;
this._refreshRect();
- this.root.addEventListener('pointermove', this._onPointerMove, { passive: true });
+ this.root.addEventListener('pointermove', this._onPointerMove, { passive: true });
this.root.addEventListener('pointerleave', this._onPointerLeave);
window.addEventListener('resize', this._onResize, { passive: true });
window.addEventListener('scroll', this._onResize, { passive: true });
@@ -78,7 +82,7 @@ export class HeroGaze {
if (!this._attached) return;
this._attached = false;
- this.root.removeEventListener('pointermove', this._onPointerMove);
+ this.root.removeEventListener('pointermove', this._onPointerMove);
this.root.removeEventListener('pointerleave', this._onPointerLeave);
window.removeEventListener('resize', this._onResize);
window.removeEventListener('scroll', this._onResize);
@@ -110,21 +114,23 @@ export class HeroGaze {
const rect = this._avatarRect;
if (!rect || rect.width === 0 || rect.height === 0) return;
- const cx = rect.left + rect.width / 2;
- const cy = rect.top + rect.height / 2;
+ const cx = rect.left + rect.width / 2;
+ const cy = rect.top + rect.height / 2;
// Normalize to [-1, 1] relative to avatar's own half-extents so the
// signal is strongest as the cursor approaches the avatar and clamps
// at the edges of the hero.
- let nx = (e.clientX - cx) / (rect.width / 2);
+ let nx = (e.clientX - cx) / (rect.width / 2);
let ny = (e.clientY - cy) / (rect.height / 2);
- if (nx < -1) nx = -1; else if (nx > 1) nx = 1;
- if (ny < -1) ny = -1; else if (ny > 1) ny = 1;
+ if (nx < -1) nx = -1;
+ else if (nx > 1) nx = 1;
+ if (ny < -1) ny = -1;
+ else if (ny > 1) ny = 1;
this._targetTheta = BASE_THETA_DEG + nx * THETA_RANGE_DEG;
// Cursor moving down (ny > 0) should tilt the avatar's gaze down too,
// which in model-viewer's polar convention means increasing phi.
- this._targetPhi = BASE_PHI_DEG + ny * PHI_RANGE_DEG;
+ this._targetPhi = BASE_PHI_DEG + ny * PHI_RANGE_DEG;
this._lastMoveAt = performance.now();
@@ -138,15 +144,15 @@ export class HeroGaze {
// Ease back to base; the tick loop will flip auto-rotate back on once
// we've settled near the default orbit.
this._targetTheta = BASE_THETA_DEG;
- this._targetPhi = BASE_PHI_DEG;
- this._lastMoveAt = 0;
+ this._targetPhi = BASE_PHI_DEG;
+ this._lastMoveAt = 0;
}
_tick() {
if (!this._attached) return;
this._currentTheta += (this._targetTheta - this._currentTheta) * SMOOTH;
- this._currentPhi += (this._targetPhi - this._currentPhi) * SMOOTH;
+ this._currentPhi += (this._targetPhi - this._currentPhi) * SMOOTH;
if (this._tracking) {
const orbit = `${this._currentTheta.toFixed(2)}deg ${this._currentPhi.toFixed(2)}deg ${BASE_RADIUS}`;
@@ -157,20 +163,24 @@ export class HeroGaze {
const idleFor = this._lastMoveAt > 0 ? now - this._lastMoveAt : 0;
const settled =
Math.abs(this._currentTheta - BASE_THETA_DEG) < SETTLE_EPSILON &&
- Math.abs(this._currentPhi - BASE_PHI_DEG) < SETTLE_EPSILON;
+ Math.abs(this._currentPhi - BASE_PHI_DEG) < SETTLE_EPSILON;
// Resume auto-rotate either after a quiet window (cursor still over the
// hero but idle) or after pointerleave once the avatar has eased home.
- const shouldResume = this._lastMoveAt === 0
- ? settled // pointerleave: wait for ease-back to complete
- : idleFor > IDLE_MS; // idle: cursor still in hero but stopped
+ const shouldResume =
+ this._lastMoveAt === 0
+ ? settled // pointerleave: wait for ease-back to complete
+ : idleFor > IDLE_MS; // idle: cursor still in hero but stopped
if (this._tracking && shouldResume) {
this._tracking = false;
if (this._lastMoveAt === 0 && settled) {
// Snap to the canonical orbit so auto-rotate picks up cleanly.
- this.modelViewer.setAttribute('camera-orbit', `${BASE_THETA_DEG}deg ${BASE_PHI_DEG}deg ${BASE_RADIUS}`);
+ this.modelViewer.setAttribute(
+ 'camera-orbit',
+ `${BASE_THETA_DEG}deg ${BASE_PHI_DEG}deg ${BASE_RADIUS}`,
+ );
this._currentTheta = BASE_THETA_DEG;
- this._currentPhi = BASE_PHI_DEG;
+ this._currentPhi = BASE_PHI_DEG;
}
this._setAutoRotate(true);
}
@@ -181,6 +191,6 @@ export class HeroGaze {
_setAutoRotate(on) {
if (!this.modelViewer) return;
if (on) this.modelViewer.setAttribute('auto-rotate', '');
- else this.modelViewer.removeAttribute('auto-rotate');
+ else this.modelViewer.removeAttribute('auto-rotate');
}
}
diff --git a/src/features/hero-pretext.js b/src/features/hero-pretext.js
index 2dd5f721d..8cf699388 100644
--- a/src/features/hero-pretext.js
+++ b/src/features/hero-pretext.js
@@ -9,23 +9,23 @@ const RESIZE_DEBOUNCE_MS = 120;
export default class PretextHero {
constructor(root, options = {}) {
- this.root = root;
- this.content = root?.querySelector('.hero-content') || null;
- this.title = root?.querySelector('.hero-title') || null;
- this.subtitle = root?.querySelector('.hero-subtitle') || null;
- this.avatar = root?.querySelector('.hero-avatar') || null;
+ this.root = root;
+ this.content = root?.querySelector('.hero-content') || null;
+ this.title = root?.querySelector('.hero-title') || null;
+ this.subtitle = root?.querySelector('.hero-subtitle') || null;
+ this.avatar = root?.querySelector('.hero-avatar') || null;
this.modelViewer = this.avatar?.querySelector('model-viewer') || null;
- this.flag = String(options.flag ?? '1');
+ this.flag = String(options.flag ?? '1');
this.pretext = null;
- this._gaze = null;
- this._dragon = null;
- this._overlay = null;
- this._onResize = null;
- this._resizeT = null;
- this._rafToken = 0;
- this._ctx = null;
+ this._gaze = null;
+ this._dragon = null;
+ this._overlay = null;
+ this._onResize = null;
+ this._resizeT = null;
+ this._rafToken = 0;
+ this._ctx = null;
}
async init() {
@@ -118,7 +118,12 @@ export default class PretextHero {
this._ctx = ctx;
const { circleX, circleY, circleR } = this._avatarCircle(ctx);
- const { lines, contentHeight } = this._layoutLinesAroundCircle(ctx, circleX, circleY, circleR);
+ const { lines, contentHeight } = this._layoutLinesAroundCircle(
+ ctx,
+ circleX,
+ circleY,
+ circleR,
+ );
const token = ++this._rafToken;
requestAnimationFrame(() => {
@@ -134,46 +139,55 @@ export default class PretextHero {
_computeLayoutContext() {
if (!this.content || !this.subtitle || !this.avatar || !this.pretext) return null;
- const contentRect = this.content.getBoundingClientRect();
+ const contentRect = this.content.getBoundingClientRect();
const subtitleRect = this.subtitle.getBoundingClientRect();
- const avatarRect = this.avatar.getBoundingClientRect();
+ const avatarRect = this.avatar.getBoundingClientRect();
- const style = getComputedStyle(this.subtitle);
- const font = `${style.fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`;
- const fontSize = Number.parseFloat(style.fontSize);
- const lhRaw = style.lineHeight;
+ const style = getComputedStyle(this.subtitle);
+ const font = `${style.fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`;
+ const fontSize = Number.parseFloat(style.fontSize);
+ const lhRaw = style.lineHeight;
const lineHeight = lhRaw === 'normal' ? fontSize * 1.5 : Number.parseFloat(lhRaw);
const overlayLeft = subtitleRect.left - contentRect.left;
- const overlayTop = subtitleRect.top - contentRect.top;
+ const overlayTop = subtitleRect.top - contentRect.top;
// Dragon mode stretches .hero-content to full hero width, so use the
// content box as the outer bound and let the subtitle flow wider.
- const heroRect = this.root.getBoundingClientRect();
- const rightmostPage = this.root.classList.contains('hero--dragon')
+ const heroRect = this.root.getBoundingClientRect();
+ const rightmostPage = this.root.classList.contains('hero--dragon')
? heroRect.right - 32
: Math.max(avatarRect.right - 24, subtitleRect.right);
- const overlayWidth = Math.max(subtitleRect.width, rightmostPage - subtitleRect.left);
+ const overlayWidth = Math.max(subtitleRect.width, rightmostPage - subtitleRect.left);
- const text = this.subtitle.textContent ?? '';
+ const text = this.subtitle.textContent ?? '';
const prepared = this.pretext.prepareWithSegments(text, font);
const circleBaseR = (Math.min(avatarRect.width, avatarRect.height) / 2) * 0.92;
return {
- font, lineHeight, prepared, text,
- overlayLeft, overlayTop, overlayWidth,
- subtitleRect, avatarRect, subtitleLeftPage: subtitleRect.left, subtitleTopPage: subtitleRect.top,
+ font,
+ lineHeight,
+ prepared,
+ text,
+ overlayLeft,
+ overlayTop,
+ overlayWidth,
+ subtitleRect,
+ avatarRect,
+ subtitleLeftPage: subtitleRect.left,
+ subtitleTopPage: subtitleRect.top,
circleBaseR,
- hPad: 14, maxLines: 32,
+ hPad: 14,
+ maxLines: 32,
};
}
_avatarCircle(ctx) {
const r = ctx.avatarRect;
return {
- circleX: (r.left + r.width / 2) - ctx.subtitleLeftPage,
- circleY: (r.top + r.height / 2) - ctx.subtitleTopPage,
+ circleX: r.left + r.width / 2 - ctx.subtitleLeftPage,
+ circleY: r.top + r.height / 2 - ctx.subtitleTopPage,
circleR: ctx.circleBaseR,
};
}
@@ -186,8 +200,8 @@ export default class PretextHero {
while (lines.length < maxLines) {
const bandMid = lineTop + lineHeight / 2;
- const dy = bandMid - circleY;
- const effR = circleR + hPad;
+ const dy = bandMid - circleY;
+ const effR = circleR + hPad;
let slotWidth = overlayWidth;
if (Math.abs(dy) < effR) {
@@ -217,16 +231,16 @@ export default class PretextHero {
_paintLines(ctx, lines, contentHeight) {
if (!this._overlay) return;
const overlay = this._overlay;
- overlay.style.left = `${ctx.overlayLeft}px`;
- overlay.style.top = `${ctx.overlayTop}px`;
- overlay.style.width = `${ctx.overlayWidth}px`;
+ overlay.style.left = `${ctx.overlayLeft}px`;
+ overlay.style.top = `${ctx.overlayTop}px`;
+ overlay.style.width = `${ctx.overlayWidth}px`;
overlay.style.height = `${Math.max(contentHeight, ctx.subtitleRect.height)}px`;
const frag = document.createDocumentFragment();
for (const { y, text } of lines) {
const span = document.createElement('span');
span.className = 'hero-subtitle-pretext-line';
- span.style.top = `${y}px`;
+ span.style.top = `${y}px`;
span.textContent = text;
frag.appendChild(span);
}
@@ -245,7 +259,12 @@ export default class PretextHero {
paintCircle(circleX, circleY, circleR) {
if (!this._ctx || !this._overlay) return 0;
const t0 = performance.now();
- const { lines, contentHeight } = this._layoutLinesAroundCircle(this._ctx, circleX, circleY, circleR);
+ const { lines, contentHeight } = this._layoutLinesAroundCircle(
+ this._ctx,
+ circleX,
+ circleY,
+ circleR,
+ );
this._paintLines(this._ctx, lines, contentHeight);
return performance.now() - t0;
}
diff --git a/src/memory/index.js b/src/memory/index.js
index 843c2a0d7..c1d7f969d 100644
--- a/src/memory/index.js
+++ b/src/memory/index.js
@@ -68,7 +68,9 @@ export class Memory {
try {
const r = await fetchFn(`${base}memory/${file}`);
if (r.ok) files[file] = await r.text();
- } catch { /* skip missing */ }
+ } catch {
+ /* skip missing */
+ }
}
return new Memory({ mode, namespace, index: { text: indexText }, files });
} catch {
@@ -126,7 +128,12 @@ export class Memory {
byType[t].push({ file, name: meta.name || file, description: meta.description || '' });
}
const lines = ['# Memory', ''];
- const headings = { user: '## User', feedback: '## Feedback', project: '## Project', reference: '## Reference' };
+ const headings = {
+ user: '## User',
+ feedback: '## Feedback',
+ project: '## Project',
+ reference: '## Reference',
+ };
for (const [t, items] of Object.entries(byType)) {
if (!items.length) continue;
lines.push(headings[t] || `## ${t}`);
diff --git a/src/model-info.js b/src/model-info.js
index 4ddb9be4a..fd6b78f40 100644
--- a/src/model-info.js
+++ b/src/model-info.js
@@ -1,5 +1,15 @@
-import { prepare, layout, prepareWithSegments, layoutWithLines, measureLineStats } from '@chenglou/pretext';
-import { prepareRichInline, walkRichInlineLineRanges, materializeRichInlineLineRange } from '@chenglou/pretext/rich-inline';
+import {
+ prepare,
+ layout,
+ prepareWithSegments,
+ layoutWithLines,
+ measureLineStats,
+} from '@chenglou/pretext';
+import {
+ prepareRichInline,
+ walkRichInlineLineRanges,
+ materializeRichInlineLineRange,
+} from '@chenglou/pretext/rich-inline';
// Fonts
const FONT_TITLE = '500 14px Inter, sans-serif';
@@ -52,7 +62,8 @@ function countStats(object) {
}
}
if (node.skeleton) hasSkinning = true;
- if (node.morphTargetInfluences && node.morphTargetInfluences.length > 0) hasMorphs = true;
+ if (node.morphTargetInfluences && node.morphTargetInfluences.length > 0)
+ hasMorphs = true;
const mats = Array.isArray(node.material) ? node.material : [node.material];
mats.forEach((mat) => {
@@ -91,7 +102,8 @@ function buildDescription(stats, clips) {
const parts = [];
if (stats.hasSkinning) parts.push('skinned');
if (stats.hasMorphs) parts.push('morph targets');
- if (clips && clips.length > 0) parts.push(`${clips.length} animation${clips.length > 1 ? 's' : ''}`);
+ if (clips && clips.length > 0)
+ parts.push(`${clips.length} animation${clips.length > 1 ? 's' : ''}`);
if (stats.materialTypes.length > 0) parts.push(stats.materialTypes.join(', '));
return parts.length > 0 ? parts.join(' · ') : '';
}
@@ -191,10 +203,11 @@ export function createModelInfo(container, object, clips) {
const canvasHeight =
PADDING +
- titleMeasure.height + ROW_GAP + // title
- ROW_GAP + // separator
+ titleMeasure.height +
+ ROW_GAP + // title
+ ROW_GAP + // separator
rowMeasurements.length * (LINE_HEIGHT + ROW_GAP) + // stat rows
- chipRowHeight + // chips
+ chipRowHeight + // chips
(descHeight > 0 ? ROW_GAP + descHeight : 0) + // description
PADDING;
diff --git a/src/nich-agent.js b/src/nich-agent.js
index 5169d7b5b..79a122519 100644
--- a/src/nich-agent.js
+++ b/src/nich-agent.js
@@ -41,24 +41,31 @@ export class NichAgent {
* @param {import('./runtime/index.js').Runtime} [runtime]
* @param {NichAgentOptions} [options]
*/
- constructor(containerEl, protocol = null, skills = null, identity = null, runtime = null, options = {}) {
- this.container = containerEl;
- this.protocol = protocol;
- this.skills = skills;
- this.identity = identity;
- this.runtime = runtime;
- this.options = options || {};
- this.layout = this.options.layout || 'floating';
- this.position = this.options.position || 'right';
- this.voiceInput = this.options.voiceInput !== false;
+ constructor(
+ containerEl,
+ protocol = null,
+ skills = null,
+ identity = null,
+ runtime = null,
+ options = {},
+ ) {
+ this.container = containerEl;
+ this.protocol = protocol;
+ this.skills = skills;
+ this.identity = identity;
+ this.runtime = runtime;
+ this.options = options || {};
+ this.layout = this.options.layout || 'floating';
+ this.position = this.options.position || 'right';
+ this.voiceInput = this.options.voiceInput !== false;
this.voiceOutput = this.options.voiceOutput !== false;
this.isSpeaking = false;
this.isListening = false;
this.recognition = null;
- this.synth = window.speechSynthesis;
- this.messages = [];
+ this.synth = window.speechSynthesis;
+ this.messages = [];
this.onFirstOpen = null;
- this._hasOpened = false;
+ this._hasOpened = false;
this._apiDisabled = false;
this._storageKey = `nich-agent:history:${this.identity?.id || 'default'}`;
this._loadHistory();
@@ -95,9 +102,9 @@ export class NichAgent {
if (!SpeechRecognition) return;
this.recognition = new SpeechRecognition();
- this.recognition.continuous = false;
- this.recognition.interimResults = false;
- this.recognition.lang = 'en-US';
+ this.recognition.continuous = false;
+ this.recognition.interimResults = false;
+ this.recognition.lang = 'en-US';
this.recognition.onresult = (event) => {
const text = event.results[0][0].transcript;
@@ -120,13 +127,19 @@ export class NichAgent {
_buildUI() {
const titleText = this.options.title || this.identity?.name || 'Agent';
- const greeting = this.options.greeting
- || (this.layout === 'embedded' ? 'Hi! Ask me anything.' : `I'm here. Drop a model, ask me anything, or say "help".`);
+ const greeting =
+ this.options.greeting ||
+ (this.layout === 'embedded'
+ ? 'Hi! Ask me anything.'
+ : `I'm here. Drop a model, ask me anything, or say "help".`);
this.panel = document.createElement('div');
- this.panel.className = 'nich-panel'
- + (this.layout === 'embedded' ? ' nich-panel--embedded nich-position--' + this.position : '');
- this.panel.innerHTML = `
+ this.panel.className =
+ 'nich-panel' +
+ (this.layout === 'embedded'
+ ? ' nich-panel--embedded nich-position--' + this.position
+ : '');
+ this.panel.innerHTML = `
<div class="nich-header">
<span class="nich-title">${_escapeHTML(titleText)}</span>
<div class="nich-header-right">
@@ -143,23 +156,27 @@ export class NichAgent {
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/></svg>
</button>
</div>
- ${this.voiceInput ? `
+ ${
+ this.voiceInput
+ ? `
<div class="nich-mic-row">
<button class="nich-mic" aria-label="Toggle microphone">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm-1-9c0-.55.45-1 1-1s1 .45 1 1v6c0 .55-.45 1-1 1s-1-.45-1-1V5zm6 6c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z"/></svg>
</button>
<span class="nich-mic-hint">${SpeechRecognition ? 'or press mic to speak' : 'voice unavailable in this browser'}</span>
</div>
- ` : ''}
+ `
+ : ''
+ }
${this.options.showPoweredBy ? '<a class="nich-powered-by" href="https://3dagent.vercel.app" target="_blank" rel="noopener noreferrer">powered by 3dagent</a>' : ''}
`;
// Apply theme overrides via CSS custom properties scoped to the panel.
if (this.options.theme) {
const t = this.options.theme;
- if (t.accent) this.panel.style.setProperty('--nich-accent', t.accent);
- if (t.background) this.panel.style.setProperty('--nich-bg', t.background);
- if (t.caption) this.panel.style.setProperty('--nich-fg', t.caption);
+ if (t.accent) this.panel.style.setProperty('--nich-accent', t.accent);
+ if (t.background) this.panel.style.setProperty('--nich-bg', t.background);
+ if (t.caption) this.panel.style.setProperty('--nich-fg', t.caption);
}
if (this.layout === 'embedded') {
@@ -182,10 +199,12 @@ export class NichAgent {
`;
this.container.appendChild(this.toggleBtn);
this.toggleBtn.addEventListener('click', () => this._togglePanel());
- this.panel.querySelector('.nich-close')?.addEventListener('click', () => this._togglePanel());
+ this.panel
+ .querySelector('.nich-close')
+ ?.addEventListener('click', () => this._togglePanel());
}
- this.panel.querySelector('.nich-send').addEventListener('click', () => this._send());
+ this.panel.querySelector('.nich-send').addEventListener('click', () => this._send());
this.panel.querySelector('.nich-input').addEventListener('keydown', (e) => {
if (e.key === 'Enter') this._send();
});
@@ -215,7 +234,7 @@ export class NichAgent {
_send() {
const input = this.panel.querySelector('.nich-input');
- const text = input.value.trim();
+ const text = input.value.trim();
if (!text) return;
input.value = '';
this._addMessage('user', text);
@@ -235,7 +254,7 @@ export class NichAgent {
this._pushHistory('assistant', result.reply);
if (this.protocol) {
this.protocol.emit({
- type: ACTION_TYPES.SPEAK,
+ type: ACTION_TYPES.SPEAK,
payload: { text: result.reply, sentiment: 0 },
agentId: this.identity?.id || 'default',
});
@@ -294,7 +313,7 @@ export class NichAgent {
if (this.protocol) {
this.protocol.emit({
- type: ACTION_TYPES.SPEAK,
+ type: ACTION_TYPES.SPEAK,
payload: { text: response, sentiment: 0 },
agentId: this.identity?.id || 'default',
});
@@ -307,9 +326,9 @@ export class NichAgent {
const typing = this._startTyping();
try {
const res = await fetch('/api/chat', {
- method: 'POST',
+ method: 'POST',
credentials: 'include',
- headers: { 'content-type': 'application/json' },
+ headers: { 'content-type': 'application/json' },
body: JSON.stringify({
message,
context: this._buildContext(),
@@ -326,7 +345,12 @@ export class NichAgent {
if (!res.ok) return { ok: false, reason: `http_${res.status}` };
const data = await res.json();
- return { ok: true, message, reply: (data.reply || '').trim(), actions: data.actions || [] };
+ return {
+ ok: true,
+ message,
+ reply: (data.reply || '').trim(),
+ actions: data.actions || [],
+ };
} catch (err) {
console.warn('[NichAgent] /api/chat failed:', err.message);
return { ok: false, reason: 'network' };
@@ -344,7 +368,7 @@ export class NichAgent {
this._pushHistory('assistant', reply);
if (this.protocol) {
this.protocol.emit({
- type: ACTION_TYPES.SPEAK,
+ type: ACTION_TYPES.SPEAK,
payload: { text: reply, sentiment: 0 },
agentId: this.identity?.id || 'default',
});
@@ -365,38 +389,40 @@ export class NichAgent {
const validator = window.VIEWER?.app?.validator;
const state = viewer?.state || {};
const ctx = {
- wireframe: !!state.wireframe,
- skeleton: !!state.skeleton,
- grid: !!state.grid,
- autoRotate: !!state.autoRotate,
+ wireframe: !!state.wireframe,
+ skeleton: !!state.skeleton,
+ grid: !!state.grid,
+ autoRotate: !!state.autoRotate,
transparentBg: !!state.transparentBg,
- bgColor: state.bgColor,
+ bgColor: state.bgColor,
currentEnvironment: state.environment,
};
if (viewer?.content) {
if (viewer.content.name) ctx.modelName = viewer.content.name;
const stats = this._countStats(viewer.content);
- ctx.vertices = stats.vertices;
+ ctx.vertices = stats.vertices;
ctx.triangles = stats.triangles;
ctx.materials = stats.materials;
ctx.animations = viewer.clips?.length || 0;
}
if (validator?.report) {
- ctx.validationErrors = validator.report.errors?.length || 0;
+ ctx.validationErrors = validator.report.errors?.length || 0;
ctx.validationWarnings = validator.report.warnings?.length || 0;
}
return ctx;
}
_countStats(root) {
- let vertices = 0, triangles = 0;
+ let vertices = 0,
+ triangles = 0;
const materials = new Set();
root.traverse((node) => {
if (node.isMesh || node.isPoints || node.isLine) {
const geo = node.geometry;
if (geo) {
if (geo.index) triangles += geo.index.count / 3;
- else if (geo.attributes.position) triangles += geo.attributes.position.count / 3;
+ else if (geo.attributes.position)
+ triangles += geo.attributes.position.count / 3;
if (geo.attributes.position) vertices += geo.attributes.position.count;
}
const mats = Array.isArray(node.material) ? node.material : [node.material];
@@ -408,21 +434,33 @@ export class NichAgent {
async _executeAction(action) {
const viewer = window.VIEWER?.app?.viewer;
- const app = window.VIEWER?.app;
+ const app = window.VIEWER?.app;
if (!action || typeof action.type !== 'string') return;
switch (action.type) {
case 'setWireframe':
- if (viewer) { viewer.state.wireframe = !!action.value; viewer.updateDisplay(); }
+ if (viewer) {
+ viewer.state.wireframe = !!action.value;
+ viewer.updateDisplay();
+ }
break;
case 'setSkeleton':
- if (viewer) { viewer.state.skeleton = !!action.value; viewer.updateDisplay(); }
+ if (viewer) {
+ viewer.state.skeleton = !!action.value;
+ viewer.updateDisplay();
+ }
break;
case 'setGrid':
- if (viewer) { viewer.state.grid = !!action.value; viewer.updateDisplay(); }
+ if (viewer) {
+ viewer.state.grid = !!action.value;
+ viewer.updateDisplay();
+ }
break;
case 'setAutoRotate':
- if (viewer) { viewer.state.autoRotate = !!action.value; viewer.updateDisplay(); }
+ if (viewer) {
+ viewer.state.autoRotate = !!action.value;
+ viewer.updateDisplay();
+ }
break;
case 'setBgColor':
if (viewer && typeof action.value === 'string') {
@@ -431,7 +469,10 @@ export class NichAgent {
}
break;
case 'setTransparentBg':
- if (viewer) { viewer.state.transparentBg = !!action.value; viewer.updateBackground(); }
+ if (viewer) {
+ viewer.state.transparentBg = !!action.value;
+ viewer.updateBackground();
+ }
break;
case 'setEnvironment':
if (viewer && typeof action.value === 'string') {
@@ -486,12 +527,16 @@ export class NichAgent {
_pushHistory(role, content) {
this._history.push({ role, content });
if (this._history.length > 20) this._history = this._history.slice(-20);
- try { sessionStorage.setItem(this._storageKey, JSON.stringify(this._history)); } catch {}
+ try {
+ sessionStorage.setItem(this._storageKey, JSON.stringify(this._history));
+ } catch {}
}
_resetHistory() {
this._history = [];
- try { sessionStorage.removeItem(this._storageKey); } catch {}
+ try {
+ sessionStorage.removeItem(this._storageKey);
+ } catch {}
}
/**
@@ -499,19 +544,20 @@ export class NichAgent {
* Returns null if no skill matches.
*/
_matchSkill(lower) {
- if (lower.match(/\b(present|describe|tell me about|what.*model|show me)\b/)) return 'present-model';
- if (lower.match(/\b(validate|check|errors|warnings|valid)\b/)) return 'validate-model';
- if (lower.match(/\b(remember|save|store|note|don't forget)\b/)) return 'remember';
- if (lower.match(/\b(sign|signature|wallet|verify|prove)\b/)) return 'sign-action';
- if (lower.match(/\b(think|recall|what do you know|context)\b/)) return 'think';
- if (lower.match(/\b(help|what can you|commands|skills|abilities)\b/)) return 'help';
+ if (lower.match(/\b(present|describe|tell me about|what.*model|show me)\b/))
+ return 'present-model';
+ if (lower.match(/\b(validate|check|errors|warnings|valid)\b/)) return 'validate-model';
+ if (lower.match(/\b(remember|save|store|note|don't forget)\b/)) return 'remember';
+ if (lower.match(/\b(sign|signature|wallet|verify|prove)\b/)) return 'sign-action';
+ if (lower.match(/\b(think|recall|what do you know|context)\b/)) return 'think';
+ if (lower.match(/\b(help|what can you|commands|skills|abilities)\b/)) return 'help';
return null;
}
// ── Response Generation (fallback) ────────────────────────────────────────
_generateResponse(input) {
- const lower = input.toLowerCase();
+ const lower = input.toLowerCase();
const viewer = window.VIEWER?.app?.viewer;
if (lower.match(/\b(hello|hi|hey|sup|yo)\b/)) {
@@ -566,7 +612,7 @@ export class NichAgent {
return 'No memories yet. Tell me something worth remembering.';
}
- return "Try asking me to present or validate the loaded model, or drop a glTF/GLB file to get started.";
+ return 'Try asking me to present or validate the loaded model, or drop a glTF/GLB file to get started.';
}
// ── Speech Synthesis ─────────────────────────────────────────────────────
@@ -576,12 +622,16 @@ export class NichAgent {
if (!this.synth) return;
this.synth.cancel();
- const utterance = new SpeechSynthesisUtterance(text);
- utterance.rate = 1.0;
- utterance.pitch = 1.0;
- utterance.volume = 0.8;
- utterance.onstart = () => { this.isSpeaking = true; };
- utterance.onend = () => { this.isSpeaking = false; };
+ const utterance = new SpeechSynthesisUtterance(text);
+ utterance.rate = 1.0;
+ utterance.pitch = 1.0;
+ utterance.volume = 0.8;
+ utterance.onstart = () => {
+ this.isSpeaking = true;
+ };
+ utterance.onend = () => {
+ this.isSpeaking = false;
+ };
this.synth.speak(utterance);
}
@@ -611,8 +661,8 @@ export class NichAgent {
this.messages.push({ role, text });
}
const messagesEl = this.panel.querySelector('#agent-messages');
- const msgEl = document.createElement('div');
- msgEl.className = `nich-message ${role}${type ? ' ' + type : ''}`;
+ const msgEl = document.createElement('div');
+ msgEl.className = `nich-message ${role}${type ? ' ' + type : ''}`;
msgEl.textContent = text;
messagesEl.appendChild(msgEl);
messagesEl.scrollTop = messagesEl.scrollHeight;
@@ -622,9 +672,13 @@ export class NichAgent {
dispose() {
if (this.recognition) {
- try { this.recognition.stop(); } catch {}
+ try {
+ this.recognition.stop();
+ } catch {}
}
- try { this.synth?.cancel(); } catch {}
+ try {
+ this.synth?.cancel();
+ } catch {}
this.panel?.remove();
this.toggleBtn?.remove();
}
diff --git a/src/pinning/index.js b/src/pinning/index.js
index 734d8efdc..244885bab 100644
--- a/src/pinning/index.js
+++ b/src/pinning/index.js
@@ -61,8 +61,7 @@ export function getPinner() {
if (typeof window !== 'undefined' && window.__agent3dPinner) {
const cfg = window.__agent3dPinner;
- _defaultPinner =
- typeof cfg.pinBlob === 'function' ? cfg : createPinner(cfg);
+ _defaultPinner = typeof cfg.pinBlob === 'function' ? cfg : createPinner(cfg);
return _defaultPinner;
}
diff --git a/src/pinning/pinata.js b/src/pinning/pinata.js
index ccae17044..d64836707 100644
--- a/src/pinning/pinata.js
+++ b/src/pinning/pinata.js
@@ -95,7 +95,10 @@ export class PinataPinner {
}).then(async (r) => {
if (!r.ok) {
const body = await r.text().catch(() => '');
- throw statusError(r.status, `Pinata directory upload failed (${r.status}): ${body}`);
+ throw statusError(
+ r.status,
+ `Pinata directory upload failed (${r.status}): ${body}`,
+ );
}
return r;
}),
diff --git a/src/pinning/web3-storage.js b/src/pinning/web3-storage.js
index 143b3d4ef..25288cfbe 100644
--- a/src/pinning/web3-storage.js
+++ b/src/pinning/web3-storage.js
@@ -46,7 +46,10 @@ export class Web3StoragePinner {
}).then(async (r) => {
if (!r.ok) {
const body = await r.text().catch(() => '');
- throw statusError(r.status, `web3.storage upload failed (${r.status}): ${body}`);
+ throw statusError(
+ r.status,
+ `web3.storage upload failed (${r.status}): ${body}`,
+ );
}
return r;
}),
diff --git a/src/reputation-page.js b/src/reputation-page.js
index 35951a4f6..f491e6171 100644
--- a/src/reputation-page.js
+++ b/src/reputation-page.js
@@ -7,4 +7,11 @@ import { getReputation, getRecentReviews, submitReputation } from './erc8004/rep
import { JsonRpcProvider, BrowserProvider } from 'ethers';
import { REGISTRY_DEPLOYMENTS } from './erc8004/abi.js';
-export { getReputation, getRecentReviews, submitReputation, JsonRpcProvider, BrowserProvider, REGISTRY_DEPLOYMENTS };
+export {
+ getReputation,
+ getRecentReviews,
+ submitReputation,
+ JsonRpcProvider,
+ BrowserProvider,
+ REGISTRY_DEPLOYMENTS,
+};
diff --git a/src/runtime/animation-slots.js b/src/runtime/animation-slots.js
index 32c677f41..1fe1e5b74 100644
--- a/src/runtime/animation-slots.js
+++ b/src/runtime/animation-slots.js
@@ -2,19 +2,30 @@
// Each slot maps to a clip name from the loaded animation library.
// Agents can override individual slots via meta.edits.animations.
-export const SLOTS = ['idle', 'wave', 'nod', 'shake', 'think', 'celebrate', 'concern', 'bow', 'point', 'shrug'];
+export const SLOTS = [
+ 'idle',
+ 'wave',
+ 'nod',
+ 'shake',
+ 'think',
+ 'celebrate',
+ 'concern',
+ 'bow',
+ 'point',
+ 'shrug',
+];
export const DEFAULT_ANIMATION_MAP = {
- idle: 'idle',
- wave: 'reaction',
- nod: 'reaction',
- shake: 'angry',
- think: 'pray',
+ idle: 'idle',
+ wave: 'reaction',
+ nod: 'reaction',
+ shake: 'angry',
+ think: 'pray',
celebrate: 'celebrate',
- concern: 'defeated',
- bow: 'sitclap',
- point: 'reaction',
- shrug: 'defeated',
+ concern: 'defeated',
+ bow: 'sitclap',
+ point: 'reaction',
+ shrug: 'defeated',
};
/**
diff --git a/src/runtime/index.js b/src/runtime/index.js
index 2a83fd644..94e794067 100644
--- a/src/runtime/index.js
+++ b/src/runtime/index.js
@@ -8,7 +8,16 @@ import { BUILTIN_TOOLS, BUILTIN_HANDLERS, STAGE_TOOLS } from './tools.js';
const MAX_TOOL_ITERATIONS = 8;
export class Runtime extends EventTarget {
- constructor({ manifest, viewer, memory, skills, providerConfig = {}, voiceConfig = {}, stage = null, agentId = null } = {}) {
+ constructor({
+ manifest,
+ viewer,
+ memory,
+ skills,
+ providerConfig = {},
+ voiceConfig = {},
+ stage = null,
+ agentId = null,
+ } = {}) {
super();
this.manifest = manifest || {};
this.viewer = viewer;
@@ -21,8 +30,8 @@ export class Runtime extends EventTarget {
...this.manifest.brain,
...providerConfig,
});
- this.tts = createTTS({ ...(this.manifest.voice?.tts), ...voiceConfig.tts });
- this.stt = createSTT({ ...(this.manifest.voice?.stt), ...voiceConfig.stt });
+ this.tts = createTTS({ ...this.manifest.voice?.tts, ...voiceConfig.tts });
+ this.stt = createSTT({ ...this.manifest.voice?.stt, ...voiceConfig.stt });
this.messages = [];
this._busy = false;
@@ -32,9 +41,13 @@ export class Runtime extends EventTarget {
const parts = [];
if (this.manifest.instructions) parts.push(this.manifest.instructions);
if (this.memory) {
- parts.push('\n\n<memory>\n' + this.memory.contextBlock({
- maxTokens: this.manifest.memory?.maxTokens || 8192,
- }) + '\n</memory>');
+ parts.push(
+ '\n\n<memory>\n' +
+ this.memory.contextBlock({
+ maxTokens: this.manifest.memory?.maxTokens || 8192,
+ }) +
+ '\n</memory>',
+ );
}
if (this.skills) parts.push(this.skills.systemPrompt());
return parts.join('');
@@ -56,14 +69,18 @@ export class Runtime extends EventTarget {
try {
this.memory?.note('user_said', { text: userText });
this.messages.push({ role: 'user', content: userText });
- this.dispatchEvent(new CustomEvent('brain:message', {
- detail: { role: 'user', content: userText },
- }));
+ this.dispatchEvent(
+ new CustomEvent('brain:message', {
+ detail: { role: 'user', content: userText },
+ }),
+ );
const reply = await this._loop();
if (voice && reply.text && this.tts) {
- this.dispatchEvent(new CustomEvent('voice:speech-start', { detail: { text: reply.text } }));
+ this.dispatchEvent(
+ new CustomEvent('voice:speech-start', { detail: { text: reply.text } }),
+ );
await this.tts.speak(reply.text);
this.dispatchEvent(new CustomEvent('voice:speech-end', {}));
}
@@ -86,15 +103,19 @@ export class Runtime extends EventTarget {
});
if (response.thinking) {
- this.dispatchEvent(new CustomEvent('brain:thinking', { detail: { content: response.thinking } }));
+ this.dispatchEvent(
+ new CustomEvent('brain:thinking', { detail: { content: response.thinking } }),
+ );
}
if (!response.toolCalls.length) {
finalText = response.text;
this.messages.push({ role: 'assistant', content: response.text });
- this.dispatchEvent(new CustomEvent('brain:message', {
- detail: { role: 'assistant', content: response.text },
- }));
+ this.dispatchEvent(
+ new CustomEvent('brain:message', {
+ detail: { role: 'assistant', content: response.text },
+ }),
+ );
break;
}
@@ -103,24 +124,29 @@ export class Runtime extends EventTarget {
this.provider.formatAssistantWithToolCalls(response.text, response.toolCalls),
);
if (response.text) {
- this.dispatchEvent(new CustomEvent('brain:message', {
- detail: { role: 'assistant', content: response.text },
- }));
+ this.dispatchEvent(
+ new CustomEvent('brain:message', {
+ detail: { role: 'assistant', content: response.text },
+ }),
+ );
}
// Dispatch each tool call
const results = [];
for (const call of response.toolCalls) {
- let output, isError = false;
+ let output,
+ isError = false;
try {
output = await this._dispatchTool(call);
} catch (err) {
output = { error: err.message || String(err) };
isError = true;
}
- this.dispatchEvent(new CustomEvent('skill:tool-called', {
- detail: { tool: call.name, args: call.input, result: output },
- }));
+ this.dispatchEvent(
+ new CustomEvent('skill:tool-called', {
+ detail: { tool: call.name, args: call.input, result: output },
+ }),
+ );
results.push({ id: call.id, output, isError });
}
this.messages.push(this.provider.formatToolResults(results));
@@ -148,11 +174,12 @@ export class Runtime extends EventTarget {
viewer: this.viewer,
memory: this.memory,
llm: {
- complete: (prompt, opts) => this.provider.complete({
- system: opts?.system || '',
- messages: [{ role: 'user', content: prompt }],
- tools: opts?.tools,
- }),
+ complete: (prompt, opts) =>
+ this.provider.complete({
+ system: opts?.system || '',
+ messages: [{ role: 'user', content: prompt }],
+ tools: opts?.tools,
+ }),
},
speak: async (text) => {
if (!this.tts) return;
@@ -179,11 +206,15 @@ export class Runtime extends EventTarget {
this.dispatchEvent(new CustomEvent('voice:listen-start', {}));
const text = await this.stt.listen({
onInterim: (t) => {
- this.dispatchEvent(new CustomEvent('voice:transcript', { detail: { text: t, final: false } }));
+ this.dispatchEvent(
+ new CustomEvent('voice:transcript', { detail: { text: t, final: false } }),
+ );
onInterim?.(t);
},
onFinal: (t) => {
- this.dispatchEvent(new CustomEvent('voice:transcript', { detail: { text: t, final: true } }));
+ this.dispatchEvent(
+ new CustomEvent('voice:transcript', { detail: { text: t, final: true } }),
+ );
onFinal?.(t);
},
});
@@ -194,6 +225,12 @@ export class Runtime extends EventTarget {
this.messages = [];
}
- pause() { this.tts?.cancel(); this.stt?.stop(); }
- destroy() { this.pause(); this.messages = []; }
+ pause() {
+ this.tts?.cancel();
+ this.stt?.stop();
+ }
+ destroy() {
+ this.pause();
+ this.messages = [];
+ }
}
diff --git a/src/runtime/scene.js b/src/runtime/scene.js
index c637ee712..22fb8bbe4 100644
--- a/src/runtime/scene.js
+++ b/src/runtime/scene.js
@@ -9,7 +9,9 @@ import { resolveURI } from '../ipfs.js';
import { resolveSlot } from './animation-slots.js';
const EXPRESSION_MAP = {
- neutral: { /* reset all */ },
+ neutral: {
+ /* reset all */
+ },
happy: { mouthSmile: 1, browInnerUp: 0.3, cheekSquintL: 0.4, cheekSquintR: 0.4 },
sad: { mouthFrownL: 0.8, mouthFrownR: 0.8, browDownL: 0.6, browDownR: 0.6 },
surprised: { jawOpen: 0.5, eyeWideL: 0.8, eyeWideR: 0.8, browInnerUp: 0.9 },
@@ -30,10 +32,18 @@ export class SceneController {
}
// Expose the underlying Three.js handles skills may need
- get scene() { return this.viewer.scene; }
- get mixer() { return this._groupMixer || this.viewer.mixer; }
- get clips() { return this._groupClips || this.viewer.clips || []; }
- get content() { return this._group || this.viewer.content; }
+ get scene() {
+ return this.viewer.scene;
+ }
+ get mixer() {
+ return this._groupMixer || this.viewer.mixer;
+ }
+ get clips() {
+ return this._groupClips || this.viewer.clips || [];
+ }
+ get content() {
+ return this._group || this.viewer.content;
+ }
// Scope all scene operations to a sub-group (used by <agent-stage>).
setGroup(group, { mixer = null, clips = null } = {}) {
@@ -53,8 +63,12 @@ export class SceneController {
dispose() {
if (this._mixerHook) this._removeHook(this._mixerHook);
if (this._groupMixer) {
- try { this._groupMixer.stopAllAction(); } catch {}
- try { this._groupMixer.uncacheRoot(this._group); } catch {}
+ try {
+ this._groupMixer.stopAllAction();
+ } catch {}
+ try {
+ this._groupMixer.uncacheRoot(this._group);
+ } catch {}
}
this._mixerHook = null;
this._groupMixer = null;
@@ -139,7 +153,8 @@ export class SceneController {
} else {
mixer.stopAllAction();
if (!this._group) {
- for (const k in this.viewer.state.actionStates) this.viewer.state.actionStates[k] = false;
+ for (const k in this.viewer.state.actionStates)
+ this.viewer.state.actionStates[k] = false;
}
}
this.viewer.invalidate();
@@ -152,7 +167,7 @@ export class SceneController {
if (!mixer || !clip) return false;
const action = mixer.clipAction(clip);
action.reset();
- action.fadeIn((opts?.blend ?? 0.2));
+ action.fadeIn(opts?.blend ?? 0.2);
action.play();
this.viewer._animating = true;
this.viewer.invalidate();
@@ -280,7 +295,9 @@ export class SceneController {
const exact = this.clips.find((c) => c.name === name);
if (exact) return exact;
const ci = name.toLowerCase();
- return this.clips.find((c) => c.name.toLowerCase() === ci)
- || this.clips.find((c) => c.name.toLowerCase().includes(ci));
+ return (
+ this.clips.find((c) => c.name.toLowerCase() === ci) ||
+ this.clips.find((c) => c.name.toLowerCase().includes(ci))
+ );
}
}
diff --git a/src/runtime/speech.js b/src/runtime/speech.js
index 3a90a444b..42bb7b07a 100644
--- a/src/runtime/speech.js
+++ b/src/runtime/speech.js
@@ -19,9 +19,19 @@ export class BrowserTTS {
utter.lang = this.lang;
const voice = this._pickVoice();
if (voice) utter.voice = voice;
- utter.onstart = () => { this._speaking = true; onStart?.(); };
- utter.onend = () => { this._speaking = false; onEnd?.(); resolve(); };
- utter.onerror = () => { this._speaking = false; resolve(); };
+ utter.onstart = () => {
+ this._speaking = true;
+ onStart?.();
+ };
+ utter.onend = () => {
+ this._speaking = false;
+ onEnd?.();
+ resolve();
+ };
+ utter.onerror = () => {
+ this._speaking = false;
+ resolve();
+ };
window.speechSynthesis.speak(utter);
});
}
@@ -31,13 +41,17 @@ export class BrowserTTS {
this._speaking = false;
}
- get speaking() { return this._speaking; }
+ get speaking() {
+ return this._speaking;
+ }
_pickVoice() {
if (!('speechSynthesis' in window)) return null;
const voices = window.speechSynthesis.getVoices();
if (this.voiceId && this.voiceId !== 'default') {
- const found = voices.find((v) => v.name === this.voiceId || v.voiceURI === this.voiceId);
+ const found = voices.find(
+ (v) => v.name === this.voiceId || v.voiceURI === this.voiceId,
+ );
if (found) return found;
}
return voices.find((v) => v.lang?.startsWith(this.lang.slice(0, 2))) || null;
@@ -82,10 +96,21 @@ export class BrowserSTT {
}
}
};
- r.onerror = (e) => { this._listening = false; reject(e.error); };
- r.onend = () => { this._listening = false; resolve(finalText.trim()); };
+ r.onerror = (e) => {
+ this._listening = false;
+ reject(e.error);
+ };
+ r.onend = () => {
+ this._listening = false;
+ resolve(finalText.trim());
+ };
this._listening = true;
- try { r.start(); } catch (e) { this._listening = false; reject(e); }
+ try {
+ r.start();
+ } catch (e) {
+ this._listening = false;
+ reject(e);
+ }
});
}
@@ -93,7 +118,9 @@ export class BrowserSTT {
if (this._recognition && this._listening) this._recognition.stop();
}
- get listening() { return this._listening; }
+ get listening() {
+ return this._listening;
+ }
}
/**
@@ -126,33 +153,33 @@ export class BrowserSTT {
export class ElevenLabsTTS {
constructor({
voiceId,
- modelId = 'eleven_turbo_v2_5',
- apiKey = null,
- proxyURL = null,
- rate = 1,
- pitch = 1,
- lang = 'en-US',
- stability = 0.5,
- similarityBoost = 0.75,
- useSpeakerBoost = true,
+ modelId = 'eleven_turbo_v2_5',
+ apiKey = null,
+ proxyURL = null,
+ rate = 1,
+ pitch = 1,
+ lang = 'en-US',
+ stability = 0.5,
+ similarityBoost = 0.75,
+ useSpeakerBoost = true,
} = {}) {
if (!voiceId) throw new Error('ElevenLabsTTS requires voiceId');
- this.voiceId = voiceId;
- this.modelId = modelId;
- this.apiKey = apiKey;
- this.proxyURL = proxyURL;
- this.rate = rate;
- this.pitch = pitch; // unused — see class comment
- this.lang = lang;
- this.stability = stability;
- this.similarityBoost = similarityBoost;
- this.useSpeakerBoost = useSpeakerBoost;
-
- this._speaking = false;
- this._abort = null; // current AbortController
- this._audio = null; // current <audio> element
- this._mediaSourceURL = null; // for revocation
- this._onEnd = null; // pending resolve
+ this.voiceId = voiceId;
+ this.modelId = modelId;
+ this.apiKey = apiKey;
+ this.proxyURL = proxyURL;
+ this.rate = rate;
+ this.pitch = pitch; // unused — see class comment
+ this.lang = lang;
+ this.stability = stability;
+ this.similarityBoost = similarityBoost;
+ this.useSpeakerBoost = useSpeakerBoost;
+
+ this._speaking = false;
+ this._abort = null; // current AbortController
+ this._audio = null; // current <audio> element
+ this._mediaSourceURL = null; // for revocation
+ this._onEnd = null; // pending resolve
}
async speak(text, { onStart, onEnd } = {}) {
@@ -162,7 +189,8 @@ export class ElevenLabsTTS {
this._abort = new AbortController();
this._speaking = true;
- const url = this.proxyURL ||
+ const url =
+ this.proxyURL ||
`https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(this.voiceId)}/stream`;
const headers = { 'content-type': 'application/json', accept: 'audio/mpeg' };
@@ -177,9 +205,9 @@ export class ElevenLabsTTS {
text,
model_id: this.modelId,
voice_settings: {
- stability: this.stability,
- similarity_boost: this.similarityBoost,
- style: styleVal,
+ stability: this.stability,
+ similarity_boost: this.similarityBoost,
+ style: styleVal,
use_speaker_boost: this.useSpeakerBoost,
},
// Forwarded for proxies that prefer a single endpoint
@@ -209,8 +237,7 @@ export class ElevenLabsTTS {
// Try MediaSource first (low-latency streaming). Fall back to buffered
// playback for browsers that don't support MSE for audio/mpeg (Safari).
const supportsMSE =
- typeof MediaSource !== 'undefined' &&
- MediaSource.isTypeSupported('audio/mpeg');
+ typeof MediaSource !== 'undefined' && MediaSource.isTypeSupported('audio/mpeg');
const playStarted = (cb) => {
if (this._startedFired) return;
@@ -242,7 +269,9 @@ export class ElevenLabsTTS {
cancel() {
if (this._abort) {
- try { this._abort.abort(); } catch {}
+ try {
+ this._abort.abort();
+ } catch {}
this._abort = null;
}
this._cleanupAudio();
@@ -251,7 +280,9 @@ export class ElevenLabsTTS {
if (this._onEnd) this._onEnd();
}
- get speaking() { return this._speaking; }
+ get speaking() {
+ return this._speaking;
+ }
// ── Internal: streaming via MediaSource ────────────────────────────────
@@ -263,8 +294,8 @@ export class ElevenLabsTTS {
audio.preload = 'auto';
audio.addEventListener('playing', onStart, { once: true });
- audio.addEventListener('ended', () => this._onEnd?.(), { once: true });
- audio.addEventListener('error', () => onError?.(), { once: true });
+ audio.addEventListener('ended', () => this._onEnd?.(), { once: true });
+ audio.addEventListener('error', () => onError?.(), { once: true });
ms.addEventListener('sourceopen', async () => {
let sb;
@@ -276,8 +307,8 @@ export class ElevenLabsTTS {
}
const reader = stream.getReader();
- const queue = [];
- let reading = true;
+ const queue = [];
+ let reading = true;
const pump = () => {
if (!reading || sb.updating) return;
@@ -287,7 +318,9 @@ export class ElevenLabsTTS {
sb.appendBuffer(next);
} catch {
reading = false;
- try { ms.endOfStream(); } catch {}
+ try {
+ ms.endOfStream();
+ } catch {}
}
};
@@ -302,7 +335,9 @@ export class ElevenLabsTTS {
if (sb.updating || queue.length) {
setTimeout(wait, 30);
} else {
- try { ms.endOfStream(); } catch {}
+ try {
+ ms.endOfStream();
+ } catch {}
}
};
wait();
@@ -324,13 +359,13 @@ export class ElevenLabsTTS {
async _playBuffered(resp, onStart, onError) {
try {
const blob = await resp.blob();
- const url = URL.createObjectURL(blob);
+ const url = URL.createObjectURL(blob);
this._mediaSourceURL = url;
const audio = new Audio(url);
this._audio = audio;
audio.addEventListener('playing', onStart, { once: true });
- audio.addEventListener('ended', () => this._onEnd?.(), { once: true });
- audio.addEventListener('error', () => onError?.(), { once: true });
+ audio.addEventListener('ended', () => this._onEnd?.(), { once: true });
+ audio.addEventListener('error', () => onError?.(), { once: true });
await audio.play();
} catch (err) {
if (err.name !== 'AbortError') onError?.();
@@ -339,12 +374,16 @@ export class ElevenLabsTTS {
_cleanupAudio() {
if (this._audio) {
- try { this._audio.pause(); } catch {}
+ try {
+ this._audio.pause();
+ } catch {}
this._audio.src = '';
this._audio = null;
}
if (this._mediaSourceURL) {
- try { URL.revokeObjectURL(this._mediaSourceURL); } catch {}
+ try {
+ URL.revokeObjectURL(this._mediaSourceURL);
+ } catch {}
this._mediaSourceURL = null;
}
this._startedFired = false;
@@ -353,8 +392,8 @@ export class ElevenLabsTTS {
export function createTTS(config = {}) {
const provider = config.provider || 'browser';
- if (provider === 'none') return null;
- if (provider === 'browser') return new BrowserTTS(config);
+ if (provider === 'none') return null;
+ if (provider === 'browser') return new BrowserTTS(config);
if (provider === 'elevenlabs') return new ElevenLabsTTS(config);
throw new Error(`TTS provider "${provider}" not implemented yet`);
}
diff --git a/src/runtime/tools.js b/src/runtime/tools.js
index a53354933..e0202b941 100644
--- a/src/runtime/tools.js
+++ b/src/runtime/tools.js
@@ -14,7 +14,7 @@ export const BUILTIN_TOOLS = [
},
{
name: 'lookAt',
- description: 'Direct the agent\'s gaze toward a target.',
+ description: "Direct the agent's gaze toward a target.",
input_schema: {
type: 'object',
properties: {
@@ -46,7 +46,10 @@ export const BUILTIN_TOOLS = [
input_schema: {
type: 'object',
properties: {
- preset: { type: 'string', enum: ['neutral', 'happy', 'sad', 'surprised', 'confused', 'focused'] },
+ preset: {
+ type: 'string',
+ enum: ['neutral', 'happy', 'sad', 'surprised', 'confused', 'focused'],
+ },
intensity: { type: 'number', minimum: 0, maximum: 1, default: 1 },
},
required: ['preset'],
@@ -54,7 +57,8 @@ export const BUILTIN_TOOLS = [
},
{
name: 'speak',
- description: 'Say something out loud via TTS. Use this instead of plain text when voice is on.',
+ description:
+ 'Say something out loud via TTS. Use this instead of plain text when voice is on.',
input_schema: {
type: 'object',
properties: { text: { type: 'string' } },
@@ -63,7 +67,8 @@ export const BUILTIN_TOOLS = [
},
{
name: 'remember',
- description: 'Save a durable memory about the user, a feedback rule, a project fact, or a reference.',
+ description:
+ 'Save a durable memory about the user, a feedback rule, a project fact, or a reference.',
input_schema: {
type: 'object',
properties: {
@@ -83,7 +88,8 @@ export const BUILTIN_TOOLS = [
export const STAGE_TOOLS = [
{
name: 'observe_agents',
- description: 'List the other agents currently sharing this stage, with their names and positions.',
+ description:
+ 'List the other agents currently sharing this stage, with their names and positions.',
input_schema: { type: 'object', properties: {} },
},
{
@@ -93,7 +99,10 @@ export const STAGE_TOOLS = [
input_schema: {
type: 'object',
properties: {
- agentId: { type: 'string', description: 'Target agent id as returned by observe_agents.' },
+ agentId: {
+ type: 'string',
+ description: 'Target agent id as returned by observe_agents.',
+ },
text: { type: 'string' },
},
required: ['agentId', 'text'],
@@ -121,7 +130,8 @@ export const BUILTIN_HANDLERS = {
const resolved = ctx.viewer.resolveAnimationSlot?.(name) ?? name;
const played = ctx.viewer.playClipByName?.(resolved, { loop, fade_ms });
if (!played) {
- if (resolved !== name) console.warn(`[play_clip] slot "${name}" → "${resolved}" not found in library`);
+ if (resolved !== name)
+ console.warn(`[play_clip] slot "${name}" → "${resolved}" not found in library`);
return { ok: false, error: `No clip named "${resolved}"` };
}
return { ok: true, name, resolved };
diff --git a/src/selfie-capture.js b/src/selfie-capture.js
index eb93832ef..d2c8cc6c8 100644
--- a/src/selfie-capture.js
+++ b/src/selfie-capture.js
@@ -25,20 +25,34 @@ const cameraSupported =
typeof navigator.mediaDevices.getUserMedia === 'function';
// ── DOM refs ───────────────────────────────────────────────────────────────
-const steps = /** @type {NodeListOf<HTMLElement>} */ (document.querySelectorAll('.step[data-step]'));
+const steps = /** @type {NodeListOf<HTMLElement>} */ (
+ document.querySelectorAll('.step[data-step]')
+);
const backBtn = /** @type {HTMLButtonElement} */ (document.getElementById('back-btn'));
-const choiceButtons = /** @type {NodeListOf<HTMLButtonElement>} */ (document.querySelectorAll('.choice[data-method]'));
+const choiceButtons = /** @type {NodeListOf<HTMLButtonElement>} */ (
+ document.querySelectorAll('.choice[data-method]')
+);
const unsupportedMsg = document.getElementById('unsupported-msg');
-const slotFrames = /** @type {NodeListOf<HTMLElement>} */ (document.querySelectorAll('.slot-frame[data-slot]'));
-const slotInputs = /** @type {NodeListOf<HTMLInputElement>} */ (document.querySelectorAll('input[data-slot-input]'));
+const slotFrames = /** @type {NodeListOf<HTMLElement>} */ (
+ document.querySelectorAll('.slot-frame[data-slot]')
+);
+const slotInputs = /** @type {NodeListOf<HTMLInputElement>} */ (
+ document.querySelectorAll('input[data-slot-input]')
+);
const submitBar = document.getElementById('submit-bar');
const submitBtn = /** @type {HTMLButtonElement} */ (document.getElementById('submit-btn'));
-const bodyBtns = /** @type {NodeListOf<HTMLButtonElement>} */ (document.querySelectorAll('[data-body]'));
-const typeBtns = /** @type {NodeListOf<HTMLButtonElement>} */ (document.querySelectorAll('[data-type]'));
+const bodyBtns = /** @type {NodeListOf<HTMLButtonElement>} */ (
+ document.querySelectorAll('[data-body]')
+);
+const typeBtns = /** @type {NodeListOf<HTMLButtonElement>} */ (
+ document.querySelectorAll('[data-type]')
+);
// ── Step 1: method picker ──────────────────────────────────────────────────
if (!cameraSupported) {
- const camChoice = /** @type {HTMLButtonElement | null} */ (document.querySelector('.choice[data-method="camera"]'));
+ const camChoice = /** @type {HTMLButtonElement | null} */ (
+ document.querySelector('.choice[data-method="camera"]')
+ );
if (camChoice) {
camChoice.disabled = true;
camChoice.setAttribute('aria-disabled', 'true');
@@ -139,7 +153,7 @@ submitBtn.addEventListener('click', () => {
avatarType: state.avatarType,
method: state.method,
},
- })
+ }),
);
// Temporary visual ack until task 3 wires the pipeline.
submitBtn.textContent = 'Sending…';
@@ -186,7 +200,9 @@ function clearSlot(slot) {
/** @param {string} slot */
function renderSlot(slot) {
- const frame = /** @type {HTMLElement | null} */ (document.querySelector(`.slot-frame[data-slot="${slot}"]`));
+ const frame = /** @type {HTMLElement | null} */ (
+ document.querySelector(`.slot-frame[data-slot="${slot}"]`)
+ );
if (!frame) return;
const file = state.files[slot];
diff --git a/src/selfie-pipeline.js b/src/selfie-pipeline.js
index b72c3c2dd..b1693640d 100644
--- a/src/selfie-pipeline.js
+++ b/src/selfie-pipeline.js
@@ -127,12 +127,32 @@ function fit(w, h, max) {
*/
function mapApiError(status, payload) {
const code = payload.error;
- if (status === 401) return withMessage(new Error(code || 'unauthorized'), 'Please sign in to create an avatar.');
- if (status === 413) return withMessage(new Error(code || 'too_large'), 'Photos are too large. Try again.');
- if (status === 429) return withMessage(new Error(code || 'rate_limited'), 'Too many attempts — wait a minute and try again.');
- if (status === 501) return withMessage(new Error(code || 'not_configured'), 'Avatar pipeline is not set up on this deployment.');
- if (status === 502) return withMessage(new Error(code || 'upstream_error'), 'Avatar provider is having trouble. Try again shortly.');
- return withMessage(new Error(code || `http_${status}`), payload.error_description || 'Could not create avatar.');
+ if (status === 401)
+ return withMessage(
+ new Error(code || 'unauthorized'),
+ 'Please sign in to create an avatar.',
+ );
+ if (status === 413)
+ return withMessage(new Error(code || 'too_large'), 'Photos are too large. Try again.');
+ if (status === 429)
+ return withMessage(
+ new Error(code || 'rate_limited'),
+ 'Too many attempts — wait a minute and try again.',
+ );
+ if (status === 501)
+ return withMessage(
+ new Error(code || 'not_configured'),
+ 'Avatar pipeline is not set up on this deployment.',
+ );
+ if (status === 502)
+ return withMessage(
+ new Error(code || 'upstream_error'),
+ 'Avatar provider is having trouble. Try again shortly.',
+ );
+ return withMessage(
+ new Error(code || `http_${status}`),
+ payload.error_description || 'Could not create avatar.',
+ );
}
/**
diff --git a/src/share-panel.css b/src/share-panel.css
index 897dec0ec..3bb25a7a8 100644
--- a/src/share-panel.css
+++ b/src/share-panel.css
@@ -102,7 +102,9 @@
font-size: 12px;
padding: 6px 12px;
white-space: nowrap;
- transition: background 0.12s, color 0.12s;
+ transition:
+ background 0.12s,
+ color 0.12s;
}
.share-panel-btn:hover {
diff --git a/src/share-panel.js b/src/share-panel.js
index f82bd45ad..927f1231e 100644
--- a/src/share-panel.js
+++ b/src/share-panel.js
@@ -188,7 +188,8 @@ function _esc(str) {
.replace(/"/g, '&quot;');
}
-const FOCUSABLE = 'a[href],button:not([disabled]),input,select,textarea,[tabindex]:not([tabindex="-1"])';
+const FOCUSABLE =
+ 'a[href],button:not([disabled]),input,select,textarea,[tabindex]:not([tabindex="-1"])';
function _trapFocus(modal) {
// Initial focus on first focusable element
diff --git a/src/stage-element.js b/src/stage-element.js
index 2b0007b74..69c6c9949 100644
--- a/src/stage-element.js
+++ b/src/stage-element.js
@@ -49,9 +49,13 @@ class AgentStageElement extends HTMLElement {
}
disconnectedCallback() {
- try { this._mo?.disconnect(); } catch {}
+ try {
+ this._mo?.disconnect();
+ } catch {}
for (const a of [...this._agents]) this.unregisterAgent(a.element);
- try { this._viewer?.dispose?.(); } catch {}
+ try {
+ this._viewer?.dispose?.();
+ } catch {}
this._viewer = null;
this._initialized = false;
}
@@ -65,7 +69,9 @@ class AgentStageElement extends HTMLElement {
return FORMATIONS.includes(f) ? f : 'row';
}
- get viewer() { return this._viewer; }
+ get viewer() {
+ return this._viewer;
+ }
_renderShell() {
const style = document.createElement('style');
@@ -90,8 +96,12 @@ class AgentStageElement extends HTMLElement {
this._viewer.defaultCamera.lookAt(0, 1.2, 0);
this._viewer.controls.target.set(0, 1.2, 0);
this._viewer.controls.update();
- try { this._viewer.updateLights?.(); } catch {}
- try { this._viewer.updateEnvironment?.(); } catch {}
+ try {
+ this._viewer.updateLights?.();
+ } catch {}
+ try {
+ this._viewer.updateEnvironment?.();
+ } catch {}
this._viewer.invalidate();
this._initialized = true;
}
@@ -104,11 +114,13 @@ class AgentStageElement extends HTMLElement {
this._agents.push(rec);
this._viewer?.scene.add(group);
this._repositionAll();
- this.dispatchEvent(new CustomEvent('stage:agent-joined', {
- detail: { agentId: finalId, element, manifest },
- bubbles: true,
- composed: true,
- }));
+ this.dispatchEvent(
+ new CustomEvent('stage:agent-joined', {
+ detail: { agentId: finalId, element, manifest },
+ bubbles: true,
+ composed: true,
+ }),
+ );
return finalId;
}
@@ -116,14 +128,18 @@ class AgentStageElement extends HTMLElement {
const i = this._agents.findIndex((a) => a.element === element);
if (i < 0) return;
const [rec] = this._agents.splice(i, 1);
- try { this._viewer?.scene.remove(rec.group); } catch {}
+ try {
+ this._viewer?.scene.remove(rec.group);
+ } catch {}
disposeGroup(rec.group);
this._repositionAll();
- this.dispatchEvent(new CustomEvent('stage:agent-left', {
- detail: { agentId: rec.id, element: rec.element },
- bubbles: true,
- composed: true,
- }));
+ this.dispatchEvent(
+ new CustomEvent('stage:agent-left', {
+ detail: { agentId: rec.id, element: rec.element },
+ bubbles: true,
+ composed: true,
+ }),
+ );
}
_uniqueId(base) {
@@ -155,11 +171,13 @@ class AgentStageElement extends HTMLElement {
if (a.id === fromId) continue;
a.element.dispatchEvent(new CustomEvent('stage:message', { detail }));
}
- this.dispatchEvent(new CustomEvent('stage:message', {
- detail,
- bubbles: true,
- composed: true,
- }));
+ this.dispatchEvent(
+ new CustomEvent('stage:message', {
+ detail,
+ bubbles: true,
+ composed: true,
+ }),
+ );
}
async routeMessage(fromId, toId, text) {
@@ -249,7 +267,9 @@ class AgentStageElement extends HTMLElement {
function disposeGroup(group) {
group.traverse((o) => {
if (o.geometry) {
- try { o.geometry.dispose(); } catch {}
+ try {
+ o.geometry.dispose();
+ } catch {}
}
if (o.material) {
const mats = Array.isArray(o.material) ? o.material : [o.material];
@@ -257,10 +277,14 @@ function disposeGroup(group) {
for (const k of Object.keys(m)) {
const v = m[k];
if (v && v.isTexture) {
- try { v.dispose(); } catch {}
+ try {
+ v.dispose();
+ } catch {}
}
}
- try { m.dispose(); } catch {}
+ try {
+ m.dispose();
+ } catch {}
}
}
});
diff --git a/src/validation-ui.js b/src/validation-ui.js
index 756693774..edc035255 100644
--- a/src/validation-ui.js
+++ b/src/validation-ui.js
@@ -10,7 +10,11 @@
*/
import { connectWallet } from './erc8004/agent-registry.js';
-import { getLatestValidation, recordValidation, hashReport } from './erc8004/validation-recorder.js';
+import {
+ getLatestValidation,
+ recordValidation,
+ hashReport,
+} from './erc8004/validation-recorder.js';
export class ValidationDashboard {
constructor(root, els) {
@@ -121,9 +125,7 @@ export class ValidationDashboard {
this.els.emptyState.style.display = 'none';
const recordArray = Array.isArray(records) ? records : [records];
- this.els.recordsContainer.innerHTML = recordArray
- .map((r) => this.renderRecord(r))
- .join('');
+ this.els.recordsContainer.innerHTML = recordArray.map((r) => this.renderRecord(r)).join('');
}
renderRecord(record) {
diff --git a/src/validator.js b/src/validator.js
index 1ddd3e1f0..12227e378 100644
--- a/src/validator.js
+++ b/src/validator.js
@@ -12,8 +12,6 @@ export class Validator {
constructor(el) {
this.el = el;
this.report = null;
-
-
}
/**
@@ -27,15 +25,15 @@ export class Validator {
validate(rootFile, rootPath, assetMap, response) {
// Use Three.js Cache to avoid re-downloading the model.
// Cache.enabled is set to true in viewer.js.
- const fetchBuffer = window.THREE && window.THREE.Cache && window.THREE.Cache.get(rootFile)
- ? Promise.resolve(window.THREE.Cache.get(rootFile))
- .then((data) => {
- if (data instanceof ArrayBuffer) return data;
- // Cache may hold string for .gltf; convert
- if (typeof data === 'string') return new TextEncoder().encode(data).buffer;
- return fetch(rootFile).then((r) => r.arrayBuffer());
- })
- : fetch(rootFile).then((r) => r.arrayBuffer());
+ const fetchBuffer =
+ window.THREE && window.THREE.Cache && window.THREE.Cache.get(rootFile)
+ ? Promise.resolve(window.THREE.Cache.get(rootFile)).then((data) => {
+ if (data instanceof ArrayBuffer) return data;
+ // Cache may hold string for .gltf; convert
+ if (typeof data === 'string') return new TextEncoder().encode(data).buffer;
+ return fetch(rootFile).then((r) => r.arrayBuffer());
+ })
+ : fetch(rootFile).then((r) => r.arrayBuffer());
return fetchBuffer
.then((buffer) =>
@@ -100,8 +98,6 @@ export class Validator {
this.setResponse(response);
-
-
function groupMessages(report) {
const CODES = {
ACCESSOR_NON_UNIT: {
@@ -175,7 +171,6 @@ export class Validator {
this.report = null;
}
-
showLightbox() {
if (!this.report) return;
const tab = window.open('', '_blank');
diff --git a/src/viewer.js b/src/viewer.js
index 7d7eddab8..ff8acd6f9 100644
--- a/src/viewer.js
+++ b/src/viewer.js
@@ -482,7 +482,9 @@ export class Viewer {
this.scene.environment = envMap;
this.scene.background = this.state.transparentBg
? null
- : this.state.background ? envMap : this.backgroundColor;
+ : this.state.background
+ ? envMap
+ : this.backgroundColor;
this.invalidate();
});
}
@@ -550,7 +552,8 @@ export class Viewer {
* @param {string|number} color CSS color string or hex int.
*/
setBackgroundColor(color) {
- this.state.bgColor = typeof color === 'string' ? color : '#' + color.toString(16).padStart(6, '0');
+ this.state.bgColor =
+ typeof color === 'string' ? color : '#' + color.toString(16).padStart(6, '0');
this.state.transparentBg = false;
this.updateBackground();
}
@@ -610,7 +613,7 @@ export class Viewer {
return;
}
- const x = (tempVec.x * halfW) + halfW;
+ const x = tempVec.x * halfW + halfW;
const y = -(tempVec.y * halfH) + halfH;
el.style.display = '';
@@ -668,7 +671,9 @@ export class Viewer {
transparentCtrl.onChange(() => this.updateBackground());
const bgColorCtrl = dispFolder.addColor(this.state, 'bgColor');
bgColorCtrl.onChange(() => this.updateBackground());
- dispFolder.add({ screenshot: () => this.takeScreenshot() }, 'screenshot').name('Screenshot [P]');
+ dispFolder
+ .add({ screenshot: () => this.takeScreenshot() }, 'screenshot')
+ .name('Screenshot [P]');
const infoCtrl = dispFolder.add(this.state, 'showInfo').name('model info');
infoCtrl.onChange(() => this.updateModelInfo(this.content, this.clips));
const labelsCtrl = dispFolder.add(this.state, 'showLabels').name('mesh labels');
@@ -714,7 +719,13 @@ export class Viewer {
// Agent controls.
const agentFolder = gui.addFolder('Agent');
- agentFolder.add(this.state, 'followMode', { 'None': 'none', 'Follow Mouse': 'mouse', 'Follow Keystrokes': 'keystrokes' }).name('follow mode');
+ agentFolder
+ .add(this.state, 'followMode', {
+ None: 'none',
+ 'Follow Mouse': 'mouse',
+ 'Follow Keystrokes': 'keystrokes',
+ })
+ .name('follow mode');
// Stats.
const perfFolder = gui.addFolder('Performance');
@@ -926,39 +937,62 @@ export class Viewer {
const activeName = this.animationManager.currentName;
const ICONS = {
- idle: '🧍', breathing: '🧍', standing: '🧍',
- walking: '🚶', walk: '🚶',
- running: '🏃', run: '🏃',
- waving: '👋', wave: '👋',
- dancing: '💃', dance: '💃',
- sitting: '🪑', sit: '🪑',
- jumping: '🦘', jump: '🦘',
- talking: '🗣️', talk: '🗣️',
- clapping: '👏', clap: '👏',
- punching: '👊', punch: '👊',
- kicking: '🦵', kick: '🦵',
+ idle: '🧍',
+ breathing: '🧍',
+ standing: '🧍',
+ walking: '🚶',
+ walk: '🚶',
+ running: '🏃',
+ run: '🏃',
+ waving: '👋',
+ wave: '👋',
+ dancing: '💃',
+ dance: '💃',
+ sitting: '🪑',
+ sit: '🪑',
+ jumping: '🦘',
+ jump: '🦘',
+ talking: '🗣️',
+ talk: '🗣️',
+ clapping: '👏',
+ clap: '👏',
+ punching: '👊',
+ punch: '👊',
+ kicking: '🦵',
+ kick: '🦵',
};
- grid.innerHTML = defs.map((def, i) => {
- const loaded = this.animationManager.isLoaded(def.name);
- const isActive = activeName === def.name;
- const icon = def.icon || ICONS[def.name.toLowerCase()] || '▶';
- const label = def.label || def.name.charAt(0).toUpperCase() + def.name.slice(1);
- const keyHint = i < 9 ? (i + 1) : '';
- return (
- '<button class="anim-btn' +
- (isActive ? ' anim-btn--active' : '') +
- (loaded ? '' : ' anim-btn--loading') +
- '" data-anim="' + def.name + '"' +
- ' title="' + label + (keyHint ? ' — press ' + keyHint : '') + '"' +
- (loaded ? '' : ' disabled') +
- '>' +
- (keyHint ? '<span class="anim-btn__key">' + keyHint + '</span>' : '') +
- '<span class="anim-btn__icon">' + icon + '</span>' +
- '<span class="anim-btn__label">' + label + '</span>' +
- '</button>'
- );
- }).join('');
+ grid.innerHTML = defs
+ .map((def, i) => {
+ const loaded = this.animationManager.isLoaded(def.name);
+ const isActive = activeName === def.name;
+ const icon = def.icon || ICONS[def.name.toLowerCase()] || '▶';
+ const label = def.label || def.name.charAt(0).toUpperCase() + def.name.slice(1);
+ const keyHint = i < 9 ? i + 1 : '';
+ return (
+ '<button class="anim-btn' +
+ (isActive ? ' anim-btn--active' : '') +
+ (loaded ? '' : ' anim-btn--loading') +
+ '" data-anim="' +
+ def.name +
+ '"' +
+ ' title="' +
+ label +
+ (keyHint ? ' — press ' + keyHint : '') +
+ '"' +
+ (loaded ? '' : ' disabled') +
+ '>' +
+ (keyHint ? '<span class="anim-btn__key">' + keyHint + '</span>' : '') +
+ '<span class="anim-btn__icon">' +
+ icon +
+ '</span>' +
+ '<span class="anim-btn__label">' +
+ label +
+ '</span>' +
+ '</button>'
+ );
+ })
+ .join('');
// Bind click events
grid.querySelectorAll('.anim-btn:not([disabled])').forEach((btn) => {
diff --git a/src/widget-types.js b/src/widget-types.js
index 02ccb8876..faf06ec78 100644
--- a/src/widget-types.js
+++ b/src/widget-types.js
@@ -8,169 +8,194 @@
import { z } from 'zod';
export const WIDGET_TYPES = {
- 'turntable': {
- label: 'Turntable Showcase',
- desc: 'Hero banner — auto-rotate, no UI, just the avatar.',
+ turntable: {
+ label: 'Turntable Showcase',
+ desc: 'Hero banner — auto-rotate, no UI, just the avatar.',
status: 'ready',
- icon: '◎',
+ icon: '◎',
},
'animation-gallery': {
- label: 'Animation Gallery',
- desc: 'Click through every clip on a rigged avatar.',
+ label: 'Animation Gallery',
+ desc: 'Click through every clip on a rigged avatar.',
status: 'pending',
- icon: '▶',
+ icon: '▶',
},
'talking-agent': {
- label: 'Talking Agent',
- desc: 'Embodied chat — your agent on your site.',
+ label: 'Talking Agent',
+ desc: 'Embodied chat — your agent on your site.',
status: 'ready',
- icon: '◐',
+ icon: '◐',
},
- 'passport': {
- label: 'ERC-8004 Passport',
- desc: 'On-chain identity card for any agent.',
+ passport: {
+ label: 'ERC-8004 Passport',
+ desc: 'On-chain identity card for any agent.',
status: 'ready',
- icon: '◊',
+ icon: '◊',
},
'hotspot-tour': {
- label: 'Hotspot Tour',
- desc: 'Annotated 3D scene with clickable points of interest.',
+ label: 'Hotspot Tour',
+ desc: 'Annotated 3D scene with clickable points of interest.',
status: 'pending',
- icon: '⌖',
+ icon: '⌖',
},
};
export const WIDGET_TYPE_KEYS = Object.keys(WIDGET_TYPES);
export const BRAND_DEFAULTS = Object.freeze({
- background: '#0a0a0a',
- accent: '#8b5cf6',
- caption: '',
- showControls: true,
- autoRotate: true,
- envPreset: 'neutral',
+ background: '#0a0a0a',
+ accent: '#8b5cf6',
+ caption: '',
+ showControls: true,
+ autoRotate: true,
+ envPreset: 'neutral',
cameraPosition: null,
});
const TYPE_DEFAULTS = {
- 'turntable': { rotationSpeed: 0.5 },
+ turntable: { rotationSpeed: 0.5 },
'animation-gallery': { defaultClip: '', loopAll: false, showClipPicker: true },
- 'talking-agent': {
- agentName: '',
- agentTitle: 'AI Agent',
- avatar: 'embedded',
- brainProvider: 'anthropic',
- proxyURL: '',
- systemPrompt: '',
- greeting: 'Hi! Ask me anything.',
- temperature: 0.7,
- maxTurns: 20,
- skills: { speak: true, wave: true, lookAt: true, playClip: true, remember: false },
+ 'talking-agent': {
+ agentName: '',
+ agentTitle: 'AI Agent',
+ avatar: 'embedded',
+ brainProvider: 'anthropic',
+ proxyURL: '',
+ systemPrompt: '',
+ greeting: 'Hi! Ask me anything.',
+ temperature: 0.7,
+ maxTurns: 20,
+ skills: { speak: true, wave: true, lookAt: true, playClip: true, remember: false },
showChatHistory: true,
- voiceInput: true,
- voiceOutput: true,
- chatPosition: 'right',
- poweredByBadge: true,
+ voiceInput: true,
+ voiceOutput: true,
+ chatPosition: 'right',
+ poweredByBadge: true,
visitorRateLimit: { msgsPerMinute: 8, msgsPerSession: 50 },
},
- 'passport': {
- chain: 'base-sepolia',
- agentId: null,
- wallet: null,
- showReputation: true,
- showRecentFeedback: true,
- showValidation: false,
+ passport: {
+ chain: 'base-sepolia',
+ agentId: null,
+ wallet: null,
+ showReputation: true,
+ showRecentFeedback: true,
+ showValidation: false,
showRegistrationJSON: true,
- layout: 'portrait',
- badgeSize: 'medium',
- rotationSpeed: 0.6,
- rpcURL: '',
- refreshIntervalSec: 60,
- showPoweredBy: true,
+ layout: 'portrait',
+ badgeSize: 'medium',
+ rotationSpeed: 0.6,
+ rpcURL: '',
+ refreshIntervalSec: 60,
+ showPoweredBy: true,
},
- 'hotspot-tour': { hotspots: [] },
+ 'hotspot-tour': { hotspots: [] },
};
-const hexColor = z.string().regex(/^#[0-9a-fA-F]{3,8}$/, 'must be a hex color');
-const cameraVec = z.tuple([z.number(), z.number(), z.number()]).nullable();
-const envPreset = z.enum(['none', 'neutral', 'venice-sunset', 'footprint-court']);
+const hexColor = z.string().regex(/^#[0-9a-fA-F]{3,8}$/, 'must be a hex color');
+const cameraVec = z.tuple([z.number(), z.number(), z.number()]).nullable();
+const envPreset = z.enum(['none', 'neutral', 'venice-sunset', 'footprint-court']);
const brandSchema = z.object({
- background: hexColor.default(BRAND_DEFAULTS.background),
- accent: hexColor.default(BRAND_DEFAULTS.accent),
- caption: z.string().max(280).default(BRAND_DEFAULTS.caption),
- showControls: z.boolean().default(BRAND_DEFAULTS.showControls),
- autoRotate: z.boolean().default(BRAND_DEFAULTS.autoRotate),
- envPreset: envPreset.default(BRAND_DEFAULTS.envPreset),
+ background: hexColor.default(BRAND_DEFAULTS.background),
+ accent: hexColor.default(BRAND_DEFAULTS.accent),
+ caption: z.string().max(280).default(BRAND_DEFAULTS.caption),
+ showControls: z.boolean().default(BRAND_DEFAULTS.showControls),
+ autoRotate: z.boolean().default(BRAND_DEFAULTS.autoRotate),
+ envPreset: envPreset.default(BRAND_DEFAULTS.envPreset),
cameraPosition: cameraVec.default(BRAND_DEFAULTS.cameraPosition),
});
const TYPE_SCHEMAS = {
- 'turntable': brandSchema.extend({
+ turntable: brandSchema.extend({
rotationSpeed: z.number().min(0).max(10).default(0.5),
}),
'animation-gallery': brandSchema.extend({
- defaultClip: z.string().max(120).default(''),
- loopAll: z.boolean().default(false),
+ defaultClip: z.string().max(120).default(''),
+ loopAll: z.boolean().default(false),
showClipPicker: z.boolean().default(true),
}),
- 'talking-agent': brandSchema.extend({
- agentName: z.string().max(80).default(''),
- agentTitle: z.string().max(80).default('AI Agent'),
- avatar: z.enum(['embedded', 'chat-only']).default('embedded'),
- brainProvider: z.enum(['none', 'anthropic', 'custom']).default('anthropic'),
- proxyURL: z.string().url().startsWith('https://').or(z.literal('')).default(''),
- systemPrompt: z.string().max(4000).default(''),
- greeting: z.string().max(280).default('Hi! Ask me anything.'),
- temperature: z.number().min(0).max(1).default(0.7),
- maxTurns: z.number().int().min(1).max(100).default(20),
- skills: z.object({
- speak: z.boolean().default(true),
- wave: z.boolean().default(true),
- lookAt: z.boolean().default(true),
- playClip: z.boolean().default(true),
- remember: z.boolean().default(false),
- }).default({ speak: true, wave: true, lookAt: true, playClip: true, remember: false }),
- showChatHistory: z.boolean().default(true),
- voiceInput: z.boolean().default(true),
- voiceOutput: z.boolean().default(true),
- chatPosition: z.enum(['right', 'bottom', 'overlay']).default('right'),
- poweredByBadge: z.boolean().default(true),
- visitorRateLimit: z.object({
- msgsPerMinute: z.number().int().min(1).max(60).default(8),
- msgsPerSession: z.number().int().min(1).max(500).default(50),
- }).default({ msgsPerMinute: 8, msgsPerSession: 50 }),
- }).superRefine((cfg, ctx) => {
- if (cfg.brainProvider === 'custom' && !cfg.proxyURL) {
- ctx.addIssue({
- path: ['proxyURL'],
- code: z.ZodIssueCode.custom,
- message: 'proxyURL is required when brainProvider is "custom"',
- });
- }
- }),
- 'passport': brandSchema.extend({
- chain: z.string().min(1).default('base-sepolia'),
- agentId: z.string().regex(/^\d+$/, 'agentId must be a uint256 string').nullable().default(null),
- wallet: z.string().regex(/^0x[0-9a-fA-F]{40}$/).nullable().default(null),
- showReputation: z.boolean().default(true),
- showRecentFeedback: z.boolean().default(true),
- showValidation: z.boolean().default(false),
+ 'talking-agent': brandSchema
+ .extend({
+ agentName: z.string().max(80).default(''),
+ agentTitle: z.string().max(80).default('AI Agent'),
+ avatar: z.enum(['embedded', 'chat-only']).default('embedded'),
+ brainProvider: z.enum(['none', 'anthropic', 'custom']).default('anthropic'),
+ proxyURL: z.string().url().startsWith('https://').or(z.literal('')).default(''),
+ systemPrompt: z.string().max(4000).default(''),
+ greeting: z.string().max(280).default('Hi! Ask me anything.'),
+ temperature: z.number().min(0).max(1).default(0.7),
+ maxTurns: z.number().int().min(1).max(100).default(20),
+ skills: z
+ .object({
+ speak: z.boolean().default(true),
+ wave: z.boolean().default(true),
+ lookAt: z.boolean().default(true),
+ playClip: z.boolean().default(true),
+ remember: z.boolean().default(false),
+ })
+ .default({
+ speak: true,
+ wave: true,
+ lookAt: true,
+ playClip: true,
+ remember: false,
+ }),
+ showChatHistory: z.boolean().default(true),
+ voiceInput: z.boolean().default(true),
+ voiceOutput: z.boolean().default(true),
+ chatPosition: z.enum(['right', 'bottom', 'overlay']).default('right'),
+ poweredByBadge: z.boolean().default(true),
+ visitorRateLimit: z
+ .object({
+ msgsPerMinute: z.number().int().min(1).max(60).default(8),
+ msgsPerSession: z.number().int().min(1).max(500).default(50),
+ })
+ .default({ msgsPerMinute: 8, msgsPerSession: 50 }),
+ })
+ .superRefine((cfg, ctx) => {
+ if (cfg.brainProvider === 'custom' && !cfg.proxyURL) {
+ ctx.addIssue({
+ path: ['proxyURL'],
+ code: z.ZodIssueCode.custom,
+ message: 'proxyURL is required when brainProvider is "custom"',
+ });
+ }
+ }),
+ passport: brandSchema.extend({
+ chain: z.string().min(1).default('base-sepolia'),
+ agentId: z
+ .string()
+ .regex(/^\d+$/, 'agentId must be a uint256 string')
+ .nullable()
+ .default(null),
+ wallet: z
+ .string()
+ .regex(/^0x[0-9a-fA-F]{40}$/)
+ .nullable()
+ .default(null),
+ showReputation: z.boolean().default(true),
+ showRecentFeedback: z.boolean().default(true),
+ showValidation: z.boolean().default(false),
showRegistrationJSON: z.boolean().default(true),
- layout: z.enum(['portrait', 'landscape', 'badge']).default('portrait'),
- badgeSize: z.enum(['small', 'medium', 'large']).default('medium'),
- rotationSpeed: z.number().min(0).max(10).default(0.6),
- rpcURL: z.string().url().startsWith('https://').or(z.literal('')).default(''),
- refreshIntervalSec: z.number().int().min(0).max(3600).default(60),
- showPoweredBy: z.boolean().default(true),
+ layout: z.enum(['portrait', 'landscape', 'badge']).default('portrait'),
+ badgeSize: z.enum(['small', 'medium', 'large']).default('medium'),
+ rotationSpeed: z.number().min(0).max(10).default(0.6),
+ rpcURL: z.string().url().startsWith('https://').or(z.literal('')).default(''),
+ refreshIntervalSec: z.number().int().min(0).max(3600).default(60),
+ showPoweredBy: z.boolean().default(true),
}),
'hotspot-tour': brandSchema.extend({
- hotspots: z.array(z.object({
- id: z.string().min(1).max(40),
- label: z.string().min(1).max(120),
- position: z.tuple([z.number(), z.number(), z.number()]),
- body: z.string().max(2000).optional(),
- })).max(40).default([]),
+ hotspots: z
+ .array(
+ z.object({
+ id: z.string().min(1).max(40),
+ label: z.string().min(1).max(120),
+ position: z.tuple([z.number(), z.number(), z.number()]),
+ body: z.string().max(2000).optional(),
+ }),
+ )
+ .max(40)
+ .default([]),
}),
};
@@ -184,7 +209,9 @@ export function validateConfig(type, config) {
if (!schema) throw new Error(`unknown widget type: ${type}`);
const res = schema.safeParse(config || {});
if (!res.success) {
- const err = new Error(res.error.issues.map((i) => `${i.path.join('.') || 'config'}: ${i.message}`).join('; '));
+ const err = new Error(
+ res.error.issues.map((i) => `${i.path.join('.') || 'config'}: ${i.message}`).join('; '),
+ );
err.code = 'validation_error';
throw err;
}
@@ -205,45 +232,45 @@ export const widgetConfigSchemas = TYPE_SCHEMAS;
// ---------------------------------------------------------------------------
export const CHAIN_SLUGS = {
- 'ethereum': 1,
- 'optimism': 10,
- 'bsc': 56,
- 'polygon': 137,
- 'base': 8453,
- 'arbitrum': 42161,
- 'sepolia': 11155111,
- 'base-sepolia': 84532,
+ ethereum: 1,
+ optimism: 10,
+ bsc: 56,
+ polygon: 137,
+ base: 8453,
+ arbitrum: 42161,
+ sepolia: 11155111,
+ 'base-sepolia': 84532,
'optimism-sepolia': 11155420,
'arbitrum-sepolia': 421614,
- 'polygon-amoy': 80002,
+ 'polygon-amoy': 80002,
};
export const PUBLIC_RPCS = {
- 1: 'https://eth.llamarpc.com',
- 10: 'https://mainnet.optimism.io',
- 56: 'https://bsc-dataseed.binance.org',
- 137: 'https://polygon-rpc.com',
- 8453: 'https://mainnet.base.org',
- 42161: 'https://arb1.arbitrum.io/rpc',
+ 1: 'https://eth.llamarpc.com',
+ 10: 'https://mainnet.optimism.io',
+ 56: 'https://bsc-dataseed.binance.org',
+ 137: 'https://polygon-rpc.com',
+ 8453: 'https://mainnet.base.org',
+ 42161: 'https://arb1.arbitrum.io/rpc',
11155111: 'https://ethereum-sepolia-rpc.publicnode.com',
- 84532: 'https://sepolia.base.org',
+ 84532: 'https://sepolia.base.org',
11155420: 'https://sepolia.optimism.io',
- 421614: 'https://sepolia-rollup.arbitrum.io/rpc',
- 80002: 'https://rpc-amoy.polygon.technology',
+ 421614: 'https://sepolia-rollup.arbitrum.io/rpc',
+ 80002: 'https://rpc-amoy.polygon.technology',
};
export const EXPLORERS = {
- 1: 'https://etherscan.io',
- 10: 'https://optimistic.etherscan.io',
- 56: 'https://bscscan.com',
- 137: 'https://polygonscan.com',
- 8453: 'https://basescan.org',
- 42161: 'https://arbiscan.io',
+ 1: 'https://etherscan.io',
+ 10: 'https://optimistic.etherscan.io',
+ 56: 'https://bscscan.com',
+ 137: 'https://polygonscan.com',
+ 8453: 'https://basescan.org',
+ 42161: 'https://arbiscan.io',
11155111: 'https://sepolia.etherscan.io',
- 84532: 'https://sepolia.basescan.org',
+ 84532: 'https://sepolia.basescan.org',
11155420: 'https://sepolia-optimism.etherscan.io',
- 421614: 'https://sepolia.arbiscan.io',
- 80002: 'https://amoy.polygonscan.com',
+ 421614: 'https://sepolia.arbiscan.io',
+ 80002: 'https://amoy.polygonscan.com',
};
/** Resolve a chain reference (slug or numeric id or numeric string) to chainId. */
diff --git a/src/widgets.js b/src/widgets.js
index 5d4fe8488..ba2b0a037 100644
--- a/src/widgets.js
+++ b/src/widgets.js
@@ -7,7 +7,7 @@ const API = '';
export async function listWidgets({ limit, cursor } = {}) {
const url = new URL(`${API}/api/widgets`, location.origin);
- if (limit) url.searchParams.set('limit', String(limit));
+ if (limit) url.searchParams.set('limit', String(limit));
if (cursor) url.searchParams.set('cursor', cursor);
const res = await fetch(url.pathname + url.search, { credentials: 'include' });
if (res.status === 401) throw err401();
@@ -73,11 +73,13 @@ async function postJson(path, body) {
async function asError(res) {
let data = null;
- try { data = await res.json(); } catch {}
+ try {
+ data = await res.json();
+ } catch {}
const e = new Error(data?.error_description || res.statusText || 'request failed');
e.status = res.status;
- e.code = data?.error || 'request_failed';
- e.data = data;
+ e.code = data?.error || 'request_failed';
+ e.data = data;
return e;
}
diff --git a/src/widgets/passport.js b/src/widgets/passport.js
index 1fe22ebd2..a37af9b0d 100644
--- a/src/widgets/passport.js
+++ b/src/widgets/passport.js
@@ -20,8 +20,11 @@ import {
REGISTRY_DEPLOYMENTS,
} from '../erc8004/index.js';
import {
- CHAIN_SLUGS, PUBLIC_RPCS, EXPLORERS,
- resolveChainId, chainLabel,
+ CHAIN_SLUGS,
+ PUBLIC_RPCS,
+ EXPLORERS,
+ resolveChainId,
+ chainLabel,
} from '../widget-types.js';
import { resolveURI, isDecentralizedURI } from '../ipfs.js';
@@ -76,7 +79,9 @@ export async function mountPassport(viewer, config, container, widgetId) {
const tick = () => {
if (state.destroyed) return;
if (document.hidden) return;
- _refresh(state, panel).catch(() => { /* keep stale */ });
+ _refresh(state, panel).catch(() => {
+ /* keep stale */
+ });
};
state.pollTimer = setInterval(tick, config.refreshIntervalSec * 1000);
@@ -189,7 +194,15 @@ async function _refresh(state, panel) {
manifest = await _fetchManifest(tokenURI).catch(() => null);
}
- state.data = { wallet, tokenURI, name, symbol, reputation: reputationData, feedback, manifest };
+ state.data = {
+ wallet,
+ tokenURI,
+ name,
+ symbol,
+ reputation: reputationData,
+ feedback,
+ manifest,
+ };
state.lastVerifiedAt = Date.now();
_writeCache(state.cacheKey, { data: state.data, savedAt: state.lastVerifiedAt });
@@ -240,9 +253,9 @@ async function _fetchManifest(tokenURI) {
function _pickManifestFields(raw) {
if (!raw || typeof raw !== 'object') return null;
return {
- name: typeof raw.name === 'string' ? raw.name.slice(0, 120) : '',
- description: typeof raw.description === 'string' ? raw.description.slice(0, 500) : '',
- image: typeof raw.image === 'string' ? raw.image : '',
+ name: typeof raw.name === 'string' ? raw.name.slice(0, 120) : '',
+ description: typeof raw.description === 'string' ? raw.description.slice(0, 500) : '',
+ image: typeof raw.image === 'string' ? raw.image : '',
agentRegistry: typeof raw.agentRegistry === 'string' ? raw.agentRegistry.slice(0, 200) : '',
};
}
@@ -290,45 +303,62 @@ function _render(panel, state, opts = {}) {
const verifiedRel = lastVerifiedAt ? _relativeTime(lastVerifiedAt) : '';
const stale = Boolean(opts.staleReason);
- const repBlock = (config.showReputation && data.reputation) ? `
+ const repBlock =
+ config.showReputation && data.reputation
+ ? `
<div class="passport-row passport-row--reputation">
<span class="passport-star" aria-hidden="true">★</span>
<span class="passport-rep-avg">${data.reputation.count === 0 ? '—' : data.reputation.average.toFixed(2)}</span>
<span class="passport-rep-count">(${data.reputation.count} ${data.reputation.count === 1 ? 'review' : 'reviews'})</span>
</div>
- ` : '';
+ `
+ : '';
- const feedbackBlock = (config.showRecentFeedback && data.feedback && data.feedback.length) ? `
+ const feedbackBlock =
+ config.showRecentFeedback && data.feedback && data.feedback.length
+ ? `
<div class="passport-section passport-section--feedback">
<div class="passport-section-title">Recent feedback</div>
<ul class="passport-feedback-list">
- ${data.feedback.map((f) => `
+ ${data.feedback
+ .map(
+ (f) => `
<li class="passport-feedback-item">
<span class="passport-feedback-comment">${_escapeHTML(f.comment || '—')}</span>
<span class="passport-feedback-meta">${_shortAddr(f.from)} · ${f.score}★</span>
</li>
- `).join('')}
+ `,
+ )
+ .join('')}
</ul>
</div>
- ` : '';
+ `
+ : '';
- const jsonBlock = (config.showRegistrationJSON && data.tokenURI) ? `
+ const jsonBlock =
+ config.showRegistrationJSON && data.tokenURI
+ ? `
<div class="passport-section passport-section--json">
<a class="passport-json-link" href="${_escapeAttr(_resolveForLink(data.tokenURI))}" target="_blank" rel="noopener noreferrer">
View passport JSON ↗
</a>
</div>
- ` : '';
+ `
+ : '';
- const explorerLink = explorer ? `
+ const explorerLink = explorer
+ ? `
<a class="passport-explorer-link" href="${_escapeAttr(`${explorer}/address/${data.wallet}`)}" target="_blank" rel="noopener noreferrer" title="View on explorer">↗</a>
- ` : '';
+ `
+ : '';
const chainSlug = chainLabel(chainId);
- const staleBanner = stale ? `
+ const staleBanner = stale
+ ? `
<div class="passport-stale">Offline · last verified ${_escapeHTML(verifiedRel)}</div>
- ` : '';
+ `
+ : '';
if (config.layout === 'badge') {
panel.innerHTML = `
@@ -340,12 +370,16 @@ function _render(panel, state, opts = {}) {
<span class="passport-badge-chain">${_escapeHTML(chainSlug)}</span>
<span class="passport-badge-check" aria-label="Registered on-chain">✓</span>
</div>
- ${config.showReputation && data.reputation ? `
+ ${
+ config.showReputation && data.reputation
+ ? `
<div class="passport-badge-rep">
<span class="passport-star" aria-hidden="true">★</span>
${data.reputation.count === 0 ? '—' : data.reputation.average.toFixed(2)}
</div>
- ` : ''}
+ `
+ : ''
+ }
${staleBanner}
</div>
${config.showPoweredBy ? _poweredByHTML(config) : ''}
@@ -373,11 +407,15 @@ function _render(panel, state, opts = {}) {
${repBlock}
${feedbackBlock}
${jsonBlock}
- ${lastVerifiedAt ? `
+ ${
+ lastVerifiedAt
+ ? `
<div class="passport-verified" title="${_escapeAttr(verifiedISO)}">
${stale ? 'Last verified' : 'Verified'} ${_escapeHTML(verifiedRel)}
</div>
- ` : ''}
+ `
+ : ''
+ }
</div>
${config.showPoweredBy ? _poweredByHTML(config) : ''}
`;
@@ -387,10 +425,15 @@ function _render(panel, state, opts = {}) {
copyBtn.addEventListener('click', () => {
const addr = copyBtn.dataset.copy;
if (!addr) return;
- navigator.clipboard?.writeText(addr).then(() => {
- copyBtn.classList.add('passport-wallet--copied');
- setTimeout(() => copyBtn.classList.remove('passport-wallet--copied'), 1200);
- }).catch(() => { /* ignore */ });
+ navigator.clipboard
+ ?.writeText(addr)
+ .then(() => {
+ copyBtn.classList.add('passport-wallet--copied');
+ setTimeout(() => copyBtn.classList.remove('passport-wallet--copied'), 1200);
+ })
+ .catch(() => {
+ /* ignore */
+ });
});
}
}
@@ -437,7 +480,9 @@ function _readCache(key) {
if (!parsed?.savedAt) return null;
if (Date.now() - parsed.savedAt > STALE_TTL_MS) return null;
return parsed;
- } catch { return null; }
+ } catch {
+ return null;
+ }
}
function _writeCache(key, payload) {
@@ -446,17 +491,19 @@ function _writeCache(key, payload) {
const safe = {
savedAt: payload.savedAt,
data: {
- wallet: payload.data.wallet,
- tokenURI: payload.data.tokenURI,
- name: payload.data.name,
- symbol: payload.data.symbol,
+ wallet: payload.data.wallet,
+ tokenURI: payload.data.tokenURI,
+ name: payload.data.name,
+ symbol: payload.data.symbol,
reputation: payload.data.reputation,
- feedback: payload.data.feedback,
- manifest: payload.data.manifest,
+ feedback: payload.data.feedback,
+ manifest: payload.data.manifest,
},
};
localStorage.setItem(key, JSON.stringify(safe));
- } catch { /* quota / privacy mode — ignore */ }
+ } catch {
+ /* quota / privacy mode — ignore */
+ }
}
// ---------------------------------------------------------------------------
@@ -484,7 +531,9 @@ function _escapeAttr(s) {
function _sanitizeText(s) {
// Strip anything that looks like a tag. Feedback is plain text.
- return String(s ?? '').replace(/<[^>]*>/g, '').slice(0, 500);
+ return String(s ?? '')
+ .replace(/<[^>]*>/g, '')
+ .slice(0, 500);
}
function _relativeTime(ts) {
diff --git a/vercel.json b/vercel.json
index ab6026092..01c277702 100644
--- a/vercel.json
+++ b/vercel.json
@@ -36,11 +36,17 @@
{ "src": "/api/agents/me", "dest": "/api/agents" },
{ "src": "/api/agents/suggest", "dest": "/api/agents/suggest" },
{ "src": "/api/agents/by-wallet", "dest": "/api/agents/by-wallet" },
- { "src": "/api/agents/by-address/([^/]+)", "dest": "/api/agents/by-address/[addr]?addr=$1" },
+ {
+ "src": "/api/agents/by-address/([^/]+)",
+ "dest": "/api/agents/by-address/[addr]?addr=$1"
+ },
{ "src": "/api/agents/([^/]+)/wallet", "dest": "/api/agents/[id]" },
- { "src": "/api/avatars/([^/]+)/storage-mode", "dest": "/api/avatars/[id]/storage-mode?id=$1" },
- { "src": "/api/avatars/([^/]+)/pin-ipfs", "dest": "/api/avatars/[id]/pin-ipfs?id=$1" },
- { "src": "/dashboard/storage", "dest": "/public/dashboard/storage.html" },
+ {
+ "src": "/api/avatars/([^/]+)/storage-mode",
+ "dest": "/api/avatars/[id]/storage-mode?id=$1"
+ },
+ { "src": "/api/avatars/([^/]+)/pin-ipfs", "dest": "/api/avatars/[id]/pin-ipfs?id=$1" },
+ { "src": "/dashboard/storage", "dest": "/public/dashboard/storage.html" },
{
"src": "/api/agents/([^/]+)/embed-policy",
"dest": "/api/agents/[id]/embed-policy?id=$1"