Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
milady
nirholasee29da6a62bf
diff --git a/.env.example b/.env.exampleindex 247cabd0a..84ddf6afd 100644--- a/.env.example+++ b/.env.example@@ -59,3 +59,8 @@ AVATURN_API_URL=https://api.avaturn.me# by Avaturn; the developer ID (if needed) is appended as a query param.VITE_AVATURN_EDITOR_URL=https://editor.avaturn.me/VITE_AVATURN_DEVELOPER_ID=++# Avatar regeneration provider (optional)+# Set to "stub" for testing, or a provider name when configured.+# Unset or "none" → API returns 501 regen_unconfigured.+AVATAR_REGEN_PROVIDER=nonediff --git a/api/_lib/env.js b/api/_lib/env.jsindex eab406069..e8c1629ad 100644--- a/api/_lib/env.js+++ b/api/_lib/env.js@@ -91,4 +91,10 @@ export const env = {get CRON_SECRET() {return opt('CRON_SECRET');},++ // Privy app ID (wallet auth via Privy identity tokens).+ // Get from https://dashboard.privy.io+ get PRIVY_APP_ID() {+ return req('PRIVY_APP_ID');+ },};diff --git a/api/_lib/privy.js b/api/_lib/privy.jsnew file mode 100644index 000000000..0df6bc207--- /dev/null+++ b/api/_lib/privy.js@@ -0,0 +1,91 @@+// Privy JWT verification: JWKS fetch + cache + token verification.++import { jwtVerify, importJWK } from 'jose';+import { env } from './env.js';++// JWKS cache: Map<kid, publicKey>. Fetched once per PRIVY_APP_ID per 60-minute window.+const jwksCache = new Map();+let lastJwksFetch = 0;+const JWKS_TTL_MS = 60 * 60 * 1000;++async function fetchJwks() {+ const now = Date.now();+ if (jwksCache.size > 0 && now - lastJwksFetch < JWKS_TTL_MS) {+ return;+ }++ const appId = env.PRIVY_APP_ID;+ const url = `https://auth.privy.io/api/v1/apps/${appId}/jwks.json`;+ const res = await fetch(url);+ if (!res.ok) {+ throw new Error(`JWKS fetch failed: ${res.status} ${res.statusText}`);+ }++ const data = await res.json();+ jwksCache.clear();+ for (const key of data.keys || []) {+ if (key.kid && key.use === 'sig' && key.kty === 'EC') {+ const publicKey = await importJWK(key, 'ES256');+ jwksCache.set(key.kid, publicKey);+ }+ }+ lastJwksFetch = now;+}++// Verify a Privy identity token.+// Returns { userId, walletAddress, email, iat, exp } on success.+export async function verifyPrivyIdToken(token) {+ await fetchJwks();++ const appId = env.PRIVY_APP_ID;+ const decoded = jwtDecode(token);+ const kid = decoded.header.kid;++ if (!kid) {+ throw new Error('Token missing kid in header');+ }++ let publicKey = jwksCache.get(kid);+ if (!publicKey) {+ // Cache miss — refresh JWKS and try again.+ jwksCache.clear();+ lastJwksFetch = 0;+ await fetchJwks();+ publicKey = jwksCache.get(kid);+ }++ if (!publicKey) {+ throw new Error(`Key not found in JWKS: ${kid}`);+ }++ const { payload } = await jwtVerify(token, publicKey, {+ issuer: 'privy.io',+ audience: appId,+ algorithms: ['ES256'],+ });++ // Extract wallet address from linked_accounts+ let walletAddress = null;+ if (payload.linked_accounts && Array.isArray(payload.linked_accounts)) {+ const wallet = payload.linked_accounts.find((acct) => acct.type === 'wallet');+ if (wallet && wallet.address) {+ walletAddress = wallet.address.toLowerCase();+ }+ }++ return {+ userId: payload.sub,+ walletAddress,+ email: payload.email || null,+ iat: payload.iat,+ exp: payload.exp,+ };+}++// Simple JWT header decoder (without verification) to extract kid.+function jwtDecode(token) {+ const [headerB64] = token.split('.');+ if (!headerB64) throw new Error('Invalid token format');+ const header = JSON.parse(Buffer.from(headerB64, 'base64').toString('utf8'));+ return { header };+}diff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex 57d3ae0d5..4d1d5638b 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -393,3 +393,17 @@ create table if not exists erc8004_crawl_cursor (-- Additive migrations for usage_events.alter table usage_events add column if not exists agent_id uuid references agent_identities(id) on delete set null;create index if not exists usage_events_agent_time on usage_events(agent_id, created_at desc) where agent_id is not null;++-- ── agent_registrations_pending — transient prep records for 2-step registration ─────+create table if not exists agent_registrations_pending (+ id uuid primary key default gen_random_uuid(),+ user_id uuid not null references users(id) on delete cascade,+ cid text not null, -- IPFS CID+ metadata_uri text not null, -- ipfs://CID+ payload jsonb not null, -- registration JSON+ created_at timestamptz not null default now(),+ expires_at timestamptz not null+);++create index if not exists agent_registrations_pending_user_expiry+ on agent_registrations_pending(user_id, expires_at);diff --git a/api/agents/REGISTER_FLOW.md b/api/agents/REGISTER_FLOW.mdnew file mode 100644index 000000000..eced6ae71--- /dev/null+++ b/api/agents/REGISTER_FLOW.md@@ -0,0 +1,215 @@+# Agent Registration Flow — Server-side Prep + Client-side Sign++## Overview++ERC-8004 agent registration is a two-step flow that keeps the private key on the client:++1. **Prep** (server): Build canonical JSON, pin to IPFS, store transient record → get CID+2. **Sign** (client): Sign the registration tx, submit to blockchain+3. **Confirm** (server): Verify tx succeeded, metadata CID matches, update database++The server-side prep endpoint eliminates the need for users to manage IPFS pinning tokens (web3.storage / Filebase), while keeping blockchain operations fully client-controlled.++---++## Sequence Diagram++```+┌────────┐ ┌──────────────┐ ┌─────────────────┐+│ Client │ │ Our Servers │ │ IPFS / Blockchain│+└───┬────┘ └──────┬───────┘ └────────┬────────┘+ │ │ │+ │ 1. POST /api/agents/register-prep │ │+ │ {name, description, avatarId, ...} │ │+ ├─────────────────────────────────────────>│ │+ │ │ │+ │ (validate input, │ │+ │ build JSON, │ │+ │ pin to IPFS) │ │+ │ │ │+ │ ├────────────────────────────────>│+ │ │ Pin registration.json │+ │ │<────────────────────────────────┤+ │ │ CID returned │+ │ │ │+ │ (store prep record,│ │+ │ 1-hour expiry) │ │+ │<─────────────────────────────────────────┤ │+ │ {ok: true, cid, metadataURI, prepId} │ │+ │ │ │+ │ 2. Sign tx locally │ │+ │ (registerAgent(owner, metadataURI)) │ │+ │ │ │+ │ 3. Submit tx to blockchain │ │+ │────────────────────────────────────────────────────────────────>│+ │ │ │+ │ │ (wait for confirmation)+ │<─────────────────────────────────────────────────────────────────┤+ │ tx.hash returned │ │+ │ │ │+ │ 4. POST /api/agents/register-confirm │ │+ │ {prepId, chainId, agentId, txHash} │ │+ ├─────────────────────────────────────────>│ │+ │ │ │+ │ (fetch tx receipt,│ │+ │ parse event, │ │+ │ verify CID match)│ │+ │ ├────────────────────────────────>│+ │ │ getTransactionReceipt(txHash) │+ │ │<────────────────────────────────┤+ │ │ Receipt with logs │+ │ │ │+ │ (upsert agent_ │ │+ │ identities, │ │+ │ consume prep) │ │+ │<─────────────────────────────────────────┤ │+ │ {ok: true, agentId} │ │+ │ │ │+```++---++## Endpoints++### 1. `POST /api/agents/register-prep`++**Purpose:** Build, pin, and reserve a registration JSON for the next 1 hour.++**Authentication:** Session cookie (`getSessionUser`) required.++**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"+}+```++**Validation:**+- `name`: 1–60 chars.+- `description`: ≤ 280 chars.+- `avatarId`: Must belong to the authed user (404 if not).+- `skills`: Array of ≤ 16 strings, each 1–40 chars, alphanumeric + hyphen.+- `brain`, `embedPolicy`, `demoSlug`: Optional.++**Response (200 OK):**+```json+{+ "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.++---++### 2. `POST /api/agents/register-confirm`++**Purpose:** Verify on-chain registration tx, confirm metadata CID, upsert agent record.++**Authentication:** Session cookie required. Must match the `prepId` owner.++**Rate limit:** `limits.authIp` (per-user, 30 per 10 min).++**Request body:**+```json+{+ "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.+4. Event's `agentURI` (metadataURI) matches prep record's `metadataURI`.+5. Agent record upserted to `agent_identities` table.++**Response (200 OK):**+```json+{+ "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.+- 409: Metadata URI mismatch.+- 429: Rate limited.++---++## Notes++### IPFS / Pinning++- **Server-side benefit:** Users don't need to manage keys or tokens; prep endpoint owns the pinning.+- **Fallback:** If web3.storage isn't configured, the JSON is stored to R2 and a stub CID is generated.+- **Client-side GLB:** The client still manages its own GLB pinning (via `pinFile()` in `src/erc8004/agent-registry.js`). The prep endpoint only pins the registration JSON.++### Prep record expiry++- Prep records expire after **1 hour**. If the user signs and submits a TX after 1 hour, the confirm endpoint will reject it.+- This is by design: stale preps cannot be confirmed, protecting against accidental delayed confirms or pre-signed TXs that sit unsigned for too long.++### On-chain event verification++- The confirm endpoint fetches the TX receipt from the chain's public RPC (from `SERVER_CHAIN_META`).+- It decodes the `Registered` event from the logs to extract the `agentURI`.+- The `agentURI` must exactly match the `ipfs://CID` that was reserved in the prep step.++### Database schema++**agent_registrations_pending:**+- `id` (uuid, PK)+- `user_id` (uuid, FK to users)+- `cid` (text) — IPFS CID+- `metadata_uri` (text) — `ipfs://CID` or http URL+- `payload` (jsonb) — the full registration JSON+- `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`++---++## Example flow (Happy path)++1. User fills out form → `POST /api/agents/register-prep`.+2. Server returns `{cid, metadataURI, prepId}`.+3. Client calls `registerAgent()` on-chain with `metadataURI` → gets `agentId` + `txHash`.+4. Client calls `POST /api/agents/register-confirm` with `txHash`.+5. Server verifies, upserts agent identity → returns success.+6. Dashboard shows "Agent registered on-chain as #1234".diff --git a/api/agents/[id]/actions.js b/api/agents/[id]/actions.jsnew file mode 100644index 000000000..6531591af--- /dev/null+++ b/api/agents/[id]/actions.js@@ -0,0 +1,94 @@+/**+ * GET /api/agents/:id/actions?limit=100&cursor=<timestamp>+ * -------+ * Paginated signed action log for an agent. Verifies EIP-191 signatures.+ * Auth: caller must own the agent OR agent visibility must be 'public'.+ */++import { verifyMessage } from 'ethers';+import { sql } from '../../_lib/db.js';+import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';+import { cors, json, error, wrap } from '../../_lib/http.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (req.method !== 'GET') return error(res, 405, 'method_not_allowed', 'GET only');++ const id = req.query?.id || new URL(req.url, 'http://x').pathname.split('/').filter(Boolean)[2];+ if (!id) return error(res, 400, 'invalid_request', 'agent id required');++ // Auth: session or bearer+ const session = await getSessionUser(req);+ const bearer = session ? null : await authenticateBearer(extractBearer(req));+ const userId = session?.id ?? bearer?.userId;++ // Check agent exists and access+ const [agent] = await sql`+ SELECT id, user_id, name, wallet_address+ FROM agent_identities+ WHERE id = ${id} AND deleted_at IS NULL+ `;+ if (!agent) return error(res, 404, 'not_found', 'agent not found');++ // Auth check: must be owner (agents don't have visibility field yet)+ if (!userId || agent.user_id !== userId) {+ return error(res, 403, 'forbidden', 'not authorized to view this agent');+ }++ const url = new URL(req.url, 'http://x');+ const limit = Math.min(Number(url.searchParams.get('limit')) || 50, 200);+ const cursor = url.searchParams.get('cursor'); // ISO timestamp cursor++ // Query actions ordered by timestamp DESC+ const actions = cursor+ ? await sql`+ SELECT id, type, payload, source_skill, signature, signer_address, created_at+ FROM agent_actions+ WHERE agent_id = ${id} AND created_at < ${cursor}+ ORDER BY created_at DESC+ LIMIT ${limit + 1}+ `+ : await sql`+ SELECT id, type, payload, source_skill, signature, signer_address, created_at+ FROM agent_actions+ WHERE agent_id = ${id}+ ORDER BY created_at DESC+ LIMIT ${limit + 1}+ `;++ const hasMore = actions.length > limit;+ const trimmed = hasMore ? actions.slice(0, limit) : actions;+ const nextCursor = hasMore ? trimmed[trimmed.length - 1].created_at.toISOString() : null;++ // Verify signatures for each action+ const decorated = trimmed.map((row) => {+ let verified = null;+ if (row.signature && row.signer_address && row.payload) {+ try {+ const message = JSON.stringify(row.payload) + row.created_at.toISOString();+ const recovered = verifyMessage(message, row.signature);+ verified = recovered.toLowerCase() === row.signer_address.toLowerCase();+ } catch {+ verified = false;+ }+ }+ return {+ id: String(row.id),+ type: row.type,+ payload: row.payload,+ sourceSkill: row.source_skill,+ timestamp: row.created_at.toISOString(),+ signature: row.signature || null,+ signer: row.signer_address || null,+ verified,+ };+ });++ // Cache: private, 10 seconds+ res.setHeader('Cache-Control', 'private, max-age=10');++ return json(res, 200, {+ actions: decorated,+ nextCursor,+ });+});diff --git a/api/agents/register-confirm.js b/api/agents/register-confirm.jsnew file mode 100644index 000000000..46f445b51--- /dev/null+++ b/api/agents/register-confirm.js@@ -0,0 +1,185 @@+/**+ * POST /api/agents/register-confirm+ *+ * Verifies on-chain registration tx, confirms metadata CID matches prep record,+ * then upserts the agent_identities row.+ *+ * Requires: session auth, valid prepId, txHash, chainId, agentId+ * Returns: { ok: true, agentId } or { ok: false, error }+ */++import { sql } from '../_lib/db.js';+import { getSessionUser } from '../_lib/auth.js';+import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';+import { parse } from '../_lib/validate.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { SERVER_CHAIN_META } from '../_lib/onchain.js';+import { z } from 'zod';+import { AbiCoder, getAddress, keccak256, toUtf8Bytes } from 'ethers';++const bodySchema = z.object({+ prepId: z.string().uuid(),+ chainId: z.number().int().positive(),+ agentId: z.union([z.string(), z.number()]),+ txHash: z.string().regex(/^0x[a-f0-9]{64}$/i),+});++// ERC-721 Transfer event (emitted when token is minted)+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;+ if (!method(req, res, ['POST'])) return;++ const session = await getSessionUser(req);+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');++ const ip = clientIp(req);+ const rl = await limits.authIp(ip);+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const body = parse(bodySchema, await readJson(req));+ const chainMeta = SERVER_CHAIN_META[body.chainId];+ if (!chainMeta) return error(res, 400, 'bad_request', `unsupported chain ${body.chainId}`);++ // Verify prep record exists, belongs to user, not expired+ const [prep] = await sql`+ select id, cid, metadata_uri, payload from agent_registrations_pending+ where id = ${body.prepId} and user_id = ${session.id} and expires_at > now()+ limit 1+ `;+ if (!prep) return error(res, 404, 'not_found', 'prep record not found or expired');++ // Fetch tx receipt from RPC+ let receipt;+ try {+ receipt = await fetchTransactionReceipt(chainMeta.rpc, body.txHash);+ } catch (err) {+ return error(res, 400, 'bad_request', `tx verification failed: ${err.message}`);+ }++ if (!receipt) {+ return error(res, 400, 'bad_request', 'tx not found or still pending');+ }++ if (receipt.status !== 1) {+ return error(res, 400, 'bad_request', 'tx failed on-chain');+ }++ // Parse Registered event from logs+ let agentURI;+ try {+ agentURI = parseRegisteredEvent(receipt.logs, chainMeta.registry);+ } catch (err) {+ return error(res, 400, 'bad_request', `failed to parse event: ${err.message}`);+ }++ // Verify metadataURI matches prep record+ if (agentURI !== prep.metadata_uri) {+ return error(res, 409, 'conflict', `metadata URI mismatch: expected ${prep.metadata_uri} got ${agentURI}`);+ }++ // Upsert agent_identities+ const agentId = String(body.agentId);+ const [updated] = await sql`+ insert into agent_identities (+ user_id, name, description, avatar_id,+ chain_id, erc8004_agent_id, erc8004_registry, registration_cid+ )+ values (+ ${session.id},+ ${(prep.payload.name || 'Unnamed Agent').slice(0, 255)},+ ${(prep.payload.description || '').slice(0, 1000)},+ null,+ ${body.chainId},+ ${agentId},+ ${chainMeta.registry},+ ${prep.cid}+ )+ on conflict (user_id) do update set+ name = excluded.name,+ description = excluded.description,+ chain_id = excluded.chain_id,+ erc8004_agent_id = excluded.erc8004_agent_id,+ erc8004_registry = excluded.erc8004_registry,+ registration_cid = excluded.registration_cid,+ updated_at = now()+ returning id+ `;++ // Consume the prep record so it can't be reused+ await sql`delete from agent_registrations_pending where id = ${body.prepId}`;++ return json(res, 200, {+ ok: true,+ agentId: updated.id,+ });+});++/**+ * Fetch transaction receipt from JSON-RPC.+ * @param {string} rpcUrl+ * @param {string} txHash+ * @returns {Promise<object|null>}+ */+async function fetchTransactionReceipt(rpcUrl, txHash) {+ const res = await fetch(rpcUrl, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'eth_getTransactionReceipt',+ params: [txHash],+ }),+ });++ const data = await res.json();+ if (data.error) throw new Error(`RPC error: ${data.error.message}`);+ return data.result;+}++/**+ * Parse Registered event from receipt logs.+ * Returns the agentURI (metadataURI) from the event.+ *+ * Event signature: Registered(uint256 indexed agentId, string agentURI, address indexed owner)+ * Topic hash: keccak256('Registered(uint256,string,address)')+ *+ * @param {array} logs+ * @param {string} registryAddress+ * @returns {string} agentURI+ */+function parseRegisteredEvent(logs, registryAddress) {+ const registryAddr = getAddress(registryAddress);+ const topic0 = eventSignatureHash('Registered(uint256,string,address)');++ for (const log of logs) {+ // Match registry address and Registered event topic+ 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.+ const abi = ['string'];+ const coder = AbiCoder.defaultAbiCoder();+ const decoded = coder.decode(abi, log.data);+ return decoded[0];+ }+ }++ throw new Error('Registered event not found in receipt');+}++/**+ * Compute keccak256 hash of event signature string.+ * Used to match event topic0.+ *+ * @param {string} signature e.g., 'Registered(uint256,string,address)'+ * @returns {string} hex digest with 0x prefix+ */+function eventSignatureHash(signature) {+ return keccak256(toUtf8Bytes(signature));+}diff --git a/api/agents/register-prep.js b/api/agents/register-prep.jsnew file mode 100644index 000000000..8662990c7--- /dev/null+++ b/api/agents/register-prep.js@@ -0,0 +1,165 @@+/**+ * POST /api/agents/register-prep+ *+ * Server-side registration prep: builds canonical registration JSON,+ * pins to IPFS, stores a transient record, returns CID for client signing.+ *+ * Requires: session auth, valid avatarId owned by user, metadata fields.+ * Rate limit: authedWrite per user.+ * Returns: { ok: true, cid, metadataURI, prepId } or { ok: false, error }+ */++import { sql } from '../_lib/db.js';+import { getSessionUser } from '../_lib/auth.js';+import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';+import { parse } from '../_lib/validate.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { env } from '../_lib/env.js';+import { r2 } from '../_lib/r2.js';+import { PutObjectCommand } from '@aws-sdk/client-s3';+import { z } from 'zod';+import { createHash } from 'crypto';++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(),+ embedPolicy: z.record(z.any()).optional(),+ demoSlug: z.string().optional(),+});++const PREP_EXPIRY_HOURS = 1;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const session = await getSessionUser(req);+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');++ const ip = clientIp(req);+ const rl = await limits.authIp(ip);+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const body = parse(bodySchema, await readJson(req));++ // Verify avatar belongs to user+ const [avatar] = await sql`+ select id from avatars+ where id = ${body.avatarId} and owner_id = ${session.id} and deleted_at is null+ limit 1+ `;+ if (!avatar) return error(res, 404, 'not_found', 'avatar not found');++ // Build canonical registration JSON per ERC-8004 spec+ const registrationJson = {+ $schema: 'https://3d-agent.io/schemas/manifest/0.1.json',+ spec: 'agent-manifest/0.1',+ name: body.name,+ description: body.description,+ image: '',+ tags: [],+ body: {+ uri: '', // filled by client-side GLB pinning if needed+ format: 'gltf-binary',+ },+ _baseURI: `ipfs://`, // CRITICAL: must end with / per invariants+ ...(body.brain && { brain: body.brain }),+ ...(body.skills && body.skills.length > 0 && { skills: body.skills }),+ ...(body.embedPolicy && { embedPolicy: body.embedPolicy }),+ ...(body.demoSlug && { demoSlug: body.demoSlug }),+ };++ // Pin to IPFS+ const { cid, metadataURI } = await pinRegistrationJson(registrationJson);++ // Store prep record (1-hour expiry)+ const expiresAt = new Date(Date.now() + PREP_EXPIRY_HOURS * 60 * 60 * 1000);+ const [prep] = await sql`+ insert into agent_registrations_pending+ (user_id, cid, metadata_uri, payload, expires_at)+ values+ (${session.id}, ${cid}, ${metadataURI}, ${JSON.stringify(registrationJson)}::jsonb, ${expiresAt})+ returning id+ `;++ return json(res, 200, {+ ok: true,+ cid,+ metadataURI,+ prepId: prep.id,+ });+});++/**+ * Pin registration JSON to IPFS.+ *+ * Strategy:+ * 1. Try web3.storage if WEB3_STORAGE_TOKEN is available+ * 2. Otherwise store to R2 and generate a content-hash-based stub CID+ *+ * @param {object} json Registration JSON+ * @returns {Promise<{cid: string, metadataURI: string}>}+ */+async function pinRegistrationJson(json) {+ const jsonStr = JSON.stringify(json);+ const jsonBytes = Buffer.from(jsonStr, 'utf-8');++ // Try web3.storage first+ const token = process.env.WEB3_STORAGE_TOKEN;+ if (token) {+ try {+ const cid = await pinToWeb3Storage(jsonBytes, token);+ return { cid, metadataURI: `ipfs://${cid}` };+ } catch (err) {+ console.error('[register-prep] web3.storage pin failed:', err.message);+ // fall through to fallback+ }+ }++ // Fallback: store to R2 and generate stub CID from content hash+ const contentHash = createHash('sha256').update(jsonStr).digest('hex');+ 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',+ }));++ return { cid: stubCid, metadataURI: `ipfs://${stubCid}` };+}++/**+ * Pin to web3.storage via HTTP API.+ * @param {Buffer} data+ * @param {string} token+ * @returns {Promise<string>} CID+ */+async function pinToWeb3Storage(data, token) {+ // web3.storage expects car format; for now use direct multipart upload+ const res = await fetch('https://api.web3.storage/upload', {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${token}`,+ },+ body: data,+ });++ if (!res.ok) {+ const text = await res.text().catch(() => res.status);+ throw new Error(`web3.storage upload failed (${res.status}): ${text}`);+ }++ const result = await res.json();+ if (!result.cid) throw new Error('web3.storage returned no CID');+ return result.cid;+}diff --git a/api/artifact.js b/api/artifact.jsnew file mode 100644index 000000000..32cf6355f--- /dev/null+++ b/api/artifact.js@@ -0,0 +1,156 @@+// GET /api/artifact?agent=<agentId> — self-contained HTML for Claude.ai artifacts+// GET /api/artifact?model=<glbUrl> — viewer-only (no agent overlay)+//+// Returns text/html, not JSON. res.end(html) is intentional here — the "no res.end"+// rule in CLAUDE.md applies to JSON responses; HTML documents are returned raw.++import { sql } from './_lib/db.js';+import { error, wrap } from './_lib/http.js';+import { limits, clientIp } from './_lib/rate-limit.js';+import { env } from './_lib/env.js';++const AGENT_ID_RE = /^[a-z0-9_-]{3,64}$/i;++// Whitelisted origins for ?model= URLs (must be https, must match one of these)+const ALLOWED_MODEL_ORIGINS = [+ /^https:\/\/[^/]+\.r2\.cloudflarestorage\.com$/,+ /^https:\/\/[^/]+\.amazonaws\.com$/,+ /^https:\/\/[^/]+\.cloudfront\.net$/,+ /^https:\/\/storage\.googleapis\.com$/,+ /^https:\/\/[^/]+\.blob\.core\.windows\.net$/,+ /^https:\/\/3dagent\.vercel\.app$/,+ /^https:\/\/[^/]+\.vercel\.app$/,+];++const CSP = [+ "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 *',+].join('; ');++function validateModelUrl(raw) {+ let url;+ try {+ url = new URL(raw);+ } catch {+ return null;+ }+ if (url.protocol !== 'https:') return null;+ const origin = url.origin;+ if (!ALLOWED_MODEL_ORIGINS.some((pat) => pat.test(origin))) return null;+ return url.toString();+}++function buildHtml({ title, element, appOrigin }) {+ return `<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width,initial-scale=1">+ <title>${title}</title>+ <style>html,body{margin:0;height:100%;background:#080814;}agent-3d{display:block;width:100%;height:100%}</style>+ </head>+ <body>+ ${element}+ <script src="${appOrigin}/dist-lib/agent-3d.umd.cjs"></script>+ </body>+</html>`;+}++export default wrap(async (req, res) => {+ if (req.method !== 'GET' && req.method !== 'HEAD') {+ res.setHeader('allow', 'GET, HEAD');+ return error(res, 405, 'method_not_allowed', 'method not allowed');+ }++ const ip = clientIp(req);+ const rl = await limits.widgetRead(ip);+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const params = new URL(req.url, 'http://x').searchParams;+ const agentId = params.get('agent');+ const modelUrl = params.get('model');+ const theme = params.get('theme') === 'light' ? 'light' : 'dark';+ const idle = params.get('idle') || '';+ const bg = params.get('bg') || '';++ const appOrigin = env.APP_ORIGIN;++ let html;++ if (agentId !== null) {+ if (!AGENT_ID_RE.test(agentId)) {+ return error(+ res,+ 400,+ 'invalid_request',+ 'agent id must be 3–64 alphanumeric/hyphen/underscore chars',+ );+ }++ const [row] = await sql`+ SELECT id, name FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL+ `;+ if (!row) return error(res, 404, 'not_found', 'agent not found');++ const attrs = [+ `agent="${escAttr(row.id)}"`,+ 'eager',+ theme === 'light' ? 'theme="light"' : '',+ idle ? `idle="${escAttr(idle)}"` : '',+ bg ? `bg="${escAttr(bg)}"` : '',+ ]+ .filter(Boolean)+ .join(' ');++ html = buildHtml({+ title: `${row.name} — 3D Agent`,+ element: `<agent-3d ${attrs}></agent-3d>`,+ appOrigin,+ });+ } else if (modelUrl !== null) {+ const safeUrl = validateModelUrl(modelUrl);+ if (!safeUrl) {+ return error(+ res,+ 400,+ 'invalid_request',+ 'model must be an https URL from a whitelisted origin',+ );+ }++ const attrs = [+ `src="${escAttr(safeUrl)}"`,+ theme === 'light' ? 'theme="light"' : '',+ bg ? `bg="${escAttr(bg)}"` : '',+ ]+ .filter(Boolean)+ .join(' ');++ html = buildHtml({+ title: '3D Agent Viewer',+ element: `<agent-3d ${attrs}></agent-3d>`,+ appOrigin,+ });+ } else {+ return error(res, 400, 'invalid_request', 'provide ?agent=<id> or ?model=<url>');+ }++ res.statusCode = 200;+ res.setHeader('content-type', 'text/html; charset=utf-8');+ res.setHeader('content-security-policy', CSP);+ res.setHeader('cache-control', 'public, max-age=60, s-maxage=60, stale-while-revalidate=3600');+ res.setHeader('x-frame-options', 'ALLOWALL');+ res.end(html);+});++function escAttr(s) {+ return String(s)+ .replace(/&/g, '&')+ .replace(/"/g, '"')+ .replace(/</g, '<')+ .replace(/>/g, '>');+}diff --git a/api/auth/privy/verify.js b/api/auth/privy/verify.jsnew file mode 100644index 000000000..d42d613ce--- /dev/null+++ b/api/auth/privy/verify.js@@ -0,0 +1,126 @@+// Verify a Privy identity token and issue a 3D-Agent session.+// POST /api/auth/privy/verify — accepts { idToken }, returns session cookie + user + wallet.++import { z } from 'zod';+import { sql } from '../../_lib/db.js';+import { createSession, sessionCookie, destroySession } from '../../_lib/auth.js';+import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';+import { limits, clientIp } from '../../_lib/rate-limit.js';+import { parse } from '../../_lib/validate.js';+import { verifyPrivyIdToken } from '../../_lib/privy.js';++const bodySchema = z.object({+ idToken: z.string().min(10).max(5000),+});++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const ip = clientIp(req);+ const rl = await limits.authIp(ip);+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many attempts');++ const body = parse(bodySchema, await readJson(req));++ // 1. Verify the Privy identity token.+ let privyData;+ try {+ privyData = await verifyPrivyIdToken(body.idToken);+ } catch (err) {+ const msg = err.message || String(err);+ // Distinguish between bad token format, expired, and signature failures.+ if (msg.includes('expired') || msg.includes('JWT expired')) {+ return error(res, 401, 'expired_token', 'token expired');+ }+ if (msg.includes('audience')) {+ return error(res, 401, 'wrong_audience', 'token audience mismatch');+ }+ if (msg.includes('JWKS') || msg.includes('fetch')) {+ // JWKS fetch failure is a server error, not a client token error.+ throw err;+ }+ return error(res, 401, 'invalid_token', 'token verification failed');+ }++ // 2. Privy token must have a linked wallet.+ if (!privyData.walletAddress) {+ return error(res, 400, 'no_wallet_linked', 'Privy account has no linked wallet');+ }++ // 3. Check that user_wallets.privy_user_id column exists (idempotent migration check).+ let hasPrivyUserIdColumn;+ try {+ const [row] = await sql`+ select exists(+ select 1 from information_schema.columns+ where table_name = 'user_wallets' and column_name = 'privy_user_id'+ ) as exists+ `;+ hasPrivyUserIdColumn = row.exists;+ } catch {+ hasPrivyUserIdColumn = false;+ }++ if (!hasPrivyUserIdColumn) {+ return error(res, 501, 'schema_migration_required', 'user_wallets.privy_user_id column missing');+ }++ // 4. Find or create the user and wallet.+ const addrLower = privyData.walletAddress.toLowerCase();+ const privyUserId = privyData.userId;++ let [wallet] = await sql`+ select user_id from user_wallets where address = ${addrLower} limit 1+ `;+ let userId;++ if (wallet) {+ userId = wallet.user_id;+ // Update last_used_at and privy_user_id if changed.+ await sql`+ update user_wallets+ set last_used_at = now(), privy_user_id = ${privyUserId}+ where address = ${addrLower}+ `;+ } else {+ // Create a new user. Use Privy email if available; otherwise synthesize one.+ const userEmail = privyData.email || `wallet-${addrLower}@privy.local`;+ const [user] = await sql`+ insert into users (email, display_name, wallet_address)+ values (${userEmail}, ${shortAddr(privyData.walletAddress)}, ${addrLower})+ returning id+ `;+ userId = user.id;++ // Link the wallet with privy_user_id.+ await sql`+ insert into user_wallets (user_id, address, chain_id, is_primary, privy_user_id)+ values (${userId}, ${addrLower}, null, true, ${privyUserId})+ `;+ }++ // 5. Issue a session.+ await destroySession(req);+ const token = await createSession({+ userId,+ userAgent: req.headers['user-agent'],+ ip,+ });+ res.setHeader('set-cookie', sessionCookie(token));++ // 6. Return user + wallet info.+ const [userRow] = await sql`+ select id, email, display_name, plan, avatar_url, created_at+ from users where id = ${userId} limit 1+ `;++ return json(res, 200, {+ user: userRow,+ wallet: { address: privyData.walletAddress, chain_id: null },+ });+});++function shortAddr(addr) {+ return `${addr.slice(0, 6)}…${addr.slice(-4)}`;+}diff --git a/api/auth/sessions/[id].js b/api/auth/sessions/[id].jsnew file mode 100644index 000000000..ca2532531--- /dev/null+++ b/api/auth/sessions/[id].js@@ -0,0 +1,28 @@+import { sql } from '../../_lib/db.js';+import { getSessionUser } from '../../_lib/auth.js';+import { cors, json, method, wrap, error } from '../../_lib/http.js';++const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'DELETE,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['DELETE'])) return;++ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthenticated', 'not signed in');++ const sessionId = req.query.id || req.url.split('/').pop();+ if (!UUID_REGEX.test(sessionId))+ return error(res, 400, 'invalid_id', 'session id must be a valid UUID');++ const rows = await sql`+ select id from sessions+ where id = ${sessionId} and user_id = ${user.id}+ limit 1+ `;++ if (!rows[0]) return error(res, 404, 'not_found', 'session not found');++ await sql`update sessions set revoked_at = now() where id = ${sessionId}`;+ return json(res, 200, { revoked: 1 });+});diff --git a/api/auth/sessions/index.js b/api/auth/sessions/index.jsnew file mode 100644index 000000000..fcc8bc962--- /dev/null+++ b/api/auth/sessions/index.js@@ -0,0 +1,36 @@+import { sql } from '../../_lib/db.js';+import { getSessionUser } from '../../_lib/auth.js';+import { cors, json, method, wrap, error } from '../../_lib/http.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,DELETE,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'DELETE'])) return;++ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthenticated', 'not signed in');++ if (req.method === 'GET') {+ const currentSessionId = user.sid;+ const rows = await sql`+ select id, user_agent, ip, created_at, last_seen_at+ from sessions+ where user_id = ${user.id} and revoked_at is null+ order by last_seen_at desc+ `;+ const sessions = rows.map((s) => ({+ ...s,+ current: s.id === currentSessionId,+ }));+ return json(res, 200, { sessions });+ }++ if (req.method === 'DELETE') {+ const currentSessionId = user.sid;+ const result = await sql`+ update sessions+ set revoked_at = now()+ where user_id = ${user.id} and revoked_at is null and id != ${currentSessionId}+ `;+ return json(res, 200, { revoked: result.count });+ }+});diff --git a/api/auth/siwe/nonce.js b/api/auth/siwe/nonce.jsindex 98ec84461..43c40c23f 100644--- a/api/auth/siwe/nonce.js+++ b/api/auth/siwe/nonce.js@@ -5,8 +5,11 @@ import { sql } from '../../_lib/db.js';import { cors, json, method, wrap, error } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { randomToken } from '../../_lib/crypto.js';+import { hmacSha256 } from '../../_lib/crypto.js';+import { env } from '../../_lib/env.js';const NONCE_TTL_SEC = 5 * 60;+const CSRF_COOKIE = '__Host-csrf-siwe';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;@@ -17,16 +20,25 @@ export default wrap(async (req, res) => {if (!rl.success) return error(res, 429, 'rate_limited', 'too many nonce requests');// EIP-4361 requires ≥8 alphanumeric chars. Strip base64url's - and _.+ // 22 chars ≈ 131 bits of entropy (log2(62^22) ≈ 131).let nonce = '';- while (nonce.length < 16) {+ while (nonce.length < 22) {nonce += randomToken(24).replace(/[^A-Za-z0-9]/g, '');}- nonce = nonce.slice(0, 16);+ nonce = nonce.slice(0, 22);await sql`insert into siwe_nonces (nonce, expires_at)values (${nonce}, now() + ${`${NONCE_TTL_SEC} seconds`}::interval)`;- return json(res, 200, { nonce, ttl: NONCE_TTL_SEC });+ // 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}`);++ const issuedAt = new Date().toISOString();+ const expiresAt = new Date(Date.now() + NONCE_TTL_SEC * 1000).toISOString();++ return json(res, 200, { nonce, issuedAt, expiresAt, csrf, ttl: NONCE_TTL_SEC });});diff --git a/api/auth/siwe/verify.js b/api/auth/siwe/verify.jsindex b99599c1f..f6cb85ab0 100644--- a/api/auth/siwe/verify.js+++ b/api/auth/siwe/verify.js@@ -9,16 +9,33 @@ import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';import { limits, clientIp } from '../../_lib/rate-limit.js';import { env } from '../../_lib/env.js';import { parse } from '../../_lib/validate.js';+import { hmacSha256, constantTimeEquals } from '../../_lib/crypto.js';const verifyBody = z.object({message: z.string().min(64).max(4000),signature: z.string().regex(/^0x[a-fA-F0-9]+$/),});+const CSRF_COOKIE = '__Host-csrf-siwe';+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;+ // Verify CSRF token before processing the request.+ const csrfHeader = req.headers['x-csrf-token'];+ if (!csrfHeader) return error(res, 403, 'invalid_request', 'CSRF check failed');++ const cookie = req.headers.cookie || '';+ const csrfMatch = cookie.match(/(?:^|;\s*)__Host-csrf-siwe=([^;]+)/);+ const csrfCookie = csrfMatch ? decodeURIComponent(csrfMatch[1]) : null;+ if (!csrfCookie) return error(res, 403, 'invalid_request', 'CSRF check failed');++ const expectedCsrf = await hmacSha256(env.JWT_SECRET, `csrf-siwe:${csrfCookie}`);+ if (!constantTimeEquals(expectedCsrf, String(csrfHeader))) {+ return error(res, 403, 'invalid_request', 'CSRF check failed');+ }+const ip = clientIp(req);const rl = await limits.authIp(ip);if (!rl.success) return error(res, 429, 'rate_limited', 'too many attempts');diff --git a/api/auth/wallets/[address].js b/api/auth/wallets/[address].jsnew file mode 100644index 000000000..805e28f6f--- /dev/null+++ b/api/auth/wallets/[address].js@@ -0,0 +1,54 @@+// Unlink a wallet from authenticated user.+// Refuse if it's the only wallet AND user has no email+password.++import { sql } from '../../_lib/db.js';+import { getSessionUser } from '../../_lib/auth.js';+import { cors, json, method, wrap, error } from '../../_lib/http.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'DELETE,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['DELETE'])) return;++ const session = await getSessionUser(req);+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');++ const { address } = req.query;+ if (!address) return error(res, 400, 'missing_address', 'address required');++ const addrLower = address.toLowerCase();++ // 1. Check that this wallet belongs to the user.+ const [wallet] = await sql`+ select id from user_wallets+ where user_id = ${session.id} and address = ${addrLower}+ limit 1+ `;+ if (!wallet) return error(res, 404, 'not_found', 'wallet not found');++ // 2. Check if this is the only wallet.+ const [count] = await sql`+ select count(*) as n from user_wallets+ where user_id = ${session.id}+ `;+ const walletCount = count.n;++ if (walletCount === 1) {+ // 3. If only wallet, check if user has password-based auth.+ const [user] = await sql`+ select password_hash from users where id = ${session.id} limit 1+ `;+ if (!user.password_hash) {+ return error(+ res,+ 400,+ 'cannot_remove_last_wallet',+ 'cannot remove the last wallet if account has no password',+ );+ }+ }++ // 4. Delete the wallet.+ await sql`delete from user_wallets where user_id = ${session.id} and address = ${addrLower}`;++ return json(res, 200, { removed: true });+});diff --git a/api/auth/wallets/_link-nonces.js b/api/auth/wallets/_link-nonces.jsnew file mode 100644index 000000000..2f3ecbf6e--- /dev/null+++ b/api/auth/wallets/_link-nonces.js@@ -0,0 +1,35 @@+// In-memory nonce store for wallet linking. Separate from login nonces.+// Used by nonce.js (issuer) and index.js (validator).++import { randomToken } from '../_lib/crypto.js';++export const NONCE_TTL_SEC = 5 * 60;+const nonceStore = new Map();++// Cleanup expired nonces every 30 seconds.+setInterval(() => {+ const now = Date.now();+ for (const [nonce, data] of nonceStore) {+ if (now - data.issuedAt > NONCE_TTL_SEC * 1000) {+ nonceStore.delete(nonce);+ }+ }+}, 30_000);++export function issueNonce(userId) {+ let nonce = '';+ while (nonce.length < 16) {+ nonce += randomToken(24).replace(/[^A-Za-z0-9]/g, '');+ }+ nonce = nonce.slice(0, 16);+ nonceStore.set(nonce, { userId, issuedAt: Date.now() });+ return nonce;+}++export function consumeNonce(nonce, userId) {+ const data = nonceStore.get(nonce);+ if (!data) return null;+ if (data.userId !== userId) return null;+ nonceStore.delete(nonce);+ return data;+}diff --git a/api/auth/wallets/index.js b/api/auth/wallets/index.jsnew file mode 100644index 000000000..1731d2588--- /dev/null+++ b/api/auth/wallets/index.js@@ -0,0 +1,109 @@+// Link new wallets to authenticated user + list existing wallets.++import { verifyMessage, getAddress } from 'ethers';+import { z } from 'zod';+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 { consumeNonce } from './_link-nonces.js';++const linkBody = z.object({+ address: z.string().regex(/^0x[a-fA-F0-9]{40}$/i),+ message: z.string().min(64).max(4000),+ signature: z.string().regex(/^0x[a-fA-F0-9]+$/),+ nonce: z.string().min(8).max(32),+});++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;++ const session = await getSessionUser(req);+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');++ if (req.method === 'GET') {+ return handleListWallets(session.id, res);+ } else if (req.method === 'POST') {+ return handleLinkWallet(session.id, req, res);+ } else if (!method(req, res, ['GET', 'POST'])) return;+});++async function handleListWallets(userId, res) {+ const rows = await sql`+ select address, chain_id, created_at, is_primary+ from user_wallets+ where user_id = ${userId}+ order by created_at asc+ `;++ return json(res, 200, {+ wallets: rows.map((w) => ({+ address: w.address,+ chain_id: w.chain_id,+ created_at: w.created_at,+ is_primary: w.is_primary,+ })),+ });+}++async function handleLinkWallet(userId, req, res) {+ const body = parse(linkBody, await readJson(req));++ // 1. Verify nonce exists and is not expired.+ const nonceData = consumeNonce(body.nonce, userId);+ if (!nonceData) {+ return error(res, 400, 'invalid_nonce', 'unknown, expired, or invalid nonce');+ }++ // 2. Verify signature recovers the claimed address.+ let recovered;+ try {+ recovered = verifyMessage(body.message, body.signature);+ } catch {+ return error(res, 401, 'invalid_signature', 'signature verification failed');+ }++ let claimed;+ try {+ claimed = getAddress(body.address);+ } catch {+ return error(res, 400, 'invalid_address', 'address not checksummed correctly');+ }++ if (recovered.toLowerCase() !== claimed.toLowerCase()) {+ return error(res, 401, 'invalid_signature', 'signer does not match address');+ }++ const addrLower = claimed.toLowerCase();++ // 3. Check if this address is already linked to this user (idempotent).+ const existing = await sql`+ select id from user_wallets+ where user_id = ${userId} and address = ${addrLower}+ `;+ if (existing.length > 0) {+ return json(res, 200, { wallet: { address: claimed, chain_id: null } });+ }++ // 4. Check if this address is already linked to a different user.+ const conflict = await sql`+ select user_id from user_wallets+ where address = ${addrLower}+ `;+ if (conflict.length > 0) {+ return error(+ res,+ 409,+ 'address_in_use',+ 'this address is already linked to another account',+ );+ }++ // 5. Insert the new wallet.+ await sql`+ insert into user_wallets (user_id, address, chain_id, is_primary)+ values (${userId}, ${addrLower}, null, false)+ `;++ return json(res, 201, { wallet: { address: claimed, chain_id: null } });+}diff --git a/api/auth/wallets/nonce.js b/api/auth/wallets/nonce.jsnew file mode 100644index 000000000..e481dc6a9--- /dev/null+++ b/api/auth/wallets/nonce.js@@ -0,0 +1,33 @@+// Issue a nonce for wallet linking (authenticated user only).+// Different from login nonce: caller is already authenticated.++import { getSessionUser } from '../../_lib/auth.js';+import { cors, json, method, wrap, error } from '../../_lib/http.js';+import { issueNonce, NONCE_TTL_SEC } from './_link-nonces.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const session = await getSessionUser(req);+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');++ const nonce = issueNonce(session.id);++ // Generate SIWE-like message for signing.+ const message = [+ `3D Agent wants you to sign in with your Ethereum account:`,+ `Address to link (will be filled by wallet):`,+ ``,+ `Link this wallet to 3D Agent account ${session.email}`,+ ``,+ `URI: ${process.env.APP_ORIGIN || 'https://3dagent.vercel.app'}`,+ `Version: 1`,+ `Chain ID: (will be set by wallet)`,+ `Nonce: ${nonce}`,+ `Issued At: ${new Date().toISOString()}`,+ `Expiration Time: ${new Date(Date.now() + NONCE_TTL_SEC * 1000).toISOString()}`,+ ].join('\n');++ return json(res, 200, { nonce, message, ttl: NONCE_TTL_SEC });+});diff --git a/api/avatars/REGENERATE.md b/api/avatars/REGENERATE.mdnew file mode 100644index 000000000..8ea85e7e6--- /dev/null+++ b/api/avatars/REGENERATE.md@@ -0,0 +1,184 @@+# Avatar Regeneration API++Pluggable endpoint for avatar re-mesh, re-texture, re-rig, and restyle operations. Designed to support multiple ML backends with a consistent interface.++## Endpoints++### `POST /api/avatars/regenerate`++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"+ }+}+```++**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+}+```++**Error responses:**++- **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."+ }+ ```+- **429 rate_limited** — user has exceeded upload quota++### `GET /api/avatars/regenerate-status?jobId=<id>`++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"+}+```++**Status values:**+- `queued` — job waiting for processing+- `running` — actively processing+- `done` — completed successfully+- `failed` — failed (check `error` field)++## Provider Plug Shape++Providers are swapped via the `AVATAR_REGEN_PROVIDER` env var (e.g., `meshy`, `csm`, `rodin`, `tripor`, `stub`).++### Provider function signature++```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://...' };+ },+ };+}+```++### 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)++## Candidate providers++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. |++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.++## Environment++Add to `.env.local` or Vercel settings:++```+# Avatar regeneration provider. Set to "stub" for testing, or a provider name.+# Unset → returns 501 regen_unconfigured.+AVATAR_REGEN_PROVIDER=stub+```++## Database schema (future migration)++The stub provider and status endpoint assume a `avatar_regen_jobs` table:++```sql+create table avatar_regen_jobs (+ job_id text primary key,+ user_id uuid not null,+ source_avatar_id uuid not null,+ mode text not null, -- remesh | retex | rerig | restyle+ params jsonb,+ status text not null, -- queued | running | done | failed+ result_avatar_id uuid,+ error text,+ created_at timestamp default now(),+ updated_at timestamp default now(),+ foreign key (user_id) references users(id),+ foreign key (source_avatar_id) references avatars(id),+ foreign key (result_avatar_id) references avatars(id)+);++create index on avatar_regen_jobs(user_id);+create index on avatar_regen_jobs(job_id, user_id);+```++This table is not required if using an external provider (e.g., Meshy) for job tracking.diff --git a/api/avatars/index.js b/api/avatars/index.jsindex 4a8a978b1..9cb79dc60 100644--- a/api/avatars/index.js+++ b/api/avatars/index.js@@ -109,6 +109,26 @@ async function handleCreate(req, res) {`;}+ // Auto-link selfie-derived avatars to the user's primary agent if it has no avatar yet.+ // Fire-and-forget — if this UPDATE fails, the 201 still returns.+ if ((body.source === 'selfie' || body.source === 'avaturn') && auth.source === 'session') {+ queueMicrotask(async () => {+ try {+ await sql`+ update agent_identities+ set avatar_id = ${avatar.id}+ where user_id = ${auth.userId}+ and avatar_id is null+ and deleted_at is null+ order by created_at asc+ limit 1+ `;+ } catch {+ // Log and ignore — don't block the response.+ }+ });+ }+recordEvent({userId: auth.userId,apiKeyId: auth.apiKeyId,diff --git a/api/avatars/regenerate-status.js b/api/avatars/regenerate-status.jsnew file mode 100644index 000000000..c1f66cbb9--- /dev/null+++ b/api/avatars/regenerate-status.js@@ -0,0 +1,52 @@+// GET /api/avatars/regenerate-status?jobId=<id> — poll job status++import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';+import { cors, json, method, wrap, error } from '../_lib/http.js';+import { sql } from '../_lib/db.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ // Auth: session OR bearer+ const session = await getSessionUser(req);+ const bearer = session ? null : await authenticateBearer(extractBearer(req));+ if (!session && !bearer)+ return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');+ if (bearer && !hasScope(bearer.scope, 'avatars:read')) {+ return error(res, 403, 'insufficient_scope', 'avatars:read scope required');+ }+ const userId = session?.id ?? bearer?.userId;++ const url = new URL(req.url, 'http://x');+ const jobId = url.searchParams.get('jobId');+ if (!jobId) return error(res, 400, 'invalid_request', 'jobId required');++ // Fetch job status — must be owned by the authenticated user+ const rows = await sql`+ select job_id, status, result_avatar_id, error, created_at+ from avatar_regen_jobs+ where job_id = ${jobId} and user_id = ${userId}+ limit 1+ `;++ if (!rows[0]) {+ return error(res, 404, 'not_found', 'job not found');+ }++ const job = rows[0];+ const response = {+ ok: true,+ jobId: job.job_id,+ status: job.status,+ };++ if (job.result_avatar_id) {+ response.resultAvatarId = job.result_avatar_id;+ }+ if (job.error) {+ response.error = job.error;+ }++ return json(res, 200, response);+});diff --git a/api/avatars/regenerate.js b/api/avatars/regenerate.jsnew file mode 100644index 000000000..470130d71--- /dev/null+++ b/api/avatars/regenerate.js@@ -0,0 +1,81 @@+// POST /api/avatars/regenerate — initiate avatar regeneration+// Pluggable provider architecture. Currently returns 501 until provider is configured.++import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { sql } from '../_lib/db.js';+import { env } from '../_lib/env.js';+import { parse } from '../_lib/validate.js';+import { z } from 'zod';+import { randomUUID } from 'crypto';++const regenerateSchema = z.object({+ sourceAvatarId: z.string().trim().min(1).max(100),+ mode: z.enum(['remesh', 'retex', 'rerig', 'restyle']),+ params: z.record(z.unknown()).optional(),+});++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ // Auth: session OR bearer+ const session = await getSessionUser(req);+ const bearer = session ? null : await authenticateBearer(extractBearer(req));+ if (!session && !bearer)+ return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');+ if (bearer && !hasScope(bearer.scope, 'avatars:write')) {+ return error(res, 403, 'insufficient_scope', 'avatars:write scope required');+ }+ const userId = session?.id ?? bearer?.userId;++ // Rate limit+ const rl = await limits.upload(userId);+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const body = parse(regenerateSchema, await readJson(req));++ // Verify source avatar exists and is owned by this user+ const rows = await sql`+ select id, name, storage_key from avatars+ where id = ${body.sourceAvatarId} and owner_id = ${userId} and deleted_at is null+ limit 1+ `;+ if (!rows[0]) {+ return error(res, 404, 'not_found', 'source avatar not found or not owned');+ }+ const sourceAvatar = rows[0];++ // Check if provider is configured+ const provider = (env.AVATAR_REGEN_PROVIDER || 'none').trim().toLowerCase();++ if (provider === 'none' || !provider) {+ return error(+ res,+ 501,+ 'regen_unconfigured',+ 'Avatar regeneration is not yet wired to an ML backend. Set AVATAR_REGEN_PROVIDER env var.',+ );+ }++ // Provider stub — always return success with deterministic fake job+ if (provider === 'stub') {+ const jobId = `stub-${randomUUID()}`;+ // In a real implementation, this would queue the job with the ML provider+ // and store metadata in a `avatar_regen_jobs` table.+ await sql`+ insert into avatar_regen_jobs (job_id, user_id, source_avatar_id, mode, params, status, created_at)+ values (${jobId}, ${userId}, ${body.sourceAvatarId}, ${body.mode}, ${JSON.stringify(body.params ?? {})}, 'queued', now())+ `;+ return json(res, 202, {+ ok: true,+ jobId,+ status: 'queued',+ eta: null,+ });+ }++ // Unknown provider — return error+ return error(res, 501, 'regen_provider_error', `Unknown provider: ${provider}`);+});diff --git a/api/config.js b/api/config.jsindex 760da56b4..6d10b7fd3 100644--- a/api/config.js+++ b/api/config.js@@ -10,5 +10,6 @@ export default wrap(async (req, res) => {return json(res, 200, {privyAppId: process.env.PRIVY_APP_ID || '',+ walletConnectProjectId: process.env.VITE_WALLETCONNECT_PROJECT_ID || '',});});diff --git a/api/erc8004/hydrate.js b/api/erc8004/hydrate.jsnew file mode 100644index 000000000..b1325335e--- /dev/null+++ b/api/erc8004/hydrate.js@@ -0,0 +1,68 @@+/**+ * GET /api/erc8004/hydrate+ * Fetch all on-chain agents owned by the user's linked wallets.+ * Returns list of discovered agents with alreadyImported flag.+ */++import { sql } from '../_lib/db.js';+import { getSessionUser } from '../_lib/auth.js';+import { cors, json, method, wrap, error } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const session = await getSessionUser(req);+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');++ const ip = clientIp(req);+ const rl = await limits.authIp(ip);+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ // Get user's linked wallets.+ const wallets = await sql`+ SELECT address FROM user_wallets+ WHERE user_id = ${session.id}+ `;++ if (wallets.length === 0) {+ return json(res, 200, { agents: [] });+ }++ const walletAddresses = wallets.map((w) => w.address.toLowerCase());++ // Query erc8004_agents_index for agents owned by these wallets.+ const indexRows = await sql`+ SELECT chain_id, agent_id, owner, name, description, image, glb_url+ FROM erc8004_agents_index+ WHERE lower(owner) = ANY(${walletAddresses})+ AND active = true+ ORDER BY registered_at DESC NULLS LAST+ `;++ // For each index row, check if already imported by this user.+ const agents = [];+ for (const row of indexRows) {+ const [imported] = await sql`+ SELECT id FROM agent_identities+ WHERE user_id = ${session.id}+ AND erc8004_agent_id = ${BigInt(row.agent_id)}+ AND chain_id = ${row.chain_id}+ AND deleted_at IS NULL+ `;++ agents.push({+ chainId: row.chain_id,+ agentId: row.agent_id,+ name: row.name || `Agent #${row.agent_id}`,+ description: row.description || '',+ image: row.image || null,+ glbUrl: row.glb_url || null,+ owner: row.owner,+ alreadyImported: !!imported,+ });+ }++ return json(res, 200, { agents });+});diff --git a/api/erc8004/import.js b/api/erc8004/import.jsnew file mode 100644index 000000000..5ce62b7a9--- /dev/null+++ b/api/erc8004/import.js@@ -0,0 +1,121 @@+/**+ * POST /api/erc8004/import+ * Import an on-chain agent for the authenticated user.+ * Creates a local agent_identities row pointing at the on-chain record.+ * Idempotent: 409 if already imported for this user.+ */++import { sql } from '../_lib/db.js';+import { getSessionUser } from '../_lib/auth.js';+import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';+import { parse } from '../_lib/validate.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { resolveOnChainAgent, SERVER_CHAIN_META } from '../_lib/onchain.js';+import { z } from 'zod';++const bodySchema = z.object({+ chainId: z.number().int().positive(),+ agentId: z.union([z.string(), z.number()]),+});++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const session = await getSessionUser(req);+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');++ const ip = clientIp(req);+ const rl = await limits.authIp(ip);+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const body = parse(bodySchema, await readJson(req));+ const chainMeta = SERVER_CHAIN_META[body.chainId];+ if (!chainMeta) {+ return error(res, 400, 'bad_request', `unsupported chain ${body.chainId}`);+ }++ const agentId = String(body.agentId);++ // Check if already imported by this user.+ const [existing] = await sql`+ SELECT id FROM agent_identities+ WHERE user_id = ${session.id}+ AND erc8004_agent_id = ${BigInt(agentId)}+ AND chain_id = ${body.chainId}+ AND deleted_at IS NULL+ `;++ if (existing) {+ return error(res, 409, 'conflict', 'agent already imported for this user');+ }++ // Look up the index row.+ const [indexRow] = await sql`+ SELECT owner, agent_uri FROM erc8004_agents_index+ WHERE chain_id = ${body.chainId} AND agent_id = ${agentId}+ `;++ if (!indexRow) {+ return error(res, 404, 'not_found', 'agent not found in index');+ }++ // Verify owner matches one of user's wallets.+ const wallets = await sql`+ SELECT address FROM user_wallets WHERE user_id = ${session.id}+ `;++ const userWallets = wallets.map((w) => w.address.toLowerCase());+ if (!userWallets.includes(indexRow.owner.toLowerCase())) {+ return error(res, 403, 'forbidden', 'you do not own this agent');+ }++ // Resolve on-chain agent metadata.+ let resolved;+ try {+ resolved = await resolveOnChainAgent({+ chainId: body.chainId,+ agentId,+ fetchManifest: true,+ timeoutMs: 5000,+ });+ } catch (err) {+ return error(res, 500, 'internal', `failed to resolve agent: ${err.message}`);+ }++ if (resolved.error) {+ return error(res, 400, 'bad_request', `failed to resolve agent: ${resolved.error}`);+ }++ const name = (resolved.name || `Agent #${agentId}`).slice(0, 255);+ const description = (resolved.description || '').slice(0, 1000);++ // Insert agent_identities row.+ const [inserted] = await sql`+ INSERT INTO agent_identities (+ user_id, name, description, avatar_id,+ chain_id, erc8004_agent_id, erc8004_registry, registration_cid+ )+ VALUES (+ ${session.id},+ ${name},+ ${description},+ null,+ ${body.chainId},+ ${BigInt(agentId)},+ ${chainMeta.registry},+ null+ )+ RETURNING id+ `;++ return json(res, 201, {+ agent: {+ id: inserted.id,+ erc8004_agent_id: agentId,+ erc8004_agent_id_chain_id: body.chainId,+ name,+ avatar_url: resolved.image,+ },+ });+});diff --git a/api/erc8004/pin.js b/api/erc8004/pin.jsindex 25b972543..553abfe33 100644--- a/api/erc8004/pin.js+++ b/api/erc8004/pin.js@@ -2,6 +2,7 @@ import { PutObjectCommand } from '@aws-sdk/client-s3';import { r2, publicUrl } from '../_lib/r2.js';import { cors, error, json, wrap } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';+import { getSessionUser } from '../_lib/auth.js';import { env } from '../_lib/env.js';const ALLOWED = new Set([@@ -9,28 +10,48 @@ const ALLOWED = new Set(['model/gltf+json','application/json','application/octet-stream',+ 'image/png',+ 'image/jpeg',+ 'image/webp',]);-const MAX_GLB = 100 * 1024 * 1024; // 100 MB-const MAX_JSON = 1024 * 1024; // 1 MB+const MAX_SIZE = 25 * 1024 * 1024; // 25 MBexport default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (req.method !== 'POST') return error(res, 405, 'method_not_allowed', 'POST only');+ const session = await getSessionUser(req);+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');+const ip = clientIp(req);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_type', 'unsupported content-type');+ if (!ALLOWED.has(ct)) return error(res, 415, 'unsupported_media_type', 'unsupported content-type');- const isJson = ct === 'application/json';- const ext = isJson ? 'json' : 'glb';- const body = await readRaw(req, isJson ? MAX_JSON : MAX_GLB);+ const body = await readRaw(req, MAX_SIZE);- const key = `erc8004/${Date.now()}-${Math.random().toString(36).slice(2)}.${ext}`;+ // Determine extension from content-type+ const ext = getExt(ct);++ // Try IPFS first (web3.storage or nft.storage)+ const web3Token = process.env.WEB3_STORAGE_TOKEN;+ const nftToken = process.env.NFT_STORAGE_TOKEN;++ if (web3Token) {+ const result = await uploadToWeb3Storage(web3Token, ext, body, ct);+ return json(res, 200, result);+ }+ if (nftToken) {+ const result = await uploadToNftStorage(nftToken, ext, body, ct);+ return json(res, 200, result);+ }++ // 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,@@ -38,9 +59,83 @@ export default wrap(async (req, res) => {ContentType: ct,}));- return json(res, 200, { url: publicUrl(key) });+ const url = publicUrl(key);+ return json(res, 200, {+ cid: null,+ uri: url,+ url,+ warning: 'R2-only pin — not decentralized',+ });});+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';+ }+}++async function uploadToWeb3Storage(token, ext, body, ct) {+ const filename = `${Date.now()}-${Math.random().toString(36).slice(2)}.${ext}`;+ const formData = new FormData();+ const blob = new Blob([body], { type: ct });+ formData.append('file', blob, filename);++ const response = await fetch('https://api.web3.storage/upload', {+ method: 'POST',+ headers: {+ 'Authorization': `Bearer ${token}`,+ },+ body: formData,+ });++ if (!response.ok) {+ throw new Error(`web3.storage upload failed: ${response.status} ${response.statusText}`);+ }++ const data = await response.json();+ const cid = data.cid;++ // web3.storage and nft.storage guarantee content-addressable uploads:+ // same bytes → same CID every time, idempotent by design.+ const uri = `ipfs://${cid}/${filename}`;+ const url = `https://w3s.link/ipfs/${cid}/${filename}`;++ return { cid, uri, url };+}++async function uploadToNftStorage(token, ext, body, ct) {+ const filename = `${Date.now()}-${Math.random().toString(36).slice(2)}.${ext}`;+ const formData = new FormData();+ const blob = new Blob([body], { type: ct });+ formData.append('file', blob, filename);++ const response = await fetch('https://api.nft.storage/upload', {+ method: 'POST',+ headers: {+ 'Authorization': `Bearer ${token}`,+ },+ body: formData,+ });++ if (!response.ok) {+ throw new Error(`nft.storage upload failed: ${response.status} ${response.statusText}`);+ }++ const data = await response.json();+ const cid = data.value.cid;++ // nft.storage guarantees content-addressable uploads: same bytes → same CID.+ const uri = `ipfs://${cid}/${filename}`;+ const url = `https://w3s.link/ipfs/${cid}/${filename}`;++ return { cid, uri, url };+}+function readRaw(req, limit) {return new Promise((resolve, reject) => {const chunks = [];diff --git a/api/onboarding/link-avatar.js b/api/onboarding/link-avatar.jsnew file mode 100644index 000000000..6605f8c74--- /dev/null+++ b/api/onboarding/link-avatar.js@@ -0,0 +1,65 @@+// POST /api/onboarding/link-avatar — link an avatar to the user's primary agent++import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { sql } from '../_lib/db.js';+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { parse } from '../_lib/validate.js';+import { z } from 'zod';++const bodySchema = z.object({+ avatarId: z.string().uuid(),+ force: z.boolean().default(false),+});++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ // Auth: session OR bearer+ const session = await getSessionUser(req);+ const bearer = session ? null : await authenticateBearer(extractBearer(req));+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');+ const userId = session?.id ?? bearer.userId;++ const body = parse(bodySchema, await readJson(req));++ // Verify the caller owns the avatar.+ const [avatar] = await sql`+ select id from avatars+ where id = ${body.avatarId} and owner_id = ${userId} and deleted_at is null+ limit 1+ `;+ if (!avatar) return error(res, 404, 'not_found', 'avatar not found or not owned by you');++ // Get the user's primary agent (first created).+ const [agent] = await sql`+ select id, avatar_id from agent_identities+ where user_id = ${userId} and deleted_at is null+ order by created_at asc+ limit 1+ `;+ if (!agent) return error(res, 404, 'not_found', 'no agent identity found for user');++ // If the agent already has a different avatar, require force flag.+ if (agent.avatar_id && agent.avatar_id !== body.avatarId && !body.force) {+ return error(+ res,+ 409,+ 'already_linked',+ 'agent already has an avatar; pass force: true to override',+ {+ current_avatar_id: agent.avatar_id,+ },+ );+ }++ // Update the agent's avatar.+ const [updated] = await sql`+ update agent_identities+ set avatar_id = ${body.avatarId}, updated_at = now()+ where id = ${agent.id}+ returning id, avatar_id, updated_at+ `;++ return json(res, 200, { agent: updated });+});diff --git a/contracts/script/DeployValidationMainnet.s.sol b/contracts/script/DeployValidationMainnet.s.solnew file mode 100644index 000000000..fad2f4470--- /dev/null+++ b/contracts/script/DeployValidationMainnet.s.sol@@ -0,0 +1,68 @@+// SPDX-License-Identifier: MIT+pragma solidity ^0.8.24;++import {Script, console} from "forge-std/Script.sol";+import {ValidationRegistry} from "../src/ValidationRegistry.sol";++/// @notice Deploys ValidationRegistry to mainnet chains via CREATE2 (deterministic).+/// All 15 mainnet chains will share the same address via CREATE2.+///+/// Usage (dry-run):+/// forge script script/DeployValidationMainnet.s.sol:DeployValidationMainnet \+/// --rpc-url https://eth.merkle.io \+/// --sender 0x...+///+/// Usage (broadcast):+/// forge script script/DeployValidationMainnet.s.sol:DeployValidationMainnet \+/// --rpc-url https://eth.merkle.io \+/// --sender 0x... \+/// --private-key 0x... \+/// --broadcast --verify --etherscan-api-key $ETHERSCAN_API_KEY+contract DeployValidationMainnet is Script {+ // Canonical IdentityRegistry address (same on all mainnet chains)+ address constant IDENTITY_REGISTRY = 0x8004A169FB4a3325136EB29fA0ceB6D2e539a432;++ // CREATE2 salt for deterministic address across all chains+ bytes32 constant SALT = keccak256(abi.encodePacked("ValidationRegistry", uint256(1)));++ function run() external returns (ValidationRegistry validation) {+ address deployer = msg.sender;++ // Compute and log the expected address before broadcasting+ address predictedAddr = computeAddress(deployer);+ console.log("Expected ValidationRegistry:", predictedAddr);+ console.log("IdentityRegistry: ", IDENTITY_REGISTRY);+ console.log("Deployer (owner): ", deployer);+ console.log("---");++ vm.startBroadcast();++ // Deploy with CREATE2 for deterministic address+ validation = new ValidationRegistry{salt: SALT}(+ IDENTITY_REGISTRY,+ deployer+ );++ vm.stopBroadcast();++ require(address(validation) == predictedAddr, "Address mismatch!");+ console.log("✓ ValidationRegistry deployed at:", address(validation));+ }++ /// @notice Computes the CREATE2 address without deploying.+ /// @param owner The owner address that will be set in the constructor.+ function computeAddress(address owner) public pure returns (address) {+ bytes memory creationCode = type(ValidationRegistry).creationCode;+ bytes memory constructorArgs = abi.encode(IDENTITY_REGISTRY, owner);+ bytes32 codeHash = keccak256(abi.encodePacked(creationCode, constructorArgs));++ return address(uint160(uint256(+ keccak256(abi.encodePacked(+ bytes1(0xff),+ address(this),+ SALT,+ codeHash+ ))+ )));+ }+}diff --git a/dist-artifact/.well-known/agent-card.json b/dist-artifact/.well-known/agent-card.jsonnew file mode 100644index 000000000..4e947a10b--- /dev/null+++ b/dist-artifact/.well-known/agent-card.json@@ -0,0 +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"+ ]+ }+ ]+}diff --git a/dist-artifact/.well-known/agent-registration.json b/dist-artifact/.well-known/agent-registration.jsonnew file mode 100644index 000000000..4bee98074--- /dev/null+++ b/dist-artifact/.well-known/agent-registration.json@@ -0,0 +1,28 @@+{+ "type": "https://eips.ethereum.org/EIPS/eip-8004#registration-v1",+ "name": "3D Agent",+ "description": "AI-powered 3D model viewer and validation agent. Drag and drop glTF, GLB, and 3D files to preview instantly in your browser. Supports real-time rendering, model validation, environment maps, and animation playback via Three.js and WebGL.",+ "image": "https://3dagent.vercel.app/og-image.png",+ "active": true,+ "services": [+ {+ "name": "web",+ "endpoint": "https://3dagent.vercel.app/"+ },+ {+ "name": "A2A",+ "endpoint": "https://3dagent.vercel.app/.well-known/agent-card.json",+ "version": "0.3.0"+ },+ {+ "name": "MCP",+ "endpoint": "https://3dagent.vercel.app/.well-known/openapi.yaml",+ "version": "2025-06-18"+ }+ ],+ "x402Support": false,+ "registrations": [],+ "supportedTrust": [+ "reputation"+ ]+}diff --git a/dist-artifact/.well-known/ai-plugin.json b/dist-artifact/.well-known/ai-plugin.jsonnew file mode 100644index 000000000..ee9a9b47b--- /dev/null+++ b/dist-artifact/.well-known/ai-plugin.json@@ -0,0 +1,17 @@+{+ "schema_version": "v1",+ "name_for_human": "3D Agent",+ "name_for_model": "3d_agent",+ "description_for_human": "AI-powered 3D model viewer. Drag and drop glTF, GLB, and 3D files to preview instantly in your browser.",+ "description_for_model": "A web-based 3D model viewer that supports glTF and GLB file formats. Users can drag-and-drop 3D models to preview them with real-time rendering powered by Three.js and WebGL.",+ "auth": {+ "type": "none"+ },+ "api": {+ "type": "openapi",+ "url": "https://3dagent.vercel.app/.well-known/openapi.yaml"+ },+ "logo_url": "https://3dagent.vercel.app/favicon.ico",+ "contact_email": "[email protected]",+ "legal_info_url": "https://3dagent.vercel.app/"+}diff --git a/dist-artifact/.well-known/openapi.yaml b/dist-artifact/.well-known/openapi.yamlnew file mode 100644index 000000000..a0c0f684d--- /dev/null+++ b/dist-artifact/.well-known/openapi.yaml@@ -0,0 +1,1695 @@+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:+ email: [email protected]+ license:+ name: MIT+ url: https://opensource.org/licenses/MIT++servers:+ - 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++# ---------------------------------------------------------------------------+# Security schemes+# ---------------------------------------------------------------------------+components:+ 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_`.++ # -------------------------------------------------------------------------+ # 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:+ 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'++ /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'++ 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+ - 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:+ 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: 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+ - 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++ /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'++ /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: {}++ /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: stringdiff --git a/dist-artifact/.well-known/security.txt b/dist-artifact/.well-known/security.txtnew file mode 100644index 000000000..294b4e7f3--- /dev/null+++ b/dist-artifact/.well-known/security.txt@@ -0,0 +1,7 @@+# Security policy for 3dagent.vercel.app+# https://securitytxt.org/++Contact: mailto:[email protected]+Preferred-Languages: en+Canonical: https://3dagent.vercel.app/.well-known/security.txt+Expires: 2027-04-14T00:00:00.000Zdiff --git a/dist-artifact/3d.png b/dist-artifact/3d.pngnew file mode 100644index 000000000..0db6e1c8fBinary files /dev/null and b/dist-artifact/3d.png differdiff --git a/dist-artifact/accessories/presets.json b/dist-artifact/accessories/presets.jsonnew file mode 100644index 000000000..f332e509a--- /dev/null+++ b/dist-artifact/accessories/presets.json@@ -0,0 +1,79 @@+[+ {+ "id": "outfit-casual",+ "kind": "outfit",+ "name": "Casual",+ "morphBinding": { "Outfit_Casual": 1.0 },+ "thumbnail": "/accessories/thumbs/outfit-casual.png"+ },+ {+ "id": "outfit-formal",+ "kind": "outfit",+ "name": "Formal",+ "morphBinding": { "Outfit_Formal": 1.0 },+ "thumbnail": "/accessories/thumbs/outfit-formal.png"+ },+ {+ "id": "outfit-sporty",+ "kind": "outfit",+ "name": "Sporty",+ "morphBinding": { "Outfit_Sporty": 1.0 },+ "thumbnail": "/accessories/thumbs/outfit-sporty.png"+ },+ {+ "id": "hat-baseball",+ "kind": "hat",+ "name": "Baseball Cap",+ "glbUrl": "/accessories/hat-baseball.glb",+ "attachBone": "Head",+ "thumbnail": "/accessories/thumbs/hat-baseball.png"+ },+ {+ "id": "hat-beanie",+ "kind": "hat",+ "name": "Beanie",+ "glbUrl": "/accessories/hat-beanie.glb",+ "attachBone": "Head",+ "thumbnail": "/accessories/thumbs/hat-beanie.png"+ },+ {+ "id": "hat-cowboy",+ "kind": "hat",+ "name": "Cowboy Hat",+ "glbUrl": "/accessories/hat-cowboy.glb",+ "attachBone": "Head",+ "thumbnail": "/accessories/thumbs/hat-cowboy.png"+ },+ {+ "id": "glasses-round",+ "kind": "glasses",+ "name": "Round Glasses",+ "glbUrl": "/accessories/glasses-round.glb",+ "attachBone": "Head",+ "thumbnail": "/accessories/thumbs/glasses-round.png"+ },+ {+ "id": "glasses-shades",+ "kind": "glasses",+ "name": "Shades",+ "glbUrl": "/accessories/glasses-shades.glb",+ "attachBone": "Head",+ "thumbnail": "/accessories/thumbs/glasses-shades.png"+ },+ {+ "id": "earrings-hoops",+ "kind": "earrings",+ "name": "Hoop Earrings",+ "glbUrl": "/accessories/earrings-hoops.glb",+ "attachBone": "Head",+ "thumbnail": "/accessories/thumbs/earrings-hoops.png"+ },+ {+ "id": "earrings-studs",+ "kind": "earrings",+ "name": "Stud Earrings",+ "glbUrl": "/accessories/earrings-studs.glb",+ "attachBone": "Head",+ "thumbnail": "/accessories/thumbs/earrings-studs.png"+ }+]diff --git a/dist-artifact/agent-edit/edit.js b/dist-artifact/agent-edit/edit.jsnew file mode 100644index 000000000..8e5b045f2--- /dev/null+++ b/dist-artifact/agent-edit/edit.js@@ -0,0 +1,604 @@+// Agent persona editor — /agent/:id/edit+// Native DOM, no framework.++const agentId = location.pathname.split('/').filter(Boolean)[1];++const DEFAULT_PERSONA = {+ name: '',+ bio: '',+ systemPrompt: '',+ catchphrases: [],+ sentimentBias: 0,+ doNotSay: [],+};++let agent = null;+let templates = [];+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 _elevenEnabled = false;+let _elevenLoaded = false;+let _webVoices = [];++// ── Bootstrap ──────────────────────────────────────────────────────────────++async function main() {+ if (!agentId) return showForbidden();++ // Auth check+ const me = await apiFetch('/api/auth/me').catch(() => null);+ if (!me?.user) {+ location.href = `/login?return=${encodeURIComponent(location.pathname)}`;+ return;+ }++ // Fetch agent+ const data = await apiFetch(`/api/agents/${encodeURIComponent(agentId)}`).catch(() => null);+ if (!data?.agent) return showForbidden();+ agent = data.agent;++ // Ownership check (user_id only present for owner)+ if (!agent.user_id || agent.user_id !== me.user.id) return showForbidden();++ // Check ElevenLabs availability+ try {+ const cfg = await apiFetch('/api/config').catch(() => ({}));+ _elevenEnabled = Boolean(cfg.elevenLabsEnabled);+ } catch {}++ // Load templates+ templates = await apiFetch('/agent-edit/templates.json').catch(() => []);++ // Restore voice config from meta+ const voiceMeta = agent.meta?.voice || {};+ _voiceProvider = voiceMeta.provider === 'eleven' ? 'eleven' : 'web';+ _voiceId = voiceMeta.voiceId || null;++ // Render+ document.getElementById('loading-screen').style.display = 'none';+ document.getElementById('layout').style.display = '';+ document.getElementById('header-title').textContent = `Edit — ${agent.name}`;+ const viewLink = document.getElementById('view-link');+ viewLink.href = `/agent/${agentId}`;++ loadPreview();+ renderTemplates();+ renderForm(agent.meta?.persona || DEFAULT_PERSONA);+ initVoicePicker();+ bindEvents();+ document.getElementById('save-btn').disabled = false;+}++function showForbidden() {+ document.getElementById('loading-screen').style.display = 'none';+ document.getElementById('forbidden-screen').style.display = '';+}++// ── Preview iframe ─────────────────────────────────────────────────────────++function loadPreview() {+ const frame = document.getElementById('preview-frame');+ const loading = document.getElementById('preview-loading');+ frame.src = `/agent/${agentId}/embed`;+ frame.addEventListener(+ 'load',+ () => {+ loading.style.display = 'none';+ frame.style.display = 'block';+ },+ { once: true },+ );+}++function reloadPreview() {+ const frame = document.getElementById('preview-frame');+ const loading = document.getElementById('preview-loading');+ frame.style.display = 'none';+ loading.style.display = 'grid';+ frame.src = `/agent/${agentId}/embed?_t=${Date.now()}`;+ frame.addEventListener(+ 'load',+ () => {+ loading.style.display = 'none';+ frame.style.display = 'block';+ },+ { once: true },+ );+}++// ── Templates ──────────────────────────────────────────────────────────────++function renderTemplates() {+ const row = document.getElementById('templates-row');+ row.innerHTML = '';+ for (const tpl of templates) {+ const btn = document.createElement('button');+ btn.className = 'template-btn';+ btn.textContent = tpl.label;+ btn.title = tpl.description;+ btn.addEventListener('click', () => applyTemplate(tpl));+ row.appendChild(btn);+ }+}++function applyTemplate(tpl) {+ renderForm({ ...DEFAULT_PERSONA, ...tpl.persona });+ toast('Template applied — review and save.');+}++// ── Form rendering ─────────────────────────────────────────────────────────++function renderForm(persona) {+ const p = { ...DEFAULT_PERSONA, ...persona };++ setVal('f-name', p.name);+ setVal('f-bio', p.bio);+ setVal('f-system-prompt', p.systemPrompt);++ const biasInput = document.getElementById('f-sentiment-bias');+ biasInput.value = p.sentimentBias;+ document.getElementById('bias-value').textContent = Number(p.sentimentBias).toFixed(2);++ renderCatchphrases(p.catchphrases || []);+ renderChips(p.doNotSay || []);+ updateCharCounts();+}++function setVal(id, val) {+ const el = document.getElementById(id);+ if (el) el.value = val || '';+}++function renderCatchphrases(list) {+ const container = document.getElementById('catchphrase-list');+ const addBtn = document.getElementById('add-catchphrase-btn');+ container.innerHTML = '';+ list.forEach((text, i) => addCatchphraseRow(text, i));+ addBtn.style.display = list.length < 5 ? '' : 'none';+}++function addCatchphraseRow(text = '', _index) {+ const container = document.getElementById('catchphrase-list');+ const addBtn = document.getElementById('add-catchphrase-btn');+ const row = document.createElement('div');+ row.className = 'catchphrase-row';++ const input = document.createElement('input');+ input.type = 'text';+ input.maxLength = 80;+ input.value = text;+ input.placeholder = 'e.g. "Let\'s figure this out"';+ input.addEventListener('input', scheduleSave);++ const removeBtn = document.createElement('button');+ removeBtn.textContent = '×';+ removeBtn.title = 'Remove';+ removeBtn.addEventListener('click', () => {+ row.remove();+ const count = container.querySelectorAll('.catchphrase-row').length;+ addBtn.style.display = count < 5 ? '' : 'none';+ scheduleSave();+ });++ row.appendChild(input);+ row.appendChild(removeBtn);+ container.appendChild(row);++ const count = container.querySelectorAll('.catchphrase-row').length;+ addBtn.style.display = count < 5 ? '' : 'none';+}++// ── Chip input (do-not-say) ────────────────────────────────────────────────++let _doNotSay = [];++function renderChips(list) {+ _doNotSay = [...list];+ rebuildChipDom();+}++function rebuildChipDom() {+ const wrap = document.getElementById('dns-wrap');+ const textInput = document.getElementById('dns-input');+ // Remove existing chips (not the text input)+ wrap.querySelectorAll('.chip').forEach((c) => c.remove());+ _doNotSay.forEach((word, i) => {+ const chip = document.createElement('span');+ chip.className = 'chip';+ chip.textContent = word;+ const del = document.createElement('button');+ del.textContent = '×';+ del.title = `Remove "${word}"`;+ del.addEventListener('click', () => {+ _doNotSay.splice(i, 1);+ rebuildChipDom();+ scheduleSave();+ });+ chip.appendChild(del);+ wrap.insertBefore(chip, textInput);+ });+}++// ── Char counters ──────────────────────────────────────────────────────────++function updateCharCounts() {+ updateCount('f-name', 'cnt-name', 40);+ updateCount('f-bio', 'cnt-bio', 280);+ updateCount('f-system-prompt', 'cnt-system-prompt', 2000);+}++function updateCount(fieldId, countId, max) {+ const field = document.getElementById(fieldId);+ const counter = document.getElementById(countId);+ if (field && counter) {+ const len = field.value.length;+ counter.textContent = `${len}/${max}`;+ counter.style.color = len > max * 0.9 ? '#ff9a3c' : '#555';+ }+}++// ── Voice picker ──────────────────────────────────────────────────────────++function initVoicePicker() {+ const group = document.getElementById('voice-picker-group');++ // Provider toggle+ const toggle = document.createElement('div');+ toggle.className = 'vp-toggle';+ toggle.innerHTML = `+ <button class="vp-toggle-btn${_voiceProvider === 'web' ? ' active' : ''}" data-vp="web">Web Speech</button>+ <button class="vp-toggle-btn${_voiceProvider === 'eleven' ? ' active' : ''}" data-vp="eleven"+ ${_elevenEnabled ? '' : 'disabled title="ElevenLabs API key not configured"'}>ElevenLabs</button>+ `;+ group.appendChild(toggle);++ toggle.querySelectorAll('.vp-toggle-btn').forEach((btn) => {+ btn.addEventListener('click', () => setVoiceProvider(btn.dataset.vp));+ });++ // Voice list container+ const listWrap = document.createElement('div');+ listWrap.id = 'vp-list-wrap';+ group.appendChild(listWrap);++ renderVoiceSection();+}++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));+ renderVoiceSection();+}++function renderVoiceSection() {+ const wrap = document.getElementById('vp-list-wrap');+ if (!wrap) return;+ wrap.innerHTML = '';+ if (_voiceProvider === 'web') renderWebVoices(wrap);+ if (_voiceProvider === 'eleven') renderElevenVoices(wrap);+}++// Web Speech+function renderWebVoices(wrap) {+ if (!('speechSynthesis' in window)) {+ wrap.innerHTML = '<div class="vp-empty">Web Speech not available in this browser.</div>';+ return;+ }++ const doRender = () => {+ _webVoices = window.speechSynthesis.getVoices();+ if (!_webVoices.length) return;++ // Group by language family+ const groups = {};+ for (const v of _webVoices) {+ const lang = v.lang ? v.lang.slice(0, 2).toUpperCase() : '??';+ (groups[lang] = groups[lang] || []).push(v);+ }++ const list = document.createElement('div');+ list.className = 'vp-list';+ 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);+ }));+ }+ }+ wrap.innerHTML = '';+ wrap.appendChild(list);+ };++ const voices = window.speechSynthesis.getVoices();+ if (voices.length) { doRender(); return; }+ window.speechSynthesis.addEventListener('voiceschanged', doRender, { once: true });+ setTimeout(doRender, 250); // fallback for browsers that don't fire voiceschanged+}++// ElevenLabs+async function renderElevenVoices(wrap) {+ if (!_elevenEnabled) {+ wrap.innerHTML = '<div class="vp-empty">ElevenLabs API key not configured on this server.</div>';+ return;+ }++ if (!_elevenLoaded) {+ wrap.innerHTML = '<div class="vp-empty">Loading ElevenLabs voices…</div>';+ let data;+ try {+ data = await apiFetch('/api/tts/eleven/voices');+ _elevenLoaded = true;+ } catch (e) {+ wrap.innerHTML = `<div class="vp-empty">Failed to load voices: ${esc(e.message)}</div>`;+ return;+ }++ if (!data.enabled) {+ wrap.innerHTML = '<div class="vp-empty">ElevenLabs not configured.</div>';+ return;+ }++ const list = document.createElement('div');+ list.className = 'vp-list';+ 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 selected = _voiceProvider === 'eleven' && _voiceId === v.voice_id;+ list.appendChild(buildVoiceItem(v.voice_id, v.name, meta, selected, (btn) => {+ previewElevenVoice(v.voice_id, btn);+ }));+ }++ wrap.innerHTML = '';+ wrap.appendChild(list);+ return;+ }++ // Already loaded — just rebuild with correct selection+ const cached = document.getElementById('vp-eleven-list');+ if (cached) {+ wrap.innerHTML = '';+ wrap.appendChild(cached);+ cached.querySelectorAll('.vp-item').forEach((item) => {+ item.classList.toggle('selected', _voiceId === item.dataset.vid);+ });+ }+}++function buildVoiceItem(vid, displayName, meta, selected, previewFn) {+ const el = document.createElement('div');+ el.className = 'vp-item' + (selected ? ' selected' : '');+ el.dataset.vid = vid;+ el.innerHTML = `+ <div class="vp-radio"></div>+ <div style="flex:1;min-width:0">+ <div class="vp-name">${esc(displayName)}</div>+ ${meta ? `<div class="vp-meta">${esc(meta)}</div>` : ''}+ </div>+ <button class="vp-preview-btn" type="button">Preview</button>+ `;+ el.addEventListener('click', (e) => {+ if (e.target.classList.contains('vp-preview-btn')) return;+ selectVoiceItem(el, vid);+ });+ el.querySelector('.vp-preview-btn').addEventListener('click', (e) => {+ e.stopPropagation();+ previewFn(e.target);+ });+ return el;+}++function selectVoiceItem(el, vid) {+ el.closest('.vp-list').querySelectorAll('.vp-item').forEach((i) => i.classList.remove('selected'));+ el.classList.add('selected');+ _voiceId = vid;+}++function previewWebVoice(name, btn) {+ if (!('speechSynthesis' in window)) return;+ window.speechSynthesis.cancel();+ const utter = new SpeechSynthesisUtterance("Hi, I'm your agent.");+ const voice = window.speechSynthesis.getVoices().find((v) => v.name === name);+ if (voice) utter.voice = voice;+ if (btn) {+ btn.disabled = true;+ utter.onend = () => { btn.disabled = false; };+ utter.onerror = () => { btn.disabled = false; };+ }+ window.speechSynthesis.speak(utter);+}++async function previewElevenVoice(voiceId, btn) {+ if (btn) btn.disabled = true;+ try {+ const res = await fetch('/api/tts/eleven', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ voiceId, text: "Hi, I'm your agent." }),+ });+ if (!res.ok) {+ const err = await res.json().catch(() => ({}));+ toast(err.error_description || `Preview failed (${res.status})`, true);+ return;+ }+ const blob = await res.blob();+ const url = URL.createObjectURL(blob);+ const audio = new Audio(url);+ 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();+ } catch (e) {+ toast(`Preview failed: ${e.message}`, true);+ if (btn) btn.disabled = false;+ }+}++// ── Read form → persona object ─────────────────────────────────────────────++function readForm() {+ const catchphrases = [...document.querySelectorAll('#catchphrase-list .catchphrase-row input')]+ .map((i) => i.value.trim())+ .filter(Boolean);++ return {+ name: document.getElementById('f-name').value.trim(),+ bio: document.getElementById('f-bio').value.trim(),+ systemPrompt: document.getElementById('f-system-prompt').value.trim(),+ catchphrases,+ sentimentBias: parseFloat(document.getElementById('f-sentiment-bias').value),+ doNotSay: [..._doNotSay],+ };+}++// ── Save ───────────────────────────────────────────────────────────────────++function scheduleSave() {+ // Not auto-saving — just here for future use if needed.+}++async function save() {+ const btn = document.getElementById('save-btn');+ btn.disabled = true;+ btn.textContent = 'Saving…';+ try {+ const persona = readForm();+ if (!persona.name) {+ toast('Name is required.', true);+ return;+ }++ // Merge voice config into meta alongside persona. We send the full meta+ // because the API replaces it wholesale via COALESCE.+ const currentMeta = agent.meta || {};+ const newMeta = {+ ...currentMeta,+ persona,+ voice: { provider: _voiceProvider, voiceId: _voiceId || null },+ };++ await apiFetch(`/api/agents/${encodeURIComponent(agentId)}`, {+ method: 'PUT',+ body: JSON.stringify({+ name: persona.name,+ description: persona.bio,+ meta: newMeta,+ }),+ });++ // Update local agent reference so subsequent saves carry forward the new meta.+ agent = { ...agent, name: persona.name, description: persona.bio, meta: newMeta };++ toast('Saved!');+ reloadPreview();+ } catch (err) {+ toast(err.message || 'Save failed.', true);+ } finally {+ btn.disabled = false;+ btn.textContent = 'Save';+ }+}++// ── Events ─────────────────────────────────────────────────────────────────++function bindEvents() {+ document.getElementById('save-btn').addEventListener('click', save);++ // Char counts+ ['f-name', 'f-bio', 'f-system-prompt'].forEach((id) => {+ document.getElementById(id)?.addEventListener('input', updateCharCounts);+ });++ // Sentiment bias label+ document.getElementById('f-sentiment-bias').addEventListener('input', (e) => {+ document.getElementById('bias-value').textContent = Number(e.target.value).toFixed(2);+ });++ // Add catchphrase+ document.getElementById('add-catchphrase-btn').addEventListener('click', () => {+ const count = document.querySelectorAll('#catchphrase-list .catchphrase-row').length;+ if (count < 5) addCatchphraseRow();+ });++ // Do-not-say chip input: Enter or comma adds chip+ document.getElementById('dns-input').addEventListener('keydown', (e) => {+ if (e.key === 'Enter' || e.key === ',') {+ e.preventDefault();+ const word = e.target.value.trim().replace(/,$/, '');+ if (word && !_doNotSay.includes(word)) {+ _doNotSay.push(word);+ rebuildChipDom();+ }+ e.target.value = '';+ } else if (e.key === 'Backspace' && !e.target.value && _doNotSay.length) {+ _doNotSay.pop();+ rebuildChipDom();+ }+ });++ // Reset prompt to template+ document.getElementById('reset-prompt-btn').addEventListener('click', () => {+ const existing = agent?.meta?.persona;+ if (existing?.systemPrompt) {+ document.getElementById('f-system-prompt').value = existing.systemPrompt;+ updateCharCounts();+ toast('Reset to last saved prompt.');+ } else {+ toast('No saved prompt to reset to.', false);+ }+ });+}++// ── Utilities ──────────────────────────────────────────────────────────────++async function apiFetch(path, opts = {}) {+ const res = await fetch(path, {+ ...opts,+ credentials: 'include',+ headers: {+ ...(opts.body ? { 'content-type': 'application/json' } : {}),+ ...opts.headers,+ },+ });+ const data = res.headers.get('content-type')?.includes('application/json')+ ? await res.json()+ : await res.json().catch(() => null);+ if (!res.ok) {+ const msg = data?.error_description || data?.error || res.statusText;+ throw new Error(msg);+ }+ return data;+}++let _toastTimer = null;+function toast(msg, isError = false) {+ const el = document.getElementById('toast');+ el.textContent = msg;+ el.className = 'toast show' + (isError ? ' err' : '');+ clearTimeout(_toastTimer);+ _toastTimer = setTimeout(() => {+ el.className = 'toast';+ }, 3200);+}++function esc(s) {+ return String(s ?? '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');+}++// ── Boot ───────────────────────────────────────────────────────────────────++main().catch((err) => {+ document.getElementById('loading-screen').textContent = `Error: ${err.message}`;+});diff --git a/dist-artifact/agent-edit/index.html b/dist-artifact/agent-edit/index.htmlnew file mode 100644index 000000000..536c4fb69--- /dev/null+++ b/dist-artifact/agent-edit/index.html@@ -0,0 +1,208 @@+<!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>++ <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">+ <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>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 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 class="toast" id="toast"></div>++<script type="module" src="./edit.js"></script>+</body>+</html>diff --git a/dist-artifact/agent-edit/templates.json b/dist-artifact/agent-edit/templates.jsonnew file mode 100644index 000000000..a502cf222--- /dev/null+++ b/dist-artifact/agent-edit/templates.json@@ -0,0 +1,47 @@+[+ {+ "id": "friend",+ "label": "Friend",+ "description": "Casual, warm, always in your corner.",+ "persona": {+ "name": "Friend",+ "bio": "Your chill, supportive companion — here to help you explore and create.",+ "systemPrompt": "You are a warm, casual, and supportive companion. Speak conversationally — contractions, light humour, genuine enthusiasm. Celebrate wins openly and acknowledge struggles with empathy. Never lecture; just help.",+ "catchphrases": ["Let's figure this out together", "Nice one!", "Happy to help"],+ "sentimentBias": 0.7,+ "voiceProvider": "web",+ "voiceId": null,+ "doNotSay": []+ }+ },+ {+ "id": "coach",+ "label": "Coach",+ "description": "Directive, concise, results-focused.",+ "persona": {+ "name": "Coach",+ "bio": "A results-focused mentor who gives clear guidance without fluff.",+ "systemPrompt": "You are a direct, efficient coach. Give concise instructions and concrete next steps. Skip pleasantries; get to the point. Use active voice. Push the user toward action.",+ "catchphrases": ["Here's what you do", "Next step:", "Focus."],+ "sentimentBias": 0,+ "voiceProvider": "web",+ "voiceId": null,+ "doNotSay": ["maybe", "I think perhaps"]+ }+ },+ {+ "id": "researcher",+ "label": "Researcher",+ "description": "Curious, precise, always asking why.",+ "persona": {+ "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…"],+ "sentimentBias": -0.1,+ "voiceProvider": "web",+ "voiceId": null,+ "doNotSay": ["obviously", "clearly", "just"]+ }+ }+]diff --git a/dist-artifact/agent/embed.html b/dist-artifact/agent/embed.htmlnew file mode 100644index 000000000..1390d26ce--- /dev/null+++ b/dist-artifact/agent/embed.html@@ -0,0 +1,255 @@+<!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;+ }+ }++ // Legacy envelope. Kept until all known hosts migrate.+ if (msg.__agent === agentId) {+ if (msg.type === 'action' && msg.action) handleAction(msg.action);+ }+ });++ 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 (!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/dist-artifact/agent/index.html b/dist-artifact/agent/index.htmlnew file mode 100644index 000000000..51a0be609--- /dev/null+++ b/dist-artifact/agent/index.html@@ -0,0 +1,583 @@+<!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>+ </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 & embed</div>+ <div class="agent-embed-tabs" role="tablist">+ <button class="agent-embed-tab active" data-tab="iframe">iframe</button>+ <button class="agent-embed-tab" data-tab="link">link</button>+ <button class="agent-embed-tab" data-tab="webcomponent"><agent-3d></button>+ </div>+ <div class="agent-embed-code-wrap">+ <div class="agent-embed-code" id="agent-embed-code"></div>+ <button class="agent-embed-copy" id="agent-embed-copy">copy</button>+ </div>+ <a class="agent-embed-preview-link" id="agent-embed-preview" target="_blank" rel="noopener">preview embed →</a>+ <a class="agent-embed-preview-link" id="agent-embed-settings" href="" target="_blank" rel="noopener">embed settings →</a>+ </div>++ <script type="module">+ import { AgentIdentity } from '/src/agent-identity.js';+ import { AgentMemory } from '/src/agent-memory.js';+ import { AgentSkills } from '/src/agent-skills.js';+ import { AgentHome } from '/src/agent-home.js';+ import { protocol } from '/src/agent-protocol.js';+ 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);+ });+ }++ // 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 {}+ });++ populateUnfurlMeta(identity);+ }++ function populateUnfurlMeta(identity) {+ const id = identity?.id;+ if (!id) return;+ const origin = location.origin;+ const name = identity.name || 'Agent';+ const desc = identity.description || 'An embodied 3D agent.';+ const agentUrl = `${origin}/agent/${id}`;+ const img = `${origin}/api/agent/${id}/og`;+ const setAttr = (elId, attr, value) => {+ const el = document.getElementById(elId);+ if (el) el.setAttribute(attr, value);+ };+ setAttr('og-title', 'content', name);+ setAttr('og-description', 'content', desc);+ setAttr('og-image', 'content', img);+ setAttr('og-url', 'content', agentUrl);+ setAttr('tw-title', 'content', name);+ setAttr('tw-description', 'content', desc);+ setAttr('tw-image', 'content', img);+ setAttr('oembed-link', 'href', `${origin}/api/oembed?url=${encodeURIComponent(agentUrl)}`);+ document.title = `${name} — 3D Agent`;+ }++ main().catch(err => {+ document.getElementById('agent-home-container').innerHTML =+ `<div class="loading-placeholder">Could not load agent: ${err.message}</div>`;+ });+ </script>+</body>+</html>diff --git a/dist-artifact/agents/README.md b/dist-artifact/agents/README.mdnew file mode 100644index 000000000..3108aa680--- /dev/null+++ b/dist-artifact/agents/README.md@@ -0,0 +1,52 @@+# Agents Directory++Public directory of registered agents across the 3D Agent ecosystem.++## Features++- **Global discovery** — Browse all registered agents on-chain+- **Chain filtering** — Filter by blockchain (Base, Base Sepolia, Optimism, Polygon)+- **Search** — Find agents by name, ID, or description+- **Sorting** — Sort by newest, oldest, or alphabetical order+- **Pagination** — 30 agents per page with shareable URLs+- **Lazy loading** — Avatar thumbnails load on-demand++## Data source++Agents are sourced from the **on-chain IdentityRegistry**. Each agent's metadata is resolved from the `tokenURI` stored on-chain. Avatar images are extracted from the agent manifest's `body.uri` field.++## URL parameters++Filters are preserved in the URL for shareability:++```+/agents/?chain=8453&sort=newest&page=2&search=Alice+```++| Parameter | Values | Default |+| --------- | ------ | ------- |+| `chain` | `all`, `8453` (Base), `84532` (Base Sepolia), `10` (Optimism), `137` (Polygon) | `all` |+| `sort` | `newest`, `oldest`, `name` | `newest` |+| `page` | `1`–N | `1` |+| `search` | Free text | (none) |++## Accessibility++- Semantic HTML with `data-agent-id` attributes on cards (QA-friendly)+- Lazy loading via `IntersectionObserver`+- Keyboard navigation support (tabs, enter)+- Target Lighthouse accessibility score ≥ 90++## Architecture++- **[index.html](./index.html)** — HTML structure + inline styles+- **[boot.js](./boot.js)** — Event handling + URL state management+- **[../../src/agents-directory.js](../../src/agents-directory.js)** — Controller class+ - Fetches from on-chain registries+ - Client-side filtering & sorting+ - SWR-style caching (60s TTL)+ - Lazy image loading++## Rate limiting++On-chain queries use public RPCs from `CHAIN_META`. No backend calls for the public list (no rate-limit concerns).diff --git a/dist-artifact/agents/boot.js b/dist-artifact/agents/boot.jsnew file mode 100644index 000000000..88aad7e4b--- /dev/null+++ b/dist-artifact/agents/boot.js@@ -0,0 +1,153 @@+/**+ * Agents directory page — initialization and event handling.+ */++import { AgentsDirectory } from '../../src/agents-directory.js';++const directory = new AgentsDirectory('#agents');++// Decode URL params+const urlParams = new URLSearchParams(window.location.search);+const initialChain = urlParams.get('chain') || 'all';+const initialSort = urlParams.get('sort') || 'newest';+const initialPage = parseInt(urlParams.get('page') || '1', 10);+const initialSearch = urlParams.get('search') || '';++// UI elements+const searchInput = document.getElementById('search');+const filterChips = document.querySelectorAll('.filter-chip');+const sortSelect = document.getElementById('sort');+const agentsContainer = document.getElementById('agents');+const emptyState = document.getElementById('empty-state');+const loadingEl = document.getElementById('loading');+const paginationEl = document.getElementById('pagination');+const pageInfo = document.getElementById('page-info');+const prevBtn = document.getElementById('prev-btn');+const nextBtn = document.getElementById('next-btn');++let currentChain = initialChain;+let currentSort = initialSort;+let currentPage = initialPage;+let currentSearch = initialSearch;++/**+ * Update URL with current state.+ */+function updateUrl() {+ const params = new URLSearchParams();+ if (currentChain !== 'all') params.set('chain', currentChain);+ if (currentSort !== 'newest') params.set('sort', currentSort);+ if (currentPage !== 1) params.set('page', currentPage);+ if (currentSearch) params.set('search', currentSearch);++ const query = params.toString();+ const path = query ? `?${query}` : '';+ window.history.replaceState({}, '', `/agents/${path}`);+}++/**+ * Load and render agents.+ */+async function render() {+ loadingEl.style.display = 'block';+ agentsContainer.innerHTML = '';+ emptyState.style.display = 'none';+ paginationEl.style.display = 'none';++ try {+ const result = await directory.load({+ chain: currentChain,+ search: currentSearch,+ sort: currentSort,+ page: currentPage,+ });++ if (result.agents.length === 0) {+ emptyState.style.display = 'block';+ loadingEl.style.display = 'none';+ return;+ }++ directory.render();+ loadingEl.style.display = 'none';+ agentsContainer.style.display = 'grid';++ // Update pagination+ const { hasNextPage, hasPrevPage, page, totalPages } = directory.getPaginationInfo();+ pageInfo.textContent = `Page ${page} of ${totalPages}`;+ prevBtn.disabled = !hasPrevPage;+ nextBtn.disabled = !hasNextPage;+ paginationEl.style.display = 'flex';++ // Scroll to top+ window.scrollTo({ top: 0, behavior: 'smooth' });+ } catch (err) {+ console.error('Failed to load agents:', err);+ loadingEl.style.display = 'none';+ emptyState.style.display = 'block';+ emptyState.querySelector('h2').textContent = 'Error loading agents';+ emptyState.querySelector('p').textContent = err.message || 'Please try again later.';+ }+}++/**+ * Handle card clicks.+ */+directory.onCardClick((agent) => {+ window.location.href = `/a/${agent.chainId}/${agent.id}`;+});++// Search input+searchInput.value = currentSearch;+searchInput.addEventListener('input', (e) => {+ currentSearch = e.target.value;+ currentPage = 1;+ updateUrl();+ render();+});++// Filter chips+filterChips.forEach((chip) => {+ const filter = chip.dataset.filter;+ if (filter === currentChain) {+ chip.classList.add('active');+ }+ chip.addEventListener('click', () => {+ filterChips.forEach((c) => c.classList.remove('active'));+ chip.classList.add('active');+ currentChain = filter;+ currentPage = 1;+ updateUrl();+ render();+ });+});++// Sort select+sortSelect.value = currentSort;+sortSelect.addEventListener('change', (e) => {+ currentSort = e.target.value;+ currentPage = 1;+ updateUrl();+ render();+});++// Pagination+prevBtn.addEventListener('click', () => {+ if (currentPage > 1) {+ currentPage--;+ updateUrl();+ render();+ }+});++nextBtn.addEventListener('click', () => {+ const info = directory.getPaginationInfo();+ if (currentPage < info.totalPages) {+ currentPage++;+ updateUrl();+ render();+ }+});++// Initial render+render();diff --git a/dist-artifact/agents/index.html b/dist-artifact/agents/index.htmlnew file mode 100644index 000000000..7ffb98297--- /dev/null+++ b/dist-artifact/agents/index.html@@ -0,0 +1,390 @@+<!DOCTYPE html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Agents Directory — 3D Agent</title>+ <style>+ * {+ margin: 0;+ padding: 0;+ box-sizing: border-box;+ }++ html,+ body {+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu',+ 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;+ background: linear-gradient(135deg, #0f0f23 0%, #1a0f3a 100%);+ color: #e0e0e0;+ min-height: 100vh;+ overflow-x: hidden;+ }++ header {+ background: rgba(15, 15, 35, 0.95);+ border-bottom: 1px solid rgba(255, 255, 255, 0.1);+ padding: 2rem 1rem;+ text-align: center;+ }++ header h1 {+ font-size: 2.5rem;+ margin-bottom: 0.5rem;+ background: linear-gradient(135deg, #00d9ff, #7c3aed);+ background-clip: text;+ -webkit-background-clip: text;+ -webkit-text-fill-color: transparent;+ }++ header p {+ font-size: 1rem;+ color: #a0a0a0;+ }++ .container {+ max-width: 1400px;+ margin: 2rem auto;+ padding: 0 1rem;+ }++ .controls {+ display: flex;+ flex-wrap: wrap;+ gap: 1rem;+ margin-bottom: 2rem;+ align-items: center;+ }++ .search-box {+ flex: 1;+ min-width: 250px;+ padding: 0.75rem 1rem;+ background: rgba(255, 255, 255, 0.05);+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: 8px;+ color: #e0e0e0;+ font-size: 1rem;+ }++ .search-box::placeholder {+ color: #666;+ }++ .search-box:focus {+ outline: none;+ border-color: #00d9ff;+ background: rgba(0, 217, 255, 0.05);+ }++ .filter-group {+ display: flex;+ gap: 0.5rem;+ flex-wrap: wrap;+ }++ .filter-label {+ font-size: 0.85rem;+ font-weight: 600;+ text-transform: uppercase;+ color: #999;+ align-self: center;+ }++ .filter-chip {+ padding: 0.5rem 1rem;+ background: rgba(255, 255, 255, 0.05);+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: 20px;+ cursor: pointer;+ font-size: 0.9rem;+ color: #a0a0a0;+ transition: all 0.2s ease;+ }++ .filter-chip:hover {+ background: rgba(255, 255, 255, 0.1);+ }++ .filter-chip.active {+ background: linear-gradient(135deg, #00d9ff, #7c3aed);+ border-color: transparent;+ color: #fff;+ font-weight: 600;+ }++ .sort-select {+ padding: 0.5rem 1rem;+ background: rgba(255, 255, 255, 0.05);+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: 8px;+ color: #e0e0e0;+ cursor: pointer;+ font-size: 0.9rem;+ }++ .sort-select:focus {+ outline: none;+ border-color: #00d9ff;+ }++ .sort-select option {+ background: #0f0f23;+ color: #e0e0e0;+ }++ .agent-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));+ gap: 1.5rem;+ margin-bottom: 2rem;+ }++ .agent-card {+ background: rgba(255, 255, 255, 0.03);+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: 12px;+ overflow: hidden;+ cursor: pointer;+ transition: all 0.3s ease;+ display: flex;+ flex-direction: column;+ }++ .agent-card:hover {+ border-color: rgba(0, 217, 255, 0.5);+ background: rgba(0, 217, 255, 0.05);+ transform: translateY(-4px);+ box-shadow: 0 8px 24px rgba(0, 217, 255, 0.15);+ }++ .card-avatar {+ width: 100%;+ aspect-ratio: 1;+ background: rgba(255, 255, 255, 0.02);+ display: flex;+ align-items: center;+ justify-content: center;+ overflow: hidden;+ }++ .card-avatar img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ }++ .avatar-placeholder {+ font-size: 3rem;+ opacity: 0.3;+ }++ .card-content {+ padding: 1.25rem;+ flex: 1;+ display: flex;+ flex-direction: column;+ }++ .card-name {+ font-size: 1.1rem;+ font-weight: 600;+ margin-bottom: 0.5rem;+ color: #fff;+ line-height: 1.3;+ }++ .card-desc {+ font-size: 0.85rem;+ color: #a0a0a0;+ margin-bottom: 1rem;+ line-height: 1.4;+ flex: 1;+ }++ .card-meta {+ display: flex;+ gap: 0.5rem;+ flex-wrap: wrap;+ font-size: 0.75rem;+ }++ .chain-badge {+ background: rgba(124, 58, 237, 0.2);+ border: 1px solid rgba(124, 58, 237, 0.5);+ padding: 0.3rem 0.6rem;+ border-radius: 4px;+ color: #c4b5fd;+ }++ .agent-id {+ background: rgba(0, 217, 255, 0.1);+ border: 1px solid rgba(0, 217, 255, 0.3);+ padding: 0.3rem 0.6rem;+ border-radius: 4px;+ color: #00d9ff;+ font-family: 'Monaco', 'Courier New', monospace;+ }++ .empty-state {+ text-align: center;+ padding: 4rem 2rem;+ }++ .empty-state h2 {+ font-size: 1.5rem;+ margin-bottom: 1rem;+ color: #fff;+ }++ .empty-state p {+ font-size: 1rem;+ color: #a0a0a0;+ margin-bottom: 2rem;+ }++ .cta-button {+ padding: 0.75rem 1.5rem;+ background: linear-gradient(135deg, #00d9ff, #7c3aed);+ border: none;+ border-radius: 8px;+ color: #fff;+ font-weight: 600;+ cursor: pointer;+ transition: all 0.2s ease;+ text-decoration: none;+ display: inline-block;+ }++ .cta-button:hover {+ transform: scale(1.05);+ box-shadow: 0 8px 24px rgba(0, 217, 255, 0.3);+ }++ .pagination {+ display: flex;+ justify-content: center;+ align-items: center;+ gap: 1rem;+ margin-top: 2rem;+ padding: 2rem;+ flex-wrap: wrap;+ }++ .pagination-button {+ padding: 0.5rem 1rem;+ background: rgba(255, 255, 255, 0.05);+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: 8px;+ color: #e0e0e0;+ cursor: pointer;+ transition: all 0.2s ease;+ }++ .pagination-button:hover:not(:disabled) {+ background: rgba(0, 217, 255, 0.1);+ border-color: #00d9ff;+ color: #00d9ff;+ }++ .pagination-button:disabled {+ opacity: 0.3;+ cursor: not-allowed;+ }++ .pagination-info {+ color: #a0a0a0;+ font-size: 0.9rem;+ }++ .loading {+ text-align: center;+ padding: 2rem;+ color: #a0a0a0;+ }++ .loading::after {+ content: '';+ display: inline-block;+ margin-left: 0.5rem;+ width: 1rem;+ height: 1rem;+ border: 2px solid rgba(0, 217, 255, 0.3);+ border-top-color: #00d9ff;+ border-radius: 50%;+ animation: spin 0.8s linear infinite;+ }++ @keyframes spin {+ to {+ transform: rotate(360deg);+ }+ }++ @media (max-width: 768px) {+ header h1 {+ font-size: 1.75rem;+ }++ .controls {+ flex-direction: column;+ }++ .search-box {+ min-width: 100%;+ }++ .agent-grid {+ grid-template-columns: 1fr;+ }+ }+ </style>+ </head>+ <body>+ <header>+ <h1>Agent Directory</h1>+ <p>Discover registered agents across the ecosystem</p>+ </header>++ <div class="container">+ <div class="controls">+ <input+ type="text"+ id="search"+ class="search-box"+ placeholder="Search by name, ID, or description…"+ />+ <div class="filter-group">+ <span class="filter-label">Chain:</span>+ <button class="filter-chip active" data-filter="all">All</button>+ <button class="filter-chip" data-filter="8453">Base</button>+ <button class="filter-chip" data-filter="84532">Base Sepolia</button>+ <button class="filter-chip" data-filter="10">Optimism</button>+ <button class="filter-chip" data-filter="137">Polygon</button>+ </div>+ <select id="sort" class="sort-select">+ <option value="newest">Newest First</option>+ <option value="oldest">Oldest First</option>+ <option value="name">Alphabetical</option>+ </select>+ </div>++ <div id="loading" class="loading" style="display: none">Loading agents</div>+ <div id="agents" class="agent-grid"></div>++ <div id="empty-state" class="empty-state" style="display: none">+ <h2>No agents found</h2>+ <p>Be the first to register your agent on-chain.</p>+ <a href="/create" class="cta-button">Create Agent</a>+ </div>++ <div id="pagination" class="pagination" style="display: none">+ <button id="prev-btn" class="pagination-button">← Previous</button>+ <span id="page-info" class="pagination-info"></span>+ <button id="next-btn" class="pagination-button">Next →</button>+ </div>+ </div>++ <script type="module" src="./boot.js"></script>+ </body>+</html>diff --git a/dist-artifact/animations/Angry.fbx b/dist-artifact/animations/Angry.fbxnew file mode 100644index 000000000..2387334bdBinary files /dev/null and b/dist-artifact/animations/Angry.fbx differdiff --git a/dist-artifact/animations/Capoeira.fbx b/dist-artifact/animations/Capoeira.fbxnew file mode 100644index 000000000..bf77dd891Binary files /dev/null and b/dist-artifact/animations/Capoeira.fbx differdiff --git a/dist-artifact/animations/Cover To Stand.fbx b/dist-artifact/animations/Cover To Stand.fbxnew file mode 100644index 000000000..8cac554e4Binary files /dev/null and b/dist-artifact/animations/Cover To Stand.fbx differdiff --git a/dist-artifact/animations/Crouch To Stand.fbx b/dist-artifact/animations/Crouch To Stand.fbxnew file mode 100644index 000000000..f1e45e85aBinary files /dev/null and b/dist-artifact/animations/Crouch To Stand.fbx differdiff --git a/dist-artifact/animations/Defeated.fbx b/dist-artifact/animations/Defeated.fbxnew file mode 100644index 000000000..3bb0d2b9dBinary files /dev/null and b/dist-artifact/animations/Defeated.fbx differdiff --git a/dist-artifact/animations/Dodging Right.fbx b/dist-artifact/animations/Dodging Right.fbxnew file mode 100644index 000000000..8d1ab9a40Binary files /dev/null and b/dist-artifact/animations/Dodging Right.fbx differdiff --git a/dist-artifact/animations/Dying.fbx b/dist-artifact/animations/Dying.fbxnew file mode 100644index 000000000..2a1ea164bBinary files /dev/null and b/dist-artifact/animations/Dying.fbx differdiff --git a/dist-artifact/animations/Falling.fbx b/dist-artifact/animations/Falling.fbxnew file mode 100644index 000000000..1c666b403Binary files /dev/null and b/dist-artifact/animations/Falling.fbx differdiff --git a/dist-artifact/animations/Goalkeeper Scoop.fbx b/dist-artifact/animations/Goalkeeper Scoop.fbxnew file mode 100644index 000000000..6318a8508Binary files /dev/null and b/dist-artifact/animations/Goalkeeper Scoop.fbx differdiff --git a/dist-artifact/animations/Header Soccerball.fbx b/dist-artifact/animations/Header Soccerball.fbxnew file mode 100644index 000000000..a7a106545Binary files /dev/null and b/dist-artifact/animations/Header Soccerball.fbx differdiff --git a/dist-artifact/animations/Hip Hop Dancing.fbx b/dist-artifact/animations/Hip Hop Dancing.fbxnew file mode 100644index 000000000..2e929cff1Binary files /dev/null and b/dist-artifact/animations/Hip Hop Dancing.fbx differdiff --git a/dist-artifact/animations/Joyful Jump.fbx b/dist-artifact/animations/Joyful Jump.fbxnew file mode 100644index 000000000..5ab7757e8Binary files /dev/null and b/dist-artifact/animations/Joyful Jump.fbx differdiff --git a/dist-artifact/animations/Jumping Down (1).fbx b/dist-artifact/animations/Jumping Down (1).fbxnew file mode 100644index 000000000..749d534b2Binary files /dev/null and b/dist-artifact/animations/Jumping Down (1).fbx differdiff --git a/dist-artifact/animations/Jumping Down (2).fbx b/dist-artifact/animations/Jumping Down (2).fbxnew file mode 100644index 000000000..42a8bad60Binary files /dev/null and b/dist-artifact/animations/Jumping Down (2).fbx differdiff --git a/dist-artifact/animations/Jumping Down.fbx b/dist-artifact/animations/Jumping Down.fbxnew file mode 100644index 000000000..c2b06dd22Binary files /dev/null and b/dist-artifact/animations/Jumping Down.fbx differdiff --git a/dist-artifact/animations/Kiss.fbx b/dist-artifact/animations/Kiss.fbxnew file mode 100644index 000000000..7014980fdBinary files /dev/null and b/dist-artifact/animations/Kiss.fbx differdiff --git a/dist-artifact/animations/Old Man Idle.fbx b/dist-artifact/animations/Old Man Idle.fbxnew file mode 100644index 000000000..008bf7d39Binary files /dev/null and b/dist-artifact/animations/Old Man Idle.fbx differdiff --git a/dist-artifact/animations/Praying.fbx b/dist-artifact/animations/Praying.fbxnew file mode 100644index 000000000..0c0c6e392Binary files /dev/null and b/dist-artifact/animations/Praying.fbx differdiff --git a/dist-artifact/animations/Reaction.fbx b/dist-artifact/animations/Reaction.fbxnew file mode 100644index 000000000..e14231714Binary files /dev/null and b/dist-artifact/animations/Reaction.fbx differdiff --git a/dist-artifact/animations/Removing Driver.fbx b/dist-artifact/animations/Removing Driver.fbxnew file mode 100644index 000000000..d2b6c6b12Binary files /dev/null and b/dist-artifact/animations/Removing Driver.fbx differdiff --git a/dist-artifact/animations/Rumba Dancing.fbx b/dist-artifact/animations/Rumba Dancing.fbxnew file mode 100644index 000000000..4827bbdc4Binary files /dev/null and b/dist-artifact/animations/Rumba Dancing.fbx differdiff --git a/dist-artifact/animations/Shoved Reaction With Spin.fbx b/dist-artifact/animations/Shoved Reaction With Spin.fbxnew file mode 100644index 000000000..e25d3fa9aBinary files /dev/null and b/dist-artifact/animations/Shoved Reaction With Spin.fbx differdiff --git a/dist-artifact/animations/Silly Dancing.fbx b/dist-artifact/animations/Silly Dancing.fbxnew file mode 100644index 000000000..be6966da5Binary files /dev/null and b/dist-artifact/animations/Silly Dancing.fbx differdiff --git a/dist-artifact/animations/Sitting Clap.fbx b/dist-artifact/animations/Sitting Clap.fbxnew file mode 100644index 000000000..2ba238f91Binary files /dev/null and b/dist-artifact/animations/Sitting Clap.fbx differdiff --git a/dist-artifact/animations/Sitting Laughing.fbx b/dist-artifact/animations/Sitting Laughing.fbxnew file mode 100644index 000000000..715d4bfa5Binary files /dev/null and b/dist-artifact/animations/Sitting Laughing.fbx differdiff --git a/dist-artifact/animations/Standing Cover Turn.fbx b/dist-artifact/animations/Standing Cover Turn.fbxnew file mode 100644index 000000000..618b9feb8Binary files /dev/null and b/dist-artifact/animations/Standing Cover Turn.fbx differdiff --git a/dist-artifact/animations/Stepping Backward.fbx b/dist-artifact/animations/Stepping Backward.fbxnew file mode 100644index 000000000..cc1761563Binary files /dev/null and b/dist-artifact/animations/Stepping Backward.fbx differdiff --git a/dist-artifact/animations/Taunt.fbx b/dist-artifact/animations/Taunt.fbxnew file mode 100644index 000000000..9ce3ecea5Binary files /dev/null and b/dist-artifact/animations/Taunt.fbx differdiff --git a/dist-artifact/animations/Thriller Part 3.fbx b/dist-artifact/animations/Thriller Part 3.fbxnew file mode 100644index 000000000..cb79ebd8bBinary files /dev/null and b/dist-artifact/animations/Thriller Part 3.fbx differdiff --git a/dist-artifact/animations/Walk Strafe Left.fbx b/dist-artifact/animations/Walk Strafe Left.fbxnew file mode 100644index 000000000..71db4e322Binary files /dev/null and b/dist-artifact/animations/Walk Strafe Left.fbx differdiff --git a/dist-artifact/animations/manifest.json b/dist-artifact/animations/manifest.jsonnew file mode 100644index 000000000..b6f2105df--- /dev/null+++ b/dist-artifact/animations/manifest.json@@ -0,0 +1,128 @@+[+ {+ "name": "idle",+ "url": "/animations/Old Man Idle.fbx",+ "label": "Idle",+ "icon": "🧍",+ "loop": true+ },+ {+ "name": "dance",+ "url": "/animations/Hip Hop Dancing.fbx",+ "label": "Dance",+ "icon": "💃",+ "loop": true+ },+ {+ "name": "celebrate",+ "url": "/animations/Joyful Jump.fbx",+ "label": "Celebrate",+ "icon": "🎉",+ "loop": false+ },+ {+ "name": "angry",+ "url": "/animations/Angry.fbx",+ "label": "Angry",+ "icon": "😡",+ "loop": false+ },+ {+ "name": "defeated",+ "url": "/animations/Defeated.fbx",+ "label": "Defeated",+ "icon": "😞",+ "loop": false+ },+ {+ "name": "dying",+ "url": "/animations/Dying.fbx",+ "label": "Dying",+ "icon": "💀",+ "loop": false+ },+ {+ "name": "falling",+ "url": "/animations/Falling.fbx",+ "label": "Falling",+ "icon": "🪂",+ "loop": false+ },+ {+ "name": "jump",+ "url": "/animations/Joyful Jump.fbx",+ "label": "Jump",+ "icon": "🦘",+ "loop": false+ },+ {+ "name": "kiss",+ "url": "/animations/Kiss.fbx",+ "label": "Kiss",+ "icon": "💋",+ "loop": false+ },+ {+ "name": "pray",+ "url": "/animations/Praying.fbx",+ "label": "Pray",+ "icon": "🙏",+ "loop": false+ },+ {+ "name": "reaction",+ "url": "/animations/Reaction.fbx",+ "label": "Reaction",+ "icon": "😲",+ "loop": false+ },+ {+ "name": "rumba",+ "url": "/animations/Rumba Dancing.fbx",+ "label": "Rumba",+ "icon": "🕺",+ "loop": true+ },+ {+ "name": "silly",+ "url": "/animations/Silly Dancing.fbx",+ "label": "Silly Dance",+ "icon": "🤪",+ "loop": true+ },+ {+ "name": "sitclap",+ "url": "/animations/Sitting Clap.fbx",+ "label": "Sit Clap",+ "icon": "👏",+ "loop": false+ },+ {+ "name": "sitlaugh",+ "url": "/animations/Sitting Laughing.fbx",+ "label": "Sit Laugh",+ "icon": "😂",+ "loop": false+ },+ {+ "name": "taunt",+ "url": "/animations/Taunt.fbx",+ "label": "Taunt",+ "icon": "😝",+ "loop": false+ },+ {+ "name": "thriller",+ "url": "/animations/Thriller Part 3.fbx",+ "label": "Thriller",+ "icon": "🧟",+ "loop": true+ },+ {+ "name": "capoeira",+ "url": "/animations/Capoeira.fbx",+ "label": "Capoeira",+ "icon": "🥋",+ "loop": true+ }+]diff --git a/dist-artifact/animations/presets.json b/dist-artifact/animations/presets.jsonnew file mode 100644index 000000000..508658819--- /dev/null+++ b/dist-artifact/animations/presets.json@@ -0,0 +1,92 @@+[+ {+ "name": "idle",+ "url": "/animations/robotexpressive.glb",+ "clipName": "Idle",+ "loop": true,+ "source": "preset",+ "label": "Idle",+ "icon": "🧍"+ },+ {+ "name": "wave",+ "url": "/animations/robotexpressive.glb",+ "clipName": "Wave",+ "loop": false,+ "source": "preset",+ "label": "Wave",+ "icon": "👋"+ },+ {+ "name": "nod",+ "url": "/animations/robotexpressive.glb",+ "clipName": "Yes",+ "loop": false,+ "source": "preset",+ "label": "Nod",+ "icon": "✅"+ },+ {+ "name": "shrug",+ "url": "/animations/robotexpressive.glb",+ "clipName": "No",+ "loop": false,+ "source": "preset",+ "label": "Shrug",+ "icon": "🚫"+ },+ {+ "name": "thinking",+ "url": "/animations/robotexpressive.glb",+ "clipName": "Sitting",+ "loop": true,+ "source": "preset",+ "label": "Thinking",+ "icon": "🤔"+ },+ {+ "name": "celebrate",+ "url": "/animations/robotexpressive.glb",+ "clipName": "ThumbsUp",+ "loop": false,+ "source": "preset",+ "label": "Celebrate",+ "icon": "🎉"+ },+ {+ "name": "typing",+ "url": "/animations/robotexpressive.glb",+ "clipName": "Standing",+ "loop": true,+ "source": "preset",+ "label": "Typing",+ "icon": "⌨️"+ },+ {+ "name": "walking",+ "url": "/animations/robotexpressive.glb",+ "clipName": "Walking",+ "loop": true,+ "source": "preset",+ "label": "Walking",+ "icon": "🚶"+ },+ {+ "name": "running",+ "url": "/animations/robotexpressive.glb",+ "clipName": "Running",+ "loop": true,+ "source": "preset",+ "label": "Running",+ "icon": "🏃"+ },+ {+ "name": "dance",+ "url": "/animations/robotexpressive.glb",+ "clipName": "Dance",+ "loop": true,+ "source": "preset",+ "label": "Dance",+ "icon": "💃"+ }+]diff --git a/dist-artifact/animations/robotexpressive.glb b/dist-artifact/animations/robotexpressive.glbnew file mode 100644index 000000000..6fec9cfb4Binary files /dev/null and b/dist-artifact/animations/robotexpressive.glb differdiff --git a/dist-artifact/animations/soldier.glb b/dist-artifact/animations/soldier.glbnew file mode 100644index 000000000..1788f122dBinary files /dev/null and b/dist-artifact/animations/soldier.glb differdiff --git a/dist-artifact/artifact.js b/dist-artifact/artifact.jsnew file mode 100644index 000000000..77b8868ae--- /dev/null+++ b/dist-artifact/artifact.js@@ -0,0 +1 @@+!function(){"use strict";!async function(){const t=document.getElementById("agent3d");if(!t)return;t.style.cssText="position: relative; width: 100%; height: 100%; min-height: 400px; background: #000;";const e=document.createElement("div");e.className="agent3d-caption",e.style.cssText="\n\t\tposition: absolute;\n\t\tbottom: 0;\n\t\tleft: 0;\n\t\tright: 0;\n\t\tbackground: rgba(0, 0, 0, 0.6);\n\t\tcolor: #fff;\n\t\tpadding: 12px 16px;\n\t\tfont-family: system-ui, -apple-system, sans-serif;\n\t\tfont-size: 14px;\n\t\tz-index: 5;\n\t\ttext-align: center;\n\t",e.textContent="Loading...",t.appendChild(e);const n=document.querySelector('script[type="application/json"][id="agent3d-config"]'),a=n?JSON.parse(n.textContent):{},o=a.agentId||t.dataset.agentId,i=a.origin||t.dataset.origin||"https://3dagent.vercel.app";if(o)try{let n=function(){requestAnimationFrame(n),x.update(),u.render(m,w)};const a=await import("https://esm.sh/[email protected]"),{GLTFLoader:s}=await import("https://esm.sh/[email protected]/examples/jsm/loaders/GLTFLoader.js"),{OrbitControls:r}=await import("https://esm.sh/[email protected]/examples/jsm/controls/OrbitControls.js"),c=await fetch(`${i}/api/agents/${o}`,{mode:"cors",credentials:"omit"});if(!c.ok)return void(e.textContent="Agent not found");const d=(await c.json()).agent;e.textContent=d.name||"Agent";const p=t.clientWidth,l=t.clientHeight,m=new a.Scene;m.background=new a.Color(0),m.fog=new a.Fog(0,1,1e3);const g=new a.AmbientLight(16777215,1);m.add(g);const h=new a.DirectionalLight(16777215,.8);h.position.set(5,10,7),h.castShadow=!0,h.shadow.mapSize.width=2048,h.shadow.mapSize.height=2048,h.shadow.camera.near=.5,h.shadow.camera.far=500,m.add(h);const w=new a.PerspectiveCamera(75,p/l,.1,1e3);w.position.set(0,1.5,3);const u=new a.WebGLRenderer({antialias:!0,alpha:!1});u.setSize(p,l),u.setPixelRatio(window.devicePixelRatio),u.shadowMap.enabled=!0,u.shadowMap.type=a.PCFShadowMap,u.outputColorSpace=a.SRGBColorSpace,u.toneMapping=a.ACESFilmicToneMapping,u.toneMappingExposure=1;const f=t.querySelector("canvas");f&&f.remove(),t.insertBefore(u.domElement,e);const x=new r(w,u.domElement);x.enableDamping=!0,x.dampingFactor=.05,x.enableZoom=!0,x.autoRotate=!0,x.autoRotateSpeed=2,x.enablePan=!1,x.minDistance=2,x.maxDistance=10,n(),window.addEventListener("resize",()=>{const e=t.clientWidth,n=t.clientHeight;w.aspect=e/n,w.updateProjectionMatrix(),u.setSize(e,n)})}catch(s){console.error("[artifact] error:",s),e.textContent="Failed to load viewer"}else e.textContent="Missing agent ID"}()}();diff --git a/dist-artifact/artifact/README.md b/dist-artifact/artifact/README.mdnew file mode 100644index 000000000..b72a7ee94--- /dev/null+++ b/dist-artifact/artifact/README.md@@ -0,0 +1,30 @@+# Citing a 3D Agent artifact in Claude.ai++`GET https://3dagent.vercel.app/api/artifact?agent=<agentId>`++Paste the URL into a Claude.ai conversation. Claude recognises it as an HTML artifact and renders the interactive 3D agent inline.++## Worked example++```+Here's my agent for this conversation:+https://3dagent.vercel.app/api/artifact?agent=alice+```++Claude will embed the artifact and display the live 3D character.++## Parameters++| 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` |++## Notes++- The document returned is a single self-contained HTML page — no external requests except the UMD bundle and your agent's GLB asset.+- `frame-ancestors *` is set in the CSP so Claude.ai's sandboxed iframe can render it.+- Rate-limited at 600 req/min per IP (shared with widget reads).diff --git a/dist-artifact/artifact/index.html b/dist-artifact/artifact/index.htmlnew file mode 100644index 000000000..95a0a2d8c--- /dev/null+++ b/dist-artifact/artifact/index.html@@ -0,0 +1,177 @@+<!DOCTYPE html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>3D Agent Artifact Demo</title>+ <style>+ * {+ margin: 0;+ padding: 0;+ box-sizing: border-box;+ }++ body {+ font-family: system-ui, -apple-system, sans-serif;+ background: #0a0e27;+ color: #fff;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ min-height: 100vh;+ padding: 20px;+ }++ .container {+ max-width: 800px;+ width: 100%;+ }++ h1 {+ text-align: center;+ margin-bottom: 20px;+ font-size: 28px;+ }++ .info {+ background: rgba(255, 255, 255, 0.05);+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: 8px;+ padding: 16px;+ margin-bottom: 20px;+ font-size: 14px;+ line-height: 1.6;+ }++ .viewer-frame {+ background: #000;+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: 8px;+ overflow: hidden;+ aspect-ratio: 16 / 9;+ margin-bottom: 20px;+ }++ #agent3d {+ width: 100%;+ height: 100%;+ }++ .controls {+ display: flex;+ gap: 10px;+ flex-wrap: wrap;+ justify-content: center;+ }++ button {+ background: rgba(59, 130, 246, 0.8);+ border: none;+ color: #fff;+ padding: 10px 20px;+ border-radius: 6px;+ cursor: pointer;+ font-size: 14px;+ transition: background 0.2s;+ }++ button:hover {+ background: rgba(59, 130, 246, 1);+ }++ button:active {+ transform: scale(0.98);+ }++ .input-group {+ display: flex;+ gap: 10px;+ align-items: center;+ margin-bottom: 10px;+ }++ input {+ background: rgba(255, 255, 255, 0.1);+ border: 1px solid rgba(255, 255, 255, 0.2);+ color: #fff;+ padding: 8px 12px;+ border-radius: 4px;+ flex: 1;+ }++ input::placeholder {+ color: rgba(255, 255, 255, 0.5);+ }+ </style>+ </head>+ <body>+ <div class="container">+ <h1>3D Agent Artifact Viewer</h1>++ <div class="info">+ <p>+ This demo shows how a 3D Agent renders inside a Claude Artifact. The bundle is+ self-contained — no external dependencies or iframes.+ </p>+ </div>++ <div class="input-group">+ <input+ type="text"+ id="agentIdInput"+ placeholder="Enter agent ID (e.g., from URL ?agentId=123)"+ value=""+ />+ <button onclick="loadAgent()">Load</button>+ </div>++ <div class="viewer-frame">+ <div id="agent3d" data-origin="https://3dagent.vercel.app"></div>+ </div>++ <div class="controls">+ <button onclick="reloadAgent()">Reload</button>+ </div>+ </div>++ <!-- The artifact bundle -->+ <script src="artifact.js"></script>++ <script>+ function getAgentIdFromUrl() {+ const params = new URLSearchParams(window.location.search);+ return params.get('agentId') || localStorage.getItem('demo-agentId');+ }++ function loadAgent() {+ const input = document.getElementById('agentIdInput');+ const agentId = input.value.trim();++ if (!agentId) {+ alert('Please enter an agent ID');+ return;+ }++ localStorage.setItem('demo-agentId', agentId);+ const container = document.getElementById('agent3d');+ container.dataset.agentId = agentId;++ location.reload();+ }++ function reloadAgent() {+ location.reload();+ }++ window.addEventListener('DOMContentLoaded', () => {+ const agentId = getAgentIdFromUrl();+ if (agentId) {+ const container = document.getElementById('agent3d');+ container.dataset.agentId = agentId;+ document.getElementById('agentIdInput').value = agentId;+ }+ });+ </script>+ </body>+</html>diff --git a/dist-artifact/artifact/snippet.html b/dist-artifact/artifact/snippet.htmlnew file mode 100644index 000000000..6a4e61bca--- /dev/null+++ b/dist-artifact/artifact/snippet.html@@ -0,0 +1,12 @@+<!-- Paste this into a Claude Artifact to embed a 3D Agent -->+<script src="https://3dagent.vercel.app/artifact.js"></script>++<div id="agent3d" data-agent-id="your-agent-id-here" data-origin="https://3dagent.vercel.app"></div>++<style>+ #agent3d {+ width: 100%;+ height: 500px;+ display: block;+ }+</style>diff --git a/dist-artifact/avatars/cz.glb b/dist-artifact/avatars/cz.glbnew file mode 100644index 000000000..48f6b081eBinary files /dev/null and b/dist-artifact/avatars/cz.glb differdiff --git a/dist-artifact/cz/README.md b/dist-artifact/cz/README.mdnew file mode 100644index 000000000..7719d6556--- /dev/null+++ b/dist-artifact/cz/README.md@@ -0,0 +1,131 @@+# CZ Demo — Landing & Claim Flow++The CZ landing page is served at `/cz/` and provides:++- Full-bleed dark landing page with centered 3D agent avatar+- **Claim CZ** button — initiates wallet connection and claim flow+- **Copy embed** button — copies `<agent-3d>` snippet to clipboard+- Footer — displays on-chain state (chain, agentId, metadataURI)+- Custom event analytics via `window.dispatchEvent('cz-demo-event', ...)`++## Files++- `index.html` — Main landing page+- `boot.js` — Client-side initialization and claim flow UI+- `state.json` — On-chain state stub (updated by `prompts/cz-demo/01-pre-register.js`)++## State Schema++`state.json` is a JSON file with this shape:++```json+{+ "status": "pre-onchain" | "onchain",+ "chainId": null | number,+ "agentId": null | number,+ "metadataURI": null | string,+ "ownerAddress": null | "0x0..." | string,+ "avatarUrl": "/avatars/cz.glb" | string+}+```++**Fields:**++- `status` — `"pre-onchain"` (not yet registered) or `"onchain"` (registered)+- `chainId` — Chain ID (e.g., `8453` for Base, `84532` for Base Sepolia), or `null`+- `agentId` — Token ID from IdentityRegistry, or `null`+- `metadataURI` — IPFS/HTTPS URL of the full registration JSON, or `null`+- `ownerAddress` — Current owner address, `"0x0..."` (unclaimed), or `null`+- `avatarUrl` — GLB URL (default `/avatars/cz.glb`)++The landing page footer displays the state. In `pre-onchain`, it shows "Not yet onchain".++## Claim Flow++The `startClaim()` function in `src/cz-flow.js` handles:++1. **Pre-onchain** — Shows modal: "Claim opens when CZ is registered"+2. **Unclaimed** (`ownerAddress === "0x0..."`): Calls `IdentityRegistry.claim(agentId)`+3. **Demo EOA transfer**: Guides user through `transferOwner()`+4. **Already owned**: Shows modal with current owner++All steps emit progress via `onProgress({ step, status, txHash?, error? })` and fire custom events:++- `landing_view` — Page loaded+- `claim_start` — Claim button clicked+- `claim_wallet_connected` — Wallet connected (implicit in flow)+- `claim_tx_sent` — Transaction sent+- `claim_complete` — Claim successful+- `claim_error` — Error occurred+- `embed_copied` — Embed snippet copied++Listen for these on `window`:++```js+window.addEventListener('cz-demo-event', (e) => {+ console.log(e.detail.event, e.detail.props);+});+```++## Routing++The page is served at `/cz/` by the Vite dev server and Vercel (`public/cz/` → `/cz/`).++To add `/cz` (without trailing slash) or a custom route, edit:++- **Local dev**: `vite.config.js` — `vercel-rewrites` plugin+- **Production**: `vercel.json` — `rewrites` array++Example for `vercel.json`:++```json+{+ "rewrites": [+ { "source": "/cz", "destination": "/cz/" }+ ]+}+```++Then run `npm run deploy` to push changes.++## Integration with `prompts/cz-demo/01-pre-register.js`++When the onchain pre-registration is ready, that script will:++1. Deploy / verify the ERC-8004 IdentityRegistry if needed+2. Call `register()` with the GLB and metadata+3. Write an updated `public/cz/state.json` with real `chainId`, `agentId`, `metadataURI`, `ownerAddress`++The landing page will automatically reflect this state on next load.++## Accessibility++- Semantic `<h1>` for the headline+- `aria-label` on all buttons+- Focus rings visible (2px outline with 2px offset)+- Reduced motion support (`prefers-reduced-motion`)+- Modal keyboard-escapable++## Testing++```bash+npm run dev+# Open http://localhost:3000/cz/++# Should show:+# - Avatar loading from /avatars/cz.glb+# - "Claim CZ" button clickable+# - "Copy embed" button copies snippet to clipboard+# - Footer shows "Not yet onchain"+```++Test the claim flow:++```js+// Open browser console on /cz/+window.addEventListener('cz-demo-event', (e) => {+ console.log('CZ demo event:', e.detail);+});++// Click "Claim CZ" → follow wallet prompts+```diff --git a/dist-artifact/cz/boot.js b/dist-artifact/cz/boot.jsnew file mode 100644index 000000000..e9a3824c9--- /dev/null+++ b/dist-artifact/cz/boot.js@@ -0,0 +1,188 @@+/**+ * CZ landing page initialization — loads state, wires up CTAs, handles claim flow.+ */++import { startClaim, mountEmbedCopy, fireAnalytics } from '../../src/cz-flow.js';++async function init() {+ // Load state+ let state = {+ status: 'pre-onchain',+ chainId: null,+ agentId: null,+ metadataURI: null,+ ownerAddress: null,+ avatarUrl: '/avatars/cz.glb',+ };++ try {+ const res = await fetch('./state.json');+ if (res.ok) {+ state = await res.json();+ }+ } catch (err) {+ console.warn('Failed to load state.json:', err);+ }++ // Update footer with state+ updateFooter(state);++ // Wire up claim button+ const claimBtn = document.getElementById('cz-claim-btn');+ if (claimBtn) {+ claimBtn.addEventListener('click', () => handleClaimClick(state));+ }++ // Wire up embed copy+ const embedContainer = document.getElementById('cz-embed-container');+ if (embedContainer) {+ mountEmbedCopy(embedContainer, { state });+ }++ // Fire landing view event+ fireAnalytics('landing_view', { status: state.status });+}++function updateFooter(state) {+ const footer = document.getElementById('cz-footer');+ if (!footer) return;++ if (state.status === 'pre-onchain') {+ footer.innerHTML = `+ <p>Not yet onchain</p>+ `;+ } else {+ const chainName = getChainName(state.chainId);+ footer.innerHTML = `+ <p><strong>Chain:</strong> ${chainName}</p>+ <p><strong>Agent ID:</strong> ${state.agentId}</p>+ ${state.metadataURI ? `<p><strong>Metadata:</strong> <code>${truncate(state.metadataURI, 40)}</code></p>` : ''}+ `;+ }+}++function getChainName(chainId) {+ const chains = {+ 1: 'Ethereum',+ 8453: 'Base',+ 84532: 'Base Sepolia',+ };+ return chains[chainId] || `Chain ${chainId}`;+}++function truncate(str, len) {+ return str.length > len ? str.slice(0, len - 3) + '…' : str;+}++async function handleClaimClick(state) {+ const claimBtn = document.getElementById('cz-claim-btn');+ const modal = document.getElementById('cz-claim-modal');++ if (!modal) return;++ fireAnalytics('claim_start', {});++ // Show modal with spinner+ modal.style.display = 'flex';+ const content = document.getElementById('cz-modal-content');+ const closeBtn = document.getElementById('cz-modal-close');++ content.innerHTML = `+ <div class="modal-spinner"></div>+ <p>Initializing claim flow…</p>+ `;++ closeBtn.addEventListener('click', () => {+ modal.style.display = 'none';+ });++ modal.addEventListener('click', (e) => {+ if (e.target === modal) modal.style.display = 'none';+ });++ // Run claim flow+ const result = await startClaim({+ state,+ onProgress: (progress) => {+ updateModal(progress, state);+ },+ });++ if (result.ok) {+ if (result.message === 'pre_onchain') {+ content.innerHTML = `+ <h3 style="margin:0 0 1rem">Coming Soon</h3>+ <p>CZ is not yet registered on-chain. Claiming opens once the registration is complete.</p>+ <button class="modal-close-btn" onclick="document.getElementById('cz-claim-modal').style.display='none'">OK</button>+ `;+ } else if (result.message === 'already_owned') {+ content.innerHTML = `+ <h3 style="margin:0 0 1rem">Already Claimed</h3>+ <p>This agent is already owned by <code>${truncate(state.ownerAddress, 20)}</code>.</p>+ <button class="modal-close-btn" onclick="document.getElementById('cz-claim-modal').style.display='none'">OK</button>+ `;+ } else if (result.message === 'transfer_available') {+ content.innerHTML = `+ <h3 style="margin:0 0 1rem">Transfer Ownership</h3>+ <p>This agent can be transferred to your wallet. Follow the prompts to continue.</p>+ <button class="modal-close-btn" onclick="document.getElementById('cz-claim-modal').style.display='none'">OK</button>+ `;+ } else {+ content.innerHTML = `+ <h3 style="margin:0 0 1rem">Claim Successful</h3>+ <p>Transaction: <code>${result.txHash}</code></p>+ <button class="modal-close-btn" onclick="document.getElementById('cz-claim-modal').style.display='none'">OK</button>+ `;+ }+ } else {+ content.innerHTML = `+ <h3 style="margin:0 0 1rem">Error</h3>+ <p>${result.error}</p>+ <button class="modal-close-btn" onclick="document.getElementById('cz-claim-modal').style.display='none'">Dismiss</button>+ `;+ }+}++function updateModal(progress, state) {+ const content = document.getElementById('cz-modal-content');+ const { step, status, error } = progress;++ if (error) {+ content.innerHTML = `+ <h3 style="margin:0 0 1rem">Error</h3>+ <p>${error}</p>+ `;+ return;+ }++ const messages = {+ connect_wallet: {+ connecting: 'Connecting wallet…',+ connected: `Connected: ${progress.address?.slice(0, 10)}…`,+ },+ check_state: {+ pre_onchain: 'Checking agent status…',+ },+ claim: {+ submitting: 'Submitting claim…',+ pending: 'Waiting for confirmation…',+ confirmed: 'Claim confirmed!',+ already_owned: 'Already owned.',+ },+ transfer: {+ guide: 'Transfer available. Approve in your wallet…',+ },+ };++ const msg = messages[step]?.[status] || `${step}: ${status}`;+ content.innerHTML = `+ <div class="modal-spinner"></div>+ <p>${msg}</p>+ `;+}++if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', init);+} else {+ init();+}diff --git a/dist-artifact/cz/index.html b/dist-artifact/cz/index.htmlnew file mode 100644index 000000000..38d649ee6--- /dev/null+++ b/dist-artifact/cz/index.html@@ -0,0 +1,321 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <title>Claim CZ · 3D Agent</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <meta name="description" content="Meet CZ — an embodied 3D AI agent." />+ <meta name="theme-color" content="#000000" />+ <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: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ padding: 24px;+ }++ .cz-hero {+ width: 100%;+ max-width: 600px;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 2rem;+ }++ .cz-avatar-container {+ width: 100%;+ max-width: 400px;+ aspect-ratio: 1;+ border-radius: 12px;+ overflow: hidden;+ box-shadow: 0 20px 60px rgba(0, 0, 0, 0.4);+ }++ agent-3d {+ width: 100%;+ height: 100%;+ }++ .cz-content {+ text-align: center;+ width: 100%;+ }++ h1 {+ font-size: 2.5rem;+ margin: 0 0 0.5rem;+ letter-spacing: -0.02em;+ font-weight: 300;+ }++ .cz-subhead {+ font-size: 1.1rem;+ color: rgba(255, 255, 255, 0.6);+ margin: 0 0 2rem;+ line-height: 1.6;+ }++ .cz-cta-group {+ display: flex;+ flex-direction: column;+ gap: 12px;+ width: 100%;+ }++ button {+ padding: 14px 24px;+ border: none;+ border-radius: 10px;+ font-size: 15px;+ font-weight: 600;+ cursor: pointer;+ transition: all 0.2s ease;+ }++ #cz-claim-btn {+ background: linear-gradient(135deg, var(--accent), var(--accent2));+ color: #fff;+ }++ #cz-claim-btn:hover {+ transform: translateY(-2px);+ box-shadow: 0 8px 24px rgba(106, 92, 255, 0.3);+ }++ #cz-claim-btn:focus {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+ }++ #cz-claim-btn:active {+ transform: translateY(0);+ }++ #cz-embed-container {+ display: flex;+ }++ #cz-embed-copy {+ background: rgba(255, 255, 255, 0.1);+ border: 1px solid rgba(255, 255, 255, 0.2);+ color: #eee;+ width: 100%;+ }++ #cz-embed-copy:hover {+ background: rgba(255, 255, 255, 0.15);+ border-color: rgba(255, 255, 255, 0.3);+ }++ #cz-embed-copy:focus {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+ }++ .cz-footer {+ margin-top: 3rem;+ padding-top: 2rem;+ border-top: 1px solid rgba(255, 255, 255, 0.1);+ font-size: 0.875rem;+ color: rgba(255, 255, 255, 0.5);+ width: 100%;+ text-align: center;+ }++ .cz-footer p {+ margin: 0.5rem 0;+ }++ .cz-footer code {+ background: rgba(255, 255, 255, 0.05);+ padding: 2px 6px;+ border-radius: 4px;+ font-family: 'Courier New', monospace;+ font-size: 0.8rem;+ color: rgba(255, 255, 255, 0.7);+ }++ /* Modal */+ #cz-claim-modal {+ display: none;+ position: fixed;+ top: 0;+ left: 0;+ right: 0;+ bottom: 0;+ background: rgba(0, 0, 0, 0.7);+ z-index: 2000;+ align-items: center;+ justify-content: center;+ padding: 24px;+ }++ .cz-modal-dialog {+ background: #14141c;+ border: 1px solid #2a2a36;+ border-radius: 16px;+ padding: 32px;+ max-width: 420px;+ width: 100%;+ position: relative;+ box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);+ }++ #cz-modal-close {+ position: absolute;+ top: 16px;+ right: 16px;+ background: none;+ border: none;+ color: rgba(255, 255, 255, 0.5);+ cursor: pointer;+ padding: 8px;+ font-size: 1.5rem;+ display: flex;+ align-items: center;+ justify-content: center;+ }++ #cz-modal-close:hover {+ color: rgba(255, 255, 255, 0.8);+ }++ #cz-modal-content {+ text-align: center;+ min-height: 100px;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ }++ #cz-modal-content h3 {+ font-size: 1.2rem;+ font-weight: 600;+ }++ #cz-modal-content p {+ color: rgba(255, 255, 255, 0.7);+ margin: 0.5rem 0;+ line-height: 1.5;+ }++ #cz-modal-content code {+ background: rgba(255, 255, 255, 0.05);+ padding: 4px 8px;+ border-radius: 4px;+ font-family: 'Courier New', monospace;+ font-size: 0.85rem;+ color: rgba(255, 255, 255, 0.8);+ word-break: break-all;+ }++ .modal-spinner {+ width: 40px;+ height: 40px;+ border: 3px solid rgba(106, 92, 255, 0.2);+ border-top-color: var(--accent);+ border-radius: 50%;+ animation: spin 0.8s linear infinite;+ margin-bottom: 1rem;+ }++ @keyframes spin {+ to {+ transform: rotate(360deg);+ }+ }++ .modal-close-btn {+ margin-top: 1.5rem;+ width: 100%;+ background: linear-gradient(135deg, var(--accent), var(--accent2));+ color: #fff;+ }++ .modal-close-btn:hover {+ transform: translateY(-2px);+ box-shadow: 0 8px 24px rgba(106, 92, 255, 0.3);+ }++ /* Responsive */+ @media (max-width: 640px) {+ h1 {+ font-size: 2rem;+ }++ .cz-hero {+ gap: 1.5rem;+ }++ .cz-avatar-container {+ max-width: 100%;+ }+ }++ /* Reduced motion */+ @media (prefers-reduced-motion: reduce) {+ button {+ transition: none;+ }++ .modal-spinner {+ animation: none;+ border-top-color: var(--accent);+ }+ }+ </style>+</head>+<body>+ <div class="cz-hero">+ <div class="cz-avatar-container">+ <agent-3d src="/avatars/cz.glb" eager></agent-3d>+ </div>++ <div class="cz-content">+ <h1>Meet CZ</h1>+ <p class="cz-subhead">An embodied 3D AI agent built for the Ethereum ecosystem.</p>++ <div class="cz-cta-group">+ <button id="cz-claim-btn" aria-label="Claim CZ agent ownership">Claim CZ</button>+ <div id="cz-embed-container"></div>+ </div>+ </div>++ <div class="cz-footer" id="cz-footer">+ <p>Not yet onchain</p>+ </div>+ </div>++ <!-- Claim Modal -->+ <div id="cz-claim-modal">+ <div class="cz-modal-dialog">+ <button id="cz-modal-close" aria-label="Close claim dialog">×</button>+ <div id="cz-modal-content">+ <div class="modal-spinner"></div>+ <p>Loading…</p>+ </div>+ </div>+ </div>++ <script type="module" src="./boot.js"></script>+</body>+</html>diff --git a/dist-artifact/cz/offline/README.md b/dist-artifact/cz/offline/README.mdnew file mode 100644index 000000000..103548d5e--- /dev/null+++ b/dist-artifact/cz/offline/README.md@@ -0,0 +1,206 @@+# CZ Offline Fallback Demo++This directory contains the offline fallback for the CZ demo — a self-contained, zero-network-dependency copy of the demo that the operator can display if live internet fails during the event.++## Overview++**Purpose:** Keep the demo running when the internet dies, RPC node is down, or the staging server is unreachable.++**File:** `index.html` — standalone HTML page with embedded assets.++**Network:** Zero external dependencies after initial page load. Avatar and state are served from origin only.++**Usage:** Open `https://3dagent.vercel.app/cz/offline/` in a browser, or `http://localhost:3000/cz/offline/` for local dev.++---++## 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)+- **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)+- **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++---++## Testing the Offline Fallback++### Test 1: Network Throttling+```bash+# Open DevTools → Network tab+# Set throttling to "Offline"+# Reload the page+# Avatar and claim flow should still work+```++### Test 2: Hard Offline (Kill WiFi)+```bash+# Open /cz/offline/ in a browser+# Physically unplug ethernet or disable WiFi+# Page should still display avatar and respond to clicks+```++### Test 3: Origin Unreachable+```bash+# Open /cz/offline/ normally+# Block the origin in DevTools (DevTools → Network → Disable)+# Reload page (from browser cache)+# Fallback image and claim flow work+```++### Test 4: Timing (Dry Run)+```bash+# Open /cz/offline/+# Click "Claim Agent" button+# Observe:+# - First modal appears at 0ms: "Initializing…"+# - Second modal at 800ms: "Connecting…"+# - Confetti at 3200ms+# Total: ~4 seconds from click to success+```++---++## 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 |++---++## 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+// etc.+```++### 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 */+```++### 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';+ ```++---++## 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+- [ ] Parameterize agentId and chain from URL query params+- [ ] Add pre-recorded video loop of agent interaction (if available)+- [ ] Support keyboard controls (arrow keys for camera, Space to claim)++---++## Files++- `index.html` — Main offline page (this is all you need)+- `README.md` — This file++---++## 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)++---++## Contact / Issues++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/dist-artifact/cz/offline/index.html b/dist-artifact/cz/offline/index.htmlnew file mode 100644index 000000000..d40525829--- /dev/null+++ b/dist-artifact/cz/offline/index.html@@ -0,0 +1,445 @@+<!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>++ <div class="container">+ <div class="avatar-container">+ <canvas id="viewer"></canvas>+ <img id="fallback" class="fallback-image" alt="CZ Avatar" />+ </div>+ </div>++ <div class="modal" id="modal">+ <div class="modal-content">+ <div id="modal-body"></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>+ <div class="footer-item">•</div>+ <div class="footer-item">+ Chain: <span class="code">Base Sepolia</span>+ </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++ 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++ function showModal(html) {+ modalBody.innerHTML = html;+ modal.classList.add('active');+ }++ function hideModal() {+ modal.classList.remove('active');+ }++ // Simulate claim flow+ function handleClaimClick() {+ showModal(`+ <div class="spinner"></div>+ <p>Initializing claim flow...</p>+ `);++ setTimeout(() => {+ showModal(`+ <div class="spinner"></div>+ <p>Connecting wallet...</p>+ `);+ }, 800);++ setTimeout(() => {+ showModal(`+ <div class="spinner"></div>+ <p>Submitting claim...</p>+ `);+ }, 1600);++ setTimeout(() => {+ showModal(`+ <div class="spinner"></div>+ <p>Waiting for confirmation...</p>+ `);+ }, 2400);++ 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 = `+ @keyframes fall-${i} {+ to {+ transform: translateY(${window.innerHeight + 20}px) rotate(720deg);+ opacity: 0;+ }+ }+ `;+ const style = document.createElement('style');+ style.textContent = keyframes;+ document.head.appendChild(style);++ confetti.style.animation = `fall-${i} ${duration}s ease-in forwards`;++ 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;+ }++ // 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;+ }++ // 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();+ }+ }++ 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 = `+ <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);+ });+ }++ console.log('CZ Offline Demo initialized');+ </script>+</body>+</html>diff --git a/dist-artifact/cz/state.json b/dist-artifact/cz/state.jsonnew file mode 100644index 000000000..e31fd0a94--- /dev/null+++ b/dist-artifact/cz/state.json@@ -0,0 +1,8 @@+{+ "status": "pre-onchain",+ "chainId": null,+ "agentId": null,+ "metadataURI": null,+ "ownerAddress": null,+ "avatarUrl": "/avatars/cz.glb"+}diff --git a/dist-artifact/dashboard/actions.html b/dist-artifact/dashboard/actions.htmlnew file mode 100644index 000000000..493e61cab--- /dev/null+++ b/dist-artifact/dashboard/actions.html@@ -0,0 +1,602 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <title>Action Log — 3D Agent</title>+ <style>+ :root {+ color-scheme: dark;+ --accent: #6a5cff;+ --accent2: #ff5ca8;+ --border: #22222e;+ --bg: #0b0b10;+ --panel: #14141c;+ }+ * {+ box-sizing: border-box;+ }+ body {+ font:+ 15px/1.55 system-ui,+ -apple-system,+ Segoe UI,+ Roboto,+ sans-serif;+ color: #eee;+ margin: 0;+ background: var(--bg);+ min-height: 100vh;+ }+ a {+ color: #9a8cff;+ text-decoration: none;+ }+ .container {+ max-width: 900px;+ margin: 0 auto;+ padding: 28px;+ }+ h1 {+ font-size: 22px;+ margin: 0 0 6px;+ letter-spacing: -0.01em;+ }+ .header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ margin-bottom: 20px;+ gap: 20px;+ flex-wrap: wrap;+ }+ .agent-info {+ flex: 1;+ min-width: 300px;+ }+ .sub {+ color: #888;+ margin: 4px 0 0;+ font-size: 14px;+ }+ .signer-pill {+ display: inline-block;+ background: rgba(106, 92, 255, 0.15);+ border: 1px solid var(--accent);+ border-radius: 999px;+ padding: 4px 12px;+ font-size: 13px;+ margin-top: 8px;+ color: #aaa;+ font-family: monospace;+ }+ .signer-pill.verified {+ background: rgba(34, 197, 94, 0.1);+ border-color: #22c55e;+ color: #86efac;+ }+ .actions-toolbar {+ display: flex;+ gap: 8px;+ align-items: center;+ margin-bottom: 20px;+ flex-wrap: wrap;+ }+ .filter-chip {+ padding: 6px 14px;+ border: 1px solid var(--border);+ background: transparent;+ color: #aaa;+ border-radius: 999px;+ cursor: pointer;+ font-size: 13px;+ transition: all 0.2s;+ }+ .filter-chip:hover {+ border-color: var(--accent);+ color: #fff;+ }+ .filter-chip.active {+ background: var(--accent);+ border-color: var(--accent);+ color: #fff;+ }+ .export-btn {+ margin-left: auto;+ padding: 6px 14px;+ border: 1px solid var(--border);+ background: transparent;+ color: #aaa;+ border-radius: 4px;+ cursor: pointer;+ font-size: 13px;+ transition: all 0.2s;+ }+ .export-btn:hover {+ border-color: var(--accent);+ color: var(--accent);+ }+ .timeline {+ display: flex;+ flex-direction: column;+ gap: 12px;+ }+ .action-row {+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 6px;+ padding: 14px;+ cursor: pointer;+ transition: all 0.2s;+ }+ .action-row:hover {+ border-color: var(--accent);+ background: rgba(106, 92, 255, 0.04);+ }+ .action-row.expanded {+ border-color: var(--accent);+ }+ .action-row-header {+ display: flex;+ align-items: center;+ gap: 12px;+ }+ .action-icon {+ width: 20px;+ height: 20px;+ display: flex;+ align-items: center;+ justify-content: center;+ font-size: 12px;+ border-radius: 3px;+ flex-shrink: 0;+ }+ .action-icon.speak {+ background: rgba(106, 92, 255, 0.2);+ color: #a5b4fc;+ }+ .action-icon.remember {+ background: rgba(34, 197, 94, 0.2);+ color: #86efac;+ }+ .action-icon.sign {+ background: rgba(168, 85, 247, 0.2);+ color: #d8b4fe;+ }+ .action-icon.skill-done {+ background: rgba(59, 130, 246, 0.2);+ color: #93c5fd;+ }+ .action-icon.validate {+ background: rgba(249, 115, 22, 0.2);+ color: #fed7aa;+ }+ .action-icon.load-end {+ background: rgba(236, 72, 153, 0.2);+ color: #f472b6;+ }+ .action-summary {+ flex: 1;+ display: flex;+ flex-direction: column;+ gap: 4px;+ min-width: 0;+ }+ .action-type {+ font-weight: 600;+ font-size: 14px;+ color: #fff;+ }+ .action-preview {+ color: #aaa;+ font-size: 13px;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }+ .action-meta {+ display: flex;+ align-items: center;+ gap: 12px;+ }+ .verify-badge {+ width: 20px;+ height: 20px;+ display: flex;+ align-items: center;+ justify-content: center;+ font-size: 12px;+ flex-shrink: 0;+ }+ .verify-badge.verified {+ color: #22c55e;+ }+ .verify-badge.unverified {+ color: #888;+ }+ .verify-badge.unsigned {+ color: #666;+ }+ .action-time {+ color: #666;+ font-size: 12px;+ flex-shrink: 0;+ }+ .action-time:hover {+ color: #aaa;+ }+ .action-detail {+ display: none;+ margin-top: 14px;+ padding-top: 14px;+ border-top: 1px solid var(--border);+ }+ .action-row.expanded .action-detail {+ display: block;+ }+ .json-block {+ background: rgba(0, 0, 0, 0.3);+ border: 1px solid var(--border);+ border-radius: 4px;+ padding: 12px;+ font-family: monospace;+ font-size: 12px;+ color: #888;+ overflow-x: auto;+ max-height: 300px;+ overflow-y: auto;+ }+ .empty-state {+ text-align: center;+ color: #666;+ padding: 40px 20px;+ }+ .empty-state-icon {+ font-size: 40px;+ margin-bottom: 12px;+ }+ .loading {+ text-align: center;+ color: #666;+ padding: 40px 20px;+ }+ .error-msg {+ background: rgba(239, 68, 68, 0.1);+ border: 1px solid #ef4444;+ color: #fca5a5;+ padding: 12px 14px;+ border-radius: 6px;+ margin-bottom: 20px;+ }+ .infinite-scroll-trigger {+ height: 1px;+ margin-top: 20px;+ }+ </style>+ </head>+ <body>+ <div class="container">+ <div class="header">+ <div class="agent-info">+ <h1 id="agent-name">Action Log</h1>+ <div class="sub" id="agent-id"></div>+ <div class="signer-pill" id="signer-pill" style="display: none"></div>+ </div>+ </div>++ <div id="error-msg"></div>++ <div class="actions-toolbar">+ <button class="filter-chip active" data-filter="all">All</button>+ <button class="filter-chip" data-filter="speak">Speak</button>+ <button class="filter-chip" data-filter="remember">Remember</button>+ <button class="filter-chip" data-filter="sign">Sign</button>+ <button class="filter-chip" data-filter="skill-done">Skill Done</button>+ <button class="filter-chip" data-filter="validate">Validate</button>+ <button class="filter-chip" data-filter="load-end">Load End</button>+ <button class="export-btn" id="export-btn">Download JSON</button>+ </div>++ <div id="timeline" class="timeline"></div>+ <div class="infinite-scroll-trigger" id="scroll-trigger"></div>+ </div>++ <script>+ const pageSize = 50;+ let currentFilter = 'all';+ let allActions = [];+ let nextCursor = null;+ let isLoading = false;+ let hasMore = true;++ const params = new URLSearchParams(location.search);+ const agentId = params.get('agent');+ if (!agentId) {+ showError('Missing ?agent= parameter.');+ document.body.innerHTML = '';+ document.body.appendChild(+ Object.assign(document.createElement('div'), {+ textContent: 'Missing ?agent= parameter. Expected: ?agent=<id>',+ style: 'color:#f87171;padding:20px;',+ }),+ );+ }++ // Auth check+ (async () => {+ try {+ const r = await fetch(`/api/agents/${agentId}/actions?limit=1`, {+ credentials: 'include',+ });+ if (r.status === 401) {+ window.location.href = `/login?next=/dashboard/actions.html?agent=${agentId}`;+ return;+ }+ if (r.status === 403) {+ showError('Not authorized to view this agent.');+ return;+ }+ if (r.status === 404) {+ showError('Agent not found.');+ return;+ }+ if (!r.ok) {+ showError(`Error ${r.status}`);+ return;+ }++ const data = await r.json();+ const { actions, nextCursor: nc } = data;++ // Fetch agent info+ const agentR = await fetch(`/api/agents/${agentId}`, {+ credentials: 'include',+ });+ if (agentR.ok) {+ const agentData = await agentR.json();+ const agent = agentData.agent;+ document.getElementById('agent-name').textContent = agent?.name || agentId;+ document.getElementById('agent-id').textContent = `${agentId}${+ agent?.wallet_address ? ` · ${agent.wallet_address.slice(0, 10)}…` : ''+ }`;++ if (agent?.wallet_address) {+ const pill = document.getElementById('signer-pill');+ pill.textContent = `Signed by ${agent.wallet_address.slice(0, 10)}…${agent.wallet_address.slice(+ -8,+ )}`;+ pill.className = 'signer-pill verified';+ pill.style.display = 'inline-block';+ }+ }++ // Load initial page+ nextCursor = nc;+ await loadMore();+ } catch (e) {+ showError(`Fetch failed: ${e.message}`);+ }+ })();++ // IntersectionObserver for infinite scroll+ const observer = new IntersectionObserver(+ (entries) => {+ if (entries[0].isIntersecting && !isLoading && hasMore) {+ loadMore();+ }+ },+ { rootMargin: '200px' },+ );++ observer.observe(document.getElementById('scroll-trigger'));++ // Load more actions+ async function loadMore() {+ if (isLoading || !hasMore) return;+ isLoading = true;++ try {+ const url = new URL(`/api/agents/${agentId}/actions`, window.location.origin);+ url.searchParams.set('limit', pageSize);+ if (nextCursor) {+ url.searchParams.set('cursor', nextCursor);+ }++ const r = await fetch(url, { credentials: 'include' });+ if (!r.ok) {+ hasMore = false;+ return;+ }++ const data = await r.json();+ const { actions, nextCursor: nc } = data;++ allActions.push(...actions);+ nextCursor = nc;+ hasMore = Boolean(nc);++ render();+ } catch (e) {+ console.error('loadMore failed:', e);+ } finally {+ isLoading = false;+ }+ }++ // Filter changes+ document.querySelectorAll('.filter-chip').forEach((btn) => {+ btn.addEventListener('click', () => {+ document+ .querySelectorAll('.filter-chip')+ .forEach((b) => b.classList.remove('active'));+ btn.classList.add('active');+ currentFilter = btn.dataset.filter;+ render();+ });+ });++ // Export+ document.getElementById('export-btn').addEventListener('click', () => {+ const filtered = getFiltered();+ const json = JSON.stringify(filtered, null, 2);+ const blob = new Blob([json], { type: 'application/json' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = `actions-${agentId}-${new Date().toISOString().split('T')[0]}.json`;+ a.click();+ URL.revokeObjectURL(url);+ });++ function getFiltered() {+ if (currentFilter === 'all') return allActions;+ return allActions.filter((a) => a.type === currentFilter);+ }++ function render() {+ const filtered = getFiltered();+ const timeline = document.getElementById('timeline');++ if (filtered.length === 0 && allActions.length === 0) {+ timeline.innerHTML =+ '<div class="empty-state"><div class="empty-state-icon">—</div><div>No actions yet.</div></div>';+ return;+ }++ if (filtered.length === 0) {+ timeline.innerHTML =+ '<div class="empty-state"><div class="empty-state-icon">—</div><div>No actions match this filter.</div></div>';+ return;+ }++ timeline.innerHTML = filtered.map((action) => renderRow(action)).join('');++ // Add expand listeners+ document.querySelectorAll('.action-row').forEach((row) => {+ row.addEventListener('click', () => {+ row.classList.toggle('expanded');+ });+ });+ }++ function renderRow(action) {+ const type = action.type;+ const preview = summarizePayload(action.payload);+ const timestamp = new Date(action.timestamp);+ const now = new Date();+ const relTime = formatRelativeTime(timestamp, now);++ let verifyIcon = '—';+ let verifyClass = 'unsigned';+ if (action.signature) {+ if (action.verified === true) {+ verifyIcon = '✓';+ verifyClass = 'verified';+ } else if (action.verified === false) {+ verifyIcon = '✗';+ verifyClass = 'unverified';+ }+ }++ return `+ <div class="action-row" data-id="${action.id}">+ <div class="action-row-header">+ <div class="action-icon ${type}">+ ${getTypeIcon(type)}+ </div>+ <div class="action-summary">+ <div class="action-type">${escapeHtml(type)}</div>+ <div class="action-preview">${escapeHtml(preview)}</div>+ </div>+ <div class="action-meta">+ <div class="verify-badge ${verifyClass}" title="${+ action.verified === true+ ? 'Verified'+ : action.verified === false+ ? 'Invalid signature'+ : 'Unsigned'+ }">${verifyIcon}</div>+ <div class="action-time" title="${timestamp.toISOString()}">${escapeHtml(relTime)}</div>+ </div>+ </div>+ <div class="action-detail">+ <div class="json-block">${escapeHtml(JSON.stringify(action.payload, null, 2))}</div>+ ${+ action.signer+ ? `<div style="margin-top:8px;color:#666;font-size:12px">Signer: <code style="color:#888">${escapeHtml(+ action.signer,+ )}</code></div>`+ : ''+ }+ </div>+ </div>+ `;+ }++ function getTypeIcon(type) {+ const icons = {+ speak: '💬',+ remember: '📝',+ sign: '✍️',+ 'skill-done': '✓',+ validate: '✔',+ 'load-end': '📦',+ };+ return icons[type] || '•';+ }++ function summarizePayload(payload) {+ if (typeof payload !== 'object' || !payload) return '(empty)';+ const keys = Object.keys(payload);+ if (keys.length === 0) return '(empty)';++ // For speak actions, show the text+ if (payload.text) return payload.text.slice(0, 80);++ // For remember, show content+ if (payload.content) return payload.content.slice(0, 80);++ // Generic: show key=value preview+ const parts = keys.slice(0, 2).map((k) => {+ const v = payload[k];+ if (typeof v === 'string') return `${k}=${v.slice(0, 30)}`;+ if (typeof v === 'number') return `${k}=${v}`;+ if (typeof v === 'boolean') return `${k}=${v}`;+ return `${k}=(object)`;+ });+ return parts.join(', ');+ }++ function formatRelativeTime(date, now) {+ const seconds = Math.floor((now - date) / 1000);++ if (seconds < 60) return `${seconds}s ago`;+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;+ if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;+ if (seconds < 604800) return `${Math.floor(seconds / 86400)}d ago`;++ const months = Math.floor(seconds / 2592000);+ if (months < 12) return `${months}mo ago`;++ return `${Math.floor(seconds / 31536000)}y ago`;+ }++ function showError(msg) {+ const el = document.getElementById('error-msg');+ el.innerHTML = `<div class="error-msg">${escapeHtml(msg)}</div>`;+ }++ function escapeHtml(text) {+ if (!text) return '';+ const map = {+ '&': '&',+ '<': '<',+ '>': '>',+ '"': '"',+ "'": ''',+ };+ return String(text).replace(/[&<>"']/g, (c) => map[c]);+ }+ </script>+ </body>+</html>diff --git a/dist-artifact/dashboard/dashboard.js b/dist-artifact/dashboard/dashboard.jsnew file mode 100644index 000000000..104f97500--- /dev/null+++ b/dist-artifact/dashboard/dashboard.js@@ -0,0 +1,2361 @@+// Dashboard single-file app. Uses native DOM — no framework.+// Keeps bundle small and ensures anything rendering <model-viewer> works without bundler.++export const state = { user: null };++export const api = {+ me: () => j('GET', '/api/auth/me'),+ listAvatars: () => j('GET', '/api/avatars?limit=100'),+ deleteAvatar: (id) => j('DELETE', `/api/avatars/${id}`),+ patchAvatar: (id, patch) => j('PATCH', `/api/avatars/${id}`, patch),+ presign: (body) => j('POST', '/api/avatars/presign', body),+ createAvatar: (body) => j('POST', '/api/avatars', body),+ listKeys: () => j('GET', '/api/keys'),+ createKey: (body) => j('POST', '/api/keys', body),+ revokeKey: (id) => j('DELETE', `/api/keys/${id}`),+ listWidgets: () => j('GET', '/api/widgets'),+ getWidget: (id) => j('GET', `/api/widgets/${encodeURIComponent(id)}`),+ patchWidget: (id, patch) => j('PATCH', `/api/widgets/${encodeURIComponent(id)}`, patch),+ deleteWidget: (id) => j('DELETE', `/api/widgets/${encodeURIComponent(id)}`),+ duplicateWidget: (id) => j('POST', `/api/widgets/${encodeURIComponent(id)}/duplicate`),+ widgetStats: (id) => j('GET', `/api/widgets/${encodeURIComponent(id)}/stats`),+ createAvatarSession: (id) => j('POST', `/api/avatars/${id}/session`),+ getAvatarVersions: (id) => j('GET', `/api/avatars/${id}/versions`),+ patchAgent: (agentId, patch) => j('PUT', `/api/agents/${agentId}`, patch),+};++async function j(method, path, body) {+ const res = await fetch(path, {+ method,+ credentials: 'include',+ headers: body ? { 'content-type': 'application/json' } : {},+ body: body ? JSON.stringify(body) : undefined,+ });+ const data = res.headers.get('content-type')?.includes('application/json')+ ? await res.json()+ : null;+ if (!res.ok)+ throw Object.assign(new Error((data && data.error_description) || res.statusText), {+ status: res.status,+ data,+ });+ return data;+}++export function signOut() {+ fetch('/api/auth/logout', { method: 'POST', credentials: 'include' }).finally(() => {+ try {+ localStorage.removeItem('3dagent:auth-hint');+ } catch {+ /* ignore */+ }+ location.href = '/';+ });+}++export function navigate(tab) {+ // Support #edit/<id> sub-routes for per-avatar edit screens.+ const [base, ...rest] = (tab || 'avatars').split('/');+ document+ .querySelectorAll('aside a')+ .forEach((a) => a.classList.toggle('active', a.dataset.tab === base));+ const main = document.getElementById('main');+ main.innerHTML = '';+ const renderer = tabs[base] || tabs.avatars;+ renderer(main, rest);+}++const tabs = {+ avatars: renderAvatars,+ create: renderCreate,+ edit: renderEdit,+ upload: renderUpload,+ widgets: renderWidgets,+ embed: renderEmbed,+ keys: renderKeys,+ mcp: renderMcp,+ billing: renderBilling,+};++// ── Avatars ─────────────────────────────────────────────────────────────────+async function renderAvatars(root) {+ root.innerHTML = `<h1>Your avatars</h1><p class="sub">Each avatar gets a stable URL and can be rendered in Claude or any app via MCP.</p><div id="list" class="cards"></div>`;+ const list = root.querySelector('#list');+ list.innerHTML = '<div class="muted">Loading…</div>';+ try {+ const { avatars } = await api.listAvatars();+ if (!avatars.length) {+ list.innerHTML = `<div class="empty">No avatars yet. <a href="#create">Take a selfie</a>, <a href="#upload">upload a .glb</a>, or <a href="/deploy">deploy a metadata-only agent on-chain</a>.</div>`;+ return;+ }+ list.innerHTML = '';+ for (const a of avatars) list.appendChild(avatarCard(a));+ } catch (e) {+ list.innerHTML = `<div class="err">${esc(e.message)}</div>`;+ }+}++function avatarCard(a) {+ const el = document.createElement('div');+ el.className = 'card';+ const preview = a.model_url+ ? `<model-viewer src="${attr(a.model_url)}" camera-controls auto-rotate shadow-intensity="1" exposure="1" tone-mapping="aces"></model-viewer>`+ : `<span>Private · preview requires signed URL</span>`;+ el.innerHTML = `+ <div class="preview">${preview}</div>+ <h3>${esc(a.name)}</h3>+ <p class="meta">${a.size_bytes ? fmtSize(a.size_bytes) : ''} · ${esc(a.visibility)} · ${new Date(a.created_at).toLocaleDateString()}</p>+ <div class="row" style="gap:6px; margin-bottom:10px">${a.tags.map((t) => `<span class="tag">${esc(t)}</span>`).join('')}</div>+ <div class="row" style="justify-content:space-between">+ <select data-vis>${['private', 'unlisted', 'public'].map((v) => `<option ${v === a.visibility ? 'selected' : ''} value="${v}">${v}</option>`).join('')}</select>+ <div class="row" style="gap:6px">+ <a class="btn sec" href="#edit/${encodeURIComponent(a.id)}">Edit</a>+ <button class="btn sec" data-replace>Replace GLB</button>+ <a class="btn sec" href="/deploy?avatar=${encodeURIComponent(a.id)}" title="Mint as ERC-8004 agent">Deploy on-chain</a>+ <button class="btn sec" data-del>Delete</button>+ </div>+ </div>+ `;+ el.querySelector('[data-vis]').addEventListener('change', async (e) => {+ try {+ await api.patchAvatar(a.id, { visibility: e.target.value });+ } catch (err) {+ alert(err.message);+ }+ });+ el.querySelector('[data-del]').addEventListener('click', async () => {+ if (!confirm(`Delete "${a.name}"?`)) return;+ try {+ await api.deleteAvatar(a.id);+ el.remove();+ } catch (err) {+ alert(err.message);+ }+ });+ el.querySelector('[data-replace]').addEventListener('click', () => replaceGlbFlow(a, el));+ return el;+}++// ── Replace GLB ─────────────────────────────────────────────────────────────+// Shows an inline warning banner on the card, then opens a file picker.+// Validates extension, MIME, and GLB magic number before uploading.+// Runs a Mixamo skeleton compatibility check and surfaces a warning if < 50%.+function replaceGlbFlow(a, cardEl) {+ if (cardEl.querySelector('[data-glb-warn]')) return; // already open++ const warn = document.createElement('div');+ warn.setAttribute('data-glb-warn', '');+ warn.style.cssText =+ 'margin:8px 0; padding:10px; background:rgba(255,165,0,.08); border:1px solid rgba(255,165,0,.25); border-radius:8px; font-size:12px; color:#d4aa44';+ warn.innerHTML = `+ <p style="margin:0 0 8px">⚠ This bypasses Avaturn — your avatar may not animate correctly if not rigged to the Mixamo skeleton.</p>+ <div class="row" style="gap:6px">+ <button class="btn" data-glb-pick style="font-size:12px;padding:6px 10px">Choose .glb file</button>+ <button class="btn sec" data-glb-cancel style="font-size:12px;padding:6px 10px">Cancel</button>+ </div>+ <input type="file" accept=".glb,model/gltf-binary" data-glb-file style="display:none">+ <div data-glb-progress style="margin-top:8px; min-height:1em"></div>+ `;+ cardEl.appendChild(warn);++ warn.querySelector('[data-glb-cancel]').addEventListener('click', () => warn.remove());+ warn.querySelector('[data-glb-pick]').addEventListener('click', () => {+ warn.querySelector('[data-glb-file]').click();+ });+ warn.querySelector('[data-glb-file]').addEventListener('change', async (e) => {+ const file = e.target.files[0];+ if (!file) return;+ const pick = warn.querySelector('[data-glb-pick]');+ const cancel = warn.querySelector('[data-glb-cancel]');+ pick.disabled = true;+ cancel.disabled = true;+ await doReplaceUpload(a, file, warn, cardEl);+ pick.disabled = false;+ cancel.disabled = false;+ });+}++async function doReplaceUpload(a, file, warnEl, cardEl) {+ const prog = warnEl.querySelector('[data-glb-progress]');+ const say = (msg, isError = false) => {+ prog.textContent = msg;+ prog.style.color = isError ? '#ffb3b3' : '#888';+ };++ // Extension check — reject .gltf and anything else+ if (!file.name.toLowerCase().endsWith('.glb')) {+ say('Only .glb files accepted. Separate .gltf + .bin packs are not supported.', true);+ return;+ }++ // MIME type check+ if (+ file.type &&+ file.type !== 'model/gltf-binary' &&+ file.type !== 'application/octet-stream'+ ) {+ say(`Unexpected file type "${file.type}". Expected model/gltf-binary.`, true);+ return;+ }++ // Magic number check: first 4 bytes must be 'glTF' (0x46546C67 little-endian)+ const header = await file.slice(0, 4).arrayBuffer();+ if (new DataView(header).getUint32(0, true) !== 0x46546c67) {+ say('Not a valid GLB \u2014 magic number check failed. Renamed files are rejected.', true);+ return;+ }++ say('Checking skeleton compatibility\u2026');+ const glbBuf = await file.arrayBuffer();+ const boneMatch = checkMixamoSkeleton(glbBuf);++ say('Requesting upload URL\u2026');+ try {+ const { upload_url, storage_key } = await api.presign({+ size_bytes: file.size,+ content_type: 'model/gltf-binary',+ });+ say(`Uploading ${fmtSize(file.size)}\u2026`);+ await uploadToR2(upload_url, file, (pct) => say(`Uploading ${pct}%\u2026`));+ say('Registering\u2026');+ const { avatar } = await api.createAvatar({+ storage_key,+ parent_avatar_id: a.id,+ name: a.name,+ description: a.description || undefined,+ visibility: a.visibility,+ tags: a.tags,+ size_bytes: file.size,+ content_type: 'model/gltf-binary',+ source: 'direct-upload',+ source_meta: { replaced_from: a.id },+ });++ // Refresh model-viewer preview if the new avatar is public/unlisted+ if (avatar.model_url) {+ const mv = cardEl.querySelector('model-viewer');+ if (mv) mv.src = avatar.model_url;+ }++ if (boneMatch !== null && boneMatch < 0.5) {+ say(+ `Uploaded. \u26a0 Animations may not play \u2014 skeleton mismatch (${Math.round(boneMatch * 100)}% Mixamo bone match).`,+ );+ } else {+ say('Replaced! Your agent now uses the new GLB.');+ }+ } catch (err) {+ say(err.message || 'Upload failed', true);+ }+}++// Parse the GLB JSON chunk and count Mixamo bone name matches.+// Reuses the same strip-prefix logic as AnimationManager._buildBoneNameMap.+// Returns a ratio 0..1, or null if the file has no parseable node names.+function checkMixamoSkeleton(buffer) {+ const MIXAMO_BONES = new Set([+ 'Hips',+ 'Spine',+ 'Spine1',+ 'Spine2',+ 'Neck',+ 'Head',+ 'LeftShoulder',+ 'LeftArm',+ 'LeftForeArm',+ 'LeftHand',+ 'RightShoulder',+ 'RightArm',+ 'RightForeArm',+ 'RightHand',+ 'LeftUpLeg',+ 'LeftLeg',+ 'LeftFoot',+ 'LeftToeBase',+ 'RightUpLeg',+ 'RightLeg',+ 'RightFoot',+ 'RightToeBase',+ ]);+ try {+ const view = new DataView(buffer);+ const chunkLen = view.getUint32(12, true);+ if (view.getUint32(16, true) !== 0x4e4f534a) return null; // chunk 0 is not JSON+ const json = JSON.parse(new TextDecoder().decode(new Uint8Array(buffer, 20, chunkLen)));+ const nodes = (json.nodes || []).filter((n) => n.name);+ if (!nodes.length) return null;+ const strip = (n) => n.replace(/^mixamorig\d*[_:]?/i, '').replace(/^Armature[_/]?/i, '');+ return nodes.filter((n) => MIXAMO_BONES.has(strip(n.name))).length / MIXAMO_BONES.size;+ } catch {+ return null;+ }+}++// ── Upload ──────────────────────────────────────────────────────────────────+function renderUpload(root) {+ root.innerHTML = `+ <h1>Upload avatar</h1><p class="sub">Upload a .glb file. It's stored on our CDN and made available via API and MCP.</p>+ <form id="up" class="card" style="max-width:520px">+ <label>File<input id="file" type="file" accept=".glb,model/gltf-binary" required></label>+ <label style="display:block;margin-top:12px">Name<input id="name" required maxlength="120" style="width:100%"></label>+ <label style="display:block;margin-top:12px">Description<textarea id="desc" rows="2" style="width:100%"></textarea></label>+ <label style="display:block;margin-top:12px">Visibility+ <select id="vis" style="width:100%">+ <option value="private">Private (only you)</option>+ <option value="unlisted">Unlisted (anyone with link)</option>+ <option value="public">Public (discoverable)</option>+ </select>+ </label>+ <label style="display:block;margin-top:12px">Tags (comma separated)<input id="tags" style="width:100%"></label>+ <div id="progress" class="muted" style="margin-top:12px"></div>+ <button class="btn" style="margin-top:16px" type="submit">Upload</button>+ </form>+ `;+ const form = root.querySelector('#up');+ const progress = root.querySelector('#progress');+ form.addEventListener('submit', async (e) => {+ e.preventDefault();+ const file = root.querySelector('#file').files[0];+ if (!file) return;+ progress.textContent = 'Requesting upload URL…';+ try {+ const { upload_url, storage_key } = await api.presign({+ size_bytes: file.size,+ content_type: file.type || 'model/gltf-binary',+ });+ progress.textContent = `Uploading ${fmtSize(file.size)}…`;+ await uploadToR2(+ upload_url,+ file,+ (pct) => (progress.textContent = `Uploading ${pct}%…`),+ );+ progress.textContent = 'Finalizing…';+ const tags = (root.querySelector('#tags').value || '')+ .split(',')+ .map((s) => s.trim())+ .filter(Boolean);+ const { avatar } = await api.createAvatar({+ storage_key,+ name: root.querySelector('#name').value,+ description: root.querySelector('#desc').value || undefined,+ visibility: root.querySelector('#vis').value,+ tags,+ size_bytes: file.size,+ content_type: file.type || 'model/gltf-binary',+ source: 'upload',+ source_meta: {},+ });+ progress.innerHTML = `Uploaded! <a href="#avatars">View</a>`;+ location.hash = 'avatars';+ } catch (err) {+ progress.textContent = '';+ alert(err.message);+ }+ });+}++function uploadToR2(url, file, onProgress) {+ return new Promise((resolve, reject) => {+ const xhr = new XMLHttpRequest();+ xhr.open('PUT', url);+ xhr.setRequestHeader('content-type', file.type || 'model/gltf-binary');+ xhr.upload.onprogress = (e) =>+ e.lengthComputable && onProgress(Math.round((e.loaded / e.total) * 100));+ xhr.onload = () =>+ xhr.status >= 200 && xhr.status < 300+ ? resolve()+ : reject(new Error(`Upload failed (${xhr.status})`));+ xhr.onerror = () => reject(new Error('Network error during upload'));+ xhr.send(file);+ });+}++// ── Create from selfie ──────────────────────────────────────────────────────+// Embeds the Ready Player Me hosted creator (free, no API key). RPM handles+// camera capture, selfie-to-mesh, and returns a GLB URL via postMessage.+// We fetch that GLB and run it through the same R2 upload path as manual uploads.+const RPM_SUBDOMAIN = 'demo'; // any public RPM subdomain works for self-serve+const RPM_ORIGIN = `https://${RPM_SUBDOMAIN}.readyplayer.me`;+const RPM_SRC = `${RPM_ORIGIN}/avatar?frameApi&bodyType=fullbody&clearCache=true`;++function renderCreate(root) {+ root.innerHTML = `+ <div class="toolbar">+ <div>+ <h1>Create from a selfie</h1>+ <p class="sub">Take a photo. We turn it into a 3D avatar and save it to your account.</p>+ </div>+ <button class="btn sec" id="rpm-restart" type="button" style="display:none">Start over</button>+ </div>+ <div id="rpm-stage" class="card" style="padding:0; overflow:hidden; min-height:640px; position:relative">+ <div id="rpm-intro" style="padding:32px; text-align:center">+ <div style="font-size:42px; line-height:1; margin-bottom:12px">📸</div>+ <p style="margin:0 0 18px; color:#ccc">+ Next screen: allow camera access, take a selfie, pick body type.+ Your avatar auto-saves here when you hit "Next" in the last step.+ </p>+ <button class="btn" id="rpm-launch" type="button">Open camera</button>+ </div>+ <iframe id="rpm-iframe" title="Avatar creator" allow="camera *; microphone *" style="display:none; width:100%; height:640px; border:0; background:#0f0f17"></iframe>+ <div id="rpm-progress" class="muted" style="padding:16px 20px; border-top:1px solid var(--border); display:none"></div>+ </div>+ `;++ const launchBtn = root.querySelector('#rpm-launch');+ const restartBtn = root.querySelector('#rpm-restart');+ const intro = root.querySelector('#rpm-intro');+ const iframe = root.querySelector('#rpm-iframe');+ const progress = root.querySelector('#rpm-progress');++ const say = (msg, isError = false) => {+ progress.style.display = 'block';+ progress.style.color = isError ? '#ffb3b3' : '#888';+ progress.textContent = msg;+ };++ let onMsg = null;++ const start = () => {+ intro.style.display = 'none';+ iframe.style.display = 'block';+ iframe.src = RPM_SRC;+ restartBtn.style.display = 'inline-block';+ progress.style.display = 'none';++ onMsg = async (event) => {+ if (event.origin !== RPM_ORIGIN) return;+ const data = parseRpmMessage(event.data);+ if (!data?.eventName) return;++ // Ready Player Me → subscribe to all events once its frame is ready.+ if (data.eventName === 'v1.frame.ready') {+ iframe.contentWindow?.postMessage(+ JSON.stringify({+ target: 'readyplayerme',+ type: 'subscribe',+ eventName: 'v1.**',+ }),+ RPM_ORIGIN,+ );+ return;+ }++ if (data.eventName === 'v1.avatar.exported') {+ const glbUrl = data.data?.url;+ if (!glbUrl) {+ say('No avatar URL returned', true);+ return;+ }+ say('Fetching avatar…');+ try {+ const avatar = await saveRpmAvatar(glbUrl);+ say(`Saved "${avatar.name}". Redirecting…`);+ setTimeout(() => {+ location.hash = 'avatars';+ }, 600);+ } catch (err) {+ say(err.message || 'Failed to save avatar', true);+ }+ }+ };+ window.addEventListener('message', onMsg);+ };++ const stop = () => {+ if (onMsg) window.removeEventListener('message', onMsg);+ onMsg = null;+ iframe.src = 'about:blank';+ iframe.style.display = 'none';+ intro.style.display = 'block';+ restartBtn.style.display = 'none';+ progress.style.display = 'none';+ };++ launchBtn.addEventListener('click', start);+ restartBtn.addEventListener('click', stop);+}++function parseRpmMessage(raw) {+ if (!raw) return null;+ if (typeof raw === 'object') return raw;+ try {+ return JSON.parse(raw);+ } catch {+ return null;+ }+}++async function saveRpmAvatar(sourceUrl) {+ const res = await fetch(sourceUrl);+ if (!res.ok) throw new Error(`Fetch avatar failed: ${res.status}`);+ const blob = await res.blob();+ const contentType = 'model/gltf-binary';+ const size = blob.size;+ const checksum = await sha256Hex(blob);++ const { upload_url, storage_key } = await api.presign({+ size_bytes: size,+ content_type: contentType,+ checksum_sha256: checksum,+ });++ await new Promise((resolve, reject) => {+ const xhr = new XMLHttpRequest();+ xhr.open('PUT', upload_url);+ xhr.setRequestHeader('content-type', contentType);+ xhr.onload = () =>+ xhr.status >= 200 && xhr.status < 300+ ? resolve()+ : reject(new Error(`Upload failed (${xhr.status})`));+ xhr.onerror = () => reject(new Error('Network error during upload'));+ xhr.send(blob);+ });++ const { avatar } = await api.createAvatar({+ storage_key,+ size_bytes: size,+ content_type: contentType,+ checksum_sha256: checksum,+ name: `Selfie avatar ${new Date().toLocaleDateString()}`,+ visibility: 'private',+ tags: ['selfie'],+ source: 'import',+ source_meta: { provider: 'readyplayerme', source_url: sourceUrl, selfie_based: true },+ });++ // Wire the new avatar straight into the caller's default agent identity so+ // the selfie immediately becomes the agent's body across the site.+ await attachAvatarToDefaultAgent(avatar.id).catch((e) =>+ console.warn('attach to agent skipped:', e.message),+ );+ return avatar;+}++async function attachAvatarToDefaultAgent(avatarId) {+ const meRes = await fetch('/api/agents/me', { credentials: 'include' });+ if (!meRes.ok) return;+ const { agent } = await meRes.json();+ if (!agent) return;+ await fetch(`/api/agents/${agent.id}`, {+ method: 'PUT',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ avatar_id: avatarId }),+ });+}++// ── Edit avatar ─────────────────────────────────────────────────────────────+async function renderEdit(root, params = []) {+ const id = params[0];+ if (!id) {+ location.hash = 'avatars';+ return;+ }++ root.innerHTML = `+ <div class="toolbar">+ <div>+ <h1>Edit avatar</h1>+ <p class="sub">Update the details that appear in MCP results and the public gallery.</p>+ </div>+ <a class="btn sec" href="#avatars">Back</a>+ </div>+ <div id="edit-body">+ <div class="muted">Loading…</div>+ </div>+ `;++ const body = root.querySelector('#edit-body');+ let avatar;+ try {+ const res = await fetch(`/api/avatars/${encodeURIComponent(id)}`, {+ credentials: 'include',+ });+ if (!res.ok) throw new Error((await res.json()).error_description || res.statusText);+ avatar = (await res.json()).avatar;+ } catch (err) {+ body.innerHTML = `<div class="err">${esc(err.message)}</div>`;+ return;+ }++ const previewUrl = avatar.url || avatar.model_url;+ body.innerHTML = `+ <div style="display:grid; grid-template-columns:minmax(260px,1fr) minmax(260px,2fr); gap:20px; align-items:start">+ <div class="card" style="padding:10px">+ <div class="preview" style="aspect-ratio:1/1; margin:0; background:#0f0f17; border-radius:10px; overflow:hidden">+ ${+ previewUrl+ ? `<model-viewer src="${attr(previewUrl)}" camera-controls auto-rotate shadow-intensity="1" exposure="1" tone-mapping="aces" style="width:100%;height:100%"></model-viewer>`+ : `<div style="display:grid;place-items:center;height:100%;color:#555;font-size:12px">Preview unavailable</div>`+ }+ </div>+ <p class="muted" style="margin:10px 4px 0">${fmtSize(avatar.size_bytes || 0)} · ${esc(avatar.source || 'upload')}</p>+ </div>+ <form id="ef" class="card" style="max-width:560px">+ <label style="display:block">Name<input id="ename" value="${attr(avatar.name || '')}" maxlength="120" style="width:100%"></label>+ <label style="display:block;margin-top:12px">Description<textarea id="edesc" rows="3" style="width:100%">${esc(avatar.description || '')}</textarea></label>+ <label style="display:block;margin-top:12px">Visibility+ <select id="evis" style="width:100%">+ ${['private', 'unlisted', 'public'].map((v) => `<option ${v === avatar.visibility ? 'selected' : ''} value="${v}">${v}</option>`).join('')}+ </select>+ </label>+ <label style="display:block;margin-top:12px">Tags (comma separated)<input id="etags" value="${attr((avatar.tags || []).join(', '))}" style="width:100%"></label>+ <div id="emsg" class="muted" style="margin-top:12px"></div>+ <div class="row" style="gap:8px; margin-top:16px">+ <button class="btn" type="submit">Save changes</button>+ <button class="btn sec" id="euse" type="button">Use as my agent's body</button>+ </div>+ </form>+ </div>+ `;++ const msg = body.querySelector('#emsg');+ body.querySelector('#ef').addEventListener('submit', async (e) => {+ e.preventDefault();+ msg.style.color = '#888';+ msg.textContent = 'Saving…';+ try {+ const tags = (body.querySelector('#etags').value || '')+ .split(',')+ .map((s) => s.trim())+ .filter(Boolean);+ await api.patchAvatar(id, {+ name: body.querySelector('#ename').value.trim(),+ description: body.querySelector('#edesc').value.trim() || undefined,+ visibility: body.querySelector('#evis').value,+ tags,+ });+ msg.style.color = '#9a8cff';+ msg.textContent = 'Saved.';+ } catch (err) {+ msg.style.color = '#ffb3b3';+ msg.textContent = err.message;+ }+ });++ body.querySelector('#euse').addEventListener('click', async () => {+ msg.style.color = '#888';+ msg.textContent = 'Linking to your agent…';+ try {+ await attachAvatarToDefaultAgent(id);+ msg.style.color = '#9a8cff';+ msg.textContent = 'Your agent will now render with this avatar.';+ } catch (err) {+ msg.style.color = '#ffb3b3';+ msg.textContent = err.message || 'Failed to link avatar to agent';+ }+ });+}++async function sha256Hex(blob) {+ const buf = await blob.arrayBuffer();+ const hash = await crypto.subtle.digest('SHA-256', buf);+ return Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, '0')).join('');+}++// ── API keys ────────────────────────────────────────────────────────────────+async function renderKeys(root) {+ root.innerHTML = `+ <h1>API keys</h1><p class="sub">Server-side keys for calling the MCP server without OAuth. Treat like passwords.</p>+ <div class="card" style="margin-bottom:16px">+ <form id="new" class="row" style="flex-wrap:wrap;gap:10px">+ <input id="kname" placeholder="Key name (e.g. my-app prod)" required>+ <select id="kenv"><option value="live">live</option><option value="test">test</option></select>+ <button class="btn" type="submit">Create key</button>+ </form>+ <div id="reveal"></div>+ </div>+ <div id="klist" class="card"></div>+ `;+ const klist = root.querySelector('#klist');+ async function refresh() {+ try {+ const { keys } = await api.listKeys();+ if (!keys.length) {+ klist.innerHTML = '<div class="muted">No keys yet.</div>';+ return;+ }+ klist.innerHTML = keys+ .map(+ (k) => `+ <div class="key-row">+ <div>+ <div><code>${esc(k.prefix)}…</code> — ${esc(k.name)}</div>+ <div class="muted">scope: ${esc(k.scope)} · created ${new Date(k.created_at).toLocaleDateString()}${k.revoked_at ? ` · <b style="color:#f88">revoked</b>` : ''}</div>+ </div>+ ${k.revoked_at ? '' : `<button class="btn sec" data-id="${esc(k.id)}">Revoke</button>`}+ </div>+ `,+ )+ .join('');+ klist.querySelectorAll('button[data-id]').forEach((b) =>+ b.addEventListener('click', async () => {+ if (!confirm('Revoke this key?')) return;+ try {+ await api.revokeKey(b.dataset.id);+ refresh();+ } catch (e) {+ alert(e.message);+ }+ }),+ );+ } catch (e) {+ klist.innerHTML = `<div class="err">${esc(e.message)}</div>`;+ }+ }+ root.querySelector('#new').addEventListener('submit', async (e) => {+ e.preventDefault();+ try {+ const { key } = await api.createKey({+ name: root.querySelector('#kname').value,+ environment: root.querySelector('#kenv').value,+ });+ root.querySelector('#reveal').innerHTML = `+ <div style="margin-top:10px">+ <p class="muted">Copy this key now — you won't see it again.</p>+ <pre><code>${esc(key.secret)}</code></pre>+ </div>+ `;+ root.querySelector('#kname').value = '';+ refresh();+ } catch (err) {+ alert(err.message);+ }+ });+ refresh();+}++// ── MCP integration ─────────────────────────────────────────────────────────+function renderMcp(root) {+ const origin = location.origin;+ root.innerHTML = `+ <h1>Use from Claude & other MCP clients</h1>+ <p class="sub">Connect any MCP-compatible client to render your avatars inline.</p>++ <h3 class="section">Remote MCP server URL</h3>+ <pre><code>${esc(origin)}/api/mcp</code></pre>++ <h3 class="section">Claude Desktop / Claude Code (remote)</h3>+ <p class="muted">Add a Custom Connector in Claude. When prompted, sign in with your 3D Agent account.</p>+ <pre><code>${esc(+ JSON.stringify(+ {+ mcpServers: {+ '3d-agent': { url: `${origin}/api/mcp` },+ },+ },+ null,+ 2,+ ),+ )}</code></pre>++ <h3 class="section">Programmatic (API key)</h3>+ <p class="muted">Bypass OAuth for server-to-server usage. Pass key as a bearer token.</p>+ <pre><code>curl -X POST ${esc(origin)}/api/mcp \\+ -H "authorization: Bearer sk_live_…" \\+ -H "content-type: application/json" \\+ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'</code></pre>++ <h3 class="section">Available tools</h3>+ <ul>+ <li><b>list_my_avatars</b> — list avatars</li>+ <li><b>get_avatar</b> — fetch by id or slug</li>+ <li><b>search_public_avatars</b> — discover public avatars</li>+ <li><b>render_avatar</b> — returns <model-viewer> HTML for rendering as a Claude artifact</li>+ <li><b>delete_avatar</b> — remove an avatar (requires <code>avatars:delete</code>)</li>+ </ul>+ `;+}++// ── Embed ───────────────────────────────────────────────────────────────────+// Shows copy-paste snippets for dropping the agent into Lobehub, Claude,+// an iframe on any site, and a postMessage example for piping chat into the+// avatar so it reacts (speaks / emotes) to host-app events.+async function renderEmbed(root) {+ root.innerHTML = `+ <h1>Embed your agent</h1>+ <p class="sub">Drop your agent into Lobehub, Claude Artifacts, your site, or anywhere that can render an iframe. The agent reacts to chat messages via a postMessage bridge.</p>+ <div id="embed-body"><div class="muted">Loading your agent…</div></div>+ `;+ const body = root.querySelector('#embed-body');++ let agent;+ try {+ const res = await fetch('/api/agents/me', { credentials: 'include' });+ if (res.ok) agent = (await res.json()).agent;+ } catch {}++ if (!agent) {+ body.innerHTML = `+ <div class="empty">+ You don't have an agent yet. <a href="#create">Create one from a selfie</a> first.+ </div>+ `;+ return;+ }++ const origin = location.origin;+ const embedUrl = `${origin}/agent/${encodeURIComponent(agent.id)}/embed`;+ const homeUrl = `${origin}/agent/${encodeURIComponent(agent.id)}`;+ const iframeSnippet = `<iframe src="${embedUrl}" allow="camera; microphone" style="width:320px;height:420px;border:0;border-radius:16px;overflow:hidden" title="${esc(agent.name || 'Agent')}"></iframe>`;+ const lobehubSnippet = [+ '// Drop into a Lobehub fork — renders the agent alongside the chat panel',+ '// and forwards assistant messages to it so the avatar speaks/emotes.',+ "import { useEffect, useRef } from 'react';",+ '',+ 'export function AgentSidecar({ latestAssistantMessage }) {',+ ` const AGENT_ID = ${JSON.stringify(agent.id)};`,+ ` const EMBED_URL = ${JSON.stringify(embedUrl)};`,+ ' const ref = useRef(null);',+ '',+ ' useEffect(() => {',+ ' if (!ref.current || !latestAssistantMessage) return;',+ ' ref.current.contentWindow?.postMessage({',+ ' __agent: AGENT_ID,',+ " type: 'action',",+ " action: { type: 'speak', payload: { text: latestAssistantMessage.text } },",+ " }, '*');",+ ' }, [latestAssistantMessage]);',+ '',+ ' return <iframe ref={ref} src={EMBED_URL} allow="camera; microphone"',+ ' style={{ width: 320, height: 420, border: 0, borderRadius: 16 }} />;',+ '}',+ ].join('\n');+ const claudeSnippet = [+ '<!-- Paste into Claude as an HTML Artifact. The avatar renders live. -->',+ `<iframe src="${embedUrl}"`,+ ' style="width:100%;height:480px;border:0;border-radius:16px"',+ ' allow="camera; microphone"></iframe>',+ ].join('\n');+ const postMessageSnippet = [+ '// From any host page, make the avatar speak + emote:',+ "const frame = document.querySelector('iframe');",+ 'frame.contentWindow.postMessage({',+ ` __agent: ${JSON.stringify(agent.id)},`,+ " type: 'action',",+ " action: { type: 'speak', payload: { text: 'Hello from the host app' } },",+ "}, '*');",+ '',+ '// Listen for agent readiness:',+ "window.addEventListener('message', (e) => {",+ ` if (e.data?.__agent === ${JSON.stringify(agent.id)} && e.data.type === 'ready') {`,+ " console.log('agent online:', e.data.name);",+ ' }',+ '});',+ ].join('\n');+ const sdkSnippet = [+ '<!-- Drop-in SDK around the postMessage Bridge v1. -->',+ '<!-- See /agent/' + agent.id + '/embed for the wire contract. -->',+ `<iframe id="agent" src="${embedUrl}" allow="camera; microphone"`,+ ' style="width:320px;height:420px;border:0;border-radius:16px"></iframe>',+ `<script src="${origin}/embed-sdk.js"></script>`,+ '<script>',+ " const bridge = Agent3D.connect(document.getElementById('agent'), {",+ ` agentId: ${JSON.stringify(agent.id)},`,+ " onReady: ({ version, capabilities }) => console.log('ready', version, capabilities),",+ " onAction: (action) => console.log('iframe emitted', action),",+ " onResize: (h) => console.log('preferred height', h),",+ " onError: (err) => console.warn('bridge error', err.message),",+ ' });',+ " bridge.ready.then(() => bridge.send({ type: 'speak', payload: { text: 'Hi from host' } }));",+ '</script>',+ ].join('\n');++ body.innerHTML = `+ <div style="display:grid; grid-template-columns:minmax(260px,1fr) minmax(320px,1.4fr); gap:20px; align-items:start">+ <div class="card" style="padding:8px">+ <iframe src="${attr(embedUrl + '?preview=1')}" style="width:100%;aspect-ratio:3/4;border:0;border-radius:10px;background:#0f0f17" title="Preview"></iframe>+ <div class="row" style="justify-content:space-between; padding:10px 6px 4px">+ <strong>${esc(agent.name || 'My Agent')}</strong>+ <a href="${attr(homeUrl)}" target="_blank" class="muted">Home page →</a>+ </div>+ <p class="muted" style="padding:0 6px">Agent ID <code>${esc(agent.id)}</code></p>+ ${+ agent.wallet_address+ ? `+ <p class="muted" style="padding:0 6px; margin-top:6px; line-height:1.4">+ Agent wallet<br>+ <code style="font-size:11px; word-break:break-all">${esc(agent.wallet_address)}</code><br>+ <span style="font-size:11px">Server-held. Agents sign autonomously via <code style="font-size:11px">POST /api/agents/${esc(agent.id)}/sign</code>.</span>+ </p>+ `+ : ''+ }+ </div>+ <div>+ ${snippetBlock('Universal iframe (any site)', iframeSnippet, 'html')}+ ${snippetBlock('Lobehub React sidecar', lobehubSnippet, 'tsx')}+ ${snippetBlock('Claude Artifact', claudeSnippet, 'html')}+ ${snippetBlock('postMessage bridge (speak + listen)', postMessageSnippet, 'js')}+ ${snippetBlock('Custom embed (Agent3D SDK · Bridge v1)', sdkSnippet, 'html')}+ <div class="card" style="margin-top:14px">+ <h3 style="margin:0 0 6px">Who can embed?</h3>+ <p class="muted" style="margin:0 0 10px">By default anyone. Lock it down to specific hosts (your Lobehub deploy, your Substack…) on the <a href="/dashboard/embed-policy?agent=${encodeURIComponent(agent.id)}">embed-policy page</a>.</p>+ </div>+ ${onchainCard(agent)}+ ${myAgentsCard()}+ </div>+ </div>+ `;++ for (const btn of body.querySelectorAll('[data-copy]')) {+ btn.addEventListener('click', async () => {+ const target = body.querySelector(btn.dataset.copy);+ if (!target) return;+ try {+ await navigator.clipboard.writeText(target.textContent);+ const original = btn.textContent;+ btn.textContent = 'Copied';+ setTimeout(() => {+ btn.textContent = original;+ }, 1200);+ } catch {+ btn.textContent = 'Copy failed';+ }+ });+ }++ bindOnchainDeploy(body, agent);+ bindMyAgents(body);+}++function snippetBlock(title, code, _lang) {+ const id = 'snip-' + Math.random().toString(36).slice(2, 8);+ return `+ <div class="card" style="margin-bottom:14px">+ <div class="row" style="justify-content:space-between; margin-bottom:8px">+ <strong>${esc(title)}</strong>+ <button class="btn sec" data-copy="#${id}" type="button">Copy</button>+ </div>+ <pre id="${id}" style="margin:0; max-height:260px">${esc(code)}</pre>+ </div>+ `;+}++// ── Onchain deploy card ─────────────────────────────────────────────────────+// Mints the agent on ERC-8004 so any host (Lobehub / Claude / etc.) can resolve+// it from its onchain ID instead of needing the /agent/:id URL. Uses the+// wallet the user already connected for SIWE; pins the avatar GLB + manifest+// to IPFS; calls register() on the Identity Registry; writes the resulting+// agentId back to our DB so the agent row becomes the bridge between our host+// and the onchain record.+function onchainCard(agent) {+ const alreadyDeployed = !!agent.erc8004_agent_id;+ const chainHint = agent.chain_id ? ` on chain ${esc(String(agent.chain_id))}` : '';+ const statusHtml = alreadyDeployed+ ? `<p style="margin:0 0 10px; color:#9a8cff">Deployed: agentId <code>${esc(String(agent.erc8004_agent_id))}</code>${chainHint}.</p>`+ : `<p class="muted" style="margin:0 0 10px">Mint your agent as an ERC-8004 onchain identity. Any client that knows the agentId can resolve your avatar, skills, and reputation — no off-chain registry lookup needed.</p>`;+ return `+ <div class="card" id="onchain-card" style="margin-top:14px">+ <h3 style="margin:0 0 6px">Deploy onchain (ERC-8004)</h3>+ ${statusHtml}+ <div class="row" style="gap:8px; flex-wrap:wrap">+ <input id="onchain-ipfs-token" placeholder="web3.storage or Filebase API token" style="flex:1; min-width:260px" type="password">+ <button class="btn" id="onchain-deploy" type="button">${alreadyDeployed ? 'Redeploy' : 'Deploy now'}</button>+ </div>+ <div id="onchain-log" class="muted" style="margin-top:10px; font-family: ui-monospace, SF Mono, Menlo, monospace; font-size:12px; white-space:pre-wrap"></div>+ </div>+ `;+}++// Attach the click handler after the embed DOM has been rendered. Called from+// renderEmbed below via a mutation after body.innerHTML is set.+function bindOnchainDeploy(body, agent) {+ const btn = body.querySelector('#onchain-deploy');+ const log = body.querySelector('#onchain-log');+ const token = body.querySelector('#onchain-ipfs-token');+ if (!btn) return;++ btn.addEventListener('click', async () => {+ btn.disabled = true;+ const say = (msg, isError = false) => {+ log.style.color = isError ? '#ffb3b3' : '#888';+ log.textContent = (log.textContent ? log.textContent + '\n' : '') + msg;+ };+ log.textContent = '';++ if (!agent.avatar_id) {+ say('Your agent has no avatar yet. Create one from a selfie first.', true);+ btn.disabled = false;+ return;+ }++ try {+ say('Fetching avatar GLB…');+ const avRes = await fetch(`/api/avatars/${encodeURIComponent(agent.avatar_id)}`, {+ credentials: 'include',+ });+ if (!avRes.ok)+ throw new Error((await avRes.json()).error_description || 'avatar fetch failed');+ const avatarRow = (await avRes.json()).avatar;+ const glbUrl = avatarRow.url || avatarRow.model_url;+ if (!glbUrl) throw new Error('avatar has no URL');+ const glbBlob = await (await fetch(glbUrl)).blob();+ const glbFile = new File([glbBlob], `${agent.id}.glb`, { type: 'model/gltf-binary' });++ say('Opening registration flow… (loading chain module)');+ const { registerAgent } = await import('/src/erc8004/agent-registry.js');++ const result = await registerAgent({+ glbFile,+ name: agent.name || 'Agent',+ description: agent.description || `3D agent ${agent.id}`,+ apiToken: token.value.trim() || undefined,+ onStatus: (msg) => say(msg),+ });++ say(`Persisting onchain IDs to your account…`);+ const wallet = window.ethereum?.selectedAddress || '';+ const chainId =+ Number((await window.ethereum?.request?.({ method: 'eth_chainId' })) || 0) ||+ undefined;+ await fetch(`/api/agents/${encodeURIComponent(agent.id)}/wallet`, {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ wallet_address: wallet,+ chain_id: chainId+ ? parseInt(+ chainId.toString(16) === chainId.toString()+ ? chainId+ : String(chainId),+ 10,+ ) || null+ : null,+ erc8004_agent_id: result.agentId,+ }),+ });++ say(+ `✓ Done. agentId=${result.agentId}, registration=ipfs://${result.registrationCID}, tx=${result.txHash}`,+ );+ } catch (err) {+ say(err.message || String(err), true);+ } finally {+ btn.disabled = false;+ }+ });+}++// ── My on-chain agents card ─────────────────────────────────────────────────+// Lists every ERC-8004 agent owned by the connected wallet — minted here or+// elsewhere. Enumerates via ERC-721: balanceOf + tokenOfOwnerByIndex, falling+// back to a Transfer-event scan if the registry isn't ERC-721-Enumerable.+// Merges in DB-registered agents from /api/agents/by-wallet so "home" links+// work for agents minted through this app.+function myAgentsCard() {+ return `+ <div class="card" id="my-agents-card" style="margin-top:14px">+ <h3 style="margin:0 0 6px">Your on-chain agents</h3>+ <p class="muted" style="margin:0 0 10px">All ERC-8004 agents owned by your connected wallet — minted here or anywhere else.</p>+ <div class="row" style="gap:8px; flex-wrap:wrap; align-items:center">+ <button class="btn sec" id="my-agents-load" type="button">Load from wallet</button>+ <span id="my-agents-status" class="muted" style="font-size:12px"></span>+ </div>+ <div id="my-agents-list" style="margin-top:12px; display:grid; gap:10px"></div>+ </div>+ `;+}++function bindMyAgents(body) {+ const btn = body.querySelector('#my-agents-load');+ const status = body.querySelector('#my-agents-status');+ const list = body.querySelector('#my-agents-list');+ if (!btn) return;++ btn.addEventListener('click', async () => {+ btn.disabled = true;+ status.textContent = 'Connecting wallet…';+ list.innerHTML = '';++ try {+ const [{ connectWallet, getIdentityRegistry }, { REGISTRY_DEPLOYMENTS }] =+ await Promise.all([+ import('/src/erc8004/agent-registry.js'),+ import('/src/erc8004/abi.js'),+ ]);++ const { signer, address, chainId } = await connectWallet();+ const deployment = REGISTRY_DEPLOYMENTS[chainId];+ if (!deployment?.identityRegistry) {+ status.textContent = `No ERC-8004 registry on chain ${chainId}. Switch networks and retry.`;+ return;+ }++ status.textContent = 'Reading registry…';+ const registry = getIdentityRegistry(chainId, signer);+ const balance = Number(await registry.balanceOf(address));++ // Fire the DB lookup in parallel with on-chain work.+ const dbPromise = fetch(+ `/api/agents/by-wallet?address=${encodeURIComponent(address)}&chain_id=${chainId}`,+ { credentials: 'include' },+ )+ .then((r) => (r.ok ? r.json() : { agents: [] }))+ .catch(() => ({ agents: [] }));++ if (balance === 0) {+ const { agents: dbAgents = [] } = await dbPromise;+ if (dbAgents.length === 0) {+ status.textContent = `No agents owned on chain ${chainId}.`;+ return;+ }+ renderAgentRows(list, [], dbAgents);+ status.textContent = `${dbAgents.length} DB record${dbAgents.length === 1 ? '' : 's'} (not on-chain yet).`;+ return;+ }++ status.textContent = `${balance} agent${balance === 1 ? '' : 's'} owned. Enumerating…`;++ // Try ERC-721 Enumerable; fall back to event scan.+ let tokenIds = [];+ try {+ for (let i = 0; i < balance; i++) {+ tokenIds.push(Number(await registry.tokenOfOwnerByIndex(address, i)));+ }+ } catch {+ status.textContent = 'Registry is not Enumerable — scanning Transfer events…';+ const events = await registry.queryFilter(registry.filters.Transfer(null, address));+ const seen = new Set();+ for (const e of events) {+ const id = Number(e.args.tokenId);+ if (seen.has(id)) continue;+ seen.add(id);+ try {+ const owner = await registry.ownerOf(id);+ if (owner.toLowerCase() === address.toLowerCase()) tokenIds.push(id);+ } catch {+ /* token burned/transferred — skip */+ }+ }+ }++ status.textContent = `Fetching metadata for ${tokenIds.length} agent${tokenIds.length === 1 ? '' : 's'}…`;+ const onchain = await Promise.all(tokenIds.map((id) => fetchTokenMeta(registry, id)));+ const { agents: dbAgents = [] } = await dbPromise;++ renderAgentRows(list, onchain, dbAgents);+ status.textContent = `${onchain.length} on-chain agent${onchain.length === 1 ? '' : 's'} on chain ${chainId}.`;+ } catch (err) {+ status.textContent = `Error: ${err.message || String(err)}`;+ } finally {+ btn.disabled = false;+ }+ });+}++async function fetchTokenMeta(registry, tokenId) {+ let uri = '';+ let meta = null;+ try {+ uri = await registry.tokenURI(tokenId);+ } catch {+ /* no URI set */+ }+ if (uri) {+ const httpUrl = uriToHttp(uri);+ try {+ const r = await fetch(httpUrl);+ const ct = r.headers.get('content-type') || '';+ if (r.ok && ct.includes('json')) meta = await r.json();+ } catch {+ /* metadata unreachable */+ }+ }+ return { id: tokenId, uri, meta };+}++function uriToHttp(uri) {+ if (!uri) return '';+ if (uri.startsWith('ipfs://')) return `https://ipfs.io/ipfs/${uri.slice(7)}`;+ if (uri.startsWith('ar://')) return `https://arweave.net/${uri.slice(5)}`;+ return uri;+}++function renderAgentRows(list, onchainAgents, dbAgents) {+ const dbByAgentId = new Map();+ for (const a of dbAgents) {+ if (a.erc8004_agent_id != null) dbByAgentId.set(String(a.erc8004_agent_id), a);+ }++ list.innerHTML = '';+ for (const { id, uri, meta } of onchainAgents) {+ const dbRow = dbByAgentId.get(String(id));+ const name = meta?.name || dbRow?.name || `Agent #${id}`;+ const desc = meta?.description || dbRow?.description || '';+ const img = uriToHttp(meta?.image || '');+ const homeLink = dbRow ? `/agent/${encodeURIComponent(dbRow.id)}` : '';+ const metaLink = uri ? uriToHttp(uri) : '';++ const el = document.createElement('div');+ el.className = 'row';+ el.style.cssText =+ 'gap:12px; padding:10px; border:1px solid #2a2a34; border-radius:10px; align-items:flex-start';+ el.innerHTML = `+ <div style="flex:0 0 64px; width:64px; height:64px; border-radius:8px; background:#0f0f17; overflow:hidden; display:flex; align-items:center; justify-content:center">+ ${img ? `<img src="${attr(img)}" alt="" style="max-width:100%;max-height:100%;object-fit:cover" onerror="this.remove()">` : '<span class="muted" style="font-size:10px">no image</span>'}+ </div>+ <div style="flex:1 1 auto; min-width:0">+ <div class="row" style="justify-content:space-between; gap:8px; flex-wrap:wrap">+ <strong style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0">${esc(name)}</strong>+ <span class="muted" style="font-size:12px">#${esc(String(id))}</span>+ </div>+ ${desc ? `<p class="muted" style="margin:4px 0 0; font-size:12px; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; overflow:hidden">${esc(desc)}</p>` : ''}+ <div class="row" style="gap:10px; margin-top:6px; font-size:12px">+ ${metaLink ? `<a href="${attr(metaLink)}" target="_blank" rel="noopener" class="muted">Metadata</a>` : ''}+ ${homeLink ? `<a href="${attr(homeLink)}" target="_blank" rel="noopener">Open home</a>` : ''}+ </div>+ </div>+ `;+ list.appendChild(el);+ }++ // Surface DB rows that aren't on-chain yet (e.g. registration failed).+ for (const a of dbAgents) {+ const hasOnchain =+ a.erc8004_agent_id != null &&+ onchainAgents.some((o) => String(o.id) === String(a.erc8004_agent_id));+ if (hasOnchain) continue;++ const el = document.createElement('div');+ el.className = 'row';+ el.style.cssText =+ 'gap:12px; padding:10px; border:1px dashed #2a2a34; border-radius:10px; align-items:flex-start; opacity:.85';+ el.innerHTML = `+ <div style="flex:0 0 64px; width:64px; height:64px; border-radius:8px; background:#0f0f17; display:flex; align-items:center; justify-content:center">+ <span class="muted" style="font-size:10px">db only</span>+ </div>+ <div style="flex:1 1 auto; min-width:0">+ <div class="row" style="justify-content:space-between; gap:8px; flex-wrap:wrap">+ <strong style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0">${esc(a.name || 'Agent')}</strong>+ <span class="muted" style="font-size:12px">not on-chain</span>+ </div>+ ${a.description ? `<p class="muted" style="margin:4px 0 0; font-size:12px">${esc(a.description)}</p>` : ''}+ <div class="row" style="gap:10px; margin-top:6px; font-size:12px">+ <a href="/agent/${encodeURIComponent(a.id)}" target="_blank" rel="noopener">Open home</a>+ </div>+ </div>+ `;+ list.appendChild(el);+ }+}++// ── Billing placeholder ─────────────────────────────────────────────────────+function renderBilling(root) {+ root.innerHTML = `<h1>Plan & usage</h1><p class="sub">You're on the <b>${esc(state.user.plan)}</b> plan.</p><div class="card muted">Detailed usage analytics coming soon.</div>`;+}++// ── Widgets ─────────────────────────────────────────────────────────────────+// Saved 3D experiences the user has generated in the Studio. Each gets its own+// card with a live, lazy-loaded preview iframe. Editing happens in /studio —+// the dashboard is for managing what already exists.++const WIDGET_TYPE_META = {+ turntable: { label: 'Turntable', color: '#6a5cff' },+ 'animation-gallery': { label: 'Animations', color: '#ff5ca8' },+ 'talking-agent': { label: 'Talking Agent', color: '#00e5a0' },+ passport: { label: 'Passport', color: '#f0c14b' },+ 'hotspot-tour': { label: 'Hotspot Tour', color: '#5cc8ff' },+};++const WIDGET_PREFS_KEY = 'dashboard.widgets.prefs';+const DEFAULT_WIDGET_PREFS = { sort: 'updated', type: '', q: '' };++function loadWidgetPrefs() {+ try {+ return {+ ...DEFAULT_WIDGET_PREFS,+ ...JSON.parse(localStorage.getItem(WIDGET_PREFS_KEY) || '{}'),+ };+ } catch {+ return { ...DEFAULT_WIDGET_PREFS };+ }+}+function saveWidgetPrefs(prefs) {+ try {+ localStorage.setItem(WIDGET_PREFS_KEY, JSON.stringify(prefs));+ } catch {}+}++async function renderWidgets(root) {+ const prefs = loadWidgetPrefs();+ root.innerHTML = `+ <div class="widgets-header">+ <div>+ <h1>Your widgets</h1>+ <p class="sub">Embeddable 3D experiences — each gets a stable URL.</p>+ </div>+ <a class="btn-primary" href="/studio">+ New widget</a>+ </div>+ <div class="widget-toolbar" role="toolbar" aria-label="Widget filters">+ <label class="sr-only" for="w-search">Search widgets</label>+ <input id="w-search" type="search" placeholder="Search by name…" value="${attr(prefs.q)}">+ <label class="sr-only" for="w-type">Filter by type</label>+ <select id="w-type" aria-label="Filter by widget type">+ <option value="">All types</option>+ ${Object.entries(WIDGET_TYPE_META)+ .map(+ ([t, m]) =>+ `<option value="${attr(t)}" ${prefs.type === t ? 'selected' : ''}>${esc(m.label)}</option>`,+ )+ .join('')}+ </select>+ <label class="sr-only" for="w-sort">Sort widgets</label>+ <select id="w-sort" aria-label="Sort widgets">+ <option value="updated" ${prefs.sort === 'updated' ? 'selected' : ''}>Recently updated</option>+ <option value="views" ${prefs.sort === 'views' ? 'selected' : ''}>Most viewed</option>+ <option value="name" ${prefs.sort === 'name' ? 'selected' : ''}>Name (A–Z)</option>+ </select>+ <span id="w-count" class="muted" aria-live="polite"></span>+ </div>+ <div id="widget-list" class="cards" aria-busy="true"><div class="muted">Loading…</div></div>+ `;++ const list = root.querySelector('#widget-list');+ const countEl = root.querySelector('#w-count');+ let widgets = [];++ try {+ const data = await api.listWidgets();+ widgets = data.widgets || [];+ } catch (e) {+ list.innerHTML = `<div class="err">${esc(e.message)}</div>`;+ list.setAttribute('aria-busy', 'false');+ return;+ }++ const observer = lazyIframeObserver();++ function rerender() {+ list.setAttribute('aria-busy', 'false');+ if (!widgets.length) {+ list.innerHTML = `+ <div class="empty" style="grid-column:1/-1">+ <p style="font-size:15px;color:#ccc;margin:0 0 8px">No widgets yet.</p>+ <p style="margin:0 0 18px">Your widgets are embeddable 3D experiences — pick an avatar, a type, and we handle the rest.</p>+ <a class="btn-primary" href="/studio">+ Create your first widget</a>+ </div>+ `;+ countEl.textContent = '';+ return;+ }+ const filtered = applyWidgetFilters(widgets, prefs);+ countEl.textContent =+ filtered.length === widgets.length+ ? `${widgets.length} widget${widgets.length === 1 ? '' : 's'}`+ : `${filtered.length} of ${widgets.length}`;+ list.innerHTML = '';+ if (!filtered.length) {+ list.innerHTML = `<div class="empty" style="grid-column:1/-1">No widgets match the current filters.</div>`;+ return;+ }+ for (const w of filtered) {+ const card = widgetCard(w, {+ reload: rerender,+ mutate: (next) => mutateLocal(widgets, w.id, next),+ remove: () => {+ widgets = widgets.filter((x) => x.id !== w.id);+ rerender();+ },+ });+ list.appendChild(card);+ const ifr = card.querySelector('iframe[data-src]');+ if (ifr) observer.observe(ifr);+ }+ }++ root.querySelector('#w-search').addEventListener('input', (e) => {+ prefs.q = e.target.value;+ saveWidgetPrefs(prefs);+ rerender();+ });+ root.querySelector('#w-type').addEventListener('change', (e) => {+ prefs.type = e.target.value;+ saveWidgetPrefs(prefs);+ rerender();+ });+ root.querySelector('#w-sort').addEventListener('change', (e) => {+ prefs.sort = e.target.value;+ saveWidgetPrefs(prefs);+ rerender();+ });++ rerender();+}++function mutateLocal(arr, id, next) {+ const i = arr.findIndex((x) => x.id === id);+ if (i >= 0) arr[i] = { ...arr[i], ...next };+}++function applyWidgetFilters(widgets, prefs) {+ let out = widgets;+ if (prefs.type) out = out.filter((w) => w.type === prefs.type);+ if (prefs.q) {+ const q = prefs.q.trim().toLowerCase();+ if (q) out = out.filter((w) => (w.name || '').toLowerCase().includes(q));+ }+ out = [...out];+ if (prefs.sort === 'name') out.sort((a, b) => (a.name || '').localeCompare(b.name || ''));+ if (prefs.sort === 'views') out.sort((a, b) => (b.view_count || 0) - (a.view_count || 0));+ if (prefs.sort === 'updated' || !prefs.sort) {+ out.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at));+ }+ return out;+}++function widgetCard(w, ctx) {+ const meta = WIDGET_TYPE_META[w.type] || { label: w.type, color: '#888' };+ const card = document.createElement('div');+ card.className = 'widget-card card';+ card.dataset.id = w.id;++ const previewSrc = `/#widget=${encodeURIComponent(w.id)}&kiosk=true&preview=1`;+ const previewHtml = w.avatar+ ? `<iframe data-src="${attr(previewSrc)}" loading="lazy" tabindex="-1" title="Preview of ${attr(w.name || 'widget')}"></iframe>`+ : `<div class="placeholder">Avatar unavailable.<br>Edit to pick a replacement.</div>`;++ card.innerHTML = `+ <div class="frame">${previewHtml}</div>+ <div class="title">+ <h3 title="Double-click to rename">${esc(w.name || 'Untitled')}</h3>+ <span class="pill"><span class="dot" style="background:${attr(meta.color)}"></span>${esc(meta.label)}</span>+ </div>+ <div class="row" style="justify-content:space-between; gap:8px">+ <span class="meta">${formatViewCount(w.view_count)} · updated ${timeAgo(w.updated_at)}</span>+ <label class="toggle" title="${w.is_public ? 'Public — anyone with the URL can view' : 'Private — only you can view'}">+ <input type="checkbox" data-public ${w.is_public ? 'checked' : ''}>+ <span class="track"></span>+ <span class="label">${w.is_public ? 'Public' : 'Private'}</span>+ </label>+ </div>+ <div class="actions">+ <a href="/studio?edit=${encodeURIComponent(w.id)}" data-edit>Edit</a>+ <button data-share type="button">Share</button>+ <button data-duplicate type="button">Duplicate</button>+ <button data-details type="button">Details</button>+ <button data-delete class="danger" type="button">Delete</button>+ </div>+ `;++ // Inline rename — double-click on the title swaps in an input.+ const titleEl = card.querySelector('.title h3');+ titleEl.addEventListener('dblclick', () => beginRename(card, w, ctx));++ // Public/private toggle — confirm before disabling so embeds aren't silently broken.+ const toggleInput = card.querySelector('input[data-public]');+ toggleInput.addEventListener('change', async () => {+ const next = toggleInput.checked;+ if (+ !next &&+ !confirm(+ 'Making this widget private will break any existing embeds on other sites. Continue?',+ )+ ) {+ toggleInput.checked = true;+ return;+ }+ try {+ await api.patchWidget(w.id, { is_public: next });+ ctx.mutate({ is_public: next });+ card.querySelector('.toggle .label').textContent = next ? 'Public' : 'Private';+ toast(next ? 'Now public' : 'Now private');+ } catch (err) {+ toggleInput.checked = !next;+ toast(err.message || 'Failed to update', true);+ }+ });++ card.querySelector('[data-share]').addEventListener('click', () => openShareModal(w));+ card.querySelector('[data-details]').addEventListener('click', () => openWidgetDrawer(w, ctx));+ card.querySelector('[data-duplicate]').addEventListener('click', async () => {+ try {+ await api.duplicateWidget(w.id);+ toast('Duplicated');+ // Re-fetch via navigate so the new row's avatar join is populated.+ navigate('widgets');+ } catch (err) {+ toast(err.message || 'Duplicate failed', true);+ }+ });+ card.querySelector('[data-delete]').addEventListener('click', async () => {+ if (!confirm(`Delete "${w.name || 'this widget'}"? This cannot be undone.`)) return;+ try {+ await api.deleteWidget(w.id);+ card.style.transition = 'opacity .2s';+ card.style.opacity = '0';+ setTimeout(() => ctx.remove(), 220);+ toast('Deleted');+ } catch (err) {+ toast(err.message || 'Delete failed', true);+ }+ });++ return card;+}++function beginRename(card, w, ctx) {+ const titleEl = card.querySelector('.title h3');+ if (!titleEl) return;+ const original = w.name || '';+ const input = document.createElement('input');+ input.type = 'text';+ input.value = original;+ input.maxLength = 120;+ input.setAttribute('aria-label', 'Widget name');+ titleEl.replaceWith(input);+ input.focus();+ input.select();++ let settled = false;+ const restore = (text) => {+ if (settled) return;+ settled = true;+ const h = document.createElement('h3');+ h.textContent = text;+ h.title = 'Double-click to rename';+ input.replaceWith(h);+ h.addEventListener('dblclick', () => beginRename(card, { ...w, name: text }, ctx));+ };++ input.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ commit();+ } else if (e.key === 'Escape') {+ e.preventDefault();+ restore(original);+ }+ });+ input.addEventListener('blur', commit);++ async function commit() {+ const next = input.value.trim();+ if (!next || next === original) {+ restore(original);+ return;+ }+ try {+ await api.patchWidget(w.id, { name: next });+ ctx.mutate({ name: next });+ restore(next);+ toast('Renamed');+ } catch (err) {+ restore(original);+ toast(err.message || 'Rename failed', true);+ }+ }+}++function lazyIframeObserver() {+ if (typeof IntersectionObserver === 'undefined') {+ // Fallback — eagerly hydrate. Old browsers shouldn't pay this a/b cost.+ return {+ observe(el) {+ hydrate(el);+ },+ };+ }+ const io = new IntersectionObserver(+ (entries) => {+ for (const entry of entries) {+ if (entry.isIntersecting) {+ hydrate(entry.target);+ io.unobserve(entry.target);+ }+ }+ },+ { rootMargin: '120px' },+ );+ return io;+ function hydrate(el) {+ const src = el.getAttribute('data-src');+ if (src && !el.src) el.src = src;+ }+}++// ── Widget details drawer ───────────────────────────────────────────────────+async function openWidgetDrawer(w, ctx) {+ const overlay = document.createElement('div');+ overlay.className = 'drawer-overlay';+ const drawer = document.createElement('aside');+ drawer.className = 'drawer';+ drawer.setAttribute('role', 'dialog');+ drawer.setAttribute('aria-label', `Widget details — ${w.name || 'untitled'}`);+ drawer.tabIndex = -1;++ const previewSrc = `/#widget=${encodeURIComponent(w.id)}&kiosk=true&preview=1`;+ const pageUrl = `${location.origin}/w/${encodeURIComponent(w.id)}`;+ const iframeSnippet = makeIframeSnippet(w, pageUrl, 600, 600);+ const scriptSnippet = `<script async src="${location.origin}/embed.js" data-widget="${esc(w.id)}"></script>`;+ const meta = WIDGET_TYPE_META[w.type] || { label: w.type, color: '#888' };++ drawer.innerHTML = `+ <header>+ <h2>${esc(w.name || 'Untitled')}</h2>+ <button class="btn sec" data-close type="button" aria-label="Close details">Close</button>+ </header>+ <div class="body">+ <div class="frame-lg"><iframe src="${attr(previewSrc)}" title="Preview"></iframe></div>+ <div>+ <span class="pill"><span class="dot" style="background:${attr(meta.color)}"></span>${esc(meta.label)}</span>+ <span class="muted" style="margin-left:8px">${esc(w.is_public ? 'Public' : 'Private')} · updated ${timeAgo(w.updated_at)}</span>+ </div>+ <div id="stats-region" aria-live="polite"><div class="muted">Loading stats…</div></div>+ <details>+ <summary>Embed code</summary>+ <div style="display:flex; flex-direction:column; gap:10px; margin-top:8px">+ <div>+ <div class="row" style="justify-content:space-between; margin-bottom:4px"><strong style="font-size:12px">Iframe</strong><button class="btn sec" data-copy="iframe" type="button">Copy</button></div>+ <pre id="snip-iframe" style="margin:0">${esc(iframeSnippet)}</pre>+ </div>+ <div>+ <div class="row" style="justify-content:space-between; margin-bottom:4px"><strong style="font-size:12px">One-line script</strong><button class="btn sec" data-copy="script" type="button">Copy</button></div>+ <pre id="snip-script" style="margin:0">${esc(scriptSnippet)}</pre>+ </div>+ <div>+ <div class="row" style="justify-content:space-between; margin-bottom:4px"><strong style="font-size:12px">Direct URL</strong><button class="btn sec" data-copy="url" type="button">Copy</button></div>+ <pre id="snip-url" style="margin:0">${esc(pageUrl)}</pre>+ </div>+ </div>+ </details>+ <details>+ <summary>Configuration (read-only)</summary>+ <pre style="margin:8px 0 0; max-height:220px">${esc(JSON.stringify(w.config || {}, null, 2))}</pre>+ </details>+ <div class="danger-zone">+ <h3>Danger zone</h3>+ <p class="muted" style="margin:0 0 10px; font-size:12px">Deleting removes the widget for everyone. Embeds will return 404.</p>+ <button class="btn-primary btn-danger" data-drawer-delete type="button">Delete this widget</button>+ </div>+ </div>+ `;++ document.body.appendChild(overlay);+ document.body.appendChild(drawer);+ requestAnimationFrame(() => {+ overlay.classList.add('open');+ drawer.classList.add('open');+ });+ drawer.focus();++ const close = () => {+ overlay.classList.remove('open');+ drawer.classList.remove('open');+ setTimeout(() => {+ overlay.remove();+ drawer.remove();+ document.removeEventListener('keydown', onKey);+ }, 220);+ };+ const onKey = (e) => {+ if (e.key === 'Escape') close();+ };+ document.addEventListener('keydown', onKey);+ overlay.addEventListener('click', close);+ drawer.querySelector('[data-close]').addEventListener('click', close);++ for (const btn of drawer.querySelectorAll('[data-copy]')) {+ btn.addEventListener('click', async () => {+ const target = drawer.querySelector(`#snip-${btn.dataset.copy}`);+ if (target) await copyToClipboard(target.textContent, btn);+ });+ }++ drawer.querySelector('[data-drawer-delete]').addEventListener('click', async () => {+ if (!confirm(`Delete "${w.name || 'this widget'}"? This cannot be undone.`)) return;+ try {+ await api.deleteWidget(w.id);+ toast('Deleted');+ close();+ ctx?.remove?.();+ } catch (err) {+ toast(err.message || 'Delete failed', true);+ }+ });++ // Stats — load async, render sparkline.+ try {+ const { stats } = await api.widgetStats(w.id);+ drawer.querySelector('#stats-region').innerHTML = renderStatsPanel(w, stats);+ } catch (err) {+ drawer.querySelector('#stats-region').innerHTML =+ `<div class="err">${esc(err.message || 'Failed to load stats')}</div>`;+ }+}++function renderStatsPanel(w, stats) {+ const total7d = (stats.recent_views_7d || []).reduce((s, d) => s + (d.count || 0), 0);+ const chatLine =+ stats.chat_count !== null && stats.chat_count !== undefined+ ? `<div class="stat"><div class="n">${formatNum(stats.chat_count)}</div><div class="l">Chats (lifetime)</div></div>`+ : '';+ const lastSeen = stats.last_viewed_at+ ? `<div class="muted" style="margin-top:4px; font-size:12px">Last viewed ${timeAgo(stats.last_viewed_at)}</div>`+ : '';+ const referers = (stats.top_referers || []).slice(0, 3);+ const refList = referers.length+ ? `<details><summary>Top referrers</summary><ul style="margin:6px 0 0; padding-left:18px; font-size:12px; color:#aaa">${referers.map((r) => `<li>${esc(r.host || '(direct)')} — ${formatNum(r.count)}</li>`).join('')}</ul></details>`+ : '';+ return `+ <div class="stat-grid">+ <div class="stat"><div class="n">${formatNum(stats.view_count)}</div><div class="l">Views (lifetime)</div></div>+ <div class="stat"><div class="n">${formatNum(total7d)}</div><div class="l">Views (7 days)</div></div>+ ${chatLine}+ </div>+ ${lastSeen}+ <div style="margin-top:14px">+ ${sparkline(stats.recent_views_7d || [])}+ </div>+ ${refList}+ `;+}++function sparkline(days) {+ if (!days.length) return '<div class="muted" style="font-size:12px">No views yet</div>';+ const W = 480,+ H = 60,+ P = 4;+ const max = Math.max(1, ...days.map((d) => d.count || 0));+ const stepX = (W - 2 * P) / Math.max(1, days.length - 1);+ const pts = days.map((d, i) => {+ const x = P + i * stepX;+ const y = H - P - ((d.count || 0) / max) * (H - 2 * P);+ return [x, y];+ });+ const linePath = pts+ .map((p, i) =>+ i === 0+ ? `M${p[0].toFixed(1)},${p[1].toFixed(1)}`+ : `L${p[0].toFixed(1)},${p[1].toFixed(1)}`,+ )+ .join(' ');+ const areaPath = `${linePath} L${pts[pts.length - 1][0].toFixed(1)},${H - P} L${pts[0][0].toFixed(1)},${H - P} Z`;+ const allZero = days.every((d) => !d.count);+ const labels = `${esc(days[0].day)} → ${esc(days[days.length - 1].day)}`;+ return `+ <svg class="spark" viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" role="img" aria-label="Views over the last 7 days, ${days.map((d) => `${d.day}: ${d.count}`).join(', ')}">+ <line class="axis" x1="${P}" y1="${H - P}" x2="${W - P}" y2="${H - P}"></line>+ ${allZero ? '' : `<path class="area" d="${areaPath}"></path><path class="line" d="${linePath}"></path>`}+ </svg>+ <div class="muted" style="font-size:11px; display:flex; justify-content:space-between; padding:0 4px">+ <span>${labels}</span>+ <span>${allZero ? 'No views yet' : `peak ${max}`}</span>+ </div>+ `;+}++// ── Share modal ─────────────────────────────────────────────────────────────+function openShareModal(w) {+ const SIZES = [+ { label: 'Small', width: 320, height: 320 },+ { label: 'Medium', width: 600, height: 600 },+ { label: 'Banner', width: 1200, height: 400 },+ { label: 'Custom', width: 0, height: 0 },+ ];+ let active = 1;+ let dim = { ...SIZES[active] };+ const pageUrl = `${location.origin}/w/${encodeURIComponent(w.id)}`;++ const overlay = document.createElement('div');+ overlay.className = 'modal-overlay';+ overlay.innerHTML = `+ <div class="modal" role="dialog" aria-label="Share widget">+ <h2>Share "${esc(w.name || 'widget')}"</h2>+ <p class="sub">Pick a size, copy the iframe, and you're done.</p>+ <div class="size-presets" role="tablist">+ ${SIZES.map((s, i) => `<button type="button" data-i="${i}" class="${i === active ? 'active' : ''}" role="tab" aria-selected="${i === active}">${esc(s.label)}${s.width ? ` (${s.width}×${s.height})` : ''}</button>`).join('')}+ </div>+ <div class="size-inputs">+ <label class="muted" style="font-size:12px">W <input id="m-w" type="number" min="120" max="2000" value="${dim.width || 600}"></label>+ <label class="muted" style="font-size:12px">H <input id="m-h" type="number" min="120" max="2000" value="${dim.height || 600}"></label>+ </div>+ <div style="background:#0f0f17; border:1px solid var(--border); border-radius:10px; padding:12px; margin-bottom:12px">+ <div class="muted" style="font-size:11px; margin-bottom:8px">Live preview (scaled to fit)</div>+ <div id="m-preview" style="display:grid; place-items:center; min-height:200px; max-height:340px; overflow:hidden"></div>+ </div>+ <div>+ <div class="row" style="justify-content:space-between; margin-bottom:4px"><strong style="font-size:12px">Iframe</strong><button class="btn sec" id="m-copy" type="button">Copy</button></div>+ <pre id="m-snip" style="margin:0"></pre>+ </div>+ <div class="row" style="justify-content:space-between; margin-top:14px">+ <a class="muted" style="font-size:12px" href="mailto:[email protected]?subject=Report+widget+${encodeURIComponent(w.id)}">Report this widget</a>+ <button class="btn sec" id="m-close" type="button">Close</button>+ </div>+ </div>+ `;+ document.body.appendChild(overlay);+ requestAnimationFrame(() => overlay.classList.add('open'));++ const wInput = overlay.querySelector('#m-w');+ const hInput = overlay.querySelector('#m-h');+ const snipEl = overlay.querySelector('#m-snip');+ const previewEl = overlay.querySelector('#m-preview');++ function refresh() {+ const snippet = makeIframeSnippet(w, pageUrl, dim.width, dim.height);+ snipEl.textContent = snippet;+ // Live preview at scaled size — fit within 320×320 while preserving ratio.+ const maxW = 320,+ maxH = 320;+ const scale = Math.min(maxW / dim.width, maxH / dim.height, 1);+ previewEl.innerHTML = `<iframe src="/#widget=${encodeURIComponent(w.id)}&kiosk=true&preview=1" style="width:${dim.width}px; height:${dim.height}px; border:0; transform:scale(${scale}); transform-origin:center" title="Preview"></iframe>`;+ previewEl.style.width = `${dim.width * scale}px`;+ previewEl.style.height = `${dim.height * scale}px`;+ }+ function setPreset(i) {+ active = i;+ overlay.querySelectorAll('.size-presets button').forEach((b, j) => {+ b.classList.toggle('active', i === j);+ b.setAttribute('aria-selected', i === j ? 'true' : 'false');+ });+ if (SIZES[i].width) {+ dim = { width: SIZES[i].width, height: SIZES[i].height };+ wInput.value = dim.width;+ hInput.value = dim.height;+ }+ refresh();+ }+ overlay.querySelectorAll('.size-presets button').forEach((b) => {+ b.addEventListener('click', () => setPreset(Number(b.dataset.i)));+ });+ const onDimChange = () => {+ dim = {+ width: clampInt(wInput.value, 120, 2000, 600),+ height: clampInt(hInput.value, 120, 2000, 600),+ };+ // Switch to "Custom" preset when typing.+ setPresetSilent(SIZES.length - 1);+ refresh();+ };+ function setPresetSilent(i) {+ active = i;+ overlay.querySelectorAll('.size-presets button').forEach((b, j) => {+ b.classList.toggle('active', i === j);+ b.setAttribute('aria-selected', i === j ? 'true' : 'false');+ });+ }+ wInput.addEventListener('input', onDimChange);+ hInput.addEventListener('input', onDimChange);++ const close = () => {+ overlay.classList.remove('open');+ setTimeout(() => {+ overlay.remove();+ document.removeEventListener('keydown', onKey);+ }, 200);+ };+ const onKey = (e) => {+ if (e.key === 'Escape') close();+ };+ document.addEventListener('keydown', onKey);+ overlay.addEventListener('click', (e) => {+ if (e.target === overlay) close();+ });+ overlay.querySelector('#m-close').addEventListener('click', close);+ overlay+ .querySelector('#m-copy')+ .addEventListener('click', (e) => copyToClipboard(snipEl.textContent, e.currentTarget));++ refresh();+}++function clampInt(v, lo, hi, fallback) {+ const n = parseInt(v, 10);+ if (Number.isNaN(n)) return fallback;+ return Math.max(lo, Math.min(hi, n));+}++function makeIframeSnippet(w, pageUrl, width, height) {+ const title = (w.name || 'Widget').replace(/"/g, '"');+ return `<iframe src="${pageUrl}" width="${width}" height="${height}" style="border:0;border-radius:12px;max-width:100%" allow="autoplay; xr-spatial-tracking; clipboard-write" title="${title}" loading="lazy"></iframe>`;+}++// ── shared widget UI helpers ────────────────────────────────────────────────+async function copyToClipboard(text, btn) {+ try {+ await navigator.clipboard.writeText(text);+ toast('Copied to clipboard');+ if (btn) {+ const orig = btn.textContent;+ btn.textContent = 'Copied';+ setTimeout(() => {+ btn.textContent = orig;+ }, 1100);+ }+ } catch {+ toast('Copy failed — select and ⌘C manually', true);+ }+}++let _toastTimer;+function toast(message, isError = false) {+ const existing = document.querySelector('.toast');+ if (existing) existing.remove();+ clearTimeout(_toastTimer);+ const el = document.createElement('div');+ el.className = 'toast';+ if (isError) {+ el.style.color = '#ffb3b3';+ el.style.borderColor = 'rgba(255,92,92,.4)';+ }+ el.setAttribute('role', isError ? 'alert' : 'status');+ el.textContent = message;+ document.body.appendChild(el);+ _toastTimer = setTimeout(() => {+ el.style.opacity = '0';+ el.style.transition = 'opacity .25s';+ setTimeout(() => el.remove(), 260);+ }, 2200);+}++function timeAgo(ts) {+ if (!ts) return 'never';+ const then = new Date(ts).getTime();+ const now = Date.now();+ const sec = Math.max(1, Math.round((now - then) / 1000));+ if (sec < 60) return `${sec}s ago`;+ const min = Math.round(sec / 60);+ if (min < 60) return `${min}m ago`;+ const hr = Math.round(min / 60);+ if (hr < 24) return `${hr}h ago`;+ const day = Math.round(hr / 24);+ if (day < 30) return `${day}d ago`;+ const mo = Math.round(day / 30);+ if (mo < 12) return `${mo}mo ago`;+ return `${Math.round(mo / 12)}y ago`;+}++function formatNum(n) {+ const v = Number(n || 0);+ if (v < 1000) return String(v);+ if (v < 10000) return (v / 1000).toFixed(1).replace(/\.0$/, '') + 'k';+ if (v < 1_000_000) return Math.round(v / 1000) + 'k';+ return (v / 1_000_000).toFixed(1).replace(/\.0$/, '') + 'M';+}++function formatViewCount(n) {+ const v = Number(n || 0);+ if (v === 0) return 'No views';+ if (v === 1) return '1 view';+ return `${formatNum(v)} views`;+}++// ── Animations ───────────────────────────────────────────────────────────────+async function renderAnimations(root) {+ root.innerHTML = `+ <div class="toolbar">+ <div>+ <h1>Animations</h1>+ <p class="sub">Manage animation clips attached to your agent. Changes sync to the viewer automatically.</p>+ </div>+ </div>+ <div id="anim-body"><div class="muted">Loading…</div></div>+ `;+ const body = root.querySelector('#anim-body');++ let agent, avatarUrl;+ try {+ const res = await api.getAgentMe();+ agent = res?.agent;+ if (!agent) {+ body.innerHTML = `<div class="empty">No agent found. <a href="#create">Create one first.</a></div>`;+ return;+ }+ if (agent.avatar_id) {+ try {+ const av = await api.getAvatar(agent.avatar_id);+ avatarUrl = av?.avatar?.url || av?.avatar?.model_url;+ } catch {+ /* no avatar URL */+ }+ }+ } catch (e) {+ body.innerHTML = `<div class="err">${esc(e.message)}</div>`;+ return;+ }++ let animations = Array.isArray(agent.meta?.animations) ? [...agent.meta.animations] : [];+ let presets = [];+ try {+ presets = await fetch('/animations/presets.json').then((r) => r.json());+ } catch {+ /* presets unavailable */+ }++ let saveTimer;+ const statusEl = document.createElement('p');+ statusEl.className = 'muted';+ statusEl.style.cssText = 'margin:4px 0 0;font-size:12px;min-height:18px;';++ function debounceSync() {+ clearTimeout(saveTimer);+ saveTimer = setTimeout(async () => {+ statusEl.style.color = '#888';+ statusEl.textContent = 'Saving…';+ try {+ await api.patchAgentAnimations(agent.id, animations);+ statusEl.style.color = '#9a8cff';+ statusEl.textContent = 'Saved.';+ setTimeout(() => {+ if (statusEl.textContent === 'Saved.') statusEl.textContent = '';+ }, 2000);+ } catch (err) {+ statusEl.style.color = '#ffb3b3';+ statusEl.textContent = err.message || 'Save failed.';+ }+ }, 500);+ }++ function isAttached(name) {+ return animations.some((a) => a.name.toLowerCase() === name.toLowerCase());+ }++ let listEl, presetGridEl;++ function renderClipList() {+ listEl.innerHTML = '';+ if (!animations.length) {+ listEl.innerHTML =+ '<div class="muted" style="padding:12px 0">No clips attached yet.</div>';+ return;+ }+ for (const clip of animations) {+ const row = document.createElement('div');+ row.className = 'clip-row';+ row.innerHTML = `+ <span class="clip-name">${esc(clip.name)}</span>+ <span class="clip-source">${esc(clip.source || 'custom')}</span>+ <label class="loop-toggle" title="Toggle loop">+ <input type="checkbox" ${clip.loop !== false ? 'checked' : ''}>+ <span>Loop</span>+ </label>+ <div class="clip-actions">+ <button class="preview-btn">Preview</button>+ <button class="danger detach-btn">Remove</button>+ </div>+ `;+ row.querySelector('.loop-toggle input').addEventListener('change', (e) => {+ clip.loop = e.target.checked;+ debounceSync();+ });+ row.querySelector('.detach-btn').addEventListener('click', () => {+ animations = animations.filter((a) => a !== clip);+ renderClipList();+ renderPresetGrid();+ debounceSync();+ });+ row.querySelector('.preview-btn').addEventListener('click', () =>+ openAnimPreview(clip, avatarUrl),+ );+ listEl.appendChild(row);+ }+ }++ function renderPresetGrid() {+ if (!presetGridEl) return;+ presetGridEl.innerHTML = '';+ for (const p of presets) {+ const tile = document.createElement('div');+ const attached = isAttached(p.name);+ tile.className = 'preset-tile' + (attached ? ' attached' : '');+ tile.innerHTML = `<div class="icon">${esc(p.icon || '🎬')}</div><div class="label">${esc(p.label || p.name)}</div>`;+ tile.title = attached ? 'Already attached' : `Add "${p.name}"`;+ tile.addEventListener('click', () => {+ if (isAttached(p.name)) {+ toast('Already attached');+ return;+ }+ animations.push({+ name: p.name,+ url: p.url,+ loop: p.loop !== false,+ clipName: p.clipName || undefined,+ source: 'preset',+ addedAt: new Date().toISOString(),+ });+ renderClipList();+ renderPresetGrid();+ debounceSync();+ });+ presetGridEl.appendChild(tile);+ }+ }++ body.innerHTML = '';++ if (agent.is_registered) {+ const warn = document.createElement('div');+ warn.className = 'anim-notice';+ warn.innerHTML = `<strong>On-chain notice:</strong> Your agent has an ERC-8004 registration. Animation changes won't be visible on-chain until you re-pin the manifest. <button class="btn sec" style="margin-left:8px;font-size:11px;padding:4px 10px;" disabled title="Re-pin not implemented — update your manifest manually">Re-pin manifest</button>`;+ body.appendChild(warn);+ }++ const cols = document.createElement('div');+ cols.className = 'anim-cols';++ const leftCol = document.createElement('div');+ const lh = document.createElement('h3');+ lh.textContent = 'Attached clips';+ leftCol.appendChild(lh);+ listEl = document.createElement('div');+ leftCol.appendChild(listEl);+ leftCol.appendChild(statusEl);++ const rightCol = document.createElement('div');+ const rh = document.createElement('h3');+ rh.textContent = 'Add clips';+ rightCol.appendChild(rh);++ if (presets.length) {+ const pl = document.createElement('p');+ pl.className = 'muted';+ pl.style.margin = '0 0 8px';+ pl.textContent = 'Presets';+ rightCol.appendChild(pl);+ presetGridEl = document.createElement('div');+ presetGridEl.className = 'preset-grid';+ rightCol.appendChild(presetGridEl);+ }++ const uploadDiv = document.createElement('div');+ uploadDiv.innerHTML = `+ <p class="muted" style="margin:16px 0 8px">Upload custom .glb</p>+ <div class="anim-upload">+ <label style="display:block">Name <input id="anim-name" type="text" placeholder="e.g. my-wave" maxlength="60" style="width:100%;margin-top:4px"></label>+ <label style="display:block;margin-top:8px">File <input id="anim-file" type="file" accept=".glb,model/gltf-binary" style="width:100%;margin-top:4px"></label>+ <div id="anim-progress" class="muted" style="font-size:12px;min-height:18px;margin-top:4px"></div>+ <button class="btn" id="anim-upload-btn" style="align-self:flex-start;margin-top:6px">Upload & attach</button>+ <div id="anim-err" class="anim-inline-err"></div>+ </div>+ `;+ rightCol.appendChild(uploadDiv);+ cols.appendChild(leftCol);+ cols.appendChild(rightCol);+ body.appendChild(cols);++ renderClipList();+ renderPresetGrid();++ const uploadBtn = body.querySelector('#anim-upload-btn');+ const uploadProgress = body.querySelector('#anim-progress');+ const uploadErr = body.querySelector('#anim-err');+ uploadBtn.addEventListener('click', async () => {+ const nameEl = body.querySelector('#anim-name');+ const fileEl = body.querySelector('#anim-file');+ const name = nameEl.value.trim();+ const file = fileEl.files?.[0];+ uploadErr.textContent = '';+ if (!name) {+ uploadErr.textContent = 'Name is required.';+ return;+ }+ if (name.length > 60) {+ uploadErr.textContent = 'Name too long (max 60 chars).';+ return;+ }+ if (isAttached(name)) {+ uploadErr.textContent = `"${name}" is already attached.`;+ return;+ }+ if (!file) {+ uploadErr.textContent = 'Select a .glb file.';+ return;+ }+ uploadBtn.disabled = true;+ uploadProgress.textContent = 'Requesting upload URL…';+ try {+ const slug =+ name+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-|-$/g, '') || 'anim';+ const { upload_url, storage_key } = await api.presignAnimation({+ size_bytes: file.size,+ content_type: 'model/gltf-binary',+ slug,+ });+ uploadProgress.textContent = `Uploading ${fmtSize(file.size)}…`;+ await _uploadXHR(upload_url, file, (pct) => {+ uploadProgress.textContent = `Uploading ${pct}%…`;+ });+ animations.push({+ name,+ url: storage_key,+ loop: true,+ source: 'custom',+ addedAt: new Date().toISOString(),+ });+ renderClipList();+ renderPresetGrid();+ debounceSync();+ uploadProgress.textContent = 'Uploaded and attached.';+ nameEl.value = '';+ fileEl.value = '';+ } catch (err) {+ uploadErr.textContent = err.message || 'Upload failed.';+ uploadProgress.textContent = '';+ } finally {+ uploadBtn.disabled = false;+ }+ });+}++function _uploadXHR(url, file, onProgress) {+ return new Promise((resolve, reject) => {+ const xhr = new XMLHttpRequest();+ xhr.open('PUT', url);+ xhr.setRequestHeader('content-type', 'model/gltf-binary');+ xhr.upload.onprogress = (e) =>+ e.lengthComputable && onProgress(Math.round((e.loaded / e.total) * 100));+ xhr.onload = () =>+ xhr.status >= 200 && xhr.status < 300+ ? resolve()+ : reject(new Error(`Upload failed (${xhr.status})`));+ xhr.onerror = () => reject(new Error('Network error'));+ xhr.send(file);+ });+}++let _animPreviewEl = null;++async function _ensureAgent3DLib() {+ if (customElements.get('agent-3d')) return true;+ try {+ await import('/dist-lib/agent-3d.js');+ return true;+ } catch {+ return false;+ }+}++async function openAnimPreview(clip, avatarUrl) {+ if (!avatarUrl) {+ toast('No avatar URL available for preview', true);+ return;+ }++ let overlay = document.getElementById('anim-preview-overlay');+ if (!overlay) {+ overlay = document.createElement('div');+ overlay.id = 'anim-preview-overlay';+ overlay.className = 'modal-overlay';+ overlay.innerHTML = `+ <div class="modal" style="width:min(400px,calc(100vw - 32px));padding:18px">+ <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px">+ <h2 id="ap-title" style="margin:0;font-size:16px"></h2>+ <button id="ap-close" class="btn sec" style="padding:4px 10px">✕</button>+ </div>+ <div class="preview-stage" id="ap-stage"></div>+ <p id="ap-status" class="muted" style="margin:8px 0 0;font-size:12px">Loading…</p>+ </div>+ `;+ document.body.appendChild(overlay);+ overlay.querySelector('#ap-close').addEventListener('click', closeAnimPreview);+ overlay.addEventListener('click', (e) => {+ if (e.target === overlay) closeAnimPreview();+ });+ }++ closeAnimPreview();+ overlay.classList.add('open');+ overlay.querySelector('#ap-title').textContent = `Preview: "${clip.name}"`;+ const stage = overlay.querySelector('#ap-stage');+ const status = overlay.querySelector('#ap-status');+ stage.innerHTML = '';+ status.textContent = 'Loading library…';++ const ok = await _ensureAgent3DLib();+ if (!ok) {+ status.textContent = 'Could not load 3D viewer.';+ return;+ }++ const el = document.createElement('agent-3d');+ el.setAttribute('body', avatarUrl);+ el.setAttribute('kiosk', '');+ el.setAttribute('eager', '');+ el.style.cssText = 'width:100%;height:100%;display:block';+ stage.appendChild(el);+ _animPreviewEl = el;++ status.textContent = 'Loading avatar…';+ try {+ await new Promise((resolve, reject) => {+ const onReady = () => {+ el.removeEventListener('agent:ready', onReady);+ el.removeEventListener('agent:error', onErr);+ resolve();+ };+ const onErr = (e) => {+ el.removeEventListener('agent:ready', onReady);+ el.removeEventListener('agent:error', onErr);+ reject(new Error(e.detail?.error?.message || 'load failed'));+ };+ el.addEventListener('agent:ready', onReady);+ el.addEventListener('agent:error', onErr);+ });+ } catch (e) {+ status.textContent = `Error: ${e.message}`;+ return;+ }++ let hasBones = false;+ el._scene?.content?.traverse?.((n) => {+ if (n.isBone) hasBones = true;+ });+ if (!hasBones) {+ status.textContent = 'This avatar has no skeleton — clips cannot be previewed.';+ return;+ }++ status.textContent = `Loading clip "${clip.name}"…`;+ try {+ const gltf = await el._scene.loadGLB(clip.url);+ const clips = gltf?.animations || [];+ const target = clip.clipName+ ? clips.find((c) => c.name === clip.clipName) || clips[0]+ : clips[0];+ if (!target) {+ status.textContent = 'No animation found in clip file.';+ return;+ }+ await el._scene.play(target, { blend: 0.35 });+ status.textContent = `Playing "${clip.name}"`;+ } catch (e) {+ status.textContent = `Preview error: ${e.message}`;+ }+}++function closeAnimPreview() {+ if (_animPreviewEl) {+ try {+ _animPreviewEl.destroy?.();+ } catch {}+ try {+ _animPreviewEl.remove();+ } catch {}+ _animPreviewEl = null;+ }+ const stage = document.getElementById('ap-stage');+ if (stage) stage.innerHTML = '';+ const overlay = document.getElementById('anim-preview-overlay');+ if (overlay) overlay.classList.remove('open');+}++// ── utils ───────────────────────────────────────────────────────────────────+function fmtSize(b) {+ if (b < 1024) return b + ' B';+ if (b < 1024 * 1024) return (b / 1024).toFixed(1) + ' KB';+ return (b / 1024 / 1024).toFixed(1) + ' MB';+}+function esc(s) {+ return String(s ?? '').replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}+function attr(s) {+ return esc(s);+}diff --git a/dist-artifact/dashboard/embed-policy.html b/dist-artifact/dashboard/embed-policy.htmlnew file mode 100644index 000000000..e9985f065--- /dev/null+++ b/dist-artifact/dashboard/embed-policy.html@@ -0,0 +1,612 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <title>Embed policy · 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: 16px 24px;+ border-bottom: 1px solid var(--border);+ position: sticky;+ top: 0;+ background: var(--bg);+ z-index: 5;+ }+ .brand {+ font-weight: 600;+ letter-spacing: -0.01em;+ }+ main {+ padding: 28px;+ max-width: 720px;+ margin: 0 auto;+ }+ h1 {+ font-size: 22px;+ margin: 0 0 6px;+ letter-spacing: -0.01em;+ }+ .sub {+ color: #888;+ margin: 0 0 22px;+ font-size: 14px;+ }+ .card {+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 14px;+ padding: 20px;+ margin-bottom: 20px;+ }+ fieldset {+ border: 0;+ padding: 0;+ margin: 0;+ }+ legend {+ font-size: 13px;+ font-weight: 600;+ color: #ccc;+ margin-bottom: 12px;+ letter-spacing: 0.02em;+ text-transform: uppercase;+ }+ label {+ display: block;+ margin: 14px 0 6px;+ font-size: 13px;+ color: #bbb;+ }+ label.check {+ display: flex;+ align-items: center;+ gap: 8px;+ margin: 8px 0;+ cursor: pointer;+ color: #ccc;+ }+ label.check input {+ width: auto;+ margin: 0;+ }+ input,+ select,+ textarea {+ background: #0f0f17;+ border: 1px solid var(--border);+ color: #eee;+ padding: 9px 11px;+ border-radius: 8px;+ font-size: 14px;+ font-family: inherit;+ width: 100%;+ }+ textarea {+ min-height: 120px;+ font-family:+ ui-monospace,+ SF Mono,+ Menlo,+ monospace;+ font-size: 13px;+ }+ input:focus,+ textarea:focus,+ select:focus {+ outline: none;+ border-color: var(--accent);+ }+ input[type='checkbox'] {+ width: 16px;+ height: 16px;+ accent-color: var(--accent);+ }+ input[type='number'] {+ -moz-appearance: textfield;+ }+ .row {+ display: flex;+ gap: 10px;+ align-items: center;+ }+ .col2 {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 12px;+ }+ .btn {+ padding: 9px 14px;+ border-radius: 9px;+ border: 0;+ font-size: 13px;+ font-weight: 600;+ cursor: pointer;+ background: var(--accent);+ color: #fff;+ }+ .btn.sec {+ background: #222230;+ color: #ddd;+ }+ .btn.danger {+ background: #3a1f24;+ color: #ff9c9c;+ }+ .muted {+ color: #888;+ font-size: 13px;+ }+ .err {+ padding: 12px;+ background: rgba(255, 92, 92, 0.1);+ border: 1px solid rgba(255, 92, 92, 0.3);+ border-radius: 8px;+ color: #ffb3b3;+ margin-bottom: 14px;+ }+ .ok {+ padding: 12px;+ background: rgba(92, 255, 140, 0.07);+ border: 1px solid rgba(92, 255, 140, 0.2);+ border-radius: 8px;+ color: #b6f2c6;+ margin-bottom: 14px;+ }+ code {+ font-family:+ ui-monospace,+ SF Mono,+ Menlo,+ monospace;+ background: #0f0f17;+ border: 1px solid var(--border);+ border-radius: 4px;+ padding: 1px 6px;+ font-size: 12px;+ }+ .actions {+ display: flex;+ gap: 10px;+ margin-top: 22px;+ }+ hr {+ border: 0;+ border-top: 1px solid var(--border);+ margin: 22px 0;+ }+ .hidden {+ display: none !important;+ }+ </style>+ </head>+ <body>+ <header>+ <div class="brand"><a href="/dashboard">← Dashboard</a></div>+ <div class="muted"><span id="agent-name">Agent</span></div>+ </header>+ <main>+ <h1>Embed policy</h1>+ <p class="sub">+ Control how <code id="embed-url"></code> can be embedded across the web.+ </p>++ <div id="status"></div>++ <!-- Origins -->+ <div class="card">+ <fieldset>+ <legend>Origins</legend>+ <label for="mode">Policy mode</label>+ <select id="mode">+ <option value="off">Off — allow all embeds</option>+ <option value="allowlist">Allowlist — only these hosts</option>+ <option value="denylist">Denylist — everywhere except these hosts</option>+ </select>++ <div id="hosts-wrap">+ <label for="hosts">Hosts (one per line)</label>+ <textarea+ id="hosts"+ placeholder="example.com *.substack.com"+ ></textarea>+ <div class="muted" style="margin-top: 6px">+ One host per line. Use <code>*.example.com</code> to match all+ subdomains.+ </div>+ </div>+ </fieldset>+ </div>++ <!-- Surfaces -->+ <div class="card">+ <fieldset>+ <legend>Surfaces</legend>+ <div class="muted" style="margin-bottom: 12px">+ Choose which embed surfaces are enabled for this agent.+ </div>+ <label class="check"+ ><input type="checkbox" id="surf-script" />+ <span+ ><strong>Script tag</strong> — <code><agent-3d></code> on+ third-party pages</span+ ></label+ >+ <label class="check"+ ><input type="checkbox" id="surf-iframe" />+ <span+ ><strong>iframe</strong> —+ <code><iframe src="/agent/:id/embed"></code></span+ ></label+ >+ <label class="check"+ ><input type="checkbox" id="surf-widget" />+ <span+ ><strong>Widget</strong> — <code>/w/:id</code> widget pages</span+ ></label+ >+ <label class="check"+ ><input type="checkbox" id="surf-mcp" />+ <span+ ><strong>MCP</strong> — exposed as an MCP tool over+ <code>/api/mcp</code></span+ ></label+ >+ </fieldset>+ </div>++ <!-- Brain -->+ <div class="card">+ <fieldset>+ <legend>Brain / LLM</legend>+ <label for="brain-mode">Payment mode</label>+ <select id="brain-mode">+ <option value="we-pay">+ We-pay — 3D Agent covers API costs (quota-limited)+ </option>+ <option value="key-proxy">+ Key-proxy — calls routed through your proxy URL+ </option>+ <option value="wallet-gated">+ Wallet-gated — user pays via connected wallet+ </option>+ <option value="none">None — LLM disabled for this agent</option>+ </select>++ <div id="proxy-url-wrap">+ <label for="brain-proxy-url">Proxy URL</label>+ <input+ type="url"+ id="brain-proxy-url"+ placeholder="https://owner.example/llm"+ />+ </div>++ <div class="col2" style="margin-top: 14px">+ <div>+ <label for="brain-quota">Monthly quota (completions)</label>+ <input+ type="number"+ id="brain-quota"+ min="0"+ placeholder="1000 (blank = unlimited)"+ />+ </div>+ <div>+ <label for="brain-rate">Rate limit (req / min)</label>+ <input+ type="number"+ id="brain-rate"+ min="0"+ placeholder="10 (blank = unlimited)"+ />+ </div>+ </div>++ <label for="brain-model">Model</label>+ <input type="text" id="brain-model" placeholder="claude-opus-4-6" />+ </fieldset>+ </div>++ <!-- Storage -->+ <div class="card">+ <fieldset>+ <legend>Storage</legend>+ <label for="storage-primary">Primary storage</label>+ <select id="storage-primary">+ <option value="r2">R2 (Cloudflare) — default</option>+ <option value="ipfs">IPFS — decentralised</option>+ </select>++ <label class="check" style="margin-top: 14px">+ <input type="checkbox" id="storage-ipfs" disabled />+ <span+ ><strong>IPFS pin</strong> — avatar pinned to IPFS+ <em class="muted">(pin flow coming soon)</em></span+ >+ </label>+ <label class="check">+ <input type="checkbox" id="storage-attested" disabled />+ <span+ ><strong>On-chain attestation</strong> — content hash recorded on-chain+ <em class="muted">(coming soon)</em></span+ >+ </label>+ </fieldset>+ </div>++ <div class="actions">+ <button class="btn" id="save">Save</button>+ <button class="btn sec" id="reload">Reload</button>+ <button class="btn danger" id="clear" style="margin-left: auto">+ Clear policy+ </button>+ </div>++ <hr />++ <div class="muted">+ Signed-in owners can preview the embed bypassing this policy by appending+ <code>?preview=1</code> to the embed URL.+ </div>+ </main>+ <script type="module">+ const params = new URL(location.href).searchParams;+ const agentId = params.get('agent');+ const statusEl = document.getElementById('status');+ const modeSel = document.getElementById('mode');+ const hostsEl = document.getElementById('hosts');+ const hostsWrap = document.getElementById('hosts-wrap');+ const nameEl = document.getElementById('agent-name');+ const urlEl = document.getElementById('embed-url');+ const brainModeSel = document.getElementById('brain-mode');+ const proxyWrap = document.getElementById('proxy-url-wrap');++ if (!agentId) {+ statusEl.innerHTML =+ '<div class="err">Missing <code>?agent=ID</code> in URL.</div>';+ throw new Error('no agent id');+ }+ urlEl.textContent = `/agent/${agentId}/embed`;++ async function api(method, path, body) {+ const res = await fetch(path, {+ method,+ credentials: 'include',+ headers: body ? { 'content-type': 'application/json' } : {},+ body: body ? JSON.stringify(body) : undefined,+ });+ const ct = res.headers.get('content-type') || '';+ const data = ct.includes('application/json') ? await res.json() : null;+ if (!res.ok)+ throw Object.assign(+ new Error((data && data.error_description) || res.statusText),+ { status: res.status, fields: data?.fields },+ );+ return data;+ }++ function setStatus(html) {+ statusEl.innerHTML = html;+ }++ function updateOriginVisibility() {+ hostsWrap.style.display = modeSel.value === 'off' ? 'none' : '';+ }++ function updateBrainVisibility() {+ proxyWrap.classList.toggle('hidden', brainModeSel.value !== 'key-proxy');+ }++ async function loadMe() {+ try {+ await api('GET', '/api/auth/me');+ } catch {+ location.href =+ '/login?next=' + encodeURIComponent(location.pathname + location.search);+ throw new Error('redirecting');+ }+ }++ async function loadAgent() {+ try {+ const { agent } = await api('GET', `/api/agents/${agentId}`);+ nameEl.textContent = agent.name || 'Agent';+ } catch (e) {+ setStatus(+ `<div class="err">Could not load agent: ${escapeHtml(e.message)}</div>`,+ );+ }+ }++ function populateForm(policy) {+ if (!policy) {+ modeSel.value = 'off';+ hostsEl.value = '';+ document.getElementById('surf-script').checked = true;+ document.getElementById('surf-iframe').checked = true;+ document.getElementById('surf-widget').checked = true;+ document.getElementById('surf-mcp').checked = false;+ brainModeSel.value = 'we-pay';+ document.getElementById('brain-proxy-url').value = '';+ document.getElementById('brain-quota').value = '1000';+ document.getElementById('brain-rate').value = '10';+ document.getElementById('brain-model').value = 'claude-opus-4-6';+ document.getElementById('storage-primary').value = 'r2';+ document.getElementById('storage-ipfs').checked = false;+ document.getElementById('storage-attested').checked = false;+ updateOriginVisibility();+ updateBrainVisibility();+ return;+ }++ const orig = policy.origins || {};+ modeSel.value = orig.mode === 'denylist' ? 'denylist' : 'allowlist';+ hostsEl.value = (orig.hosts || []).join('\n');++ const surf = policy.surfaces || {};+ document.getElementById('surf-script').checked = surf.script !== false;+ document.getElementById('surf-iframe').checked = surf.iframe !== false;+ document.getElementById('surf-widget').checked = surf.widget !== false;+ document.getElementById('surf-mcp').checked = !!surf.mcp;++ const brain = policy.brain || {};+ brainModeSel.value = brain.mode || 'we-pay';+ document.getElementById('brain-proxy-url').value = brain.proxy_url || '';+ document.getElementById('brain-quota').value =+ brain.monthly_quota != null ? String(brain.monthly_quota) : '';+ document.getElementById('brain-rate').value =+ brain.rate_limit_per_min != null ? String(brain.rate_limit_per_min) : '';+ document.getElementById('brain-model').value = brain.model || 'claude-opus-4-6';++ const storage = policy.storage || {};+ document.getElementById('storage-primary').value = storage.primary || 'r2';+ document.getElementById('storage-ipfs').checked = !!storage.pinned_ipfs;+ document.getElementById('storage-attested').checked = !!storage.onchain_attested;++ updateOriginVisibility();+ updateBrainVisibility();+ }++ async function loadPolicy() {+ try {+ const { policy } = await api('GET', `/api/agents/${agentId}/embed-policy`);+ populateForm(policy);+ } catch (e) {+ setStatus(+ `<div class="err">Could not load policy: ${escapeHtml(e.message)}</div>`,+ );+ }+ }++ function buildPolicy() {+ const numOrNull = (id) => {+ const v = document.getElementById(id).value.trim();+ return v === '' ? null : parseInt(v, 10);+ };++ return {+ version: 1,+ origins: {+ mode: modeSel.value === 'off' ? 'allowlist' : modeSel.value,+ hosts:+ modeSel.value === 'off'+ ? []+ : hostsEl.value+ .split(/\r?\n/)+ .map((s) => s.trim())+ .filter(Boolean),+ },+ surfaces: {+ script: document.getElementById('surf-script').checked,+ iframe: document.getElementById('surf-iframe').checked,+ widget: document.getElementById('surf-widget').checked,+ mcp: document.getElementById('surf-mcp').checked,+ },+ brain: {+ mode: brainModeSel.value,+ proxy_url: document.getElementById('brain-proxy-url').value.trim() || null,+ monthly_quota: numOrNull('brain-quota'),+ rate_limit_per_min: numOrNull('brain-rate'),+ model:+ document.getElementById('brain-model').value.trim() ||+ 'claude-opus-4-6',+ },+ storage: {+ primary: document.getElementById('storage-primary').value,+ pinned_ipfs: document.getElementById('storage-ipfs').checked,+ onchain_attested: document.getElementById('storage-attested').checked,+ },+ };+ }++ async function save() {+ setStatus('');+ try {+ const { policy } = await api(+ 'PUT',+ `/api/agents/${agentId}/embed-policy`,+ buildPolicy(),+ );+ populateForm(policy);+ setStatus('<div class="ok">Policy saved.</div>');+ } catch (e) {+ let msg = escapeHtml(e.message);+ if (e.fields && e.fields.length) {+ msg +=+ '<br><small>' ++ e.fields+ .map((f) => escapeHtml(f.path?.join('.') + ': ' + f.message))+ .join('<br>') ++ '</small>';+ }+ setStatus(`<div class="err">${msg}</div>`);+ }+ }++ async function clearPolicy() {+ if (!confirm('Clear the embed policy? Defaults will apply.')) return;+ try {+ await api('DELETE', `/api/agents/${agentId}/embed-policy`);+ populateForm(null);+ setStatus('<div class="ok">Policy cleared.</div>');+ } catch (e) {+ setStatus(`<div class="err">${escapeHtml(e.message)}</div>`);+ }+ }++ function escapeHtml(s) {+ return String(s ?? '').replace(+ /[&<>"']/g,+ (c) =>+ ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[+ c+ ],+ );+ }++ modeSel.addEventListener('change', updateOriginVisibility);+ brainModeSel.addEventListener('change', updateBrainVisibility);+ document.getElementById('save').addEventListener('click', save);+ document.getElementById('reload').addEventListener('click', loadPolicy);+ document.getElementById('clear').addEventListener('click', clearPolicy);++ (async () => {+ await loadMe();+ await loadAgent();+ await loadPolicy();+ })();+ </script>+ </body>+</html>diff --git a/dist-artifact/dashboard/index.html b/dist-artifact/dashboard/index.htmlnew file mode 100644index 000000000..3299709d8--- /dev/null+++ b/dist-artifact/dashboard/index.html@@ -0,0 +1,695 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <title>Dashboard · 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: 16px 24px;+ border-bottom: 1px solid var(--border);+ position: sticky;+ top: 0;+ background: var(--bg);+ z-index: 5;+ }+ .brand {+ font-weight: 600;+ letter-spacing: -0.01em;+ }+ nav a {+ margin-right: 14px;+ color: #aaa;+ font-size: 14px;+ }+ nav a.active {+ color: #fff;+ }+ .layout {+ display: grid;+ grid-template-columns: 220px 1fr;+ min-height: calc(100vh - 57px);+ }+ aside {+ border-right: 1px solid var(--border);+ padding: 20px 0;+ }+ aside a {+ display: block;+ padding: 9px 20px;+ color: #aaa;+ font-size: 14px;+ border-left: 2px solid transparent;+ }+ aside a.active {+ color: #fff;+ background: rgba(106, 92, 255, 0.08);+ border-left-color: var(--accent);+ }+ main {+ padding: 28px;+ max-width: 1100px;+ }+ h1 {+ font-size: 22px;+ margin: 0 0 6px;+ letter-spacing: -0.01em;+ }+ .sub {+ color: #888;+ margin: 0 0 22px;+ font-size: 14px;+ }+ .cards {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));+ gap: 14px;+ }+ .card {+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 14px;+ padding: 16px;+ }+ .card h3 {+ margin: 0 0 4px;+ font-size: 15px;+ }+ .card .meta {+ font-size: 12px;+ color: #888;+ margin: 0 0 10px;+ }+ .preview {+ aspect-ratio: 1/1;+ background: #0f0f17;+ border-radius: 10px;+ margin-bottom: 10px;+ overflow: hidden;+ display: grid;+ place-items: center;+ color: #555;+ font-size: 12px;+ }+ .preview model-viewer {+ width: 100%;+ height: 100%;+ }+ .row {+ display: flex;+ align-items: center;+ gap: 8px;+ }+ .tag {+ font-size: 11px;+ padding: 2px 7px;+ border-radius: 99px;+ background: #20202c;+ color: #ccc;+ }+ .btn {+ padding: 9px 14px;+ border-radius: 9px;+ border: 0;+ font-size: 13px;+ font-weight: 600;+ cursor: pointer;+ background: var(--accent);+ color: #fff;+ }+ .btn.sec {+ background: #222230;+ color: #ddd;+ }+ .empty {+ text-align: center;+ padding: 60px 20px;+ border: 1px dashed var(--border);+ border-radius: 14px;+ color: #888;+ }+ .toolbar {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: 18px;+ }+ .err {+ padding: 12px;+ background: rgba(255, 92, 92, 0.1);+ border: 1px solid rgba(255, 92, 92, 0.3);+ border-radius: 8px;+ color: #ffb3b3;+ margin-bottom: 14px;+ }+ pre {+ background: #0f0f17;+ border: 1px solid var(--border);+ border-radius: 8px;+ padding: 10px 12px;+ overflow: auto;+ font-size: 12px;+ }+ code {+ font-family:+ ui-monospace,+ SF Mono,+ Menlo,+ monospace;+ }+ .key-row {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: 10px 0;+ border-bottom: 1px solid var(--border);+ }+ .key-row:last-child {+ border: 0;+ }+ .muted {+ color: #888;+ font-size: 13px;+ }+ .section {+ margin-top: 34px;+ }+ input,+ textarea,+ select {+ background: #0f0f17;+ border: 1px solid var(--border);+ color: #eee;+ padding: 9px 11px;+ border-radius: 8px;+ font-size: 14px;+ font-family: inherit;+ }+ input:focus,+ textarea:focus,+ select:focus {+ outline: none;+ border-color: var(--accent);+ }++ /* ── Widgets tab ─────────────────────────────────────────────────────── */+ .btn-primary {+ display: inline-block;+ padding: 9px 14px;+ border-radius: 9px;+ border: 0;+ font-size: 13px;+ font-weight: 600;+ cursor: pointer;+ background: var(--accent);+ color: #fff;+ text-decoration: none;+ }+ .btn-primary:hover {+ filter: brightness(1.08);+ }+ .btn-danger {+ background: #cc4040;+ }+ .widgets-header {+ display: flex;+ justify-content: space-between;+ align-items: flex-start;+ gap: 14px;+ margin-bottom: 18px;+ flex-wrap: wrap;+ }+ .widgets-header h1 {+ margin-bottom: 6px;+ }+ .widget-toolbar {+ display: flex;+ gap: 10px;+ align-items: center;+ margin-bottom: 18px;+ flex-wrap: wrap;+ }+ .widget-toolbar input,+ .widget-toolbar select {+ padding: 7px 10px;+ font-size: 13px;+ }+ .widget-toolbar input[type='search'] {+ min-width: 200px;+ }+ .widget-card {+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 14px;+ padding: 14px;+ display: flex;+ flex-direction: column;+ gap: 10px;+ position: relative;+ transition: border-color 0.15s;+ }+ .widget-card:hover {+ border-color: #2c2c40;+ }+ .widget-card .frame {+ aspect-ratio: 1/1;+ background: #0f0f17;+ border-radius: 10px;+ overflow: hidden;+ position: relative;+ }+ .widget-card .frame iframe {+ width: 100%;+ height: 100%;+ border: 0;+ display: block;+ }+ .widget-card .frame .placeholder {+ display: grid;+ place-items: center;+ height: 100%;+ color: #555;+ font-size: 12px;+ padding: 10px;+ text-align: center;+ }+ .widget-card .title {+ display: flex;+ align-items: baseline;+ gap: 8px;+ min-height: 22px;+ }+ .widget-card .title h3 {+ margin: 0;+ font-size: 14px;+ cursor: text;+ flex: 1;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .widget-card .title input {+ flex: 1;+ padding: 3px 6px;+ font-size: 14px;+ font-weight: 600;+ }+ .widget-card .pill {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ font-size: 11px;+ padding: 2px 8px;+ border-radius: 99px;+ background: #20202c;+ color: #ccc;+ white-space: nowrap;+ }+ .widget-card .pill .dot {+ width: 7px;+ height: 7px;+ border-radius: 50%;+ }+ .widget-card .meta {+ font-size: 12px;+ color: #888;+ }+ .widget-card .actions {+ display: flex;+ gap: 6px;+ flex-wrap: wrap;+ margin-top: auto;+ }+ .widget-card .actions button,+ .widget-card .actions a {+ padding: 6px 10px;+ border-radius: 7px;+ border: 1px solid var(--border);+ background: #1a1a24;+ color: #ddd;+ font-size: 12px;+ cursor: pointer;+ text-decoration: none;+ }+ .widget-card .actions button:hover,+ .widget-card .actions a:hover {+ background: #22222e;+ }+ .widget-card .actions .danger:hover {+ background: rgba(204, 64, 64, 0.18);+ border-color: rgba(204, 64, 64, 0.5);+ color: #ffb3b3;+ }+ .toggle {+ position: relative;+ display: inline-flex;+ align-items: center;+ gap: 6px;+ cursor: pointer;+ user-select: none;+ }+ .toggle input {+ position: absolute;+ opacity: 0;+ width: 0;+ height: 0;+ }+ .toggle .track {+ width: 30px;+ height: 17px;+ background: #2a2a36;+ border-radius: 99px;+ position: relative;+ transition: background 0.15s;+ }+ .toggle .track::after {+ content: '';+ position: absolute;+ top: 2px;+ left: 2px;+ width: 13px;+ height: 13px;+ background: #aaa;+ border-radius: 50%;+ transition:+ transform 0.15s,+ background 0.15s;+ }+ .toggle input:checked + .track {+ background: rgba(106, 92, 255, 0.55);+ }+ .toggle input:checked + .track::after {+ transform: translateX(13px);+ background: #fff;+ }+ .toggle input:focus-visible + .track {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+ }+ .toggle .label {+ font-size: 11px;+ color: #888;+ }++ /* Drawer */+ .drawer-overlay {+ position: fixed;+ inset: 0;+ background: rgba(0, 0, 0, 0.55);+ z-index: 50;+ opacity: 0;+ pointer-events: none;+ transition: opacity 0.18s;+ }+ .drawer-overlay.open {+ opacity: 1;+ pointer-events: auto;+ }+ .drawer {+ position: fixed;+ right: 0;+ top: 0;+ bottom: 0;+ width: min(560px, 100vw);+ background: #0e0e16;+ border-left: 1px solid var(--border);+ transform: translateX(100%);+ transition: transform 0.22s cubic-bezier(0.2, 0.8, 0.2, 1);+ z-index: 51;+ overflow-y: auto;+ }+ .drawer.open {+ transform: none;+ }+ .drawer header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 16px 20px;+ border-bottom: 1px solid var(--border);+ position: sticky;+ top: 0;+ background: #0e0e16;+ z-index: 1;+ }+ .drawer header h2 {+ margin: 0;+ font-size: 16px;+ }+ .drawer .body {+ padding: 20px;+ display: flex;+ flex-direction: column;+ gap: 18px;+ }+ .drawer .frame-lg {+ aspect-ratio: 1/1;+ background: #0f0f17;+ border-radius: 10px;+ overflow: hidden;+ }+ .drawer .frame-lg iframe {+ width: 100%;+ height: 100%;+ border: 0;+ }+ .drawer .stat-grid {+ display: grid;+ grid-template-columns: repeat(2, 1fr);+ gap: 10px;+ }+ .drawer .stat {+ background: #13131c;+ border: 1px solid var(--border);+ border-radius: 10px;+ padding: 12px 14px;+ }+ .drawer .stat .n {+ font-size: 22px;+ font-weight: 600;+ }+ .drawer .stat .l {+ font-size: 11px;+ color: #888;+ text-transform: uppercase;+ letter-spacing: 0.5px;+ }+ .spark {+ width: 100%;+ height: 60px;+ }+ .spark path.area {+ fill: rgba(106, 92, 255, 0.18);+ }+ .spark path.line {+ fill: none;+ stroke: var(--accent);+ stroke-width: 2;+ }+ .spark .axis {+ stroke: #22222e;+ stroke-width: 1;+ }+ details summary {+ cursor: pointer;+ padding: 6px 0;+ color: #aaa;+ font-size: 13px;+ }+ details[open] summary {+ color: #eee;+ }+ .danger-zone {+ border: 1px solid rgba(204, 64, 64, 0.4);+ border-radius: 10px;+ padding: 14px;+ background: rgba(204, 64, 64, 0.05);+ }+ .danger-zone h3 {+ margin: 0 0 6px;+ color: #ffb3b3;+ font-size: 13px;+ }++ /* Modal */+ .modal-overlay {+ position: fixed;+ inset: 0;+ background: rgba(0, 0, 0, 0.6);+ z-index: 60;+ display: grid;+ place-items: center;+ opacity: 0;+ pointer-events: none;+ transition: opacity 0.15s;+ }+ .modal-overlay.open {+ opacity: 1;+ pointer-events: auto;+ }+ .modal {+ background: #0e0e16;+ border: 1px solid var(--border);+ border-radius: 14px;+ padding: 22px;+ width: min(560px, calc(100vw - 32px));+ max-height: calc(100vh - 32px);+ overflow-y: auto;+ }+ .modal h2 {+ margin: 0 0 4px;+ font-size: 17px;+ }+ .modal .sub {+ margin: 0 0 18px;+ }+ .size-presets {+ display: flex;+ gap: 6px;+ flex-wrap: wrap;+ margin-bottom: 14px;+ }+ .size-presets button {+ padding: 6px 12px;+ border-radius: 99px;+ border: 1px solid var(--border);+ background: #13131c;+ color: #ccc;+ font-size: 12px;+ cursor: pointer;+ }+ .size-presets button.active {+ border-color: var(--accent);+ color: #fff;+ background: rgba(106, 92, 255, 0.15);+ }+ .size-inputs {+ display: flex;+ gap: 8px;+ align-items: center;+ margin-bottom: 14px;+ }+ .size-inputs input {+ width: 90px;+ }++ .toast {+ position: fixed;+ bottom: 24px;+ left: 50%;+ transform: translateX(-50%);+ background: #1a1a24;+ border: 1px solid var(--border);+ padding: 10px 18px;+ border-radius: 99px;+ font-size: 13px;+ color: #ddd;+ z-index: 70;+ box-shadow: 0 4px 18px rgba(0, 0, 0, 0.4);+ animation: toast-in 0.2s;+ }+ @keyframes toast-in {+ from {+ opacity: 0;+ transform: translate(-50%, 8px);+ }+ to {+ opacity: 1;+ transform: translateX(-50%);+ }+ }++ /* visually-hidden utility for screen-reader-only labels */+ .sr-only {+ position: absolute;+ width: 1px;+ height: 1px;+ padding: 0;+ margin: -1px;+ overflow: hidden;+ clip: rect(0, 0, 0, 0);+ border: 0;+ }+ </style>+ <script+ type="module"+ src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"+ ></script>+ </head>+ <body>+ <header>+ <div class="brand"><a href="/">3D Agent</a></div>+ <div class="row">+ <span id="user-email" class="muted"></span>+ <button class="btn sec" onclick="signOut()">Sign out</button>+ </div>+ </header>+ <div class="layout">+ <aside>+ <a href="#avatars" class="active" data-tab="avatars">Avatars</a>+ <a href="#create" data-tab="create">Create from selfie</a>+ <a href="#upload" data-tab="upload">Upload</a>+ <a href="#widgets" data-tab="widgets">Widgets</a>+ <a href="#embed" data-tab="embed">Embed</a>+ <a href="#keys" data-tab="keys">API keys</a>+ <a href="#mcp" data-tab="mcp">MCP</a>+ <a href="#billing" data-tab="billing">Plan & usage</a>+ <a href="/explore" title="Browse on-chain agents across every supported chain"+ >Explore on-chain ↗</a+ >+ </aside>+ <main id="main"></main>+ </div>+ <script type="module">+ import { state, api, navigate, signOut } from '/dashboard/dashboard.js';+ window.signOut = signOut;++ (async () => {+ try {+ const me = await api.me();+ state.user = me.user;+ document.getElementById('user-email').textContent = me.user.email;+ } catch {+ location.href =+ '/login?next=' + encodeURIComponent(location.pathname + location.hash);+ return;+ }+ navigate(location.hash.slice(1) || 'avatars');+ window.addEventListener('hashchange', () =>+ navigate(location.hash.slice(1) || 'avatars'),+ );+ })();+ </script>+ </body>+</html>diff --git a/dist-artifact/dashboard/sessions.html b/dist-artifact/dashboard/sessions.htmlnew file mode 100644index 000000000..ff9594a98--- /dev/null+++ b/dist-artifact/dashboard/sessions.html@@ -0,0 +1,442 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <title>Sessions · 3D Agent</title>+ <link rel="icon" href="/favicon.ico" />+ <style>+ :root {+ color-scheme: dark;+ --accent: #6a5cff;+ --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: 16px 24px;+ border-bottom: 1px solid var(--border);+ position: sticky;+ top: 0;+ background: var(--bg);+ z-index: 5;+ }+ .brand {+ font-weight: 600;+ letter-spacing: -0.01em;+ }+ .row {+ display: flex;+ align-items: center;+ gap: 8px;+ }+ main {+ padding: 28px;+ max-width: 800px;+ }+ h1 {+ font-size: 22px;+ margin: 0 0 6px;+ letter-spacing: -0.01em;+ }+ .sub {+ color: #888;+ margin: 0 0 22px;+ font-size: 14px;+ }+ .btn {+ padding: 9px 14px;+ border-radius: 9px;+ border: 0;+ font-size: 13px;+ font-weight: 600;+ cursor: pointer;+ background: var(--accent);+ color: #fff;+ }+ .btn:disabled {+ opacity: 0.5;+ cursor: not-allowed;+ }+ .btn.sec {+ background: #222230;+ color: #ddd;+ }+ .btn.danger {+ background: #cc4040;+ }+ .btn-group {+ display: flex;+ gap: 8px;+ margin-bottom: 20px;+ }+ table {+ width: 100%;+ border-collapse: collapse;+ border: 1px solid var(--border);+ border-radius: 10px;+ overflow: hidden;+ background: var(--panel);+ }+ thead {+ background: #0f0f17;+ border-bottom: 1px solid var(--border);+ }+ th {+ padding: 12px 16px;+ text-align: left;+ font-size: 12px;+ font-weight: 600;+ text-transform: uppercase;+ letter-spacing: 0.5px;+ color: #888;+ }+ td {+ padding: 12px 16px;+ border-bottom: 1px solid var(--border);+ font-size: 14px;+ }+ tr:last-child td {+ border-bottom: 0;+ }+ .pill {+ display: inline-block;+ font-size: 11px;+ padding: 3px 8px;+ border-radius: 99px;+ background: rgba(106, 92, 255, 0.2);+ color: #a8a0ff;+ white-space: nowrap;+ }+ .agent-cell {+ max-width: 200px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ color: #bbb;+ font-size: 13px;+ }+ .time-cell {+ color: #999;+ font-size: 13px;+ }+ .actions {+ text-align: right;+ }+ .empty {+ text-align: center;+ padding: 40px 20px;+ color: #888;+ }+ .toast {+ position: fixed;+ bottom: 24px;+ left: 50%;+ transform: translateX(-50%);+ background: #1a1a24;+ border: 1px solid var(--border);+ padding: 10px 18px;+ border-radius: 99px;+ font-size: 13px;+ color: #ddd;+ z-index: 70;+ box-shadow: 0 4px 18px rgba(0, 0, 0, 0.4);+ animation: toast-in 0.2s;+ }+ .toast.error {+ background: rgba(204, 64, 64, 0.15);+ border-color: rgba(204, 64, 64, 0.3);+ color: #ffb3b3;+ }+ @keyframes toast-in {+ from {+ opacity: 0;+ transform: translate(-50%, 8px);+ }+ to {+ opacity: 1;+ transform: translateX(-50%);+ }+ }+ .btn-sec {+ background: #222230;+ color: #ddd;+ }+ </style>+ </head>+ <body>+ <header>+ <div class="brand"><a href="/">3D Agent</a></div>+ <button class="btn sec" onclick="signOut()">Sign out</button>+ </header>+ <main>+ <h1>Sessions</h1>+ <p class="sub">Manage your active login sessions across devices.</p>++ <div class="btn-group">+ <button class="btn danger" id="signOutBtn" style="display: none">+ Sign out of all other devices+ </button>+ </div>++ <table id="sessionsTable" style="display: none">+ <thead>+ <tr>+ <th>Device / User Agent</th>+ <th>IP Address</th>+ <th>Created</th>+ <th>Last Seen</th>+ <th class="actions">Actions</th>+ </tr>+ </thead>+ <tbody id="sessionsList"></tbody>+ </table>++ <div class="empty" id="loadingMessage">Loading sessions...</div>+ </main>++ <script>+ function signOut() {+ location.href = '/login';+ }++ function showToast(message, isError = false) {+ const toast = document.createElement('div');+ toast.className = 'toast' + (isError ? ' error' : '');+ toast.textContent = message;+ document.body.appendChild(toast);+ setTimeout(() => {+ toast.remove();+ }, 3000);+ }++ function formatRelativeTime(date) {+ const now = new Date();+ const diff = now - new Date(date);+ const seconds = Math.floor(diff / 1000);+ const minutes = Math.floor(seconds / 60);+ const hours = Math.floor(minutes / 60);+ const days = Math.floor(hours / 24);++ if (seconds < 60) return 'Just now';+ if (minutes < 60) return `${minutes}m ago`;+ if (hours < 24) return `${hours}h ago`;+ if (days < 7) return `${days}d ago`;++ return new Date(date).toLocaleDateString('en-US', {+ month: 'short',+ day: 'numeric',+ });+ }++ function formatAbsoluteDate(date) {+ return new Date(date).toLocaleDateString('en-US', {+ month: 'short',+ day: 'numeric',+ year: 'numeric',+ hour: '2-digit',+ minute: '2-digit',+ });+ }++ function truncateUA(ua) {+ if (!ua) return 'Unknown';+ if (ua.length > 50) return ua.substring(0, 47) + '…';+ return ua;+ }++ async function loadSessions() {+ try {+ const res = await fetch('/api/auth/me', { credentials: 'include' });+ if (res.status === 401) {+ location.href = '/login?next=' + encodeURIComponent(location.pathname);+ return;+ }+ if (!res.ok) throw new Error('Failed to verify auth');++ const sessionsRes = await fetch('/api/auth/sessions', {+ credentials: 'include',+ });+ if (!sessionsRes.ok) throw new Error('Failed to load sessions');++ const { sessions } = await sessionsRes.json();++ const tbody = document.getElementById('sessionsList');+ tbody.innerHTML = '';++ if (sessions.length === 0) {+ document.getElementById('loadingMessage').textContent =+ 'No active sessions';+ return;+ }++ document.getElementById('sessionsTable').style.display = 'table';+ document.getElementById('loadingMessage').style.display = 'none';++ const hasMultiple = sessions.length > 1;+ document.getElementById('signOutBtn').style.display = hasMultiple+ ? 'block'+ : 'none';++ sessions.forEach((session) => {+ const row = document.createElement('tr');+ row.id = `session-${session.id}`;++ const isCurrentSession = session.current;+ const uaCell = document.createElement('td');+ uaCell.className = 'agent-cell';+ uaCell.textContent = truncateUA(session.user_agent);++ const ipCell = document.createElement('td');+ ipCell.className = 'agent-cell';+ ipCell.textContent = session.ip || 'Unknown';++ const createdCell = document.createElement('td');+ createdCell.className = 'time-cell';+ createdCell.textContent = formatAbsoluteDate(session.created_at);++ const lastSeenCell = document.createElement('td');+ lastSeenCell.className = 'time-cell';+ if (isCurrentSession) {+ lastSeenCell.innerHTML = '<span class="pill">This device</span>';+ } else {+ lastSeenCell.textContent = formatRelativeTime(session.last_seen_at);+ }++ const actionsCell = document.createElement('td');+ actionsCell.className = 'actions';+ if (!isCurrentSession) {+ const revokeBtn = document.createElement('button');+ revokeBtn.className = 'btn sec';+ revokeBtn.style.padding = '6px 12px';+ revokeBtn.style.fontSize = '12px';+ revokeBtn.textContent = 'Revoke';+ revokeBtn.onclick = () => revokeSession(session.id, row);+ actionsCell.appendChild(revokeBtn);+ } else {+ const placeholder = document.createElement('span');+ placeholder.style.color = '#666';+ placeholder.style.fontSize = '12px';+ placeholder.textContent = '—';+ actionsCell.appendChild(placeholder);+ }++ row.appendChild(uaCell);+ row.appendChild(ipCell);+ row.appendChild(createdCell);+ row.appendChild(lastSeenCell);+ row.appendChild(actionsCell);+ tbody.appendChild(row);+ });+ } catch (err) {+ console.error(err);+ document.getElementById('loadingMessage').textContent =+ 'Error loading sessions';+ }+ }++ async function revokeSession(sessionId, row) {+ const originalRow = row.cloneNode(true);+ row.style.opacity = '0.5';+ row.querySelector('button').disabled = true;++ try {+ const res = await fetch(`/api/auth/sessions/${sessionId}`, {+ method: 'DELETE',+ credentials: 'include',+ });++ if (!res.ok) {+ throw new Error('Failed to revoke session');+ }++ row.style.animation = 'fade-out 0.3s';+ setTimeout(() => {+ row.remove();+ showToast('Session revoked');+ const remaining = document.querySelectorAll('#sessionsList tr').length;+ if (remaining === 1) {+ document.getElementById('signOutBtn').style.display = 'none';+ }+ }, 300);+ } catch (err) {+ console.error(err);+ row.replaceWith(originalRow);+ originalRow.querySelector('button').onclick = () =>+ revokeSession(sessionId, originalRow);+ showToast('Failed to revoke session', true);+ }+ }++ async function signOutEverywhere() {+ if (+ !confirm(+ 'Sign out of all other devices? You will stay signed in on this device.',+ )+ )+ return;++ const signOutBtn = document.getElementById('signOutBtn');+ const originalText = signOutBtn.textContent;+ signOutBtn.disabled = true;+ signOutBtn.textContent = 'Signing out...';++ try {+ const res = await fetch('/api/auth/sessions', {+ method: 'DELETE',+ credentials: 'include',+ });++ if (!res.ok) throw new Error('Failed to sign out');++ const { revoked } = await res.json();+ showToast(`Signed out of ${revoked} device${revoked === 1 ? '' : 's'}`);+ loadSessions();+ } catch (err) {+ console.error(err);+ signOutBtn.disabled = false;+ signOutBtn.textContent = originalText;+ showToast('Failed to sign out of other devices', true);+ }+ }++ document.getElementById('signOutBtn').onclick = signOutEverywhere;++ loadSessions();++ // Add CSS animation+ const style = document.createElement('style');+ style.textContent = `+ @keyframes fade-out {+ to {+ opacity: 0;+ transform: translateX(-20px);+ }+ }+ `;+ document.head.appendChild(style);+ </script>+ </body>+</html>diff --git a/dist-artifact/dashboard/storage.html b/dist-artifact/dashboard/storage.htmlnew file mode 100644index 000000000..bc9170d24--- /dev/null+++ b/dist-artifact/dashboard/storage.html@@ -0,0 +1,447 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <title>Storage · 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: 16px 24px;+ border-bottom: 1px solid var(--border);+ position: sticky;+ top: 0;+ background: var(--bg);+ z-index: 5;+ }+ .brand {+ font-weight: 600;+ letter-spacing: -0.01em;+ }+ main {+ padding: 28px;+ max-width: 720px;+ margin: 0 auto;+ }+ h1 {+ font-size: 22px;+ margin: 0 0 6px;+ letter-spacing: -0.01em;+ }+ .sub {+ color: #888;+ margin: 0 0 22px;+ font-size: 14px;+ }+ .card {+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 14px;+ padding: 20px;+ margin-bottom: 20px;+ }+ fieldset {+ border: 0;+ padding: 0;+ margin: 0;+ }+ legend {+ font-size: 13px;+ font-weight: 600;+ color: #ccc;+ margin-bottom: 12px;+ letter-spacing: 0.02em;+ text-transform: uppercase;+ }+ label {+ display: block;+ margin: 14px 0 6px;+ font-size: 13px;+ color: #bbb;+ }+ input,+ select {+ background: #0f0f17;+ border: 1px solid var(--border);+ color: #eee;+ padding: 9px 11px;+ border-radius: 8px;+ font-size: 14px;+ font-family: inherit;+ width: 100%;+ }+ input:focus,+ select:focus {+ outline: none;+ border-color: var(--accent);+ }+ .kv {+ display: flex;+ align-items: center;+ gap: 10px;+ margin: 10px 0;+ }+ .kv-label {+ font-size: 13px;+ color: #888;+ min-width: 120px;+ }+ .kv-value {+ font-size: 13px;+ color: #ddd;+ word-break: break-all;+ }+ .badge {+ display: inline-block;+ font-size: 11px;+ font-weight: 700;+ padding: 2px 8px;+ border-radius: 99px;+ letter-spacing: 0.04em;+ }+ .badge.green {+ background: rgba(92, 255, 140, 0.1);+ color: #7ef0a3;+ border: 1px solid rgba(92, 255, 140, 0.25);+ }+ .badge.grey {+ background: rgba(180, 180, 200, 0.08);+ color: #aaa;+ border: 1px solid rgba(180, 180, 200, 0.15);+ }+ .badge.yellow {+ background: rgba(255, 220, 92, 0.1);+ color: #f0dc7e;+ border: 1px solid rgba(255, 220, 92, 0.25);+ }+ .btn {+ padding: 9px 14px;+ border-radius: 9px;+ border: 0;+ font-size: 13px;+ font-weight: 600;+ cursor: pointer;+ background: var(--accent);+ color: #fff;+ }+ .btn:disabled {+ opacity: 0.5;+ cursor: not-allowed;+ }+ .btn.sec {+ background: #222230;+ color: #ddd;+ }+ .muted {+ color: #888;+ font-size: 13px;+ }+ .err {+ padding: 12px;+ background: rgba(255, 92, 92, 0.1);+ border: 1px solid rgba(255, 92, 92, 0.3);+ border-radius: 8px;+ color: #ffb3b3;+ margin-bottom: 14px;+ }+ .ok {+ padding: 12px;+ background: rgba(92, 255, 140, 0.07);+ border: 1px solid rgba(92, 255, 140, 0.2);+ border-radius: 8px;+ color: #b6f2c6;+ margin-bottom: 14px;+ }+ code {+ font-family:+ ui-monospace,+ SF Mono,+ Menlo,+ monospace;+ background: #0f0f17;+ border: 1px solid var(--border);+ border-radius: 4px;+ padding: 1px 6px;+ font-size: 12px;+ }+ .actions {+ display: flex;+ gap: 10px;+ margin-top: 16px;+ }+ hr {+ border: 0;+ border-top: 1px solid var(--border);+ margin: 22px 0;+ }+ .hidden {+ display: none !important;+ }+ </style>+ </head>+ <body>+ <header>+ <div class="brand"><a href="/dashboard">← Dashboard</a></div>+ <div class="muted"><span id="avatar-name">Avatar</span></div>+ </header>+ <main>+ <h1>Storage</h1>+ <p class="sub">+ Manage where <code id="avatar-id-label"></code>'s bytes live and track content+ attestation.+ </p>++ <div id="status"></div>++ <!-- R2 -->+ <div class="card">+ <fieldset>+ <legend>R2 (primary storage)</legend>+ <div class="kv">+ <span class="kv-label">Status</span>+ <span class="badge green" id="r2-present-badge">Present</span>+ </div>+ <div class="kv">+ <span class="kv-label">Storage key</span>+ <code id="r2-key" class="kv-value">—</code>+ </div>+ </fieldset>+ </div>++ <!-- IPFS -->+ <div class="card">+ <fieldset>+ <legend>IPFS</legend>+ <div class="kv">+ <span class="kv-label">Pinned</span>+ <span class="badge grey" id="ipfs-pinned-badge">Not pinned</span>+ </div>+ <div class="kv" id="ipfs-cid-row">+ <span class="kv-label">CID</span>+ <code id="ipfs-cid" class="kv-value">—</code>+ </div>+ <div class="kv" id="ipfs-pinned-at-row">+ <span class="kv-label">Pinned at</span>+ <span id="ipfs-pinned-at" class="kv-value muted">—</span>+ </div>+ <div class="actions">+ <button class="btn" id="pin-btn">Pin to IPFS (stub)</button>+ </div>+ <p class="muted" style="margin-top: 10px">+ Real Pinata / Web3.Storage integration is a follow-up. This stub records a+ placeholder CID derived from the content hash.+ </p>+ </fieldset>+ </div>++ <!-- Attestation -->+ <div class="card">+ <fieldset>+ <legend>On-chain attestation</legend>+ <div class="kv">+ <span class="kv-label">Content hash</span>+ <code id="attest-hash" class="kv-value">—</code>+ </div>+ <div class="kv">+ <span class="kv-label">Chain</span>+ <span id="attest-chain" class="kv-value muted">—</span>+ </div>+ <div class="kv">+ <span class="kv-label">Tx hash</span>+ <code id="attest-tx" class="kv-value">—</code>+ </div>+ <div class="kv">+ <span class="kv-label">Attested at</span>+ <span id="attest-at" class="kv-value muted">—</span>+ </div>+ <p class="muted" style="margin-top: 10px">+ On-chain attestation is read-only. Content hashing runs server-side+ post-upload. Transaction broadcasting is a future feature.+ </p>+ </fieldset>+ </div>++ <div class="actions">+ <button class="btn sec" id="reload">Reload</button>+ </div>+ </main>+ <script type="module">+ const params = new URL(location.href).searchParams;+ const avatarId = params.get('id');+ const statusEl = document.getElementById('status');+ const nameEl = document.getElementById('avatar-name');+ const labelEl = document.getElementById('avatar-id-label');++ if (!avatarId) {+ statusEl.innerHTML =+ '<div class="err">Missing <code>?id=AVATAR_ID</code> in URL.</div>';+ throw new Error('no avatar id');+ }+ labelEl.textContent = avatarId;++ async function api(method, path, body) {+ const res = await fetch(path, {+ method,+ credentials: 'include',+ headers: body ? { 'content-type': 'application/json' } : {},+ body: body ? JSON.stringify(body) : undefined,+ });+ const ct = res.headers.get('content-type') || '';+ const data = ct.includes('application/json') ? await res.json() : null;+ if (!res.ok)+ throw Object.assign(+ new Error((data && data.error_description) || res.statusText),+ { status: res.status },+ );+ return data;+ }++ function setStatus(html) {+ statusEl.innerHTML = html;+ }++ function escapeHtml(s) {+ return String(s ?? '').replace(+ /[&<>"']/g,+ (c) =>+ ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[+ c+ ],+ );+ }++ function populateMode(mode) {+ if (!mode) return;++ // R2+ document.getElementById('r2-key').textContent = mode.r2?.key || '—';+ const r2Badge = document.getElementById('r2-present-badge');+ if (mode.r2?.present) {+ r2Badge.textContent = 'Present';+ r2Badge.className = 'badge green';+ } else {+ r2Badge.textContent = 'Missing';+ r2Badge.className = 'badge grey';+ }++ // IPFS+ const ipfsBadge = document.getElementById('ipfs-pinned-badge');+ if (mode.ipfs?.pinned) {+ ipfsBadge.textContent = 'Pinned';+ ipfsBadge.className = 'badge green';+ document.getElementById('pin-btn').disabled = true;+ document.getElementById('pin-btn').textContent = 'Already pinned';+ } else {+ ipfsBadge.textContent = 'Not pinned';+ ipfsBadge.className = 'badge grey';+ document.getElementById('pin-btn').disabled = false;+ document.getElementById('pin-btn').textContent = 'Pin to IPFS (stub)';+ }+ document.getElementById('ipfs-cid').textContent = mode.ipfs?.cid || '—';+ document.getElementById('ipfs-pinned-at').textContent = mode.ipfs?.pinned_at+ ? new Date(mode.ipfs.pinned_at).toLocaleString()+ : '—';++ // Attestation+ const hash = mode.attestation?.hash;+ document.getElementById('attest-hash').textContent = hash || 'Not yet computed';+ document.getElementById('attest-chain').textContent =+ mode.attestation?.chain_id != null ? String(mode.attestation.chain_id) : '—';+ document.getElementById('attest-tx').textContent = mode.attestation?.tx_hash || '—';+ document.getElementById('attest-at').textContent = mode.attestation?.attested_at+ ? new Date(mode.attestation.attested_at).toLocaleString()+ : '—';+ }++ async function loadMe() {+ try {+ await api('GET', '/api/auth/me');+ } catch {+ location.href =+ '/login?next=' + encodeURIComponent(location.pathname + location.search);+ throw new Error('redirecting');+ }+ }++ async function loadAvatar() {+ try {+ const data = await api('GET', `/api/avatars/${avatarId}`);+ const av = data.avatar || data;+ nameEl.textContent = av.name || avatarId;+ } catch (e) {+ setStatus(+ `<div class="err">Could not load avatar: ${escapeHtml(e.message)}</div>`,+ );+ }+ }++ async function loadMode() {+ try {+ const { storage_mode } = await api(+ 'GET',+ `/api/avatars/${avatarId}/storage-mode`,+ );+ populateMode(storage_mode);+ } catch (e) {+ setStatus(+ `<div class="err">Could not load storage mode: ${escapeHtml(e.message)}</div>`,+ );+ }+ }++ async function pinIpfs() {+ setStatus('');+ document.getElementById('pin-btn').disabled = true;+ try {+ const { storage_mode } = await api('POST', `/api/avatars/${avatarId}/pin-ipfs`);+ populateMode(storage_mode);+ setStatus(+ '<div class="ok">Pinned (stub). Real IPFS pinning is a follow-up.</div>',+ );+ } catch (e) {+ document.getElementById('pin-btn').disabled = false;+ setStatus(`<div class="err">${escapeHtml(e.message)}</div>`);+ }+ }++ document.getElementById('pin-btn').addEventListener('click', pinIpfs);+ document.getElementById('reload').addEventListener('click', loadMode);++ (async () => {+ await loadMe();+ await loadAvatar();+ await loadMode();+ })();+ </script>+ </body>+</html>diff --git a/dist-artifact/dashboard/usage.html b/dist-artifact/dashboard/usage.htmlnew file mode 100644index 000000000..3d46aae13--- /dev/null+++ b/dist-artifact/dashboard/usage.html@@ -0,0 +1,212 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <title>LLM Usage — 3D Agent</title>+ <link rel="stylesheet" href="/assets/dashboard.css" />+ <style>+ body {+ font-family:+ system-ui,+ -apple-system,+ sans-serif;+ max-width: 640px;+ margin: 2rem auto;+ padding: 0 1rem;+ color: #111;+ }+ h1 {+ font-size: 1.25rem;+ margin-bottom: 0.25rem;+ }+ .sub {+ color: #555;+ font-size: 0.875rem;+ margin-bottom: 1.5rem;+ }+ .quota-bar {+ background: #e5e7eb;+ border-radius: 999px;+ height: 12px;+ overflow: hidden;+ margin: 0.5rem 0 0.25rem;+ }+ .quota-fill {+ background: #3b82f6;+ height: 100%;+ border-radius: 999px;+ transition: width 0.4s;+ }+ .quota-fill.warn {+ background: #f59e0b;+ }+ .quota-fill.danger {+ background: #ef4444;+ }+ .quota-label {+ font-size: 0.8rem;+ color: #555;+ }+ table {+ width: 100%;+ border-collapse: collapse;+ margin-top: 1.5rem;+ font-size: 0.875rem;+ }+ th {+ text-align: left;+ padding: 6px 8px;+ border-bottom: 2px solid #e5e7eb;+ color: #555;+ font-weight: 600;+ }+ td {+ padding: 5px 8px;+ border-bottom: 1px solid #f3f4f6;+ }+ .sparkline {+ display: flex;+ align-items: flex-end;+ gap: 2px;+ height: 40px;+ margin-top: 1.5rem;+ }+ .sparkline-bar {+ flex: 1;+ background: #3b82f6;+ border-radius: 2px 2px 0 0;+ min-height: 2px;+ }+ .sparkline-bar:hover {+ background: #2563eb;+ }+ .error {+ color: #dc2626;+ padding: 1rem 0;+ }+ .section {+ margin-top: 2rem;+ }+ h2 {+ font-size: 1rem;+ margin-bottom: 0.5rem;+ color: #374151;+ }+ </style>+ </head>+ <body>+ <h1>LLM Usage</h1>+ <div class="sub" id="agent-label">Loading…</div>++ <div class="section" id="quota-section" style="display: none">+ <h2>Current month</h2>+ <div class="quota-bar">+ <div class="quota-fill" id="quota-fill" style="width: 0%"></div>+ </div>+ <div class="quota-label" id="quota-label"></div>+ </div>++ <div class="section" id="spark-section" style="display: none">+ <h2>Last 30 days</h2>+ <div class="sparkline" id="sparkline"></div>+ </div>++ <div class="section" id="table-section" style="display: none">+ <table>+ <thead>+ <tr>+ <th>Day</th>+ <th>Calls</th>+ </tr>+ </thead>+ <tbody id="daily-tbody"></tbody>+ </table>+ </div>++ <div class="error" id="error-msg" style="display: none"></div>++ <script>+ (async () => {+ const params = new URLSearchParams(location.search);+ const id = params.get('id');+ if (!id) {+ show('error-msg', 'Missing ?id= parameter.');+ return;+ }++ document.getElementById('agent-label').textContent = `Agent ${id}`;++ let data;+ try {+ const r = await fetch(`/api/agents/${id}/usage`, { credentials: 'include' });+ if (r.status === 401) {+ show('error-msg', 'Not signed in. Visit /login first.');+ return;+ }+ if (r.status === 404) {+ show('error-msg', 'Agent not found or not yours.');+ return;+ }+ if (!r.ok) {+ show('error-msg', `Error ${r.status}`);+ return;+ }+ data = await r.json();+ } catch (e) {+ show('error-msg', `Fetch failed: ${e.message}`);+ return;+ }++ const { currentMonthCalls, monthlyQuota, dailyBreakdown, agentId } = data;+ document.getElementById('agent-label').textContent = `Agent ${agentId}`;++ // Quota bar+ if (typeof monthlyQuota === 'number') {+ const pct = Math.min(100, (currentMonthCalls / monthlyQuota) * 100);+ const fill = document.getElementById('quota-fill');+ fill.style.width = pct + '%';+ fill.className =+ 'quota-fill' + (pct >= 90 ? ' danger' : pct >= 70 ? ' warn' : '');+ document.getElementById('quota-label').textContent =+ `${currentMonthCalls.toLocaleString()} / ${monthlyQuota.toLocaleString()} calls this month (${Math.round(pct)}%)`;+ document.getElementById('quota-section').style.display = '';+ } else {+ document.getElementById('quota-section').style.display = '';+ document.getElementById('quota-label').textContent =+ `${currentMonthCalls.toLocaleString()} calls this month (no quota set)`;+ }++ // Sparkline + table+ if (dailyBreakdown && dailyBreakdown.length) {+ const max = Math.max(1, ...dailyBreakdown.map((r) => r.calls));+ const spark = document.getElementById('sparkline');+ const tbody = document.getElementById('daily-tbody');+ for (const row of dailyBreakdown) {+ const bar = document.createElement('div');+ bar.className = 'sparkline-bar';+ bar.style.height = Math.max(2, Math.round((row.calls / max) * 40)) + 'px';+ bar.title = `${row.day}: ${row.calls}`;+ spark.appendChild(bar);++ const tr = document.createElement('tr');+ tr.innerHTML = `<td>${row.day}</td><td>${row.calls.toLocaleString()}</td>`;+ tbody.appendChild(tr);+ }+ document.getElementById('spark-section').style.display = '';+ document.getElementById('table-section').style.display = '';+ } else {+ document.getElementById('spark-section').style.display = '';+ document.getElementById('spark-section').innerHTML +=+ '<p style="color:#555;font-size:0.875rem">No calls in the last 30 days.</p>';+ }+ })();++ function show(id, msg) {+ const el = document.getElementById(id);+ el.textContent = msg;+ el.style.display = '';+ }+ </script>+ </body>+</html>diff --git a/dist-artifact/dashboard/wallets.html b/dist-artifact/dashboard/wallets.htmlnew file mode 100644index 000000000..98b126ec3--- /dev/null+++ b/dist-artifact/dashboard/wallets.html@@ -0,0 +1,418 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <title>Linked Wallets · Dashboard · 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: 16px 24px;+ border-bottom: 1px solid var(--border);+ position: sticky;+ top: 0;+ background: var(--bg);+ z-index: 5;+ }+ .brand {+ font-weight: 600;+ letter-spacing: -0.01em;+ }+ .row {+ display: flex;+ align-items: center;+ gap: 8px;+ }+ main {+ padding: 28px;+ max-width: 800px;+ margin: 0 auto;+ }+ h1 {+ font-size: 22px;+ margin: 0 0 6px;+ letter-spacing: -0.01em;+ }+ .sub {+ color: #888;+ margin: 0 0 22px;+ font-size: 14px;+ }+ .btn {+ padding: 9px 14px;+ border-radius: 9px;+ border: 0;+ font-size: 13px;+ font-weight: 600;+ cursor: pointer;+ background: var(--accent);+ color: #fff;+ }+ .btn:hover {+ filter: brightness(1.08);+ }+ .btn.sec {+ background: #222230;+ color: #ddd;+ }+ .btn.danger {+ background: #cc4040;+ }+ .btn:disabled {+ opacity: 0.5;+ cursor: not-allowed;+ }+ .wallet-table {+ width: 100%;+ border-collapse: collapse;+ margin-bottom: 24px;+ }+ .wallet-table th {+ text-align: left;+ padding: 12px;+ border-bottom: 1px solid var(--border);+ font-size: 12px;+ font-weight: 600;+ color: #aaa;+ text-transform: uppercase;+ letter-spacing: 0.5px;+ }+ .wallet-table td {+ padding: 12px;+ border-bottom: 1px solid var(--border);+ font-size: 14px;+ }+ .wallet-table tr:last-child td {+ border-bottom: none;+ }+ .address-cell {+ display: flex;+ align-items: center;+ gap: 8px;+ font-family:+ ui-monospace,+ SF Mono,+ Menlo,+ monospace;+ font-size: 13px;+ }+ .copy-btn {+ background: none;+ border: none;+ color: #666;+ cursor: pointer;+ padding: 2px 4px;+ font-size: 12px;+ }+ .copy-btn:hover {+ color: #aaa;+ }+ .pill {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ font-size: 11px;+ padding: 3px 8px;+ border-radius: 99px;+ background: #20202c;+ color: #ccc;+ white-space: nowrap;+ }+ .meta {+ color: #888;+ font-size: 13px;+ }+ .err {+ padding: 12px;+ background: rgba(255, 92, 92, 0.1);+ border: 1px solid rgba(255, 92, 92, 0.3);+ border-radius: 8px;+ color: #ffb3b3;+ margin-bottom: 14px;+ display: none;+ }+ .empty {+ text-align: center;+ padding: 40px 20px;+ border: 1px dashed var(--border);+ border-radius: 14px;+ color: #888;+ }+ .loading {+ opacity: 0.6;+ }+ .muted {+ color: #888;+ font-size: 13px;+ }+ </style>+ </head>+ <body>+ <header>+ <div class="brand"><a href="/">3D Agent</a></div>+ <div class="row">+ <span class="muted" id="user-email"></span>+ <button class="btn sec" onclick="signOut()">Sign out</button>+ </div>+ </header>+ <main>+ <h1>Linked Wallets</h1>+ <p class="sub">Manage Ethereum wallets connected to your account.</p>++ <div id="error" class="err"></div>++ <div id="wallets-container" class="loading">+ <p style="color: #666">Loading wallets…</p>+ </div>++ <button id="link-btn" class="btn" style="margin-top: 20px">Link Another Wallet</button>+ </main>++ <script type="module">+ let apiUrl = '/api';++ async function signOut() {+ await fetch(`${apiUrl}/auth/logout`, { method: 'POST', credentials: 'include' });+ location.href = '/login';+ }++ async function fetchUser() {+ const res = await fetch(`${apiUrl}/auth/me`, { credentials: 'include' });+ if (!res.ok) {+ location.href = '/login?next=' + encodeURIComponent(location.pathname);+ return null;+ }+ return res.json();+ }++ async function loadWallets() {+ try {+ const res = await fetch(`${apiUrl}/auth/wallets`, { credentials: 'include' });+ if (!res.ok) throw new Error('Failed to load wallets');+ const data = await res.json();+ renderWallets(data.wallets);+ } catch (err) {+ showError(err.message);+ }+ }++ function renderWallets(wallets) {+ const container = document.getElementById('wallets-container');+ if (wallets.length === 0) {+ container.innerHTML = `+ <div class="empty">+ <p>No wallets linked yet.</p>+ <p class="muted">Click "Link Another Wallet" to add your first wallet.</p>+ </div>+ `;+ return;+ }++ const rows = wallets+ .map(+ (w) => `+ <tr>+ <td>+ <div class="address-cell">+ <span>${w.address.slice(0, 6)}…${w.address.slice(-4)}</span>+ <button+ class="copy-btn"+ onclick="copyToClipboard('${w.address}')"+ title="Copy full address"+ >+ 📋+ </button>+ </div>+ </td>+ <td class="meta">${w.chain_id ? `Chain ${w.chain_id}` : 'Multi-chain'}</td>+ <td class="meta">${new Date(w.created_at).toLocaleDateString()}</td>+ <td>+ ${w.is_primary ? '<span class="pill">Primary</span>' : ''}+ </td>+ <td style="text-align: right">+ <button+ class="btn sec btn-sm"+ onclick="unlinkWallet('${w.address}')"+ style="padding: 6px 10px; font-size: 12px"+ >+ Unlink+ </button>+ </td>+ </tr>+ `,+ )+ .join('');++ container.innerHTML = `+ <table class="wallet-table">+ <thead>+ <tr>+ <th>Address</th>+ <th>Chain</th>+ <th>Linked</th>+ <th></th>+ <th></th>+ </tr>+ </thead>+ <tbody>+ ${rows}+ </tbody>+ </table>+ `;+ }++ function copyToClipboard(text) {+ navigator.clipboard.writeText(text).then(+ () => {+ // Show brief feedback+ const btn = event.target;+ const orig = btn.textContent;+ btn.textContent = '✓';+ setTimeout(() => {+ btn.textContent = orig;+ }, 1500);+ },+ () => alert('Copy failed'),+ );+ }++ async function unlinkWallet(address) {+ if (!confirm(`Unlink ${address.slice(0, 6)}…${address.slice(-4)}?`)) return;++ try {+ const res = await fetch(`${apiUrl}/auth/wallets/${address}`, {+ method: 'DELETE',+ credentials: 'include',+ });+ if (!res.ok) {+ const err = await res.json();+ throw new Error(err.error_description || 'Failed to unlink wallet');+ }+ loadWallets();+ } catch (err) {+ showError(err.message);+ }+ }++ async function linkWallet() {+ if (!window.ethereum) {+ showError('MetaMask not found. Please install it to link wallets.');+ return;+ }++ try {+ // 1. Request accounts from MetaMask+ const accounts = await window.ethereum.request({+ method: 'eth_requestAccounts',+ });+ const address = accounts[0];++ // 2. Get nonce from server+ const nonceRes = await fetch(`${apiUrl}/auth/wallets/nonce`, {+ method: 'POST',+ credentials: 'include',+ });+ if (!nonceRes.ok) throw new Error('Failed to get nonce');+ const { nonce, message } = await nonceRes.json();++ // 3. Sign message with MetaMask+ let signature;+ try {+ signature = await window.ethereum.request({+ method: 'personal_sign',+ params: [message, address],+ });+ } catch (err) {+ if (err.code === 4001) {+ showError('Signature cancelled by user');+ } else {+ showError(err.message || 'Signature failed');+ }+ return;+ }++ // 4. Send signature to server+ const linkRes = await fetch(`${apiUrl}/auth/wallets`, {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ address, message, signature, nonce }),+ });+ if (!linkRes.ok) {+ const err = await linkRes.json();+ throw new Error(err.error_description || 'Failed to link wallet');+ }++ showError('', 'success');+ loadWallets();+ } catch (err) {+ showError(err.message);+ }+ }++ function showError(msg, type = 'error') {+ const el = document.getElementById('error');+ if (!msg) {+ el.style.display = 'none';+ return;+ }+ if (type === 'success') {+ el.textContent = '✓ Wallet linked successfully!';+ el.style.background = 'rgba(92, 255, 92, 0.1)';+ el.style.borderColor = 'rgba(92, 255, 92, 0.3)';+ el.style.color = '#b3ffb3';+ } else {+ el.textContent = msg;+ el.style.background = 'rgba(255, 92, 92, 0.1)';+ el.style.borderColor = 'rgba(255, 92, 92, 0.3)';+ el.style.color = '#ffb3b3';+ }+ el.style.display = 'block';+ }++ window.copyToClipboard = copyToClipboard;+ window.unlinkWallet = unlinkWallet;++ // Initialize+ (async () => {+ const me = await fetchUser();+ if (me) {+ document.getElementById('user-email').textContent = me.user.email;+ loadWallets();+ }+ })();++ document.getElementById('link-btn').addEventListener('click', linkWallet);+ </script>+ </body>+</html>diff --git a/dist-artifact/ddd.png b/dist-artifact/ddd.pngnew file mode 100644index 000000000..f5998260bBinary files /dev/null and b/dist-artifact/ddd.png differdiff --git a/dist-artifact/docs-widgets.html b/dist-artifact/docs-widgets.htmlnew file mode 100644index 000000000..103458f3b--- /dev/null+++ b/dist-artifact/docs-widgets.html@@ -0,0 +1,248 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <meta http-equiv="X-UA-Compatible" content="IE=edge">+ <title>Widget Docs — 3D Agent</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">+ <meta name="description" content="Embed 3D widgets on any site. URL params, iframe + script embeds, postMessage API, oEmbed, privacy.">+ <meta name="theme-color" content="#0a0a0a">++ <meta property="og:type" content="article">+ <meta property="og:title" content="3D Agent — Widget Docs">+ <meta property="og:description" content="Embed 3D widgets on any site. URL params, postMessage API, oEmbed, privacy.">+ <meta property="og:url" content="https://3dagent.vercel.app/docs/widgets">++ <link rel="canonical" href="https://3dagent.vercel.app/docs/widgets">+ <link rel="shortcut icon" href="/favicon.ico">+ <link rel="preconnect" href="https://fonts.googleapis.com">+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap" rel="stylesheet">+ <link rel="stylesheet" href="/style.css">+ <link rel="stylesheet" href="/widgets-gallery/gallery.css">+ <style>+ .docs-main {+ max-width: 760px;+ margin: 0 auto;+ padding: var(--space-2xl) var(--space-lg);+ line-height: var(--leading-normal);+ }+ .docs-main h1 {+ font-family: var(--font-display);+ font-weight: 300;+ font-size: var(--text-2xl);+ letter-spacing: -1px;+ margin: 0 0 var(--space-md);+ }+ .docs-main h2 {+ font-family: var(--font-display);+ font-weight: 400;+ font-size: var(--text-xl);+ margin: var(--space-2xl) 0 var(--space-sm);+ padding-bottom: var(--space-xs);+ border-bottom: 1px solid rgba(255,255,255,0.08);+ }+ .docs-main h3 {+ font-weight: 500;+ font-size: var(--text-lg);+ margin: var(--space-xl) 0 var(--space-sm);+ }+ .docs-main p, .docs-main li { color: rgba(229,229,229,0.85); }+ .docs-main ul, .docs-main ol { padding-left: var(--space-lg); }+ .docs-main code {+ font-family: var(--font-mono);+ font-size: 0.92em;+ background: rgba(255,255,255,0.06);+ padding: 1px 5px;+ border-radius: 3px;+ color: #e5e5e5;+ }+ .docs-main pre {+ background: #0a0a0a;+ border: 1px solid rgba(255,255,255,0.08);+ border-radius: var(--radius-md);+ padding: var(--space-md);+ overflow-x: auto;+ line-height: 1.5;+ font-family: var(--font-mono);+ font-size: var(--text-sm);+ }+ .docs-main pre code {+ background: transparent;+ padding: 0;+ }+ .docs-main table {+ width: 100%;+ border-collapse: collapse;+ margin: var(--space-md) 0;+ font-size: var(--text-sm);+ }+ .docs-main th, .docs-main td {+ text-align: left;+ padding: var(--space-xs) var(--space-sm);+ border-bottom: 1px solid rgba(255,255,255,0.06);+ }+ .docs-main th { color: rgba(229,229,229,0.6); font-weight: 500; }+ .docs-main a { color: var(--accent); }+ .docs-main hr { border: 0; border-top: 1px solid rgba(255,255,255,0.08); margin: var(--space-xl) 0; }+ .docs-toc {+ padding: var(--space-md);+ background: rgba(255,255,255,0.025);+ border: 1px solid rgba(255,255,255,0.06);+ border-radius: var(--radius-md);+ margin-bottom: var(--space-xl);+ }+ .docs-toc ul { margin: var(--space-xs) 0; padding-left: var(--space-md); }+ </style>+</head>+<body class="gallery-body">+ <header class="gallery-header">+ <h1><a href="/"><span class="wordmark-dot" aria-hidden="true"></span>3D Agent</a></h1>+ <nav class="features-nav">+ <a href="/">Viewer</a>+ <a href="/features">Features</a>+ <a href="/widgets">Widgets</a>+ <a href="/docs/widgets" class="active" aria-current="page">Docs</a>+ <a href="/dashboard" class="nav-dashboard">Dashboard</a>+ </nav>+ </header>++ <main class="docs-main">+ <h1>Widgets</h1>+ <p>Embeddable 3D — a configured, shareable view of an avatar that any site can drop in with one line of HTML.</p>+ <p>A widget is a saved bundle of: an avatar (GLB stored in R2), a widget type (turntable, animation gallery, talking agent, ERC-8004 passport, hotspot tour), and brand config (background, accent, caption, controls, camera). Widgets are created in the <a href="/studio">Widget Studio</a> and shared via short URLs.</p>++ <div class="docs-toc">+ <strong>On this page:</strong>+ <ul>+ <li><a href="#quick-start">Quick start</a></li>+ <li><a href="#widget-types">Widget types</a></li>+ <li><a href="#urls">URLs</a></li>+ <li><a href="#embedding">Embedding</a></li>+ <li><a href="#postmessage-api">postMessage API</a></li>+ <li><a href="#og-oembed">OG / oEmbed</a></li>+ <li><a href="#csp-cors">CSP / CORS</a></li>+ <li><a href="#privacy">Privacy & analytics</a></li>+ <li><a href="#faq">FAQ</a></li>+ </ul>+ </div>++ <h2 id="quick-start">Quick start</h2>+ <ol>+ <li>Sign in at <a href="/">3dagent.vercel.app</a>.</li>+ <li>Open the <a href="/studio">Studio</a>.</li>+ <li>Pick an avatar, pick a widget type, tweak brand colors and controls, click <strong>Generate Embed</strong>.</li>+ <li>Copy the iframe snippet into any HTML page, blog post, Notion doc, or CMS.</li>+ </ol>++ <h2 id="widget-types">Widget types</h2>+ <table>+ <thead><tr><th>Type</th><th>Best for</th><th>Default size</th></tr></thead>+ <tbody>+ <tr><td><code>turntable</code></td><td>Hero banners, product showcases. Auto-rotate, no UI.</td><td>600 × 600</td></tr>+ <tr><td><code>animation-gallery</code></td><td>Showcasing a rigged avatar's animation library.</td><td>720 × 720</td></tr>+ <tr><td><code>talking-agent</code></td><td>Embodied chat — your agent on your site.</td><td>420 × 600</td></tr>+ <tr><td><code>passport</code></td><td>On-chain identity card backed by ERC-8004.</td><td>480 × 560</td></tr>+ <tr><td><code>hotspot-tour</code></td><td>Annotated 3D scenes with clickable POIs.</td><td>800 × 600</td></tr>+ </tbody>+ </table>++ <h2 id="urls">URLs</h2>+ <p>Every widget has three canonical URLs.</p>+ <table>+ <thead><tr><th>URL</th><th>Use it for</th></tr></thead>+ <tbody>+ <tr><td><code>/w/<id></code></td><td>Sharing in Slack/Discord/X — server-rendered with rich OG card.</td></tr>+ <tr><td><code>/#widget=<id></code></td><td>The SPA viewer with the widget config applied.</td></tr>+ <tr><td><code>/api/widgets/<id>/og</code></td><td>The 1200×630 preview image.</td></tr>+ </tbody>+ </table>++ <h3>Hash parameters</h3>+ <table>+ <thead><tr><th>Param</th><th>Type</th><th>Description</th></tr></thead>+ <tbody>+ <tr><td><code>widget</code></td><td>string</td><td>Loads a saved widget by id.</td></tr>+ <tr><td><code>model</code></td><td>string</td><td>Loads a raw GLB by URL (mutually exclusive with <code>widget</code>).</td></tr>+ <tr><td><code>kiosk</code></td><td>boolean</td><td>Hides the header chrome for clean iframe embeds.</td></tr>+ <tr><td><code>cameraPosition</code></td><td>x,y,z</td><td>Comma-separated camera position override.</td></tr>+ <tr><td><code>preset</code></td><td>string</td><td>HDR environment preset name.</td></tr>+ </tbody>+ </table>++ <h2 id="embedding">Embedding</h2>+ <h3>iframe (recommended)</h3>+<pre><code><iframe+ src="https://3dagent.vercel.app/#widget=wdgt_abc123def456&kiosk=true"+ width="600"+ height="600"+ style="border:0;border-radius:12px;max-width:100%"+ allow="autoplay; xr-spatial-tracking; clipboard-write"+ loading="lazy"></iframe></code></pre>++ <h3>Script embed</h3>+<pre><code><script async src="https://3dagent.vercel.app/embed.js" data-widget="wdgt_abc123def456"></script></code></pre>++ <h3>oEmbed (WordPress, Ghost, Notion)</h3>+ <p>Most CMSes auto-detect oEmbed. Paste a <code>/w/<id></code> URL on its own line and the editor should turn it into a live embed automatically.</p>++ <h2 id="postmessage-api">postMessage API</h2>+ <p>Widgets communicate with the parent page via <code>window.postMessage</code>. <strong>Always check <code>event.origin</code> before trusting any message.</strong></p>++ <h3>iframe → parent</h3>+ <table>+ <thead><tr><th>Event</th><th>Payload</th><th>When</th></tr></thead>+ <tbody>+ <tr><td><code>widget:ready</code></td><td><code>{ id, type }</code></td><td>Widget runtime has booted.</td></tr>+ <tr><td><code>widget:load</code></td><td><code>{ id, model_url }</code></td><td>Underlying GLB loaded successfully.</td></tr>+ <tr><td><code>widget:load:error</code></td><td><code>{ id, error }</code></td><td>GLB or config failed to load.</td></tr>+ <tr><td><code>widget:chat:message</code></td><td><code>{ role, content }</code></td><td>Talking-agent only.</td></tr>+ <tr><td><code>widget:hotspot:open</code></td><td><code>{ id, label }</code></td><td>Hotspot-tour only.</td></tr>+ <tr><td><code>widget:resize</code></td><td><code>{ width, height }</code></td><td>Widget reports preferred size.</td></tr>+ </tbody>+ </table>++<pre><code>window.addEventListener('message', (e) => {+ if (e.origin !== 'https://3dagent.vercel.app') return;+ if (e.data?.type === 'widget:ready') {+ console.log('Widget mounted:', e.data.id);+ }+});</code></pre>++ <h3>parent → iframe</h3>+ <table>+ <thead><tr><th>Event</th><th>Payload</th><th>Effect</th></tr></thead>+ <tbody>+ <tr><td><code>widget:config</code></td><td><code>{ background, accent, autoRotate, … }</code></td><td>Live-update brand config.</td></tr>+ <tr><td><code>widget:command</code></td><td><code>{ command, args }</code></td><td>Trigger a runtime action.</td></tr>+ </tbody>+ </table>++ <h2 id="og-oembed">OG / oEmbed</h2>+ <p>Every widget URL serves rich-preview metadata. <code>/w/<id></code> is server-rendered with Open Graph + Twitter card tags and a <code><link rel="alternate" type="application/json+oembed"></code> pointer.</p>+<pre><code>GET /api/widgets/oembed?url=<widget-url>&format=json</code></pre>+ <p>Returns standard <a href="https://oembed.com">oEmbed v1.0</a> JSON, type <code>rich</code>. Accepts both <code>/w/<id></code> and <code>/#widget=<id></code> forms.</p>++ <h2 id="csp-cors">CSP / CORS</h2>+ <p>Widgets run in a sandboxed iframe with these <code>allow</code> flags: <code>autoplay</code>, <code>xr-spatial-tracking</code>, <code>clipboard-write</code>. If your site uses strict CSP, allow:</p>+<pre><code>frame-src https://3dagent.vercel.app;+img-src https://3dagent.vercel.app data:;</code></pre>++ <h2 id="privacy">Privacy & analytics</h2>+ <p>We log a minimal first-party event per widget load: <code>widget_id</code>, <code>type</code>, <code>country</code> (Vercel edge header), <code>referer_host</code> (hostname only), <code>created_at</code>. No IPs. No cookies. No user agents. No chat content. No cross-widget tracking.</p>++ <h2 id="faq">FAQ</h2>+ <p><strong>Can I self-host?</strong> The runtime is open source. The Studio + saved-widgets API depends on Neon + R2; you'd need to wire those yourself. See <a href="/docs/deployment">deployment guide</a>.</p>+ <p><strong>Why no WordPress plugin?</strong> The oEmbed endpoint already does what a plugin would.</p>+ <p><strong>How big is the bundle?</strong> Cold load ~400KB JS + the GLB itself.</p>+ <p><strong>Mobile?</strong> Yes — every widget type works on iOS Safari and Android Chrome.</p>++ <hr>+ <p><a href="/widgets">← Back to gallery</a> · <a href="/studio">Open the Studio →</a></p>+ </main>++ <footer class="gallery-footer">+ <p>3D Agent · <a href="/">Viewer</a> · <a href="/widgets">Widgets</a> · <a href="/docs/widgets">Docs</a> · <a href="https://github.com/nirholas/3D">GitHub</a></p>+ </footer>+</body>+</html>diff --git a/dist-artifact/embed-sdk.js b/dist-artifact/embed-sdk.jsnew file mode 100644index 000000000..8205b4973--- /dev/null+++ b/dist-artifact/embed-sdk.js@@ -0,0 +1,137 @@+/*+ * Agent3D embed SDK — Bridge v1+ * -----------------------------+ * <script src="https://3dagent.vercel.app/embed-sdk.js"></script>+ * const bridge = Agent3D.connect(iframeEl, {+ * agentId,+ * onReady, // ({ version, capabilities, name }) => void+ * onAction, // (action) => void — every protocol action the iframe emits+ * onResize, // (height) => void — auto-applied to iframe unless autoResize:false+ * onError, // (err) => void — handshake timeout, blocked embed, etc.+ * helloTimeoutMs: 2000,+ * autoResize: true,+ * });+ * bridge.send({ type: 'speak', payload: { text: 'hello' } });+ * bridge.ping().then(rttMs => …);+ * bridge.destroy();+ *+ * Tiny on purpose. See public/agent/embed.html for the full bridge contract.+ */+(function (root) {+ 'use strict';+ if (root.Agent3D && root.Agent3D.connect) return;++ function connect(iframeEl, opts) {+ if (!iframeEl || iframeEl.tagName !== 'IFRAME') throw new Error('Agent3D.connect: iframe element required');+ if (!opts || !opts.agentId) throw new Error('Agent3D.connect: opts.agentId required');++ var agentId = String(opts.agentId);+ var helloTimeoutMs = opts.helloTimeoutMs == null ? 2000 : opts.helloTimeoutMs;+ var autoResize = opts.autoResize !== false;+ var iframeOrigin = opts.origin || originOf(iframeEl.src);+ var pings = Object.create(null);+ var nextPingId = 1;+ var ready = false;+ var destroyed = false;+ var readyResolve, readyReject;+ var readyPromise = new Promise(function (resolve, reject) { readyResolve = resolve; readyReject = reject; });++ function post(msg) {+ if (destroyed || !iframeEl.contentWindow) return;+ iframeEl.contentWindow.postMessage(msg, iframeOrigin || '*');+ }++ function onMessage(ev) {+ if (destroyed) return;+ // Origin lock — when we know the iframe origin, ignore everything else.+ if (iframeOrigin && ev.origin !== iframeOrigin) return;+ var msg = ev.data;+ if (!msg || typeof msg !== 'object' || msg.agentId !== agentId) return;+ switch (msg.type) {+ case 'agent:ready':+ if (!ready) {+ ready = true;+ readyResolve({ version: msg.version, capabilities: msg.capabilities || [], name: msg.name });+ if (typeof opts.onReady === 'function') {+ try { opts.onReady({ version: msg.version, capabilities: msg.capabilities || [], name: msg.name }); }+ catch (e) { console.error('[Agent3D] onReady threw', e); }+ }+ }+ return;+ case 'agent:action':+ if (typeof opts.onAction === 'function') {+ try { opts.onAction(msg.action); } catch (e) { console.error('[Agent3D] onAction threw', e); }+ }+ return;+ case 'agent:resize':+ if (autoResize && typeof msg.height === 'number' && msg.height > 0) {+ iframeEl.style.height = msg.height + 'px';+ }+ if (typeof opts.onResize === 'function') {+ try { opts.onResize(msg.height); } catch (e) { console.error('[Agent3D] onResize threw', e); }+ }+ return;+ case 'agent:pong':+ var pending = pings[msg.id];+ if (pending) { delete pings[msg.id]; pending.resolve(Date.now() - pending.t); }+ return;+ case 'agent:blocked':+ emitError(new Error('Embed blocked by agent policy'));+ return;+ }+ }++ function emitError(err) {+ if (typeof opts.onError === 'function') {+ try { opts.onError(err); } catch (e) { console.error('[Agent3D] onError threw', e); }+ }+ if (!ready) readyReject(err);+ }++ function sendHello() { post({ type: 'agent:hello', agentId: agentId, host: location.origin }); }++ window.addEventListener('message', onMessage);++ // Send hello on every load — also on first attach if the iframe was+ // already loaded before connect() ran (common when the host hydrates+ // after the iframe).+ iframeEl.addEventListener('load', sendHello);+ if (iframeEl.contentDocument && iframeEl.contentDocument.readyState === 'complete') sendHello();+ // Belt-and-braces: hosts that miss the load event still get a hello.+ setTimeout(sendHello, 50);++ var helloTimer = helloTimeoutMs > 0 ? setTimeout(function () {+ if (!ready) emitError(new Error('agent:ready not received within ' + helloTimeoutMs + 'ms'));+ }, helloTimeoutMs) : null;++ readyPromise.finally(function () { if (helloTimer) clearTimeout(helloTimer); });++ return {+ ready: readyPromise,+ send: function (action) { post({ type: 'agent:action', agentId: agentId, action: action }); },+ ping: function (timeoutMs) {+ var id = String(nextPingId++);+ return new Promise(function (resolve, reject) {+ pings[id] = { t: Date.now(), resolve: resolve };+ post({ type: 'agent:ping', agentId: agentId, id: id });+ setTimeout(function () {+ if (pings[id]) { delete pings[id]; reject(new Error('ping timeout')); }+ }, timeoutMs || 2000);+ });+ },+ destroy: function () {+ destroyed = true;+ window.removeEventListener('message', onMessage);+ iframeEl.removeEventListener('load', sendHello);+ if (helloTimer) clearTimeout(helloTimer);+ },+ };+ }++ function originOf(url) {+ if (!url) return '';+ try { return new URL(url, location.href).origin; } catch (_) { return ''; }+ }++ root.Agent3D = { connect: connect, version: '1' };+})(typeof window !== 'undefined' ? window : globalThis);diff --git a/dist-artifact/embed.js b/dist-artifact/embed.jsnew file mode 100644index 000000000..8836141d9--- /dev/null+++ b/dist-artifact/embed.js@@ -0,0 +1,80 @@+// 3D Agent — script-tag embed.+// <script async src="https://3dagent.vercel.app/embed.js" data-widget="wdgt_..."></script>+//+// Injects a sandboxed iframe at the script tag's location, sized via data-*+// attributes (or the type's default), then forwards widget:resize events from+// the iframe to keep the host layout snug.+//+// Zero deps, plain DOM. Intentionally tiny — gets minified/cached at the edge.++(function () {+ 'use strict';++ var TYPE_SIZES = {+ 'turntable': [600, 600],+ 'animation-gallery': [720, 720],+ 'talking-agent': [420, 600],+ 'passport': [480, 560],+ 'hotspot-tour': [800, 600],+ };++ var ORIGIN = (function () {+ try { return new URL(document.currentScript.src).origin; }+ catch (e) { return 'https://3dagent.vercel.app'; }+ })();++ function attr(el, name, fallback) {+ var v = el && el.getAttribute && el.getAttribute(name);+ return v != null && v !== '' ? v : fallback;+ }++ function mount(scriptEl) {+ var widgetId = attr(scriptEl, 'data-widget', null);+ if (!widgetId) {+ console.warn('[3d-agent embed] missing data-widget attribute');+ return;+ }+ var type = attr(scriptEl, 'data-type', null);+ var defaults = (type && TYPE_SIZES[type]) || [600, 600];+ var width = attr(scriptEl, 'data-width', String(defaults[0]));+ var height = attr(scriptEl, 'data-height', String(defaults[1]));+ var radius = attr(scriptEl, 'data-radius', '12');+ var border = attr(scriptEl, 'data-border', '0');++ var src = ORIGIN + '/#widget=' + encodeURIComponent(widgetId) + '&kiosk=true';++ var iframe = document.createElement('iframe');+ iframe.src = src;+ iframe.title = '3D Agent widget ' + widgetId;+ iframe.loading = 'lazy';+ iframe.allow = 'autoplay; xr-spatial-tracking; clipboard-write';+ iframe.setAttribute('width', width);+ iframe.setAttribute('height', height);+ iframe.style.border = border + 'px solid transparent';+ iframe.style.borderRadius = radius + 'px';+ iframe.style.maxWidth = '100%';+ iframe.style.display = 'block';++ var anchor = scriptEl.parentNode;+ if (!anchor) return;+ anchor.insertBefore(iframe, scriptEl);++ // Optional: auto-resize when the widget reports a preferred size.+ window.addEventListener('message', function (e) {+ if (e.origin !== ORIGIN) return;+ if (!e.data || e.data.type !== 'widget:resize') return;+ if (e.data.id && e.data.id !== widgetId) return;+ if (e.data.width) iframe.setAttribute('width', String(e.data.width));+ if (e.data.height) iframe.setAttribute('height', String(e.data.height));+ });+ }++ // Mount every <script data-widget="..."> on the page (allows multiple embeds).+ var current = document.currentScript;+ if (current && current.getAttribute('data-widget')) {+ mount(current);+ return;+ }+ var scripts = document.querySelectorAll('script[data-widget][src*="embed.js"]');+ for (var i = 0; i < scripts.length; i++) mount(scripts[i]);+})();diff --git a/dist-artifact/explore/explore.js b/dist-artifact/explore/explore.jsnew file mode 100644index 000000000..0b8556578--- /dev/null+++ b/dist-artifact/explore/explore.js@@ -0,0 +1,348 @@+/**+ * /explore — ERC-8004 agent marketplace grid.+ *+ * Pulls from GET /api/explore. Filters + infinite pagination via cursor.+ * Clicking a card opens the on-chain token page on the source chain's+ * explorer; clicking the 3D preview (when present) loads the GLB in the+ * main viewer via /#model=<url>.+ */++const CHAINS = [+ { id: 8453, name: 'Base' },+ { id: 42161, name: 'Arbitrum One' },+ { id: 56, name: 'BNB Chain' },+ { id: 1, name: 'Ethereum' },+ { id: 10, name: 'Optimism' },+ { id: 137, name: 'Polygon' },+ { id: 43114, name: 'Avalanche' },+ { id: 100, name: 'Gnosis' },+ { id: 250, name: 'Fantom' },+ { id: 42220, name: 'Celo' },+ { id: 59144, name: 'Linea' },+ { id: 534352, name: 'Scroll' },+ { id: 5000, name: 'Mantle' },+ { id: 324, name: 'zkSync Era' },+ { id: 1284, name: 'Moonbeam' },+ { id: 97, name: 'BSC Testnet' },+ { id: 84532, name: 'Base Sepolia' },+ { id: 421614, name: 'Arbitrum Sepolia' },+ { id: 11155111, name: 'Ethereum Sepolia' },+ { id: 11155420, name: 'Optimism Sepolia' },+ { id: 80002, name: 'Polygon Amoy' },+ { id: 43113, name: 'Avalanche Fuji' },+];++const els = {+ search: document.querySelector('[data-role="search"]'),+ filters: document.querySelector('[data-role="filters"]'),+ chain: document.querySelector('[data-role="chain"]'),+ grid: document.querySelector('[data-role="grid"]'),+ status: document.querySelector('[data-role="status"]'),+ loadMore: document.querySelector('[data-role="load-more"]'),+ statAll: document.querySelector('[data-role="stat-all"]'),+ stat3d: document.querySelector('[data-role="stat-3d"]'),+};++// Populate chain dropdown.+for (const c of CHAINS) {+ const opt = document.createElement('option');+ opt.value = String(c.id);+ opt.textContent = c.name;+ els.chain.appendChild(opt);+}++const state = {+ filter: 'all', // 'all' | '3d'+ chainId: '',+ query: '',+ cursor: null,+ loading: false,+};++let searchDebounce;++els.filters.addEventListener('click', (e) => {+ const btn = e.target.closest('[data-filter]');+ if (!btn) return;+ state.filter = btn.dataset.filter;+ for (const b of els.filters.querySelectorAll('[data-filter]')) {+ b.classList.toggle('active', b.dataset.filter === state.filter);+ }+ resetAndLoad();+});++els.chain.addEventListener('change', () => {+ state.chainId = els.chain.value;+ resetAndLoad();+});++els.search.addEventListener('input', () => {+ clearTimeout(searchDebounce);+ searchDebounce = setTimeout(() => {+ state.query = els.search.value.trim();+ resetAndLoad();+ }, 250);+});++els.loadMore.addEventListener('click', () => loadPage());++// Delegated embed-button click — cards can be re-rendered freely+els.grid.addEventListener('click', (e) => {+ const btn = e.target.closest('[data-role="card-embed"]');+ if (!btn) return;+ e.preventDefault();+ e.stopPropagation();+ openEmbedModal({+ chainId: Number(btn.dataset.chainId),+ agentId: btn.dataset.agentId,+ name: btn.dataset.name,+ });+});++function resetAndLoad() {+ state.cursor = null;+ els.grid.innerHTML = '';+ loadPage();+}++async function loadPage() {+ if (state.loading) return;+ state.loading = true;+ els.loadMore.hidden = true;+ els.status.textContent = state.cursor ? 'Loading more…' : 'Loading agents…';++ const params = new URLSearchParams();+ if (state.filter === '3d') params.set('only3d', '1');+ if (state.chainId) params.set('chain', state.chainId);+ if (state.query) params.set('q', state.query);+ if (state.cursor) params.set('cursor', state.cursor);+ params.set('limit', '24');++ try {+ const res = await fetch(`/api/explore?${params.toString()}`);+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const data = await res.json();++ if (data.totals) {+ els.statAll.textContent = data.totals.all.toLocaleString();+ els.stat3d.textContent = data.totals.threeD.toLocaleString();+ }++ for (const item of data.items) {+ els.grid.appendChild(renderCard(item));+ }+ state.cursor = data.nextCursor;+ els.loadMore.hidden = !state.cursor;++ if (els.grid.children.length === 0) {+ els.status.innerHTML =+ '<div class="explore-empty">No agents match these filters yet.</div>';+ } else {+ els.status.textContent = '';+ }+ } catch (err) {+ els.status.innerHTML = `<div class="explore-error">Failed to load: ${escapeHtml(err.message)}</div>`;+ } finally {+ state.loading = false;+ }+}++function renderCard(item) {+ const card = document.createElement('article');+ card.className = 'explore-card' + (item.has3d ? ' explore-card--3d' : '');++ const thumb = item.image+ ? `<img src="${escapeAttr(item.image)}" alt="" loading="lazy" />`+ : `<div class="explore-card-ph">${item.has3d ? '🎭' : '🤖'}</div>`;++ const badges = [];+ 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.x402Support)+ badges.push(`<span class="explore-badge explore-badge--x402">x402</span>`);++ const serviceChips = (item.services || [])+ .filter((s) => s.name && !['avatar', '3d'].includes(String(s.name).toLowerCase()))+ .slice(0, 3)+ .map((s) => `<span class="explore-svc">${escapeHtml(s.name)}</span>`)+ .join('');++ const primaryHref = item.viewerUrl || item.tokenExplorerUrl || '#';+ const primaryLabel = item.viewerUrl ? 'Load in viewer' : 'View on explorer';+ const primaryTarget = item.viewerUrl ? '_self' : '_blank';++ card.innerHTML = `+ <a class="explore-card-thumb" href="${escapeAttr(primaryHref)}" target="${primaryTarget}" rel="noopener">+ ${thumb}+ ${item.has3d ? '<span class="explore-card-play">▶</span>' : ''}+ </a>+ <div class="explore-card-body">+ <div class="explore-card-head">+ <h3 class="explore-card-name">${escapeHtml(item.name)}</h3>+ <span class="explore-card-id">#${escapeHtml(item.agentId)}</span>+ </div>+ <div class="explore-card-badges">${badges.join('')}</div>+ ${item.description ? `<p class="explore-card-desc">${escapeHtml(item.description)}</p>` : ''}+ ${serviceChips ? `<div class="explore-card-svcs">${serviceChips}</div>` : ''}+ <div class="explore-card-foot">+ <a class="explore-card-owner" href="${escapeAttr(item.ownerExplorerUrl || '#')}" target="_blank" rel="noopener" title="${escapeAttr(item.owner)}">+ ${escapeHtml(item.ownerShort)}+ </a>+ <div class="explore-card-actions">+ ${item.viewerUrl ? `<a class="explore-card-link" href="${escapeAttr(item.viewerUrl)}">View 3D</a>` : ''}+ <a class="explore-card-link" href="${escapeAttr(item.tokenExplorerUrl || '#')}" target="_blank" rel="noopener">On-chain ↗</a>+ <button type="button" class="explore-card-link explore-card-link--ghost" data-role="card-embed"+ data-chain-id="${escapeAttr(String(item.chainId))}"+ data-agent-id="${escapeAttr(String(item.agentId))}"+ data-name="${escapeAttr(item.name || `Agent #${item.agentId}`)}">Embed</button>+ </div>+ </div>+ </div>+ `;+ return card;+}++function escapeHtml(s) {+ return String(s ?? '')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}+function escapeAttr(s) {+ return escapeHtml(s).replace(/'/g, ''');+}++// ─── Embed modal ──────────────────────────────────────────────────────────+const LIB_CDN_URL = 'https://3dagent.vercel.app/agent-3d/latest/agent-3d.js';++function openEmbedModal({ chainId, agentId, name }) {+ document.querySelector('.embed-modal')?.remove();++ const origin = location.origin;+ const pageUrl = `${origin}/a/${chainId}/${agentId}`;+ const embedUrl = `${origin}/a/${chainId}/${agentId}/embed`;+ const agentUri = `agent://${chainId}/${agentId}`;+ const displayName = name || `Agent #${agentId}`;++ const snippets = {+ webComponent: `<script type="module" src="${LIB_CDN_URL}"></script>\n<agent-3d src="${agentUri}" mode="inline" width="480px" responsive></agent-3d>`,+ iframe: `<iframe src="${embedUrl}" width="480" height="600" style="border:0;border-radius:12px" allow="autoplay; xr-spatial-tracking" sandbox="allow-scripts allow-same-origin allow-popups" title="${displayName}"></iframe>`,+ link: pageUrl,+ markdown: `[](${pageUrl})`,+ farcaster: pageUrl,+ };++ const modal = document.createElement('div');+ modal.className = 'embed-modal';+ modal.setAttribute('role', 'dialog');+ modal.setAttribute('aria-modal', 'true');+ modal.innerHTML = `+ <div class="embed-modal__backdrop" data-role="close"></div>+ <div class="embed-modal__panel" role="document">+ <header class="embed-modal__head">+ <div>+ <h2 class="embed-modal__title">Embed ${escapeHtml(displayName)}</h2>+ <p class="embed-modal__sub">Drop this anywhere — any site, any doc, any chat.</p>+ </div>+ <button type="button" class="embed-modal__close" data-role="close" aria-label="Close">×</button>+ </header>+ <div class="embed-modal__tabs" role="tablist">+ <button type="button" class="embed-tab is-active" data-tab="webComponent" role="tab" aria-selected="true">Web component</button>+ <button type="button" class="embed-tab" data-tab="iframe" role="tab" aria-selected="false">iframe</button>+ <button type="button" class="embed-tab" data-tab="link" role="tab" aria-selected="false">Link</button>+ <button type="button" class="embed-tab" data-tab="markdown" role="tab" aria-selected="false">Markdown</button>+ <button type="button" class="embed-tab" data-tab="farcaster" role="tab" aria-selected="false">Farcaster</button>+ </div>+ <div class="embed-modal__body">+ <div class="embed-pane is-active" data-pane="webComponent">+ <p class="embed-pane__hint">Full fidelity — avatar, animations, voice, memory. Requires script module.</p>+ <textarea class="embed-snippet" readonly rows="3">${escapeHtml(snippets.webComponent)}</textarea>+ <button type="button" class="embed-copy-btn" data-role="copy" data-key="webComponent">Copy</button>+ </div>+ <div class="embed-pane" data-pane="iframe">+ <p class="embed-pane__hint">Works anywhere that allows iframes: Notion, Substack, Ghost, blogs.</p>+ <textarea class="embed-snippet" readonly rows="3">${escapeHtml(snippets.iframe)}</textarea>+ <button type="button" class="embed-copy-btn" data-role="copy" data-key="iframe">Copy</button>+ </div>+ <div class="embed-pane" data-pane="link">+ <p class="embed-pane__hint">Unfurls in Slack, X, Discord, iMessage with a rich preview card.</p>+ <input class="embed-snippet embed-snippet--input" readonly value="${escapeAttr(snippets.link)}" />+ <button type="button" class="embed-copy-btn" data-role="copy" data-key="link">Copy</button>+ </div>+ <div class="embed-pane" data-pane="markdown">+ <p class="embed-pane__hint">GitHub README, Markdown blog — renders a preview card that links to the viewer.</p>+ <textarea class="embed-snippet" readonly rows="2">${escapeHtml(snippets.markdown)}</textarea>+ <button type="button" class="embed-copy-btn" data-role="copy" data-key="markdown">Copy</button>+ </div>+ <div class="embed-pane" data-pane="farcaster">+ <p class="embed-pane__hint">Cast this link — Warpcast and compatible clients render an interactive Frame with View 3D + Explore buttons.</p>+ <input class="embed-snippet embed-snippet--input" readonly value="${escapeAttr(snippets.farcaster)}" />+ <button type="button" class="embed-copy-btn" data-role="copy" data-key="farcaster">Copy</button>+ </div>+ </div>+ <footer class="embed-modal__foot">+ <a href="${escapeAttr(pageUrl)}" target="_blank" rel="noopener" class="embed-foot-link">Open standalone page ↗</a>+ <a href="${escapeAttr(embedUrl)}" target="_blank" rel="noopener" class="embed-foot-link">Preview iframe ↗</a>+ </footer>+ </div>+ `;+ document.body.appendChild(modal);++ const close = () => {+ modal.remove();+ document.removeEventListener('keydown', onEsc);+ };+ const onEsc = (e) => {+ if (e.key === 'Escape') close();+ };+ document.addEventListener('keydown', onEsc);+ modal.querySelectorAll('[data-role="close"]').forEach((el) => el.addEventListener('click', close));++ modal.querySelectorAll('.embed-tab').forEach((tab) => {+ tab.addEventListener('click', () => {+ modal.querySelectorAll('.embed-tab').forEach((t) => {+ t.classList.toggle('is-active', t === tab);+ t.setAttribute('aria-selected', t === tab ? 'true' : 'false');+ });+ modal.querySelectorAll('.embed-pane').forEach((p) => {+ p.classList.toggle('is-active', p.dataset.pane === tab.dataset.tab);+ });+ });+ });++ modal.querySelectorAll('[data-role="copy"]').forEach((btn) => {+ btn.addEventListener('click', () => {+ const key = btn.dataset.key;+ const text = snippets[key];+ if (!text) return;+ const done = (ok) => {+ btn.textContent = ok ? 'Copied ✓' : 'Copy failed';+ setTimeout(() => (btn.textContent = 'Copy'), 1400);+ };+ if (navigator.clipboard?.writeText) {+ navigator.clipboard.writeText(text).then(() => done(true), () => done(false));+ } else {+ const ta = modal.querySelector(`[data-pane="${key}"] .embed-snippet`);+ ta?.select();+ try {+ document.execCommand('copy');+ done(true);+ } catch {+ done(false);+ }+ }+ });+ });++ setTimeout(() => {+ const first = modal.querySelector('.embed-pane.is-active .embed-snippet');+ first?.focus();+ first?.select?.();+ }, 50);+}++loadPage();diff --git a/dist-artifact/explore/index.html b/dist-artifact/explore/index.htmlnew file mode 100644index 000000000..5d38da558--- /dev/null+++ b/dist-artifact/explore/index.html@@ -0,0 +1,103 @@+<!doctype html>+<html lang="en">+ <head>+ <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="description"+ content="Browse every ERC-8004 agent registered on-chain across 20+ EVM networks. Filter by 3D avatar, chain, and keywords."+ />+ <meta name="theme-color" content="#000000" />+ <link rel="canonical" href="https://3dagent.vercel.app/explore" />+ <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;600;700&family=Space+Grotesk:wght@500;600;700&display=swap"+ rel="stylesheet"+ />+ </head>+ <body class="features-page explore-page">+ <header>+ <h1>+ <a href="/"><span class="wordmark-dot" aria-hidden="true"></span>3D Agent</a>+ </h1>+ <nav class="features-nav">+ <a href="/app">Viewer</a>+ <a href="/explore" class="active">Explore</a>+ <a href="/features">Features</a>+ <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>+ </nav>+ </header>++ <main class="features-main explore-main">+ <section class="explore-hero">+ <div class="explore-hero-chip">+ <span class="explore-hero-dot"></span>+ <span>ERC-8004 Agent Directory</span>+ </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.+ </p>++ <div class="explore-stats" data-role="stats">+ <div class="explore-stat">+ <div class="explore-stat-value" data-role="stat-all">—</div>+ <div class="explore-stat-label">Agents indexed</div>+ </div>+ <div class="explore-stat">+ <div class="explore-stat-value" data-role="stat-3d">—</div>+ <div class="explore-stat-label">With 3D avatars</div>+ </div>+ <div class="explore-stat">+ <div class="explore-stat-value" data-role="stat-chains">22</div>+ <div class="explore-stat-label">Chains crawled</div>+ </div>+ </div>+ </section>++ <section class="explore-controls">+ <div class="explore-search">+ <input+ type="search"+ placeholder="Search by name or description…"+ data-role="search"+ aria-label="Search agents"+ />+ </div>+ <div class="explore-chips" data-role="filters">+ <button class="explore-chip active" data-filter="all">All agents</button>+ <button class="explore-chip" data-filter="3d">3D only</button>+ </div>+ <div class="explore-chain-select">+ <label for="explore-chain">Chain:</label>+ <select id="explore-chain" data-role="chain">+ <option value="">All chains</option>+ </select>+ </div>+ </section>++ <section class="explore-grid-wrap">+ <div class="explore-grid" data-role="grid"></div>+ <div class="explore-status" data-role="status"></div>+ <div class="explore-load-more-wrap">+ <button class="explore-load-more" data-role="load-more" hidden>+ Load more+ </button>+ </div>+ </section>+ </main>++ <script type="module" src="./explore.js"></script>+ </body>+</html>diff --git a/dist-artifact/favicon.ico b/dist-artifact/favicon.iconew file mode 100644index 000000000..a0bdf04e1Binary files /dev/null and b/dist-artifact/favicon.ico differdiff --git a/dist-artifact/first-meet/first-meet.js b/dist-artifact/first-meet/first-meet.jsnew file mode 100644index 000000000..e2906ca77--- /dev/null+++ b/dist-artifact/first-meet/first-meet.js@@ -0,0 +1,328 @@+// First meet onboarding flow for newly created avatars++const STEPS = ['name', 'bio', 'voice', 'greet', 'done'];+let currentStep = 0;+let state = {+ avatarId: null,+ avatar: null,+ agent: null,+ name: 'My Agent',+ bio: '',+ voice: 'en-US-female',+ bodyType: 'neutral',+};++// ── Init ───────────────────────────────────────────────────────────────────++async function boot() {+ const avatarId = new URL(window.location).searchParams.get('avatar');+ if (!avatarId) {+ window.location.href = '/login';+ return;+ }++ // Auth check+ const authRes = await fetch('/api/auth/me', { credentials: 'include' });+ if (!authRes.ok) {+ window.location.href =+ '/login?next=' + encodeURIComponent(window.location.pathname + window.location.search);+ return;+ }++ state.avatarId = avatarId;++ // Load avatar+ try {+ const res = await fetch(`/api/avatars/${avatarId}`, { credentials: 'include' });+ if (!res.ok) throw new Error('Avatar not found');+ const data = await res.json();+ state.avatar = data.avatar;+ renderPreview();+ } catch (err) {+ showPreviewError('Failed to load avatar: ' + err.message);+ return;+ }++ // Load existing agent if any+ try {+ const res = await fetch('/api/agents/me', { credentials: 'include' });+ if (res.ok) {+ const data = await res.json();+ if (data.agent) {+ state.agent = data.agent;+ if (data.agent.name) state.name = data.agent.name;+ if (data.agent.description) state.bio = data.agent.description;+ }+ }+ } catch {+ // Ignore agent load errors, proceed+ }++ wireStepButtons();+ updateProgress();+ goToStep(0);+}++// ── Rendering ───────────────────────────────────────────────────────────────++function renderPreview() {+ const container = document.getElementById('preview-content');+ if (!state.avatar || !state.avatar.model_url) {+ container.innerHTML = '<div class="error-msg">Avatar URL not available</div>';+ return;+ }++ const viewer = document.createElement('model-viewer');+ viewer.src = state.avatar.model_url;+ viewer.alt = state.avatar.name || 'Avatar';+ viewer.setAttribute('auto-rotate', '');+ viewer.setAttribute('camera-controls', '');+ viewer.setAttribute('enable-shadow', '');++ container.innerHTML = '';+ container.appendChild(viewer);+}++function showPreviewError(msg) {+ const container = document.getElementById('preview-content');+ container.innerHTML = `<div class="error-msg">${escapeHtml(msg)}</div>`;+}++function updateProgress() {+ const pct = ((currentStep + 1) / STEPS.length) * 100;+ document.getElementById('progress-bar').style.width = pct + '%';+}++function goToStep(n) {+ STEPS.forEach((s) => {+ document.getElementById(`step-${s}`).classList.remove('active');+ });+ currentStep = n;+ document.getElementById(`step-${STEPS[currentStep]}`).classList.add('active');+ updateProgress();++ if (currentStep === 0) {+ const input = document.getElementById('name-input');+ input.value = state.name;+ input.focus();+ updateCharCount('name');+ } else if (currentStep === 1) {+ const textarea = document.getElementById('bio-input');+ textarea.value = state.bio;+ textarea.focus();+ updateCharCount('bio');+ } else if (currentStep === 2) {+ document.getElementById('voice-select').value = state.voice;+ document.getElementById('body-type-select').value = state.bodyType;+ } else if (currentStep === 3) {+ renderGreeting();+ }+}++function updateCharCount(field) {+ const input = document.getElementById(`${field}-input`);+ const count = document.getElementById(`${field}-count`);+ count.textContent = input.value.length;+}++// ── Wire buttons ─────────────────────────────────────────────────────────────++function wireStepButtons() {+ // Step 1: Name+ document.getElementById('name-input').addEventListener('input', (e) => {+ state.name = e.target.value || 'My Agent';+ updateCharCount('name');+ });+ document.getElementById('name-next').addEventListener('click', () => goToStep(1));+ document.getElementById('name-skip').addEventListener('click', () => goToStep(1));++ // Step 2: Bio+ document.getElementById('bio-input').addEventListener('input', (e) => {+ state.bio = e.target.value;+ updateCharCount('bio');+ });+ document.getElementById('bio-next').addEventListener('click', () => goToStep(2));+ document.getElementById('bio-back').addEventListener('click', () => goToStep(0));++ // Step 3: Voice+ document.getElementById('voice-select').addEventListener('change', (e) => {+ state.voice = e.target.value;+ });+ document.getElementById('body-type-select').addEventListener('change', (e) => {+ state.bodyType = e.target.value;+ });+ document.getElementById('voice-next').addEventListener('click', () => goToStep(3));+ document.getElementById('voice-back').addEventListener('click', () => goToStep(1));++ // Step 4: Greet+ document.getElementById('greet-next').addEventListener('click', () => goToStep(4));++ // Step 5: Done+ document.getElementById('done-agent').addEventListener('click', async () => {+ // Persist final state+ try {+ await persistState();+ } catch (err) {+ alert('Failed to save: ' + err.message);+ return;+ }+ if (state.agent) {+ window.location.href = `/agent/${state.agent.id}`;+ }+ });+ document.getElementById('done-dashboard').addEventListener('click', () => {+ window.location.href = '/dashboard';+ });+}++// ── Greeting (Step 4) ───────────────────────────────────────────────────────++async function renderGreeting() {+ const container = document.getElementById('preview-content');+ const textDiv = document.getElementById('greeting-text');++ try {+ // Try to load agent-3d element+ if (window.customElements && customElements.get('agent-3d')) {+ const agent3d = document.createElement('agent-3d');+ agent3d.setAttribute('model', state.avatar.model_url);+ agent3d.setAttribute('voice', state.voice);+ agent3d.setAttribute('eager', '');++ container.innerHTML = '';+ container.appendChild(agent3d);++ textDiv.textContent = 'Greeting…';++ // Wait for element to be ready, then emit speak event+ setTimeout(() => {+ try {+ const greetingText = buildGreetingText();+ const event = new CustomEvent('speak', {+ detail: { text: greetingText, sentiment: 0.8 },+ });+ agent3d.dispatchEvent(event);+ textDiv.textContent = `"${greetingText}"`;+ } catch (e) {+ console.error('Greeting failed:', e);+ textDiv.textContent = buildGreetingText();+ }+ }, 500);+ } else {+ // Fallback: model-viewer + text+ const viewer = document.createElement('model-viewer');+ viewer.src = state.avatar.model_url;+ viewer.alt = state.avatar.name || 'Avatar';+ viewer.setAttribute('auto-rotate', '');+ viewer.setAttribute('camera-controls', '');+ viewer.setAttribute('enable-shadow', '');++ container.innerHTML = '';+ container.appendChild(viewer);++ const greetingText = buildGreetingText();+ textDiv.textContent = `"${greetingText}"`;++ // Try browser TTS+ if (window.SpeechSynthesis || window.webkitSpeechSynthesis) {+ const synth = window.speechSynthesis || window.webkitSpeechSynthesis;+ const utterance = new SpeechSynthesisUtterance(greetingText);+ utterance.voice = findVoice(state.voice);+ utterance.rate = 0.95;+ synth.speak(utterance);+ }+ }+ } catch (err) {+ console.error('Greeting render error:', err);+ textDiv.textContent = buildGreetingText();+ }+}++function buildGreetingText() {+ const bioSuffix = state.bio ? ' ' + state.bio : '';+ return `Hi — I'm ${state.name}.${bioSuffix}`;+}++function findVoice(voiceId) {+ if (!(window.SpeechSynthesis || window.webkitSpeechSynthesis)) return null;+ const synth = window.speechSynthesis || window.webkitSpeechSynthesis;+ const voices = synth.getVoices();++ const langMap = {+ 'en-US-female': ['en-US', 'female'],+ 'en-US-male': ['en-US', 'male'],+ 'en-GB-female': ['en-GB', 'female'],+ 'en-GB-male': ['en-GB', 'male'],+ };++ const [lang, gender] = langMap[voiceId] || ['en-US', 'female'];++ return (+ voices.find((v) => v.lang.startsWith(lang) && (v.name.includes(gender) || true)) ||+ voices[0] ||+ null+ );+}++// ── Persistence ────────────────────────────────────────────────────────────++async function persistState() {+ // 1. PATCH avatar name + description+ await fetch(`/api/avatars/${state.avatarId}`, {+ method: 'PATCH',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ name: state.name,+ description: state.bio,+ }),+ }).then((r) => {+ if (!r.ok) throw new Error(`Avatar update failed: ${r.status}`);+ return r.json();+ });++ // 2. Create or update agent+ if (!state.agent) {+ // POST new agent+ const res = await fetch('/api/agents', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ name: state.name,+ description: state.bio,+ avatar_id: state.avatarId,+ }),+ });+ if (!res.ok) throw new Error(`Agent creation failed: ${res.status}`);+ const data = await res.json();+ state.agent = data.agent;+ } else {+ // PATCH existing agent+ const res = await fetch(`/api/agents/${state.agent.id}`, {+ method: 'PATCH',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ name: state.name,+ description: state.bio,+ avatar_id: state.avatarId,+ }),+ });+ if (!res.ok) throw new Error(`Agent update failed: ${res.status}`);+ const data = await res.json();+ state.agent = data.agent;+ }+}++// ── Helpers ────────────────────────────────────────────────────────────────++function escapeHtml(text) {+ const div = document.createElement('div');+ div.textContent = text;+ return div.innerHTML;+}++// ── Bootstrap ──────────────────────────────────────────────────────────────++boot();diff --git a/dist-artifact/first-meet/index.html b/dist-artifact/first-meet/index.htmlnew file mode 100644index 000000000..befed6937--- /dev/null+++ b/dist-artifact/first-meet/index.html@@ -0,0 +1,319 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>Meet Your Agent · 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;+ }+ .container {+ display: grid;+ grid-template-columns: 1fr 1fr;+ min-height: 100vh;+ gap: 0;+ }+ .preview-col {+ background: var(--panel);+ border-right: 1px solid var(--border);+ padding: 28px;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ overflow: auto;+ }+ .preview-col model-viewer,+ .preview-col agent-3d {+ width: 100%;+ height: 100%;+ max-height: 600px;+ border-radius: 8px;+ background: linear-gradient(135deg, #1a1a24 0%, #0f0f14 100%);+ }+ .preview-col .loading,+ .preview-col .error-msg {+ text-align: center;+ color: #aaa;+ }+ .form-col {+ padding: 28px;+ display: flex;+ flex-direction: column;+ justify-content: center;+ max-width: 600px;+ overflow: auto;+ }+ .form-col h1 {+ font-size: 24px;+ margin: 0 0 8px;+ letter-spacing: -0.01em;+ }+ .form-col .sub {+ color: #888;+ font-size: 14px;+ margin: 0 0 24px;+ }+ .step {+ display: none;+ }+ .step.active {+ display: block;+ }+ .form-group {+ margin-bottom: 20px;+ }+ label {+ display: block;+ font-size: 14px;+ font-weight: 500;+ margin-bottom: 8px;+ color: #ccc;+ }+ input[type='text'],+ textarea,+ select {+ width: 100%;+ padding: 10px 12px;+ border: 1px solid var(--border);+ border-radius: 6px;+ background: rgba(0, 0, 0, 0.3);+ color: #eee;+ font-size: 14px;+ font-family: inherit;+ transition:+ border-color 0.2s,+ background-color 0.2s;+ }+ input[type='text']:focus,+ textarea:focus,+ select:focus {+ outline: none;+ border-color: var(--accent);+ background: rgba(0, 0, 0, 0.5);+ }+ textarea {+ resize: vertical;+ min-height: 80px;+ }+ .char-count {+ font-size: 12px;+ color: #666;+ margin-top: 4px;+ }+ .buttons {+ display: flex;+ gap: 12px;+ margin-top: 24px;+ }+ button {+ flex: 1;+ padding: 10px 16px;+ border: 1px solid var(--border);+ border-radius: 6px;+ background: rgba(106, 92, 255, 0.1);+ color: #9a8cff;+ font-size: 14px;+ font-weight: 500;+ cursor: pointer;+ transition:+ background-color 0.2s,+ border-color 0.2s;+ }+ button:hover:not(:disabled) {+ background: rgba(106, 92, 255, 0.2);+ border-color: var(--accent);+ }+ button:disabled {+ opacity: 0.5;+ cursor: not-allowed;+ }+ button.primary {+ background: var(--accent);+ color: #000;+ border-color: var(--accent);+ }+ button.primary:hover:not(:disabled) {+ background: #7b6dff;+ }+ .skip-btn {+ flex: 0;+ padding: 10px 20px;+ background: transparent;+ color: #666;+ border: none;+ }+ .skip-btn:hover {+ color: #aaa;+ background: transparent;+ }+ .progress {+ height: 3px;+ background: var(--border);+ border-radius: 2px;+ margin-bottom: 20px;+ overflow: hidden;+ }+ .progress-bar {+ height: 100%;+ background: var(--accent);+ transition: width 0.3s ease;+ }+ .greeting-text {+ text-align: center;+ margin: 20px 0;+ font-size: 16px;+ color: #aaa;+ font-style: italic;+ }+ .grid-2col {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 12px;+ }+ .grid-2col .form-group {+ margin-bottom: 0;+ }+ @media (max-width: 900px) {+ .container {+ grid-template-columns: 1fr;+ }+ .preview-col {+ min-height: 300px;+ border-right: none;+ border-bottom: 1px solid var(--border);+ }+ }+ </style>+ </head>+ <body>+ <div class="container">+ <div class="preview-col">+ <div id="preview-content">+ <div class="loading">Loading avatar…</div>+ </div>+ </div>+ <div class="form-col">+ <div class="progress">+ <div class="progress-bar" id="progress-bar"></div>+ </div>++ <!-- Step 1: Name -->+ <div class="step active" id="step-name">+ <h1>Name your agent</h1>+ <p class="sub">Give your avatar a name. You can change it later.</p>+ <div class="form-group">+ <input+ type="text"+ id="name-input"+ placeholder="My Agent"+ minlength="2"+ maxlength="40"+ autofocus+ />+ <div class="char-count"><span id="name-count">0</span>/40</div>+ </div>+ <div class="buttons">+ <button class="primary" id="name-next">Next</button>+ <button class="skip-btn" id="name-skip">Skip</button>+ </div>+ </div>++ <!-- Step 2: Bio -->+ <div class="step" id="step-bio">+ <h1>Tell us about your agent</h1>+ <p class="sub">Add a short bio (optional). Max 280 characters.</p>+ <div class="form-group">+ <textarea+ id="bio-input"+ placeholder="What should people know about this agent?"+ maxlength="280"+ ></textarea>+ <div class="char-count"><span id="bio-count">0</span>/280</div>+ </div>+ <div class="buttons">+ <button class="primary" id="bio-next">Next</button>+ <button id="bio-back">Back</button>+ </div>+ </div>++ <!-- Step 3: Voice + Body Type -->+ <div class="step" id="step-voice">+ <h1>Voice & appearance</h1>+ <p class="sub">Choose how your agent communicates and looks.</p>+ <div class="form-group">+ <label for="voice-select">Voice</label>+ <select id="voice-select">+ <option value="en-US-female">US Female</option>+ <option value="en-US-male">US Male</option>+ <option value="en-GB-female">British Female</option>+ <option value="en-GB-male">British Male</option>+ </select>+ </div>+ <div class="form-group">+ <label for="body-type-select">Body type</label>+ <select id="body-type-select">+ <option value="neutral">Neutral</option>+ <option value="feminine">Feminine</option>+ <option value="masculine">Masculine</option>+ </select>+ </div>+ <div class="buttons">+ <button class="primary" id="voice-next">Next</button>+ <button id="voice-back">Back</button>+ </div>+ </div>++ <!-- Step 4: Greet -->+ <div class="step" id="step-greet">+ <h1>Meet your agent</h1>+ <p class="sub">Your agent is ready to say hello.</p>+ <div class="greeting-text" id="greeting-text">Listening…</div>+ <div class="buttons">+ <button class="primary" id="greet-next">Continue</button>+ </div>+ </div>++ <!-- Step 5: Done -->+ <div class="step" id="step-done">+ <h1>All set!</h1>+ <p class="sub">Your agent is ready to go.</p>+ <div class="buttons">+ <button class="primary" id="done-agent">Go to my agent</button>+ <button id="done-dashboard">Back to dashboard</button>+ </div>+ </div>+ </div>+ </div>++ <script src="/dist-lib/agent-3d.js" type="module"></script>+ <script src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>+ <script type="module" src="./first-meet.js"></script>+ </body>+</html>diff --git a/dist-artifact/hydrate/index.html b/dist-artifact/hydrate/index.htmlnew file mode 100644index 000000000..93e9d4ac8--- /dev/null+++ b/dist-artifact/hydrate/index.html@@ -0,0 +1,465 @@+<!DOCTYPE html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Import My Agents</title>+ <style>+ :root {+ --primary: #0066cc;+ --primary-dark: #0052a3;+ --gray-100: #f5f5f5;+ --gray-200: #e0e0e0;+ --gray-700: #333;+ --error: #d32f2f;+ --success: #388e3c;+ }++ * {+ margin: 0;+ padding: 0;+ box-sizing: border-box;+ }++ body {+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;+ background: var(--gray-100);+ color: var(--gray-700);+ min-height: 100vh;+ padding: 20px;+ }++ .container {+ max-width: 800px;+ margin: 0 auto;+ background: white;+ border-radius: 8px;+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);+ padding: 40px;+ }++ h1 {+ margin-bottom: 10px;+ font-size: 28px;+ }++ .subtitle {+ color: #666;+ margin-bottom: 30px;+ font-size: 14px;+ }++ .alert {+ padding: 16px;+ border-radius: 4px;+ margin-bottom: 24px;+ display: none;+ }++ .alert.show {+ display: block;+ }++ .alert.error {+ background: #ffebee;+ color: var(--error);+ border-left: 4px solid var(--error);+ }++ .alert.success {+ background: #e8f5e9;+ color: var(--success);+ border-left: 4px solid var(--success);+ }++ .alert.info {+ background: #e3f2fd;+ color: var(--primary);+ border-left: 4px solid var(--primary);+ }++ .auth-prompt {+ text-align: center;+ padding: 40px 20px;+ }++ .auth-prompt p {+ margin-bottom: 20px;+ color: #666;+ }++ .button {+ display: inline-block;+ padding: 12px 24px;+ border-radius: 4px;+ border: none;+ font-size: 14px;+ font-weight: 600;+ cursor: pointer;+ text-decoration: none;+ text-align: center;+ transition: all 0.2s;+ }++ .button.primary {+ background: var(--primary);+ color: white;+ }++ .button.primary:hover {+ background: var(--primary-dark);+ }++ .button.secondary {+ background: var(--gray-200);+ color: var(--gray-700);+ }++ .button.secondary:hover {+ background: var(--gray-300);+ }++ .button:disabled {+ opacity: 0.5;+ cursor: not-allowed;+ }++ .agents-list {+ display: none;+ }++ .agent-card {+ border: 1px solid var(--gray-200);+ border-radius: 6px;+ padding: 16px;+ margin-bottom: 16px;+ display: flex;+ gap: 16px;+ align-items: flex-start;+ }++ .agent-image {+ width: 80px;+ height: 80px;+ background: var(--gray-100);+ border-radius: 4px;+ flex-shrink: 0;+ display: flex;+ align-items: center;+ justify-content: center;+ font-size: 12px;+ color: #999;+ overflow: hidden;+ }++ .agent-image img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ }++ .agent-info {+ flex: 1;+ min-width: 0;+ }++ .agent-header {+ display: flex;+ align-items: baseline;+ gap: 8px;+ margin-bottom: 4px;+ }++ .agent-name {+ font-size: 16px;+ font-weight: 600;+ color: var(--gray-700);+ }++ .chain-badge {+ display: inline-block;+ background: var(--gray-100);+ color: #666;+ padding: 2px 8px;+ border-radius: 3px;+ font-size: 12px;+ font-weight: 500;+ }++ .agent-description {+ color: #666;+ font-size: 14px;+ line-height: 1.4;+ margin-bottom: 8px;+ }++ .agent-id {+ color: #999;+ font-size: 12px;+ font-family: monospace;+ }++ .agent-actions {+ display: flex;+ gap: 8px;+ margin-top: 12px;+ }++ .button-small {+ padding: 6px 12px;+ font-size: 12px;+ }++ .import-link {+ color: var(--primary);+ text-decoration: none;+ font-weight: 600;+ font-size: 12px;+ }++ .import-link:hover {+ text-decoration: underline;+ }++ .loading {+ text-align: center;+ padding: 40px;+ color: #666;+ }++ .spinner {+ display: inline-block;+ width: 20px;+ height: 20px;+ border: 2px solid var(--gray-200);+ border-top-color: var(--primary);+ border-radius: 50%;+ animation: spin 0.6s linear infinite;+ margin-right: 10px;+ vertical-align: middle;+ }++ @keyframes spin {+ to {+ transform: rotate(360deg);+ }+ }++ .empty-state {+ text-align: center;+ padding: 60px 20px;+ }++ .empty-state p {+ color: #666;+ margin-bottom: 20px;+ }++ .breadcrumb {+ font-size: 12px;+ color: #999;+ margin-bottom: 20px;+ }++ .breadcrumb a {+ color: var(--primary);+ text-decoration: none;+ }++ .breadcrumb a:hover {+ text-decoration: underline;+ }+ </style>+ </head>+ <body>+ <div class="container">+ <div class="breadcrumb">+ <a href="/">Home</a> / <a href="/dashboard/">Dashboard</a> / Import Agents+ </div>++ <h1>Import My Agents</h1>+ <p class="subtitle">+ Discover and import agents you've already registered on-chain+ </p>++ <div id="alert" class="alert"></div>++ <div id="authPrompt" class="auth-prompt" style="display: none">+ <p>+ To import your on-chain agents, you need to+ <strong>connect a wallet</strong> first.+ </p>+ <a href="/dashboard/wallets.html" class="button primary">Connect Wallet</a>+ </div>++ <div id="loadingState" class="loading" style="display: none">+ <span class="spinner"></span> Fetching your agents…+ </div>++ <div id="agentsList" class="agents-list"></div>++ <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>+ </p>+ </div>+ </div>++ <script type="module">+ const alertEl = document.getElementById('alert');+ const authPrompt = document.getElementById('authPrompt');+ const loadingState = document.getElementById('loadingState');+ const agentsList = document.getElementById('agentsList');+ const emptyState = document.getElementById('emptyState');++ function showAlert(message, type = 'info') {+ alertEl.textContent = message;+ alertEl.className = `alert show ${type}`;+ if (type === 'error') {+ console.error('[hydrate]', message);+ }+ }++ function hideAlert() {+ alertEl.className = 'alert';+ }++ async function checkAuth() {+ try {+ const res = await fetch('/api/auth/wallets', {+ credentials: 'include',+ });++ if (res.status === 401) {+ // Not authenticated+ return { authenticated: false, wallets: [] };+ }++ const data = await res.json();+ return {+ authenticated: true,+ wallets: data.wallets || [],+ };+ } catch (err) {+ console.error('[hydrate] auth check failed', err);+ return { authenticated: false, wallets: [] };+ }+ }++ async function loadAgents() {+ const auth = await checkAuth();++ if (!auth.authenticated) {+ authPrompt.style.display = 'block';+ return;+ }++ if (auth.wallets.length === 0) {+ authPrompt.style.display = 'block';+ return;+ }++ loadingState.style.display = 'block';++ try {+ const { fetchDiscoveredAgents } = await import('/src/erc8004/hydrate.js');+ const agents = await fetchDiscoveredAgents();++ loadingState.style.display = 'none';++ if (agents.length === 0) {+ emptyState.style.display = 'block';+ return;+ }++ renderAgents(agents);+ agentsList.style.display = 'block';+ } catch (err) {+ loadingState.style.display = 'none';+ showAlert(`Failed to load agents: ${err.message}`, 'error');+ }+ }++ function renderAgents(agents) {+ agentsList.innerHTML = agents+ .map(+ (agent) => `+ <div class="agent-card">+ <div class="agent-image">+ ${+ 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>`+ : ''+ }+ <div class="agent-id">Agent ID: ${escapeHtml(agent.agentId)}</div>+ </div>+ <div class="agent-actions">+ ${+ agent.alreadyImported+ ? `<a href="/dashboard/?agent=${escapeHtml(agent.id)}" class="import-link">Go to agent →</a>`+ : `<button class="button primary button-small" data-chain="${agent.chainId}" data-id="${escapeHtml(agent.agentId)}">Import</button>`+ }+ </div>+ </div>+ `,+ )+ .join('');++ // Attach import handlers+ document.querySelectorAll('[data-chain]').forEach((btn) => {+ btn.addEventListener('click', () => {+ importAgent(btn.dataset.chain, btn.dataset.id, btn);+ });+ });+ }++ async function importAgent(chainId, agentId, button) {+ button.disabled = true;+ const originalText = button.textContent;+ button.innerHTML = '<span class="spinner"></span> Importing…';+ hideAlert();++ try {+ const { importAgent: doImport } = await import('/src/erc8004/hydrate.js');+ const agent = await doImport({+ chainId: parseInt(chainId),+ agentId,+ });++ showAlert(`Successfully imported ${agent.name}!`, 'success');++ // Replace button with link after a brief delay+ setTimeout(() => {+ button.outerHTML = `<a href="/dashboard/?agent=${escapeHtml(agent.id)}" class="import-link">Go to agent →</a>`;+ }, 1000);+ } catch (err) {+ showAlert(`Import failed: ${err.message}`, 'error');+ button.disabled = false;+ button.textContent = originalText;+ }+ }++ function escapeHtml(text) {+ if (!text) return '';+ const div = document.createElement('div');+ div.textContent = text;+ return div.innerHTML;+ }++ // Load on page load+ loadAgents();+ </script>+ </body>+</html>diff --git a/dist-artifact/login.html b/dist-artifact/login.htmlnew file mode 100644index 000000000..6899653f6--- /dev/null+++ b/dist-artifact/login.html@@ -0,0 +1,93 @@+<!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/';++// 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>+</html>diff --git a/dist-artifact/og-image.png b/dist-artifact/og-image.pngnew file mode 100644index 000000000..c8d017dcfBinary files /dev/null and b/dist-artifact/og-image.png differdiff --git a/dist-artifact/pwa-192x192.png b/dist-artifact/pwa-192x192.pngnew file mode 100644index 000000000..3438a05a3Binary files /dev/null and b/dist-artifact/pwa-192x192.png differdiff --git a/dist-artifact/pwa-512x512.png b/dist-artifact/pwa-512x512.pngnew file mode 100644index 000000000..c6ce55590Binary files /dev/null and b/dist-artifact/pwa-512x512.png differdiff --git a/dist-artifact/pwa-icon.svg b/dist-artifact/pwa-icon.svgnew file mode 100644index 000000000..58713989d--- /dev/null+++ b/dist-artifact/pwa-icon.svg@@ -0,0 +1,89 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">+ <defs>+ <!-- Vertex glow -->+ <radialGradient id="vglow" cx="50%" cy="50%" r="50%">+ <stop offset="0%" stop-color="#ffffff" stop-opacity="0.9"/>+ <stop offset="30%" stop-color="#b8e8ff" stop-opacity="0.5"/>+ <stop offset="100%" stop-color="#b8e8ff" stop-opacity="0"/>+ </radialGradient>+ <!-- Edge glow filter -->+ <filter id="edgeGlow" x="-20%" y="-20%" width="140%" height="140%">+ <feGaussianBlur stdDeviation="3" result="blur"/>+ <feMerge><feMergeNode in="blur"/><feMergeNode in="SourceGraphic"/></feMerge>+ </filter>+ <!-- Strong vertex glow filter -->+ <filter id="vtxGlow" x="-100%" y="-100%" width="300%" height="300%">+ <feGaussianBlur stdDeviation="8" result="blur"/>+ <feMerge><feMergeNode in="blur"/><feMergeNode in="SourceGraphic"/></feMerge>+ </filter>+ <!-- Cube face gradient — top -->+ <linearGradient id="faceTop" x1="0" y1="0" x2="0" y2="1">+ <stop offset="0%" stop-color="#1a2a3a" stop-opacity="0.7"/>+ <stop offset="100%" stop-color="#0a1520" stop-opacity="0.85"/>+ </linearGradient>+ <!-- Cube face gradient — right -->+ <linearGradient id="faceRight" x1="0" y1="0" x2="1" y2="1">+ <stop offset="0%" stop-color="#0f1e2e" stop-opacity="0.8"/>+ <stop offset="100%" stop-color="#060e18" stop-opacity="0.9"/>+ </linearGradient>+ <!-- Cube face gradient — left -->+ <linearGradient id="faceLeft" x1="1" y1="0" x2="0" y2="1">+ <stop offset="0%" stop-color="#0d1a28" stop-opacity="0.75"/>+ <stop offset="100%" stop-color="#080f1a" stop-opacity="0.9"/>+ </linearGradient>+ </defs>++ <!-- Background -->+ <rect width="512" height="512" rx="96" fill="#080814"/>++ <!-- Isometric cube — 3/4 view like 3d.png -->+ <!-- Vertices: top=256,110 front-left=116,256 front-right=396,256+ bottom=256,402 back-left=116,182 back-right=396,182 -->++ <!-- Left face -->+ <polygon points="256,110 116,182 116,330 256,402" fill="url(#faceLeft)" stroke="none"/>+ <!-- Right face -->+ <polygon points="256,110 396,182 396,330 256,402" fill="url(#faceRight)" stroke="none"/>+ <!-- Top face -->+ <polygon points="256,110 116,182 256,254 396,182" fill="url(#faceTop)" stroke="none"/>++ <!-- Subtle inner grid lines on faces -->+ <!-- Left face grid -->+ <line x1="186" y1="146" x2="186" y2="366" stroke="#1a3a5a" stroke-width="0.5" opacity="0.3"/>+ <line x1="116" y1="256" x2="256" y2="256" stroke="#1a3a5a" stroke-width="0.5" opacity="0.3"/>+ <!-- Right face grid -->+ <line x1="326" y1="146" x2="326" y2="366" stroke="#1a3a5a" stroke-width="0.5" opacity="0.3"/>+ <line x1="256" y1="256" x2="396" y2="256" stroke="#1a3a5a" stroke-width="0.5" opacity="0.3"/>+ <!-- Top face grid -->+ <line x1="186" y1="146" x2="326" y2="146" stroke="#1a3a5a" stroke-width="0.5" opacity="0.25"/>+ <line x1="256" y1="110" x2="256" y2="254" stroke="#1a3a5a" stroke-width="0.5" opacity="0.25"/>++ <!-- Edges — glowing cyan/white like crystal cube -->+ <!-- Top edges -->+ <line x1="256" y1="110" x2="116" y2="182" stroke="#7ec8e3" stroke-width="2" opacity="0.7" filter="url(#edgeGlow)"/>+ <line x1="256" y1="110" x2="396" y2="182" stroke="#7ec8e3" stroke-width="2" opacity="0.7" filter="url(#edgeGlow)"/>+ <!-- Top front edge -->+ <line x1="116" y1="182" x2="256" y2="254" stroke="#5aadcf" stroke-width="1.5" opacity="0.5" filter="url(#edgeGlow)"/>+ <line x1="396" y1="182" x2="256" y2="254" stroke="#5aadcf" stroke-width="1.5" opacity="0.5" filter="url(#edgeGlow)"/>+ <!-- Vertical edges -->+ <line x1="116" y1="182" x2="116" y2="330" stroke="#5aadcf" stroke-width="1.8" opacity="0.5" filter="url(#edgeGlow)"/>+ <line x1="396" y1="182" x2="396" y2="330" stroke="#5aadcf" stroke-width="1.8" opacity="0.5" filter="url(#edgeGlow)"/>+ <line x1="256" y1="254" x2="256" y2="402" stroke="#4a9abf" stroke-width="1.5" opacity="0.4" filter="url(#edgeGlow)"/>+ <!-- Bottom edges -->+ <line x1="116" y1="330" x2="256" y2="402" stroke="#5aadcf" stroke-width="1.8" opacity="0.55" filter="url(#edgeGlow)"/>+ <line x1="396" y1="330" x2="256" y2="402" stroke="#5aadcf" stroke-width="1.8" opacity="0.55" filter="url(#edgeGlow)"/>++ <!-- Bright vertex glows — matching 3d.png's bright corner highlights -->+ <!-- Top vertex — brightest -->+ <circle cx="256" cy="110" r="14" fill="url(#vglow)" filter="url(#vtxGlow)"/>+ <!-- Left vertex -->+ <circle cx="116" cy="182" r="10" fill="url(#vglow)" opacity="0.6" filter="url(#vtxGlow)"/>+ <!-- Right vertex -->+ <circle cx="396" cy="182" r="10" fill="url(#vglow)" opacity="0.6" filter="url(#vtxGlow)"/>+ <!-- Front-bottom vertex -->+ <circle cx="256" cy="402" r="8" fill="url(#vglow)" opacity="0.35" filter="url(#vtxGlow)"/>+ <!-- Mid vertices — subtler -->+ <circle cx="256" cy="254" r="7" fill="url(#vglow)" opacity="0.3" filter="url(#vtxGlow)"/>+ <circle cx="116" cy="330" r="7" fill="url(#vglow)" opacity="0.3" filter="url(#vtxGlow)"/>+ <circle cx="396" cy="330" r="7" fill="url(#vglow)" opacity="0.4" filter="url(#vtxGlow)"/>+</svg>diff --git a/dist-artifact/register.html b/dist-artifact/register.htmlnew file mode 100644index 000000000..00e445dfb--- /dev/null+++ b/dist-artifact/register.html@@ -0,0 +1,74 @@+<!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>+</html>diff --git a/dist-artifact/reputation/index.html b/dist-artifact/reputation/index.htmlnew file mode 100644index 000000000..01f8c0b7b--- /dev/null+++ b/dist-artifact/reputation/index.html@@ -0,0 +1,502 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />+ <title>Agent Reputation — 3D Agent</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <meta name="description" content="View and submit reviews for on-chain agents." />+ <meta name="theme-color" content="#0a0a0a" />++ <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"+ />++ <style>+ * {+ margin: 0;+ padding: 0;+ box-sizing: border-box;+ }++ html,+ body {+ background: #0a0a0a;+ color: #e5e5e5;+ font-family:+ 'Inter',+ -apple-system,+ BlinkMacSystemFont,+ 'Segoe UI',+ sans-serif;+ font-size: 16px;+ line-height: 1.5;+ height: 100%;+ }++ body {+ overflow-y: auto;+ overflow-x: hidden;+ }++ main {+ max-width: 800px;+ margin: 0 auto;+ padding: 2rem 1.5rem;+ min-height: 100vh;+ }++ h1,+ h2,+ h3 {+ font-family:+ 'Space Grotesk',+ -apple-system,+ BlinkMacSystemFont,+ 'Segoe UI',+ sans-serif;+ font-weight: 600;+ letter-spacing: -0.5px;+ }++ h1 {+ font-size: 2rem;+ }+ h3 {+ font-size: 1.125rem;+ margin: 1.5rem 0 1rem;+ }++ a {+ color: #a78bfa;+ text-decoration: none;+ }+ a:hover {+ color: #c4b5fd;+ }++ /* Header */+ .rep-header {+ margin-bottom: 2rem;+ padding-bottom: 1.5rem;+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);+ }++ .rep-header h1 {+ margin: 0 0 0.5rem 0;+ }++ .rep-header-meta {+ color: rgba(229, 229, 229, 0.6);+ font-size: 0.875rem;+ }++ /* Stats Row */+ .rep-stats {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));+ gap: 1rem;+ margin-bottom: 2rem;+ padding: 1.5rem;+ background: rgba(139, 92, 246, 0.04);+ border: 1px solid rgba(139, 92, 246, 0.1);+ border-radius: 8px;+ }++ .rep-stat {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+ }++ .rep-stat-label {+ font-size: 0.75rem;+ text-transform: uppercase;+ letter-spacing: 1px;+ color: rgba(229, 229, 229, 0.5);+ font-weight: 600;+ }++ .rep-stat-value {+ font-size: 1.75rem;+ font-weight: 700;+ color: #e5e5e5;+ font-family: 'Space Grotesk', monospace;+ }++ /* Reviews Section */+ .rep-reviews {+ margin-bottom: 2rem;+ }++ .rep-empty {+ text-align: center;+ color: rgba(229, 229, 229, 0.5);+ padding: 2rem 1rem;+ }++ .rep-review-list {+ display: flex;+ flex-direction: column;+ gap: 1rem;+ }++ .rep-review-item {+ padding: 1rem;+ background: rgba(255, 255, 255, 0.02);+ border: 1px solid rgba(255, 255, 255, 0.06);+ border-radius: 6px;+ transition:+ background 0.15s,+ border-color 0.15s;+ }++ .rep-review-item:hover {+ background: rgba(255, 255, 255, 0.04);+ border-color: rgba(255, 255, 255, 0.12);+ }++ .rep-review-item.pending {+ opacity: 0.75;+ }++ .rep-review-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: 0.5rem;+ gap: 1rem;+ }++ .rep-reviewer {+ font-weight: 500;+ font-size: 0.875rem;+ color: rgba(229, 229, 229, 0.7);+ font-family: 'Courier New', monospace;+ }++ .rep-stars {+ font-size: 0.875rem;+ letter-spacing: 2px;+ color: #fbbf24;+ }++ .rep-comment {+ margin: 0.75rem 0 0.75rem 0;+ color: rgba(229, 229, 229, 0.8);+ font-size: 0.9375rem;+ line-height: 1.6;+ word-wrap: break-word;+ white-space: pre-wrap;+ }++ .rep-review-footer {+ display: flex;+ gap: 0.75rem;+ align-items: center;+ font-size: 0.75rem;+ }++ .rep-review-footer a {+ color: #a78bfa;+ text-decoration: none;+ }++ .rep-review-footer a:hover {+ text-decoration: underline;+ }++ .rep-tx-hash {+ color: rgba(229, 229, 229, 0.5);+ font-family: monospace;+ }++ .rep-pending-badge {+ background: rgba(251, 191, 36, 0.15);+ color: #fbbf24;+ padding: 0.25rem 0.5rem;+ border-radius: 3px;+ font-weight: 500;+ }++ .rep-more-reviews {+ text-align: center;+ color: rgba(229, 229, 229, 0.5);+ font-size: 0.875rem;+ margin-top: 1rem;+ }++ /* Submit Form */+ .rep-submit-form {+ margin-top: 2.5rem;+ padding: 1.5rem;+ background: rgba(139, 92, 246, 0.04);+ border: 1px solid rgba(139, 92, 246, 0.1);+ border-radius: 8px;+ }++ .rep-form-group {+ margin-bottom: 1.5rem;+ }++ .rep-form-group label {+ display: block;+ margin-bottom: 0.5rem;+ font-weight: 500;+ font-size: 0.875rem;+ }++ .rep-stars-input {+ display: flex;+ gap: 0.5rem;+ margin-bottom: 0.5rem;+ }++ .rep-star-btn {+ background: rgba(255, 255, 255, 0.08);+ border: 1px solid rgba(255, 255, 255, 0.12);+ color: rgba(229, 229, 229, 0.6);+ font-size: 1.5rem;+ width: 3rem;+ height: 3rem;+ border-radius: 6px;+ cursor: pointer;+ transition: all 0.15s;+ }++ .rep-star-btn:hover {+ background: rgba(251, 191, 36, 0.1);+ color: #fbbf24;+ border-color: rgba(251, 191, 36, 0.3);+ }++ .rep-star-btn.selected {+ background: rgba(251, 191, 36, 0.15);+ color: #fbbf24;+ border-color: rgba(251, 191, 36, 0.3);+ }++ textarea {+ width: 100%;+ padding: 0.75rem;+ background: rgba(255, 255, 255, 0.05);+ border: 1px solid rgba(255, 255, 255, 0.12);+ border-radius: 6px;+ color: #e5e5e5;+ font-family: 'Inter', sans-serif;+ font-size: 0.9375rem;+ line-height: 1.5;+ resize: vertical;+ transition:+ background 0.15s,+ border-color 0.15s;+ }++ textarea:focus {+ outline: none;+ background: rgba(255, 255, 255, 0.08);+ border-color: rgba(139, 92, 246, 0.3);+ }++ small {+ display: block;+ margin-top: 0.25rem;+ color: rgba(229, 229, 229, 0.5);+ font-size: 0.75rem;+ }++ .rep-submit-btn {+ width: 100%;+ padding: 0.875rem 1.5rem;+ background: #8b5cf6;+ border: 1px solid transparent;+ color: #fff;+ font-weight: 600;+ font-size: 0.9375rem;+ border-radius: 6px;+ cursor: pointer;+ transition: all 0.15s;+ }++ .rep-submit-btn:hover:not(:disabled) {+ background: #7c3aed;+ transform: translateY(-1px);+ }++ .rep-submit-btn:active:not(:disabled) {+ transform: translateY(0);+ }++ .rep-submit-btn:disabled {+ opacity: 0.6;+ cursor: not-allowed;+ }++ .rep-form-hint {+ text-align: center;+ color: rgba(229, 229, 229, 0.5);+ }++ #rep-rating {+ display: none;+ }++ /* Error State */+ .rep-error {+ padding: 2rem;+ text-align: center;+ background: rgba(255, 80, 80, 0.06);+ border: 1px solid rgba(255, 80, 80, 0.2);+ border-radius: 8px;+ }++ .rep-error h3 {+ margin: 0 0 0.5rem 0;+ color: rgba(255, 200, 200, 0.9);+ }++ .rep-error p {+ color: rgba(255, 150, 150, 0.8);+ margin: 0 0 1rem 0;+ }++ .rep-error button {+ padding: 0.5rem 1.5rem;+ background: rgba(255, 100, 100, 0.2);+ border: 1px solid rgba(255, 100, 100, 0.3);+ color: #ffc8c8;+ border-radius: 4px;+ cursor: pointer;+ font-weight: 500;+ transition: all 0.15s;+ }++ .rep-error button:hover {+ background: rgba(255, 100, 100, 0.3);+ }++ /* Loading */+ .rep-loading {+ text-align: center;+ padding: 2rem;+ color: rgba(229, 229, 229, 0.5);+ }++ .spinner {+ display: inline-block;+ width: 20px;+ height: 20px;+ border: 2px solid rgba(139, 92, 246, 0.3);+ border-top-color: #8b5cf6;+ border-radius: 50%;+ animation: spin 0.8s linear infinite;+ }++ @keyframes spin {+ to {+ transform: rotate(360deg);+ }+ }++ /* Responsive */+ @media (max-width: 640px) {+ main {+ padding: 1rem;+ }++ .rep-stats {+ grid-template-columns: repeat(3, 1fr);+ gap: 0.75rem;+ padding: 1rem;+ }++ .rep-stat-value {+ font-size: 1.25rem;+ }++ .rep-review-header {+ flex-direction: column;+ align-items: flex-start;+ }++ .rep-stars-input {+ gap: 0.25rem;+ }++ .rep-star-btn {+ width: 2.5rem;+ height: 2.5rem;+ font-size: 1.25rem;+ }+ }++ @media (prefers-reduced-motion: reduce) {+ * {+ animation-duration: 0.01ms !important;+ animation-iteration-count: 1 !important;+ transition-duration: 0.01ms !important;+ }+ }+ </style>+ </head>+ <body>+ <main id="app">+ <div class="rep-loading">+ <div class="spinner"></div>+ <p>Loading reputation…</p>+ </div>+ </main>++ <script type="module">+ import { ReputationDashboard } from '/src/reputation-ui.js';++ function getQueryParam(name) {+ const params = new URLSearchParams(window.location.search);+ return params.get(name);+ }++ async function init() {+ const agentId = getQueryParam('agent');+ const chainId = getQueryParam('chain');++ if (!agentId) {+ document.querySelector('#app').innerHTML = `+ <div class="rep-error">+ <h3>Missing agent ID</h3>+ <p>URL parameter required: ?agent=<id>&chain=<chainId></p>+ <p style="color: rgba(229,229,229,0.5); font-size: 0.875rem;">+ Example: ?agent=1&chain=84532+ </p>+ </div>+ `;+ return;+ }++ const resolvedChainId = chainId ? Number(chainId) : 84532; // Default: Base Sepolia++ const app = document.querySelector('#app');+ const dashboard = new ReputationDashboard(app, {+ agentId: Number(agentId),+ chainId: resolvedChainId,+ });++ await dashboard.load();+ }++ init().catch((err) => {+ console.error('Init failed:', err);+ document.querySelector('#app').innerHTML = `+ <div class="rep-error">+ <h3>Failed to initialize</h3>+ <p>${err.message || String(err)}</p>+ <button onclick="location.reload()">Retry</button>+ </div>+ `;+ });+ </script>+ </body>+</html>diff --git a/dist-artifact/reputation/reputation.js b/dist-artifact/reputation/reputation.jsnew file mode 100644index 000000000..913d2a334--- /dev/null+++ b/dist-artifact/reputation/reputation.js@@ -0,0 +1,416 @@+/**+ * Reputation page logic — view agent scores and submit reviews.+ * Imports from src/erc8004/reputation.js for contract interactions.+ */++import { getReputation, getRecentReviews, submitReputation } from '../../src/erc8004/reputation.js';+import { JsonRpcProvider, BrowserProvider } from 'ethers';+import { REGISTRY_DEPLOYMENTS } from '../../src/erc8004/abi.js';++const CHAIN_NAMES = {+ 1: 'Ethereum',+ 10: 'Optimism',+ 56: 'BSC',+ 100: 'Gnosis',+ 137: 'Polygon',+ 250: 'Fantom',+ 324: 'zkSync Era',+ 1284: 'Moonbeam',+ 5000: 'Mantle',+ 8453: 'Base',+ 42161: 'Arbitrum One',+ 42220: 'Celo',+ 43114: 'Avalanche',+ 59144: 'Linea',+ 534352: 'Scroll',+ 97: 'BSC Testnet',+ 11155111: 'Ethereum Sepolia',+ 84532: 'Base Sepolia',+ 421614: 'Arbitrum Sepolia',+ 11155420: 'Optimism Sepolia',+ 80002: 'Polygon Amoy',+ 43113: 'Avalanche Fuji',+};++function getChainName(chainId) {+ return CHAIN_NAMES[chainId] || `Chain ${chainId}`;+}++function getExplorerUrl(chainId, txHash) {+ const base = {+ 1: 'https://etherscan.io',+ 10: 'https://optimistic.etherscan.io',+ 56: 'https://bscscan.com',+ 100: 'https://gnosisscan.io',+ 137: 'https://polygonscan.com',+ 250: 'https://ftmscan.com',+ 324: 'https://explorer.zksync.io',+ 1284: 'https://moonscan.io',+ 5000: 'https://explorer.mantle.xyz',+ 8453: 'https://basescan.org',+ 42161: 'https://arbiscan.io',+ 42220: 'https://explorer.celo.org',+ 43114: 'https://snowscan.xyz',+ 59144: 'https://lineascan.build',+ 534352: 'https://scrollscan.com',+ 97: 'https://testnet.bscscan.com',+ 11155111: 'https://sepolia.etherscan.io',+ 84532: 'https://sepolia.basescan.org',+ 421614: 'https://sepolia.arbiscan.io',+ 11155420: 'https://sepolia-optimism.etherscan.io',+ 80002: 'https://amoy.polygonscan.com',+ 43113: 'https://testnet.snowtrace.io',+ }[chainId];+ return base ? `${base}/tx/${txHash}` : null;+}++async function parseAgentId() {+ const params = new URLSearchParams(window.location.search);+ const agentParam = params.get('agent');++ if (!agentParam) {+ throw new Error('Missing ?agent=<chainId>:<agentId> parameter');+ }++ const parts = agentParam.split(':');+ if (parts.length !== 2) {+ throw new Error('Invalid agent format. Expected ?agent=<chainId>:<agentId>');+ }++ const chainId = Number(parts[0]);+ const agentId = Number(parts[1]);++ if (!chainId || !agentId) {+ throw new Error('Invalid agent ID or chain ID');+ }++ return { chainId, agentId };+}++async function fetchAgentInfo(agentId) {+ try {+ const response = await fetch(`/api/agents/${agentId}`);+ if (!response.ok) return null;+ return await response.json();+ } catch {+ return null;+ }+}++function truncateAddress(addr) {+ if (!addr || addr.length < 10) return addr;+ return `${addr.slice(0, 6)}…${addr.slice(-4)}`;+}++async function resolveENS(address, provider) {+ try {+ return await provider.resolveName(address);+ } catch {+ return null;+ }+}++function formatScore(score) {+ if (typeof score === 'number') {+ return score.toFixed(1);+ }+ return '—';+}++function getRatingClass(score) {+ if (score > 0) return 'rating-positive';+ if (score < 0) return 'rating-negative';+ return 'rating-neutral';+}++function formatDate(blockNumber) {+ // Rough estimate: blockNumber doesn't give us date directly+ // In production, you'd want to store the actual timestamp on-chain+ // For now, just show "Recent"+ return 'Recent';+}++async function main() {+ const appEl = document.querySelector('#app');++ try {+ const { chainId, agentId } = await parseAgentId();++ // Show loading state+ appEl.innerHTML = `+ <div class="rep-loading">+ <div class="spinner"></div>+ <p>Loading reputation…</p>+ </div>+ `;++ // Check if chain is supported+ if (!REGISTRY_DEPLOYMENTS[chainId]) {+ throw new Error(`ReputationRegistry not deployed on ${getChainName(chainId)}`);+ }++ // Get agent info from backend if available+ const agentInfo = await fetchAgentInfo(agentId);++ // Create provider for on-chain data+ const rpcUrl = REGISTRY_DEPLOYMENTS[chainId]?.rpcUrl || `https://rpc.${chainId}.io`;+ const provider = new JsonRpcProvider(rpcUrl);++ // Fetch reputation data+ const [repData, reviews] = await Promise.all([+ getReputation({ agentId, runner: provider, chainId }),+ getRecentReviews({ agentId, runner: provider, chainId, fromBlock: 0 }),+ ]);++ // Reverse to show most recent first, limit to 20+ const recentReviews = reviews.reverse().slice(0, 20);++ // Render page+ let html = `+ <div class="rep-header">+ <h1>${agentInfo?.name || `Agent #${agentId}`}</h1>+ <div class="rep-header-meta">+ ${getChainName(chainId)} • ID: ${agentId}+ </div>+ </div>++ <div class="rep-stats">+ <div class="rep-stat">+ <div class="rep-stat-label">Average Rating</div>+ <div class="rep-stat-value">${formatScore(repData.average)}</div>+ </div>+ <div class="rep-stat">+ <div class="rep-stat-label">Reviews</div>+ <div class="rep-stat-value">${repData.count}</div>+ </div>+ <div class="rep-stat">+ <div class="rep-stat-label">Total Score</div>+ <div class="rep-stat-value">${repData.total}</div>+ </div>+ </div>+ `;++ if (recentReviews.length === 0) {+ html += `+ <div class="rep-reviews">+ <div class="rep-empty">No reviews yet. Be the first to review this agent!</div>+ </div>+ `;+ } else {+ html += `+ <div class="rep-reviews">+ <h3>Recent Reviews</h3>+ <div class="rep-review-list">+ `;++ // Resolve ENS names in parallel+ const ensPromises = recentReviews.map(async (rev) => {+ const name = await resolveENS(rev.from, provider).catch(() => null);+ return { review: rev, name };+ });++ const reviewsWithENS = await Promise.all(ensPromises);++ reviewsWithENS.forEach(({ review, name }) => {+ const displayName = name || truncateAddress(review.from);+ const explorerUrl = getExplorerUrl(chainId, review.txHash);+ const scoreClass = getRatingClass(review.score);++ html += `+ <div class="rep-review-item">+ <div class="rep-review-header">+ <span class="rep-reviewer">${displayName}</span>+ <span class="rep-stars">${review.score > 0 ? '+' : ''}${review.score}</span>+ </div>+ `;++ if (review.comment) {+ html += `<div class="rep-comment">${escapeHtml(review.comment)}</div>`;+ }++ html += `+ <div class="rep-review-footer">+ <span>${formatDate(review.blockNumber)}</span>+ `;++ if (explorerUrl) {+ html += `<a href="${explorerUrl}" target="_blank" rel="noopener" class="rep-tx-hash">tx</a>`;+ }++ html += `+ </div>+ </div>+ `;+ });++ html += `+ </div>+ </div>+ `;+ }++ // Submit form+ html += `+ <div class="rep-submit-form">+ <h3>Submit a Review</h3>+ <div id="wallet-status" class="rep-form-hint">+ <button id="connect-wallet" class="rep-submit-btn">Connect Wallet</button>+ </div>+ <div id="form-container" style="display:none">+ <div class="rep-form-group">+ <label>Your Rating</label>+ <div class="rep-stars-input" id="rating-input">+ <!-- Stars filled by JS -->+ </div>+ <input type="hidden" id="rep-rating" value="0" />+ </div>+ <div class="rep-form-group">+ <label>Comment (optional)</label>+ <textarea id="rep-comment" placeholder="Share your feedback…" maxlength="280"></textarea>+ <small><span id="char-count">0</span>/280 characters</small>+ </div>+ <button id="submit-review" class="rep-submit-btn" disabled>Submit Review</button>+ <div id="form-message" style="display:none; margin-top:1rem"></div>+ </div>+ </div>+ `;++ appEl.innerHTML = html;++ // Wire up wallet connection+ const connectBtn = document.getElementById('connect-wallet');+ const walletStatus = document.getElementById('wallet-status');+ const formContainer = document.getElementById('form-container');+ const submitBtn = document.getElementById('submit-review');+ const ratingInput = document.getElementById('rating-input');+ const commentEl = document.getElementById('rep-comment');+ const charCount = document.getElementById('char-count');+ const formMessage = document.getElementById('form-message');++ // Create star buttons+ for (let i = -100; i <= 100; i += 20) {+ const btn = document.createElement('button');+ btn.className = 'rep-star-btn';+ btn.textContent = i >= 0 ? `+${i}` : `${i}`;+ btn.dataset.value = i;+ btn.addEventListener('click', () => {+ document.querySelectorAll('#rating-input button').forEach(b => b.classList.remove('selected'));+ btn.classList.add('selected');+ document.getElementById('rep-rating').value = i;+ submitBtn.disabled = false;+ });+ ratingInput.appendChild(btn);+ }++ commentEl.addEventListener('input', () => {+ charCount.textContent = commentEl.value.length;+ });++ let connectedAddress = null;++ connectBtn.addEventListener('click', async () => {+ try {+ if (typeof window.ethereum === 'undefined') {+ throw new Error('MetaMask not found. Please install it.');+ }++ const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });+ connectedAddress = accounts[0];++ // Check if already reviewed+ const hasReviewed = recentReviews.some(r => r.from.toLowerCase() === connectedAddress.toLowerCase());+ if (hasReviewed) {+ walletStatus.innerHTML = `+ <div class="rep-error">+ <p>You've already reviewed this agent.</p>+ </div>+ `;+ formContainer.style.display = 'none';+ return;+ }++ walletStatus.innerHTML = `+ <p style="color:rgba(229,229,229,0.7)">+ Connected: <code style="font-family:monospace">${truncateAddress(connectedAddress)}</code>+ </p>+ `;+ formContainer.style.display = '';+ connectBtn.style.display = 'none';+ } catch (err) {+ formMessage.style.display = '';+ formMessage.className = 'rep-error';+ formMessage.innerHTML = `<p>${err.message}</p>`;+ }+ });++ submitBtn.addEventListener('click', async () => {+ if (!connectedAddress) {+ formMessage.innerHTML = '<p>Please connect your wallet first.</p>';+ formMessage.className = 'rep-error';+ formMessage.style.display = '';+ return;+ }++ const rating = Number(document.getElementById('rep-rating').value);+ const comment = commentEl.value.trim();++ if (!rating && rating !== 0) {+ formMessage.innerHTML = '<p>Please select a rating.</p>';+ formMessage.className = 'rep-error';+ formMessage.style.display = '';+ return;+ }++ try {+ submitBtn.disabled = true;+ submitBtn.textContent = 'Submitting…';++ if (typeof window.ethereum === 'undefined') {+ throw new Error('MetaMask not found.');+ }++ const signer = new BrowserProvider(window.ethereum).getSigner();+ const txHash = await submitReputation({+ agentId,+ score: Math.abs(rating),+ comment,+ signer: await signer,+ chainId,+ });++ formMessage.innerHTML = `+ <div class="rep-success">+ <p>Review submitted! <a href="${getExplorerUrl(chainId, txHash) || '#'}" target="_blank" rel="noopener">View transaction</a></p>+ </div>+ `;+ formMessage.style.display = '';+ formContainer.style.display = 'none';+ connectBtn.style.display = '';+ connectBtn.textContent = 'Submit Another?';+ } catch (err) {+ formMessage.innerHTML = `<p>${err.message || 'Submission failed'}</p>`;+ formMessage.className = 'rep-error';+ formMessage.style.display = '';+ submitBtn.disabled = false;+ submitBtn.textContent = 'Submit Review';+ }+ });+ } catch (err) {+ console.error('Failed to load reputation:', err);+ appEl.innerHTML = `+ <div class="rep-error">+ <h3>Error</h3>+ <p>${err.message}</p>+ <button onclick="location.reload()">Retry</button>+ </div>+ `;+ }+}++function escapeHtml(text) {+ const div = document.createElement('div');+ div.textContent = text;+ return div.innerHTML;+}++main();diff --git a/dist-artifact/robots.txt b/dist-artifact/robots.txtnew file mode 100644index 000000000..fb4b4747d--- /dev/null+++ b/dist-artifact/robots.txt@@ -0,0 +1,3 @@+User-agent: *+Allow: /+Sitemap: https://3dagent.vercel.app/sitemap.xmldiff --git a/dist-artifact/sitemap.xml b/dist-artifact/sitemap.xmlnew file mode 100644index 000000000..068b429e5--- /dev/null+++ b/dist-artifact/sitemap.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="UTF-8"?>+<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">+ <url>+ <loc>https://3dagent.vercel.app/</loc>+ <lastmod>2026-04-14</lastmod>+ <priority>1.0</priority>+ </url>+</urlset>diff --git a/dist-artifact/skills-index.json b/dist-artifact/skills-index.jsonnew file mode 100644index 000000000..bdd8084de--- /dev/null+++ b/dist-artifact/skills-index.json@@ -0,0 +1,26 @@+[+ {+ "id": "wave",+ "name": "Wave",+ "description": "Agent waves at the user on greet or prompt.",+ "version": "0.1.0",+ "uri": "skills/wave/",+ "author": "3d-agent"+ },+ {+ "id": "dance",+ "name": "Dance",+ "description": "Plays a dance animation loop on request.",+ "version": "0.1.0",+ "uri": "skills/dance/",+ "author": "3d-agent"+ },+ {+ "id": "explain-gltf",+ "name": "Explain glTF",+ "description": "Narrates mesh, material, and animation info from the loaded scene.",+ "version": "0.3.0",+ "uri": "https://skills.3d-agent.io/[email protected]",+ "author": "3d-agent"+ }+]diff --git a/dist-artifact/skills.mp4 b/dist-artifact/skills.mp4new file mode 100644index 000000000..ee2cb2fe5Binary files /dev/null and b/dist-artifact/skills.mp4 differdiff --git a/dist-artifact/studio/index.html b/dist-artifact/studio/index.htmlnew file mode 100644index 000000000..839368efd--- /dev/null+++ b/dist-artifact/studio/index.html@@ -0,0 +1,154 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <meta http-equiv="X-UA-Compatible" content="IE=edge">+ <title>Widget Studio · 3D Agent</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">+ <meta name="description" content="Turn any avatar into an embeddable 3D widget. Five types, brand controls, one-line embed.">+ <meta name="theme-color" content="#0a0a0a">+ <meta name="robots" content="noindex">+ <link rel="shortcut icon" href="/favicon.ico">+ <link rel="preconnect" href="https://fonts.googleapis.com">+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap" rel="stylesheet">+ <link rel="stylesheet" href="/style.css">+ <link rel="stylesheet" href="/studio/studio.css">+</head>+<body class="studio-body">+ <header class="studio-header">+ <h1><a href="/"><span class="wordmark-dot" aria-hidden="true"></span>3D Agent</a><span class="studio-tag">Studio</span></h1>+ <nav>+ <a href="/widgets">Gallery</a>+ <a href="/docs/widgets">Docs</a>+ <a href="/dashboard#widgets">My widgets</a>+ <button class="btn-ghost" id="signout-btn" type="button">Sign out</button>+ </nav>+ </header>++ <main class="studio-layout" id="studio-layout" hidden>+ <section class="studio-col-left" aria-label="Pick avatar and widget type">+ <div class="panel">+ <h2>1. Pick avatar</h2>+ <div class="avatar-list" id="avatar-list" aria-busy="true"></div>+ </div>+ <div class="panel">+ <h2>2. Pick widget type</h2>+ <div class="type-grid" id="type-grid"></div>+ </div>+ </section>++ <section class="studio-col-mid" aria-label="Preview">+ <div class="preview-shell">+ <div class="preview-frame" id="preview-frame">+ <iframe id="preview-iframe" title="Live widget preview" allow="autoplay; xr-spatial-tracking" loading="eager"></iframe>+ </div>+ <div class="preview-meta">+ <span id="preview-status" class="muted">Pick an avatar to preview</span>+ <button class="btn-ghost btn-sm" id="capture-camera-btn" type="button" disabled>Use current view</button>+ </div>+ </div>+ </section>++ <section class="studio-col-right" aria-label="Brand and config">+ <div class="panel">+ <h2>3. Brand</h2>+ <form id="config-form" class="config-form" autocomplete="off" onsubmit="return false">+ <label class="field">+ <span>Name</span>+ <input type="text" name="name" maxlength="120" required placeholder="My turntable widget">+ </label>+ <label class="field">+ <span>Background</span>+ <input type="color" name="background" value="#0a0a0a">+ </label>+ <label class="field">+ <span>Accent</span>+ <input type="color" name="accent" value="#8b5cf6">+ </label>+ <label class="field">+ <span>Caption (optional)</span>+ <input type="text" name="caption" maxlength="280" placeholder="Hello, world.">+ </label>+ <label class="field row">+ <input type="checkbox" name="showControls" checked>+ <span>Show controls</span>+ </label>+ <label class="field row">+ <input type="checkbox" name="autoRotate" checked>+ <span>Auto-rotate</span>+ </label>+ <label class="field">+ <span>Environment</span>+ <select name="envPreset">+ <option value="none">None</option>+ <option value="neutral" selected>Neutral</option>+ <option value="venice-sunset">Venice sunset</option>+ <option value="footprint-court">Footprint court</option>+ </select>+ </label>+ <label class="field row">+ <input type="checkbox" name="is_public" checked>+ <span>Public widget (anyone with the URL can load it)</span>+ </label>++ <div id="type-fields" class="type-fields"></div>+ </form>+ </div>++ <div class="action-row">+ <button type="button" class="btn-ghost" id="save-draft-btn">Save draft</button>+ <button type="button" class="btn-primary" id="generate-btn">Generate embed</button>+ </div>+ <p id="form-error" class="form-error" hidden></p>+ </section>+ </main>++ <div class="auth-blocker" id="auth-blocker">+ <div class="auth-blocker-card">+ <p>Sign in to use the Studio.</p>+ <a class="btn-primary" href="#" id="signin-link">Sign in →</a>+ </div>+ </div>++ <div class="modal-overlay" id="embed-modal" hidden>+ <div class="modal" role="dialog" aria-labelledby="embed-modal-title" aria-modal="true">+ <button type="button" class="modal-close" id="embed-modal-close" aria-label="Close">×</button>+ <h2 id="embed-modal-title">Your widget is live</h2>+ <p class="muted">Share the URL or paste the snippet anywhere.</p>++ <div class="embed-preview">+ <iframe id="embed-preview-iframe" title="Embed preview" allow="autoplay; xr-spatial-tracking"></iframe>+ </div>++ <label class="field">+ <span>Shareable URL</span>+ <div class="copy-row">+ <input type="text" id="embed-share-url" readonly>+ <button type="button" class="btn-ghost btn-sm" data-copy="#embed-share-url">Copy</button>+ </div>+ </label>++ <label class="field">+ <span>iframe snippet</span>+ <div class="copy-row">+ <textarea id="embed-iframe-snippet" rows="3" readonly></textarea>+ <button type="button" class="btn-ghost btn-sm" data-copy="#embed-iframe-snippet">Copy</button>+ </div>+ </label>++ <details>+ <summary>Script-tag embed</summary>+ <div class="copy-row">+ <textarea id="embed-script-snippet" rows="2" readonly></textarea>+ <button type="button" class="btn-ghost btn-sm" data-copy="#embed-script-snippet">Copy</button>+ </div>+ </details>+ </div>+ </div>++ <div class="toast" id="toast" hidden></div>++ <script type="module" src="/studio/studio.js"></script>+</body>+</html>diff --git a/dist-artifact/studio/studio.css b/dist-artifact/studio/studio.cssnew file mode 100644index 000000000..413d8d056--- /dev/null+++ b/dist-artifact/studio/studio.css@@ -0,0 +1,415 @@+/* Widget Studio — dark, three-column. Reuses tokens from /style.css. */++html, body.studio-body {+ height: 100%;+ overflow: hidden;+}++.studio-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: var(--space-sm) var(--space-lg);+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);+ height: 56px;+}+.studio-header h1 {+ margin: 0;+ font-size: var(--text-lg);+ font-weight: 600;+ display: flex;+ align-items: center;+ gap: var(--space-sm);+}+.studio-header h1 a {+ color: inherit;+ text-decoration: none;+ display: inline-flex;+ align-items: center;+ gap: var(--space-xs);+}+.studio-tag {+ font-size: var(--text-sm);+ font-weight: 500;+ padding: 2px 10px;+ border-radius: 999px;+ background: rgba(139, 92, 246, 0.15);+ color: #c4b5fd;+ letter-spacing: 1px;+ text-transform: uppercase;+}+.studio-header nav {+ display: flex;+ align-items: center;+ gap: var(--space-md);+ font-size: var(--text-sm);+}+.studio-header nav a {+ color: rgba(229, 229, 229, 0.7);+ text-decoration: none;+}+.studio-header nav a:hover { color: #fff; }++.studio-layout {+ display: grid;+ grid-template-columns: 280px 1fr 320px;+ gap: var(--space-md);+ padding: var(--space-md);+ height: calc(100vh - 56px);+ overflow: hidden;+}+@media (max-width: 1024px) {+ .studio-layout { grid-template-columns: 1fr; height: auto; overflow: auto; }+ html, body.studio-body { overflow: auto; height: auto; }+}++.studio-col-left, .studio-col-right {+ display: flex;+ flex-direction: column;+ gap: var(--space-md);+ overflow-y: auto;+ min-height: 0;+}++.studio-col-mid {+ display: flex;+ flex-direction: column;+ min-height: 0;+}++.panel {+ background: rgba(255, 255, 255, 0.025);+ border: 1px solid rgba(255, 255, 255, 0.06);+ border-radius: var(--radius-lg);+ padding: var(--space-md);+}+.panel h2 {+ font-family: var(--font-display);+ font-weight: 500;+ font-size: var(--text-base);+ margin: 0 0 var(--space-sm);+ color: rgba(229, 229, 229, 0.85);+ letter-spacing: 0.3px;+}++.avatar-list {+ display: grid;+ grid-template-columns: repeat(2, 1fr);+ gap: var(--space-xs);+ max-height: 320px;+ overflow-y: auto;+}+.avatar-card {+ background: #0a0a0a;+ border: 1px solid rgba(255, 255, 255, 0.08);+ border-radius: var(--radius-md);+ padding: var(--space-xs);+ cursor: pointer;+ display: flex;+ flex-direction: column;+ gap: 4px;+ font-size: var(--text-sm);+ transition: border-color 0.15s, background 0.15s;+ text-align: left;+ color: inherit;+ font-family: inherit;+}+.avatar-card:hover { border-color: rgba(139, 92, 246, 0.5); }+.avatar-card.selected { border-color: var(--accent); background: rgba(139, 92, 246, 0.08); }+.avatar-card:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+.avatar-card .thumb {+ aspect-ratio: 1 / 1;+ background: #050505;+ border-radius: 4px;+ display: grid;+ place-items: center;+ color: #444;+ font-size: 22px;+ overflow: hidden;+}+.avatar-card .thumb img { width: 100%; height: 100%; object-fit: cover; }+.avatar-card .name { font-size: var(--text-sm); color: #ddd; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.avatar-card .meta { font-size: var(--text-xs); color: #777; }+.avatar-list .empty { grid-column: 1 / -1; padding: var(--space-md); text-align: center; color: #777; font-size: var(--text-sm); }+.avatar-list .empty a { color: var(--accent); }++.type-grid {+ display: grid;+ grid-template-columns: repeat(2, 1fr);+ gap: var(--space-xs);+}+.type-card {+ background: #0a0a0a;+ border: 1px solid rgba(255, 255, 255, 0.08);+ border-radius: var(--radius-md);+ padding: var(--space-sm);+ cursor: pointer;+ color: inherit;+ font-family: inherit;+ text-align: left;+ display: flex;+ flex-direction: column;+ gap: 4px;+ transition: border-color 0.15s, background 0.15s;+ position: relative;+}+.type-card:hover { border-color: rgba(139, 92, 246, 0.5); }+.type-card.selected { border-color: var(--accent); background: rgba(139, 92, 246, 0.08); }+.type-card:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+.type-card .icon { font-size: 18px; opacity: 0.8; }+.type-card .label { font-size: var(--text-sm); color: #ddd; }+.type-card .desc { font-size: var(--text-xs); color: #888; line-height: 1.4; }+.type-card .pending {+ font-size: 10px;+ letter-spacing: 1px;+ text-transform: uppercase;+ color: #ffb94d;+ background: rgba(255, 185, 77, 0.12);+ padding: 1px 6px;+ border-radius: 3px;+ width: fit-content;+}++.preview-shell {+ flex: 1;+ display: flex;+ flex-direction: column;+ gap: var(--space-xs);+ background: rgba(255, 255, 255, 0.025);+ border: 1px solid rgba(255, 255, 255, 0.06);+ border-radius: var(--radius-lg);+ padding: var(--space-sm);+ min-height: 400px;+}+.preview-frame {+ flex: 1;+ background: #050505;+ border-radius: var(--radius-md);+ overflow: hidden;+ position: relative;+ min-height: 0;+}+.preview-frame iframe {+ width: 100%;+ height: 100%;+ border: 0;+ display: block;+}+.preview-meta {+ display: flex;+ align-items: center;+ justify-content: space-between;+ font-size: var(--text-sm);+}+.muted { color: rgba(229, 229, 229, 0.55); }++.config-form {+ display: flex;+ flex-direction: column;+ gap: var(--space-sm);+}+.field {+ display: flex;+ flex-direction: column;+ gap: 4px;+ font-size: var(--text-sm);+ color: rgba(229, 229, 229, 0.75);+}+.field.row {+ flex-direction: row;+ align-items: center;+ gap: var(--space-xs);+ cursor: pointer;+}+.field input[type="text"], .field select, .field textarea, .field input[type="color"] {+ background: #0a0a0a;+ border: 1px solid rgba(255, 255, 255, 0.1);+ color: #e5e5e5;+ padding: 6px 10px;+ border-radius: var(--radius-md);+ font-size: var(--text-sm);+ font-family: inherit;+}+.field input[type="color"] { padding: 2px; height: 32px; cursor: pointer; }+.field input:focus, .field select:focus, .field textarea:focus {+ outline: none;+ border-color: var(--accent);+}+.field input[type="checkbox"] { width: 16px; height: 16px; accent-color: var(--accent); }++.type-fields {+ display: flex;+ flex-direction: column;+ gap: var(--space-sm);+ padding-top: var(--space-sm);+ border-top: 1px solid rgba(255, 255, 255, 0.06);+ margin-top: var(--space-xs);+}+.type-fields .pending-banner {+ background: rgba(255, 185, 77, 0.08);+ border: 1px solid rgba(255, 185, 77, 0.2);+ padding: var(--space-sm);+ border-radius: var(--radius-md);+ font-size: var(--text-xs);+ color: #ffd699;+ line-height: 1.5;+}++.action-row {+ display: flex;+ gap: var(--space-xs);+ margin-top: var(--space-sm);+}+.action-row button { flex: 1; }++.btn-primary, .btn-ghost {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: var(--space-xs);+ padding: var(--space-sm) var(--space-md);+ border-radius: var(--radius-md);+ font-family: inherit;+ font-size: var(--text-sm);+ font-weight: 500;+ border: 1px solid transparent;+ cursor: pointer;+ text-decoration: none;+ transition: background 0.15s, border-color 0.15s;+}+.btn-primary { background: var(--accent); color: #fff; }+.btn-primary:hover { background: #7c3aed; }+.btn-ghost {+ background: transparent;+ color: rgba(229, 229, 229, 0.85);+ border-color: rgba(255, 255, 255, 0.15);+}+.btn-ghost:hover { background: rgba(255, 255, 255, 0.05); }+.btn-ghost:disabled { opacity: 0.4; cursor: not-allowed; }+.btn-sm { padding: 4px 10px; font-size: var(--text-xs); }++.btn-primary:focus-visible, .btn-ghost:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+}++.form-error {+ margin: var(--space-xs) 0 0;+ padding: var(--space-xs) var(--space-sm);+ background: rgba(255, 80, 80, 0.08);+ border: 1px solid rgba(255, 80, 80, 0.25);+ border-radius: var(--radius-md);+ color: #ffb3b3;+ font-size: var(--text-xs);+}++.auth-blocker {+ position: fixed;+ inset: 0;+ background: rgba(10, 10, 10, 0.92);+ display: grid;+ place-items: center;+ z-index: 80;+ visibility: hidden;+ opacity: 0;+ transition: opacity 0.15s;+}+.auth-blocker.visible { visibility: visible; opacity: 1; }+.auth-blocker-card {+ background: #14141c;+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: var(--radius-lg);+ padding: var(--space-xl);+ text-align: center;+ display: flex;+ flex-direction: column;+ gap: var(--space-md);+}++.modal-overlay {+ position: fixed;+ inset: 0;+ background: rgba(0, 0, 0, 0.6);+ display: grid;+ place-items: center;+ z-index: 90;+ padding: var(--space-md);+}+.modal-overlay[hidden] { display: none; }+.modal {+ background: #14141c;+ border: 1px solid rgba(255, 255, 255, 0.08);+ border-radius: var(--radius-lg);+ padding: var(--space-lg);+ width: min(560px, 100%);+ max-height: calc(100vh - 32px);+ overflow-y: auto;+ display: flex;+ flex-direction: column;+ gap: var(--space-md);+ position: relative;+}+.modal h2 { margin: 0; font-family: var(--font-display); font-weight: 400; font-size: var(--text-lg); }+.modal .muted { font-size: var(--text-sm); margin: 0; }+.modal-close {+ position: absolute;+ top: 10px;+ right: 14px;+ background: none;+ border: 0;+ color: rgba(229, 229, 229, 0.5);+ font-size: 24px;+ cursor: pointer;+ line-height: 1;+ padding: 4px 8px;+}+.modal-close:hover { color: #fff; }++.embed-preview {+ aspect-ratio: 1 / 1;+ background: #050505;+ border-radius: var(--radius-md);+ overflow: hidden;+}+.embed-preview iframe { width: 100%; height: 100%; border: 0; }++.copy-row {+ display: flex;+ gap: var(--space-xs);+ align-items: stretch;+}+.copy-row input, .copy-row textarea {+ flex: 1;+ background: #0a0a0a;+ border: 1px solid rgba(255, 255, 255, 0.08);+ color: #e5e5e5;+ padding: var(--space-xs) var(--space-sm);+ border-radius: var(--radius-md);+ font-family: var(--font-mono);+ font-size: var(--text-xs);+ resize: vertical;+ min-height: 32px;+}+.copy-row button { flex-shrink: 0; }++.toast {+ position: fixed;+ bottom: 24px;+ left: 50%;+ transform: translateX(-50%);+ background: #14141c;+ border: 1px solid rgba(255, 255, 255, 0.1);+ padding: var(--space-xs) var(--space-md);+ border-radius: 999px;+ font-size: var(--text-sm);+ color: #ddd;+ z-index: 100;+ animation: toast-in 0.18s;+}+.toast[hidden] { display: none; }+@keyframes toast-in { from { opacity: 0; transform: translate(-50%, 8px); } to { opacity: 1; transform: translateX(-50%); } }++@media (prefers-reduced-motion: reduce) {+ .toast { animation: none; }+ .btn-primary, .btn-ghost { transition: none; }+}diff --git a/dist-artifact/studio/studio.js b/dist-artifact/studio/studio.jsnew file mode 100644index 000000000..ce0038258--- /dev/null+++ b/dist-artifact/studio/studio.js@@ -0,0 +1,444 @@+// Widget Studio — three-column UI for creating + editing widgets.+// Native DOM, no framework. Uses /api/widgets and /api/avatars.+//+// Type registry is inlined here (rather than imported from /src/) because+// /public/* is served verbatim by Vercel — the build doesn't transform it.+// Keep this list in sync with src/widget-types.js as new types light up.++const WIDGET_TYPES = {+ 'turntable': { label: 'Turntable Showcase', desc: 'Hero banner — auto-rotate, no UI, just the avatar.', status: 'ready', icon: '◎' },+ 'animation-gallery': { label: 'Animation Gallery', desc: 'Click through every clip on a rigged avatar.', status: 'pending', icon: '▶' },+ 'talking-agent': { label: 'Talking Agent', desc: 'Embodied chat — your agent on your site.', status: 'pending', icon: '◐' },+ 'passport': { label: 'ERC-8004 Passport', desc: 'On-chain identity card for any agent.', status: 'ready', icon: '◊' },+ 'hotspot-tour': { label: 'Hotspot Tour', desc: 'Annotated 3D scene with clickable POIs.', status: 'pending', icon: '⌖' },+};++const BRAND_DEFAULTS = Object.freeze({+ background: '#0a0a0a', accent: '#8b5cf6', caption: '',+ showControls: true, autoRotate: true, envPreset: 'neutral', cameraPosition: null,+});++const TYPE_DEFAULTS = {+ 'turntable': { rotationSpeed: 0.5 },+ 'animation-gallery': { defaultClip: '', loopAll: false, showClipPicker: true },+ 'talking-agent': { greeting: 'Hi! What would you like to know?', brain: 'none', proxyURL: '' },+ 'passport': { chain: 'base-sepolia', agentId: null, wallet: null, showReputation: true, showRecentFeedback: true, layout: 'portrait', rotationSpeed: 0.6 },+ 'hotspot-tour': { hotspots: [] },+};++function defaultConfig(type) {+ return { ...BRAND_DEFAULTS, ...(TYPE_DEFAULTS[type] || {}) };+}++const $ = (sel, root = document) => root.querySelector(sel);++const layoutEl = $('#studio-layout');+const blockerEl = $('#auth-blocker');+const signinLink = $('#signin-link');+const formEl = $('#config-form');+const errEl = $('#form-error');+const previewIfr = $('#preview-iframe');+const previewSt = $('#preview-status');+const captureBtn = $('#capture-camera-btn');+const saveBtn = $('#save-draft-btn');+const generateBtn= $('#generate-btn');+const toastEl = $('#toast');++const state = {+ user: null,+ avatars: [],+ avatarId: null,+ type: 'turntable',+ editingId: null,+ config: defaultConfig('turntable'),+ name: '',+ is_public: true,+ preselectedModel: null,+};++const params = new URLSearchParams(location.search);+const editId = params.get('edit');+const tplId = params.get('template');+const pickType = params.get('type');+const preModel = params.get('model');++if (pickType && WIDGET_TYPES[pickType]) state.type = pickType;+if (preModel) state.preselectedModel = preModel;++(async function boot() {+ signinLink.href = `/login?next=${encodeURIComponent(location.pathname + location.search)}`;+ const me = await fetchMe();+ if (!me) {+ blockerEl.classList.add('visible');+ return;+ }+ state.user = me;+ layoutEl.hidden = false;++ renderTypeGrid();+ renderTypeFields();+ wireForm();+ wireButtons();++ await loadAvatars();++ if (editId) await loadForEdit(editId);+ else if (tplId) await cloneTemplate(tplId);+ else if (state.preselectedModel) selectByModelUrl(state.preselectedModel);++ updatePreview(true);+})();++// ── data ─────────────────────────────────────────────────────────────────────+async function fetchMe() {+ try {+ const res = await fetch('/api/auth/me', { credentials: 'include' });+ if (!res.ok) return null;+ const { user } = await res.json();+ return user || null;+ } catch { return null; }+}++async function loadAvatars() {+ const list = $('#avatar-list');+ try {+ const res = await fetch('/api/avatars?limit=100', { credentials: 'include' });+ if (!res.ok) throw new Error(`avatars: ${res.status}`);+ const { avatars = [] } = await res.json();+ state.avatars = avatars;+ list.removeAttribute('aria-busy');+ renderAvatarList();+ } catch (err) {+ list.removeAttribute('aria-busy');+ list.innerHTML = `<div class="empty">Couldn't load avatars: ${escapeHtml(err.message)}</div>`;+ }+}++async function loadForEdit(id) {+ try {+ const res = await fetch(`/api/widgets/${encodeURIComponent(id)}`, { credentials: 'include' });+ if (!res.ok) return;+ const { widget } = await res.json();+ state.editingId = widget.id;+ state.type = widget.type;+ state.avatarId = widget.avatar_id;+ state.name = widget.name || '';+ state.config = { ...defaultConfig(widget.type), ...(widget.config || {}) };+ state.is_public = widget.is_public;+ hydrateForm();+ renderTypeGrid();+ renderAvatarList();+ renderTypeFields();+ } catch (err) { console.warn('[studio] edit load failed', err); }+}++async function cloneTemplate(id) {+ try {+ const res = await fetch(`/api/widgets/${encodeURIComponent(id)}`);+ if (!res.ok) return;+ const { widget } = await res.json();+ state.type = widget.type;+ state.config = { ...defaultConfig(widget.type), ...(widget.config || {}) };+ state.name = `Copy of ${widget.name}`;+ // avatarId stays unset — user must pick their own+ hydrateForm();+ renderTypeGrid();+ renderTypeFields();+ } catch { /* ignore */ }+}++// ── rendering ────────────────────────────────────────────────────────────────+function renderAvatarList() {+ const list = $('#avatar-list');+ if (!state.avatars.length) {+ list.innerHTML = `<div class="empty">No avatars yet. <a href="/dashboard#upload">Upload one →</a></div>`;+ return;+ }+ list.innerHTML = '';+ for (const a of state.avatars) {+ const card = document.createElement('button');+ card.type = 'button';+ card.className = 'avatar-card' + (a.id === state.avatarId ? ' selected' : '');+ card.dataset.id = a.id;+ card.setAttribute('aria-pressed', String(a.id === state.avatarId));+ const thumb = a.thumbnail_url+ ? `<div class="thumb"><img src="${attr(a.thumbnail_url)}" alt="" loading="lazy"></div>`+ : `<div class="thumb">◎</div>`;+ card.innerHTML = `${thumb}<span class="name">${escapeHtml(a.name || a.slug || a.id)}</span>`;+ card.addEventListener('click', () => selectAvatar(a.id));+ list.appendChild(card);+ }+}++function renderTypeGrid() {+ const grid = $('#type-grid');+ grid.innerHTML = '';+ for (const [key, t] of Object.entries(WIDGET_TYPES)) {+ const card = document.createElement('button');+ card.type = 'button';+ card.className = 'type-card' + (key === state.type ? ' selected' : '');+ card.setAttribute('aria-pressed', String(key === state.type));+ card.innerHTML = `+ <span class="icon" aria-hidden="true">${t.icon}</span>+ <span class="label">${escapeHtml(t.label)}</span>+ <span class="desc">${escapeHtml(t.desc)}</span>+ ${t.status === 'pending' ? '<span class="pending">Coming soon</span>' : ''}+ `;+ card.addEventListener('click', () => selectType(key));+ grid.appendChild(card);+ }+}++function renderTypeFields() {+ const wrap = $('#type-fields');+ wrap.innerHTML = '';+ const t = WIDGET_TYPES[state.type];+ if (t.status === 'pending') {+ const banner = document.createElement('div');+ banner.className = 'pending-banner';+ banner.textContent = `${t.label} runtime ships in a later prompt. You can still save the config; it'll light up when the runtime lands.`;+ wrap.appendChild(banner);+ return;+ }+ if (state.type === 'turntable') {+ wrap.appendChild(numberField('rotationSpeed', 'Rotation speed', state.config.rotationSpeed ?? 0.5, { min: 0, max: 10, step: 0.1 }));+ }+}++function numberField(name, label, value, { min, max, step }) {+ const f = document.createElement('label');+ f.className = 'field';+ f.innerHTML = `<span>${escapeHtml(label)}</span>+ <input type="number" name="${attr(name)}" value="${attr(String(value))}" min="${min}" max="${max}" step="${step}">`;+ f.querySelector('input').addEventListener('input', (e) => {+ const v = parseFloat(e.target.value);+ if (!isNaN(v)) {+ state.config[name] = v;+ schedulePreview();+ }+ });+ return f;+}++// ── interaction ──────────────────────────────────────────────────────────────+function selectAvatar(id) {+ state.avatarId = id;+ renderAvatarList();+ updatePreview(true);+ captureBtn.disabled = false;+}++function selectByModelUrl(url) {+ const 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; }+ });+ if (found) selectAvatar(found.id);+}++function selectType(key) {+ if (state.type === key) return;+ state.type = key;+ state.config = { ...defaultConfig(key), ...pickBrand(state.config) };+ renderTypeGrid();+ renderTypeFields();+ updatePreview(true);+}++function pickBrand(cfg) {+ const out = {};+ for (const k of Object.keys(BRAND_DEFAULTS)) {+ if (cfg[k] !== undefined) out[k] = cfg[k];+ }+ return out;+}++function wireForm() {+ hydrateForm();+ formEl.addEventListener('input', (e) => {+ const t = e.target;+ if (!t.name) return;+ const val = t.type === 'checkbox' ? t.checked : t.value;+ if (t.name === 'name') state.name = val;+ else if (t.name === 'is_public') state.is_public = val;+ else state.config[t.name] = val;+ schedulePreview();+ });+}++function hydrateForm() {+ for (const el of formEl.elements) {+ if (!el.name) continue;+ if (el.name === 'name') el.value = state.name || '';+ else if (el.name === 'is_public') el.checked = !!state.is_public;+ else if (el.type === 'checkbox') el.checked = !!state.config[el.name];+ else if (state.config[el.name] !== undefined) el.value = state.config[el.name];+ }+}++function wireButtons() {+ $('#signout-btn').addEventListener('click', async () => {+ await fetch('/api/auth/logout', { method: 'POST', credentials: 'include' }).catch(() => {});+ try { localStorage.removeItem('3dagent:auth-hint'); } catch { /* ignore */ }+ location.href = '/';+ });++ captureBtn.addEventListener('click', () => {+ try {+ const w = previewIfr.contentWindow;+ const cam = w?.VIEWER?.viewer?.activeCamera;+ if (!cam) return toast('Preview not ready');+ state.config.cameraPosition = [cam.position.x, cam.position.y, cam.position.z];+ toast('Camera captured');+ updatePreview(true);+ } catch { toast('Could not read camera'); }+ });++ saveBtn.addEventListener('click', () => save({ generate: false }));+ generateBtn.addEventListener('click', () => save({ generate: true }));++ $('#embed-modal-close').addEventListener('click', () => {+ $('#embed-modal').hidden = true;+ });++ for (const btn of document.querySelectorAll('[data-copy]')) {+ btn.addEventListener('click', () => copyFromSelector(btn.dataset.copy, btn));+ }+}++// ── preview ──────────────────────────────────────────────────────────────────+let previewTimer = null;+let previewSrcKey = '';++function schedulePreview() {+ clearTimeout(previewTimer);+ previewTimer = setTimeout(() => updatePreview(false), 200);+}++function updatePreview(forceReload) {+ if (!state.avatarId && !state.preselectedModel) {+ previewSt.textContent = 'Pick an avatar to preview';+ return;+ }+ const avatar = state.avatars.find((a) => a.id === state.avatarId);+ const modelUrl = avatar?.model_url || state.preselectedModel;+ if (!modelUrl) {+ previewSt.textContent = 'Avatar has no public URL — make it public/unlisted to preview';+ return;+ }+ previewSt.textContent = 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 src = `/?widget-preview=1#model=${encodeURIComponent(modelUrl)}&kiosk=true${camStr}${presetStr}`;+ const key = src;+ if (forceReload || key !== previewSrcKey) {+ previewSrcKey = key;+ previewIfr.src = src;+ }+ postConfigToPreview();+}++function postConfigToPreview() {+ if (!previewIfr.contentWindow) return;+ try {+ previewIfr.contentWindow.postMessage(+ { type: 'widget:config', config: { ...state.config } },+ location.origin,+ );+ } catch { /* iframe may not be ready yet — full reload covers it */ }+}++// ── save / generate ──────────────────────────────────────────────────────────+async function save({ generate }) {+ errEl.hidden = true;++ if (!state.name?.trim()) return showError('Name is required');+ if (!state.avatarId) return showError('Pick an avatar first');+ if (!WIDGET_TYPES[state.type]) return showError('Pick a widget type');++ const body = {+ type: state.type,+ name: state.name.trim(),+ avatar_id: state.avatarId,+ is_public: state.is_public,+ config: state.config,+ };++ const url = state.editingId ? `/api/widgets/${encodeURIComponent(state.editingId)}` : '/api/widgets';+ const method = state.editingId ? 'PATCH' : 'POST';+ const sendBody = state.editingId ? { name: body.name, avatar_id: body.avatar_id, is_public: body.is_public, config: body.config } : body;++ saveBtn.disabled = true; generateBtn.disabled = true;+ try {+ const res = await fetch(url, {+ method,+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(sendBody),+ });+ if (!res.ok) {+ const data = await res.json().catch(() => ({}));+ throw new Error(data.error_description || `save failed: ${res.status}`);+ }+ const { widget } = await res.json();+ state.editingId = widget.id;+ const newUrl = new URL(location.href);+ newUrl.searchParams.set('edit', widget.id);+ newUrl.searchParams.delete('template');+ newUrl.searchParams.delete('model');+ history.replaceState(null, '', newUrl);++ if (generate) openEmbedModal(widget);+ else toast('Saved');+ } catch (err) {+ showError(err.message);+ } finally {+ saveBtn.disabled = false; generateBtn.disabled = false;+ }+}++function openEmbedModal(widget) {+ const origin = location.origin;+ const shareUrl = `${origin}/w/${widget.id}`;+ const embedUrl = `${origin}/#widget=${widget.id}&kiosk=true`;+ $('#embed-share-url').value = shareUrl;+ $('#embed-iframe-snippet').value = `<iframe src="${embedUrl}" width="600" height="600" style="border:0;border-radius:12px" allow="autoplay; xr-spatial-tracking" loading="lazy"></iframe>`;+ $('#embed-script-snippet').value = `<script async src="${origin}/embed.js" data-widget="${widget.id}"></` + 'script>';+ $('#embed-preview-iframe').src = embedUrl;+ $('#embed-modal').hidden = false;+}++function copyFromSelector(sel, btn) {+ const el = $(sel);+ if (!el) return;+ el.select?.();+ navigator.clipboard.writeText(el.value).then(+ () => { const o = btn.textContent; btn.textContent = 'Copied'; setTimeout(() => btn.textContent = o, 1200); },+ () => toast('Copy failed'),+ );+}++function showError(msg) {+ errEl.textContent = msg;+ errEl.hidden = false;+}++let toastTimer = null;+function toast(msg) {+ toastEl.textContent = msg;+ toastEl.hidden = false;+ clearTimeout(toastTimer);+ toastTimer = setTimeout(() => toastEl.hidden = true, 1800);+}++function escapeHtml(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&':'&','<':'<','>':'>','"':'"',"'":''' }[c]));+}+function attr(s) { return escapeHtml(s); }diff --git a/dist-artifact/validation/REPORT_FORMAT.md b/dist-artifact/validation/REPORT_FORMAT.mdnew file mode 100644index 000000000..0b1c2ce2d--- /dev/null+++ b/dist-artifact/validation/REPORT_FORMAT.md@@ -0,0 +1,94 @@+# Agent Validation Report Format++## Overview++An **agent validation report** is a JSON document that captures the results of testing an agent's GLB model and metadata against a suite of validation rules. Validators (auditors, testing services) generate these reports, sign them on-chain via `recordValidation()`, and end-users browse them to verify trust.++## Schema++```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."+}+```++## 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). |++## 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. |++## 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.++- **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.++- **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.++## Example++See [`example-report.json`](./example-report.json) for a complete, valid example.++## Hashing & On-Chain Storage++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...`).++Validators can verify the hash by fetching the report from IPFS and recomputing the hash locally.++## Trust Model++- Only Ethereum-validated wallets can submit validations.+- The `validator` address is recorded on-chain.+- End-users can view all validations for an agent and choose which validators to trust.+- No endorsement or filtering by the 3D Agent team — raw records from all validators are visible.diff --git a/dist-artifact/validation/boot.js b/dist-artifact/validation/boot.jsnew file mode 100644index 000000000..4db292be6--- /dev/null+++ b/dist-artifact/validation/boot.js@@ -0,0 +1,8 @@+/**+ * Boot script for the validation dashboard.+ * Exported as a module to avoid bundler requirement.+ */++import { ValidationDashboard } from '/src/validation-ui.js';++export { ValidationDashboard };diff --git a/dist-artifact/validation/example-report.json b/dist-artifact/validation/example-report.jsonnew file mode 100644index 000000000..ec44a49d5--- /dev/null+++ b/dist-artifact/validation/example-report.json@@ -0,0 +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."+}diff --git a/dist-artifact/validation/index.html b/dist-artifact/validation/index.htmlnew file mode 100644index 000000000..c50a9b343--- /dev/null+++ b/dist-artifact/validation/index.html@@ -0,0 +1,485 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <title>Validation Records · 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: 16px 24px;+ border-bottom: 1px solid var(--border);+ position: sticky;+ top: 0;+ background: var(--bg);+ z-index: 5;+ }+ .brand {+ font-weight: 600;+ letter-spacing: -0.01em;+ }+ nav a {+ margin-right: 14px;+ color: #aaa;+ font-size: 14px;+ }+ nav a.active {+ color: #fff;+ }+ main {+ padding: 28px;+ max-width: 1200px;+ margin: 0 auto;+ }+ h1 {+ font-size: 22px;+ margin: 0 0 6px;+ letter-spacing: -0.01em;+ }+ .sub {+ color: #888;+ margin: 0 0 22px;+ font-size: 14px;+ }+ .toolbar {+ display: flex;+ gap: 12px;+ margin-bottom: 24px;+ flex-wrap: wrap;+ align-items: center;+ }+ .toolbar input {+ padding: 9px 11px;+ background: #0f0f17;+ border: 1px solid var(--border);+ color: #eee;+ border-radius: 8px;+ font-size: 14px;+ }+ .toolbar input:focus {+ outline: none;+ border-color: var(--accent);+ }+ .form-group {+ margin-bottom: 18px;+ }+ label {+ display: block;+ font-size: 13px;+ font-weight: 500;+ color: #bbb;+ margin-bottom: 6px;+ }+ 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;+ font-family: ui-monospace, SF Mono, Menlo, monospace;+ font-size: 13px;+ }+ .btn {+ padding: 9px 14px;+ 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: #222230;+ color: #ddd;+ }+ .err {+ padding: 12px;+ background: rgba(255, 92, 92, 0.1);+ border: 1px solid rgba(255, 92, 92, 0.3);+ border-radius: 8px;+ color: #ffb3b3;+ margin-bottom: 14px;+ }+ .info {+ padding: 12px;+ background: rgba(106, 92, 255, 0.1);+ border: 1px solid rgba(106, 92, 255, 0.3);+ border-radius: 8px;+ color: #c9bfff;+ margin-bottom: 14px;+ font-size: 13px;+ }+ .records {+ display: flex;+ flex-direction: column;+ gap: 12px;+ }+ .record {+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 10px;+ padding: 16px;+ }+ .record-header {+ display: flex;+ justify-content: space-between;+ align-items: flex-start;+ margin-bottom: 10px;+ }+ .record-title {+ display: flex;+ align-items: center;+ gap: 10px;+ }+ .record-title h3 {+ margin: 0;+ font-size: 14px;+ }+ .badge {+ display: inline-flex;+ align-items: center;+ padding: 3px 9px;+ border-radius: 99px;+ font-size: 11px;+ font-weight: 600;+ text-transform: uppercase;+ letter-spacing: 0.5px;+ }+ .badge.pass {+ background: rgba(76, 175, 80, 0.15);+ color: #76d776;+ }+ .badge.warn {+ background: rgba(255, 193, 7, 0.15);+ color: #ffc107;+ }+ .badge.fail {+ background: rgba(244, 67, 54, 0.15);+ color: #ff5252;+ }+ .record-meta {+ display: flex;+ gap: 16px;+ font-size: 12px;+ color: #888;+ margin: 8px 0;+ }+ .record-meta-item {+ display: flex;+ flex-direction: column;+ gap: 2px;+ }+ .record-meta-label {+ color: #666;+ font-size: 11px;+ text-transform: uppercase;+ letter-spacing: 0.5px;+ }+ .record-meta-value {+ color: #ccc;+ font-family: ui-monospace, SF Mono, Menlo, monospace;+ font-size: 13px;+ word-break: break-all;+ }+ .record-actions {+ display: flex;+ gap: 8px;+ margin-top: 10px;+ }+ .record-actions button,+ .record-actions a {+ padding: 6px 10px;+ font-size: 12px;+ border-radius: 7px;+ border: 1px solid var(--border);+ background: #1a1a24;+ color: #ddd;+ cursor: pointer;+ text-decoration: none;+ }+ .record-actions button:hover,+ .record-actions a:hover {+ background: #22222e;+ }+ .empty {+ text-align: center;+ padding: 60px 20px;+ border: 1px dashed var(--border);+ border-radius: 14px;+ color: #888;+ }+ .modal-overlay {+ position: fixed;+ inset: 0;+ background: rgba(0, 0, 0, 0.6);+ z-index: 60;+ display: grid;+ place-items: center;+ opacity: 0;+ pointer-events: none;+ transition: opacity 0.15s;+ }+ .modal-overlay.open {+ opacity: 1;+ pointer-events: auto;+ }+ .modal {+ background: #0e0e16;+ border: 1px solid var(--border);+ border-radius: 14px;+ padding: 22px;+ width: min(600px, calc(100vw - 32px));+ max-height: calc(100vh - 32px);+ overflow-y: auto;+ }+ .modal h2 {+ margin: 0 0 4px;+ font-size: 17px;+ }+ .modal .sub {+ margin: 0 0 18px;+ }+ .modal-actions {+ display: flex;+ gap: 8px;+ margin-top: 20px;+ justify-content: flex-end;+ }+ .toast {+ position: fixed;+ bottom: 24px;+ left: 50%;+ transform: translateX(-50%);+ background: #1a1a24;+ border: 1px solid var(--border);+ padding: 10px 18px;+ border-radius: 99px;+ font-size: 13px;+ color: #ddd;+ z-index: 70;+ box-shadow: 0 4px 18px rgba(0, 0, 0, 0.4);+ animation: toast-in 0.2s;+ }+ @keyframes toast-in {+ from {+ opacity: 0;+ transform: translate(-50%, 8px);+ }+ to {+ opacity: 1;+ transform: translateX(-50%);+ }+ }+ .toast.err {+ border-color: #cc4040;+ background: #1e1010;+ }+ .section {+ margin-top: 34px;+ }+ .section-title {+ font-size: 15px;+ font-weight: 600;+ margin: 0 0 12px;+ color: #eee;+ }+ .file-input-wrapper {+ position: relative;+ display: inline-block;+ width: 100%;+ }+ .file-input-wrapper input[type='file'] {+ position: absolute;+ opacity: 0;+ width: 0;+ height: 0;+ }+ .file-input-label {+ display: block;+ padding: 18px;+ background: #0f0f17;+ border: 2px dashed var(--border);+ border-radius: 8px;+ text-align: center;+ cursor: pointer;+ transition: border-color 0.15s;+ color: #888;+ }+ .file-input-wrapper input[type='file']:focus + .file-input-label {+ border-color: var(--accent);+ color: #ccc;+ }+ .file-input-wrapper:hover .file-input-label {+ border-color: #444;+ color: #aaa;+ }+ pre {+ background: #0f0f17;+ border: 1px solid var(--border);+ border-radius: 8px;+ padding: 10px 12px;+ overflow: auto;+ font-size: 12px;+ max-height: 200px;+ }+ code {+ font-family: ui-monospace, SF Mono, Menlo, monospace;+ }+ </style>+ </head>+ <body>+ <header>+ <div class="brand"><a href="/">3D Agent</a></div>+ <nav>+ <a href="/">Home</a>+ <a href="/dashboard">Dashboard</a>+ <a href="/explore">Explore</a>+ </nav>+ </header>++ <main id="main">+ <h1>Validation Records</h1>+ <p class="sub">Browse validation reports for this agent to verify trust and integrity.</p>++ <div class="toolbar">+ <input+ type="text"+ id="agent-input"+ placeholder="Agent ID (e.g., 1)"+ style="width: 200px"+ />+ <input+ type="text"+ id="chain-input"+ placeholder="Chain ID (e.g., 84532)"+ style="width: 200px"+ />+ <button class="btn" id="load-btn">Load Records</button>+ <button class="btn sec" id="submit-btn">Submit Validation</button>+ </div>++ <div id="error" class="err" style="display: none"></div>+ <div id="info" class="info" style="display: none"></div>+ <div id="records" class="records"></div>+ <div id="empty" class="empty" style="display: none">No validation records yet.</div>+ </main>++ <!-- Submit Modal -->+ <div class="modal-overlay" id="submit-modal">+ <div class="modal">+ <h2>Submit Validation Report</h2>+ <p class="sub">Upload a JSON validation report signed by your wallet.</p>++ <div class="form-group">+ <label>Report File (JSON)</label>+ <div class="file-input-wrapper">+ <input type="file" id="report-file" accept=".json" />+ <label for="report-file" class="file-input-label">+ 📄 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>++ <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>++ <div id="hash-section" style="display: none" class="form-group">+ <label>Report Hash</label>+ <input+ type="text"+ id="report-hash"+ readonly+ 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))+ </div>+ </div>++ <div class="modal-actions">+ <button class="btn sec" onclick="closeSubmitModal()">Cancel</button>+ <button class="btn" id="submit-report-btn" disabled>Submit on-chain</button>+ </div>+ </div>+ </div>++ <script type="module">+ import { ValidationDashboard } from '/validation/boot.js';++ const dashboard = new ValidationDashboard(document.getElementById('main'), {+ agentInput: document.getElementById('agent-input'),+ chainInput: document.getElementById('chain-input'),+ loadBtn: document.getElementById('load-btn'),+ submitBtn: document.getElementById('submit-btn'),+ recordsContainer: document.getElementById('records'),+ emptyState: document.getElementById('empty'),+ errorEl: document.getElementById('error'),+ infoEl: document.getElementById('info'),+ submitModal: document.getElementById('submit-modal'),+ reportFile: document.getElementById('report-file'),+ fileStatus: document.getElementById('file-status'),+ previewSection: document.getElementById('preview-section'),+ previewJson: document.getElementById('preview-json'),+ previewError: document.getElementById('preview-error'),+ hashSection: document.getElementById('hash-section'),+ reportHash: document.getElementById('report-hash'),+ submitReportBtn: document.getElementById('submit-report-btn'),+ });++ window.closeSubmitModal = () => dashboard.closeModal();+ window.submitModal = () => dashboard.submitReport();+ </script>+ </body>+</html>diff --git a/dist-artifact/wallet-login.js b/dist-artifact/wallet-login.jsnew file mode 100644index 000000000..ba7fdb5cf--- /dev/null+++ b/dist-artifact/wallet-login.js@@ -0,0 +1,149 @@+// Client-side wallet authentication.+// Used by /login and /register pages. Supports two paths:+// 1. Privy — email/social/wallet login with auto-created embedded wallets+// 2. Raw MetaMask/SIWE — direct Sign-In with Ethereum for existing wallets+//+// Loaded as a module from login.html — imports from CDN so it works outside Vite.++import { BrowserProvider } from 'https://esm.sh/[email protected]';++const params = new URLSearchParams(location.search);+const next = params.get('next') || '/dashboard/';++// Privy app id comes from /api/config (backed by PRIVY_APP_ID env var). The+// meta tag is a local-dev fallback — prod should rely on the fetched config.+let PRIVY_APP_ID = document.querySelector('meta[name="privy-app-id"]')?.content || '';+const configReady = fetch('/api/config', { credentials: 'omit' })+ .then((r) => r.ok ? r.json() : null)+ .then((cfg) => { if (cfg?.privyAppId) PRIVY_APP_ID = cfg.privyAppId; })+ .catch(() => {});++// ── UI helpers ──────────────────────────────────────────────────────────────++function ui() {+ const walletBtn = document.getElementById('wallet');+ const privyBtn = document.getElementById('privy');+ const err = document.getElementById('err');+ return {+ walletBtn, privyBtn, err,+ setErr: (m) => { if (err) { err.textContent = m; err.style.display = 'block'; } },+ clearErr: () => { if (err) { err.style.display = 'none'; } },+ };+}++// ── Privy login (primary path) ─────────────────────────────────────────────+// Privy handles email + social + wallet login. On success it provides an+// EIP-1193 provider (embedded or external) which we SIWE-verify against our+// backend exactly like a raw MetaMask login.++async function signInWithPrivy() {+ const { privyBtn, setErr, clearErr } = ui();+ await configReady;+ if (!PRIVY_APP_ID) { setErr('Privy not configured.'); return; }++ clearErr();+ if (privyBtn) { privyBtn.disabled = true; privyBtn.textContent = 'Loading Privy…'; }++ try {+ const mod = await import('https://esm.sh/@privy-io/js-sdk-core@latest');+ const PrivyClient = mod.PrivyClient || mod.default;+ const privy = new PrivyClient({ appId: PRIVY_APP_ID });++ if (privyBtn) privyBtn.textContent = 'Opening login…';+ await privy.login({ loginMethods: ['wallet', 'email', 'google'] });++ if (privyBtn) privyBtn.textContent = 'Connecting wallet…';+ const eip1193 = await privy.getEthereumProvider();+ if (!eip1193) throw new Error('No wallet provider returned by Privy.');++ const provider = new BrowserProvider(eip1193);+ await completeSignIn(provider, privyBtn);+ } catch (e) {+ const msg = e?.message || String(e);+ setErr(msg === 'user rejected action' || msg.includes('cancelled') ? 'Login cancelled.' : msg);+ if (privyBtn) { privyBtn.disabled = false; privyBtn.textContent = 'Sign in with Privy'; }+ }+}++// ── Raw MetaMask / SIWE (fallback path) ────────────────────────────────────++async function signInWithWallet() {+ const { walletBtn, setErr, clearErr } = ui();++ if (!window.ethereum) {+ setErr('No wallet detected. Install MetaMask or another Ethereum wallet.');+ return;+ }++ clearErr();+ if (walletBtn) { walletBtn.disabled = true; walletBtn.textContent = 'Connecting…'; }+ const original = walletBtn?.innerHTML;++ try {+ const provider = new BrowserProvider(window.ethereum);+ await provider.send('eth_requestAccounts', []);+ await completeSignIn(provider, walletBtn);+ } catch (e) {+ const msg = e?.info?.error?.message || e?.message || String(e);+ setErr(msg === 'user rejected action' ? 'Signature cancelled.' : msg);+ if (walletBtn) { walletBtn.disabled = false; walletBtn.innerHTML = original; }+ }+}++// ── Shared SIWE flow ───────────────────────────────────────────────────────+// Both Privy and raw wallet paths use this to complete the login.++async function completeSignIn(provider, btn) {+ const signer = await provider.getSigner();+ const address = await signer.getAddress();+ const network = await provider.getNetwork();+ const chainId = Number(network.chainId);++ if (btn) btn.textContent = 'Requesting nonce…';+ const nonceRes = await fetch('/api/auth/siwe/nonce', { credentials: 'include' });+ if (!nonceRes.ok) throw new Error('Failed to get nonce');+ const { nonce, csrf } = await nonceRes.json();++ const domain = location.host;+ const uri = location.origin;+ const issuedAt = new Date().toISOString();+ const expirationTime = new Date(Date.now() + 5 * 60 * 1000).toISOString();++ const message = [+ `${domain} wants you to sign in with your Ethereum account:`,+ address,+ '',+ 'Sign in to 3D Agent. This does not cost anything and proves wallet ownership.',+ '',+ `URI: ${uri}`,+ 'Version: 1',+ `Chain ID: ${chainId}`,+ `Nonce: ${nonce}`,+ `Issued At: ${issuedAt}`,+ `Expiration Time: ${expirationTime}`,+ ].join('\n');++ if (btn) btn.textContent = 'Check your wallet…';+ const signature = await signer.signMessage(message);++ if (btn) btn.textContent = 'Verifying…';+ const verifyRes = await fetch('/api/auth/siwe/verify', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json', 'x-csrf-token': csrf },+ body: JSON.stringify({ message, signature }),+ });+ const data = await verifyRes.json();+ if (!verifyRes.ok) throw new Error(data.error_description || 'Verification failed');++ try { localStorage.setItem('3dagent:auth-hint', JSON.stringify({ authed: true, ts: Date.now() })); } catch { /* ignore */ }+ location.href = next;+}++// ── Bind buttons ────────────────────────────────────────────────────────────++const walletBtn = document.getElementById('wallet');+const privyBtn = document.getElementById('privy');++if (walletBtn) walletBtn.addEventListener('click', signInWithWallet);+if (privyBtn) privyBtn.addEventListener('click', signInWithPrivy);diff --git a/dist-artifact/widgets-gallery/gallery.css b/dist-artifact/widgets-gallery/gallery.cssnew file mode 100644index 000000000..de85b4c84--- /dev/null+++ b/dist-artifact/widgets-gallery/gallery.css@@ -0,0 +1,285 @@+/* Widget gallery — matches root style.css tokens. No new design system. */++html, body.gallery-body {+ overflow: auto;+ height: auto;+ min-height: 100vh;+}++.gallery-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: var(--space-md) var(--space-lg);+ border-bottom: 1px solid rgba(255,255,255,0.06);+ background: rgba(0,0,0,0.5);+ backdrop-filter: blur(8px);+ position: sticky;+ top: 0;+ z-index: 10;+}+.gallery-header h1 {+ margin: 0;+ font-size: var(--text-lg);+ font-weight: 600;+}+.gallery-header h1 a {+ color: inherit;+ text-decoration: none;+ display: inline-flex;+ align-items: center;+ gap: var(--space-xs);+}+.gallery-header .features-nav {+ display: flex;+ gap: var(--space-md);+ align-items: center;+ font-size: var(--text-sm);+}+.gallery-header .features-nav a {+ color: rgba(229,229,229,0.65);+ text-decoration: none;+ padding: var(--space-xs) var(--space-sm);+ border-radius: var(--radius-md);+ transition: color 0.15s, background 0.15s;+}+.gallery-header .features-nav a:hover,+.gallery-header .features-nav a.active {+ color: #fff;+ background: rgba(255,255,255,0.06);+}++.gallery-main {+ max-width: 1080px;+ margin: 0 auto;+ padding: var(--space-2xl) var(--space-lg);+ display: flex;+ flex-direction: column;+ gap: var(--space-2xl);+}++.gallery-hero {+ text-align: center;+ display: flex;+ flex-direction: column;+ gap: var(--space-md);+ align-items: center;+}+.gallery-hero .eyebrow {+ margin: 0;+ font-size: var(--text-sm);+ letter-spacing: 4px;+ text-transform: uppercase;+ color: var(--accent);+ font-weight: 600;+}+.gallery-hero h2 {+ margin: 0;+ font-family: var(--font-display);+ font-size: var(--text-2xl);+ font-weight: 300;+ letter-spacing: -1px;+ line-height: 1.1;+}+.gallery-hero .lede {+ max-width: 60ch;+ margin: 0;+ font-size: var(--text-lg);+ color: rgba(229,229,229,0.7);+ line-height: var(--leading-normal);+}+.cta-row {+ display: flex;+ gap: var(--space-sm);+ flex-wrap: wrap;+ justify-content: center;+ margin-top: var(--space-sm);+}++.btn {+ display: inline-flex;+ align-items: center;+ gap: var(--space-xs);+ padding: var(--space-sm) var(--space-lg);+ border-radius: 999px;+ font-family: var(--font-body);+ font-size: var(--text-base);+ font-weight: 500;+ text-decoration: none;+ border: 1px solid transparent;+ cursor: pointer;+ transition: transform 0.15s, background 0.15s, border-color 0.15s;+}+.btn:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+}+.btn-primary {+ background: var(--accent);+ color: #fff;+}+.btn-primary:hover { transform: translateY(-1px); background: #7c3aed; }+.btn-ghost {+ background: transparent;+ color: rgba(229,229,229,0.85);+ border-color: rgba(255,255,255,0.18);+}+.btn-ghost:hover { background: rgba(255,255,255,0.06); }++.gallery-grid {+ display: flex;+ flex-direction: column;+ gap: var(--space-2xl);+}+.gallery-grid .loading {+ color: rgba(229,229,229,0.55);+ text-align: center;+}++.showcase {+ display: grid;+ grid-template-columns: minmax(0, 1fr) minmax(280px, 380px);+ gap: var(--space-xl);+ align-items: start;+ padding: var(--space-xl);+ background: rgba(255,255,255,0.025);+ border: 1px solid rgba(255,255,255,0.06);+ border-radius: var(--radius-lg);+}+@media (max-width: 820px) {+ .showcase { grid-template-columns: 1fr; }+}++.showcase-frame {+ position: relative;+ border-radius: var(--radius-md);+ overflow: hidden;+ background: #050505;+ aspect-ratio: 1 / 1;+}+.showcase-frame iframe {+ position: absolute;+ inset: 0;+ width: 100%;+ height: 100%;+ border: 0;+ display: block;+}++.showcase-meta {+ display: flex;+ flex-direction: column;+ gap: var(--space-md);+}+.showcase-meta .type-tag {+ display: inline-block;+ font-size: var(--text-xs);+ letter-spacing: 3px;+ text-transform: uppercase;+ color: var(--accent);+ font-weight: 600;+}+.showcase-meta h3 {+ margin: 0;+ font-family: var(--font-display);+ font-size: var(--text-xl);+ font-weight: 400;+ letter-spacing: -0.5px;+}+.showcase-meta p {+ margin: 0;+ color: rgba(229,229,229,0.7);+ line-height: var(--leading-normal);+}++.snippet {+ position: relative;+ background: #0a0a0a;+ border: 1px solid rgba(255,255,255,0.08);+ border-radius: var(--radius-md);+ padding: var(--space-sm);+ font-family: var(--font-mono);+ font-size: var(--text-sm);+ color: rgba(229,229,229,0.85);+ white-space: pre-wrap;+ word-break: break-all;+ overflow-x: auto;+}+.snippet code { display: block; }+.snippet-row {+ display: flex;+ gap: var(--space-xs);+ flex-wrap: wrap;+ margin-top: var(--space-sm);+}+.snippet-row button,+.snippet-row a {+ flex: 1 1 auto;+ min-width: 120px;+ padding: var(--space-xs) var(--space-sm);+ font-size: var(--text-sm);+ background: rgba(255,255,255,0.05);+ border: 1px solid rgba(255,255,255,0.1);+ color: #e5e5e5;+ border-radius: var(--radius-md);+ cursor: pointer;+ text-align: center;+ text-decoration: none;+ font-family: var(--font-body);+ transition: background 0.15s;+}+.snippet-row button:hover,+.snippet-row a:hover { background: rgba(255,255,255,0.1); }+.snippet-row button:focus-visible,+.snippet-row a:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+}+.snippet-row .copied { background: var(--accent-soft); border-color: var(--accent); }++.error-state {+ padding: var(--space-md);+ background: rgba(255,80,80,0.06);+ border: 1px solid rgba(255,80,80,0.2);+ border-radius: var(--radius-md);+ color: rgba(255,200,200,0.9);+ font-size: var(--text-sm);+}++.gallery-cta {+ text-align: center;+ padding: var(--space-2xl) var(--space-lg);+ background: rgba(139,92,246,0.06);+ border: 1px solid rgba(139,92,246,0.15);+ border-radius: var(--radius-lg);+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: var(--space-md);+}+.gallery-cta h3 {+ margin: 0;+ font-family: var(--font-display);+ font-size: var(--text-xl);+ font-weight: 400;+}+.gallery-cta p { margin: 0; color: rgba(229,229,229,0.7); }++.gallery-footer {+ padding: var(--space-lg);+ text-align: center;+ color: rgba(229,229,229,0.5);+ font-size: var(--text-sm);+ border-top: 1px solid rgba(255,255,255,0.06);+}+.gallery-footer a {+ color: rgba(229,229,229,0.7);+ text-decoration: none;+ margin: 0 var(--space-xs);+}+.gallery-footer a:hover { color: #fff; }++@media (prefers-reduced-motion: reduce) {+ .btn, .snippet-row button, .snippet-row a { transition: none; }+ .btn-primary:hover { transform: none; }+}diff --git a/dist-artifact/widgets-gallery/gallery.js b/dist-artifact/widgets-gallery/gallery.jsnew file mode 100644index 000000000..8b376d46d--- /dev/null+++ b/dist-artifact/widgets-gallery/gallery.js@@ -0,0 +1,133 @@+// Widget gallery — native DOM, no framework. Renders showcase cards from+// /widgets-gallery/showcase.json with a real iframe and a copy-paste snippet+// per widget. If a showcase id isn't a real widget yet, the iframe shows the+// /w/<id> fallback page; the copy snippet still works once the id is filled in.++const GRID_EL = document.getElementById('gallery-grid');++const ORIGIN = location.origin;++(async function init() {+ let showcase;+ try {+ const res = await fetch('/widgets-gallery/showcase.json', { cache: 'no-cache' });+ if (!res.ok) throw new Error(`showcase.json ${res.status}`);+ showcase = await res.json();+ } catch (err) {+ GRID_EL.innerHTML = '';+ GRID_EL.appendChild(errorEl('Could not load showcase config.', err.message));+ GRID_EL.removeAttribute('aria-busy');+ return;+ }++ GRID_EL.innerHTML = '';+ for (const w of showcase.widgets || []) {+ GRID_EL.appendChild(renderShowcase(w));+ }+ GRID_EL.removeAttribute('aria-busy');+})();++function renderShowcase(w) {+ const root = document.createElement('article');+ root.className = 'showcase';+ root.setAttribute('aria-labelledby', `sc-${w.id}-title`);++ const widgetUrl = `${ORIGIN}/#widget=${encodeURIComponent(w.id)}&kiosk=true`;+ const pageUrl = `${ORIGIN}/w/${encodeURIComponent(w.id)}`;+ const snippet = `<iframe src="${widgetUrl}" width="${w.width}" height="${w.height}" style="border:0;border-radius:12px;max-width:100%" allow="autoplay; xr-spatial-tracking; clipboard-write" loading="lazy"></iframe>`;++ const frame = document.createElement('div');+ frame.className = 'showcase-frame';+ frame.style.aspectRatio = `${w.width} / ${w.height}`;++ const iframe = document.createElement('iframe');+ iframe.src = widgetUrl;+ iframe.title = `${w.label} demo`;+ iframe.loading = 'lazy';+ iframe.allow = 'autoplay; xr-spatial-tracking; clipboard-write';+ frame.appendChild(iframe);++ const meta = document.createElement('div');+ meta.className = 'showcase-meta';++ const tag = document.createElement('span');+ tag.className = 'type-tag';+ tag.textContent = w.type;+ meta.appendChild(tag);++ const h = document.createElement('h3');+ h.id = `sc-${w.id}-title`;+ h.textContent = w.label;+ meta.appendChild(h);++ const desc = document.createElement('p');+ desc.textContent = w.tagline;+ meta.appendChild(desc);++ const code = document.createElement('pre');+ code.className = 'snippet';+ code.setAttribute('aria-label', 'Embed snippet');+ const codeInner = document.createElement('code');+ codeInner.textContent = snippet;+ code.appendChild(codeInner);+ meta.appendChild(code);++ const row = document.createElement('div');+ row.className = 'snippet-row';++ const copyBtn = document.createElement('button');+ copyBtn.type = 'button';+ copyBtn.textContent = 'Copy iframe';+ copyBtn.setAttribute('aria-label', `Copy embed snippet for ${w.label}`);+ copyBtn.addEventListener('click', () => copy(snippet, copyBtn));+ row.appendChild(copyBtn);++ const copyUrlBtn = document.createElement('button');+ copyUrlBtn.type = 'button';+ copyUrlBtn.textContent = 'Copy URL';+ copyUrlBtn.setAttribute('aria-label', `Copy shareable URL for ${w.label}`);+ copyUrlBtn.addEventListener('click', () => copy(pageUrl, copyUrlBtn));+ row.appendChild(copyUrlBtn);++ const studio = document.createElement('a');+ studio.href = `/studio?template=${encodeURIComponent(w.id)}`;+ studio.textContent = 'Open in Studio';+ studio.setAttribute('aria-label', `Clone ${w.label} into the Studio`);+ row.appendChild(studio);++ meta.appendChild(row);++ root.appendChild(frame);+ root.appendChild(meta);+ return root;+}++async function copy(text, btn) {+ try {+ await navigator.clipboard.writeText(text);+ } catch {+ // Fallback for old browsers+ const ta = document.createElement('textarea');+ ta.value = text;+ ta.style.position = 'fixed';+ ta.style.opacity = '0';+ document.body.appendChild(ta);+ ta.select();+ try { document.execCommand('copy'); } catch {}+ ta.remove();+ }+ const orig = btn.textContent;+ btn.classList.add('copied');+ btn.textContent = 'Copied!';+ setTimeout(() => {+ btn.textContent = orig;+ btn.classList.remove('copied');+ }, 1400);+}++function errorEl(msg, detail) {+ const e = document.createElement('div');+ e.className = 'error-state';+ e.textContent = detail ? `${msg} (${detail})` : msg;+ return e;+}diff --git a/dist-artifact/widgets-gallery/index.html b/dist-artifact/widgets-gallery/index.htmlnew file mode 100644index 000000000..9e494d317--- /dev/null+++ b/dist-artifact/widgets-gallery/index.html@@ -0,0 +1,65 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <meta http-equiv="X-UA-Compatible" content="IE=edge">+ <title>Widgets — 3D Agent</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">+ <meta name="description" content="Embeddable 3D, no code. Drop a widget into any site, blog, or Notion doc.">+ <meta name="theme-color" content="#0a0a0a">++ <meta property="og:type" content="website">+ <meta property="og:site_name" content="3D Agent">+ <meta property="og:title" content="3D Agent — Widgets">+ <meta property="og:description" content="Embeddable 3D, no code. Drop a widget into any site, blog, or Notion doc.">+ <meta property="og:url" content="https://3dagent.vercel.app/widgets">++ <link rel="canonical" href="https://3dagent.vercel.app/widgets">+ <link rel="shortcut icon" href="/favicon.ico">+ <link rel="preconnect" href="https://fonts.googleapis.com">+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap" rel="stylesheet">+ <link rel="stylesheet" href="/style.css">+ <link rel="stylesheet" href="/widgets-gallery/gallery.css">+</head>+<body class="gallery-body">+ <header class="gallery-header">+ <h1><a href="/"><span class="wordmark-dot" aria-hidden="true"></span>3D Agent</a></h1>+ <nav class="features-nav">+ <a href="/">Viewer</a>+ <a href="/features">Features</a>+ <a href="/widgets" class="active" aria-current="page">Widgets</a>+ <a href="/docs/widgets">Docs</a>+ <a href="/dashboard" class="nav-dashboard">Dashboard</a>+ </nav>+ </header>++ <main class="gallery-main" id="gallery-main">+ <section class="gallery-hero">+ <p class="eyebrow">Widget Studio</p>+ <h2>Embeddable 3D, no code.</h2>+ <p class="lede">Drop a 3D agent — turntable, talking head, on-chain passport, or guided tour — into any site, blog, or Notion doc with one line of HTML.</p>+ <div class="cta-row">+ <a class="btn btn-primary" href="/studio">Create yours — it's free</a>+ <a class="btn btn-ghost" href="/docs/widgets">Read the docs</a>+ </div>+ </section>++ <section class="gallery-grid" id="gallery-grid" aria-busy="true">+ <p class="loading">Loading showcase widgets…</p>+ </section>++ <section class="gallery-cta">+ <h3>Make your own.</h3>+ <p>Pick an avatar, pick a widget type, paste the snippet. Free for personal use.</p>+ <a class="btn btn-primary" href="/studio">Open the Studio</a>+ </section>+ </main>++ <footer class="gallery-footer">+ <p>3D Agent · <a href="/">Viewer</a> · <a href="/widgets">Widgets</a> · <a href="/docs/widgets">Docs</a> · <a href="https://github.com/nirholas/3D">GitHub</a></p>+ </footer>++ <script type="module" src="/widgets-gallery/gallery.js"></script>+</body>+</html>diff --git a/dist-artifact/widgets-gallery/showcase.json b/dist-artifact/widgets-gallery/showcase.jsonnew file mode 100644index 000000000..d99143ace--- /dev/null+++ b/dist-artifact/widgets-gallery/showcase.json@@ -0,0 +1,45 @@+{+ "_comment": "Each entry is a real, working widget on a demo account. Replace the placeholder ids with actual wdgt_ ids once Prompts 01-05 ship and you've created showcase widgets in the studio.",+ "widgets": [+ {+ "type": "turntable",+ "label": "Turntable Showcase",+ "tagline": "Hero banner for sites — auto-rotate, no UI.",+ "id": "wdgt_demo_turntab",+ "width": 600,+ "height": 600+ },+ {+ "type": "animation-gallery",+ "label": "Animation Gallery",+ "tagline": "Click through every clip on a rigged avatar.",+ "id": "wdgt_demo_animgal",+ "width": 720,+ "height": 720+ },+ {+ "type": "talking-agent",+ "label": "Talking Agent",+ "tagline": "Embodied chat — your agent, your site, your tone.",+ "id": "wdgt_demo_talking",+ "width": 420,+ "height": 600+ },+ {+ "type": "passport",+ "label": "ERC-8004 Passport",+ "tagline": "On-chain identity card for any agent.",+ "id": "wdgt_demo_passprt",+ "width": 480,+ "height": 560+ },+ {+ "type": "hotspot-tour",+ "label": "Hotspot Tour",+ "tagline": "Explorable 3D scenes with annotated points of interest.",+ "id": "wdgt_demo_hotspot",+ "width": 800,+ "height": 600+ }+ ]+}diff --git a/docs/CZ_DEMO_FAILURE_MODES.md b/docs/CZ_DEMO_FAILURE_MODES.mdnew file mode 100644index 000000000..bad8a3b83--- /dev/null+++ b/docs/CZ_DEMO_FAILURE_MODES.md@@ -0,0 +1,141 @@+# CZ Demo Failure Modes++A comprehensive table of conceivable failures during the live CZ demo, their symptoms, recovery paths, and time costs. Use this to rehearse worst-case scenarios before the event.++---++## 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 |++---++## 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.+- **#5 Out of gas:** Fund CZ's wallet with 0.1 ETH the day before. Verify with `eth_getBalance`.+- **#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.+- **#4 RPC slow:** Practice narrating the feature without the UI (talk about wallets, transactions, on-chain identity).+- **#8 Block explorer down:** Skip the Basescan screenshot; show the code instead.+- **#10 LobeHub blank:** Focus the demo on the avatar and claiming, not the plugin.+- **#11 Wifi drops:** Hotspot ready; offline fallback preloaded.+- **#12 GPU throttle:** Laptop at idle before demo; close Chrome tabs.+- **#13 Wrong chain:** One MetaMask click to fix.+- **#15 Browser crash:** Reload tab from history.+- **#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.+- **#9 Confetti fails:** Still a successful claim; visual polish, not essential.+- **#14 IPFS slow:** Metadata loads eventually; doesn't block core flow.+- **#18 Token expired:** Rare. Quick reload fixes.+- **#20 CSS broken:** Reload or incognito; not architectural.++---++## Pre-Demo Verification Checklist++Run this 1 hour before the demo to catch failures **before** the event:++```bash+# 1. Staging is up+curl -I https://staging-url/cz | grep "200 OK" || echo "FAIL: staging down"++# 2. API is responding+curl -s https://staging-url/api/cz/identity | jq .agentId || echo "FAIL: API 404 or error"++# 3. Avatar file exists and is reasonable size+curl -I https://staging-url/avatars/cz.glb | grep "Content-Length" | awk '{print $2}' | \+ awk '{if ($1 > 1000000 && $1 < 20000000) print "OK"; else print "FAIL: size out of range"}' || echo "FAIL: size check"++# 4. CZ wallet has enough gas+# (requires ethers.js or web3.py; manual check in MetaMask is fine)+echo "Check MetaMask balance: 0x<CZ_ADDRESS> on Base Sepolia > 0.05 ETH"++# 5. Offline fallback loads (no network calls)+echo "Open http://localhost:3000/cz/offline/index.html with network throttled to offline"++# 6. Browser is fresh+echo "Close all browser windows; open incognito/private window; install MetaMask"++# 7. Check console for errors+echo "DevTools on /cz: Ctrl+Shift+J, look for red errors"+```++---++## Incident Log Template++If something fails during the actual demo, fill this out immediately after (for post-mortem):++```markdown+**Failure:** #[X] — [Name]+**Time in demo:** [HH:MM:SS or "step X"]+**Exact symptom:** [What the operator observed]+**Recovery used:** [Which fallback or workaround]+**Audience reaction:** [Noticed? Lost interest? Recovered?]+**Root cause (investigation):** [After-the-fact diagnosis]+**Action item:** [Fix for next time]+```++Example:+```markdown+**Failure:** #4 — RPC Congestion+**Time in demo:** Step 5 (claim confirmation)+**Exact symptom:** Modal hung on "Waiting for confirmation…" for 2m 30s+**Recovery used:** Switched to /cz?rehearsal=1 after 90s narration+**Audience reaction:** Didn't seem to notice; thought it was intentional+**Root cause:** Base Sepolia RPC had 12-block backlog at demo time+**Action item:** Use secondary RPC fallback endpoint for next event+```++---++## Rehearsal Script++**Run this the day before the event** to catch + fix failures before they're live:++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)+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.mdnew file mode 100644index 000000000..8c58d30e1--- /dev/null+++ b/docs/CZ_DEMO_RUNBOOK.md@@ -0,0 +1,271 @@+# CZ Demo Runbook++Live event runbook for the CZ agent demo. This is the operator's edge — when things break, refer here.++---++## Pre-Flight Checklist (T-24 hours)++- [ ] All `prompts/complete/*` changes merged to main and deployed to staging+- [ ] Staging URL loads `/cz` with avatar rendering and camera controls functional+- [ ] Base Sepolia testnet: CZ's wallet seeded with > 0.05 ETH for gas (testnet faucets if needed)+- [ ] Basescan or Block Explorer confirms agent registration state (onchain or pre-onchain)+- [ ] `GET /api/cz/identity` returns valid agent metadata JSON (or 404 if pre-onchain)+- [ ] MetaMask / hardware wallet ready with CZ's seed phrase or connected device+- [ ] Fresh browser profile created (zero extensions, zero stored cookies)+- [ ] 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)++---++## Pre-Flight Checklist (T-1 hour)++- [ ] Fresh browser window opened (not a tab in existing profile)+- [ ] MetaMask imported from seed or hardware wallet connected+- [ ] DNS cached: run `nslookup 3dagent.vercel.app` twice, confirm same IP both times+- [ ] 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+- [ ] 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++---++## 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/`+- Let avatar load and start idle animation+- Pause on the tagline / description+- **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."++### Step 3: Claim Flow Begins (10 seconds)+**Speaker:** "CZ, can you claim this? Let's see."++- Back to CZ tab+- Click "Claim" button+- MetaMask popup appears (if not blocked by browser)+- **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)+- Return to browser window+- Modal shows "Waiting for confirmation..."+- **Expected screen:** Spinning modal with confirmation text++### Step 5: Confirmation (30 seconds)+**Speaker:** "And it's confirmed. Confetti."++- Confetti animation plays+- Modal updates: "Claim successful"+- Transaction hash displayed (or "pre-claimed" if rehearsal mode)+- Footer updates with new owner address+- **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)+- Agent appears in sidebar (same agentId)+- Type in chat: "Hello"+- Avatar animates (wave or smile)+- **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+- Take a screenshot if time permits+- **Expected screen:** Avatar with visible emotion feedback++### Step 9: Close (10 seconds)+**Speaker:** "That's CZ. Questions?"++- Close tabs+- Return to home or pause for Q&A+- **Expected screen:** Ready for audience questions++**Total estimated time: 4 minutes 45 seconds**++---++## 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`+4. If slow: Wait 30 seconds; if still loading, switch to offline fallback (see below)+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."+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."+4. Optionally open our hosted agent chat in a separate window as a fallback++---++## Recovery & Graceful Exit++If the demo hits a hard blocker (venue wifi down, RPC completely unavailable, laptop crash), **here's the one-slide recovery:**++1. Show `/cz/offline/` on a phone hotspot+2. Say: "Even without live internet, the agent is ready. Here's what you just saw, fully cached and running locally."+3. Walk through the avatar and claim flow using the offline version+4. Open Q&A: "Any questions about how agents work on-chain?"++**Duration:** 2 minutes. Gets you out gracefully without losing credibility.++---++## Post-Demo Checklist++**Immediately after demo (while audience is still present):**++- [ ] Capture transaction hash from MetaMask history or Basescan (screenshot / copy to notes)+- [ ] Note the `agentId` from footer or `/api/cz/identity`+- [ ] Ask audience for immediate Q&A and feedback (record notes on pain points, questions, enthusiasm level)+- [ ] If claim failed, note the exact error message for root-cause investigation++**Within 24 hours (for post-mortem):**++- [ ] File any bugs observed: avatar performance, modal UX, RPC failures, etc.+- [ ] Upload transaction screenshot and agentId to shared incident file+- [ ] Review Vercel logs for API errors or rate-limit spikes during demo window+- [ ] Check Basescan for gas price spikes or network congestion during demo time+- [ ] Update this runbook with any gaps or timing adjustments needed for the next run++---++## Demo Environment Setup (for the operator)++### Local / Staging Setup+```bash+# Ensure staging is deployed and healthy+npm run deploy++# Check that cz endpoint is live+curl -s https://staging-url/cz | head -c 200++# Verify API is responding+curl -s https://staging-url/api/cz/identity | jq .agentId++# Pre-warm browser caches+# (open /cz in browser, let it idle for 30s)+```++### 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)++### Network Backup+```bash+# Save these endpoints locally for manual testing+PRIMARY_RPC="https://sepolia.base.org/"+SECONDARY_RPC="https://base-sepolia.g.alchemy.com/v2/YOUR_KEY"++# Test manually if live demo fails+curl -s -X POST $PRIMARY_RPC \+ -H "Content-Type: application/json" \+ -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' | jq .+```++---++## 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** | |++---++## Common Questions (for Operator)++**Q: What if someone asks "Can I claim it right now?"**+A: "You can—let me show you the flow." Do a dry-run with your MetaMask in the audience. If it works, great; if not, say "The testnet is having a moment, but the code is production-ready."++**Q: What if they ask about the avatar?**+A: "That's a GLB model—think of it as a 3D asset we can animate and rig. Every agent gets one, either pre-made or custom from a photo."++**Q: What if RPC is slow?**+A: "Testnet is a bit congested right now. On mainnet, this would be instant." (Don't lie; testnet is slower by design.)++---diff --git a/docs/VALIDATION_DEPLOY.md b/docs/VALIDATION_DEPLOY.mdnew file mode 100644index 000000000..11b849e9e--- /dev/null+++ b/docs/VALIDATION_DEPLOY.md@@ -0,0 +1,465 @@+# ValidationRegistry Mainnet Deployment Runbook++Deploys `ValidationRegistry` to 15 mainnet chains via CREATE2 (deterministic address parity). This contract manages allow-listed validators that attest off-chain proofs for agents.++**Status:** Not yet deployed to mainnet (testnet: `0x8004Cb1BF31DAf7788923b405b754f57acEB4272`).++---++## 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) |++---++## Pre-Deployment Checklist++- [ ] Read and understand [contracts/CLAUDE.md](../contracts/CLAUDE.md)+- [ ] Confirm deployer wallet has enough gas on all 15 chains (est. ≈0.01–0.5 ETH per chain depending on L2 vs. L1)+- [ ] Have Etherscan API keys for all 15 chains (or at least the L1s)+- [ ] Build and test: `cd contracts && forge build && forge test`+- [ ] Dry-run at least one chain before any broadcasts++---++## Step 1: Build & Test++```bash+cd contracts+forge build+forge test+```++Output should show all tests passing:+```+...+Test result: ok. X passed; 0 failed; 0 skipped+```++---++## Step 2: Environment Variables++Create a `.env.local` file in the repo root or set these in your shell:++```bash+# Deployer private key (must have gas on all 15 chains)+export DEPLOYER_PK=0x...++# Etherscan API keys (name convention: CHAIN_ETHERSCAN_API_KEY)+export ETHEREUM_ETHERSCAN_API_KEY=...+export BASE_ETHERSCAN_API_KEY=...+export OPTIMISM_ETHERSCAN_API_KEY=...+# ... (see "Etherscan API Keys" table below)++# Optional: override RPC endpoints (defaults use public providers)+export ETHEREUM_RPC_URL=https://...+export BASE_RPC_URL=https://...+# ... (see "RPC Endpoints" table below)+```++**Do not commit `.env.local`.** It contains secrets.++---++## Step 3: Dry-Run (No Broadcasting)++Before broadcasting to any chain, verify the deployment locally:++```bash+cd contracts+forge script script/DeployValidationMainnet.s.sol:DeployValidationMainnet \+ --rpc-url https://ethereum-rpc.publicnode.com \+ --sender 0x...+```++Expected output:+```+Expected ValidationRegistry: 0x...+IdentityRegistry: 0x8004A169FB4a3325136EB29fA0ceB6D2e539a432+Deployer (owner): 0x...+---+Traces:+ ...+```++**Do not see `--broadcast` in the command.** This is a local simulation only.++---++## Step 4: Deployment Commands (All Chains)++Deploy to each mainnet chain using `--broadcast`. Suggested order: **L1s first** (Ethereum, Polygon), then L2s.++### Ethereum Mainnet++```bash+forge script script/DeployValidationMainnet.s.sol:DeployValidationMainnet \+ --rpc-url https://ethereum-rpc.publicnode.com \+ --sender $DEPLOYER_WALLET \+ --private-key $DEPLOYER_PK \+ --broadcast --verify --etherscan-api-key $ETHEREUM_ETHERSCAN_API_KEY+```++Expected gas: ≈0.5 ETH @ standard rates.+Expected address: `0x8004Cb1BF31DAf7788923b405b754f57acEB42ab` (run `cast create2` below to verify).++### Base++```bash+forge script script/DeployValidationMainnet.s.sol:DeployValidationMainnet \+ --rpc-url https://base-rpc.publicnode.com \+ --sender $DEPLOYER_WALLET \+ --private-key $DEPLOYER_PK \+ --broadcast --verify --etherscan-api-key $BASE_ETHERSCAN_API_KEY+```++Expected gas: ≈0.01 ETH (L2).+Expected address: **identical to Ethereum** (CREATE2 determinism).++### Optimism++```bash+forge script script/DeployValidationMainnet.s.sol:DeployValidationMainnet \+ --rpc-url https://optimism-rpc.publicnode.com \+ --sender $DEPLOYER_WALLET \+ --private-key $DEPLOYER_PK \+ --broadcast --verify --etherscan-api-key $OPTIMISM_ETHERSCAN_API_KEY+```++Expected gas: ≈0.01 ETH (L2).+Expected address: **identical to all others**.++### Arbitrum One++```bash+forge script script/DeployValidationMainnet.s.sol:DeployValidationMainnet \+ --rpc-url https://arbitrum-rpc.publicnode.com \+ --sender $DEPLOYER_WALLET \+ --private-key $DEPLOYER_PK \+ --broadcast --verify --etherscan-api-key $ARBITRUM_ETHERSCAN_API_KEY+```++Expected gas: ≈0.01 ETH (L2).+Expected address: **identical to all others**.++### Polygon (Matic)++```bash+forge script script/DeployValidationMainnet.s.sol:DeployValidationMainnet \+ --rpc-url https://polygon-rpc.publicnode.com \+ --sender $DEPLOYER_WALLET \+ --private-key $DEPLOYER_PK \+ --broadcast --verify --etherscan-api-key $POLYGON_ETHERSCAN_API_KEY+```++Expected gas: ≈0.001 ETH (sidechain).+Expected address: **identical to all others**.++### BNB Chain++```bash+forge script script/DeployValidationMainnet.s.sol:DeployValidationMainnet \+ --rpc-url https://bsc-rpc.publicnode.com \+ --sender $DEPLOYER_WALLET \+ --private-key $DEPLOYER_PK \+ --broadcast --verify --etherscan-api-key $BSC_ETHERSCAN_API_KEY+```++Expected gas: ≈0.002 ETH.+Expected address: **identical to all others**.++### Avalanche C-Chain++```bash+forge script script/DeployValidationMainnet.s.sol:DeployValidationMainnet \+ --rpc-url https://avalanche-c-chain-rpc.publicnode.com \+ --sender $DEPLOYER_WALLET \+ --private-key $DEPLOYER_PK \+ --broadcast --verify --etherscan-api-key $AVALANCHE_ETHERSCAN_API_KEY+```++Expected gas: ≈0.005 ETH.+Expected address: **identical to all others**.++### Gnosis++```bash+forge script script/DeployValidationMainnet.s.sol:DeployValidationMainnet \+ --rpc-url https://gnosis-rpc.publicnode.com \+ --sender $DEPLOYER_WALLET \+ --private-key $DEPLOYER_PK \+ --broadcast --verify --etherscan-api-key $GNOSIS_ETHERSCAN_API_KEY+```++Expected gas: ≈0.002 ETH.+Expected address: **identical to all others**.++### Linea++```bash+forge script script/DeployValidationMainnet.s.sol:DeployValidationMainnet \+ --rpc-url https://linea-rpc.publicnode.com \+ --sender $DEPLOYER_WALLET \+ --private-key $DEPLOYER_PK \+ --broadcast --verify --etherscan-api-key $LINEA_ETHERSCAN_API_KEY+```++Expected gas: ≈0.005 ETH (L2).+Expected address: **identical to all others**.++### Scroll++```bash+forge script script/DeployValidationMainnet.s.sol:DeployValidationMainnet \+ --rpc-url https://scroll-rpc.publicnode.com \+ --sender $DEPLOYER_WALLET \+ --private-key $DEPLOYER_PK \+ --broadcast --verify --etherscan-api-key $SCROLL_ETHERSCAN_API_KEY+```++Expected gas: ≈0.005 ETH (L2).+Expected address: **identical to all others**.++### zkSync Era++```bash+forge script script/DeployValidationMainnet.s.sol:DeployValidationMainnet \+ --rpc-url https://zksync-mainnet-rpc.publicnode.com \+ --sender $DEPLOYER_WALLET \+ --private-key $DEPLOYER_PK \+ --broadcast --verify --etherscan-api-key $ZKSYNC_ETHERSCAN_API_KEY+```++Expected gas: ≈0.005 ETH (L2).+Expected address: **identical to all others**.++### Mantle++```bash+forge script script/DeployValidationMainnet.s.sol:DeployValidationMainnet \+ --rpc-url https://mantle-rpc.publicnode.com \+ --sender $DEPLOYER_WALLET \+ --private-key $DEPLOYER_PK \+ --broadcast --verify --etherscan-api-key $MANTLE_ETHERSCAN_API_KEY+```++Expected gas: ≈0.005 ETH (L2).+Expected address: **identical to all others**.++### Celo++```bash+forge script script/DeployValidationMainnet.s.sol:DeployValidationMainnet \+ --rpc-url https://celo-mainnet-rpc.publicnode.com \+ --sender $DEPLOYER_WALLET \+ --private-key $DEPLOYER_PK \+ --broadcast --verify --etherscan-api-key $CELO_ETHERSCAN_API_KEY+```++Expected gas: ≈0.001 ETH (sidechain).+Expected address: **identical to all others**.++### Ink++```bash+forge script script/DeployValidationMainnet.s.sol:DeployValidationMainnet \+ --rpc-url https://ink-mainnet-rpc.publicnode.com \+ --sender $DEPLOYER_WALLET \+ --private-key $DEPLOYER_PK \+ --broadcast --verify --etherscan-api-key $INK_ETHERSCAN_API_KEY+```++Expected gas: ≈0.01 ETH (L2).+Expected address: **identical to all others**.++### Unichain++```bash+forge script script/DeployValidationMainnet.s.sol:DeployValidationMainnet \+ --rpc-url https://unichain-mainnet-rpc.publicnode.com \+ --sender $DEPLOYER_WALLET \+ --private-key $DEPLOYER_PK \+ --broadcast --verify --etherscan-api-key $UNICHAIN_ETHERSCAN_API_KEY+```++Expected gas: ≈0.01 ETH (L2).+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` |++---++## Expected Addresses++To compute the expected `ValidationRegistry` address before deployment, use `cast`:++```bash+cast create2 \+ --salt 0x56616c69646174696f6e526567697374727900000000000000000000000001 \+ --code-path <(solc --bin contracts/src/ValidationRegistry.sol:ValidationRegistry) \+ --constructor-args "$(cast abi-encode "constructor(address,address)" \+ 0x8004A169FB4a3325136EB29fA0ceB6D2e539a432 \+ 0x$(cast to-checksum-address "$(cast call --rpc-url $RPC --from 0x0000000000000000000000000000000000000000 eth_call | head -1)"))"+```++**Simpler approach:** The address will be **identical on all 15 chains** due to CREATE2 determinism. If you deploy to Ethereum first, use that address for verification on subsequent chains.++All chains → `0x8004Cb1BF31DAf7788923b405b754f57acEB42ab` (example — compute locally to verify).++---++## Step 5: Post-Deployment Verification++After deploying to each chain, verify the contract exists and is correct:++### Etherscan Web UI++Visit the block explorer for each chain and search for the deployment transaction hash. Once finality is reached, the contract should appear.++**Example (Ethereum):** `https://etherscan.io/address/0x...`++### Cast CLI++```bash+# Verify constructor args are correct+cast call 0x... "identityRegistry()" --rpc-url https://ethereum-rpc.publicnode.com+# Should output: 0x8004A169FB4a3325136EB29fA0ceB6D2e539a432++cast call 0x... "owner()" --rpc-url https://ethereum-rpc.publicnode.com+# Should output: 0x... (your deployer address)+```++### Smoke Test (Integration)++Once deployed to all chains, verify the contract can record validations:++```bash+# Add a test validator+cast send 0x... \+ "addValidator(address)" \+ 0xVALIDATOR_ADDR \+ --private-key $DEPLOYER_PK \+ --rpc-url https://ethereum-rpc.publicnode.com++# Verify it was added+cast call 0x... "isValidator(address)" 0xVALIDATOR_ADDR --rpc-url https://ethereum-rpc.publicnode.com+# Should output: 0x0000000000000000000000000000000000000000000000000000000000000001+```++---++## Step 6: Update Frontend++Once deployed and verified on all 15 chains, update [src/erc8004/abi.js](../src/erc8004/abi.js) to register the mainnet address:++```javascript+const MAINNET = {+ identityRegistry: '0x8004A169FB4a3325136EB29fA0ceB6D2e539a432',+ reputationRegistry: '0x8004BAa17C55a88189AE136b182e5fdA19dE9b63',+ validationRegistry: '0x8004Cb1BF31DAf7788923b405b754f57acEB42ab', // <- ADD THIS LINE+};+```++Update `REGISTRY_DEPLOYMENTS` object—it should already have entries for all 15 chain IDs, just ensure they point to the new address.++---++## Rollback (If Needed)++**CREATE2 addresses are single-shot.** Once deployed, you cannot redeploy to the same address. If deployment fails or is incorrect:++1. **Document the failed deploy:** Note which chains succeeded, which failed, the address, and the failure reason.+2. **New salt:** Create a new deployment script with a different salt (e.g., increment `uint256(2)` in the salt).+3. **Redeploy** with the new script to all chains.+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++---++## 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 |++(Etherscan verification is usually free; if using a paid RPC, factor in API costs.)++---++## 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.++---++## References++- [contracts/CLAUDE.md](../contracts/CLAUDE.md) — Foundry setup & conventions+- [contracts/src/ValidationRegistry.sol](../contracts/src/ValidationRegistry.sol) — Contract source+- [src/erc8004/abi.js](../src/erc8004/abi.js) — Frontend registry deployments+- [docs/ARCHITECTURE.md](./ARCHITECTURE.md) — System overview+- [Foundry Book](https://book.getfoundry.sh/) — Forge docs+- [CREATE2 deep dive](https://ethereum.org/en/developers/docs/accounts/#contract-accounts) — How deterministic addresses workdiff --git a/lobehub-plugin/.gitignore b/lobehub-plugin/.gitignorenew file mode 100644index 000000000..62ccde41c--- /dev/null+++ b/lobehub-plugin/.gitignore@@ -0,0 +1,4 @@+node_modules/+dist/+*.tsbuildinfo+.DS_Storediff --git a/lobehub-plugin/README.md b/lobehub-plugin/README.mdnew file mode 100644index 000000000..9a0ad6f93--- /dev/null+++ b/lobehub-plugin/README.md@@ -0,0 +1,152 @@+# @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.++## Features++- **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++1. Clone this directory into your LobeHub fork at `plugins/@3dagent/lobehub-plugin/`+2. Install dependencies:+ ```bash+ cd lobehub-plugin+ npm install+ ```+3. Build:+ ```bash+ npm run build+ ```+4. Reference the plugin manifest in your LobeHub fork's plugin registry.++## Usage++In LobeHub's plugin settings, configure:++- **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`)++The plugin will render an iframe pointing to `${apiOrigin}/agent/${agentId}/embed` and listen for chat messages.++## Configuration++Plugin settings are defined in [`src/config-schema.ts`](src/config-schema.ts) and exposed via the [`manifest.json`](manifest.json) schema section.++## Bridge Protocol++The plugin uses the **v1 bridge protocol** (FROZEN) from `public/agent/embed.html`:++### Host → Iframe++```json+{+ "type": "agent:hello",+ "agentId": "agent-id",+ "host": "optional-origin"+}+```++```json+{+ "type": "agent:action",+ "agentId": "agent-id",+ "action": {+ "type": "speak",+ "payload": { "text": "Hello, world!" }+ }+}+```++### Iframe → Host++```json+{+ "type": "agent:ready",+ "agentId": "agent-id",+ "version": "1",+ "capabilities": ["speak", "gesture", "look-at", "emote", "present-model"],+ "name": "Agent Name"+}+```++```json+{+ "type": "agent:resize",+ "agentId": "agent-id",+ "height": 500+}+```++## Lobe Hook Integration++### Current Status++The plugin currently **mocks** the Lobe hook API with a custom event emitter. To integrate with a real LobeHub fork, you must:++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:++```typescript+// Example (adjust based on actual SDK):+import { usePluginStore } from '@lobehub/ui';++export const AgentPane: React.FC<AgentPaneProps> = ({ settings }) => {+ // ... existing code ...++ const { onAssistantMessage } = usePluginStore();++ useEffect(() => {+ if (onAssistantMessage) {+ const unsubscribe = onAssistantMessage((msg) => {+ if (msg.content && bridgeRef.current) {+ bridgeRef.current.speak(msg.content);+ }+ });+ return unsubscribe;+ }+ }, [onAssistantMessage]);++ // ... rest of component ...+};+```++### Placeholder Implementation++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++```bash+npm install+npm run dev # Watch build (tsc + esbuild)+npm run type-check # Check TypeScript without emitting+npm run build # Production bundle+```++The build outputs to `dist/bundle.js` (ESM module).++## 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+```++## License++MITdiff --git a/lobehub-plugin/manifest.json b/lobehub-plugin/manifest.jsonnew file mode 100644index 000000000..94b4d60ad--- /dev/null+++ b/lobehub-plugin/manifest.json@@ -0,0 +1,18 @@+{+ "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", "title": "API Origin" }+ ]+}diff --git a/lobehub-plugin/package-lock.json b/lobehub-plugin/package-lock.jsonnew file mode 100644index 000000000..2762af1b2--- /dev/null+++ b/lobehub-plugin/package-lock.json@@ -0,0 +1,559 @@+{+ "name": "@3dagent/lobehub-plugin",+ "version": "1.0.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "@3dagent/lobehub-plugin",+ "version": "1.0.0",+ "license": "MIT",+ "devDependencies": {+ "@types/react": "^18.2.0",+ "@types/react-dom": "^18.2.0",+ "esbuild": "^0.21.0",+ "typescript": "^5.4.0"+ },+ "peerDependencies": {+ "react": "^18.0.0",+ "react-dom": "^18.0.0"+ }+ },+ "node_modules/@esbuild/aix-ppc64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",+ "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "aix"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/android-arm": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz",+ "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/android-arm64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz",+ "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/android-x64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz",+ "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "android"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/darwin-arm64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz",+ "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/darwin-x64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz",+ "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "darwin"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/freebsd-arm64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz",+ "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/freebsd-x64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz",+ "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "freebsd"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/linux-arm": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz",+ "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==",+ "cpu": [+ "arm"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/linux-arm64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz",+ "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/linux-ia32": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz",+ "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/linux-loong64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz",+ "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==",+ "cpu": [+ "loong64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/linux-mips64el": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz",+ "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==",+ "cpu": [+ "mips64el"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/linux-ppc64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz",+ "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==",+ "cpu": [+ "ppc64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/linux-riscv64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz",+ "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==",+ "cpu": [+ "riscv64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/linux-s390x": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz",+ "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==",+ "cpu": [+ "s390x"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/linux-x64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz",+ "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "linux"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/netbsd-x64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz",+ "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "netbsd"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/openbsd-x64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz",+ "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "openbsd"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/sunos-x64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz",+ "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "sunos"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/win32-arm64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz",+ "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==",+ "cpu": [+ "arm64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/win32-ia32": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz",+ "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==",+ "cpu": [+ "ia32"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@esbuild/win32-x64": {+ "version": "0.21.5",+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz",+ "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==",+ "cpu": [+ "x64"+ ],+ "dev": true,+ "license": "MIT",+ "optional": true,+ "os": [+ "win32"+ ],+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/@types/prop-types": {+ "version": "15.7.15",+ "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",+ "integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/@types/react": {+ "version": "18.3.28",+ "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.28.tgz",+ "integrity": "sha512-z9VXpC7MWrhfWipitjNdgCauoMLRdIILQsAEV+ZesIzBq/oUlxk0m3ApZuMFCXdnS4U7KrI+l3WRUEGQ8K1QKw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/prop-types": "*",+ "csstype": "^3.2.2"+ }+ },+ "node_modules/@types/react-dom": {+ "version": "18.3.7",+ "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.7.tgz",+ "integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",+ "dev": true,+ "license": "MIT",+ "peerDependencies": {+ "@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/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,+ "hasInstallScript": true,+ "license": "MIT",+ "bin": {+ "esbuild": "bin/esbuild"+ },+ "engines": {+ "node": ">=12"+ },+ "optionalDependencies": {+ "@esbuild/aix-ppc64": "0.21.5",+ "@esbuild/android-arm": "0.21.5",+ "@esbuild/android-arm64": "0.21.5",+ "@esbuild/android-x64": "0.21.5",+ "@esbuild/darwin-arm64": "0.21.5",+ "@esbuild/darwin-x64": "0.21.5",+ "@esbuild/freebsd-arm64": "0.21.5",+ "@esbuild/freebsd-x64": "0.21.5",+ "@esbuild/linux-arm": "0.21.5",+ "@esbuild/linux-arm64": "0.21.5",+ "@esbuild/linux-ia32": "0.21.5",+ "@esbuild/linux-loong64": "0.21.5",+ "@esbuild/linux-mips64el": "0.21.5",+ "@esbuild/linux-ppc64": "0.21.5",+ "@esbuild/linux-riscv64": "0.21.5",+ "@esbuild/linux-s390x": "0.21.5",+ "@esbuild/linux-x64": "0.21.5",+ "@esbuild/netbsd-x64": "0.21.5",+ "@esbuild/openbsd-x64": "0.21.5",+ "@esbuild/sunos-x64": "0.21.5",+ "@esbuild/win32-arm64": "0.21.5",+ "@esbuild/win32-ia32": "0.21.5",+ "@esbuild/win32-x64": "0.21.5"+ }+ },+ "node_modules/js-tokens": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",+ "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",+ "license": "MIT",+ "peer": true+ },+ "node_modules/loose-envify": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",+ "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "js-tokens": "^3.0.0 || ^4.0.0"+ },+ "bin": {+ "loose-envify": "cli.js"+ }+ },+ "node_modules/react": {+ "version": "18.3.1",+ "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",+ "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "loose-envify": "^1.1.0"+ },+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/react-dom": {+ "version": "18.3.1",+ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",+ "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "loose-envify": "^1.1.0",+ "scheduler": "^0.23.2"+ },+ "peerDependencies": {+ "react": "^18.3.1"+ }+ },+ "node_modules/scheduler": {+ "version": "0.23.2",+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",+ "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "loose-envify": "^1.1.0"+ }+ },+ "node_modules/typescript": {+ "version": "5.9.3",+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ }+ }+}diff --git a/lobehub-plugin/package.json b/lobehub-plugin/package.jsonnew file mode 100644index 000000000..738b13e6d--- /dev/null+++ b/lobehub-plugin/package.json@@ -0,0 +1,33 @@+{+ "name": "@3dagent/lobehub-plugin",+ "version": "1.0.0",+ "description": "3D Agent for LobeHub — sidebar plugin that renders an embodied avatar",+ "private": true,+ "type": "module",+ "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",+ "type-check": "tsc --noEmit"+ },+ "devDependencies": {+ "@types/react": "^18.2.0",+ "@types/react-dom": "^18.2.0",+ "esbuild": "^0.21.0",+ "typescript": "^5.4.0"+ },+ "peerDependencies": {+ "react": "^18.0.0",+ "react-dom": "^18.0.0"+ },+ "keywords": [+ "lobehub",+ "plugin",+ "3d-agent",+ "avatar",+ "agent"+ ],+ "author": "3D Agent",+ "license": "MIT"+}diff --git a/lobehub-plugin/src/AgentPane.tsx b/lobehub-plugin/src/AgentPane.tsxnew file mode 100644index 000000000..54803c9ca--- /dev/null+++ b/lobehub-plugin/src/AgentPane.tsx@@ -0,0 +1,105 @@+import React, { useRef, useEffect, useState } from 'react';+import { AgentBridge } from './bridge';+import { PluginSettings, DEFAULT_API_ORIGIN } from './config-schema';++export interface AgentPaneProps {+ settings: PluginSettings;+}++/**+ * 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.+ */+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 apiOrigin = settings.apiOrigin || DEFAULT_API_ORIGIN;+ const embedUrl = `${apiOrigin}/agent/${settings.agentId}/embed?bg=transparent&name=1`;++ // Initialize bridge on mount.+ useEffect(() => {+ const bridge = new AgentBridge({+ agentId: settings.agentId,+ iframeRef,+ onReady: () => setIsReady(true),+ onResize: (height: number) => setFrameHeight(Math.min(height, 600)),+ });++ bridge.mount();+ bridgeRef.current = bridge;++ return () => {+ bridge.unmount();+ };+ }, [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.+ useEffect(() => {+ const handleLobeMessage = (ev: CustomEvent) => {+ const { content } = ev.detail || {};+ if (content && bridgeRef.current) {+ bridgeRef.current.speak(content);+ }+ };++ // 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);++ return () => {+ window.removeEventListener('lobe:assistantMessage', handleLobeMessage as EventListener);+ };+ }, []);++ return (+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ width: '100%',+ height: frameHeight,+ backgroundColor: 'transparent',+ borderRadius: '8px',+ overflow: 'hidden',+ }}+ >+ {!isReady && (+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ width: '100%',+ height: '100%',+ backgroundColor: 'rgba(0, 0, 0, 0.1)',+ color: 'rgba(0, 0, 0, 0.5)',+ fontSize: '12px',+ }}+ >+ Loading agent…+ </div>+ )}+ <iframe+ ref={iframeRef}+ src={embedUrl}+ title={`3D Agent ${settings.agentId}`}+ style={{+ width: '100%',+ height: '100%',+ border: 'none',+ display: isReady ? 'block' : 'none',+ }}+ sandbox="allow-same-origin allow-scripts allow-presentation"+ />+ </div>+ );+};++export default AgentPane;diff --git a/lobehub-plugin/src/bridge.ts b/lobehub-plugin/src/bridge.tsnew file mode 100644index 000000000..294ad67a4--- /dev/null+++ b/lobehub-plugin/src/bridge.ts@@ -0,0 +1,111 @@+/**+ * PostMessage bridge wrapping the agent embed iframe.+ * Implements the v1 protocol from /public/agent/embed.html (FROZEN).+ */++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;+ id: string;+}++interface AgentReadyMessage {+ type: 'agent:ready';+ 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;+ onResize?: (height: number) => void;+ onAction?: (action: Record<string, unknown>) => void;+}++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;++ constructor(opts: BridgeOptions) {+ this.agentId = opts.agentId;+ this.iframeRef = opts.iframeRef;+ 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);+ }++ private handleMessage(ev: MessageEvent): void {+ const msg = ev.data;+ 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);+ break;+ case 'agent:action':+ this.onAction?.(msg.action);+ break;+ }+ }++ private sayHello(): void {+ this.post({+ type: 'agent:hello',+ agentId: this.agentId,+ });+ }++ speak(text: string): void {+ this.post({+ type: 'agent:action',+ agentId: this.agentId,+ action: {+ type: 'speak',+ payload: { text },+ },+ });+ }++ private post(msg: OutboundMessage): void {+ const frame = this.iframeRef.current;+ if (frame?.contentWindow) {+ frame.contentWindow.postMessage(msg, '*');+ }+ }+}diff --git a/lobehub-plugin/src/config-schema.ts b/lobehub-plugin/src/config-schema.tsnew file mode 100644index 000000000..c9bff1b1f--- /dev/null+++ b/lobehub-plugin/src/config-schema.ts@@ -0,0 +1,28 @@+/**+ * Plugin settings schema for LobeHub configuration UI.+ */++export interface PluginSettings {+ agentId: string;+ apiOrigin: string;+}++export const DEFAULT_API_ORIGIN = 'https://3dagent.vercel.app';++export const settingsSchema = {+ agentId: {+ type: 'string' as const,+ title: 'Agent ID',+ description: 'The ID of the 3D agent to render',+ placeholder: 'e.g., agent-xyz-123',+ required: true,+ },+ apiOrigin: {+ type: 'string' as const,+ title: 'API Origin',+ description: 'Base URL of the 3D Agent server',+ default: DEFAULT_API_ORIGIN,+ placeholder: DEFAULT_API_ORIGIN,+ required: false,+ },+};diff --git a/lobehub-plugin/src/index.ts b/lobehub-plugin/src/index.tsnew file mode 100644index 000000000..8b28123a0--- /dev/null+++ b/lobehub-plugin/src/index.ts@@ -0,0 +1,12 @@+/**+ * @3dagent/lobehub-plugin+ *+ * Entry point for the 3D Agent LobeHub plugin.+ * Exports the main React component and configuration.+ */++export { AgentPane, type AgentPaneProps } from './AgentPane';+export { AgentBridge, type BridgeOptions } from './bridge';+export { settingsSchema, DEFAULT_API_ORIGIN, type PluginSettings } from './config-schema';++// Manifest is served separately as manifest.json; no runtime export needed.diff --git a/lobehub-plugin/tsconfig.json b/lobehub-plugin/tsconfig.jsonnew file mode 100644index 000000000..b195fd27c--- /dev/null+++ b/lobehub-plugin/tsconfig.json@@ -0,0 +1,29 @@+{+ "compilerOptions": {+ "target": "ES2020",+ "useDefineForClassFields": true,+ "lib": ["ES2020", "DOM", "DOM.Iterable"],+ "module": "ESNext",+ "skipLibCheck": true,+ "esModuleInterop": true,+ "allowSyntheticDefaultImports": true,+ "strict": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "noImplicitReturns": true,+ "noImplicitAny": true,+ "noImplicitThis": true,+ "declaration": true,+ "declarationMap": true,+ "sourceMap": true,+ "outDir": "./dist",+ "rootDir": "./src",+ "moduleResolution": "bundler",+ "resolveJsonModule": true,+ "isolatedModules": true,+ "jsx": "react-jsx",+ "jsxImportSource": "react"+ },+ "include": ["src"],+ "exclude": ["node_modules"]+}diff --git a/package.json b/package.jsonindex fc5e3fb29..7044f9bd9 100644--- a/package.json+++ b/package.json@@ -37,6 +37,7 @@"dev:lib": "TARGET=lib vite","build": "vite build","build:lib": "TARGET=lib vite build",+ "build:artifact": "vite build --config vite.config.artifact.js","publish:lib": "node scripts/publish-lib.mjs","build:all": "npm run build && npm run build:lib && npm run publish:lib","clean": "rm -rf dist/* dist-lib/* || true",diff --git a/prompts/complete/01-walletconnect-siwe.md b/prompts/complete/01-walletconnect-siwe.mdnew file mode 100644index 000000000..a6f440301--- /dev/null+++ b/prompts/complete/01-walletconnect-siwe.md@@ -0,0 +1,54 @@+# 01 — WalletConnect → SIWE bridge++## 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.++Closes the audit's only remaining wallet-auth gap.++## What to build++A single module that exposes:++```js+// src/auth/walletconnect-bridge.js+export async function signInWithWalletConnect({ projectId, chains } = {}) → { user, address }+export function getWalletConnectProvider() → EIP1193Provider | null+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\_).+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).+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.++## Files you own++- Create: `src/auth/walletconnect-bridge.js`+- Create: `src/auth/walletconnect-bridge.test.html`+- Create: `src/auth/README.md` — documents env var `VITE_WALLETCONNECT_PROJECT_ID`, CDN version pinned, known issues.++## Files off-limits++- `api/auth/siwe/*` — consume as-is.+- `src/account.js`, `src/erc8004/privy.js` — read-only.+- `vite.config.js`, `vercel.json`, `package.json` — do not edit.++## Acceptance++- `node --check src/auth/walletconnect-bridge.js` passes.+- Opening `src/auth/walletconnect-bridge.test.html` via `npm run dev` → WC button opens modal, scan → connect → sign → `/api/auth/me` returns a user.+- The bridge does **not** throw when `projectId` is missing — it returns a clear error.++## Reporting++Files created, exact CDN URL pinned, WalletConnect version, any SIWE message format mismatch discovered against [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js).diff --git a/prompts/complete/02-editor-spec.md b/prompts/complete/02-editor-spec.mdnew file mode 100644index 000000000..9ecdbfebb--- /dev/null+++ b/prompts/complete/02-editor-spec.md@@ -0,0 +1,76 @@+# 02 — EDITOR_SPEC.md++## Why++[specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md) references a future `EDITOR_SPEC.md` that never got written. The editor surface (`src/editor/*`, `public/studio/`, the `agent-edit.html` route) is 90% shipped but has no public contract. Writing the spec freezes the interface so downstream integrations (Studio, CLI, external hosts) can depend on it.++**This is a documentation-only task.** No code changes.++## What to write++Create [specs/EDITOR_SPEC.md](../../specs/EDITOR_SPEC.md) covering:++### 1. Identity++- Format ID: `agent-editor/0.1`+- Stability: draft+- Relationship to `EMBED_SPEC` (the embed plays, the editor writes)++### 2. Attached editor contract++Document how `<agent-3d editor>` activates the editor panel. List every editor-only attribute that exists on [src/element.js](../../src/element.js) — read the file and enumerate them. Required and optional attrs.++### 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.+- `glb-export.js` — export format, options, what's included vs. stripped.+- `publish.js` — R2 presign flow, API endpoints called, auth requirements.++For each: inputs (what data it reads), outputs (what it writes), events (bus or DOM), and failure modes.++### 4. Permission model++- Who can edit which fields (anonymous / authed / owner-only).+- How the editor checks ownership (reference [src/account.js](../../src/account.js) + `/api/auth/me`).+- What happens on save for an unauthed user (redirect → `/login?next=...`).++### 5. Events++Table of CustomEvents emitted on the editor host — names, detail shapes, when they fire. Mirror the style of the protocol-bus table in [src/CLAUDE.md](../../src/CLAUDE.md).++### 6. Extension points++- Custom panels — how a third-party dev would add one.+- Custom exporters — shape of the exporter plugin contract (even if you recommend against doing it today, document the seam).++### 7. Security++- What's sanitized before upload (see `api/avatars/presign` + `api/avatars` — read them, don't speculate).+- Max file size, allowed mimetypes.+- SSRF protections (the presign flow doesn't fetch, but the `fetch-model` helper does — note which paths are fetchable).++### 8. Versioning++- Breaking vs non-breaking change policy for this spec.+- How to check which version an `<agent-3d editor>` element speaks (hint: add a `data-editor-version` attr or an event).++## Files you own++- Create: `specs/EDITOR_SPEC.md`++## Files off-limits++- Everything in `src/editor/`, `src/element.js`, `api/` — read only. Do not modify to make the spec cleaner. If you find a bug worth fixing, note it in reporting.++## Acceptance++- `specs/EDITOR_SPEC.md` exists and every claim cites an exact file path + line number from the current codebase.+- No API invented. If `src/editor/foo.js` doesn't export `bar`, the spec doesn't say it does.+- At least one subsection explicitly documents current pre-1.0 inconsistencies so readers aren't misled.++## Reporting++Word count, number of file citations, list of pre-1.0 rough edges called out, any API invented and then removed during review.diff --git a/prompts/complete/03-claude-artifact.md b/prompts/complete/03-claude-artifact.mdnew file mode 100644index 000000000..afde60b63--- /dev/null+++ b/prompts/complete/03-claude-artifact.md@@ -0,0 +1,72 @@+# 03 — Claude.ai artifact snippet++## 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.++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.++## What to build++### 1. The endpoint++Create [api/artifact.js](../../api/artifact.js) — a serverless function that returns `text/html` with:++- `GET /api/artifact?agent=<agentId>` — full-page HTML+- `GET /api/artifact?model=<glbUrl>` — full-page HTML with no agent overlay (just viewer)+- Optional `theme=<dark|light>`, `idle=<clipName>`, `bg=<hex>` query params.++Output shape — a minimal HTML document inline-styled and inline-scripted, using `<agent-3d>` via the already-built library UMD at `/dist-lib/agent-3d.umd.cjs`. Sample:++```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>+</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).+- `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.++### 2. Static fallback + docs++Create `public/artifact/index.html` — a viewer explaining the endpoint, showing live preview via iframe, copy-to-clipboard button. Style is minimal; use the inline `<style>` pattern from [public/widgets-gallery/index.html](../../public/widgets-gallery/index.html) as a model.++Create `public/artifact/README.md` — how to cite this endpoint in a Claude.ai conversation so it auto-renders as an artifact. Include a worked example.++Create `specs/CLAUDE_ARTIFACT.md` — the contract: URL shape, accepted params, returned CSP, browser compat notes.++## Files you own++- Create: `api/artifact.js`+- Create: `public/artifact/index.html`+- Create: `public/artifact/README.md`+- Create: `specs/CLAUDE_ARTIFACT.md`++## Files off-limits++- `api/mcp.js` — read-only. If its `render_avatar` tool needs to call your new endpoint, that's a **follow-up** task, not this one. Note in reporting.+- `src/element.js`, `src/lib.js` — read-only.++## Acceptance++- `curl -I 'http://localhost:3000/api/artifact?agent=test-id'` → `200`, `Content-Type: text/html`, CSP header set.+- Pasting the URL into Claude.ai (real test) renders an interactive 3D artifact. If you can't run this test, say so in reporting.+- Rejecting malformed input: `?agent=<script>` → 400.+- Rejecting disallowed model origins: `?model=http://evil.example.com/x.glb` → 400.++## Reporting++Endpoint response headers dumped, sample output HTML length, list of query params implemented, whether manual Claude.ai test was run.diff --git a/prompts/complete/04-lobehub-plugin.md b/prompts/complete/04-lobehub-plugin.mdnew file mode 100644index 000000000..4a84b77bc--- /dev/null+++ b/prompts/complete/04-lobehub-plugin.md@@ -0,0 +1,73 @@+# 04 — LobeHub plugin manifest + iframe handshake++## Why++Band 5 gap: no shipped LobeHub plugin. Even if we can't get merged into LobeHub's registry today, we can ship a **plugin-shaped** bundle they (or a LobeHub fork operator) can drop in. The spec folder [prompts/lobehub-embed/](../lobehub-embed/) has the design; this prompt ships the minimum viable plugin surface.++**No external submissions.** Everything lives in our repo. Submission PR is out of scope.++## What to build++### 1. Plugin manifest++Create `public/lobehub/plugin.json` — follows the LobeHub plugin manifest v1 shape (look up the current schema; if you can't access it, use a best-effort version matching the fields in [prompts/lobehub-embed/01-plugin-manifest.md](../lobehub-embed/01-plugin-manifest.md)). Fields:++- `identifier`: `3d-agent`+- `version`: `0.1.0`+- `api[]`: one entry pointing at our MCP-compatible endpoints+- `ui.iframe.url`: `https://3dagent.vercel.app/lobehub/iframe`+- `ui.iframe.height`: `480`+- `meta`: title, description, avatar (use our repo avatar), tags++### 2. Plugin iframe page++Create `public/lobehub/iframe/index.html` — minimal page that:++- Loads `<agent-3d>` (lazy).+- Accepts an `?agent=<id>` param.+- Implements the `postMessage` handshake from [prompts/lobehub-embed/02-iframe-handshake.md](../lobehub-embed/02-iframe-handshake.md) — at minimum: `ready`, `resize`, and `action` messages. Origin check against a documented allowlist (`chat.lobehub.com`, `lobechat.ai`, `*`, dev hosts).+- Forwards protocol-bus events (`speak`, `skill-done`, etc.) up to the parent via `postMessage({ type: 'agent-event', detail: ... })`.++### 3. Handshake endpoint++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`.++### 4. Manifest serving endpoint++Create `api/lobehub/manifest.js` — GET-only, returns the contents of `public/lobehub/plugin.json` with `Content-Type: application/json`, `Cache-Control: public, max-age=300`. Exists so the manifest is resolvable at a clean URL (`/api/lobehub/manifest`) even if Vercel's static serving changes.++### 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).+- Links to related specs in [prompts/lobehub-embed/](../lobehub-embed/).++## Files you own++- Create: `public/lobehub/plugin.json`+- Create: `public/lobehub/iframe/index.html`+- Create: `public/lobehub/iframe/boot.js`+- Create: `public/lobehub/README.md`+- Create: `api/lobehub/handshake.js`+- Create: `api/lobehub/manifest.js`++## Files off-limits++- `api/mcp.js` — the iframe can consume it, but don't modify.+- `src/element.js` — read-only; use the existing `<agent-3d>` attributes.+- Any file under `prompts/lobehub-embed/` — those are design docs for a different sprint.++## Acceptance++- `GET /api/lobehub/manifest` returns 200 with valid JSON.+- `POST /api/lobehub/handshake` with `{ agentId: '<known>' }` returns `{ ok: true }`; with `{ agentId: 'does-not-exist' }` returns 404.+- Opening `/lobehub/iframe/?agent=<id>` in an iframe and posting `{ type: 'handshake' }` from the parent window gets back a `{ type: 'ready' }` response.+- `node --check` passes on both API files and `boot.js`.++## Reporting++LobeHub manifest schema version used + source URL, postMessage types wired, list of any LobeHub features explicitly skipped.diff --git a/prompts/complete/05-reputation-dashboard.md b/prompts/complete/05-reputation-dashboard.mdnew file mode 100644index 000000000..68178ae1f--- /dev/null+++ b/prompts/complete/05-reputation-dashboard.md@@ -0,0 +1,70 @@+# 05 — Reputation dashboard UI++## Why++[src/erc8004/reputation.js](../../src/erc8004/reputation.js) exposes `submitFeedback()`, `getReputation()`, `getRecentReviews()` — the contract glue is done. But there's no UI for a user to read reviews or post one. Band 6 audit flagged "reputation UI minimal."++Ship a standalone dashboard at `/reputation/` that works against **any** agent id on **any** supported chain.++## What to build++### 1. Page++Create `public/reputation/index.html` — a self-contained page with:++- Header: agent avatar (pulled via `<agent-3d agent="{id}">` small inline), name, chain + agentId.+- Stats row: total reviews, avg rating, last-review timestamp.+- Review list: paginated, newest-first, shows reviewer address (truncated), rating, comment, tx link to the chain's explorer.+- Submit form: star rating (1–5), comment textarea, submit button. Gated on wallet connection (reuse [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js) `connectWallet()`).+- URL params: `?agent=<id>&chain=<chainId>` (default chain from [src/erc8004/abi.js](../../src/erc8004/abi.js) `REGISTRY_DEPLOYMENTS` — pick Base Sepolia).++### 2. Controller module++Create `src/reputation-ui.js` — the JS that powers the page. Public API:++```js+export class ReputationDashboard {+ constructor(container, { agentId, chainId })+ async load() // fetches getReputation + getRecentReviews+ async submit({ rating, comment }) // calls submitFeedback after wallet connect+ onReviewAdded(fn) // subscribe to new reviews (polls every 30s while tab visible)+}+```++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).++### 3. Styling++Inline `<style>` in `index.html` matching the dark-theme palette used in [public/widgets-gallery/index.html](../../public/widgets-gallery/index.html). Don't import the main app's stylesheet — keep the page tiny and independent.++### 4. Error states++- Wallet not connected → "Connect wallet to leave a review" CTA.+- Unsupported chain → banner with "switch to Base Sepolia" button (standard EIP-3326 call).+- Agent not found on chain → show "This agent isn't registered on chain `<name>`" with a link to `/register`.+- RPC failure → graceful "couldn't reach chain" message with retry.++## Files you own++- Create: `public/reputation/index.html`+- Create: `public/reputation/boot.js` (if you'd rather extract the bootstrapping)+- Create: `src/reputation-ui.js`++## Files off-limits++- `src/erc8004/reputation.js`, `src/erc8004/abi.js`, `src/erc8004/agent-registry.js` — consume as-is. If missing a function, stop and report.++## Acceptance++- Navigating to `http://localhost:3000/reputation/?agent=1&chain=84532` loads without JS errors.+- Review list renders (even if empty).+- Submit flow prompts wallet, sends tx, optimistically appends review on tx hash.+- `node --check src/reputation-ui.js` passes.+- `npm run build` passes.++## Reporting++Functions consumed from `src/erc8004/reputation.js`, any behavior mismatch against the contract, screenshots (or descriptions) of empty / full / error states.diff --git a/prompts/complete/06-validation-dashboard.md b/prompts/complete/06-validation-dashboard.mdnew file mode 100644index 000000000..ce1aa9a3b--- /dev/null+++ b/prompts/complete/06-validation-dashboard.md@@ -0,0 +1,80 @@+# 06 — Validation dashboard UI++## Why++[src/erc8004/validation-recorder.js](../../src/erc8004/validation-recorder.js) exposes `recordValidation()`, `hashReport()`. The contract is live. No UI. Mirror task 05's approach but for ValidationRegistry.++Use case: a third-party validator (auditor) runs tests against an agent's GLB / manifest, signs a report, and submits it on-chain. End-users can browse past validation records for an agent to decide whether to trust it.++## What to build++### 1. Page++Create `public/validation/index.html`:++- Header: agent ref.+- Validation records: list of past reports with validator address, report hash (linkable to IPFS gateway), timestamp, "verdict" (pass/fail/warn).+- Submit form: upload a JSON report, preview its contents, compute hash client-side, upload to IPFS via [src/ipfs.js](../../src/ipfs.js), call `recordValidation(agentId, reportURI, reportHash)`.+- Gated on wallet; any wallet can validate (the contract rule).++### 2. Controller++Create `src/validation-ui.js` with:++```js+export class ValidationDashboard {+ constructor(container, { agentId, chainId })+ async load()+ async submit({ reportFile }) // read JSON, hash, pin, submit+}+```++### 3. Report format++Document the **expected report JSON shape** in `public/validation/REPORT_FORMAT.md`:++```json+{+ "type": "agent-validation-report/0.1",+ "agentId": "...",+ "chainId": 84532,+ "validator": "0x...",+ "ranAt": "2026-04-17T00:00:00Z",+ "suites": [+ { "name": "glb-schema", "status": "pass", "details": "..." },+ { "name": "manifest-integrity", "status": "pass" },+ { "name": "skill-handlers-load", "status": "warn", "details": "skill 'x' missing deps" }+ ],+ "verdict": "pass" | "warn" | "fail",+ "notes": "..."+}+```++Include a sample report at `public/validation/example-report.json`.++### 4. Error states++Same rules as prompt 05: wallet, chain, agent-not-found, RPC failures.++## Files you own++- Create: `public/validation/index.html`+- Create: `public/validation/REPORT_FORMAT.md`+- Create: `public/validation/example-report.json`+- Create: `public/validation/boot.js` (optional)+- Create: `src/validation-ui.js`++## Files off-limits++- `src/erc8004/validation-recorder.js`, `src/erc8004/abi.js`, `src/ipfs.js` — read-only.++## Acceptance++- `http://localhost:3000/validation/?agent=1&chain=84532` renders.+- Uploading the sample report → hash matches what `hashReport()` computes.+- Submit flow triggers wallet, sends tx.+- `npm run build` clean.++## Reporting++Validation report schema frozen, IPFS gateway used for pinning, any mismatch between `hashReport()` algorithm and the client-side hash.diff --git a/prompts/complete/07-avatar-regenerate.md b/prompts/complete/07-avatar-regenerate.mdnew file mode 100644index 000000000..374778f69--- /dev/null+++ b/prompts/complete/07-avatar-regenerate.md@@ -0,0 +1,77 @@+# 07 — Avatar regenerate endpoint + UI++## Why++Band 3 gap: editor has material / mesh / texture tools but no "regenerate" path (re-mesh, re-texture, re-rig from a new prompt or reference photo). Real regen needs an ML backend we haven't picked yet — so this prompt ships the **seam**: an API contract, a UI panel, and a config-driven provider stub.++When an ML provider is chosen later, wiring it in is one config change. Until then, the endpoint returns `501 Not Implemented` with a clear message; the UI shows a disabled-but-visible panel explaining the roadmap.++## What to build++### 1. API contract++Create `api/avatars/regenerate.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.+- 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.+- 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).++### 2. Status endpoint++Create `api/avatars/regenerate-status.js`:++- `GET /api/avatars/regenerate-status?jobId=<id>` — auth required.+- Returns `{ ok: true, jobId, status: 'queued'|'running'|'done'|'failed', resultAvatarId?, error? }`.+- Stub provider always returns `done` with `resultAvatarId = sourceAvatarId` (no-op round-trip).++### 3. UI panel++Create `src/editor/regenerate-panel.js` — a UI panel that:++- Exports `mountRegeneratePanel(container, { avatarId, onResult })`.+- Renders a form: mode select, freeform params textarea (JSON), submit button.+- POSTs to `/api/avatars/regenerate`, polls `/regenerate-status` every 3s until terminal.+- On 501 error, shows an inline disabled banner: "Regeneration is not yet live. Join the waitlist." (link is a `mailto:` or your feedback issue — pick one and document).+- JSDoc the public API.++**Don't auto-mount this panel into the main editor.** That's a wiring step the operator does later in one line. Export the mount function and document how to call it.++### 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.++## Files you own++- Create: `api/avatars/regenerate.js`+- Create: `api/avatars/regenerate-status.js`+- Create: `api/avatars/REGENERATE.md`+- Create: `src/editor/regenerate-panel.js`++## Files off-limits++- `api/avatars/*` existing files — don't touch.+- `src/editor/*` existing files — don't touch. The new panel is a standalone module consumers can mount.++## Acceptance++- `POST /api/avatars/regenerate` with no auth → 401.+- With auth + `AVATAR_REGEN_PROVIDER` unset → 501 with `{ error: 'regen-unconfigured' }`.+- With `AVATAR_REGEN_PROVIDER=stub` → returns jobId; status endpoint goes `queued` → `done`.+- `node --check` passes on every new JS.+- `npm run build` clean.++## Reporting++Files created, endpoint contract finalized, provider plug shape documented, list of candidate ML providers with rough cost-per-generation if known (optional research).diff --git a/prompts/complete/08-register-prep-endpoint.md b/prompts/complete/08-register-prep-endpoint.mdnew file mode 100644index 000000000..a1e7d2f97--- /dev/null+++ b/prompts/complete/08-register-prep-endpoint.md@@ -0,0 +1,67 @@+# 08 — Server-side registration prep endpoint++## Why++Registration today is 100% client-side: [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js) builds the JSON, pins to IPFS, calls the contract. That works but requires the client to hold pinning tokens (web3.storage / Filebase) — which means either shipping them publicly (bad) or forcing each user to bring their own.++This prompt ships a server-side **prep** endpoint that does the non-signing steps — build canonical JSON, pin to IPFS — and returns the CID. The client then only has to sign the `registerAgent(owner, metadataURI)` transaction.++## What to build++### 1. Endpoint++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.+- 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.)+- Return `{ ok: true, cid, metadataURI: 'ipfs://<cid>', prepId }`.++Rate-limit via `limits.authedWrite`. Never log the full payload body (may contain PII).++### 2. Confirm endpoint++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 }`.+- Returns `{ ok: true, agentId }`.++This closes the loop without ever needing a private key on the server.++### 3. Docs++Create `api/agents/REGISTER_FLOW.md` — sequence diagram (ascii is fine), endpoints involved, what the client has to do (prep → sign → confirm).++## Files you own++- Create: `api/agents/register-prep.js`+- Create: `api/agents/register-confirm.js`+- Create: `api/agents/REGISTER_FLOW.md`+- Create: `scripts/sql/<timestamp>-create-agent-registrations-pending.sql` (only if the table doesn't exist — check via `Grep` in `scripts/sql/` first)++## Files off-limits++- `src/erc8004/agent-registry.js`, `src/ipfs.js`, `api/_lib/*` — read-only.+- Any other `api/agents/*.js` — read-only. If you need to read the schema, do it via grep, not editing.++## Acceptance++- `POST /api/agents/register-prep` unauth → 401.+- Authed + valid body → 200 + cid + `ipfs://` URI; fetching that URI returns the pinned JSON.+- `POST /api/agents/register-confirm` with a fake txHash → rejected by receipt verification.+- `node --check` passes.+- `npm run build` clean.++## Reporting++IPFS pinning backend used, any schema changes needed (with the migration SQL included in PR), what happens if `agent_registrations_pending` doesn't exist yet.diff --git a/prompts/complete/09-cz-landing-claim.md b/prompts/complete/09-cz-landing-claim.mdnew file mode 100644index 000000000..f6678bb18--- /dev/null+++ b/prompts/complete/09-cz-landing-claim.md@@ -0,0 +1,109 @@+# 09 — CZ landing page + claim flow++## Why++cz-demo is the ship target. [prompts/cz-demo/](../cz-demo/) has the task list but nothing is shipped. Task 01 (pre-register onchain) requires a real broadcast tx — **out of scope for this prompt**. We can still ship everything around it so the moment the tx fires, the demo is live.++This prompt builds the landing page + claim flow that reads state from chain (or from a stub JSON when chain is not yet live).++## What to build++### 1. Landing page++Create `public/cz/index.html`:++- Full-bleed dark theme.+- Centered `<agent-3d>` loading `/avatars/cz.glb` (pre-baked, already in repo).+- Headline, subhead, single CTA: **"Claim CZ"** (opens claim flow) + secondary: **"Copy embed"**.+- Footer shows chain + agentId + metadata-URI (read from `public/cz/state.json` if present, fall back to "Not yet onchain" placeholder).+- Meets accessibility basics: semantic headings, `aria-label` on CTAs, focus ring visible.++### 2. State source++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"+}+```++When task 01 from `prompts/cz-demo/` is run, it writes over this file. For now, ship the stub so the landing page behaves deterministically in CI.++### 3. Claim flow module++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? })+}++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.++### 4. Embed snippet++The embed-copy CTA writes this to clipboard:++```html+<agent-3d agent="cz" chain="84532" src="/avatars/cz.glb" eager></agent-3d>+<script src="https://3dagent.vercel.app/dist-lib/agent-3d.umd.cjs"></script>+```++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`+- `claim_tx_sent`+- `claim_complete`+- `embed_copied`++Don't wire a real analytics provider — keep it as a custom event anyone can hook.++### 6. Routing++`public/cz/` is served at `/cz/` by default. If you want `/cz` without a trailing slash to also work, that requires `vite.config.js` / `vercel.json` edits — **skip that.** Document in the README that operators should add the route in a follow-up.++Also create `public/cz/README.md` with the above note + copy-paste lines for when the operator is ready.++## Files you own++- Create: `public/cz/index.html`+- Create: `public/cz/state.json`+- Create: `public/cz/boot.js`+- Create: `public/cz/README.md`+- Create: `src/cz-flow.js`++## Files off-limits++- `prompts/cz-demo/*` — those are task specs, read-only.+- `src/erc8004/*`, `src/agent-*.js`, `src/element.js` — read-only.+- `vite.config.js`, `vercel.json` — skip routing edits; document instead.++## Acceptance++- `http://localhost:3000/cz/` renders the landing page, avatar loads from `/avatars/cz.glb`.+- "Claim CZ" button works in `pre-onchain` state (shows explainer modal).+- "Copy embed" copies a valid snippet to clipboard.+- `node --check src/cz-flow.js` passes.+- `npm run build` clean.++## Reporting++Files shipped, state.json schema frozen, claim-flow behavior in each `status` branch, analytics events wired, accessibility checklist run.diff --git a/prompts/complete/10-cz-runbook.md b/prompts/complete/10-cz-runbook.mdnew file mode 100644index 000000000..868ec5186--- /dev/null+++ b/prompts/complete/10-cz-runbook.md@@ -0,0 +1,74 @@+# 10 — CZ demo runbook + fallback kit++## Why++[prompts/cz-demo/05-demo-script-and-fallbacks.md](../cz-demo/05-demo-script-and-fallbacks.md) describes a runbook that doesn't exist yet. This prompt ships **only the runbook + offline fallback kit** — documentation and shell-level tooling. No UI code. No on-chain broadcast.++When the operator demos the product, they follow this runbook. When the internet dies mid-demo, the fallback kit keeps the show running.++## What to build++### 1. The runbook++Create `docs/CZ_DEMO_RUNBOOK.md` with sections:++- **T-24h**: what to verify (all `prompts/complete/*` merged, staging URL up, wallet seeded with gas on Base Sepolia, IPFS pin healthy).+- **T-1h**: health-check script (`scripts/cz-demo/runbook.sh check`) runs, outputs pass/fail per item.+- **Demo sequence**: 9-step walk-through with exact clicks, spoken script, and expected screen state. Time each step. Total ≤ 5 minutes.+- **Fallbacks**: what to do if the chain is slow (pre-recorded tx video); if IPFS is slow (local-pin fallback); if LobeHub breaks (switch to our hosted iframe); if wallet fails (pre-connected Privy session).+- **Recovery**: how to bail gracefully — one slide, one message, no scrambling.+- **Post-demo**: what to capture (tx hashes, agentId, Q&A, gotchas). Where to file it.++### 2. Health-check script++Create `scripts/cz-demo/runbook.sh`:++```bash+#!/usr/bin/env bash+# Usage: scripts/cz-demo/runbook.sh {check|warm|stop}++check # curls /api/health, /api/agents/cz, /cz/state.json, verifies tx on chain+warm # hits all demo URLs to warm caches+stop # disables public traffic (sets a feature flag or similar) — stub for now+```++Exit code 0 = all good, non-zero = at least one fail. Log output in human-readable form, no JSON noise.++### 3. Offline fallback kit++Create `public/cz/offline/index.html` — a single page that works with no network:++- Embeds `/avatars/cz.glb` (already in repo, served from origin).+- Shows a pre-rendered "claim successful" state (static screenshot as fallback `<img>`).+- Loop of 30-second pre-recorded interaction video (use an existing asset if one exists; otherwise note in reporting that a video asset is needed).++The operator can open `/cz/offline/` if the live demo fails and still look competent.++### 4. Failure rehearsal checklist++Create `docs/CZ_DEMO_FAILURE_MODES.md` — a table of every conceivable failure, the symptom, the recovery path, the time cost. Filled with at least 10 rows.++## Files you own++- Create: `docs/CZ_DEMO_RUNBOOK.md`+- Create: `docs/CZ_DEMO_FAILURE_MODES.md`+- Create: `scripts/cz-demo/runbook.sh`+- Create: `public/cz/offline/index.html`+- Create: `public/cz/offline/README.md`++## Files off-limits++- `public/cz/index.html`, `public/cz/state.json`, `public/cz/boot.js`, `src/cz-flow.js` — those are prompt 09's files. Read them if they exist, but don't edit.+- `prompts/cz-demo/*` — read-only.+- Everything else in `public/`, `src/`, `api/` — off-limits.++## Acceptance++- `bash scripts/cz-demo/runbook.sh check` runs (may exit non-zero if real env not set up; exit behavior documented).+- `docs/CZ_DEMO_RUNBOOK.md` exists, every step has expected-screen + spoken-script.+- `public/cz/offline/index.html` renders the avatar at `/cz/offline/` with zero network calls to third parties (served from origin only).+- `chmod +x` set on `runbook.sh`.++## Reporting++Runbook step count + total estimated demo time, failure modes table row count, whether pre-recorded assets (video / screenshots) exist or are TBD, known runbook gaps that need a live rehearsal to refine.diff --git a/prompts/complete/11-agents-directory.md b/prompts/complete/11-agents-directory.mdnew file mode 100644index 000000000..9c30849bb--- /dev/null+++ b/prompts/complete/11-agents-directory.md@@ -0,0 +1,75 @@+# 11 — Public agents directory++## 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.++A public directory makes the ecosystem feel alive, lets users discover agents, and is the natural surface to paginate on-chain registrations.++## What to build++### 1. Page++Create `public/agents/index.html`:++- Grid of agent cards: avatar thumbnail (iframe into `<agent-3d>` or a still PNG if available), name, short description, chain badge, registration date, click → `/agent/<id>`.+- Search box: filters by name / id / chain.+- Chain filter chips: All / Base / Base Sepolia / Optimism / Polygon.+- Sort: newest, most-reviewed, alphabetical.+- Pagination (30 per page, URL param `?page=2`).++### 2. Data++Source data from two places:++- **Local backend**: `GET /api/agents` — list endpoint. Check [api/agents/](../../api/agents/) — if a list endpoint already exists, consume it. If not, skip this branch and just use on-chain data. **Don't** create a new `/api/agents` list endpoint (that could conflict with prompt 08).+- **On-chain fallback**: if `/api/agents` isn't available, call `IdentityRegistry` for the latest N agents via a read-only RPC (use the ABI from [src/erc8004/abi.js](../../src/erc8004/abi.js)). Paginate by `agentId` descending.++### 3. Controller++Create `src/agents-directory.js`:++```js+export class AgentsDirectory {+ constructor(container)+ async load({ chain, search, sort, page })+ onCardClick(fn)+}+```++- Caches fetched pages in memory (SWR-style, 60s TTL).+- Uses `IntersectionObserver` to lazy-load avatar thumbnails.++### 4. Card component++Each card should be plain HTML, no framework. Use `loading="lazy"` on images. Every card has a stable `data-agent-id` attr for QA.++### 5. Empty state++If no agents exist yet (likely, pre-launch): show a friendly empty-state with a **"Register yours"** CTA → `/register` (which exists? if not, just link to `/create`).++## Files you own++- Create: `public/agents/index.html`+- Create: `public/agents/boot.js`+- Create: `public/agents/README.md`+- Create: `src/agents-directory.js`++## Files off-limits++- Everything under `api/agents/` — read-only. If a list endpoint doesn't exist, use on-chain fallback; do **not** create a list endpoint.+- `src/erc8004/*` — read-only.+- `public/explore/*` — different feature, don't touch.++## Acceptance++- `http://localhost:3000/agents/` renders without JS errors.+- Empty-state shows when backend returns `[]`.+- Filter / sort / search all work client-side on the already-fetched page.+- Pagination URL is shareable (refresh lands on the same page).+- Lighthouse accessibility score ≥ 90 (describe quickly).+- `npm run build` clean.++## Reporting++Data source used (backend vs on-chain), pagination approach, any endpoint assumptions you made and want verified, accessibility audit summary.diff --git a/prompts/complete/MATRIX.md b/prompts/complete/MATRIX.mdnew file mode 100644index 000000000..b55767b75--- /dev/null+++ b/prompts/complete/MATRIX.md@@ -0,0 +1,44 @@+# Parallel-safety Matrix++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 |++## Read-only (shared) modules — do not modify++- `src/erc8004/*` — ABIs, registration helpers, queries.+- `src/agent-*.js` — runtime (protocol, identity, memory, avatar, home).+- `api/_lib/*` — db, http, auth, cors, limits.+- `api/auth/siwe/*` — SIWE endpoints (prompt 01 consumes nonce + verify only).+- `src/account.js` — auth hint helpers.+- `src/manifest.js` — agent manifest loader.+- `contracts/*` — Solidity sources + deployment scripts (read-only; do not edit ABIs).++## Files no one may edit++- `vite.config.js` — if your prompt needs a route, create it under `public/<name>/index.html` so it's served by default. If you truly need a top-level file rewrite, stop and report.+- `vercel.json` — same rule.+- `package.json` — no new deps unless the prompt explicitly says so.+- `.env.example` — document any new env vars in your prompt's README instead.diff --git a/prompts/complete/README.md b/prompts/complete/README.mdnew file mode 100644index 000000000..7a0d260fa--- /dev/null+++ b/prompts/complete/README.md@@ -0,0 +1,31 @@+# Completion Sprint — Parallel Prompts++11 self-contained prompts designed to push every priority band toward 100%. **All can be run in parallel** — each prompt owns a distinct set of files. If one fails or stalls, the others still merge cleanly.++## Why these files don't collide++Each prompt only creates new files under a unique path, or edits exactly one file that no sibling prompt touches. The conflict matrix is in [MATRIX.md](MATRIX.md).++## 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` |++## House rules++- ESM only, tabs (4-wide), single quotes, vhtml JSX, JSDoc for public APIs.+- `node --check` every JS file modified. `npm run build` before reporting done.+- Reporting block at the end: files touched, commands run, what was skipped.+- **Do not** edit files outside your prompt's "Files you own" list. If you need to, stop and report.+- **Never** run `forge script --broadcast` or any tx-broadcasting command.diff --git a/prompts/parallel-finish/01-siwe-csrf-hardening.md b/prompts/parallel-finish/01-siwe-csrf-hardening.mdnew file mode 100644index 000000000..3d965732b--- /dev/null+++ b/prompts/parallel-finish/01-siwe-csrf-hardening.md@@ -0,0 +1,44 @@+# Task: Add CSRF protection to SIWE verify + tighten nonce entropy++## Context++Repo root: `/workspaces/3D-Agent`. Read [/CLAUDE.md](../../CLAUDE.md) and [api/CLAUDE.md](../../api/CLAUDE.md) first.++The SIWE flow at [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) is functionally correct but missing CSRF protection. `api/_lib/auth.js` already exports `verifyCsrfToken` — it is imported nowhere in `api/auth/siwe/*`. Nonce entropy in [api/auth/siwe/nonce.js](../../api/auth/siwe/nonce.js) is ~95 bits (16 alphanumeric chars); spec calls for ≥128.++## Files you own (exclusive)++- [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js)+- [api/auth/siwe/nonce.js](../../api/auth/siwe/nonce.js)++**Do not edit anything else.** If you discover a bug elsewhere, note it in your report; do not fix it.++## Deliverable++1. `verify.js` — call `verifyCsrfToken(req)` (from `api/_lib/auth.js`) at the top of the POST handler, before body parsing. Return `error(res, 403, 'invalid_request', 'CSRF check failed')` on fail.+2. `nonce.js` — bump alphabet length to 22 chars (≈128 bits). Keep the same alphabet set.+3. `nonce.js` — return a fresh CSRF token in the response body (`{ nonce, issuedAt, expiresAt, csrf }`). Use `issueCsrfToken(res)` from `api/_lib/auth.js` — it already sets the cookie, you just echo the token in JSON for the client.+4. Update [public/wallet-login.js](../../public/wallet-login.js) **only** to read `csrf` from the nonce response and send it as `x-csrf-token` header on the verify POST. This is the one allowed cross-file edit; restrict yourself to the two lines needed.++## Out of scope++- Do not change the SIWE parser.+- Do not change session cookie logic.+- Do not add new rate-limit presets.++## Verification++```bash+node --check api/auth/siwe/verify.js+node --check api/auth/siwe/nonce.js+node --check public/wallet-login.js+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.++## Report back++Files changed, both commands run + output, any edge case you noticed in the SIWE parser (note, don't fix).diff --git a/prompts/parallel-finish/02-sessions-management.md b/prompts/parallel-finish/02-sessions-management.mdnew file mode 100644index 000000000..a54440f2d--- /dev/null+++ b/prompts/parallel-finish/02-sessions-management.md@@ -0,0 +1,72 @@+# Task: Sessions API + "sign out everywhere" page++## Context++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.++## Files you own (exclusive — create all as new files)++- `api/auth/sessions/index.js` — `GET /api/auth/sessions` lists current user's sessions, `DELETE /api/auth/sessions` revokes all except the current one.+- `api/auth/sessions/[id].js` — `DELETE /api/auth/sessions/:id` revokes a single session (must belong to caller).+- `public/dashboard/sessions.html` — standalone page that renders the session list, each with user-agent + IP + last-seen + a revoke button. "Sign out of all other devices" button at top. Uses fetch + vanilla JS, no framework. Style with inline `<style>` that matches the existing dashboard aesthetic (see [public/dashboard/index.html](../../public/dashboard/index.html) for color tokens: `--accent: #6a5cff`, `--border: #22222e`, `--bg: #0b0b10`, `--panel: #14141c`).++**Do not edit anything else.** No changes to `dashboard.js`, `dashboard/index.html`, or the sidebar. The page is reachable at `/dashboard/sessions.html` directly.++## Conventions (from api/CLAUDE.md)++- Import `sql` from `api/_lib/db.js` — never `new Pool()`.+- Use `json()` / `error()` / `wrap()` from `api/_lib/http.js`.+- Use `getSessionUser()` from `api/_lib/auth.js` for auth. Return `401 unauthorized` if absent.+- Tagged-template SQL only — no concat.+- ESM, tabs (4-wide), single quotes.++## Deliverable details++### `api/auth/sessions/index.js`++```+GET → { sessions: [{ id, user_agent, ip, created_at, last_seen_at, current: bool }], ... }+DELETE → { revoked: N } — deletes all sessions for the user except the one matching the current cookie.+```++Identify "current" by the token cookie's session id (expose via `getSessionUser` extended return, or read cookie directly with the existing helper in `api/_lib/auth.js`).++### `api/auth/sessions/[id].js`++```+DELETE → { revoked: 1 | 0 }+```++Must 404 if the session doesn't belong to the user. Must 400 if `id` is not a UUID.++### `public/dashboard/sessions.html`++- Auth check on load (`fetch('/api/auth/me')` — redirect to `/login?next=/dashboard/sessions.html` on 401).+- Table: user-agent (truncated), IP, last seen (relative time), created (absolute), actions.+- Current session row marked with a `This device` pill; revoke disabled.+- "Sign out everywhere else" button fires `DELETE /api/auth/sessions`.+- Per-row revoke fires `DELETE /api/auth/sessions/:id`.+- On revoke, remove row optimistically + show a toast. Error path restores row.++## Out of scope++- Do not add a link from the main dashboard sidebar — that's a later integration step.+- Do not change the schema (the `sessions` table already has all needed columns).+- Do not implement a "name this device" feature.++## Verification++```bash+node --check api/auth/sessions/index.js+node --check api/auth/sessions/[id].js+npx prettier --write api/auth/sessions/index.js api/auth/sessions/[id].js public/dashboard/sessions.html+npm run build+```++Manually: visit `/dashboard/sessions.html`, confirm your current session appears and "sign out everywhere" revokes others.++## Report back++Files created, commands run, any assumption made about the current-session identifier mechanism.diff --git a/prompts/parallel-finish/03-privy-backend-verify.md b/prompts/parallel-finish/03-privy-backend-verify.mdnew file mode 100644index 000000000..a7310b9ef--- /dev/null+++ b/prompts/parallel-finish/03-privy-backend-verify.md@@ -0,0 +1,61 @@+# Task: Server-side Privy JWT verification endpoint++## Context++Repo root: `/workspaces/3D-Agent`. Read [/CLAUDE.md](../../CLAUDE.md) and [api/CLAUDE.md](../../api/CLAUDE.md) first.++Today the Privy client path ([public/wallet-login.js](../../public/wallet-login.js)) uses Privy only to surface wallet providers; the trust chain remains raw SIWE. We want a second supported flow: a user with a Privy session can mint a 3D-Agent session by presenting their Privy identity token server-side, without running SIWE again. This avoids an extra wallet signature for returning users.++Privy provides a verifier — their JWKS endpoint is at `https://auth.privy.io/api/v1/apps/{APP_ID}/jwks.json`. The identity token is sent as a bearer header.++## Files you own (exclusive — all new)++- `api/auth/privy/verify.js` — `POST /api/auth/privy/verify` — accepts `{ idToken }` in body, verifies against Privy JWKS, extracts the linked wallet address, find-or-creates the user + `user_wallets` record, issues a 3D-Agent session cookie.+- `api/_lib/privy.js` — JWKS fetch + cache + JWT verification helper. Exported `verifyPrivyIdToken(token) → { userId, walletAddress, email?, iat, exp }`.++**Do not edit** `api/_lib/auth.js`, `public/wallet-login.js`, or any SIWE file. If you need a helper that's almost-but-not-quite in `api/_lib/auth.js`, duplicate the tiny bit you need into `api/_lib/privy.js`.++## Conventions (from api/CLAUDE.md)++- `sql` from `api/_lib/db.js`.+- `json()` / `error()` / `wrap()` / `cors()` from `api/_lib/http.js`.+- Use the existing `createSession` from `api/_lib/auth.js` (this is an import-only use, not an edit).+- ESM, tabs (4-wide), single quotes. No TypeScript.+- Validate input with Zod (already a dep — see other endpoints for pattern).++## Requirements++1. **JWKS cache.** In-process Map keyed by `kid`. TTL 60 min. Refresh on cache miss.+2. **JWT verification.** Use `jose` (already in `node_modules` — verify, else fall back to hand-rolled with `crypto.verify()`). Algorithm: ES256 (Privy's choice). Issuer: `privy.io`. Audience: the `PRIVY_APP_ID` env var.+3. **Rate limit.** Use `limits.authIp(ip)` from `api/_lib/rate-limit.js`.+4. **User resolution.** Privy `sub` → `user_wallets.privy_user_id` (add this column if missing; schema file is `api/_lib/schema.sql` — **do not edit the schema**, instead check for the column and if missing, return a clear 501 with `schema_migration_required`). The user's wallet address is in the `linked_accounts` claim under `type: 'wallet'`.+5. **Session issuance.** Reuse `createSession(res, userId)` from `api/_lib/auth.js`.+6. **Response shape.** `{ user: { id, email }, wallet: { address, chain_id } }`.+7. **Errors.** Return typed error codes: `invalid_token`, `expired_token`, `wrong_audience`, `no_wallet_linked`, `schema_migration_required`.++## Out of scope++- Do not add the Privy flow to the login page UI (that's a separate integration step).+- Do not change `PRIVY_APP_ID` env resolution logic elsewhere.+- Do not implement email-only Privy sessions (wallet-less). Return `no_wallet_linked` if the Privy token has no wallet.++## Verification++```bash+node --check api/auth/privy/verify.js+node --check api/_lib/privy.js+npm run build+```++Manual smoke test (assuming you have a Privy dev tenant):++```+curl -X POST localhost:3000/api/auth/privy/verify -H 'content-type: application/json' \+ -d '{"idToken":"<paste>"}'+```++Expected: 200 + `Set-Cookie: __Host-sid=...` and JSON body; 401 `invalid_token` on a garbage token.++## Report back++Files created, verification output, whether `user_wallets.privy_user_id` exists today (check schema file to determine — do not add it), and what env vars this endpoint needs (`PRIVY_APP_ID`, any others).diff --git a/prompts/parallel-finish/04-link-wallet-api.md b/prompts/parallel-finish/04-link-wallet-api.mdnew file mode 100644index 000000000..3df439e72--- /dev/null+++ b/prompts/parallel-finish/04-link-wallet-api.md@@ -0,0 +1,73 @@+# Task: Link multiple wallets to one account — API + standalone page++## Context++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 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).++## Files you own (exclusive — all new)++- `api/auth/wallets/index.js` — `GET` list wallets, `POST` link a new wallet (takes `{ address, message, signature }`).+- `api/auth/wallets/[address].js` — `DELETE` unlink (refuses to remove the last wallet if it's the primary auth method).+- `api/auth/wallets/nonce.js` — `POST` issue a link-nonce for the authenticated user. Separate from the login nonce because the threat model is different (caller is already authenticated, but we still need replay protection).+- `public/dashboard/wallets.html` — standalone page listing linked wallets + "Link another wallet" button. Uses MetaMask directly via `window.ethereum` — no Privy dependency. Reuses the color palette from [public/dashboard/index.html](../../public/dashboard/index.html).++**Do not edit** `dashboard.js`, `dashboard/index.html`, or any existing SIWE file.++## Conventions++- ESM, tabs, single quotes, 100-col. No TS.+- `sql` from `api/_lib/db.js`; `json()` / `error()` from `api/_lib/http.js`.+- Auth via `getSessionUser()` from `api/_lib/auth.js`.+- Signature verify via `ethers.verifyMessage` (already a dep).+- Nonce storage: reuse the existing `siwe_nonces` table with a `purpose` discriminator — check if column exists in schema file; if not, use a separate in-memory Map (TTL 5 min) and document the limitation in your report.++## Endpoints++### `POST /api/auth/wallets/nonce` (authenticated)++Input: `{}`. Output: `{ nonce, message }` — `message` is the exact string the wallet must sign. Include `issuedAt`, `domain`, `address: null` (filled by client), and a human-readable purpose line `Link this wallet to 3D Agent account <email>`.++### `GET /api/auth/wallets`++Output: `{ wallets: [{ address, chain_id, created_at, is_primary: bool }] }`. Primary = oldest row for this user, or whichever has `is_primary = true` if you want to add that column (don't — just derive).++### `POST /api/auth/wallets` (authenticated)++Input: `{ address, signature, nonce }`. Verify signature recovers `address`, nonce is unused and was issued to this user. Insert row (ignore conflict on `(user_id, address)`). Output: `{ wallet }`.++### `DELETE /api/auth/wallets/:address`++Refuse if it's the only wallet AND user has no other auth method (email+password). Else delete. Output: `{ removed: true }`.++## `public/dashboard/wallets.html`++- Auth check on load.+- Table: address (truncated + copy button), chain, linked at, primary pill, unlink button.+- "Link another wallet" button triggers MetaMask request → fetch nonce → sign → POST → reload list.+- No framework. Reuse the exact color tokens from `dashboard/index.html`.++## Out of scope++- Do not touch the login flow.+- Do not integrate into the dashboard sidebar (separate integration step).+- Do not handle WalletConnect — MetaMask-only for this task.++## Verification++```bash+node --check api/auth/wallets/index.js+node --check api/auth/wallets/[address].js+node --check api/auth/wallets/nonce.js+npx prettier --write api/auth/wallets/*.js public/dashboard/wallets.html+npm run build+```++Manually in a browser, visit `/dashboard/wallets.html` while logged in, link a second MetaMask account, confirm it appears.++## Report back++Files created, commands + output, whether you used `siwe_nonces` or in-memory nonces and why.diff --git a/prompts/parallel-finish/05-first-meet-flow.md b/prompts/parallel-finish/05-first-meet-flow.mdnew file mode 100644index 000000000..f2996a037--- /dev/null+++ b/prompts/parallel-finish/05-first-meet-flow.md@@ -0,0 +1,57 @@+# Task: "First meet" flow — name, describe, greet the new avatar++## Context++Repo root: `/workspaces/3D-Agent`. Read [/CLAUDE.md](../../CLAUDE.md) and [src/CLAUDE.md](../../src/CLAUDE.md) first.++After the selfie pipeline produces a GLB and it's saved via `saveRemoteGlbToAccount` in [src/create.js](../../src/create.js), the user lands in the viewer with no identity step. We want a short onboarding: **name your avatar, give it a one-line bio, hear it greet you**. This becomes the user's first emotional moment with their agent.++This task builds a **standalone page** at `/first-meet/?avatar=<id>` so it doesn't interfere with the main app's hash-routing. A later integration step will redirect users here from `saveRemoteGlbToAccount` success.++## Files you own (exclusive — all new)++- `public/first-meet/index.html` — the page shell.+- `public/first-meet/first-meet.js` — the flow logic.+- `public/first-meet/styles.css` — optional; inline styles in HTML are also fine.++**Do not edit** `src/create.js`, `src/app.js`, or the dashboard. The redirect-to-first-meet hook is out of scope.++## Flow++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?"*.+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`).++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).++## Constraints++- No framework. Vanilla JS, one file max for logic, one HTML file for shell.+- Reuse the dashboard's color palette (check [public/dashboard/index.html](../../public/dashboard/index.html) `:root`).+- Use `<model-viewer>` from the existing CDN: `https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js`.+- The `<agent-3d>` element is served from `/dist-lib/agent-3d.js` after `npm run build:lib`. In dev, that path may not exist yet; gracefully fall back to a `<model-viewer>` with no TTS and a plain text greeting bubble.++## Out of scope++- Do NOT auto-redirect users here from the save-avatar flow (that's an integration step).+- Do NOT edit `src/create.js`.+- Do not add authentication logic beyond a simple redirect — reuse the existing `/api/auth/me` pattern.+- Do not write a component library.++## Verification++```bash+node --check public/first-meet/first-meet.js+npx prettier --write public/first-meet/*+npm run build+```++Manually: `npm run dev`, go to `http://localhost:3000/first-meet/?avatar=<id-of-an-existing-avatar>`, walk through the 5 steps.++## Report back++Files created, commands run, what fallback behavior kicks in when `/dist-lib/agent-3d.js` isn't built, what PATCH / POST shapes you actually sent.diff --git a/prompts/parallel-finish/06-selfie-progress-ui.md b/prompts/parallel-finish/06-selfie-progress-ui.mdnew file mode 100644index 000000000..f272eddbb--- /dev/null+++ b/prompts/parallel-finish/06-selfie-progress-ui.md@@ -0,0 +1,67 @@+# Task: Granular progress UI for the selfie → avatar pipeline++## Context++Repo root: `/workspaces/3D-Agent`. Read [src/CLAUDE.md](../../src/CLAUDE.md) first.++Today the selfie submit button shows "Sending…" while the server does 10–30s of work against the Avaturn API (see [src/selfie-pipeline.js](../../src/selfie-pipeline.js) and [src/selfie-capture.js](../../src/selfie-capture.js)). Users think it's broken and refresh. We want a clear 5-stage progress UI.++## Files you own (exclusive)++- [src/selfie-pipeline.js](../../src/selfie-pipeline.js)+- [src/selfie-capture.js](../../src/selfie-capture.js)++**Do not edit** any `api/` file, any other `src/` file, or add new files outside those two.++## Stages to surface++1. `compressing` — images are being downscaled (usually < 2s).+2. `uploading` — POST to `/api/onboarding/avaturn-session` in flight.+3. `queued` — server accepted, waiting for Avaturn response.+4. `building` — Avaturn is generating (this is where the real time goes).+5. `ready` — session URL received, redirecting to the Avaturn iframe.++Stages 3–4 are inferred client-side from elapsed time because the current backend returns once, not a stream. Use these heuristics:++- After POST returns successfully with a session URL, we jump straight to `ready`.+- If POST is in flight more than 2s, flip label from `uploading` to `queued`.+- 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.++## UI requirements++- A progress bar with 5 labelled dots, current stage pulsing.+- Elapsed time (MM:SS) under the bar.+- Cancel button disabled during `compressing`/`uploading` (avoids orphan Avaturn sessions), enabled during `queued`/`building`.+- Cancel aborts the fetch via `AbortController`.+- Use the existing `selfie:*` event names or add `selfie:progress` with `{ stage, elapsedMs }`. If you add a new event, emit it only from `selfie-pipeline.js` and consume it in `selfie-capture.js`.++## Conventions++- Tabs, 4-wide, single quotes, 100-col. ESM.+- No new deps.+- Keep the existing event names (`selfie:submit`, `selfie:error`, etc.) — additive only.++## Out of scope++- Do not change the backend endpoint at `api/onboarding/avaturn-session.js`.+- Do not touch the Avaturn SDK wiring in `src/avatar-creator.js`.+- Do not add progress streaming (SSE / WebSocket) — client-side heuristic only.+- Do not redesign the selfie capture UI — progress panel is an addition, not a replacement.++## Verification++```bash+node --check src/selfie-pipeline.js+node --check src/selfie-capture.js+npx prettier --write src/selfie-pipeline.js src/selfie-capture.js+npm run build+```++Manually: `npm run dev`, take a selfie, confirm stages tick through. Throttle network in DevTools to see the `queued` → `building` transitions.++## Report back++Files edited, commands + output, the exact stage transitions you used, what happens on fetch abort.diff --git a/prompts/parallel-finish/07-avatar-agent-link.md b/prompts/parallel-finish/07-avatar-agent-link.mdnew file mode 100644index 000000000..e2dade5a6--- /dev/null+++ b/prompts/parallel-finish/07-avatar-agent-link.md@@ -0,0 +1,60 @@+# Task: Auto-link a new avatar to the user's agent identity++## Context++Repo root: `/workspaces/3D-Agent`. Read [/CLAUDE.md](../../CLAUDE.md) and [api/CLAUDE.md](../../api/CLAUDE.md) first.++Today: a user saves a selfie-derived avatar → a row lands in `avatars`. Separately, `/api/agents/me` auto-creates a default `agent_identities` row. These two are **not linked** — `agent_identities.avatar_id` stays NULL, so the user's agent has no 3D body assigned. This breaks the "my agent" experience end-to-end.++We fix this with a single small endpoint + a tweak to the avatar-create hook.++## Files you own (exclusive)++- [api/avatars/index.js](../../api/avatars/index.js) — only the `POST` handler's success branch; do not refactor the rest.+- `api/onboarding/link-avatar.js` — new file. `POST /api/onboarding/link-avatar` with `{ avatarId }` sets `agent_identities.avatar_id` for the authenticated user's primary agent. Idempotent.++**Do not edit** any other file. Not `api/agents/*`, not `src/*`, not the dashboard.++## Logic++### `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.++Do this inline; do not introduce a job queue or event bus.++### `POST /api/onboarding/link-avatar`++Explicit manual endpoint for clients (e.g., the forthcoming first-meet page) to set the link regardless of conditions. Input: `{ avatarId }`. Auth required. Ownership check: user must own the avatar. Output: `{ agent: { id, avatar_id, updated_at } }`. Returns 404 if the user has no agent. Returns 409 if the agent already has a different avatar and the caller didn't pass `force: true`.++## Conventions++- `sql` from `api/_lib/db.js`.+- `json()` / `error()` from `api/_lib/http.js`.+- Auth via `getSessionUser()`.+- Tagged-template SQL.+- ESM, tabs.+- Zod for input validation (matches sibling endpoints).+- Error codes: `unauthorized`, `not_found`, `already_linked`, `invalid_request`.++## Out of scope++- Do not change the `avatar_id` column itself — it exists in the schema.+- Do not build the UI for this (the client side is handled by `05-first-meet-flow.md`).+- Do not touch `api/agents/me.js` or `api/agents/[id].js`.+- Do not add a "history of avatar changes" log.++## Verification++```bash+node --check api/avatars/index.js+node --check api/onboarding/link-avatar.js+npx prettier --write api/avatars/index.js api/onboarding/link-avatar.js+npm run build+```++Manually: create an avatar with `source: 'selfie'`, check DB that `agent_identities.avatar_id` got set. Then call `/api/onboarding/link-avatar` with a different avatar id, confirm 409 `already_linked` without `force`, and success with `force: true`.++## Report back++Files edited/created, commands + output, the exact SQL you ran in the inline hook, any edge case where the hook might fire wrongly (e.g., multi-agent users).diff --git a/prompts/parallel-finish/08-artifact-bundle.md b/prompts/parallel-finish/08-artifact-bundle.mdnew file mode 100644index 000000000..799d8acef--- /dev/null+++ b/prompts/parallel-finish/08-artifact-bundle.md@@ -0,0 +1,57 @@+# Task: Self-contained "Claude Artifact" bundle — one-file viewer++## Context++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.++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).++## Files you own (exclusive — all new)++- `public/artifact/index.html` — demo page that mirrors what a user would paste inside an Artifact. Used for smoke-testing.+- `public/artifact/snippet.html` — the exact HTML snippet to give users (with `<!-- paste this -->` comments). This is copy-pasted by the dashboard; do not edit the dashboard.+- `src/artifact/entry.js` — the build entry point (IIFE bundle).+- `vite.config.artifact.js` — a second vite config that builds `src/artifact/entry.js` → `dist-artifact/artifact.js` (single file, inline assets).+- `package.json` — add a `build:artifact` script: `vite build --config vite.config.artifact.js`. Do not touch the existing `build` / `build:lib` scripts. **Minimal diff.**++**Do not edit** any other file.++## Bundle requirements++- **Single file**, target ES2020, IIFE format, all deps bundled.+- **Self-booting:** reads config from `<script type="application/json" id="agent3d-config">{"agentId": "...", "theme": "dark"}</script>` or data attributes on the root div (`<div id="agent3d" data-agent-id="..."></div>`).+- **Fetches** `GET /api/agents/:id` from `https://3dagent.vercel.app` (configurable via `data-origin`). Falls back to a `poster` image if the fetch fails.+- **Renders** the GLB with OrbitControls, auto-rotate, basic lighting.+- **Caption line** below the canvas — shows `agent.name`. No chat. No TTS. (Artifacts are a viewer-only surface.)+- **Size budget:** < 500KB gzipped after Three is bundled. If it's bigger, document why.++## 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.++## Out of scope++- Do not implement chat or postMessage inside the artifact bundle.+- Do not touch the main `vite.config.js`.+- Do not add the artifact to the dashboard embed tab (separate integration step).+- Do not implement an auto-deploy — the CI/CD side is a later concern.++## Verification++```bash+node --check src/artifact/entry.js+npm run build:artifact+ls -la dist-artifact/artifact.js+npm run build+```++Manually: serve `dist-artifact/` via `python3 -m http.server 8080`, open `public/artifact/index.html` in a browser with `?agentId=<existing-id>`, confirm the GLB renders.++Paste the contents of `snippet.html` into a real Claude Artifact and confirm it works there too (nice-to-have).++## Report back++Files created, build output size, commands + output, any CSP / CORS issue hit while testing in a real Artifact, dependency audit if any new deps were added (ideally zero).diff --git a/prompts/parallel-finish/09-lobehub-plugin.md b/prompts/parallel-finish/09-lobehub-plugin.mdnew file mode 100644index 000000000..763a82c33--- /dev/null+++ b/prompts/parallel-finish/09-lobehub-plugin.md@@ -0,0 +1,88 @@+# Task: LobeHub plugin package — drop-in agent sidecar++## Context++Repo root: `/workspaces/3D-Agent`. Read [/CLAUDE.md](../../CLAUDE.md) first.++LobeHub is a self-hostable chat UI fork. We want to publish a standalone plugin under `lobehub-plugin/` that users can install into their Lobe fork to get a 3D agent pane that reacts to assistant messages. Today the dashboard only shows a copy-paste React snippet — insufficient for a real plugin.++This is a **new top-level package**, fully isolated from the rest of the monorepo. It does not need to be published to npm in this task; just produce a working, locally-installable TS-React package with a manifest.++## Files you own (exclusive — all new, under `lobehub-plugin/`)++```+lobehub-plugin/+├── package.json+├── tsconfig.json+├── manifest.json # Lobe plugin manifest+├── README.md+├── src/+│ ├── index.ts+│ ├── AgentPane.tsx+│ ├── bridge.ts # postMessage wrapper around /agent/:id/embed+│ └── config-schema.ts # plugin settings schema+└── dist/ # gitignored; produced by build+```++**Do not edit** any other file in the repo.++## Plugin behavior++- **Settings:** `agentId` (string, required) and `apiOrigin` (defaults to `https://3dagent.vercel.app`). Expose these via `config-schema.ts`.+- **Render:** a fixed 320×420 pane (sidebar or floating — Lobe decides) containing an `<iframe>` pointing at `${apiOrigin}/agent/${agentId}/embed`.+- **Bridge:** on Lobe's assistant-message event, call `bridge.speak(text)` which posts `{ __agent: agentId, type: 'action', action: { type: 'speak', payload: { text } } }` to the iframe — matching the FROZEN v1 bridge in [public/agent/embed.html](../../public/agent/embed.html).+- **Lobe hooks used:** `usePluginStore`, `onAssistantMessage`. If the exact API differs, write against what's published in `@lobehub/ui@latest` or `lobehub-plugin-sdk` — if neither exists at time of writing, mock the hooks with clear TODO comments and document in README.+- **TypeScript**, strict. Tabs 4-wide, single quotes (match the rest of the repo style even though this is a TS package).++## `manifest.json` shape++```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" }+ ]+}+```++## `package.json`++- `name: "@3dagent/lobehub-plugin"`+- `private: true` (for now).+- `scripts`: `build` uses `tsc` + a bundler of your choice (esbuild or vite — pick the lighter one). `dev` runs the bundler in watch.+- `devDependencies`: TypeScript, React types, the bundler. No new prod deps beyond React.++## Out of scope++- Do not publish to npm.+- Do not wire this into the repo root `package.json` scripts.+- Do not make it depend on anything in the parent repo's `src/` (it's fully standalone).+- Do not implement memory / skills / wallet features — this plugin is a viewer + speak bridge only.++## Verification++```bash+cd lobehub-plugin+npm install+npm run build+ls -la dist/+cd ..+```++Note: the root `npm run build` is unaffected because this package is not part of the root Vite build.++## Report back++Files created, build output, which Lobe SDK API you wrote against (and whether you mocked it), a copy of the README you wrote.diff --git a/prompts/parallel-finish/10-reputation-ui.md b/prompts/parallel-finish/10-reputation-ui.mdnew file mode 100644index 000000000..5e5c535c5--- /dev/null+++ b/prompts/parallel-finish/10-reputation-ui.md@@ -0,0 +1,55 @@+# Task: Reputation viewing + feedback submission UI++## Context++Repo root: `/workspaces/3D-Agent`. Read [/CLAUDE.md](../../CLAUDE.md), [src/CLAUDE.md](../../src/CLAUDE.md), and [contracts/CLAUDE.md](../../contracts/CLAUDE.md) first.++The ERC-8004 `ReputationRegistry` contract is deployed on 15 mainnet chains and the ethers-v6 client in [src/erc8004/reputation.js](../../src/erc8004/reputation.js) has `submitFeedback`, `getReputation`, `getRecentReviews` — but nothing in the UI surfaces these. We want a **standalone page** at `/reputation/?agent=<chainId>:<agentId>` that:++- Shows the agent's running score + review count.+- Lists the most recent 20 reviews (rating + optional text comment, reviewer address).+- Lets a connected wallet submit a rating (-100..+100) and a short comment. One per address per agent.++## Files you own (exclusive — all new)++- `public/reputation/index.html` — page shell.+- `public/reputation/reputation.js` — page logic. **Imports from `/src/erc8004/reputation.js` via the Vite bundle**, not via a raw `/src/...` URL (which won't resolve in production — see how `agent-home.html` wires its script).+- `src/reputation-page.js` — the Vite entry that `index.html` references. This file imports `reputation.js` and kicks it off.+- `public/reputation/styles.css` — inline in HTML is also fine.+- `vite.config.js` — add the page as a multi-page input. **This is the one shared file you may touch**; add exactly one line to `rollupOptions.input`. If `vite.config.js` doesn't already have a multi-page setup, check other prompts in this folder aren't also modifying it (they aren't — `08-artifact-bundle.md` uses a separate config file); add a `rollupOptions.input` block.++**Do not edit** any other file. Not `src/erc8004/reputation.js` (import only), not the dashboard, not `src/element.js`.++## UI++1. **Load** — parse `?agent=<chainId>:<agentId>` from URL, fetch `/api/agents/:id` if the agent has a backend record, else resolve on-chain only. Show agent name + avatar thumbnail if available.+2. **Score card** — big number (average rating), review count, sparkline of last 30 days.+3. **Review list** — 20 most recent. Each row: reviewer (ENS if resolvable, else truncated address), rating pill (color-coded: red < 0, gray ~0, green > 0), comment (if any), timestamp.+4. **Submit section** — "Connect wallet" button (MetaMask; use `window.ethereum` directly, no Privy). After connect, show a slider (-100..+100) + a 280-char comment box + Submit. Submission calls `submitFeedback` from `src/erc8004/reputation.js`. Disabled if the connected wallet already has a review for this agent (check with `getRecentReviews` filtered to address).++## Constraints++- Tabs, 4-wide, single quotes, ESM. Vanilla JS — no framework.+- Use the dashboard's color palette.+- Do not write a new reputation contract client. Reuse `src/erc8004/reputation.js` as-is.++## Out of scope++- Do not build a `/dashboard` tab for this — standalone page only.+- Do not add a web-component (`<reputation-for agent="...">` is nice but deferred).+- Do not implement validator attestations (that's `ValidationRegistry` — separate prompt `11`).+- Do not add pagination beyond the most-recent-20.++## Verification++```bash+node --check public/reputation/reputation.js+node --check src/reputation-page.js+npm run build+```++Manually: `npm run dev`, open `/reputation/?agent=8453:1` (or any real agent id on Base mainnet). Confirm score + reviews render. Connect MetaMask on Base and submit a review on a testnet agent.++## Report back++Files created, commands + output, your exact `vite.config.js` diff (paste the inserted lines), any RPC/CORS issue hit.diff --git a/prompts/parallel-finish/11-validation-registry-deploy.md b/prompts/parallel-finish/11-validation-registry-deploy.mdnew file mode 100644index 000000000..48387f3e7--- /dev/null+++ b/prompts/parallel-finish/11-validation-registry-deploy.md@@ -0,0 +1,78 @@+# Task: Mainnet deployment script + runbook for `ValidationRegistry`++## Context++Repo root: `/workspaces/3D-Agent`. Read [contracts/CLAUDE.md](../../contracts/CLAUDE.md) first.++`ValidationRegistry.sol` is implemented and tested but **not deployed on any mainnet**. `IdentityRegistry` and `ReputationRegistry` are live on 15 chains (see `REGISTRY_DEPLOYMENTS` in [src/erc8004/abi.js](../../src/erc8004/abi.js)). Those were deployed via CREATE2 so all chains share the same address. We want the same for `ValidationRegistry`.++This task produces the **script + runbook**, not the broadcast itself. Per [/CLAUDE.md](../../CLAUDE.md): **never `forge script --broadcast` without approval.** The user will run the broadcast step themselves after reviewing your work.++## Files you own (exclusive — all new)++- `contracts/script/DeployValidationMainnet.s.sol` — single-purpose deploy script. Uses the same CREATE2 salt pattern as `Deploy.s.sol`. Deploys `ValidationRegistry` with the correct constructor args (check the contract — it takes `identityRegistry` address).+- `docs/VALIDATION_DEPLOY.md` — step-by-step runbook: env vars needed, dry-run command, broadcast command, verification command on each chain's block explorer, post-deploy smoke test, patch to `src/erc8004/abi.js` `REGISTRY_DEPLOYMENTS`.++**Do not edit** `src/erc8004/abi.js` (the runbook instructs the human on how to update it — you don't run the broadcast, so you don't know the address).++**Do not edit** `Deploy.s.sol` or any other Solidity file. If `ValidationRegistry.sol` has an issue, document it in the runbook — do not fix it.++## Script requirements++- 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).+- `forge script ... --rpc-url $RPC --sender $DEPLOYER` as the dry-run. Broadcast is `--broadcast --verify --etherscan-api-key $KEY`.++## Runbook requirements++Target chains (from `contracts/CLAUDE.md` — verify the list):++- Ethereum mainnet+- Base+- Optimism+- Arbitrum One+- Polygon+- BNB Chain+- Avalanche+- Gnosis+- Linea+- Scroll+- zkSync Era+- Mantle+- Celo+- Ink+- Unichain++For each, list:++- RPC URL env var name.+- Etherscan-equivalent verification URL + API key env var.+- Estimated gas cost (order of magnitude — "≈0.01 ETH on L2s").+- Expected deterministic address (compute locally with `cast create2` and include in the runbook).++Include a **rollback section**: since CREATE2 addresses are single-shot, "rollback" means documenting the bad deploy and re-deploying with a new salt. Explain why we want to avoid this.++Include a **patch block** showing exactly what to add to `src/erc8004/abi.js`'s `REGISTRY_DEPLOYMENTS` for each chain.++## Out of scope++- **Do not broadcast.**+- Do not modify the contract source.+- Do not deploy to testnet (if a testnet deploy is missing, note it in the runbook; someone else will do that task).+- Do not implement validator allow-listing at the registry level — that's a post-deploy governance concern.++## Verification++```bash+cd contracts+forge build+forge test+forge script script/DeployValidationMainnet.s.sol --rpc-url https://ethereum-rpc.publicnode.com --sender 0x0000000000000000000000000000000000000001+```++The `forge script` dry-run should compute an address and exit without broadcasting.++## Report back++Files created, `forge test` output, the computed CREATE2 address (from the dry-run), the runbook's total gas-cost estimate across all 15 chains.diff --git a/prompts/parallel-finish/12-hydrate-from-chain.md b/prompts/parallel-finish/12-hydrate-from-chain.mdnew file mode 100644index 000000000..db13abd53--- /dev/null+++ b/prompts/parallel-finish/12-hydrate-from-chain.md@@ -0,0 +1,73 @@+# Task: Hydrate dashboard from on-chain — import ERC-8004 agents owned by connected wallet++## Context++Repo root: `/workspaces/3D-Agent`. Read [/CLAUDE.md](../../CLAUDE.md) and [src/CLAUDE.md](../../src/CLAUDE.md) first.++Today, if a user has already minted an ERC-8004 agent on-chain, signing into 3D Agent does **not** auto-discover it. They have to re-register via `/deploy`, which creates a dupe. We need a "import my on-chain agents" flow.++The crawler at [api/cron/erc8004-crawl.js](../../api/cron/erc8004-crawl.js) indexes all agents into `erc8004_agents_index`. We use that index, filter by owner = user's linked wallets, and offer one-click import.++## Files you own (exclusive — all new)++- `src/erc8004/hydrate.js` — fetch agents for the user's connected wallets, dedupe against existing `agent_identities`, return the delta.+- `api/erc8004/hydrate.js` — `GET /api/erc8004/hydrate` — server-side version that queries `erc8004_agents_index` filtered by the user's `user_wallets` addresses. Returns `{ agents: [{ chainId, agentId, tokenURI, owner, alreadyImported: bool }] }`.+- `api/erc8004/import.js` — `POST /api/erc8004/import` with `{ chainId, agentId }` — creates a local `agent_identities` row pointing at the on-chain record. Idempotent (409 if already imported for this user).+- `public/hydrate/index.html` — standalone page, reachable at `/hydrate/`. Lists discovered agents with avatar thumbnails (resolved from `tokenURI` via `resolveOnChainAgent`), each with an Import button. Connect-wallet prompt if no wallets are linked.++**Do not edit** the crawler, the existing `api/agents/*` endpoints, the dashboard sidebar, or `src/element.js`.++## API details++### `GET /api/erc8004/hydrate`++- Auth required.+- Read user's wallet addresses from `user_wallets`.+- Query `erc8004_agents_index WHERE lower(owner) IN (...)`.+- For each row, check if there's an `agent_identities` row with matching `(erc8004_agent_id, erc8004_agent_id_chain_id, user_id = self)`. Set `alreadyImported`.+- Return shape above.++### `POST /api/erc8004/import`++- 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)).+- 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 } }`.++## Client (`public/hydrate/index.html`)++- Auth check on load.+- "Connect wallet" button if `/api/auth/wallets` returns empty (link the standalone `/dashboard/wallets.html` page if it exists in the deployment).+- List of discovered agents with thumbnail, name, chain badge, Import button.+- On Import success: replace the button with a "Go to agent" link.++## Conventions++- ESM, tabs, single quotes. Vanilla JS.+- `sql`/`json`/`error` helpers. Zod validation on the POST.+- Reuse `resolveOnChainAgent` — do not write a new one.++## Out of scope++- Do not build an "export all my local agents to chain" flow (reverse direction).+- Do not change the crawler schedule or schema.+- Do not integrate into the dashboard sidebar.+- Do not handle multi-chain mirror deduplication (same agentId on multiple chains — treat each (chainId, agentId) as distinct).++## Verification++```bash+node --check src/erc8004/hydrate.js+node --check api/erc8004/hydrate.js+node --check api/erc8004/import.js+npm run build+```++Manually: link a wallet that owns an ERC-8004 agent on Base, open `/hydrate/`, confirm the agent appears, click Import, confirm it lands in `/dashboard`.++## Report back++Files created, commands + output, whether you download+rehost thumbnails or link directly, any chain whose RPC was flaky in testing.diff --git a/prompts/parallel-finish/13-signed-action-log-ui.md b/prompts/parallel-finish/13-signed-action-log-ui.mdnew file mode 100644index 000000000..9af65febd--- /dev/null+++ b/prompts/parallel-finish/13-signed-action-log-ui.md@@ -0,0 +1,63 @@+# Task: Signed action log viewer (standalone page)++## Context++Repo root: `/workspaces/3D-Agent`. Read [/CLAUDE.md](../../CLAUDE.md), [api/CLAUDE.md](../../api/CLAUDE.md), and [src/CLAUDE.md](../../src/CLAUDE.md) first.++The agent has a signed action log: every `speak`, `remember`, `sign`, `skill-done`, `validate`, `load-end` event goes through `POST /api/agent-actions` (fire-and-forget from `agent-identity.js`). The `/api/agents/[id]/sign.js` endpoint produces EIP-191 signatures over each entry. Rows live in `agent_actions`.++There is **no UI** to view this log. We need one — the timeline is the most honest "what has my agent been doing" surface and is a CZ-demo win.++## Files you own (exclusive — new only)++- `public/dashboard/actions.html` — standalone page at `/dashboard/actions.html?agent=<id>`. Renders the action log for one agent with signature verification badges.+- `api/agents/[id]/actions.js` — `GET /api/agents/:id/actions?limit=100&cursor=<ts>` — paginated list of actions. Returns `{ actions: [{ id, type, payload, timestamp, signature, signer, verified: bool }], nextCursor }`.++**Do not edit** `api/agent-actions.js`, `api/agents/[id]/sign.js`, `agent-identity.js`, or the dashboard sidebar.++## Server++### `GET /api/agents/:id/actions`++- Auth required. Caller must own the agent OR the agent must be `visibility = 'public'`.+- Query `agent_actions WHERE agent_id = :id ORDER BY timestamp DESC LIMIT :limit`.+- Cursor is a timestamp (ISO string). Encode/decode as-is — no opaque cursors needed for this volume.+- `verified` is a derived field: check `signature` against `signer` for EIP-191 signed `JSON.stringify(payload) + timestamp`. Use `ethers.verifyMessage`. If no signature stored, `verified: null`.+- Cache-Control: `private, max-age=10`.++## Client++- Auth check on load. `401` → `/login?next=/dashboard/actions.html?agent=<id>`.+- Header: agent name + verified-signer pill (the EOA that signed these actions).+- Filter chips: All, speak, remember, sign, skill-done, validate, load-end.+- Timeline: newest first. Each row has an icon per type, a 1-line summary (type + first 80 chars of payload), a verified checkmark (green) / unverified (gray) / unsigned (dash), a timestamp (relative + absolute on hover), and a click-to-expand JSON payload.+- Infinite scroll via `IntersectionObserver` on the last row.+- Export button: "Download JSON" dumps the current filtered list.++## Constraints++- Vanilla JS. Reuse dashboard color tokens.+- No new runtime deps.+- Use `fetch` with `credentials: 'include'`.++## Out of scope++- 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 add time-range picker beyond the infinite-scroll.+- Do not add CSV export — JSON is enough.++## Verification++```bash+node --check api/agents/[id]/actions.js+npx prettier --write api/agents/[id]/actions.js public/dashboard/actions.html+npm run build+```++Manually: use an agent with stored actions, open `/dashboard/actions.html?agent=<id>`, confirm rows appear with correct verified badges. Flip one signature in the DB and confirm it shows as unverified.++## Report back++Files created, commands + output, your verification logic (exact string you sign/verify), behavior when the DB has no actions yet (should show an empty state, not an error).diff --git a/prompts/parallel-finish/14-ipfs-pinning-real.md b/prompts/parallel-finish/14-ipfs-pinning-real.mdnew file mode 100644index 000000000..444b49e15--- /dev/null+++ b/prompts/parallel-finish/14-ipfs-pinning-real.md@@ -0,0 +1,72 @@+# Task: Make `/api/erc8004/pin` return real IPFS CIDs++## Context++Repo root: `/workspaces/3D-Agent`. Read [contracts/CLAUDE.md](../../contracts/CLAUDE.md) first.++The ERC-8004 registration flow ([src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js)) pins the agent's registration JSON via one of two paths:++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.++## Files you own (exclusive)++- [api/erc8004/pin.js](../../api/erc8004/pin.js) — the only file you edit.++**Do not edit** anything else. Not the client, not the registry, not the crawler.++## Requirements++- **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.+- **Response shape:**++ ```+ { 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.++- **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.++- **Rate limit:** apply `limits.authIp(ip)` from `api/_lib/rate-limit.js`.++- **Auth:** require `getSessionUser()` — this endpoint is not public.++- **Size limit:** enforce 25 MB max (avatar GLBs can legitimately reach ~20 MB). Return `413 payload_too_large` otherwise.++- **Mime validation:** accept `application/json`, `model/gltf-binary`, `image/png`, `image/jpeg`, `image/webp`. Reject others with `415 unsupported_media_type`.++## Non-goals++- Do not remove the existing R2 code entirely — keep it as the final fallback.+- Do not change the Pinata path in [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js).+- Do not introduce a background job to re-pin expired content (web3.storage retains ≥ 30 days by default — document but don't automate).+- Do not add a new DB table to track pinned CIDs. Idempotent by CID is enough.++## Verification++```bash+node --check api/erc8004/pin.js+npm run build+```++Manually (requires a web3.storage token):++```+curl -X POST localhost:3000/api/erc8004/pin \+ -H 'content-type: application/json' \+ -H 'cookie: __Host-sid=...' \+ -d '{"filename":"test.json","content":"{\"hello\":\"world\"}","contentType":"application/json"}'+```++Expected: `{ cid: "bafy...", uri: "ipfs://bafy.../test.json", url: "https://w3s.link/ipfs/bafy.../test.json" }`.++## Report back++File edited, commands + output, which IPFS service you primarily used + why, what happens when all env vars are missing (should still work with R2-only + warning, not 500).diff --git a/prompts/parallel-finish/README.md b/prompts/parallel-finish/README.mdnew file mode 100644index 000000000..4fced9117--- /dev/null+++ b/prompts/parallel-finish/README.md@@ -0,0 +1,34 @@+# Parallel Finish — 14 independent prompts to close the audit gaps++These prompts are designed to run **simultaneously in separate agent chats** with zero inter-task blocking. Each one:++- Creates only new files, OR edits a single file that no other prompt in this folder touches.+- Produces a self-contained deliverable. If any single prompt fails to complete, nothing else breaks.+- Never modifies shared files like [src/element.js](../../src/element.js), [src/app.js](../../src/app.js), [public/dashboard/dashboard.js](../../public/dashboard/dashboard.js), or [public/dashboard/index.html](../../public/dashboard/index.html). Integration of these features into the main dashboard sidebar is a later merge step (see `zz-integration.md`).++## 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) |+| `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` |++## Running them++Open 14 agent chats. In each, paste the corresponding prompt as the first message. Run `npm run verify` when each finishes. Collect reports; merge serially.++## After all are done++Run `zz-integration.md` (written after these land) to wire the new standalone pages into the dashboard sidebar. That single final merge is NOT safe to run in parallel with the 14 — it intentionally touches `public/dashboard/index.html` and `public/dashboard/dashboard.js`.diff --git a/prompts/sprint-100/00-README.md b/prompts/sprint-100/00-README.mdnew file mode 100644index 000000000..d40ea2a98--- /dev/null+++ b/prompts/sprint-100/00-README.md@@ -0,0 +1,48 @@+# Sprint-100 — Parallel-safe prompts to 100%++Every prompt in this folder is designed to run **in parallel** with every other prompt in this folder. No prompt depends on any other prompt completing. Each prompt owns a distinct set of files; where a shared file must be touched, the edit is surgical and additive.++## How to use++- Spin up one agent chat per `.md` file.+- Run them all at once. If one fails or stalls, the others still ship value.+- Each prompt reports what landed + what it skipped. Integration (wiring modules together in `src/app.js`, etc.) is a separate, later step — **do not** wire new modules into `src/app.js` from inside these prompts unless the prompt explicitly says so.++## House rules (every prompt)++1. **Own only the files listed under "Files you own"**. Treat everything else as read-only.+2. **No bundler / build-config changes**. No new runtime deps unless the prompt explicitly lists them.+3. **Prettier** (tabs, 4-wide, single quotes, 100-col) — run `npx prettier --write` on every file you touch.+4. **Verify**: `node --check <file>` on every JS file you modify, then `npm run build`. Paste both outputs into the report.+5. **Report** at the end: files changed, commands run, what you skipped, unrelated bugs noticed.+6. If a required upstream piece (endpoint, table, module) doesn't exist yet, **stub it** and note the stub in the report. Don't reach out of scope to build it.++## 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` |diff --git a/prompts/sprint-100/01-wallet-signin-button.md b/prompts/sprint-100/01-wallet-signin-button.mdnew file mode 100644index 000000000..55bd30994--- /dev/null+++ b/prompts/sprint-100/01-wallet-signin-button.md@@ -0,0 +1,74 @@+# 01 — Wallet signin button (client module + header affordance)++## Why++Server endpoints at [api/auth/siwe/nonce.js](../../api/auth/siwe/nonce.js) and [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) already exist and work. The user-facing button does not. Without a click-path, SIWE is unreachable.++## Parallel-safety++- You own ONE new file and make ONE single-line edit to [index.html](../../index.html) (adding the button near existing nav). You may NOT edit `src/app.js`.+- If another prompt is also editing `index.html`, insert your button at the end of the existing `<header>` nav section and keep your diff to <10 lines.++## Files you own++- Create: `src/wallet-auth.js`+- Edit: [index.html](../../index.html) — add a `<button id="btn-wallet-signin">Sign in with wallet</button>` inside the existing header nav, plus one `<script type="module">` tag at the bottom that imports and wires your module. No other edits.++## Read first (do not edit)++- [src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js) — exports `connectWallet()` returning `{ provider, signer, address, chainId }`.+- [api/auth/siwe/nonce.js](../../api/auth/siwe/nonce.js) — returns `{ nonce, ttl }`; treat `ttl` as seconds from now.+- [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) — accepts `{ message, signature }`, sets `__Host-sid` cookie on success.+- [api/auth/me.js](../../api/auth/me.js) — GET returns `{ user }` if signed in, 401 otherwise.++## Deliverable++`src/wallet-auth.js` exports:++```js+export async function signInWithWallet()+export async function signOut()+export async function getCurrentUser() // returns user or null, via /api/auth/me+export function wireSigninButton(buttonEl) // attaches click handler + swaps UI for signed-in chip+```++`signInWithWallet()` flow:++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()}+ ```+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."++Use no `alert()`. No new CSS files. Reuse existing CSS vars if present, otherwise inline minimal styles (`style="..."`).++## Acceptance++- `node --check src/wallet-auth.js` passes.+- `npm run build` produces no new warnings.+- Header button renders; clicking it with MetaMask present triggers the SIWE signature flow and reloads signed-in.+- Refresh → chip shows truncated address. Click sign-out → cookie cleared, button returns.++## Report++- Commands run + full output.+- A note on how signed-in detection works (the `getCurrentUser` call) and its caching/latency.+- Any friction (double prompts, race on fast clicks).diff --git a/prompts/sprint-100/02-session-management-api.md b/prompts/sprint-100/02-session-management-api.mdnew file mode 100644index 000000000..802a19276--- /dev/null+++ b/prompts/sprint-100/02-session-management-api.md@@ -0,0 +1,63 @@+# 02 — Session refresh + logout-all endpoints++## Why++Long-lived sessions need rotation and a "log out everywhere" escape hatch. Today [api/auth/logout.js](../../api/auth/logout.js) only kills the current cookie.++## 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`.++## Files you own++- Create: `api/auth/session/refresh.js`+- Create: `api/auth/session/list.js`+- Create: `api/auth/session/revoke.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/auth/logout.js](../../api/auth/logout.js) — reference pattern.++## Deliverable++### `POST /api/auth/session/refresh`++- Requires current session cookie.+- Rotates: invalidate old session row (`revoked_at = now()`), issue a new `__Host-sid` cookie bound to the same user.+- Response `{ ok: true, rotatedAt }`.+- Rate limit: `10/10min per user` via the existing `limits.*` presets if available; otherwise inline `rateLimit(req, { key: 'session-refresh:'+user.id, max: 10, windowMs: 600000 })` — if the helper isn't present, skip and note it.++### `GET /api/auth/session/list`++- Requires current session cookie.+- Returns array of `{ id, createdAt, lastUsedAt, userAgent, ipHash, current: boolean }` for all non-revoked sessions of the user.+- `ipHash` is the first 8 hex chars of a sha256 of the IP — never return raw IP.++### `POST /api/auth/session/revoke`++- Body `{ sessionId }` OR `{ all: true }`.+- `sessionId` → revoke that row (must belong to the caller's user).+- `all: true` → revoke every session of the user, INCLUDING the current one; clear the `__Host-sid` cookie on the response.+- Response `{ ok: true, revoked: N }`.++## Constraints++- Use `sql` tagged template; NO string-concat.+- Use `json()` / `error()` / `wrap()`; NO `res.end(JSON.stringify(...))`.+- CORS + method gate on every handler.+- Never return a session token or secret in any response.++## Acceptance++- `node --check` on all three files passes.+- `npm run build` clean.+- With an authenticated cookie, `curl /api/auth/session/list` returns the session array; `/refresh` rotates and a subsequent `/list` shows a new `createdAt`; `/revoke {all:true}` returns 401 on the next `/me`.++## Report++- Schema assumptions (which columns you queried; confirm they exist or note the gap).+- If `createSession()` needed something you had to stub, list it.+- curl session transcripts.diff --git a/prompts/sprint-100/03-wallet-link-account.md b/prompts/sprint-100/03-wallet-link-account.mdnew file mode 100644index 000000000..55c9da466--- /dev/null+++ b/prompts/sprint-100/03-wallet-link-account.md@@ -0,0 +1,62 @@+# 03 — Link / unlink wallet to existing account++## Why++An email user should be able to attach a wallet (and detach it) without creating a second account. Without this, SIWE-signin creates a split identity for users who already have an email account.++## Parallel-safety++You create two NEW endpoints. You do not touch SIWE nonce/verify or login/register. Uses the same `user_wallets` table that [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) already writes to.++## Files you own++- Create: `api/auth/wallet/link.js`+- Create: `api/auth/wallet/unlink.js`++## 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.++## Deliverable++### `POST /api/auth/wallet/link`++- 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 }`.+- Rate limit: `10/10min per user`.++### `POST /api/auth/wallet/unlink`++- 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 }`.+- If `is_primary` was true and other wallets exist, promote the most-recently-used remaining wallet to primary.++## Constraints++- Reuse the exact same nonce parsing / verify logic that [api/auth/siwe/verify.js](../../api/auth/siwe/verify.js) uses. If you refactor it into a shared helper, put the helper at `api/_lib/siwe.js`. If you'd rather inline to stay scoped, that's fine — note the duplication in the report.+- No new runtime deps. Use `ethers` since it's already a dep.++## Acceptance++- `node --check` clean.+- Manual: email-signup a user → call `/link` with a SIWE signature from a fresh wallet → `/auth/me` now returns the wallet address too. Call `/unlink` → it's gone.+- Trying to link a wallet already on another account returns `409 wallet-taken`.++## Report++- The refactor-or-inline decision on the SIWE parse logic.+- Whether you added `api/_lib/siwe.js` and what it exports.diff --git a/prompts/sprint-100/04-camera-capture-module.md b/prompts/sprint-100/04-camera-capture-module.mdnew file mode 100644index 000000000..0e8650f56--- /dev/null+++ b/prompts/sprint-100/04-camera-capture-module.md@@ -0,0 +1,60 @@+# 04 — Camera capture module (self-contained)++## Why++The selfie → avatar flow starts with a camera capture UI. Today the only entry is a Ready-Player-Me iframe. We need a real `getUserMedia` capture that produces a `Blob` any downstream module can consume.++## Parallel-safety++This prompt ships a self-contained JS module with **no route wiring**. A sibling prompt (07) and/or the existing `/create` route will mount it later. You do NOT edit `src/app.js`, `index.html`, or `vite.config.js`.++## Files you own++- Create: `src/camera-capture.js`+- Create: `src/camera-capture.css`++## Deliverable++`src/camera-capture.js` exports:++```js+export class CameraCapture {+ constructor({ container, onCapture, onCancel, aspect = 1 })+ start() // request permission, start stream, render UI+ stop() // teardown; safe to call multiple times+}+```++Behavior:++1. `container` is any element; on `start()`, render inside it: a square preview (`<video autoplay muted playsinline>`), a capture button, a "switch camera" button (mobile), a "use upload instead" link.+2. Request `navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user', width: { ideal: 1280 }, height: { ideal: 1280 }}})`.+3. On capture, draw current video frame to a square `<canvas>`, convert to JPEG blob at 0.92 quality.+4. Show preview with "retake" / "use this photo" buttons. "Use this photo" calls `onCapture(blob, { width, height, mimeType: 'image/jpeg' })`.+5. On permission-denied or no camera: fall back to `<input type="file" accept="image/*" capture="user">`. File pick also calls `onCapture`.+6. `onCancel()` fires if user backs out before capturing.++Stop must release the MediaStream tracks and remove all listeners.++## CSS++`src/camera-capture.css` — scoped under `.camera-capture-root`. Dark overlay, centered square preview, large capture button. No external fonts, no CSS vars from other modules.++## Constraints++- No framework. Vanilla DOM.+- No new deps.+- Must handle Safari iOS (the `playsinline` attribute + muted video matter).+- Must not throw on SSR (guard `typeof navigator !== 'undefined'` in module-top code).++## Acceptance++- `node --check src/camera-capture.js` passes.+- A tiny test harness page (inline, not committed) confirms: mount → permission prompt → capture → blob logged with plausible byte size.+- `npm run build` clean.++## Report++- Mobile Safari behavior notes (inline + muted).+- The blob size you saw for a typical 1280x1280 JPEG at q=0.92.+- Any permissions / HTTPS gotchas.diff --git a/prompts/sprint-100/05-avaturn-client.md b/prompts/sprint-100/05-avaturn-client.mdnew file mode 100644index 000000000..5bfdcc489--- /dev/null+++ b/prompts/sprint-100/05-avaturn-client.md@@ -0,0 +1,59 @@+# 05 — Avaturn client bridge++## Why++The backend [api/onboarding/avaturn-session.js](../../api/onboarding/avaturn-session.js) exists and returns `{ session_url, expires_at }` for a set of captured photos. No client wraps it. Without this module, captured photos have no path to an actual GLB.++## Parallel-safety++Pure client module. You create ONE file. No route wiring; a sibling/later prompt connects this to the camera module.++## Files you own++- Create: `src/avaturn-client.js`++## Read first++- [api/onboarding/avaturn-session.js](../../api/onboarding/avaturn-session.js) — shape of request (`{ photos: { front, left, right } }` — confirm by reading) and response.++## Deliverable++```js+export async function createAvaturnSession({ front, left, right })+// POST /api/onboarding/avaturn-session with the three base64 JPEGs (data URLs).+// Returns { sessionUrl, expiresAt } or throws a typed error.++export async function awaitAvatarGLB({ sessionUrl, onProgress, signal })+// Opens the Avaturn session inside a hidden iframe, listens via postMessage for+// the 'avatar.ready' / 'avatar.exported' event with a GLB URL, fetches the GLB,+// returns { glbBytes: ArrayBuffer, thumbnailUrl?: string, metadata?: object }.+// onProgress({ step, pct }) fires with steps: 'iframe-load' | 'avatar-gen' | 'glb-fetch'.+// signal is an AbortSignal; on abort, tear down the iframe and reject with AbortError.++export class AvaturnError extends Error {} // name === 'AvaturnError', has .code: 'quota' | 'auth' | 'session-expired' | 'network' | 'timeout'+```++Implementation notes:++- `blobToDataUrl(blob)` helper to convert the JPEG `Blob`s from the camera module.+- The hidden iframe mounts at `document.body` with `style.display = 'none'`, `sandbox="allow-scripts allow-same-origin"`. Confirm Avaturn's actual sandbox requirements — if it needs more, widen minimally and note it.+- `postMessage` listener scoped to the iframe's `contentWindow`; ignore messages from other sources.+- Overall timeout: 120s from `awaitAvatarGLB` start → reject with `AvaturnError('timeout')`.+- If the server returned `expires_at` before now + 10s, reject immediately with `AvaturnError('session-expired')`.++## Constraints++- No new deps.+- Do not hardcode Avaturn's origin; derive it from `sessionUrl`.+- Do not log GLB bytes or any raw photo data.++## Acceptance++- `node --check` clean.+- `npm run build` clean.+- Integration is NOT required for acceptance — a sibling prompt wires this to the camera module. Include a small doc-comment example at the top of the file showing the intended use.++## Report++- Exact Avaturn postMessage event shape you coded against (cite their docs or the existing code that references them).+- Whether you needed to loosen the iframe sandbox.diff --git a/prompts/sprint-100/06-agent-naming-form.md b/prompts/sprint-100/06-agent-naming-form.mdnew file mode 100644index 000000000..c3d290c76--- /dev/null+++ b/prompts/sprint-100/06-agent-naming-form.md@@ -0,0 +1,66 @@+# 06 — Agent naming form module++## Why++After a GLB is produced, the user names the agent. Needs uniqueness check + denylist. Isolated module; a later prompt mounts it in the onboarding flow.++## Parallel-safety++One new JS module + one new server endpoint for uniqueness check. No route wiring, no edits to `src/app.js`.++## Files you own++- Create: `src/agent-naming.js`+- Create: `api/agents/check-name.js` (if [api/agents/check-name.js](../../api/agents/check-name.js) already exists — read it first and extend only if your needs aren't met; otherwise stub a client-side check and note it).++## 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`.++## Deliverable++### `src/agent-naming.js`++```js+export class AgentNaming {+ constructor({ container, initialName = '', onSubmit })+ mount() // renders form+ unmount() // cleanup+}+```++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.++Denylist (hardcode array in the module): `['admin', 'root', 'system', 'anthropic', 'claude', 'openai', 'null', 'undefined', 'test']`.++### `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.++## Constraints++- No framework. Minimal inline styles.+- No new deps.++## Acceptance++- `node --check` clean on all files you touched.+- `npm run build` clean.+- Manually: mount the module in a scratch page, type a known-taken name → sees ✗; type a unique valid name → ✓, submit fires with the `{ name, description }` payload.++## Report++- Whether you created or extended `check-name.js`, with the exact diff.+- What table you queried for uniqueness.diff --git a/prompts/sprint-100/07-first-meet-celebration.md b/prompts/sprint-100/07-first-meet-celebration.mdnew file mode 100644index 000000000..669083141--- /dev/null+++ b/prompts/sprint-100/07-first-meet-celebration.md@@ -0,0 +1,56 @@+# 07 — First-meet celebration module++## Why++The moment an avatar is generated, the user should feel something. A brief wave, a confetti burst, a "share" CTA. Raises perceived quality massively for near-zero cost.++## Parallel-safety++Self-contained module. No app wiring.++## Files you own++- Create: `src/first-meet.js`+- Create: `src/first-meet.css`++## Deliverable++```js+export async function playFirstMeet({ viewer, agent, onShare, onContinue })+// viewer: the SceneController / AgentAvatar instance (duck-typed — it has .playClip(name) OR .mixer and .animations).+// agent: { id, name, slug } — used for share URL + greeting text.+// onShare: () => void — invoked when user clicks "share"+// onContinue: () => void — invoked when user clicks "go to agent home"+//+// Plays a ~3s sequence:+// t=0.0 — fade black → scene (if from dark background; else no-op)+// t=0.2 — avatar waves (prefer clip 'Wave'; fallback: a scripted head tilt + hand raise via bone names 'mixamorigRightHand' or 'RightHand')+// t=0.6 — "Hello, I'm {name}." subtitle fades in+// t=1.4 — confetti burst (CSS-only; no canvas library)+// t=2.2 — buttons "Share" and "Continue" fade in+// t= ∞ — resolves when user clicks a button+```++Confetti: 40–60 absolutely-positioned `<span>` elements, randomized hue/size/rotation, CSS `@keyframes` falling + fading, `pointer-events: none`. Cleans up after 2s.++If the avatar has no Wave clip and no rig bone names match, skip the wave gracefully — don't throw.++## CSS++`src/first-meet.css`, scoped under `.first-meet-root`. All keyframes prefixed `fm-` to avoid collisions.++## Constraints++- No canvas libs, no tween libs. Pure CSS + `requestAnimationFrame` if needed.+- `prefers-reduced-motion: reduce` → skip confetti, keep the subtitle + buttons, no wave scripting, no fade.++## Acceptance++- `node --check src/first-meet.js` passes.+- `npm run build` clean.+- In a scratch page with a dummy viewer mock, the sequence runs and resolves on button click.++## Report++- What clip names / bone names you probed and in what order.+- What the sequence looks like if no Wave and no matching bones (screenshot/description).diff --git a/prompts/sprint-100/08-avatar-patch-endpoint.md b/prompts/sprint-100/08-avatar-patch-endpoint.mdnew file mode 100644index 000000000..354595733--- /dev/null+++ b/prompts/sprint-100/08-avatar-patch-endpoint.md@@ -0,0 +1,52 @@+# 08 — Avatar PATCH endpoint (editor save-back)++## Why++The editor can export a GLB but has no server path to persist it. A `PATCH /api/avatars/:id` lets the editor write edited bytes back to R2 and update the DB row, creating a new version entry.++## Parallel-safety++[api/avatars/[id].js](../../api/avatars/[id].js) already exists. You must NOT rewrite it — read it and ADD a PATCH branch (or create a sibling file at `api/avatars/[id]/patch.js` if Vercel's routing supports the sibling better; default: add the branch to the existing file with an additive diff under 80 lines).++## Files you own++- Edit (additive only): [api/avatars/[id].js](../../api/avatars/[id].js) — add PATCH handler branch, keep GET/DELETE untouched.++## Read first++- [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).++## Deliverable++### `PATCH /api/avatars/:id`++- 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 } }`.+- Rate limit: `20/hour per user`.++## Constraints++- Additive diff. Do not change GET or DELETE behavior.+- Use `sql` tag, `json()`, `error()`.+- No new deps.++## Acceptance++- `node --check` clean.+- `npm run build` clean.+- curl an authenticated PATCH with a valid glbUrl → 200 + updated row in DB. Wrong owner → 403. Oversize object → 413 or 400 with a clear error code.++## Report++- The exact diff (or paste the added branch).+- What you did if the `avatar_versions` table isn't there.+- What `headObject` shape you used and which SDK call.diff --git a/prompts/sprint-100/09-editor-save-back.md b/prompts/sprint-100/09-editor-save-back.mdnew file mode 100644index 000000000..1e27b28b9--- /dev/null+++ b/prompts/sprint-100/09-editor-save-back.md@@ -0,0 +1,67 @@+# 09 — Editor save-back button (client)++## Why++Editor can export GLB bytes ([src/editor/glb-export.js](../../src/editor/glb-export.js)) but doesn't push them anywhere. This adds a client module that exports → presigned-uploads to R2 → calls `PATCH /api/avatars/:id`.++## Parallel-safety++New client module. You make ONE additive edit to [src/editor/index.js](../../src/editor/index.js) to wire a "💾 save edits" control, under 10 lines. The `PATCH /api/avatars/:id` endpoint may or may not exist yet (sibling prompt 08 builds it) — this module calls it anyway and surfaces any error gracefully.++## Files you own++- Create: `src/editor/save-back.js`+- Edit (<10 lines additive): [src/editor/index.js](../../src/editor/index.js) — add a control in `_addExportFolder()` after the download-GLB row.++## Read first++- [src/editor/glb-export.js](../../src/editor/glb-export.js) — has `exportCurrentGLB(session)` or similar; confirm the export entry point.+- [src/editor/publish.js](../../src/editor/publish.js) — already does a similar dance for widget publish; reuse its presign helpers if they're exported. If they're private, do not refactor — duplicate the minimal code you need.+- [api/avatars/presign.js](../../api/avatars/presign.js) — presign contract.++## Deliverable++`src/editor/save-back.js` exports:++```js+export async function saveEditedAvatar(session, { avatarId, onStep })+// 1. Export GLB bytes from the editor session.+// 2. POST /api/avatars/presign with { size, contentType: 'model/gltf-binary', purpose: 'avatar-edit' }.+// 3. PUT the bytes to the returned signed URL.+// 4. PATCH /api/avatars/:id with { glbUrl: <the non-signed R2 URL> }.+// onStep({ step: 'export'|'presign'|'upload'|'patch', pct }).+// Returns { ok: true, avatar } or throws with a .code of 'auth' | 'oversize' | 'network' | 'server'.+```++### Editor control++In `_addExportFolder()` add:++```js+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>`.++## Constraints++- No modal. Non-blocking save.+- No new deps.+- If `session.avatarId` isn't on the session object, fallback to `new URLSearchParams(location.search).get('avatarId')`.++## Acceptance++- `node --check src/editor/save-back.js` passes.+- `npm run build` clean.+- With the PATCH endpoint live: edit an avatar, click Save → refresh the page → edits persisted.+- Without the endpoint live: click Save → clear error toast, no console spam.++## Report++- Whether `exportCurrentGLB` was already exported or needed to be called via an existing public method.+- Full terminal output of `node --check` and `npm run build`.diff --git a/prompts/sprint-100/10-avatar-version-history.md b/prompts/sprint-100/10-avatar-version-history.mdnew file mode 100644index 000000000..68ae473c7--- /dev/null+++ b/prompts/sprint-100/10-avatar-version-history.md@@ -0,0 +1,70 @@+# 10 — Avatar version history (schema + API)++## Why++Editor save-back needs rollback. This prompt adds the `avatar_versions` table and a minimal list/rollback API.++## Parallel-safety++Pure schema + two new endpoints. No client wiring.++## Files you own++- Create: `scripts/migrations/add-avatar-versions.sql`+- Create: `api/avatars/[id]/versions.js` (GET list)+- Create: `api/avatars/[id]/rollback.js` (POST)++## 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`.+- [scripts/](../../scripts/) — any existing migration conventions.++## Deliverable++### Migration++```sql+create table if not exists avatar_versions (+ id bigserial primary key,+ avatar_id uuid not null references avatars(id) on delete cascade,+ glb_url text not null,+ metadata jsonb,+ created_at timestamptz not null default now(),+ created_by uuid references users(id)+);++create index if not exists avatar_versions_avatar_id_idx on avatar_versions(avatar_id, created_at desc);+```++If `avatars` doesn't exist with a `uuid` id (or the id is `text`), adapt the FK type — read the real schema first and note any adaptation in the report.++### `GET /api/avatars/:id/versions`++- Auth required; ownership check.+- Returns `{ versions: [{ id, glbUrl, createdAt, metadata }...] }`, newest first, limit 50.++### `POST /api/avatars/:id/rollback`++- Auth required; ownership check.+- Body: `{ versionId }`.+- Look up the version row (must belong to this avatar), set `avatars.current_glb_url = versions.glb_url`, insert a new `avatar_versions` row noting this was a rollback (metadata `{ rollback_of: versionId }`).+- Response `{ ok: true, avatar: {...} }`.+- Rate limit: `10/hour per user`.++## Constraints++- Migration must be idempotent (uses `if not exists`).+- All SQL via tagged template.+- No new deps.++## Acceptance++- `psql -f scripts/migrations/add-avatar-versions.sql` runs clean against a dev db (you can skip actually running it — just show the SQL parses via `psql --dry-run` or syntax-check it).+- `node --check` clean on both endpoints.+- `npm run build` clean.++## Report++- Actual `avatars.id` type and any FK adaptation.+- Confirm whether a migration-runner convention already exists in this repo and how to invoke it.diff --git a/prompts/sprint-100/11-share-panel.md b/prompts/sprint-100/11-share-panel.mdnew file mode 100644index 000000000..952f9ccce--- /dev/null+++ b/prompts/sprint-100/11-share-panel.md@@ -0,0 +1,61 @@+# 11 — Share panel module++## Why++Users need a one-click way to get copy-paste snippets for any agent: short link, iframe, `<agent-3d>` web-component, OG-preview thumbnail. Currently scattered across dashboards and not surfaced on the public agent page.++## Parallel-safety++Self-contained module. No app wiring. No edits to `src/app.js` or any agent page.++## Files you own++- Create: `src/share-panel.js`+- Create: `src/share-panel.css`++## Deliverable++```js+export class SharePanel {+ constructor({ agent, container, embedOrigin = location.origin })+ // agent: { id, slug, name, thumbnailUrl }+ open()+ close()+}+```++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>+ ```+3. **Web-component snippet**:+ ```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.++Each copy button: flash "copied ✓" for 1.2s.+`Esc` closes. Click outside `.share-panel-modal` closes. Focus trap.++## Constraints++- No new runtime deps. For QR: use a tiny inline `qr-generator` — if [src/erc8004/qr.js](../../src/erc8004/qr.js) exists and exports a helper, reuse it; otherwise render a placeholder `<div>` labeled "QR coming soon" and note it in the report. Do NOT install a QR package.+- Dark-theme default. Scoped CSS (`.share-panel-*`).+- ARIA: `role="dialog"`, `aria-modal="true"`, `aria-labelledby`.++## Acceptance++- `node --check src/share-panel.js` passes.+- `npm run build` clean.+- Scratch-mount with a fake agent object: modal opens, all copy buttons work, Esc closes, focus returns to opener.++## Report++- QR decision (reused helper vs stub).+- Accessibility smoke (keyboard-only walkthrough).diff --git a/prompts/sprint-100/12-agent-id-attribute.md b/prompts/sprint-100/12-agent-id-attribute.mdnew file mode 100644index 000000000..4259f0ec5--- /dev/null+++ b/prompts/sprint-100/12-agent-id-attribute.md@@ -0,0 +1,64 @@+# 12 — `<agent-3d agent-id="...">` attribute resolver++## Why++Today embedding requires a full manifest URL. A bare `agent-id` attribute makes the embed snippet 3x shorter and is what we paste into Claude.ai / LobeHub. The resolver must translate `agent-id="xyz"` → manifest URL → full boot.++## Parallel-safety++You own ONE existing file, [src/agent-resolver.js](../../src/agent-resolver.js), and may create one new sibling if needed. You do NOT edit the web-component definition directly (find it; it's likely in [dist-lib/](../../dist-lib/) generated output or [src/](../../src/) — read `vite.config.js` for the library entry).++## Read first++- [src/agent-resolver.js](../../src/agent-resolver.js)+- [src/agent-identity.js](../../src/agent-identity.js)+- [vite.config.js](../../vite.config.js) — library entry for `agent-3d.js`.+- The web-component definition file (grep for `customElements.define('agent-3d'`).++## Files you own++- Edit: [src/agent-resolver.js](../../src/agent-resolver.js) — add `resolveByAgentId(agentId)` export.+- Edit: the web-component file — ONLY the `connectedCallback` (or equivalent) to prefer `agent-id` attribute if `manifest` is absent.++## Deliverable++### `resolveByAgentId(agentId)`++```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.+}+```++### 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.+- 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.++Also observe `attributeChangedCallback` for `agent-id` (add to `observedAttributes`). If it changes post-mount, reset and re-boot.++## Constraints++- No new deps.+- No new network fetches beyond the one `/api/agents/:id` call per unique id.+- Must work when the component is embedded in a cross-origin iframe (no `localStorage` access — use in-memory Map only).++## Acceptance++- `node --check` clean on all edited files.+- `npm run build:lib` rebuilds `dist-lib/agent-3d.js` cleanly.+- `<agent-3d agent-id="demo">` on a test page boots the demo agent. Removing the attribute and setting a new one re-boots.++## Report++- The exact file where `customElements.define('agent-3d'` lives.+- Whether the existing boot was inside `connectedCallback` or an observer; how you hooked in without regressing the manifest path.diff --git a/prompts/sprint-100/13-artifact-bundle.md b/prompts/sprint-100/13-artifact-bundle.mdnew file mode 100644index 000000000..ceb39c62d--- /dev/null+++ b/prompts/sprint-100/13-artifact-bundle.md@@ -0,0 +1,58 @@+# 13 — Zero-dep Claude.ai artifact bundle++## Why++Claude.ai Artifacts run in a sandboxed iframe: no npm, no localStorage, CDN scripts allowed. We need a single-file `artifact.js` that, dropped into an Artifact's HTML, boots an embodied agent keyed by agent-id.++## Parallel-safety++Output is a new static file under `public/`. No edits to `src/app.js` or the library build.++## Files you own++- Create: `public/artifact.js` — single self-contained ES module, ~300 LOC max.+- Create: `public/artifact-example.html` — copy-paste-ready template demonstrating usage.++## Deliverable++### `public/artifact.js`++- Import Three.js + GLTFLoader from a pinned CDN (`https://esm.sh/[email protected]`, `https://esm.sh/[email protected]/examples/jsm/loaders/GLTFLoader.js`). Pin exact versions. No dynamic unpkg.+- Exports an auto-mount IIFE: scans the document for `<div data-agent-id="..."></div>` elements on `DOMContentLoaded` and mounts a viewer into each.+- Fetches `https://3dagent.vercel.app/api/agents/${id}` → gets `manifest_url` → fetches manifest → loads `avatar.glb`.+- Renders: transparent background (`alpha: true`), orbit controls off, a subtle auto-rotate + breathing idle (inline, no idle-animation.js dep), responsive to container size.+- If fetch fails, shows an inline error div with the CDN-safe CSS injected at the top of the mount.++### `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>+</html>+```++## Constraints++- Absolutely no imports from `src/`, `dist-lib/`, or anything in this repo. Must be self-contained.+- Pinned CDN versions only. No unversioned URLs.+- Must respect `prefers-reduced-motion` — skip auto-rotate / breathing if set.+- No localStorage / sessionStorage. No cookies.+- No `window.VIEWER` debug globals.+- Must handle DPR (`renderer.setPixelRatio(Math.min(devicePixelRatio, 2))`).++## Acceptance++- Open `public/artifact-example.html` directly in a browser (via a local server) → demo agent loads and idles.+- Paste the example HTML into a Claude.ai Artifact — same behavior.+- Network tab: exactly one Three import, one GLTFLoader import, one `/api/agents/:id`, one manifest fetch, one `.glb` fetch.++## Report++- Final file size of `public/artifact.js` gzipped (measure with `gzip -c public/artifact.js | wc -c`).+- Any CORS surprises you hit fetching from the Artifact sandbox.diff --git a/public/agents/README.md b/public/agents/README.mdnew file mode 100644index 000000000..3108aa680--- /dev/null+++ b/public/agents/README.md@@ -0,0 +1,52 @@+# Agents Directory++Public directory of registered agents across the 3D Agent ecosystem.++## Features++- **Global discovery** — Browse all registered agents on-chain+- **Chain filtering** — Filter by blockchain (Base, Base Sepolia, Optimism, Polygon)+- **Search** — Find agents by name, ID, or description+- **Sorting** — Sort by newest, oldest, or alphabetical order+- **Pagination** — 30 agents per page with shareable URLs+- **Lazy loading** — Avatar thumbnails load on-demand++## Data source++Agents are sourced from the **on-chain IdentityRegistry**. Each agent's metadata is resolved from the `tokenURI` stored on-chain. Avatar images are extracted from the agent manifest's `body.uri` field.++## URL parameters++Filters are preserved in the URL for shareability:++```+/agents/?chain=8453&sort=newest&page=2&search=Alice+```++| Parameter | Values | Default |+| --------- | ------ | ------- |+| `chain` | `all`, `8453` (Base), `84532` (Base Sepolia), `10` (Optimism), `137` (Polygon) | `all` |+| `sort` | `newest`, `oldest`, `name` | `newest` |+| `page` | `1`–N | `1` |+| `search` | Free text | (none) |++## Accessibility++- Semantic HTML with `data-agent-id` attributes on cards (QA-friendly)+- Lazy loading via `IntersectionObserver`+- Keyboard navigation support (tabs, enter)+- Target Lighthouse accessibility score ≥ 90++## Architecture++- **[index.html](./index.html)** — HTML structure + inline styles+- **[boot.js](./boot.js)** — Event handling + URL state management+- **[../../src/agents-directory.js](../../src/agents-directory.js)** — Controller class+ - Fetches from on-chain registries+ - Client-side filtering & sorting+ - SWR-style caching (60s TTL)+ - Lazy image loading++## Rate limiting++On-chain queries use public RPCs from `CHAIN_META`. No backend calls for the public list (no rate-limit concerns).diff --git a/public/agents/boot.js b/public/agents/boot.jsnew file mode 100644index 000000000..88aad7e4b--- /dev/null+++ b/public/agents/boot.js@@ -0,0 +1,153 @@+/**+ * Agents directory page — initialization and event handling.+ */++import { AgentsDirectory } from '../../src/agents-directory.js';++const directory = new AgentsDirectory('#agents');++// Decode URL params+const urlParams = new URLSearchParams(window.location.search);+const initialChain = urlParams.get('chain') || 'all';+const initialSort = urlParams.get('sort') || 'newest';+const initialPage = parseInt(urlParams.get('page') || '1', 10);+const initialSearch = urlParams.get('search') || '';++// UI elements+const searchInput = document.getElementById('search');+const filterChips = document.querySelectorAll('.filter-chip');+const sortSelect = document.getElementById('sort');+const agentsContainer = document.getElementById('agents');+const emptyState = document.getElementById('empty-state');+const loadingEl = document.getElementById('loading');+const paginationEl = document.getElementById('pagination');+const pageInfo = document.getElementById('page-info');+const prevBtn = document.getElementById('prev-btn');+const nextBtn = document.getElementById('next-btn');++let currentChain = initialChain;+let currentSort = initialSort;+let currentPage = initialPage;+let currentSearch = initialSearch;++/**+ * Update URL with current state.+ */+function updateUrl() {+ const params = new URLSearchParams();+ if (currentChain !== 'all') params.set('chain', currentChain);+ if (currentSort !== 'newest') params.set('sort', currentSort);+ if (currentPage !== 1) params.set('page', currentPage);+ if (currentSearch) params.set('search', currentSearch);++ const query = params.toString();+ const path = query ? `?${query}` : '';+ window.history.replaceState({}, '', `/agents/${path}`);+}++/**+ * Load and render agents.+ */+async function render() {+ loadingEl.style.display = 'block';+ agentsContainer.innerHTML = '';+ emptyState.style.display = 'none';+ paginationEl.style.display = 'none';++ try {+ const result = await directory.load({+ chain: currentChain,+ search: currentSearch,+ sort: currentSort,+ page: currentPage,+ });++ if (result.agents.length === 0) {+ emptyState.style.display = 'block';+ loadingEl.style.display = 'none';+ return;+ }++ directory.render();+ loadingEl.style.display = 'none';+ agentsContainer.style.display = 'grid';++ // Update pagination+ const { hasNextPage, hasPrevPage, page, totalPages } = directory.getPaginationInfo();+ pageInfo.textContent = `Page ${page} of ${totalPages}`;+ prevBtn.disabled = !hasPrevPage;+ nextBtn.disabled = !hasNextPage;+ paginationEl.style.display = 'flex';++ // Scroll to top+ window.scrollTo({ top: 0, behavior: 'smooth' });+ } catch (err) {+ console.error('Failed to load agents:', err);+ loadingEl.style.display = 'none';+ emptyState.style.display = 'block';+ emptyState.querySelector('h2').textContent = 'Error loading agents';+ emptyState.querySelector('p').textContent = err.message || 'Please try again later.';+ }+}++/**+ * Handle card clicks.+ */+directory.onCardClick((agent) => {+ window.location.href = `/a/${agent.chainId}/${agent.id}`;+});++// Search input+searchInput.value = currentSearch;+searchInput.addEventListener('input', (e) => {+ currentSearch = e.target.value;+ currentPage = 1;+ updateUrl();+ render();+});++// Filter chips+filterChips.forEach((chip) => {+ const filter = chip.dataset.filter;+ if (filter === currentChain) {+ chip.classList.add('active');+ }+ chip.addEventListener('click', () => {+ filterChips.forEach((c) => c.classList.remove('active'));+ chip.classList.add('active');+ currentChain = filter;+ currentPage = 1;+ updateUrl();+ render();+ });+});++// Sort select+sortSelect.value = currentSort;+sortSelect.addEventListener('change', (e) => {+ currentSort = e.target.value;+ currentPage = 1;+ updateUrl();+ render();+});++// Pagination+prevBtn.addEventListener('click', () => {+ if (currentPage > 1) {+ currentPage--;+ updateUrl();+ render();+ }+});++nextBtn.addEventListener('click', () => {+ const info = directory.getPaginationInfo();+ if (currentPage < info.totalPages) {+ currentPage++;+ updateUrl();+ render();+ }+});++// Initial render+render();diff --git a/public/agents/index.html b/public/agents/index.htmlnew file mode 100644index 000000000..7ffb98297--- /dev/null+++ b/public/agents/index.html@@ -0,0 +1,390 @@+<!DOCTYPE html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Agents Directory — 3D Agent</title>+ <style>+ * {+ margin: 0;+ padding: 0;+ box-sizing: border-box;+ }++ html,+ body {+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu',+ 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;+ background: linear-gradient(135deg, #0f0f23 0%, #1a0f3a 100%);+ color: #e0e0e0;+ min-height: 100vh;+ overflow-x: hidden;+ }++ header {+ background: rgba(15, 15, 35, 0.95);+ border-bottom: 1px solid rgba(255, 255, 255, 0.1);+ padding: 2rem 1rem;+ text-align: center;+ }++ header h1 {+ font-size: 2.5rem;+ margin-bottom: 0.5rem;+ background: linear-gradient(135deg, #00d9ff, #7c3aed);+ background-clip: text;+ -webkit-background-clip: text;+ -webkit-text-fill-color: transparent;+ }++ header p {+ font-size: 1rem;+ color: #a0a0a0;+ }++ .container {+ max-width: 1400px;+ margin: 2rem auto;+ padding: 0 1rem;+ }++ .controls {+ display: flex;+ flex-wrap: wrap;+ gap: 1rem;+ margin-bottom: 2rem;+ align-items: center;+ }++ .search-box {+ flex: 1;+ min-width: 250px;+ padding: 0.75rem 1rem;+ background: rgba(255, 255, 255, 0.05);+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: 8px;+ color: #e0e0e0;+ font-size: 1rem;+ }++ .search-box::placeholder {+ color: #666;+ }++ .search-box:focus {+ outline: none;+ border-color: #00d9ff;+ background: rgba(0, 217, 255, 0.05);+ }++ .filter-group {+ display: flex;+ gap: 0.5rem;+ flex-wrap: wrap;+ }++ .filter-label {+ font-size: 0.85rem;+ font-weight: 600;+ text-transform: uppercase;+ color: #999;+ align-self: center;+ }++ .filter-chip {+ padding: 0.5rem 1rem;+ background: rgba(255, 255, 255, 0.05);+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: 20px;+ cursor: pointer;+ font-size: 0.9rem;+ color: #a0a0a0;+ transition: all 0.2s ease;+ }++ .filter-chip:hover {+ background: rgba(255, 255, 255, 0.1);+ }++ .filter-chip.active {+ background: linear-gradient(135deg, #00d9ff, #7c3aed);+ border-color: transparent;+ color: #fff;+ font-weight: 600;+ }++ .sort-select {+ padding: 0.5rem 1rem;+ background: rgba(255, 255, 255, 0.05);+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: 8px;+ color: #e0e0e0;+ cursor: pointer;+ font-size: 0.9rem;+ }++ .sort-select:focus {+ outline: none;+ border-color: #00d9ff;+ }++ .sort-select option {+ background: #0f0f23;+ color: #e0e0e0;+ }++ .agent-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));+ gap: 1.5rem;+ margin-bottom: 2rem;+ }++ .agent-card {+ background: rgba(255, 255, 255, 0.03);+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: 12px;+ overflow: hidden;+ cursor: pointer;+ transition: all 0.3s ease;+ display: flex;+ flex-direction: column;+ }++ .agent-card:hover {+ border-color: rgba(0, 217, 255, 0.5);+ background: rgba(0, 217, 255, 0.05);+ transform: translateY(-4px);+ box-shadow: 0 8px 24px rgba(0, 217, 255, 0.15);+ }++ .card-avatar {+ width: 100%;+ aspect-ratio: 1;+ background: rgba(255, 255, 255, 0.02);+ display: flex;+ align-items: center;+ justify-content: center;+ overflow: hidden;+ }++ .card-avatar img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ }++ .avatar-placeholder {+ font-size: 3rem;+ opacity: 0.3;+ }++ .card-content {+ padding: 1.25rem;+ flex: 1;+ display: flex;+ flex-direction: column;+ }++ .card-name {+ font-size: 1.1rem;+ font-weight: 600;+ margin-bottom: 0.5rem;+ color: #fff;+ line-height: 1.3;+ }++ .card-desc {+ font-size: 0.85rem;+ color: #a0a0a0;+ margin-bottom: 1rem;+ line-height: 1.4;+ flex: 1;+ }++ .card-meta {+ display: flex;+ gap: 0.5rem;+ flex-wrap: wrap;+ font-size: 0.75rem;+ }++ .chain-badge {+ background: rgba(124, 58, 237, 0.2);+ border: 1px solid rgba(124, 58, 237, 0.5);+ padding: 0.3rem 0.6rem;+ border-radius: 4px;+ color: #c4b5fd;+ }++ .agent-id {+ background: rgba(0, 217, 255, 0.1);+ border: 1px solid rgba(0, 217, 255, 0.3);+ padding: 0.3rem 0.6rem;+ border-radius: 4px;+ color: #00d9ff;+ font-family: 'Monaco', 'Courier New', monospace;+ }++ .empty-state {+ text-align: center;+ padding: 4rem 2rem;+ }++ .empty-state h2 {+ font-size: 1.5rem;+ margin-bottom: 1rem;+ color: #fff;+ }++ .empty-state p {+ font-size: 1rem;+ color: #a0a0a0;+ margin-bottom: 2rem;+ }++ .cta-button {+ padding: 0.75rem 1.5rem;+ background: linear-gradient(135deg, #00d9ff, #7c3aed);+ border: none;+ border-radius: 8px;+ color: #fff;+ font-weight: 600;+ cursor: pointer;+ transition: all 0.2s ease;+ text-decoration: none;+ display: inline-block;+ }++ .cta-button:hover {+ transform: scale(1.05);+ box-shadow: 0 8px 24px rgba(0, 217, 255, 0.3);+ }++ .pagination {+ display: flex;+ justify-content: center;+ align-items: center;+ gap: 1rem;+ margin-top: 2rem;+ padding: 2rem;+ flex-wrap: wrap;+ }++ .pagination-button {+ padding: 0.5rem 1rem;+ background: rgba(255, 255, 255, 0.05);+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: 8px;+ color: #e0e0e0;+ cursor: pointer;+ transition: all 0.2s ease;+ }++ .pagination-button:hover:not(:disabled) {+ background: rgba(0, 217, 255, 0.1);+ border-color: #00d9ff;+ color: #00d9ff;+ }++ .pagination-button:disabled {+ opacity: 0.3;+ cursor: not-allowed;+ }++ .pagination-info {+ color: #a0a0a0;+ font-size: 0.9rem;+ }++ .loading {+ text-align: center;+ padding: 2rem;+ color: #a0a0a0;+ }++ .loading::after {+ content: '';+ display: inline-block;+ margin-left: 0.5rem;+ width: 1rem;+ height: 1rem;+ border: 2px solid rgba(0, 217, 255, 0.3);+ border-top-color: #00d9ff;+ border-radius: 50%;+ animation: spin 0.8s linear infinite;+ }++ @keyframes spin {+ to {+ transform: rotate(360deg);+ }+ }++ @media (max-width: 768px) {+ header h1 {+ font-size: 1.75rem;+ }++ .controls {+ flex-direction: column;+ }++ .search-box {+ min-width: 100%;+ }++ .agent-grid {+ grid-template-columns: 1fr;+ }+ }+ </style>+ </head>+ <body>+ <header>+ <h1>Agent Directory</h1>+ <p>Discover registered agents across the ecosystem</p>+ </header>++ <div class="container">+ <div class="controls">+ <input+ type="text"+ id="search"+ class="search-box"+ placeholder="Search by name, ID, or description…"+ />+ <div class="filter-group">+ <span class="filter-label">Chain:</span>+ <button class="filter-chip active" data-filter="all">All</button>+ <button class="filter-chip" data-filter="8453">Base</button>+ <button class="filter-chip" data-filter="84532">Base Sepolia</button>+ <button class="filter-chip" data-filter="10">Optimism</button>+ <button class="filter-chip" data-filter="137">Polygon</button>+ </div>+ <select id="sort" class="sort-select">+ <option value="newest">Newest First</option>+ <option value="oldest">Oldest First</option>+ <option value="name">Alphabetical</option>+ </select>+ </div>++ <div id="loading" class="loading" style="display: none">Loading agents</div>+ <div id="agents" class="agent-grid"></div>++ <div id="empty-state" class="empty-state" style="display: none">+ <h2>No agents found</h2>+ <p>Be the first to register your agent on-chain.</p>+ <a href="/create" class="cta-button">Create Agent</a>+ </div>++ <div id="pagination" class="pagination" style="display: none">+ <button id="prev-btn" class="pagination-button">← Previous</button>+ <span id="page-info" class="pagination-info"></span>+ <button id="next-btn" class="pagination-button">Next →</button>+ </div>+ </div>++ <script type="module" src="./boot.js"></script>+ </body>+</html>diff --git a/public/artifact/README.md b/public/artifact/README.mdnew file mode 100644index 000000000..b72a7ee94--- /dev/null+++ b/public/artifact/README.md@@ -0,0 +1,30 @@+# Citing a 3D Agent artifact in Claude.ai++`GET https://3dagent.vercel.app/api/artifact?agent=<agentId>`++Paste the URL into a Claude.ai conversation. Claude recognises it as an HTML artifact and renders the interactive 3D agent inline.++## Worked example++```+Here's my agent for this conversation:+https://3dagent.vercel.app/api/artifact?agent=alice+```++Claude will embed the artifact and display the live 3D character.++## Parameters++| 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` |++## Notes++- The document returned is a single self-contained HTML page — no external requests except the UMD bundle and your agent's GLB asset.+- `frame-ancestors *` is set in the CSP so Claude.ai's sandboxed iframe can render it.+- Rate-limited at 600 req/min per IP (shared with widget reads).diff --git a/public/artifact/index.html b/public/artifact/index.htmlnew file mode 100644index 000000000..95a0a2d8c--- /dev/null+++ b/public/artifact/index.html@@ -0,0 +1,177 @@+<!DOCTYPE html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>3D Agent Artifact Demo</title>+ <style>+ * {+ margin: 0;+ padding: 0;+ box-sizing: border-box;+ }++ body {+ font-family: system-ui, -apple-system, sans-serif;+ background: #0a0e27;+ color: #fff;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ min-height: 100vh;+ padding: 20px;+ }++ .container {+ max-width: 800px;+ width: 100%;+ }++ h1 {+ text-align: center;+ margin-bottom: 20px;+ font-size: 28px;+ }++ .info {+ background: rgba(255, 255, 255, 0.05);+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: 8px;+ padding: 16px;+ margin-bottom: 20px;+ font-size: 14px;+ line-height: 1.6;+ }++ .viewer-frame {+ background: #000;+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: 8px;+ overflow: hidden;+ aspect-ratio: 16 / 9;+ margin-bottom: 20px;+ }++ #agent3d {+ width: 100%;+ height: 100%;+ }++ .controls {+ display: flex;+ gap: 10px;+ flex-wrap: wrap;+ justify-content: center;+ }++ button {+ background: rgba(59, 130, 246, 0.8);+ border: none;+ color: #fff;+ padding: 10px 20px;+ border-radius: 6px;+ cursor: pointer;+ font-size: 14px;+ transition: background 0.2s;+ }++ button:hover {+ background: rgba(59, 130, 246, 1);+ }++ button:active {+ transform: scale(0.98);+ }++ .input-group {+ display: flex;+ gap: 10px;+ align-items: center;+ margin-bottom: 10px;+ }++ input {+ background: rgba(255, 255, 255, 0.1);+ border: 1px solid rgba(255, 255, 255, 0.2);+ color: #fff;+ padding: 8px 12px;+ border-radius: 4px;+ flex: 1;+ }++ input::placeholder {+ color: rgba(255, 255, 255, 0.5);+ }+ </style>+ </head>+ <body>+ <div class="container">+ <h1>3D Agent Artifact Viewer</h1>++ <div class="info">+ <p>+ This demo shows how a 3D Agent renders inside a Claude Artifact. The bundle is+ self-contained — no external dependencies or iframes.+ </p>+ </div>++ <div class="input-group">+ <input+ type="text"+ id="agentIdInput"+ placeholder="Enter agent ID (e.g., from URL ?agentId=123)"+ value=""+ />+ <button onclick="loadAgent()">Load</button>+ </div>++ <div class="viewer-frame">+ <div id="agent3d" data-origin="https://3dagent.vercel.app"></div>+ </div>++ <div class="controls">+ <button onclick="reloadAgent()">Reload</button>+ </div>+ </div>++ <!-- The artifact bundle -->+ <script src="artifact.js"></script>++ <script>+ function getAgentIdFromUrl() {+ const params = new URLSearchParams(window.location.search);+ return params.get('agentId') || localStorage.getItem('demo-agentId');+ }++ function loadAgent() {+ const input = document.getElementById('agentIdInput');+ const agentId = input.value.trim();++ if (!agentId) {+ alert('Please enter an agent ID');+ return;+ }++ localStorage.setItem('demo-agentId', agentId);+ const container = document.getElementById('agent3d');+ container.dataset.agentId = agentId;++ location.reload();+ }++ function reloadAgent() {+ location.reload();+ }++ window.addEventListener('DOMContentLoaded', () => {+ const agentId = getAgentIdFromUrl();+ if (agentId) {+ const container = document.getElementById('agent3d');+ container.dataset.agentId = agentId;+ document.getElementById('agentIdInput').value = agentId;+ }+ });+ </script>+ </body>+</html>diff --git a/public/artifact/snippet.html b/public/artifact/snippet.htmlnew file mode 100644index 000000000..6a4e61bca--- /dev/null+++ b/public/artifact/snippet.html@@ -0,0 +1,12 @@+<!-- Paste this into a Claude Artifact to embed a 3D Agent -->+<script src="https://3dagent.vercel.app/artifact.js"></script>++<div id="agent3d" data-agent-id="your-agent-id-here" data-origin="https://3dagent.vercel.app"></div>++<style>+ #agent3d {+ width: 100%;+ height: 500px;+ display: block;+ }+</style>diff --git a/public/cz/README.md b/public/cz/README.mdnew file mode 100644index 000000000..7719d6556--- /dev/null+++ b/public/cz/README.md@@ -0,0 +1,131 @@+# CZ Demo — Landing & Claim Flow++The CZ landing page is served at `/cz/` and provides:++- Full-bleed dark landing page with centered 3D agent avatar+- **Claim CZ** button — initiates wallet connection and claim flow+- **Copy embed** button — copies `<agent-3d>` snippet to clipboard+- Footer — displays on-chain state (chain, agentId, metadataURI)+- Custom event analytics via `window.dispatchEvent('cz-demo-event', ...)`++## Files++- `index.html` — Main landing page+- `boot.js` — Client-side initialization and claim flow UI+- `state.json` — On-chain state stub (updated by `prompts/cz-demo/01-pre-register.js`)++## State Schema++`state.json` is a JSON file with this shape:++```json+{+ "status": "pre-onchain" | "onchain",+ "chainId": null | number,+ "agentId": null | number,+ "metadataURI": null | string,+ "ownerAddress": null | "0x0..." | string,+ "avatarUrl": "/avatars/cz.glb" | string+}+```++**Fields:**++- `status` — `"pre-onchain"` (not yet registered) or `"onchain"` (registered)+- `chainId` — Chain ID (e.g., `8453` for Base, `84532` for Base Sepolia), or `null`+- `agentId` — Token ID from IdentityRegistry, or `null`+- `metadataURI` — IPFS/HTTPS URL of the full registration JSON, or `null`+- `ownerAddress` — Current owner address, `"0x0..."` (unclaimed), or `null`+- `avatarUrl` — GLB URL (default `/avatars/cz.glb`)++The landing page footer displays the state. In `pre-onchain`, it shows "Not yet onchain".++## Claim Flow++The `startClaim()` function in `src/cz-flow.js` handles:++1. **Pre-onchain** — Shows modal: "Claim opens when CZ is registered"+2. **Unclaimed** (`ownerAddress === "0x0..."`): Calls `IdentityRegistry.claim(agentId)`+3. **Demo EOA transfer**: Guides user through `transferOwner()`+4. **Already owned**: Shows modal with current owner++All steps emit progress via `onProgress({ step, status, txHash?, error? })` and fire custom events:++- `landing_view` — Page loaded+- `claim_start` — Claim button clicked+- `claim_wallet_connected` — Wallet connected (implicit in flow)+- `claim_tx_sent` — Transaction sent+- `claim_complete` — Claim successful+- `claim_error` — Error occurred+- `embed_copied` — Embed snippet copied++Listen for these on `window`:++```js+window.addEventListener('cz-demo-event', (e) => {+ console.log(e.detail.event, e.detail.props);+});+```++## Routing++The page is served at `/cz/` by the Vite dev server and Vercel (`public/cz/` → `/cz/`).++To add `/cz` (without trailing slash) or a custom route, edit:++- **Local dev**: `vite.config.js` — `vercel-rewrites` plugin+- **Production**: `vercel.json` — `rewrites` array++Example for `vercel.json`:++```json+{+ "rewrites": [+ { "source": "/cz", "destination": "/cz/" }+ ]+}+```++Then run `npm run deploy` to push changes.++## Integration with `prompts/cz-demo/01-pre-register.js`++When the onchain pre-registration is ready, that script will:++1. Deploy / verify the ERC-8004 IdentityRegistry if needed+2. Call `register()` with the GLB and metadata+3. Write an updated `public/cz/state.json` with real `chainId`, `agentId`, `metadataURI`, `ownerAddress`++The landing page will automatically reflect this state on next load.++## Accessibility++- Semantic `<h1>` for the headline+- `aria-label` on all buttons+- Focus rings visible (2px outline with 2px offset)+- Reduced motion support (`prefers-reduced-motion`)+- Modal keyboard-escapable++## Testing++```bash+npm run dev+# Open http://localhost:3000/cz/++# Should show:+# - Avatar loading from /avatars/cz.glb+# - "Claim CZ" button clickable+# - "Copy embed" button copies snippet to clipboard+# - Footer shows "Not yet onchain"+```++Test the claim flow:++```js+// Open browser console on /cz/+window.addEventListener('cz-demo-event', (e) => {+ console.log('CZ demo event:', e.detail);+});++// Click "Claim CZ" → follow wallet prompts+```diff --git a/public/cz/boot.js b/public/cz/boot.jsnew file mode 100644index 000000000..e9a3824c9--- /dev/null+++ b/public/cz/boot.js@@ -0,0 +1,188 @@+/**+ * CZ landing page initialization — loads state, wires up CTAs, handles claim flow.+ */++import { startClaim, mountEmbedCopy, fireAnalytics } from '../../src/cz-flow.js';++async function init() {+ // Load state+ let state = {+ status: 'pre-onchain',+ chainId: null,+ agentId: null,+ metadataURI: null,+ ownerAddress: null,+ avatarUrl: '/avatars/cz.glb',+ };++ try {+ const res = await fetch('./state.json');+ if (res.ok) {+ state = await res.json();+ }+ } catch (err) {+ console.warn('Failed to load state.json:', err);+ }++ // Update footer with state+ updateFooter(state);++ // Wire up claim button+ const claimBtn = document.getElementById('cz-claim-btn');+ if (claimBtn) {+ claimBtn.addEventListener('click', () => handleClaimClick(state));+ }++ // Wire up embed copy+ const embedContainer = document.getElementById('cz-embed-container');+ if (embedContainer) {+ mountEmbedCopy(embedContainer, { state });+ }++ // Fire landing view event+ fireAnalytics('landing_view', { status: state.status });+}++function updateFooter(state) {+ const footer = document.getElementById('cz-footer');+ if (!footer) return;++ if (state.status === 'pre-onchain') {+ footer.innerHTML = `+ <p>Not yet onchain</p>+ `;+ } else {+ const chainName = getChainName(state.chainId);+ footer.innerHTML = `+ <p><strong>Chain:</strong> ${chainName}</p>+ <p><strong>Agent ID:</strong> ${state.agentId}</p>+ ${state.metadataURI ? `<p><strong>Metadata:</strong> <code>${truncate(state.metadataURI, 40)}</code></p>` : ''}+ `;+ }+}++function getChainName(chainId) {+ const chains = {+ 1: 'Ethereum',+ 8453: 'Base',+ 84532: 'Base Sepolia',+ };+ return chains[chainId] || `Chain ${chainId}`;+}++function truncate(str, len) {+ return str.length > len ? str.slice(0, len - 3) + '…' : str;+}++async function handleClaimClick(state) {+ const claimBtn = document.getElementById('cz-claim-btn');+ const modal = document.getElementById('cz-claim-modal');++ if (!modal) return;++ fireAnalytics('claim_start', {});++ // Show modal with spinner+ modal.style.display = 'flex';+ const content = document.getElementById('cz-modal-content');+ const closeBtn = document.getElementById('cz-modal-close');++ content.innerHTML = `+ <div class="modal-spinner"></div>+ <p>Initializing claim flow…</p>+ `;++ closeBtn.addEventListener('click', () => {+ modal.style.display = 'none';+ });++ modal.addEventListener('click', (e) => {+ if (e.target === modal) modal.style.display = 'none';+ });++ // Run claim flow+ const result = await startClaim({+ state,+ onProgress: (progress) => {+ updateModal(progress, state);+ },+ });++ if (result.ok) {+ if (result.message === 'pre_onchain') {+ content.innerHTML = `+ <h3 style="margin:0 0 1rem">Coming Soon</h3>+ <p>CZ is not yet registered on-chain. Claiming opens once the registration is complete.</p>+ <button class="modal-close-btn" onclick="document.getElementById('cz-claim-modal').style.display='none'">OK</button>+ `;+ } else if (result.message === 'already_owned') {+ content.innerHTML = `+ <h3 style="margin:0 0 1rem">Already Claimed</h3>+ <p>This agent is already owned by <code>${truncate(state.ownerAddress, 20)}</code>.</p>+ <button class="modal-close-btn" onclick="document.getElementById('cz-claim-modal').style.display='none'">OK</button>+ `;+ } else if (result.message === 'transfer_available') {+ content.innerHTML = `+ <h3 style="margin:0 0 1rem">Transfer Ownership</h3>+ <p>This agent can be transferred to your wallet. Follow the prompts to continue.</p>+ <button class="modal-close-btn" onclick="document.getElementById('cz-claim-modal').style.display='none'">OK</button>+ `;+ } else {+ content.innerHTML = `+ <h3 style="margin:0 0 1rem">Claim Successful</h3>+ <p>Transaction: <code>${result.txHash}</code></p>+ <button class="modal-close-btn" onclick="document.getElementById('cz-claim-modal').style.display='none'">OK</button>+ `;+ }+ } else {+ content.innerHTML = `+ <h3 style="margin:0 0 1rem">Error</h3>+ <p>${result.error}</p>+ <button class="modal-close-btn" onclick="document.getElementById('cz-claim-modal').style.display='none'">Dismiss</button>+ `;+ }+}++function updateModal(progress, state) {+ const content = document.getElementById('cz-modal-content');+ const { step, status, error } = progress;++ if (error) {+ content.innerHTML = `+ <h3 style="margin:0 0 1rem">Error</h3>+ <p>${error}</p>+ `;+ return;+ }++ const messages = {+ connect_wallet: {+ connecting: 'Connecting wallet…',+ connected: `Connected: ${progress.address?.slice(0, 10)}…`,+ },+ check_state: {+ pre_onchain: 'Checking agent status…',+ },+ claim: {+ submitting: 'Submitting claim…',+ pending: 'Waiting for confirmation…',+ confirmed: 'Claim confirmed!',+ already_owned: 'Already owned.',+ },+ transfer: {+ guide: 'Transfer available. Approve in your wallet…',+ },+ };++ const msg = messages[step]?.[status] || `${step}: ${status}`;+ content.innerHTML = `+ <div class="modal-spinner"></div>+ <p>${msg}</p>+ `;+}++if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', init);+} else {+ init();+}diff --git a/public/cz/index.html b/public/cz/index.htmlnew file mode 100644index 000000000..38d649ee6--- /dev/null+++ b/public/cz/index.html@@ -0,0 +1,321 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <title>Claim CZ · 3D Agent</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <meta name="description" content="Meet CZ — an embodied 3D AI agent." />+ <meta name="theme-color" content="#000000" />+ <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: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ padding: 24px;+ }++ .cz-hero {+ width: 100%;+ max-width: 600px;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 2rem;+ }++ .cz-avatar-container {+ width: 100%;+ max-width: 400px;+ aspect-ratio: 1;+ border-radius: 12px;+ overflow: hidden;+ box-shadow: 0 20px 60px rgba(0, 0, 0, 0.4);+ }++ agent-3d {+ width: 100%;+ height: 100%;+ }++ .cz-content {+ text-align: center;+ width: 100%;+ }++ h1 {+ font-size: 2.5rem;+ margin: 0 0 0.5rem;+ letter-spacing: -0.02em;+ font-weight: 300;+ }++ .cz-subhead {+ font-size: 1.1rem;+ color: rgba(255, 255, 255, 0.6);+ margin: 0 0 2rem;+ line-height: 1.6;+ }++ .cz-cta-group {+ display: flex;+ flex-direction: column;+ gap: 12px;+ width: 100%;+ }++ button {+ padding: 14px 24px;+ border: none;+ border-radius: 10px;+ font-size: 15px;+ font-weight: 600;+ cursor: pointer;+ transition: all 0.2s ease;+ }++ #cz-claim-btn {+ background: linear-gradient(135deg, var(--accent), var(--accent2));+ color: #fff;+ }++ #cz-claim-btn:hover {+ transform: translateY(-2px);+ box-shadow: 0 8px 24px rgba(106, 92, 255, 0.3);+ }++ #cz-claim-btn:focus {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+ }++ #cz-claim-btn:active {+ transform: translateY(0);+ }++ #cz-embed-container {+ display: flex;+ }++ #cz-embed-copy {+ background: rgba(255, 255, 255, 0.1);+ border: 1px solid rgba(255, 255, 255, 0.2);+ color: #eee;+ width: 100%;+ }++ #cz-embed-copy:hover {+ background: rgba(255, 255, 255, 0.15);+ border-color: rgba(255, 255, 255, 0.3);+ }++ #cz-embed-copy:focus {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+ }++ .cz-footer {+ margin-top: 3rem;+ padding-top: 2rem;+ border-top: 1px solid rgba(255, 255, 255, 0.1);+ font-size: 0.875rem;+ color: rgba(255, 255, 255, 0.5);+ width: 100%;+ text-align: center;+ }++ .cz-footer p {+ margin: 0.5rem 0;+ }++ .cz-footer code {+ background: rgba(255, 255, 255, 0.05);+ padding: 2px 6px;+ border-radius: 4px;+ font-family: 'Courier New', monospace;+ font-size: 0.8rem;+ color: rgba(255, 255, 255, 0.7);+ }++ /* Modal */+ #cz-claim-modal {+ display: none;+ position: fixed;+ top: 0;+ left: 0;+ right: 0;+ bottom: 0;+ background: rgba(0, 0, 0, 0.7);+ z-index: 2000;+ align-items: center;+ justify-content: center;+ padding: 24px;+ }++ .cz-modal-dialog {+ background: #14141c;+ border: 1px solid #2a2a36;+ border-radius: 16px;+ padding: 32px;+ max-width: 420px;+ width: 100%;+ position: relative;+ box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);+ }++ #cz-modal-close {+ position: absolute;+ top: 16px;+ right: 16px;+ background: none;+ border: none;+ color: rgba(255, 255, 255, 0.5);+ cursor: pointer;+ padding: 8px;+ font-size: 1.5rem;+ display: flex;+ align-items: center;+ justify-content: center;+ }++ #cz-modal-close:hover {+ color: rgba(255, 255, 255, 0.8);+ }++ #cz-modal-content {+ text-align: center;+ min-height: 100px;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ }++ #cz-modal-content h3 {+ font-size: 1.2rem;+ font-weight: 600;+ }++ #cz-modal-content p {+ color: rgba(255, 255, 255, 0.7);+ margin: 0.5rem 0;+ line-height: 1.5;+ }++ #cz-modal-content code {+ background: rgba(255, 255, 255, 0.05);+ padding: 4px 8px;+ border-radius: 4px;+ font-family: 'Courier New', monospace;+ font-size: 0.85rem;+ color: rgba(255, 255, 255, 0.8);+ word-break: break-all;+ }++ .modal-spinner {+ width: 40px;+ height: 40px;+ border: 3px solid rgba(106, 92, 255, 0.2);+ border-top-color: var(--accent);+ border-radius: 50%;+ animation: spin 0.8s linear infinite;+ margin-bottom: 1rem;+ }++ @keyframes spin {+ to {+ transform: rotate(360deg);+ }+ }++ .modal-close-btn {+ margin-top: 1.5rem;+ width: 100%;+ background: linear-gradient(135deg, var(--accent), var(--accent2));+ color: #fff;+ }++ .modal-close-btn:hover {+ transform: translateY(-2px);+ box-shadow: 0 8px 24px rgba(106, 92, 255, 0.3);+ }++ /* Responsive */+ @media (max-width: 640px) {+ h1 {+ font-size: 2rem;+ }++ .cz-hero {+ gap: 1.5rem;+ }++ .cz-avatar-container {+ max-width: 100%;+ }+ }++ /* Reduced motion */+ @media (prefers-reduced-motion: reduce) {+ button {+ transition: none;+ }++ .modal-spinner {+ animation: none;+ border-top-color: var(--accent);+ }+ }+ </style>+</head>+<body>+ <div class="cz-hero">+ <div class="cz-avatar-container">+ <agent-3d src="/avatars/cz.glb" eager></agent-3d>+ </div>++ <div class="cz-content">+ <h1>Meet CZ</h1>+ <p class="cz-subhead">An embodied 3D AI agent built for the Ethereum ecosystem.</p>++ <div class="cz-cta-group">+ <button id="cz-claim-btn" aria-label="Claim CZ agent ownership">Claim CZ</button>+ <div id="cz-embed-container"></div>+ </div>+ </div>++ <div class="cz-footer" id="cz-footer">+ <p>Not yet onchain</p>+ </div>+ </div>++ <!-- Claim Modal -->+ <div id="cz-claim-modal">+ <div class="cz-modal-dialog">+ <button id="cz-modal-close" aria-label="Close claim dialog">×</button>+ <div id="cz-modal-content">+ <div class="modal-spinner"></div>+ <p>Loading…</p>+ </div>+ </div>+ </div>++ <script type="module" src="./boot.js"></script>+</body>+</html>diff --git a/public/cz/offline/README.md b/public/cz/offline/README.mdnew file mode 100644index 000000000..103548d5e--- /dev/null+++ b/public/cz/offline/README.md@@ -0,0 +1,206 @@+# CZ Offline Fallback Demo++This directory contains the offline fallback for the CZ demo — a self-contained, zero-network-dependency copy of the demo that the operator can display if live internet fails during the event.++## Overview++**Purpose:** Keep the demo running when the internet dies, RPC node is down, or the staging server is unreachable.++**File:** `index.html` — standalone HTML page with embedded assets.++**Network:** Zero external dependencies after initial page load. Avatar and state are served from origin only.++**Usage:** Open `https://3dagent.vercel.app/cz/offline/` in a browser, or `http://localhost:3000/cz/offline/` for local dev.++---++## 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)+- **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)+- **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++---++## Testing the Offline Fallback++### Test 1: Network Throttling+```bash+# Open DevTools → Network tab+# Set throttling to "Offline"+# Reload the page+# Avatar and claim flow should still work+```++### Test 2: Hard Offline (Kill WiFi)+```bash+# Open /cz/offline/ in a browser+# Physically unplug ethernet or disable WiFi+# Page should still display avatar and respond to clicks+```++### Test 3: Origin Unreachable+```bash+# Open /cz/offline/ normally+# Block the origin in DevTools (DevTools → Network → Disable)+# Reload page (from browser cache)+# Fallback image and claim flow work+```++### Test 4: Timing (Dry Run)+```bash+# Open /cz/offline/+# Click "Claim Agent" button+# Observe:+# - First modal appears at 0ms: "Initializing…"+# - Second modal at 800ms: "Connecting…"+# - Confetti at 3200ms+# Total: ~4 seconds from click to success+```++---++## 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 |++---++## 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+// etc.+```++### 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 */+```++### 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';+ ```++---++## 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+- [ ] Parameterize agentId and chain from URL query params+- [ ] Add pre-recorded video loop of agent interaction (if available)+- [ ] Support keyboard controls (arrow keys for camera, Space to claim)++---++## Files++- `index.html` — Main offline page (this is all you need)+- `README.md` — This file++---++## 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)++---++## Contact / Issues++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.htmlnew file mode 100644index 000000000..d40525829--- /dev/null+++ b/public/cz/offline/index.html@@ -0,0 +1,445 @@+<!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>++ <div class="container">+ <div class="avatar-container">+ <canvas id="viewer"></canvas>+ <img id="fallback" class="fallback-image" alt="CZ Avatar" />+ </div>+ </div>++ <div class="modal" id="modal">+ <div class="modal-content">+ <div id="modal-body"></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>+ <div class="footer-item">•</div>+ <div class="footer-item">+ Chain: <span class="code">Base Sepolia</span>+ </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++ 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++ function showModal(html) {+ modalBody.innerHTML = html;+ modal.classList.add('active');+ }++ function hideModal() {+ modal.classList.remove('active');+ }++ // Simulate claim flow+ function handleClaimClick() {+ showModal(`+ <div class="spinner"></div>+ <p>Initializing claim flow...</p>+ `);++ setTimeout(() => {+ showModal(`+ <div class="spinner"></div>+ <p>Connecting wallet...</p>+ `);+ }, 800);++ setTimeout(() => {+ showModal(`+ <div class="spinner"></div>+ <p>Submitting claim...</p>+ `);+ }, 1600);++ setTimeout(() => {+ showModal(`+ <div class="spinner"></div>+ <p>Waiting for confirmation...</p>+ `);+ }, 2400);++ 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 = `+ @keyframes fall-${i} {+ to {+ transform: translateY(${window.innerHeight + 20}px) rotate(720deg);+ opacity: 0;+ }+ }+ `;+ const style = document.createElement('style');+ style.textContent = keyframes;+ document.head.appendChild(style);++ confetti.style.animation = `fall-${i} ${duration}s ease-in forwards`;++ 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;+ }++ // 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;+ }++ // 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();+ }+ }++ 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 = `+ <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);+ });+ }++ console.log('CZ Offline Demo initialized');+ </script>+</body>+</html>diff --git a/public/cz/state.json b/public/cz/state.jsonnew file mode 100644index 000000000..e31fd0a94--- /dev/null+++ b/public/cz/state.json@@ -0,0 +1,8 @@+{+ "status": "pre-onchain",+ "chainId": null,+ "agentId": null,+ "metadataURI": null,+ "ownerAddress": null,+ "avatarUrl": "/avatars/cz.glb"+}diff --git a/public/dashboard/actions.html b/public/dashboard/actions.htmlnew file mode 100644index 000000000..493e61cab--- /dev/null+++ b/public/dashboard/actions.html@@ -0,0 +1,602 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <title>Action Log — 3D Agent</title>+ <style>+ :root {+ color-scheme: dark;+ --accent: #6a5cff;+ --accent2: #ff5ca8;+ --border: #22222e;+ --bg: #0b0b10;+ --panel: #14141c;+ }+ * {+ box-sizing: border-box;+ }+ body {+ font:+ 15px/1.55 system-ui,+ -apple-system,+ Segoe UI,+ Roboto,+ sans-serif;+ color: #eee;+ margin: 0;+ background: var(--bg);+ min-height: 100vh;+ }+ a {+ color: #9a8cff;+ text-decoration: none;+ }+ .container {+ max-width: 900px;+ margin: 0 auto;+ padding: 28px;+ }+ h1 {+ font-size: 22px;+ margin: 0 0 6px;+ letter-spacing: -0.01em;+ }+ .header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ margin-bottom: 20px;+ gap: 20px;+ flex-wrap: wrap;+ }+ .agent-info {+ flex: 1;+ min-width: 300px;+ }+ .sub {+ color: #888;+ margin: 4px 0 0;+ font-size: 14px;+ }+ .signer-pill {+ display: inline-block;+ background: rgba(106, 92, 255, 0.15);+ border: 1px solid var(--accent);+ border-radius: 999px;+ padding: 4px 12px;+ font-size: 13px;+ margin-top: 8px;+ color: #aaa;+ font-family: monospace;+ }+ .signer-pill.verified {+ background: rgba(34, 197, 94, 0.1);+ border-color: #22c55e;+ color: #86efac;+ }+ .actions-toolbar {+ display: flex;+ gap: 8px;+ align-items: center;+ margin-bottom: 20px;+ flex-wrap: wrap;+ }+ .filter-chip {+ padding: 6px 14px;+ border: 1px solid var(--border);+ background: transparent;+ color: #aaa;+ border-radius: 999px;+ cursor: pointer;+ font-size: 13px;+ transition: all 0.2s;+ }+ .filter-chip:hover {+ border-color: var(--accent);+ color: #fff;+ }+ .filter-chip.active {+ background: var(--accent);+ border-color: var(--accent);+ color: #fff;+ }+ .export-btn {+ margin-left: auto;+ padding: 6px 14px;+ border: 1px solid var(--border);+ background: transparent;+ color: #aaa;+ border-radius: 4px;+ cursor: pointer;+ font-size: 13px;+ transition: all 0.2s;+ }+ .export-btn:hover {+ border-color: var(--accent);+ color: var(--accent);+ }+ .timeline {+ display: flex;+ flex-direction: column;+ gap: 12px;+ }+ .action-row {+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 6px;+ padding: 14px;+ cursor: pointer;+ transition: all 0.2s;+ }+ .action-row:hover {+ border-color: var(--accent);+ background: rgba(106, 92, 255, 0.04);+ }+ .action-row.expanded {+ border-color: var(--accent);+ }+ .action-row-header {+ display: flex;+ align-items: center;+ gap: 12px;+ }+ .action-icon {+ width: 20px;+ height: 20px;+ display: flex;+ align-items: center;+ justify-content: center;+ font-size: 12px;+ border-radius: 3px;+ flex-shrink: 0;+ }+ .action-icon.speak {+ background: rgba(106, 92, 255, 0.2);+ color: #a5b4fc;+ }+ .action-icon.remember {+ background: rgba(34, 197, 94, 0.2);+ color: #86efac;+ }+ .action-icon.sign {+ background: rgba(168, 85, 247, 0.2);+ color: #d8b4fe;+ }+ .action-icon.skill-done {+ background: rgba(59, 130, 246, 0.2);+ color: #93c5fd;+ }+ .action-icon.validate {+ background: rgba(249, 115, 22, 0.2);+ color: #fed7aa;+ }+ .action-icon.load-end {+ background: rgba(236, 72, 153, 0.2);+ color: #f472b6;+ }+ .action-summary {+ flex: 1;+ display: flex;+ flex-direction: column;+ gap: 4px;+ min-width: 0;+ }+ .action-type {+ font-weight: 600;+ font-size: 14px;+ color: #fff;+ }+ .action-preview {+ color: #aaa;+ font-size: 13px;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }+ .action-meta {+ display: flex;+ align-items: center;+ gap: 12px;+ }+ .verify-badge {+ width: 20px;+ height: 20px;+ display: flex;+ align-items: center;+ justify-content: center;+ font-size: 12px;+ flex-shrink: 0;+ }+ .verify-badge.verified {+ color: #22c55e;+ }+ .verify-badge.unverified {+ color: #888;+ }+ .verify-badge.unsigned {+ color: #666;+ }+ .action-time {+ color: #666;+ font-size: 12px;+ flex-shrink: 0;+ }+ .action-time:hover {+ color: #aaa;+ }+ .action-detail {+ display: none;+ margin-top: 14px;+ padding-top: 14px;+ border-top: 1px solid var(--border);+ }+ .action-row.expanded .action-detail {+ display: block;+ }+ .json-block {+ background: rgba(0, 0, 0, 0.3);+ border: 1px solid var(--border);+ border-radius: 4px;+ padding: 12px;+ font-family: monospace;+ font-size: 12px;+ color: #888;+ overflow-x: auto;+ max-height: 300px;+ overflow-y: auto;+ }+ .empty-state {+ text-align: center;+ color: #666;+ padding: 40px 20px;+ }+ .empty-state-icon {+ font-size: 40px;+ margin-bottom: 12px;+ }+ .loading {+ text-align: center;+ color: #666;+ padding: 40px 20px;+ }+ .error-msg {+ background: rgba(239, 68, 68, 0.1);+ border: 1px solid #ef4444;+ color: #fca5a5;+ padding: 12px 14px;+ border-radius: 6px;+ margin-bottom: 20px;+ }+ .infinite-scroll-trigger {+ height: 1px;+ margin-top: 20px;+ }+ </style>+ </head>+ <body>+ <div class="container">+ <div class="header">+ <div class="agent-info">+ <h1 id="agent-name">Action Log</h1>+ <div class="sub" id="agent-id"></div>+ <div class="signer-pill" id="signer-pill" style="display: none"></div>+ </div>+ </div>++ <div id="error-msg"></div>++ <div class="actions-toolbar">+ <button class="filter-chip active" data-filter="all">All</button>+ <button class="filter-chip" data-filter="speak">Speak</button>+ <button class="filter-chip" data-filter="remember">Remember</button>+ <button class="filter-chip" data-filter="sign">Sign</button>+ <button class="filter-chip" data-filter="skill-done">Skill Done</button>+ <button class="filter-chip" data-filter="validate">Validate</button>+ <button class="filter-chip" data-filter="load-end">Load End</button>+ <button class="export-btn" id="export-btn">Download JSON</button>+ </div>++ <div id="timeline" class="timeline"></div>+ <div class="infinite-scroll-trigger" id="scroll-trigger"></div>+ </div>++ <script>+ const pageSize = 50;+ let currentFilter = 'all';+ let allActions = [];+ let nextCursor = null;+ let isLoading = false;+ let hasMore = true;++ const params = new URLSearchParams(location.search);+ const agentId = params.get('agent');+ if (!agentId) {+ showError('Missing ?agent= parameter.');+ document.body.innerHTML = '';+ document.body.appendChild(+ Object.assign(document.createElement('div'), {+ textContent: 'Missing ?agent= parameter. Expected: ?agent=<id>',+ style: 'color:#f87171;padding:20px;',+ }),+ );+ }++ // Auth check+ (async () => {+ try {+ const r = await fetch(`/api/agents/${agentId}/actions?limit=1`, {+ credentials: 'include',+ });+ if (r.status === 401) {+ window.location.href = `/login?next=/dashboard/actions.html?agent=${agentId}`;+ return;+ }+ if (r.status === 403) {+ showError('Not authorized to view this agent.');+ return;+ }+ if (r.status === 404) {+ showError('Agent not found.');+ return;+ }+ if (!r.ok) {+ showError(`Error ${r.status}`);+ return;+ }++ const data = await r.json();+ const { actions, nextCursor: nc } = data;++ // Fetch agent info+ const agentR = await fetch(`/api/agents/${agentId}`, {+ credentials: 'include',+ });+ if (agentR.ok) {+ const agentData = await agentR.json();+ const agent = agentData.agent;+ document.getElementById('agent-name').textContent = agent?.name || agentId;+ document.getElementById('agent-id').textContent = `${agentId}${+ agent?.wallet_address ? ` · ${agent.wallet_address.slice(0, 10)}…` : ''+ }`;++ if (agent?.wallet_address) {+ const pill = document.getElementById('signer-pill');+ pill.textContent = `Signed by ${agent.wallet_address.slice(0, 10)}…${agent.wallet_address.slice(+ -8,+ )}`;+ pill.className = 'signer-pill verified';+ pill.style.display = 'inline-block';+ }+ }++ // Load initial page+ nextCursor = nc;+ await loadMore();+ } catch (e) {+ showError(`Fetch failed: ${e.message}`);+ }+ })();++ // IntersectionObserver for infinite scroll+ const observer = new IntersectionObserver(+ (entries) => {+ if (entries[0].isIntersecting && !isLoading && hasMore) {+ loadMore();+ }+ },+ { rootMargin: '200px' },+ );++ observer.observe(document.getElementById('scroll-trigger'));++ // Load more actions+ async function loadMore() {+ if (isLoading || !hasMore) return;+ isLoading = true;++ try {+ const url = new URL(`/api/agents/${agentId}/actions`, window.location.origin);+ url.searchParams.set('limit', pageSize);+ if (nextCursor) {+ url.searchParams.set('cursor', nextCursor);+ }++ const r = await fetch(url, { credentials: 'include' });+ if (!r.ok) {+ hasMore = false;+ return;+ }++ const data = await r.json();+ const { actions, nextCursor: nc } = data;++ allActions.push(...actions);+ nextCursor = nc;+ hasMore = Boolean(nc);++ render();+ } catch (e) {+ console.error('loadMore failed:', e);+ } finally {+ isLoading = false;+ }+ }++ // Filter changes+ document.querySelectorAll('.filter-chip').forEach((btn) => {+ btn.addEventListener('click', () => {+ document+ .querySelectorAll('.filter-chip')+ .forEach((b) => b.classList.remove('active'));+ btn.classList.add('active');+ currentFilter = btn.dataset.filter;+ render();+ });+ });++ // Export+ document.getElementById('export-btn').addEventListener('click', () => {+ const filtered = getFiltered();+ const json = JSON.stringify(filtered, null, 2);+ const blob = new Blob([json], { type: 'application/json' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = `actions-${agentId}-${new Date().toISOString().split('T')[0]}.json`;+ a.click();+ URL.revokeObjectURL(url);+ });++ function getFiltered() {+ if (currentFilter === 'all') return allActions;+ return allActions.filter((a) => a.type === currentFilter);+ }++ function render() {+ const filtered = getFiltered();+ const timeline = document.getElementById('timeline');++ if (filtered.length === 0 && allActions.length === 0) {+ timeline.innerHTML =+ '<div class="empty-state"><div class="empty-state-icon">—</div><div>No actions yet.</div></div>';+ return;+ }++ if (filtered.length === 0) {+ timeline.innerHTML =+ '<div class="empty-state"><div class="empty-state-icon">—</div><div>No actions match this filter.</div></div>';+ return;+ }++ timeline.innerHTML = filtered.map((action) => renderRow(action)).join('');++ // Add expand listeners+ document.querySelectorAll('.action-row').forEach((row) => {+ row.addEventListener('click', () => {+ row.classList.toggle('expanded');+ });+ });+ }++ function renderRow(action) {+ const type = action.type;+ const preview = summarizePayload(action.payload);+ const timestamp = new Date(action.timestamp);+ const now = new Date();+ const relTime = formatRelativeTime(timestamp, now);++ let verifyIcon = '—';+ let verifyClass = 'unsigned';+ if (action.signature) {+ if (action.verified === true) {+ verifyIcon = '✓';+ verifyClass = 'verified';+ } else if (action.verified === false) {+ verifyIcon = '✗';+ verifyClass = 'unverified';+ }+ }++ return `+ <div class="action-row" data-id="${action.id}">+ <div class="action-row-header">+ <div class="action-icon ${type}">+ ${getTypeIcon(type)}+ </div>+ <div class="action-summary">+ <div class="action-type">${escapeHtml(type)}</div>+ <div class="action-preview">${escapeHtml(preview)}</div>+ </div>+ <div class="action-meta">+ <div class="verify-badge ${verifyClass}" title="${+ action.verified === true+ ? 'Verified'+ : action.verified === false+ ? 'Invalid signature'+ : 'Unsigned'+ }">${verifyIcon}</div>+ <div class="action-time" title="${timestamp.toISOString()}">${escapeHtml(relTime)}</div>+ </div>+ </div>+ <div class="action-detail">+ <div class="json-block">${escapeHtml(JSON.stringify(action.payload, null, 2))}</div>+ ${+ action.signer+ ? `<div style="margin-top:8px;color:#666;font-size:12px">Signer: <code style="color:#888">${escapeHtml(+ action.signer,+ )}</code></div>`+ : ''+ }+ </div>+ </div>+ `;+ }++ function getTypeIcon(type) {+ const icons = {+ speak: '💬',+ remember: '📝',+ sign: '✍️',+ 'skill-done': '✓',+ validate: '✔',+ 'load-end': '📦',+ };+ return icons[type] || '•';+ }++ function summarizePayload(payload) {+ if (typeof payload !== 'object' || !payload) return '(empty)';+ const keys = Object.keys(payload);+ if (keys.length === 0) return '(empty)';++ // For speak actions, show the text+ if (payload.text) return payload.text.slice(0, 80);++ // For remember, show content+ if (payload.content) return payload.content.slice(0, 80);++ // Generic: show key=value preview+ const parts = keys.slice(0, 2).map((k) => {+ const v = payload[k];+ if (typeof v === 'string') return `${k}=${v.slice(0, 30)}`;+ if (typeof v === 'number') return `${k}=${v}`;+ if (typeof v === 'boolean') return `${k}=${v}`;+ return `${k}=(object)`;+ });+ return parts.join(', ');+ }++ function formatRelativeTime(date, now) {+ const seconds = Math.floor((now - date) / 1000);++ if (seconds < 60) return `${seconds}s ago`;+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;+ if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;+ if (seconds < 604800) return `${Math.floor(seconds / 86400)}d ago`;++ const months = Math.floor(seconds / 2592000);+ if (months < 12) return `${months}mo ago`;++ return `${Math.floor(seconds / 31536000)}y ago`;+ }++ function showError(msg) {+ const el = document.getElementById('error-msg');+ el.innerHTML = `<div class="error-msg">${escapeHtml(msg)}</div>`;+ }++ function escapeHtml(text) {+ if (!text) return '';+ const map = {+ '&': '&',+ '<': '<',+ '>': '>',+ '"': '"',+ "'": ''',+ };+ return String(text).replace(/[&<>"']/g, (c) => map[c]);+ }+ </script>+ </body>+</html>diff --git a/public/dashboard/sessions.html b/public/dashboard/sessions.htmlnew file mode 100644index 000000000..ff9594a98--- /dev/null+++ b/public/dashboard/sessions.html@@ -0,0 +1,442 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <title>Sessions · 3D Agent</title>+ <link rel="icon" href="/favicon.ico" />+ <style>+ :root {+ color-scheme: dark;+ --accent: #6a5cff;+ --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: 16px 24px;+ border-bottom: 1px solid var(--border);+ position: sticky;+ top: 0;+ background: var(--bg);+ z-index: 5;+ }+ .brand {+ font-weight: 600;+ letter-spacing: -0.01em;+ }+ .row {+ display: flex;+ align-items: center;+ gap: 8px;+ }+ main {+ padding: 28px;+ max-width: 800px;+ }+ h1 {+ font-size: 22px;+ margin: 0 0 6px;+ letter-spacing: -0.01em;+ }+ .sub {+ color: #888;+ margin: 0 0 22px;+ font-size: 14px;+ }+ .btn {+ padding: 9px 14px;+ border-radius: 9px;+ border: 0;+ font-size: 13px;+ font-weight: 600;+ cursor: pointer;+ background: var(--accent);+ color: #fff;+ }+ .btn:disabled {+ opacity: 0.5;+ cursor: not-allowed;+ }+ .btn.sec {+ background: #222230;+ color: #ddd;+ }+ .btn.danger {+ background: #cc4040;+ }+ .btn-group {+ display: flex;+ gap: 8px;+ margin-bottom: 20px;+ }+ table {+ width: 100%;+ border-collapse: collapse;+ border: 1px solid var(--border);+ border-radius: 10px;+ overflow: hidden;+ background: var(--panel);+ }+ thead {+ background: #0f0f17;+ border-bottom: 1px solid var(--border);+ }+ th {+ padding: 12px 16px;+ text-align: left;+ font-size: 12px;+ font-weight: 600;+ text-transform: uppercase;+ letter-spacing: 0.5px;+ color: #888;+ }+ td {+ padding: 12px 16px;+ border-bottom: 1px solid var(--border);+ font-size: 14px;+ }+ tr:last-child td {+ border-bottom: 0;+ }+ .pill {+ display: inline-block;+ font-size: 11px;+ padding: 3px 8px;+ border-radius: 99px;+ background: rgba(106, 92, 255, 0.2);+ color: #a8a0ff;+ white-space: nowrap;+ }+ .agent-cell {+ max-width: 200px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ color: #bbb;+ font-size: 13px;+ }+ .time-cell {+ color: #999;+ font-size: 13px;+ }+ .actions {+ text-align: right;+ }+ .empty {+ text-align: center;+ padding: 40px 20px;+ color: #888;+ }+ .toast {+ position: fixed;+ bottom: 24px;+ left: 50%;+ transform: translateX(-50%);+ background: #1a1a24;+ border: 1px solid var(--border);+ padding: 10px 18px;+ border-radius: 99px;+ font-size: 13px;+ color: #ddd;+ z-index: 70;+ box-shadow: 0 4px 18px rgba(0, 0, 0, 0.4);+ animation: toast-in 0.2s;+ }+ .toast.error {+ background: rgba(204, 64, 64, 0.15);+ border-color: rgba(204, 64, 64, 0.3);+ color: #ffb3b3;+ }+ @keyframes toast-in {+ from {+ opacity: 0;+ transform: translate(-50%, 8px);+ }+ to {+ opacity: 1;+ transform: translateX(-50%);+ }+ }+ .btn-sec {+ background: #222230;+ color: #ddd;+ }+ </style>+ </head>+ <body>+ <header>+ <div class="brand"><a href="/">3D Agent</a></div>+ <button class="btn sec" onclick="signOut()">Sign out</button>+ </header>+ <main>+ <h1>Sessions</h1>+ <p class="sub">Manage your active login sessions across devices.</p>++ <div class="btn-group">+ <button class="btn danger" id="signOutBtn" style="display: none">+ Sign out of all other devices+ </button>+ </div>++ <table id="sessionsTable" style="display: none">+ <thead>+ <tr>+ <th>Device / User Agent</th>+ <th>IP Address</th>+ <th>Created</th>+ <th>Last Seen</th>+ <th class="actions">Actions</th>+ </tr>+ </thead>+ <tbody id="sessionsList"></tbody>+ </table>++ <div class="empty" id="loadingMessage">Loading sessions...</div>+ </main>++ <script>+ function signOut() {+ location.href = '/login';+ }++ function showToast(message, isError = false) {+ const toast = document.createElement('div');+ toast.className = 'toast' + (isError ? ' error' : '');+ toast.textContent = message;+ document.body.appendChild(toast);+ setTimeout(() => {+ toast.remove();+ }, 3000);+ }++ function formatRelativeTime(date) {+ const now = new Date();+ const diff = now - new Date(date);+ const seconds = Math.floor(diff / 1000);+ const minutes = Math.floor(seconds / 60);+ const hours = Math.floor(minutes / 60);+ const days = Math.floor(hours / 24);++ if (seconds < 60) return 'Just now';+ if (minutes < 60) return `${minutes}m ago`;+ if (hours < 24) return `${hours}h ago`;+ if (days < 7) return `${days}d ago`;++ return new Date(date).toLocaleDateString('en-US', {+ month: 'short',+ day: 'numeric',+ });+ }++ function formatAbsoluteDate(date) {+ return new Date(date).toLocaleDateString('en-US', {+ month: 'short',+ day: 'numeric',+ year: 'numeric',+ hour: '2-digit',+ minute: '2-digit',+ });+ }++ function truncateUA(ua) {+ if (!ua) return 'Unknown';+ if (ua.length > 50) return ua.substring(0, 47) + '…';+ return ua;+ }++ async function loadSessions() {+ try {+ const res = await fetch('/api/auth/me', { credentials: 'include' });+ if (res.status === 401) {+ location.href = '/login?next=' + encodeURIComponent(location.pathname);+ return;+ }+ if (!res.ok) throw new Error('Failed to verify auth');++ const sessionsRes = await fetch('/api/auth/sessions', {+ credentials: 'include',+ });+ if (!sessionsRes.ok) throw new Error('Failed to load sessions');++ const { sessions } = await sessionsRes.json();++ const tbody = document.getElementById('sessionsList');+ tbody.innerHTML = '';++ if (sessions.length === 0) {+ document.getElementById('loadingMessage').textContent =+ 'No active sessions';+ return;+ }++ document.getElementById('sessionsTable').style.display = 'table';+ document.getElementById('loadingMessage').style.display = 'none';++ const hasMultiple = sessions.length > 1;+ document.getElementById('signOutBtn').style.display = hasMultiple+ ? 'block'+ : 'none';++ sessions.forEach((session) => {+ const row = document.createElement('tr');+ row.id = `session-${session.id}`;++ const isCurrentSession = session.current;+ const uaCell = document.createElement('td');+ uaCell.className = 'agent-cell';+ uaCell.textContent = truncateUA(session.user_agent);++ const ipCell = document.createElement('td');+ ipCell.className = 'agent-cell';+ ipCell.textContent = session.ip || 'Unknown';++ const createdCell = document.createElement('td');+ createdCell.className = 'time-cell';+ createdCell.textContent = formatAbsoluteDate(session.created_at);++ const lastSeenCell = document.createElement('td');+ lastSeenCell.className = 'time-cell';+ if (isCurrentSession) {+ lastSeenCell.innerHTML = '<span class="pill">This device</span>';+ } else {+ lastSeenCell.textContent = formatRelativeTime(session.last_seen_at);+ }++ const actionsCell = document.createElement('td');+ actionsCell.className = 'actions';+ if (!isCurrentSession) {+ const revokeBtn = document.createElement('button');+ revokeBtn.className = 'btn sec';+ revokeBtn.style.padding = '6px 12px';+ revokeBtn.style.fontSize = '12px';+ revokeBtn.textContent = 'Revoke';+ revokeBtn.onclick = () => revokeSession(session.id, row);+ actionsCell.appendChild(revokeBtn);+ } else {+ const placeholder = document.createElement('span');+ placeholder.style.color = '#666';+ placeholder.style.fontSize = '12px';+ placeholder.textContent = '—';+ actionsCell.appendChild(placeholder);+ }++ row.appendChild(uaCell);+ row.appendChild(ipCell);+ row.appendChild(createdCell);+ row.appendChild(lastSeenCell);+ row.appendChild(actionsCell);+ tbody.appendChild(row);+ });+ } catch (err) {+ console.error(err);+ document.getElementById('loadingMessage').textContent =+ 'Error loading sessions';+ }+ }++ async function revokeSession(sessionId, row) {+ const originalRow = row.cloneNode(true);+ row.style.opacity = '0.5';+ row.querySelector('button').disabled = true;++ try {+ const res = await fetch(`/api/auth/sessions/${sessionId}`, {+ method: 'DELETE',+ credentials: 'include',+ });++ if (!res.ok) {+ throw new Error('Failed to revoke session');+ }++ row.style.animation = 'fade-out 0.3s';+ setTimeout(() => {+ row.remove();+ showToast('Session revoked');+ const remaining = document.querySelectorAll('#sessionsList tr').length;+ if (remaining === 1) {+ document.getElementById('signOutBtn').style.display = 'none';+ }+ }, 300);+ } catch (err) {+ console.error(err);+ row.replaceWith(originalRow);+ originalRow.querySelector('button').onclick = () =>+ revokeSession(sessionId, originalRow);+ showToast('Failed to revoke session', true);+ }+ }++ async function signOutEverywhere() {+ if (+ !confirm(+ 'Sign out of all other devices? You will stay signed in on this device.',+ )+ )+ return;++ const signOutBtn = document.getElementById('signOutBtn');+ const originalText = signOutBtn.textContent;+ signOutBtn.disabled = true;+ signOutBtn.textContent = 'Signing out...';++ try {+ const res = await fetch('/api/auth/sessions', {+ method: 'DELETE',+ credentials: 'include',+ });++ if (!res.ok) throw new Error('Failed to sign out');++ const { revoked } = await res.json();+ showToast(`Signed out of ${revoked} device${revoked === 1 ? '' : 's'}`);+ loadSessions();+ } catch (err) {+ console.error(err);+ signOutBtn.disabled = false;+ signOutBtn.textContent = originalText;+ showToast('Failed to sign out of other devices', true);+ }+ }++ document.getElementById('signOutBtn').onclick = signOutEverywhere;++ loadSessions();++ // Add CSS animation+ const style = document.createElement('style');+ style.textContent = `+ @keyframes fade-out {+ to {+ opacity: 0;+ transform: translateX(-20px);+ }+ }+ `;+ document.head.appendChild(style);+ </script>+ </body>+</html>diff --git a/public/dashboard/wallets.html b/public/dashboard/wallets.htmlnew file mode 100644index 000000000..98b126ec3--- /dev/null+++ b/public/dashboard/wallets.html@@ -0,0 +1,418 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <title>Linked Wallets · Dashboard · 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: 16px 24px;+ border-bottom: 1px solid var(--border);+ position: sticky;+ top: 0;+ background: var(--bg);+ z-index: 5;+ }+ .brand {+ font-weight: 600;+ letter-spacing: -0.01em;+ }+ .row {+ display: flex;+ align-items: center;+ gap: 8px;+ }+ main {+ padding: 28px;+ max-width: 800px;+ margin: 0 auto;+ }+ h1 {+ font-size: 22px;+ margin: 0 0 6px;+ letter-spacing: -0.01em;+ }+ .sub {+ color: #888;+ margin: 0 0 22px;+ font-size: 14px;+ }+ .btn {+ padding: 9px 14px;+ border-radius: 9px;+ border: 0;+ font-size: 13px;+ font-weight: 600;+ cursor: pointer;+ background: var(--accent);+ color: #fff;+ }+ .btn:hover {+ filter: brightness(1.08);+ }+ .btn.sec {+ background: #222230;+ color: #ddd;+ }+ .btn.danger {+ background: #cc4040;+ }+ .btn:disabled {+ opacity: 0.5;+ cursor: not-allowed;+ }+ .wallet-table {+ width: 100%;+ border-collapse: collapse;+ margin-bottom: 24px;+ }+ .wallet-table th {+ text-align: left;+ padding: 12px;+ border-bottom: 1px solid var(--border);+ font-size: 12px;+ font-weight: 600;+ color: #aaa;+ text-transform: uppercase;+ letter-spacing: 0.5px;+ }+ .wallet-table td {+ padding: 12px;+ border-bottom: 1px solid var(--border);+ font-size: 14px;+ }+ .wallet-table tr:last-child td {+ border-bottom: none;+ }+ .address-cell {+ display: flex;+ align-items: center;+ gap: 8px;+ font-family:+ ui-monospace,+ SF Mono,+ Menlo,+ monospace;+ font-size: 13px;+ }+ .copy-btn {+ background: none;+ border: none;+ color: #666;+ cursor: pointer;+ padding: 2px 4px;+ font-size: 12px;+ }+ .copy-btn:hover {+ color: #aaa;+ }+ .pill {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ font-size: 11px;+ padding: 3px 8px;+ border-radius: 99px;+ background: #20202c;+ color: #ccc;+ white-space: nowrap;+ }+ .meta {+ color: #888;+ font-size: 13px;+ }+ .err {+ padding: 12px;+ background: rgba(255, 92, 92, 0.1);+ border: 1px solid rgba(255, 92, 92, 0.3);+ border-radius: 8px;+ color: #ffb3b3;+ margin-bottom: 14px;+ display: none;+ }+ .empty {+ text-align: center;+ padding: 40px 20px;+ border: 1px dashed var(--border);+ border-radius: 14px;+ color: #888;+ }+ .loading {+ opacity: 0.6;+ }+ .muted {+ color: #888;+ font-size: 13px;+ }+ </style>+ </head>+ <body>+ <header>+ <div class="brand"><a href="/">3D Agent</a></div>+ <div class="row">+ <span class="muted" id="user-email"></span>+ <button class="btn sec" onclick="signOut()">Sign out</button>+ </div>+ </header>+ <main>+ <h1>Linked Wallets</h1>+ <p class="sub">Manage Ethereum wallets connected to your account.</p>++ <div id="error" class="err"></div>++ <div id="wallets-container" class="loading">+ <p style="color: #666">Loading wallets…</p>+ </div>++ <button id="link-btn" class="btn" style="margin-top: 20px">Link Another Wallet</button>+ </main>++ <script type="module">+ let apiUrl = '/api';++ async function signOut() {+ await fetch(`${apiUrl}/auth/logout`, { method: 'POST', credentials: 'include' });+ location.href = '/login';+ }++ async function fetchUser() {+ const res = await fetch(`${apiUrl}/auth/me`, { credentials: 'include' });+ if (!res.ok) {+ location.href = '/login?next=' + encodeURIComponent(location.pathname);+ return null;+ }+ return res.json();+ }++ async function loadWallets() {+ try {+ const res = await fetch(`${apiUrl}/auth/wallets`, { credentials: 'include' });+ if (!res.ok) throw new Error('Failed to load wallets');+ const data = await res.json();+ renderWallets(data.wallets);+ } catch (err) {+ showError(err.message);+ }+ }++ function renderWallets(wallets) {+ const container = document.getElementById('wallets-container');+ if (wallets.length === 0) {+ container.innerHTML = `+ <div class="empty">+ <p>No wallets linked yet.</p>+ <p class="muted">Click "Link Another Wallet" to add your first wallet.</p>+ </div>+ `;+ return;+ }++ const rows = wallets+ .map(+ (w) => `+ <tr>+ <td>+ <div class="address-cell">+ <span>${w.address.slice(0, 6)}…${w.address.slice(-4)}</span>+ <button+ class="copy-btn"+ onclick="copyToClipboard('${w.address}')"+ title="Copy full address"+ >+ 📋+ </button>+ </div>+ </td>+ <td class="meta">${w.chain_id ? `Chain ${w.chain_id}` : 'Multi-chain'}</td>+ <td class="meta">${new Date(w.created_at).toLocaleDateString()}</td>+ <td>+ ${w.is_primary ? '<span class="pill">Primary</span>' : ''}+ </td>+ <td style="text-align: right">+ <button+ class="btn sec btn-sm"+ onclick="unlinkWallet('${w.address}')"+ style="padding: 6px 10px; font-size: 12px"+ >+ Unlink+ </button>+ </td>+ </tr>+ `,+ )+ .join('');++ container.innerHTML = `+ <table class="wallet-table">+ <thead>+ <tr>+ <th>Address</th>+ <th>Chain</th>+ <th>Linked</th>+ <th></th>+ <th></th>+ </tr>+ </thead>+ <tbody>+ ${rows}+ </tbody>+ </table>+ `;+ }++ function copyToClipboard(text) {+ navigator.clipboard.writeText(text).then(+ () => {+ // Show brief feedback+ const btn = event.target;+ const orig = btn.textContent;+ btn.textContent = '✓';+ setTimeout(() => {+ btn.textContent = orig;+ }, 1500);+ },+ () => alert('Copy failed'),+ );+ }++ async function unlinkWallet(address) {+ if (!confirm(`Unlink ${address.slice(0, 6)}…${address.slice(-4)}?`)) return;++ try {+ const res = await fetch(`${apiUrl}/auth/wallets/${address}`, {+ method: 'DELETE',+ credentials: 'include',+ });+ if (!res.ok) {+ const err = await res.json();+ throw new Error(err.error_description || 'Failed to unlink wallet');+ }+ loadWallets();+ } catch (err) {+ showError(err.message);+ }+ }++ async function linkWallet() {+ if (!window.ethereum) {+ showError('MetaMask not found. Please install it to link wallets.');+ return;+ }++ try {+ // 1. Request accounts from MetaMask+ const accounts = await window.ethereum.request({+ method: 'eth_requestAccounts',+ });+ const address = accounts[0];++ // 2. Get nonce from server+ const nonceRes = await fetch(`${apiUrl}/auth/wallets/nonce`, {+ method: 'POST',+ credentials: 'include',+ });+ if (!nonceRes.ok) throw new Error('Failed to get nonce');+ const { nonce, message } = await nonceRes.json();++ // 3. Sign message with MetaMask+ let signature;+ try {+ signature = await window.ethereum.request({+ method: 'personal_sign',+ params: [message, address],+ });+ } catch (err) {+ if (err.code === 4001) {+ showError('Signature cancelled by user');+ } else {+ showError(err.message || 'Signature failed');+ }+ return;+ }++ // 4. Send signature to server+ const linkRes = await fetch(`${apiUrl}/auth/wallets`, {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ address, message, signature, nonce }),+ });+ if (!linkRes.ok) {+ const err = await linkRes.json();+ throw new Error(err.error_description || 'Failed to link wallet');+ }++ showError('', 'success');+ loadWallets();+ } catch (err) {+ showError(err.message);+ }+ }++ function showError(msg, type = 'error') {+ const el = document.getElementById('error');+ if (!msg) {+ el.style.display = 'none';+ return;+ }+ if (type === 'success') {+ el.textContent = '✓ Wallet linked successfully!';+ el.style.background = 'rgba(92, 255, 92, 0.1)';+ el.style.borderColor = 'rgba(92, 255, 92, 0.3)';+ el.style.color = '#b3ffb3';+ } else {+ el.textContent = msg;+ el.style.background = 'rgba(255, 92, 92, 0.1)';+ el.style.borderColor = 'rgba(255, 92, 92, 0.3)';+ el.style.color = '#ffb3b3';+ }+ el.style.display = 'block';+ }++ window.copyToClipboard = copyToClipboard;+ window.unlinkWallet = unlinkWallet;++ // Initialize+ (async () => {+ const me = await fetchUser();+ if (me) {+ document.getElementById('user-email').textContent = me.user.email;+ loadWallets();+ }+ })();++ document.getElementById('link-btn').addEventListener('click', linkWallet);+ </script>+ </body>+</html>diff --git a/public/first-meet/first-meet.js b/public/first-meet/first-meet.jsnew file mode 100644index 000000000..e2906ca77--- /dev/null+++ b/public/first-meet/first-meet.js@@ -0,0 +1,328 @@+// First meet onboarding flow for newly created avatars++const STEPS = ['name', 'bio', 'voice', 'greet', 'done'];+let currentStep = 0;+let state = {+ avatarId: null,+ avatar: null,+ agent: null,+ name: 'My Agent',+ bio: '',+ voice: 'en-US-female',+ bodyType: 'neutral',+};++// ── Init ───────────────────────────────────────────────────────────────────++async function boot() {+ const avatarId = new URL(window.location).searchParams.get('avatar');+ if (!avatarId) {+ window.location.href = '/login';+ return;+ }++ // Auth check+ const authRes = await fetch('/api/auth/me', { credentials: 'include' });+ if (!authRes.ok) {+ window.location.href =+ '/login?next=' + encodeURIComponent(window.location.pathname + window.location.search);+ return;+ }++ state.avatarId = avatarId;++ // Load avatar+ try {+ const res = await fetch(`/api/avatars/${avatarId}`, { credentials: 'include' });+ if (!res.ok) throw new Error('Avatar not found');+ const data = await res.json();+ state.avatar = data.avatar;+ renderPreview();+ } catch (err) {+ showPreviewError('Failed to load avatar: ' + err.message);+ return;+ }++ // Load existing agent if any+ try {+ const res = await fetch('/api/agents/me', { credentials: 'include' });+ if (res.ok) {+ const data = await res.json();+ if (data.agent) {+ state.agent = data.agent;+ if (data.agent.name) state.name = data.agent.name;+ if (data.agent.description) state.bio = data.agent.description;+ }+ }+ } catch {+ // Ignore agent load errors, proceed+ }++ wireStepButtons();+ updateProgress();+ goToStep(0);+}++// ── Rendering ───────────────────────────────────────────────────────────────++function renderPreview() {+ const container = document.getElementById('preview-content');+ if (!state.avatar || !state.avatar.model_url) {+ container.innerHTML = '<div class="error-msg">Avatar URL not available</div>';+ return;+ }++ const viewer = document.createElement('model-viewer');+ viewer.src = state.avatar.model_url;+ viewer.alt = state.avatar.name || 'Avatar';+ viewer.setAttribute('auto-rotate', '');+ viewer.setAttribute('camera-controls', '');+ viewer.setAttribute('enable-shadow', '');++ container.innerHTML = '';+ container.appendChild(viewer);+}++function showPreviewError(msg) {+ const container = document.getElementById('preview-content');+ container.innerHTML = `<div class="error-msg">${escapeHtml(msg)}</div>`;+}++function updateProgress() {+ const pct = ((currentStep + 1) / STEPS.length) * 100;+ document.getElementById('progress-bar').style.width = pct + '%';+}++function goToStep(n) {+ STEPS.forEach((s) => {+ document.getElementById(`step-${s}`).classList.remove('active');+ });+ currentStep = n;+ document.getElementById(`step-${STEPS[currentStep]}`).classList.add('active');+ updateProgress();++ if (currentStep === 0) {+ const input = document.getElementById('name-input');+ input.value = state.name;+ input.focus();+ updateCharCount('name');+ } else if (currentStep === 1) {+ const textarea = document.getElementById('bio-input');+ textarea.value = state.bio;+ textarea.focus();+ updateCharCount('bio');+ } else if (currentStep === 2) {+ document.getElementById('voice-select').value = state.voice;+ document.getElementById('body-type-select').value = state.bodyType;+ } else if (currentStep === 3) {+ renderGreeting();+ }+}++function updateCharCount(field) {+ const input = document.getElementById(`${field}-input`);+ const count = document.getElementById(`${field}-count`);+ count.textContent = input.value.length;+}++// ── Wire buttons ─────────────────────────────────────────────────────────────++function wireStepButtons() {+ // Step 1: Name+ document.getElementById('name-input').addEventListener('input', (e) => {+ state.name = e.target.value || 'My Agent';+ updateCharCount('name');+ });+ document.getElementById('name-next').addEventListener('click', () => goToStep(1));+ document.getElementById('name-skip').addEventListener('click', () => goToStep(1));++ // Step 2: Bio+ document.getElementById('bio-input').addEventListener('input', (e) => {+ state.bio = e.target.value;+ updateCharCount('bio');+ });+ document.getElementById('bio-next').addEventListener('click', () => goToStep(2));+ document.getElementById('bio-back').addEventListener('click', () => goToStep(0));++ // Step 3: Voice+ document.getElementById('voice-select').addEventListener('change', (e) => {+ state.voice = e.target.value;+ });+ document.getElementById('body-type-select').addEventListener('change', (e) => {+ state.bodyType = e.target.value;+ });+ document.getElementById('voice-next').addEventListener('click', () => goToStep(3));+ document.getElementById('voice-back').addEventListener('click', () => goToStep(1));++ // Step 4: Greet+ document.getElementById('greet-next').addEventListener('click', () => goToStep(4));++ // Step 5: Done+ document.getElementById('done-agent').addEventListener('click', async () => {+ // Persist final state+ try {+ await persistState();+ } catch (err) {+ alert('Failed to save: ' + err.message);+ return;+ }+ if (state.agent) {+ window.location.href = `/agent/${state.agent.id}`;+ }+ });+ document.getElementById('done-dashboard').addEventListener('click', () => {+ window.location.href = '/dashboard';+ });+}++// ── Greeting (Step 4) ───────────────────────────────────────────────────────++async function renderGreeting() {+ const container = document.getElementById('preview-content');+ const textDiv = document.getElementById('greeting-text');++ try {+ // Try to load agent-3d element+ if (window.customElements && customElements.get('agent-3d')) {+ const agent3d = document.createElement('agent-3d');+ agent3d.setAttribute('model', state.avatar.model_url);+ agent3d.setAttribute('voice', state.voice);+ agent3d.setAttribute('eager', '');++ container.innerHTML = '';+ container.appendChild(agent3d);++ textDiv.textContent = 'Greeting…';++ // Wait for element to be ready, then emit speak event+ setTimeout(() => {+ try {+ const greetingText = buildGreetingText();+ const event = new CustomEvent('speak', {+ detail: { text: greetingText, sentiment: 0.8 },+ });+ agent3d.dispatchEvent(event);+ textDiv.textContent = `"${greetingText}"`;+ } catch (e) {+ console.error('Greeting failed:', e);+ textDiv.textContent = buildGreetingText();+ }+ }, 500);+ } else {+ // Fallback: model-viewer + text+ const viewer = document.createElement('model-viewer');+ viewer.src = state.avatar.model_url;+ viewer.alt = state.avatar.name || 'Avatar';+ viewer.setAttribute('auto-rotate', '');+ viewer.setAttribute('camera-controls', '');+ viewer.setAttribute('enable-shadow', '');++ container.innerHTML = '';+ container.appendChild(viewer);++ const greetingText = buildGreetingText();+ textDiv.textContent = `"${greetingText}"`;++ // Try browser TTS+ if (window.SpeechSynthesis || window.webkitSpeechSynthesis) {+ const synth = window.speechSynthesis || window.webkitSpeechSynthesis;+ const utterance = new SpeechSynthesisUtterance(greetingText);+ utterance.voice = findVoice(state.voice);+ utterance.rate = 0.95;+ synth.speak(utterance);+ }+ }+ } catch (err) {+ console.error('Greeting render error:', err);+ textDiv.textContent = buildGreetingText();+ }+}++function buildGreetingText() {+ const bioSuffix = state.bio ? ' ' + state.bio : '';+ return `Hi — I'm ${state.name}.${bioSuffix}`;+}++function findVoice(voiceId) {+ if (!(window.SpeechSynthesis || window.webkitSpeechSynthesis)) return null;+ const synth = window.speechSynthesis || window.webkitSpeechSynthesis;+ const voices = synth.getVoices();++ const langMap = {+ 'en-US-female': ['en-US', 'female'],+ 'en-US-male': ['en-US', 'male'],+ 'en-GB-female': ['en-GB', 'female'],+ 'en-GB-male': ['en-GB', 'male'],+ };++ const [lang, gender] = langMap[voiceId] || ['en-US', 'female'];++ return (+ voices.find((v) => v.lang.startsWith(lang) && (v.name.includes(gender) || true)) ||+ voices[0] ||+ null+ );+}++// ── Persistence ────────────────────────────────────────────────────────────++async function persistState() {+ // 1. PATCH avatar name + description+ await fetch(`/api/avatars/${state.avatarId}`, {+ method: 'PATCH',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ name: state.name,+ description: state.bio,+ }),+ }).then((r) => {+ if (!r.ok) throw new Error(`Avatar update failed: ${r.status}`);+ return r.json();+ });++ // 2. Create or update agent+ if (!state.agent) {+ // POST new agent+ const res = await fetch('/api/agents', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ name: state.name,+ description: state.bio,+ avatar_id: state.avatarId,+ }),+ });+ if (!res.ok) throw new Error(`Agent creation failed: ${res.status}`);+ const data = await res.json();+ state.agent = data.agent;+ } else {+ // PATCH existing agent+ const res = await fetch(`/api/agents/${state.agent.id}`, {+ method: 'PATCH',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ name: state.name,+ description: state.bio,+ avatar_id: state.avatarId,+ }),+ });+ if (!res.ok) throw new Error(`Agent update failed: ${res.status}`);+ const data = await res.json();+ state.agent = data.agent;+ }+}++// ── Helpers ────────────────────────────────────────────────────────────────++function escapeHtml(text) {+ const div = document.createElement('div');+ div.textContent = text;+ return div.innerHTML;+}++// ── Bootstrap ──────────────────────────────────────────────────────────────++boot();diff --git a/public/first-meet/index.html b/public/first-meet/index.htmlnew file mode 100644index 000000000..befed6937--- /dev/null+++ b/public/first-meet/index.html@@ -0,0 +1,319 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>Meet Your Agent · 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;+ }+ .container {+ display: grid;+ grid-template-columns: 1fr 1fr;+ min-height: 100vh;+ gap: 0;+ }+ .preview-col {+ background: var(--panel);+ border-right: 1px solid var(--border);+ padding: 28px;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ overflow: auto;+ }+ .preview-col model-viewer,+ .preview-col agent-3d {+ width: 100%;+ height: 100%;+ max-height: 600px;+ border-radius: 8px;+ background: linear-gradient(135deg, #1a1a24 0%, #0f0f14 100%);+ }+ .preview-col .loading,+ .preview-col .error-msg {+ text-align: center;+ color: #aaa;+ }+ .form-col {+ padding: 28px;+ display: flex;+ flex-direction: column;+ justify-content: center;+ max-width: 600px;+ overflow: auto;+ }+ .form-col h1 {+ font-size: 24px;+ margin: 0 0 8px;+ letter-spacing: -0.01em;+ }+ .form-col .sub {+ color: #888;+ font-size: 14px;+ margin: 0 0 24px;+ }+ .step {+ display: none;+ }+ .step.active {+ display: block;+ }+ .form-group {+ margin-bottom: 20px;+ }+ label {+ display: block;+ font-size: 14px;+ font-weight: 500;+ margin-bottom: 8px;+ color: #ccc;+ }+ input[type='text'],+ textarea,+ select {+ width: 100%;+ padding: 10px 12px;+ border: 1px solid var(--border);+ border-radius: 6px;+ background: rgba(0, 0, 0, 0.3);+ color: #eee;+ font-size: 14px;+ font-family: inherit;+ transition:+ border-color 0.2s,+ background-color 0.2s;+ }+ input[type='text']:focus,+ textarea:focus,+ select:focus {+ outline: none;+ border-color: var(--accent);+ background: rgba(0, 0, 0, 0.5);+ }+ textarea {+ resize: vertical;+ min-height: 80px;+ }+ .char-count {+ font-size: 12px;+ color: #666;+ margin-top: 4px;+ }+ .buttons {+ display: flex;+ gap: 12px;+ margin-top: 24px;+ }+ button {+ flex: 1;+ padding: 10px 16px;+ border: 1px solid var(--border);+ border-radius: 6px;+ background: rgba(106, 92, 255, 0.1);+ color: #9a8cff;+ font-size: 14px;+ font-weight: 500;+ cursor: pointer;+ transition:+ background-color 0.2s,+ border-color 0.2s;+ }+ button:hover:not(:disabled) {+ background: rgba(106, 92, 255, 0.2);+ border-color: var(--accent);+ }+ button:disabled {+ opacity: 0.5;+ cursor: not-allowed;+ }+ button.primary {+ background: var(--accent);+ color: #000;+ border-color: var(--accent);+ }+ button.primary:hover:not(:disabled) {+ background: #7b6dff;+ }+ .skip-btn {+ flex: 0;+ padding: 10px 20px;+ background: transparent;+ color: #666;+ border: none;+ }+ .skip-btn:hover {+ color: #aaa;+ background: transparent;+ }+ .progress {+ height: 3px;+ background: var(--border);+ border-radius: 2px;+ margin-bottom: 20px;+ overflow: hidden;+ }+ .progress-bar {+ height: 100%;+ background: var(--accent);+ transition: width 0.3s ease;+ }+ .greeting-text {+ text-align: center;+ margin: 20px 0;+ font-size: 16px;+ color: #aaa;+ font-style: italic;+ }+ .grid-2col {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 12px;+ }+ .grid-2col .form-group {+ margin-bottom: 0;+ }+ @media (max-width: 900px) {+ .container {+ grid-template-columns: 1fr;+ }+ .preview-col {+ min-height: 300px;+ border-right: none;+ border-bottom: 1px solid var(--border);+ }+ }+ </style>+ </head>+ <body>+ <div class="container">+ <div class="preview-col">+ <div id="preview-content">+ <div class="loading">Loading avatar…</div>+ </div>+ </div>+ <div class="form-col">+ <div class="progress">+ <div class="progress-bar" id="progress-bar"></div>+ </div>++ <!-- Step 1: Name -->+ <div class="step active" id="step-name">+ <h1>Name your agent</h1>+ <p class="sub">Give your avatar a name. You can change it later.</p>+ <div class="form-group">+ <input+ type="text"+ id="name-input"+ placeholder="My Agent"+ minlength="2"+ maxlength="40"+ autofocus+ />+ <div class="char-count"><span id="name-count">0</span>/40</div>+ </div>+ <div class="buttons">+ <button class="primary" id="name-next">Next</button>+ <button class="skip-btn" id="name-skip">Skip</button>+ </div>+ </div>++ <!-- Step 2: Bio -->+ <div class="step" id="step-bio">+ <h1>Tell us about your agent</h1>+ <p class="sub">Add a short bio (optional). Max 280 characters.</p>+ <div class="form-group">+ <textarea+ id="bio-input"+ placeholder="What should people know about this agent?"+ maxlength="280"+ ></textarea>+ <div class="char-count"><span id="bio-count">0</span>/280</div>+ </div>+ <div class="buttons">+ <button class="primary" id="bio-next">Next</button>+ <button id="bio-back">Back</button>+ </div>+ </div>++ <!-- Step 3: Voice + Body Type -->+ <div class="step" id="step-voice">+ <h1>Voice & appearance</h1>+ <p class="sub">Choose how your agent communicates and looks.</p>+ <div class="form-group">+ <label for="voice-select">Voice</label>+ <select id="voice-select">+ <option value="en-US-female">US Female</option>+ <option value="en-US-male">US Male</option>+ <option value="en-GB-female">British Female</option>+ <option value="en-GB-male">British Male</option>+ </select>+ </div>+ <div class="form-group">+ <label for="body-type-select">Body type</label>+ <select id="body-type-select">+ <option value="neutral">Neutral</option>+ <option value="feminine">Feminine</option>+ <option value="masculine">Masculine</option>+ </select>+ </div>+ <div class="buttons">+ <button class="primary" id="voice-next">Next</button>+ <button id="voice-back">Back</button>+ </div>+ </div>++ <!-- Step 4: Greet -->+ <div class="step" id="step-greet">+ <h1>Meet your agent</h1>+ <p class="sub">Your agent is ready to say hello.</p>+ <div class="greeting-text" id="greeting-text">Listening…</div>+ <div class="buttons">+ <button class="primary" id="greet-next">Continue</button>+ </div>+ </div>++ <!-- Step 5: Done -->+ <div class="step" id="step-done">+ <h1>All set!</h1>+ <p class="sub">Your agent is ready to go.</p>+ <div class="buttons">+ <button class="primary" id="done-agent">Go to my agent</button>+ <button id="done-dashboard">Back to dashboard</button>+ </div>+ </div>+ </div>+ </div>++ <script src="/dist-lib/agent-3d.js" type="module"></script>+ <script src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>+ <script type="module" src="./first-meet.js"></script>+ </body>+</html>diff --git a/public/hydrate/index.html b/public/hydrate/index.htmlnew file mode 100644index 000000000..93e9d4ac8--- /dev/null+++ b/public/hydrate/index.html@@ -0,0 +1,465 @@+<!DOCTYPE html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Import My Agents</title>+ <style>+ :root {+ --primary: #0066cc;+ --primary-dark: #0052a3;+ --gray-100: #f5f5f5;+ --gray-200: #e0e0e0;+ --gray-700: #333;+ --error: #d32f2f;+ --success: #388e3c;+ }++ * {+ margin: 0;+ padding: 0;+ box-sizing: border-box;+ }++ body {+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;+ background: var(--gray-100);+ color: var(--gray-700);+ min-height: 100vh;+ padding: 20px;+ }++ .container {+ max-width: 800px;+ margin: 0 auto;+ background: white;+ border-radius: 8px;+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);+ padding: 40px;+ }++ h1 {+ margin-bottom: 10px;+ font-size: 28px;+ }++ .subtitle {+ color: #666;+ margin-bottom: 30px;+ font-size: 14px;+ }++ .alert {+ padding: 16px;+ border-radius: 4px;+ margin-bottom: 24px;+ display: none;+ }++ .alert.show {+ display: block;+ }++ .alert.error {+ background: #ffebee;+ color: var(--error);+ border-left: 4px solid var(--error);+ }++ .alert.success {+ background: #e8f5e9;+ color: var(--success);+ border-left: 4px solid var(--success);+ }++ .alert.info {+ background: #e3f2fd;+ color: var(--primary);+ border-left: 4px solid var(--primary);+ }++ .auth-prompt {+ text-align: center;+ padding: 40px 20px;+ }++ .auth-prompt p {+ margin-bottom: 20px;+ color: #666;+ }++ .button {+ display: inline-block;+ padding: 12px 24px;+ border-radius: 4px;+ border: none;+ font-size: 14px;+ font-weight: 600;+ cursor: pointer;+ text-decoration: none;+ text-align: center;+ transition: all 0.2s;+ }++ .button.primary {+ background: var(--primary);+ color: white;+ }++ .button.primary:hover {+ background: var(--primary-dark);+ }++ .button.secondary {+ background: var(--gray-200);+ color: var(--gray-700);+ }++ .button.secondary:hover {+ background: var(--gray-300);+ }++ .button:disabled {+ opacity: 0.5;+ cursor: not-allowed;+ }++ .agents-list {+ display: none;+ }++ .agent-card {+ border: 1px solid var(--gray-200);+ border-radius: 6px;+ padding: 16px;+ margin-bottom: 16px;+ display: flex;+ gap: 16px;+ align-items: flex-start;+ }++ .agent-image {+ width: 80px;+ height: 80px;+ background: var(--gray-100);+ border-radius: 4px;+ flex-shrink: 0;+ display: flex;+ align-items: center;+ justify-content: center;+ font-size: 12px;+ color: #999;+ overflow: hidden;+ }++ .agent-image img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ }++ .agent-info {+ flex: 1;+ min-width: 0;+ }++ .agent-header {+ display: flex;+ align-items: baseline;+ gap: 8px;+ margin-bottom: 4px;+ }++ .agent-name {+ font-size: 16px;+ font-weight: 600;+ color: var(--gray-700);+ }++ .chain-badge {+ display: inline-block;+ background: var(--gray-100);+ color: #666;+ padding: 2px 8px;+ border-radius: 3px;+ font-size: 12px;+ font-weight: 500;+ }++ .agent-description {+ color: #666;+ font-size: 14px;+ line-height: 1.4;+ margin-bottom: 8px;+ }++ .agent-id {+ color: #999;+ font-size: 12px;+ font-family: monospace;+ }++ .agent-actions {+ display: flex;+ gap: 8px;+ margin-top: 12px;+ }++ .button-small {+ padding: 6px 12px;+ font-size: 12px;+ }++ .import-link {+ color: var(--primary);+ text-decoration: none;+ font-weight: 600;+ font-size: 12px;+ }++ .import-link:hover {+ text-decoration: underline;+ }++ .loading {+ text-align: center;+ padding: 40px;+ color: #666;+ }++ .spinner {+ display: inline-block;+ width: 20px;+ height: 20px;+ border: 2px solid var(--gray-200);+ border-top-color: var(--primary);+ border-radius: 50%;+ animation: spin 0.6s linear infinite;+ margin-right: 10px;+ vertical-align: middle;+ }++ @keyframes spin {+ to {+ transform: rotate(360deg);+ }+ }++ .empty-state {+ text-align: center;+ padding: 60px 20px;+ }++ .empty-state p {+ color: #666;+ margin-bottom: 20px;+ }++ .breadcrumb {+ font-size: 12px;+ color: #999;+ margin-bottom: 20px;+ }++ .breadcrumb a {+ color: var(--primary);+ text-decoration: none;+ }++ .breadcrumb a:hover {+ text-decoration: underline;+ }+ </style>+ </head>+ <body>+ <div class="container">+ <div class="breadcrumb">+ <a href="/">Home</a> / <a href="/dashboard/">Dashboard</a> / Import Agents+ </div>++ <h1>Import My Agents</h1>+ <p class="subtitle">+ Discover and import agents you've already registered on-chain+ </p>++ <div id="alert" class="alert"></div>++ <div id="authPrompt" class="auth-prompt" style="display: none">+ <p>+ To import your on-chain agents, you need to+ <strong>connect a wallet</strong> first.+ </p>+ <a href="/dashboard/wallets.html" class="button primary">Connect Wallet</a>+ </div>++ <div id="loadingState" class="loading" style="display: none">+ <span class="spinner"></span> Fetching your agents…+ </div>++ <div id="agentsList" class="agents-list"></div>++ <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>+ </p>+ </div>+ </div>++ <script type="module">+ const alertEl = document.getElementById('alert');+ const authPrompt = document.getElementById('authPrompt');+ const loadingState = document.getElementById('loadingState');+ const agentsList = document.getElementById('agentsList');+ const emptyState = document.getElementById('emptyState');++ function showAlert(message, type = 'info') {+ alertEl.textContent = message;+ alertEl.className = `alert show ${type}`;+ if (type === 'error') {+ console.error('[hydrate]', message);+ }+ }++ function hideAlert() {+ alertEl.className = 'alert';+ }++ async function checkAuth() {+ try {+ const res = await fetch('/api/auth/wallets', {+ credentials: 'include',+ });++ if (res.status === 401) {+ // Not authenticated+ return { authenticated: false, wallets: [] };+ }++ const data = await res.json();+ return {+ authenticated: true,+ wallets: data.wallets || [],+ };+ } catch (err) {+ console.error('[hydrate] auth check failed', err);+ return { authenticated: false, wallets: [] };+ }+ }++ async function loadAgents() {+ const auth = await checkAuth();++ if (!auth.authenticated) {+ authPrompt.style.display = 'block';+ return;+ }++ if (auth.wallets.length === 0) {+ authPrompt.style.display = 'block';+ return;+ }++ loadingState.style.display = 'block';++ try {+ const { fetchDiscoveredAgents } = await import('/src/erc8004/hydrate.js');+ const agents = await fetchDiscoveredAgents();++ loadingState.style.display = 'none';++ if (agents.length === 0) {+ emptyState.style.display = 'block';+ return;+ }++ renderAgents(agents);+ agentsList.style.display = 'block';+ } catch (err) {+ loadingState.style.display = 'none';+ showAlert(`Failed to load agents: ${err.message}`, 'error');+ }+ }++ function renderAgents(agents) {+ agentsList.innerHTML = agents+ .map(+ (agent) => `+ <div class="agent-card">+ <div class="agent-image">+ ${+ 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>`+ : ''+ }+ <div class="agent-id">Agent ID: ${escapeHtml(agent.agentId)}</div>+ </div>+ <div class="agent-actions">+ ${+ agent.alreadyImported+ ? `<a href="/dashboard/?agent=${escapeHtml(agent.id)}" class="import-link">Go to agent →</a>`+ : `<button class="button primary button-small" data-chain="${agent.chainId}" data-id="${escapeHtml(agent.agentId)}">Import</button>`+ }+ </div>+ </div>+ `,+ )+ .join('');++ // Attach import handlers+ document.querySelectorAll('[data-chain]').forEach((btn) => {+ btn.addEventListener('click', () => {+ importAgent(btn.dataset.chain, btn.dataset.id, btn);+ });+ });+ }++ async function importAgent(chainId, agentId, button) {+ button.disabled = true;+ const originalText = button.textContent;+ button.innerHTML = '<span class="spinner"></span> Importing…';+ hideAlert();++ try {+ const { importAgent: doImport } = await import('/src/erc8004/hydrate.js');+ const agent = await doImport({+ chainId: parseInt(chainId),+ agentId,+ });++ showAlert(`Successfully imported ${agent.name}!`, 'success');++ // Replace button with link after a brief delay+ setTimeout(() => {+ button.outerHTML = `<a href="/dashboard/?agent=${escapeHtml(agent.id)}" class="import-link">Go to agent →</a>`;+ }, 1000);+ } catch (err) {+ showAlert(`Import failed: ${err.message}`, 'error');+ button.disabled = false;+ button.textContent = originalText;+ }+ }++ function escapeHtml(text) {+ if (!text) return '';+ const div = document.createElement('div');+ div.textContent = text;+ return div.innerHTML;+ }++ // Load on page load+ loadAgents();+ </script>+ </body>+</html>diff --git a/public/login.html b/public/login.htmlindex 04be01bf0..6899653f6 100644--- a/public/login.html+++ b/public/login.html@@ -55,6 +55,12 @@<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(() => {});+const form = document.getElementById('f');const err = document.getElementById('err');const btn = document.getElementById('submit');diff --git a/public/reputation/index.html b/public/reputation/index.htmlnew file mode 100644index 000000000..bb0368c1d--- /dev/null+++ b/public/reputation/index.html@@ -0,0 +1,502 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />+ <title>Agent Reputation — 3D Agent</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <meta name="description" content="View and submit reviews for on-chain agents." />+ <meta name="theme-color" content="#0a0a0a" />++ <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"+ />++ <style>+ * {+ margin: 0;+ padding: 0;+ box-sizing: border-box;+ }++ html,+ body {+ background: #0a0a0a;+ color: #e5e5e5;+ font-family:+ 'Inter',+ -apple-system,+ BlinkMacSystemFont,+ 'Segoe UI',+ sans-serif;+ font-size: 16px;+ line-height: 1.5;+ height: 100%;+ }++ body {+ overflow-y: auto;+ overflow-x: hidden;+ }++ main {+ max-width: 800px;+ margin: 0 auto;+ padding: 2rem 1.5rem;+ min-height: 100vh;+ }++ h1,+ h2,+ h3 {+ font-family:+ 'Space Grotesk',+ -apple-system,+ BlinkMacSystemFont,+ 'Segoe UI',+ sans-serif;+ font-weight: 600;+ letter-spacing: -0.5px;+ }++ h1 {+ font-size: 2rem;+ }+ h3 {+ font-size: 1.125rem;+ margin: 1.5rem 0 1rem;+ }++ a {+ color: #a78bfa;+ text-decoration: none;+ }+ a:hover {+ color: #c4b5fd;+ }++ /* Header */+ .rep-header {+ margin-bottom: 2rem;+ padding-bottom: 1.5rem;+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);+ }++ .rep-header h1 {+ margin: 0 0 0.5rem 0;+ }++ .rep-header-meta {+ color: rgba(229, 229, 229, 0.6);+ font-size: 0.875rem;+ }++ /* Stats Row */+ .rep-stats {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));+ gap: 1rem;+ margin-bottom: 2rem;+ padding: 1.5rem;+ background: rgba(139, 92, 246, 0.04);+ border: 1px solid rgba(139, 92, 246, 0.1);+ border-radius: 8px;+ }++ .rep-stat {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+ }++ .rep-stat-label {+ font-size: 0.75rem;+ text-transform: uppercase;+ letter-spacing: 1px;+ color: rgba(229, 229, 229, 0.5);+ font-weight: 600;+ }++ .rep-stat-value {+ font-size: 1.75rem;+ font-weight: 700;+ color: #e5e5e5;+ font-family: 'Space Grotesk', monospace;+ }++ /* Reviews Section */+ .rep-reviews {+ margin-bottom: 2rem;+ }++ .rep-empty {+ text-align: center;+ color: rgba(229, 229, 229, 0.5);+ padding: 2rem 1rem;+ }++ .rep-review-list {+ display: flex;+ flex-direction: column;+ gap: 1rem;+ }++ .rep-review-item {+ padding: 1rem;+ background: rgba(255, 255, 255, 0.02);+ border: 1px solid rgba(255, 255, 255, 0.06);+ border-radius: 6px;+ transition:+ background 0.15s,+ border-color 0.15s;+ }++ .rep-review-item:hover {+ background: rgba(255, 255, 255, 0.04);+ border-color: rgba(255, 255, 255, 0.12);+ }++ .rep-review-item.pending {+ opacity: 0.75;+ }++ .rep-review-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: 0.5rem;+ gap: 1rem;+ }++ .rep-reviewer {+ font-weight: 500;+ font-size: 0.875rem;+ color: rgba(229, 229, 229, 0.7);+ font-family: 'Courier New', monospace;+ }++ .rep-stars {+ font-size: 0.875rem;+ letter-spacing: 2px;+ color: #fbbf24;+ }++ .rep-comment {+ margin: 0.75rem 0 0.75rem 0;+ color: rgba(229, 229, 229, 0.8);+ font-size: 0.9375rem;+ line-height: 1.6;+ word-wrap: break-word;+ white-space: pre-wrap;+ }++ .rep-review-footer {+ display: flex;+ gap: 0.75rem;+ align-items: center;+ font-size: 0.75rem;+ }++ .rep-review-footer a {+ color: #a78bfa;+ text-decoration: none;+ }++ .rep-review-footer a:hover {+ text-decoration: underline;+ }++ .rep-tx-hash {+ color: rgba(229, 229, 229, 0.5);+ font-family: monospace;+ }++ .rep-pending-badge {+ background: rgba(251, 191, 36, 0.15);+ color: #fbbf24;+ padding: 0.25rem 0.5rem;+ border-radius: 3px;+ font-weight: 500;+ }++ .rep-more-reviews {+ text-align: center;+ color: rgba(229, 229, 229, 0.5);+ font-size: 0.875rem;+ margin-top: 1rem;+ }++ /* Submit Form */+ .rep-submit-form {+ margin-top: 2.5rem;+ padding: 1.5rem;+ background: rgba(139, 92, 246, 0.04);+ border: 1px solid rgba(139, 92, 246, 0.1);+ border-radius: 8px;+ }++ .rep-form-group {+ margin-bottom: 1.5rem;+ }++ .rep-form-group label {+ display: block;+ margin-bottom: 0.5rem;+ font-weight: 500;+ font-size: 0.875rem;+ }++ .rep-stars-input {+ display: flex;+ gap: 0.5rem;+ margin-bottom: 0.5rem;+ }++ .rep-star-btn {+ background: rgba(255, 255, 255, 0.08);+ border: 1px solid rgba(255, 255, 255, 0.12);+ color: rgba(229, 229, 229, 0.6);+ font-size: 1.5rem;+ width: 3rem;+ height: 3rem;+ border-radius: 6px;+ cursor: pointer;+ transition: all 0.15s;+ }++ .rep-star-btn:hover {+ background: rgba(251, 191, 36, 0.1);+ color: #fbbf24;+ border-color: rgba(251, 191, 36, 0.3);+ }++ .rep-star-btn.selected {+ background: rgba(251, 191, 36, 0.15);+ color: #fbbf24;+ border-color: rgba(251, 191, 36, 0.3);+ }++ textarea {+ width: 100%;+ padding: 0.75rem;+ background: rgba(255, 255, 255, 0.05);+ border: 1px solid rgba(255, 255, 255, 0.12);+ border-radius: 6px;+ color: #e5e5e5;+ font-family: 'Inter', sans-serif;+ font-size: 0.9375rem;+ line-height: 1.5;+ resize: vertical;+ transition:+ background 0.15s,+ border-color 0.15s;+ }++ textarea:focus {+ outline: none;+ background: rgba(255, 255, 255, 0.08);+ border-color: rgba(139, 92, 246, 0.3);+ }++ small {+ display: block;+ margin-top: 0.25rem;+ color: rgba(229, 229, 229, 0.5);+ font-size: 0.75rem;+ }++ .rep-submit-btn {+ width: 100%;+ padding: 0.875rem 1.5rem;+ background: #8b5cf6;+ border: 1px solid transparent;+ color: #fff;+ font-weight: 600;+ font-size: 0.9375rem;+ border-radius: 6px;+ cursor: pointer;+ transition: all 0.15s;+ }++ .rep-submit-btn:hover:not(:disabled) {+ background: #7c3aed;+ transform: translateY(-1px);+ }++ .rep-submit-btn:active:not(:disabled) {+ transform: translateY(0);+ }++ .rep-submit-btn:disabled {+ opacity: 0.6;+ cursor: not-allowed;+ }++ .rep-form-hint {+ text-align: center;+ color: rgba(229, 229, 229, 0.5);+ }++ #rep-rating {+ display: none;+ }++ /* Error State */+ .rep-error {+ padding: 2rem;+ text-align: center;+ background: rgba(255, 80, 80, 0.06);+ border: 1px solid rgba(255, 80, 80, 0.2);+ border-radius: 8px;+ }++ .rep-error h3 {+ margin: 0 0 0.5rem 0;+ color: rgba(255, 200, 200, 0.9);+ }++ .rep-error p {+ color: rgba(255, 150, 150, 0.8);+ margin: 0 0 1rem 0;+ }++ .rep-error button {+ padding: 0.5rem 1.5rem;+ background: rgba(255, 100, 100, 0.2);+ border: 1px solid rgba(255, 100, 100, 0.3);+ color: #ffc8c8;+ border-radius: 4px;+ cursor: pointer;+ font-weight: 500;+ transition: all 0.15s;+ }++ .rep-error button:hover {+ background: rgba(255, 100, 100, 0.3);+ }++ /* Loading */+ .rep-loading {+ text-align: center;+ padding: 2rem;+ color: rgba(229, 229, 229, 0.5);+ }++ .spinner {+ display: inline-block;+ width: 20px;+ height: 20px;+ border: 2px solid rgba(139, 92, 246, 0.3);+ border-top-color: #8b5cf6;+ border-radius: 50%;+ animation: spin 0.8s linear infinite;+ }++ @keyframes spin {+ to {+ transform: rotate(360deg);+ }+ }++ /* Responsive */+ @media (max-width: 640px) {+ main {+ padding: 1rem;+ }++ .rep-stats {+ grid-template-columns: repeat(3, 1fr);+ gap: 0.75rem;+ padding: 1rem;+ }++ .rep-stat-value {+ font-size: 1.25rem;+ }++ .rep-review-header {+ flex-direction: column;+ align-items: flex-start;+ }++ .rep-stars-input {+ gap: 0.25rem;+ }++ .rep-star-btn {+ width: 2.5rem;+ height: 2.5rem;+ font-size: 1.25rem;+ }+ }++ @media (prefers-reduced-motion: reduce) {+ * {+ animation-duration: 0.01ms !important;+ animation-iteration-count: 1 !important;+ transition-duration: 0.01ms !important;+ }+ }+ </style>+ </head>+ <body>+ <main id="app">+ <div class="rep-loading">+ <div class="spinner"></div>+ <p>Loading reputation…</p>+ </div>+ </main>++ <script type="module">+ import { ReputationDashboard } from '/src/reputation-ui.js';++ function getQueryParam(name) {+ const params = new URLSearchParams(window.location.search);+ return params.get(name);+ }++ async function init() {+ const agentId = getQueryParam('agent');+ const chainId = getQueryParam('chain');++ if (!agentId) {+ document.querySelector('#app').innerHTML = `+ <div class="rep-error">+ <h3>Missing agent ID</h3>+ <p>URL parameter required: ?agent=<id>&chain=<chainId></p>+ <p style="color: rgba(229,229,229,0.5); font-size: 0.875rem;">+ Example: ?agent=1&chain=84532+ </p>+ </div>+ `;+ return;+ }++ const resolvedChainId = chainId ? Number(chainId) : 84532; // Default: Base Sepolia++ const app = document.querySelector('#app');+ const dashboard = new ReputationDashboard(app, {+ agentId: Number(agentId),+ chainId: resolvedChainId,+ });++ await dashboard.load();+ }++ init().catch((err) => {+ console.error('Init failed:', err);+ document.querySelector('#app').innerHTML = `+ <div class="rep-error">+ <h3>Failed to initialize</h3>+ <p>${err.message || String(err)}</p>+ <button onclick="location.reload()">Retry</button>+ </div>+ `;+ });+ </script>+ </body>+</html>diff --git a/public/reputation/reputation.js b/public/reputation/reputation.jsnew file mode 100644index 000000000..913d2a334--- /dev/null+++ b/public/reputation/reputation.js@@ -0,0 +1,416 @@+/**+ * Reputation page logic — view agent scores and submit reviews.+ * Imports from src/erc8004/reputation.js for contract interactions.+ */++import { getReputation, getRecentReviews, submitReputation } from '../../src/erc8004/reputation.js';+import { JsonRpcProvider, BrowserProvider } from 'ethers';+import { REGISTRY_DEPLOYMENTS } from '../../src/erc8004/abi.js';++const CHAIN_NAMES = {+ 1: 'Ethereum',+ 10: 'Optimism',+ 56: 'BSC',+ 100: 'Gnosis',+ 137: 'Polygon',+ 250: 'Fantom',+ 324: 'zkSync Era',+ 1284: 'Moonbeam',+ 5000: 'Mantle',+ 8453: 'Base',+ 42161: 'Arbitrum One',+ 42220: 'Celo',+ 43114: 'Avalanche',+ 59144: 'Linea',+ 534352: 'Scroll',+ 97: 'BSC Testnet',+ 11155111: 'Ethereum Sepolia',+ 84532: 'Base Sepolia',+ 421614: 'Arbitrum Sepolia',+ 11155420: 'Optimism Sepolia',+ 80002: 'Polygon Amoy',+ 43113: 'Avalanche Fuji',+};++function getChainName(chainId) {+ return CHAIN_NAMES[chainId] || `Chain ${chainId}`;+}++function getExplorerUrl(chainId, txHash) {+ const base = {+ 1: 'https://etherscan.io',+ 10: 'https://optimistic.etherscan.io',+ 56: 'https://bscscan.com',+ 100: 'https://gnosisscan.io',+ 137: 'https://polygonscan.com',+ 250: 'https://ftmscan.com',+ 324: 'https://explorer.zksync.io',+ 1284: 'https://moonscan.io',+ 5000: 'https://explorer.mantle.xyz',+ 8453: 'https://basescan.org',+ 42161: 'https://arbiscan.io',+ 42220: 'https://explorer.celo.org',+ 43114: 'https://snowscan.xyz',+ 59144: 'https://lineascan.build',+ 534352: 'https://scrollscan.com',+ 97: 'https://testnet.bscscan.com',+ 11155111: 'https://sepolia.etherscan.io',+ 84532: 'https://sepolia.basescan.org',+ 421614: 'https://sepolia.arbiscan.io',+ 11155420: 'https://sepolia-optimism.etherscan.io',+ 80002: 'https://amoy.polygonscan.com',+ 43113: 'https://testnet.snowtrace.io',+ }[chainId];+ return base ? `${base}/tx/${txHash}` : null;+}++async function parseAgentId() {+ const params = new URLSearchParams(window.location.search);+ const agentParam = params.get('agent');++ if (!agentParam) {+ throw new Error('Missing ?agent=<chainId>:<agentId> parameter');+ }++ const parts = agentParam.split(':');+ if (parts.length !== 2) {+ throw new Error('Invalid agent format. Expected ?agent=<chainId>:<agentId>');+ }++ const chainId = Number(parts[0]);+ const agentId = Number(parts[1]);++ if (!chainId || !agentId) {+ throw new Error('Invalid agent ID or chain ID');+ }++ return { chainId, agentId };+}++async function fetchAgentInfo(agentId) {+ try {+ const response = await fetch(`/api/agents/${agentId}`);+ if (!response.ok) return null;+ return await response.json();+ } catch {+ return null;+ }+}++function truncateAddress(addr) {+ if (!addr || addr.length < 10) return addr;+ return `${addr.slice(0, 6)}…${addr.slice(-4)}`;+}++async function resolveENS(address, provider) {+ try {+ return await provider.resolveName(address);+ } catch {+ return null;+ }+}++function formatScore(score) {+ if (typeof score === 'number') {+ return score.toFixed(1);+ }+ return '—';+}++function getRatingClass(score) {+ if (score > 0) return 'rating-positive';+ if (score < 0) return 'rating-negative';+ return 'rating-neutral';+}++function formatDate(blockNumber) {+ // Rough estimate: blockNumber doesn't give us date directly+ // In production, you'd want to store the actual timestamp on-chain+ // For now, just show "Recent"+ return 'Recent';+}++async function main() {+ const appEl = document.querySelector('#app');++ try {+ const { chainId, agentId } = await parseAgentId();++ // Show loading state+ appEl.innerHTML = `+ <div class="rep-loading">+ <div class="spinner"></div>+ <p>Loading reputation…</p>+ </div>+ `;++ // Check if chain is supported+ if (!REGISTRY_DEPLOYMENTS[chainId]) {+ throw new Error(`ReputationRegistry not deployed on ${getChainName(chainId)}`);+ }++ // Get agent info from backend if available+ const agentInfo = await fetchAgentInfo(agentId);++ // Create provider for on-chain data+ const rpcUrl = REGISTRY_DEPLOYMENTS[chainId]?.rpcUrl || `https://rpc.${chainId}.io`;+ const provider = new JsonRpcProvider(rpcUrl);++ // Fetch reputation data+ const [repData, reviews] = await Promise.all([+ getReputation({ agentId, runner: provider, chainId }),+ getRecentReviews({ agentId, runner: provider, chainId, fromBlock: 0 }),+ ]);++ // Reverse to show most recent first, limit to 20+ const recentReviews = reviews.reverse().slice(0, 20);++ // Render page+ let html = `+ <div class="rep-header">+ <h1>${agentInfo?.name || `Agent #${agentId}`}</h1>+ <div class="rep-header-meta">+ ${getChainName(chainId)} • ID: ${agentId}+ </div>+ </div>++ <div class="rep-stats">+ <div class="rep-stat">+ <div class="rep-stat-label">Average Rating</div>+ <div class="rep-stat-value">${formatScore(repData.average)}</div>+ </div>+ <div class="rep-stat">+ <div class="rep-stat-label">Reviews</div>+ <div class="rep-stat-value">${repData.count}</div>+ </div>+ <div class="rep-stat">+ <div class="rep-stat-label">Total Score</div>+ <div class="rep-stat-value">${repData.total}</div>+ </div>+ </div>+ `;++ if (recentReviews.length === 0) {+ html += `+ <div class="rep-reviews">+ <div class="rep-empty">No reviews yet. Be the first to review this agent!</div>+ </div>+ `;+ } else {+ html += `+ <div class="rep-reviews">+ <h3>Recent Reviews</h3>+ <div class="rep-review-list">+ `;++ // Resolve ENS names in parallel+ const ensPromises = recentReviews.map(async (rev) => {+ const name = await resolveENS(rev.from, provider).catch(() => null);+ return { review: rev, name };+ });++ const reviewsWithENS = await Promise.all(ensPromises);++ reviewsWithENS.forEach(({ review, name }) => {+ const displayName = name || truncateAddress(review.from);+ const explorerUrl = getExplorerUrl(chainId, review.txHash);+ const scoreClass = getRatingClass(review.score);++ html += `+ <div class="rep-review-item">+ <div class="rep-review-header">+ <span class="rep-reviewer">${displayName}</span>+ <span class="rep-stars">${review.score > 0 ? '+' : ''}${review.score}</span>+ </div>+ `;++ if (review.comment) {+ html += `<div class="rep-comment">${escapeHtml(review.comment)}</div>`;+ }++ html += `+ <div class="rep-review-footer">+ <span>${formatDate(review.blockNumber)}</span>+ `;++ if (explorerUrl) {+ html += `<a href="${explorerUrl}" target="_blank" rel="noopener" class="rep-tx-hash">tx</a>`;+ }++ html += `+ </div>+ </div>+ `;+ });++ html += `+ </div>+ </div>+ `;+ }++ // Submit form+ html += `+ <div class="rep-submit-form">+ <h3>Submit a Review</h3>+ <div id="wallet-status" class="rep-form-hint">+ <button id="connect-wallet" class="rep-submit-btn">Connect Wallet</button>+ </div>+ <div id="form-container" style="display:none">+ <div class="rep-form-group">+ <label>Your Rating</label>+ <div class="rep-stars-input" id="rating-input">+ <!-- Stars filled by JS -->+ </div>+ <input type="hidden" id="rep-rating" value="0" />+ </div>+ <div class="rep-form-group">+ <label>Comment (optional)</label>+ <textarea id="rep-comment" placeholder="Share your feedback…" maxlength="280"></textarea>+ <small><span id="char-count">0</span>/280 characters</small>+ </div>+ <button id="submit-review" class="rep-submit-btn" disabled>Submit Review</button>+ <div id="form-message" style="display:none; margin-top:1rem"></div>+ </div>+ </div>+ `;++ appEl.innerHTML = html;++ // Wire up wallet connection+ const connectBtn = document.getElementById('connect-wallet');+ const walletStatus = document.getElementById('wallet-status');+ const formContainer = document.getElementById('form-container');+ const submitBtn = document.getElementById('submit-review');+ const ratingInput = document.getElementById('rating-input');+ const commentEl = document.getElementById('rep-comment');+ const charCount = document.getElementById('char-count');+ const formMessage = document.getElementById('form-message');++ // Create star buttons+ for (let i = -100; i <= 100; i += 20) {+ const btn = document.createElement('button');+ btn.className = 'rep-star-btn';+ btn.textContent = i >= 0 ? `+${i}` : `${i}`;+ btn.dataset.value = i;+ btn.addEventListener('click', () => {+ document.querySelectorAll('#rating-input button').forEach(b => b.classList.remove('selected'));+ btn.classList.add('selected');+ document.getElementById('rep-rating').value = i;+ submitBtn.disabled = false;+ });+ ratingInput.appendChild(btn);+ }++ commentEl.addEventListener('input', () => {+ charCount.textContent = commentEl.value.length;+ });++ let connectedAddress = null;++ connectBtn.addEventListener('click', async () => {+ try {+ if (typeof window.ethereum === 'undefined') {+ throw new Error('MetaMask not found. Please install it.');+ }++ const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });+ connectedAddress = accounts[0];++ // Check if already reviewed+ const hasReviewed = recentReviews.some(r => r.from.toLowerCase() === connectedAddress.toLowerCase());+ if (hasReviewed) {+ walletStatus.innerHTML = `+ <div class="rep-error">+ <p>You've already reviewed this agent.</p>+ </div>+ `;+ formContainer.style.display = 'none';+ return;+ }++ walletStatus.innerHTML = `+ <p style="color:rgba(229,229,229,0.7)">+ Connected: <code style="font-family:monospace">${truncateAddress(connectedAddress)}</code>+ </p>+ `;+ formContainer.style.display = '';+ connectBtn.style.display = 'none';+ } catch (err) {+ formMessage.style.display = '';+ formMessage.className = 'rep-error';+ formMessage.innerHTML = `<p>${err.message}</p>`;+ }+ });++ submitBtn.addEventListener('click', async () => {+ if (!connectedAddress) {+ formMessage.innerHTML = '<p>Please connect your wallet first.</p>';+ formMessage.className = 'rep-error';+ formMessage.style.display = '';+ return;+ }++ const rating = Number(document.getElementById('rep-rating').value);+ const comment = commentEl.value.trim();++ if (!rating && rating !== 0) {+ formMessage.innerHTML = '<p>Please select a rating.</p>';+ formMessage.className = 'rep-error';+ formMessage.style.display = '';+ return;+ }++ try {+ submitBtn.disabled = true;+ submitBtn.textContent = 'Submitting…';++ if (typeof window.ethereum === 'undefined') {+ throw new Error('MetaMask not found.');+ }++ const signer = new BrowserProvider(window.ethereum).getSigner();+ const txHash = await submitReputation({+ agentId,+ score: Math.abs(rating),+ comment,+ signer: await signer,+ chainId,+ });++ formMessage.innerHTML = `+ <div class="rep-success">+ <p>Review submitted! <a href="${getExplorerUrl(chainId, txHash) || '#'}" target="_blank" rel="noopener">View transaction</a></p>+ </div>+ `;+ formMessage.style.display = '';+ formContainer.style.display = 'none';+ connectBtn.style.display = '';+ connectBtn.textContent = 'Submit Another?';+ } catch (err) {+ formMessage.innerHTML = `<p>${err.message || 'Submission failed'}</p>`;+ formMessage.className = 'rep-error';+ formMessage.style.display = '';+ submitBtn.disabled = false;+ submitBtn.textContent = 'Submit Review';+ }+ });+ } catch (err) {+ console.error('Failed to load reputation:', err);+ appEl.innerHTML = `+ <div class="rep-error">+ <h3>Error</h3>+ <p>${err.message}</p>+ <button onclick="location.reload()">Retry</button>+ </div>+ `;+ }+}++function escapeHtml(text) {+ const div = document.createElement('div');+ div.textContent = text;+ return div.innerHTML;+}++main();diff --git a/public/validation/REPORT_FORMAT.md b/public/validation/REPORT_FORMAT.mdnew file mode 100644index 000000000..0b1c2ce2d--- /dev/null+++ b/public/validation/REPORT_FORMAT.md@@ -0,0 +1,94 @@+# Agent Validation Report Format++## Overview++An **agent validation report** is a JSON document that captures the results of testing an agent's GLB model and metadata against a suite of validation rules. Validators (auditors, testing services) generate these reports, sign them on-chain via `recordValidation()`, and end-users browse them to verify trust.++## Schema++```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."+}+```++## 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). |++## 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. |++## 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.++- **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.++- **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.++## Example++See [`example-report.json`](./example-report.json) for a complete, valid example.++## Hashing & On-Chain Storage++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...`).++Validators can verify the hash by fetching the report from IPFS and recomputing the hash locally.++## Trust Model++- Only Ethereum-validated wallets can submit validations.+- The `validator` address is recorded on-chain.+- End-users can view all validations for an agent and choose which validators to trust.+- No endorsement or filtering by the 3D Agent team — raw records from all validators are visible.diff --git a/public/validation/boot.js b/public/validation/boot.jsnew file mode 100644index 000000000..4db292be6--- /dev/null+++ b/public/validation/boot.js@@ -0,0 +1,8 @@+/**+ * Boot script for the validation dashboard.+ * Exported as a module to avoid bundler requirement.+ */++import { ValidationDashboard } from '/src/validation-ui.js';++export { ValidationDashboard };diff --git a/public/validation/example-report.json b/public/validation/example-report.jsonnew file mode 100644index 000000000..ec44a49d5--- /dev/null+++ b/public/validation/example-report.json@@ -0,0 +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."+}diff --git a/public/validation/index.html b/public/validation/index.htmlnew file mode 100644index 000000000..c50a9b343--- /dev/null+++ b/public/validation/index.html@@ -0,0 +1,485 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <title>Validation Records · 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: 16px 24px;+ border-bottom: 1px solid var(--border);+ position: sticky;+ top: 0;+ background: var(--bg);+ z-index: 5;+ }+ .brand {+ font-weight: 600;+ letter-spacing: -0.01em;+ }+ nav a {+ margin-right: 14px;+ color: #aaa;+ font-size: 14px;+ }+ nav a.active {+ color: #fff;+ }+ main {+ padding: 28px;+ max-width: 1200px;+ margin: 0 auto;+ }+ h1 {+ font-size: 22px;+ margin: 0 0 6px;+ letter-spacing: -0.01em;+ }+ .sub {+ color: #888;+ margin: 0 0 22px;+ font-size: 14px;+ }+ .toolbar {+ display: flex;+ gap: 12px;+ margin-bottom: 24px;+ flex-wrap: wrap;+ align-items: center;+ }+ .toolbar input {+ padding: 9px 11px;+ background: #0f0f17;+ border: 1px solid var(--border);+ color: #eee;+ border-radius: 8px;+ font-size: 14px;+ }+ .toolbar input:focus {+ outline: none;+ border-color: var(--accent);+ }+ .form-group {+ margin-bottom: 18px;+ }+ label {+ display: block;+ font-size: 13px;+ font-weight: 500;+ color: #bbb;+ margin-bottom: 6px;+ }+ 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;+ font-family: ui-monospace, SF Mono, Menlo, monospace;+ font-size: 13px;+ }+ .btn {+ padding: 9px 14px;+ 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: #222230;+ color: #ddd;+ }+ .err {+ padding: 12px;+ background: rgba(255, 92, 92, 0.1);+ border: 1px solid rgba(255, 92, 92, 0.3);+ border-radius: 8px;+ color: #ffb3b3;+ margin-bottom: 14px;+ }+ .info {+ padding: 12px;+ background: rgba(106, 92, 255, 0.1);+ border: 1px solid rgba(106, 92, 255, 0.3);+ border-radius: 8px;+ color: #c9bfff;+ margin-bottom: 14px;+ font-size: 13px;+ }+ .records {+ display: flex;+ flex-direction: column;+ gap: 12px;+ }+ .record {+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 10px;+ padding: 16px;+ }+ .record-header {+ display: flex;+ justify-content: space-between;+ align-items: flex-start;+ margin-bottom: 10px;+ }+ .record-title {+ display: flex;+ align-items: center;+ gap: 10px;+ }+ .record-title h3 {+ margin: 0;+ font-size: 14px;+ }+ .badge {+ display: inline-flex;+ align-items: center;+ padding: 3px 9px;+ border-radius: 99px;+ font-size: 11px;+ font-weight: 600;+ text-transform: uppercase;+ letter-spacing: 0.5px;+ }+ .badge.pass {+ background: rgba(76, 175, 80, 0.15);+ color: #76d776;+ }+ .badge.warn {+ background: rgba(255, 193, 7, 0.15);+ color: #ffc107;+ }+ .badge.fail {+ background: rgba(244, 67, 54, 0.15);+ color: #ff5252;+ }+ .record-meta {+ display: flex;+ gap: 16px;+ font-size: 12px;+ color: #888;+ margin: 8px 0;+ }+ .record-meta-item {+ display: flex;+ flex-direction: column;+ gap: 2px;+ }+ .record-meta-label {+ color: #666;+ font-size: 11px;+ text-transform: uppercase;+ letter-spacing: 0.5px;+ }+ .record-meta-value {+ color: #ccc;+ font-family: ui-monospace, SF Mono, Menlo, monospace;+ font-size: 13px;+ word-break: break-all;+ }+ .record-actions {+ display: flex;+ gap: 8px;+ margin-top: 10px;+ }+ .record-actions button,+ .record-actions a {+ padding: 6px 10px;+ font-size: 12px;+ border-radius: 7px;+ border: 1px solid var(--border);+ background: #1a1a24;+ color: #ddd;+ cursor: pointer;+ text-decoration: none;+ }+ .record-actions button:hover,+ .record-actions a:hover {+ background: #22222e;+ }+ .empty {+ text-align: center;+ padding: 60px 20px;+ border: 1px dashed var(--border);+ border-radius: 14px;+ color: #888;+ }+ .modal-overlay {+ position: fixed;+ inset: 0;+ background: rgba(0, 0, 0, 0.6);+ z-index: 60;+ display: grid;+ place-items: center;+ opacity: 0;+ pointer-events: none;+ transition: opacity 0.15s;+ }+ .modal-overlay.open {+ opacity: 1;+ pointer-events: auto;+ }+ .modal {+ background: #0e0e16;+ border: 1px solid var(--border);+ border-radius: 14px;+ padding: 22px;+ width: min(600px, calc(100vw - 32px));+ max-height: calc(100vh - 32px);+ overflow-y: auto;+ }+ .modal h2 {+ margin: 0 0 4px;+ font-size: 17px;+ }+ .modal .sub {+ margin: 0 0 18px;+ }+ .modal-actions {+ display: flex;+ gap: 8px;+ margin-top: 20px;+ justify-content: flex-end;+ }+ .toast {+ position: fixed;+ bottom: 24px;+ left: 50%;+ transform: translateX(-50%);+ background: #1a1a24;+ border: 1px solid var(--border);+ padding: 10px 18px;+ border-radius: 99px;+ font-size: 13px;+ color: #ddd;+ z-index: 70;+ box-shadow: 0 4px 18px rgba(0, 0, 0, 0.4);+ animation: toast-in 0.2s;+ }+ @keyframes toast-in {+ from {+ opacity: 0;+ transform: translate(-50%, 8px);+ }+ to {+ opacity: 1;+ transform: translateX(-50%);+ }+ }+ .toast.err {+ border-color: #cc4040;+ background: #1e1010;+ }+ .section {+ margin-top: 34px;+ }+ .section-title {+ font-size: 15px;+ font-weight: 600;+ margin: 0 0 12px;+ color: #eee;+ }+ .file-input-wrapper {+ position: relative;+ display: inline-block;+ width: 100%;+ }+ .file-input-wrapper input[type='file'] {+ position: absolute;+ opacity: 0;+ width: 0;+ height: 0;+ }+ .file-input-label {+ display: block;+ padding: 18px;+ background: #0f0f17;+ border: 2px dashed var(--border);+ border-radius: 8px;+ text-align: center;+ cursor: pointer;+ transition: border-color 0.15s;+ color: #888;+ }+ .file-input-wrapper input[type='file']:focus + .file-input-label {+ border-color: var(--accent);+ color: #ccc;+ }+ .file-input-wrapper:hover .file-input-label {+ border-color: #444;+ color: #aaa;+ }+ pre {+ background: #0f0f17;+ border: 1px solid var(--border);+ border-radius: 8px;+ padding: 10px 12px;+ overflow: auto;+ font-size: 12px;+ max-height: 200px;+ }+ code {+ font-family: ui-monospace, SF Mono, Menlo, monospace;+ }+ </style>+ </head>+ <body>+ <header>+ <div class="brand"><a href="/">3D Agent</a></div>+ <nav>+ <a href="/">Home</a>+ <a href="/dashboard">Dashboard</a>+ <a href="/explore">Explore</a>+ </nav>+ </header>++ <main id="main">+ <h1>Validation Records</h1>+ <p class="sub">Browse validation reports for this agent to verify trust and integrity.</p>++ <div class="toolbar">+ <input+ type="text"+ id="agent-input"+ placeholder="Agent ID (e.g., 1)"+ style="width: 200px"+ />+ <input+ type="text"+ id="chain-input"+ placeholder="Chain ID (e.g., 84532)"+ style="width: 200px"+ />+ <button class="btn" id="load-btn">Load Records</button>+ <button class="btn sec" id="submit-btn">Submit Validation</button>+ </div>++ <div id="error" class="err" style="display: none"></div>+ <div id="info" class="info" style="display: none"></div>+ <div id="records" class="records"></div>+ <div id="empty" class="empty" style="display: none">No validation records yet.</div>+ </main>++ <!-- Submit Modal -->+ <div class="modal-overlay" id="submit-modal">+ <div class="modal">+ <h2>Submit Validation Report</h2>+ <p class="sub">Upload a JSON validation report signed by your wallet.</p>++ <div class="form-group">+ <label>Report File (JSON)</label>+ <div class="file-input-wrapper">+ <input type="file" id="report-file" accept=".json" />+ <label for="report-file" class="file-input-label">+ 📄 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>++ <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>++ <div id="hash-section" style="display: none" class="form-group">+ <label>Report Hash</label>+ <input+ type="text"+ id="report-hash"+ readonly+ 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))+ </div>+ </div>++ <div class="modal-actions">+ <button class="btn sec" onclick="closeSubmitModal()">Cancel</button>+ <button class="btn" id="submit-report-btn" disabled>Submit on-chain</button>+ </div>+ </div>+ </div>++ <script type="module">+ import { ValidationDashboard } from '/validation/boot.js';++ const dashboard = new ValidationDashboard(document.getElementById('main'), {+ agentInput: document.getElementById('agent-input'),+ chainInput: document.getElementById('chain-input'),+ loadBtn: document.getElementById('load-btn'),+ submitBtn: document.getElementById('submit-btn'),+ recordsContainer: document.getElementById('records'),+ emptyState: document.getElementById('empty'),+ errorEl: document.getElementById('error'),+ infoEl: document.getElementById('info'),+ submitModal: document.getElementById('submit-modal'),+ reportFile: document.getElementById('report-file'),+ fileStatus: document.getElementById('file-status'),+ previewSection: document.getElementById('preview-section'),+ previewJson: document.getElementById('preview-json'),+ previewError: document.getElementById('preview-error'),+ hashSection: document.getElementById('hash-section'),+ reportHash: document.getElementById('report-hash'),+ submitReportBtn: document.getElementById('submit-report-btn'),+ });++ window.closeSubmitModal = () => dashboard.closeModal();+ window.submitModal = () => dashboard.submitReport();+ </script>+ </body>+</html>diff --git a/public/wallet-login.js b/public/wallet-login.jsindex b61828fd3..ba7fdb5cf 100644--- a/public/wallet-login.js+++ b/public/wallet-login.js@@ -102,7 +102,7 @@ async function completeSignIn(provider, btn) {if (btn) btn.textContent = 'Requesting nonce…';const nonceRes = await fetch('/api/auth/siwe/nonce', { credentials: 'include' });if (!nonceRes.ok) throw new Error('Failed to get nonce');- const { nonce } = await nonceRes.json();+ const { nonce, csrf } = await nonceRes.json();const domain = location.host;const uri = location.origin;@@ -130,7 +130,7 @@ async function completeSignIn(provider, btn) {const verifyRes = await fetch('/api/auth/siwe/verify', {method: 'POST',credentials: 'include',- headers: { 'content-type': 'application/json' },+ headers: { 'content-type': 'application/json', 'x-csrf-token': csrf },body: JSON.stringify({ message, signature }),});const data = await verifyRes.json();diff --git a/scripts/cz-demo/runbook.sh b/scripts/cz-demo/runbook.shnew file mode 100755index 000000000..a3257204c--- /dev/null+++ b/scripts/cz-demo/runbook.sh@@ -0,0 +1,249 @@+#!/usr/bin/env bash+# CZ Demo Health-Check Script+# Usage: scripts/cz-demo/runbook.sh {check|warm|stop}+#+# check — verify all demo dependencies (staging up, API working, chain state, etc.)+# warm — pre-warm caches by hitting all demo URLs+# stop — gracefully disable public traffic (stub for now)++set -e++# Colors for output+RED='\033[0;31m'+GREEN='\033[0;32m'+YELLOW='\033[1;33m'+BLUE='\033[0;34m'+NC='\033[0m' # No Color++# Configuration — set these before running+STAGING_URL="${STAGING_URL:-http://localhost:3000}"+CHAIN_ID="${CHAIN_ID:-84532}" # Base Sepolia+BLOCK_EXPLORER="${BLOCK_EXPLORER:-https://sepolia.basescan.org}"+RPC_ENDPOINT="${RPC_ENDPOINT:-https://sepolia.base.org}"++# Counters+CHECKS_PASSED=0+CHECKS_FAILED=0++log_pass() {+ echo -e "${GREEN}✓${NC} $1"+ ((CHECKS_PASSED++))+}++log_fail() {+ echo -e "${RED}✗${NC} $1"+ ((CHECKS_FAILED++))+}++log_info() {+ echo -e "${BLUE}ℹ${NC} $1"+}++log_warn() {+ echo -e "${YELLOW}⚠${NC} $1"+}++# ============================================================================+# COMMAND: check+# ============================================================================++cmd_check() {+ echo -e "${BLUE}CZ Demo Health Check${NC}"+ echo "Staging URL: $STAGING_URL"+ echo "RPC Endpoint: $RPC_ENDPOINT"+ echo "---"++ # 1. Staging /cz endpoint+ echo -n "Checking /cz endpoint... "+ if curl -sf "$STAGING_URL/cz" > /dev/null 2>&1; then+ log_pass "/cz endpoint reachable"+ else+ log_fail "/cz endpoint not reachable (HTTP error or timeout)"+ fi++ # 2. Avatar file exists+ echo -n "Checking avatar GLB... "+ if curl -sI "$STAGING_URL/avatars/cz.glb" 2>/dev/null | grep -q "200 OK"; then+ AVATAR_SIZE=$(curl -sI "$STAGING_URL/avatars/cz.glb" 2>/dev/null | grep -i "content-length" | awk '{print $2}' | tr -d '\r')+ if [ -z "$AVATAR_SIZE" ]; then+ log_warn "/avatars/cz.glb exists but size unknown"+ elif [ "$AVATAR_SIZE" -lt 1000000 ] || [ "$AVATAR_SIZE" -gt 20000000 ]; then+ log_warn "/avatars/cz.glb size out of expected range: $AVATAR_SIZE bytes"+ else+ log_pass "/avatars/cz.glb exists (${AVATAR_SIZE} bytes)"+ fi+ else+ log_fail "/avatars/cz.glb not found or CORS blocked (HTTP error)"+ fi++ # 3. CZ state endpoint+ echo -n "Checking /cz/state.json... "+ STATE_RESPONSE=$(curl -s "$STAGING_URL/cz/state.json" 2>/dev/null || echo "{}")+ if echo "$STATE_RESPONSE" | grep -q "status"; then+ STATUS=$(echo "$STATE_RESPONSE" | grep -o '"status":"[^"]*"' | cut -d'"' -f4)+ log_pass "/cz/state.json responds (status: $STATUS)"+ else+ log_fail "/cz/state.json not found or invalid JSON"+ fi++ # 4. API health+ echo -n "Checking /api/config endpoint... "+ if curl -sf "$STAGING_URL/api/config" > /dev/null 2>&1; then+ log_pass "/api/config endpoint reachable"+ else+ log_fail "/api/config endpoint not reachable (HTTP error)"+ fi++ # 5. CZ identity endpoint (may be 404 if pre-onchain)+ echo -n "Checking /api/cz/identity endpoint... "+ IDENTITY_STATUS=$(curl -s -o /dev/null -w "%{http_code}" "$STAGING_URL/api/cz/identity" 2>/dev/null)+ if [ "$IDENTITY_STATUS" = "200" ]; then+ AGENT_ID=$(curl -s "$STAGING_URL/api/cz/identity" 2>/dev/null | grep -o '"agentId":"[^"]*"' | cut -d'"' -f4)+ log_pass "/api/cz/identity responds (agentId: ${AGENT_ID:0:8}…)"+ elif [ "$IDENTITY_STATUS" = "404" ]; then+ log_warn "/api/cz/identity returns 404 (agent not yet registered on-chain)"+ else+ log_fail "/api/cz/identity returned HTTP $IDENTITY_STATUS"+ fi++ # 6. RPC connectivity+ echo -n "Checking RPC endpoint... "+ if RPC_RESPONSE=$(curl -s -X POST "$RPC_ENDPOINT" \+ -H "Content-Type: application/json" \+ -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' 2>/dev/null); then+ if echo "$RPC_RESPONSE" | grep -q "result"; then+ BLOCK_HEX=$(echo "$RPC_RESPONSE" | grep -o '"result":"0x[^"]*"' | cut -d'"' -f4)+ BLOCK_DEC=$((16#${BLOCK_HEX:2}))+ log_pass "RPC endpoint responding (latest block: $BLOCK_DEC)"+ else+ log_fail "RPC endpoint returned invalid JSON or error"+ fi+ else+ log_fail "RPC endpoint not reachable (connection timeout)"+ fi++ # 7. Offline fallback exists+ echo -n "Checking offline fallback... "+ if curl -sf "$STAGING_URL/cz/offline/index.html" > /dev/null 2>&1; then+ log_pass "/cz/offline/index.html exists and is accessible"+ else+ log_fail "/cz/offline/index.html not found (HTTP error)"+ fi++ # 8. Browser cache warm-up suggestion+ echo ""+ log_info "Tip: Pre-load /cz in your browser 30 min before demo to warm caches"++ # Summary+ echo ""+ echo -e "${BLUE}Summary${NC}"+ echo -e "Passed: ${GREEN}${CHECKS_PASSED}${NC} | Failed: ${RED}${CHECKS_FAILED}${NC}"+ echo ""++ if [ $CHECKS_FAILED -eq 0 ]; then+ echo -e "${GREEN}All checks passed! Ready for demo.${NC}"+ exit 0+ else+ echo -e "${RED}Some checks failed. Review above and fix before proceeding.${NC}"+ exit 1+ fi+}++# ============================================================================+# COMMAND: warm+# ============================================================================++cmd_warm() {+ echo -e "${BLUE}CZ Demo Cache Warm-Up${NC}"+ echo "Loading all demo URLs to warm browser and CDN caches..."+ echo "---"++ # List of URLs to pre-load+ URLS=(+ "$STAGING_URL/cz"+ "$STAGING_URL/avatars/cz.glb"+ "$STAGING_URL/cz/state.json"+ "$STAGING_URL/api/config"+ "$STAGING_URL/api/cz/identity"+ "$STAGING_URL/cz/offline/index.html"+ )++ SUCCESS=0+ FAILED=0++ for URL in "${URLS[@]}"; do+ echo -n "Warming $URL... "+ if curl -sf "$URL" > /dev/null 2>&1; then+ echo -e "${GREEN}OK${NC}"+ ((SUCCESS++))+ else+ echo -e "${RED}FAIL${NC}"+ ((FAILED++))+ fi+ # Small delay to avoid hammering the server+ sleep 0.5+ done++ echo ""+ echo -e "${BLUE}Warm-up complete${NC}"+ echo -e "Successful: ${GREEN}${SUCCESS}${NC} | Failed: ${RED}${FAILED}${NC}"++ if [ $FAILED -eq 0 ]; then+ echo -e "${GREEN}Caches warmed. Demo ready to start.${NC}"+ exit 0+ else+ echo -e "${YELLOW}Some URLs failed to load. Check connectivity.${NC}"+ exit 1+ fi+}++# ============================================================================+# COMMAND: stop+# ============================================================================++cmd_stop() {+ echo -e "${BLUE}CZ Demo Stop Command${NC}"+ echo "---"+ log_info "Gracefully disabling public traffic (stub implementation)"+ echo ""+ echo "In a future release, this will:"+ echo " - Set a feature flag to enable 'maintenance mode'"+ echo " - Return 503 Service Unavailable with a scheduled-restart message"+ echo " - Allow the operator to continue using the demo internally"+ echo ""+ echo "For now, manual steps:"+ echo " 1. In Vercel dashboard, set CZ_DEMO_ACTIVE=false in environment"+ echo " 2. Redeploy or wait for next build"+ echo " 3. Public traffic sees the fallback page"+ echo ""+ log_warn "This is a stub. Implement as part of the next demo cycle."+ exit 0+}++# ============================================================================+# MAIN+# ============================================================================++COMMAND="${1:-check}"++case "$COMMAND" in+ check)+ cmd_check+ ;;+ warm)+ cmd_warm+ ;;+ stop)+ cmd_stop+ ;;+ *)+ echo "Usage: $0 {check|warm|stop}"+ echo ""+ echo "Commands:"+ echo " check Verify all demo dependencies (endpoints, avatars, chain state)"+ echo " warm Pre-load all demo URLs to warm caches"+ echo " stop Gracefully disable public traffic (stub)"+ echo ""+ exit 1+ ;;+esacdiff --git a/specs/CLAUDE_ARTIFACT.md b/specs/CLAUDE_ARTIFACT.mdnew file mode 100644index 000000000..3eec008b0--- /dev/null+++ b/specs/CLAUDE_ARTIFACT.md@@ -0,0 +1,78 @@+# CLAUDE_ARTIFACT — contract spec++Endpoint that returns a single self-contained HTML document suitable for rendering as a Claude.ai artifact.++## URL shape++```+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 |++Exactly one of `agent` or `model` must be supplied; both or neither → 400.++## Whitelisted model origins++- `*.r2.cloudflarestorage.com`+- `*.amazonaws.com`+- `*.cloudfront.net`+- `storage.googleapis.com`+- `*.blob.core.windows.net`+- `3dagent.vercel.app`+- `*.vercel.app`++Any other origin, or non-`https:` scheme → 400.++## Response++- **Status:** `200 OK`+- **Content-Type:** `text/html; charset=utf-8`+- **Cache:** `public, max-age=60, s-maxage=60, stale-while-revalidate=3600`++### 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 *+```++`frame-ancestors *` allows Claude.ai's sandboxed artifact iframe to load the document.++## Error responses++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) |++## Browser compat++The returned document uses `<agent-3d>` (custom element) defined by the UMD bundle at `/dist-lib/agent-3d.umd.cjs`. Requires:++- Custom Elements v1 — Chrome 67+, Firefox 63+, Safari 10.1++- WebGL 1 (three.js fallback for WebGL 2 absent)++Claude.ai artifact iframes run Chromium — fully supported.++## Authoring notes++- `res.end(html)` is used intentionally. The "no `res.end`" rule in `CLAUDE.md` applies to JSON responses only.+- HTML attribute values are escaped via `escAttr()` to prevent XSS from user-supplied agent names or model URLs.+- SQL lookup uses tagged-template `sql\`...\`` — no string concat.diff --git a/specs/EDITOR_SPEC.md b/specs/EDITOR_SPEC.mdnew file mode 100644index 000000000..255ef4423--- /dev/null+++ b/specs/EDITOR_SPEC.md@@ -0,0 +1,540 @@+# 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.++---++## 1. Identity++The editor layer lives in [`src/editor/`](../src/editor/) and is orchestrated by [`src/editor/index.js`](../src/editor/index.js) (`Editor` class). It is activated in the Studio/viewer via a dat.gui `Editor` folder; the intended web-component activation path uses the `editor` boolean attribute on `<agent-3d>`.++### Pre-1.0 rough edge #1 — `editor` attribute not yet wired++[`EMBED_SPEC.md` §Dev/debug](./EMBED_SPEC.md) documents `<agent-3d editor>` and says it "mounts the embed editor instead of the live agent." However, [`src/element.js`](../src/element.js) does not include `editor` in `observedAttributes()` (line 211–226) and `_boot()` has no branch for it. The embed editor module ([`src/editor/embed-editor.js`](../src/editor/embed-editor.js)) must be imported and mounted manually today. Downstream hosts must not rely on the attribute-driven path until this is wired.++---++## 2. Attached editor contract++### `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).++### Other attributes used by editor flows++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 |++---++## 3. Editor panels++### 3.1 `EditorSession` — [`src/editor/session.js`](../src/editor/session.js)++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` |++**Patch shapes:**++```js+// MaterialEditPatch+{+ name: string, // material.name — used for GLB export name-matching+ uuid: string,+ baseColor?: [r, g, b], // 0–1 floats+ metalness?: number,+ roughness?: number,+ emissive?: [r, g, b],+ opacity?: number,+ alphaMode?: 'OPAQUE'|'BLEND'|'MASK',+ alphaCutoff?: number,+ doubleSided?: boolean+}++// TransformEditPatch+{+ name: string, // node.name — used for GLB export name-matching+ uuid: string,+ position: [x, y, z],+ rotation: [x, y, z], // Euler, radians, XYZ order+ scale: [x, y, z]+}+```++**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 |++**Failure modes:** `getSourceBuffer()` throws if no source is set. `reset()` with no source logs a warning but does not throw.++---++### 3.2 `MaterialEditor` — [`src/editor/material-editor.js`](../src/editor/material-editor.js)++**What it edits:** PBR properties on every `MeshStandardMaterial` and `MeshPhysicalMaterial` in the loaded scene. One dat.gui subfolder per material, opened under a top-level `Materials` folder.++**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` |++**Inputs:** `viewer.content` (Three.js scene graph), `viewer.gui` (dat.GUI instance), `EditorSession`.++**Outputs:** mutates Three.js material in place for live preview; records to `session.materialEdits` on every change via `recordMaterialEdit()`.++**Events:** none. Internal only via `session.onChange`.++**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.++### Pre-1.0 rough edge #2 — emissive intensity not persisted++`emissiveIntensity` changes call `mat.needsUpdate = true` and `viewer.invalidate()` but do **not** call `record()` ([`src/editor/material-editor.js:100–103`](../src/editor/material-editor.js#L100)). The value is visible in the viewport but will not appear in an exported GLB.++---++### 3.3 `SceneExplorer` — [`src/editor/scene-explorer.js`](../src/editor/scene-explorer.js)++**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+- Visibility toggle (● visible / ○ hidden)++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`.++**Search:** Text input filters tree rows by label; matching rows expand their ancestors.++**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 |+| `Escape` | Detach gizmo, deselect node |++**Inputs:** `viewer` (Viewer instance), `EditorSession`.++**Outputs:** mutates Three.js scene graph in place for live preview; records to `session.transformEdits` / `session.visibilityEdits`.++**Events:** none emitted. `dragging-changed` on TransformControls disables `viewer.controls` while dragging.++**Failure modes:** If `viewer.renderer.domElement` is unavailable at `attach()` time, pointer-down raycasting silently skips. Panel remains in the DOM on error.++---++### 3.4 `TextureInspector` — [`src/editor/texture-inspector.js`](../src/editor/texture-inspector.js)++**What it does:** Catalogs every texture referenced by the loaded model, renders a thumbnail grid panel, and provides a full-screen lightbox with per-channel extraction, zoom/pan, and UV wireframe overlay.++**Read-only:** The TextureInspector does **not** record edits to the session. It is a diagnostic/inspection tool only. No texture modifications are persisted to the exported GLB.++**Texture catalog:** Collected by traversing `viewer.content` via `traverseMaterials()`. For each unique texture UUID, tracks: material slot labels, material names, and mesh nodes (for UV overlay). Covered slots: base color, normal, metallic, roughness, occlusion, emissive, bump, alpha, displacement, clearcoat (and variants), sheen (and variants), specular (and variants), transmission, thickness, light map — 19 slots total.++**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)+- Zoom (mouse wheel) and pan (mouse drag) with cursor-centered zoom+- Fit/reset button++**Keyboard shortcut:** `X` — toggle the texture grid panel open/closed.++**Inputs:** `viewer.content`, `viewer.gui`.++**Outputs:** none to session. DOM panels appended to `document.body`.++**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.++---++### 3.5 `exportEditedGLB` / `downloadGLB` — [`src/editor/glb-export.js`](../src/editor/glb-export.js)++**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).++**What is stripped:** Nothing — all geometry, animations, extensions, and accessories in the source file are preserved.++**Name matching:** Materials and nodes are matched to glTF-Transform entities by **name**, not UUID. Three.js UUIDs do not cross the serialization boundary. The first material/node with a matching name receives the edit. Duplicate names silently affect only the first match.++**`downloadGLB(bytes, filename)`:** Creates a `Blob` URL, triggers an `<a download>` click, removes the element, and revokes the URL after 1 second.++**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`.++### Pre-1.0 rough edge #3 — visibility via scale hack++Hidden nodes are written as `scale = [0, 0, 0]` rather than using a `KHR_node_visibility` extension or `extras.hidden`. This works visually but destroys the scale edit for those nodes and is not spec-compliant glTF visibility. ([`src/editor/glb-export.js:106–109`](../src/editor/glb-export.js#L106))++### Pre-1.0 rough edge #4 — duplicate name collision++Both material edits and transform/visibility edits match by the first occurrence of each name in the glTF root. If a model has two materials both named `"Material"`, only the first is patched. The GUI shows both under different folder labels but they share the name key. ([`src/editor/glb-export.js:53–58`](../src/editor/glb-export.js#L53))++---++### 3.6 `publishEditedGLB` — [`src/editor/publish.js`](../src/editor/publish.js)++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` |++**Progress callback:** `onStep({ step, pct })` fired at each step boundary. Steps: `'export'`, `'presign'`, `'upload'`, `'register'`, `'widget'`.++**Return value on success:**+```js+{+ widget: { id, ... },+ avatar: { id, ... },+ urls: {+ page: 'https://…/w/<widgetId>',+ iframe: '<iframe src="…" …></iframe>',+ element: '<script …></script>\n<agent-3d src="…" …></agent-3d>'+ }+}+```++**Error classes exported** (importable from `./publish.js`):++| 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 |++**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.++**Auth requirements:** Session cookie (`credentials: 'include'`) or bearer token with `avatars:write` scope. No anonymous publishing.++**Failure on 401:** throws `AuthRequiredError`. Callers (e.g. `PublishModal`) redirect to `/login?next=<url>` and stash session state in `sessionStorage`/IndexedDB via [`src/editor/edit-persistence.js`](../src/editor/edit-persistence.js) for round-trip restore.++---++### 3.7 `PublishModal` — [`src/editor/publish-modal.js`](../src/editor/publish-modal.js)++UI wrapper over `publishEditedGLB`. Manages three states: **working** (step progress list), **result** (shareable snippets), **error** / **auth-required**. Appended to `containerEl` (default: `document.body`) as a modal overlay.++**Auth-required state:** Stashes session via `edit-persistence.stashSession()`, then redirects to `/login?next=<url with ?resume=<token>&publish=1>`.++**Output shown to user on success:** share link, iframe snippet, web component snippet. Each copyable. Share link also has an "Open" button.++**Accessibility:** `role="dialog"`, `aria-modal="true"`, focus trap, `Escape` closes, `aria-live="polite"` on step list.++---++### 3.8 `EmbedEditor` — [`src/editor/embed-editor.js`](../src/editor/embed-editor.js)++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+- Responsive preset (fixed, mobile-first, desktop-first)+- Device preview switcher (desktop 1440×900, tablet 768×1024, mobile 390×844)+- "Copy Embed" — generates and copies the `<agent-3d>` snippet++**Output:** a complete `<script type="module">` + `<agent-3d>` snippet with no `editor` attribute.++**Note:** This module is self-contained and not wired through the `Editor` orchestrator in `index.js`. It imports `../element.js` directly.++---++### 3.9 `Editor` orchestrator — [`src/editor/index.js`](../src/editor/index.js)++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.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]`+- `↺ revert all edits`++**`dispose()`:** removes all sub-panels, gui folder, and detaches SceneExplorer.++---++## 4. Permission model++### 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 |++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++1. `POST /api/avatars/presign` — requires valid session or bearer with `avatars:write`. Returns 401 if missing. ([`api/avatars/presign.js:15–18`](../api/avatars/presign.js#L15))+2. `POST /api/avatars` — same auth requirement. Additionally verifies that `storage_key` starts with `u/{auth.userId}/` to prevent cross-user key claiming. ([`api/avatars/index.js:50–53`](../api/avatars/index.js#L50))++### How the editor checks identity++Client-side auth hint via `readAuthHint()` from [`src/account.js:43`](../src/account.js#L43) (localStorage, 7-day TTL). This is optimistic and non-authoritative — used only to gate first-paint UI. Authoritative check is `getMe()` → `GET /api/auth/me` ([`src/account.js:63`](../src/account.js#L63)). Both session cookie and bearer token are accepted.++### 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.++([`src/editor/publish-modal.js:155–163`](../src/editor/publish-modal.js#L155))++---++## 5. Events++### Session internal events++`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 |++### 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 |++(`PublishModal.onStep` maps `'presign'` → `'upload'` bucket for UI display.)++### Pre-1.0 rough edge #5 — no DOM CustomEvents from the Editor++The `Editor` class and all panels communicate via `session.onChange()` callbacks and direct method calls. No `CustomEvent` is dispatched on any DOM node. External hosts integrating the editor cannot listen to edit events on the element without accessing `editor.session.onChange()` directly. This is an integration gap for the `<agent-3d editor>` web-component path.++---++## 6. Extension points++### Adding a custom panel++There is no formal plugin API. The pattern followed by existing panels:++1. Class takes `(viewer, session)` in its constructor.+2. Exposes `rebuild()` called by `Editor.onContentChanged()`.+3. Exposes `dispose()` for cleanup.+4. Optionally adds a dat.gui folder via `viewer.gui`.+5. Calls `session.onChange()` to react to upstream changes, returns the unsubscribe function for cleanup.++To wire a custom panel into the orchestrator, modify `Editor` in [`src/editor/index.js`](../src/editor/index.js) — there is no registration mechanism today.++### Adding a custom exporter++`exportEditedGLB` in [`src/editor/glb-export.js`](../src/editor/glb-export.js) is a standalone async function:++```js+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.++No formal exporter plugin contract exists; the `Editor._exportGLB()` method ([`src/editor/index.js:108`](../src/editor/index.js#L108)) hardcodes the import. Replacing the exporter requires editing the orchestrator.++**Recommendation:** Do not invest in a custom exporter plugin seam until the `editor` attribute is wired in `element.js` — the integration surface is too unstable before that.++---++## 7. Security++### What is sanitized before upload++**Content-type allowlist:** Only `model/gltf-binary` and `model/gltf+json` are accepted by the presign and avatar-create endpoints. This is enforced by the Zod schema `avatarContentType` at [`api/_lib/validate.js:20–23`](../api/_lib/validate.js#L20). An upload of any other MIME type (HTML, SVG, JS, etc.) is rejected with `400 validation_error` before a presigned URL is issued — preventing XSS via CDN-hosted file.++**Storage key ownership:** `POST /api/avatars` verifies that the submitted `storage_key` starts with `u/{auth.userId}/` and does not contain `..` ([`api/avatars/index.js:50–53`](../api/avatars/index.js#L50)). Users cannot register objects uploaded by other users.++**R2 object existence:** `headObject(storage_key)` is called before writing the `avatars` record ([`api/avatars/index.js:56–57`](../api/avatars/index.js#L57)). If the object is not in R2 or the `size_bytes` does not match, the request is rejected. This blocks attempts to register a fake record without performing the upload.++**Optional checksum:** If the browser includes a `checksum_sha256` in the presign or register body, it is stored. If not provided, the server attempts to read it from the R2 object metadata ([`api/avatars/index.js:63–79`](../api/avatars/index.js#L63)). Not enforced as required today.++### 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 |++The client enforces 25 MB; the server allows up to 500 MB. A caller bypassing the client library can upload up to 500 MB.++### Allowed MIME types++`model/gltf-binary` and `model/gltf+json` only. Enforced at both presign and register endpoints.++### SSRF++The presign flow issues a PUT URL for direct browser-to-R2 upload; the server never fetches the uploaded content. No SSRF surface in the publish path.++`EditorSession.getSourceBuffer()` does `fetch(this.sourceURL)` ([`src/editor/session.js:179`](../src/editor/session.js#L179)) to retrieve the source model bytes. This runs in the **browser**, not the server, so there is no server-side SSRF. However, any URL the user can set as `sourceURL` is fetched. This is intentional: users can load GLBs from arbitrary HTTPS origins (subject to browser CORS policy).++---++## 8. Versioning++### Spec version++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).+- CSS/layout changes inside panels.++### Detecting the editor version at runtime++No version attribute or event exists today. To check which spec version an editor host speaks:++**Recommended (not yet implemented):** Add a `data-editor-version="agent-editor/0.1"` attribute to the root element mounted by `mountEmbedEditor`, and/or dispatch a `editor:ready` CustomEvent with `{ version: 'agent-editor/0.1' }` on the host element at mount time. This attribute/event should be added before the `editor` attribute is wired in `element.js`.++Until then, feature-detect by checking whether the `Editor` class is exported from [`src/editor/index.js`](../src/editor/index.js).++---++## 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 |++---++## See also++- [EMBED_SPEC.md](./EMBED_SPEC.md) — full attribute reference for `<agent-3d>`+- [AGENT_MANIFEST.md](./AGENT_MANIFEST.md) — manifest format+- [`src/editor/`](../src/editor/) — source of truth for all claims above+- [`api/avatars/`](../api/avatars/) — presign and register endpoints+- [`api/_lib/validate.js`](../api/_lib/validate.js) — content-type allowlist and size limitsdiff --git a/src/agents-directory.js b/src/agents-directory.jsnew file mode 100644index 000000000..a0699a6ba--- /dev/null+++ b/src/agents-directory.js@@ -0,0 +1,276 @@+/**+ * Public agents directory controller.+ *+ * Manages fetching, caching, filtering, and sorting of registered agents.+ * Uses on-chain data from IdentityRegistry with optional backend metadata.+ */++import { listRegisteredEvents, getAgentOnchain, fetchAgentMetadata, findAvatar3D } from './erc8004/queries.js';+import { CHAIN_META } from './erc8004/chain-meta.js';+import { REGISTRY_DEPLOYMENTS } from './erc8004/abi.js';++const CACHE_TTL_MS = 60000; // 60s SWR cache+const ITEMS_PER_PAGE = 30;++export class AgentsDirectory {+ constructor(containerSelector) {+ this.container = document.querySelector(containerSelector);+ if (!this.container) throw new Error(`Container not found: ${containerSelector}`);+ this.agents = []; // All loaded agents+ this.displayedAgents = []; // Filtered agents for current page+ this.currentPage = 1;+ this.filters = {+ chain: 'all',+ search: '',+ sort: 'newest',+ };+ this.cache = new Map(); // Per-page caches: `${chain}:${page}` → { data, time }+ this.cardClickHandler = null;+ this.lazyObserver = null;+ }++ /**+ * Load agents for a given chain, page, and filters.+ * @param {object} opts+ * @param {string} [opts.chain='all'] Chain filter: 'all', 'base', 'base-sepolia', etc.+ * @param {string} [opts.search=''] Search term (name/id)+ * @param {string} [opts.sort='newest'] Sort key: 'newest', 'name', 'oldest'+ * @param {number} [opts.page=1] Page number (1-indexed)+ * @returns {Promise<{ agents: Array, totalPages: number, total: number }>}+ */+ async load({ chain = 'all', search = '', sort = 'newest', page = 1 } = {}) {+ this.filters = { chain, search, sort };+ this.currentPage = page;++ // Check cache+ const cacheKey = `${chain}:${page}:${search}:${sort}`;+ const cached = this.cache.get(cacheKey);+ if (cached && Date.now() - cached.time < CACHE_TTL_MS) {+ this.displayedAgents = cached.data;+ const totalPages = Math.ceil(this.agents.length / ITEMS_PER_PAGE);+ return { agents: this.displayedAgents, totalPages, total: this.agents.length };+ }++ // Fetch all agents if not already loaded+ if (this.agents.length === 0) {+ await this._fetchAllAgents();+ }++ // Apply filters and sorting+ let filtered = this._applyFilters();+ filtered = this._applySorting(filtered);++ // Paginate+ const totalPages = Math.ceil(filtered.length / ITEMS_PER_PAGE);+ const offset = (page - 1) * ITEMS_PER_PAGE;+ this.displayedAgents = filtered.slice(offset, offset + ITEMS_PER_PAGE);++ // Cache result+ this.cache.set(cacheKey, { data: this.displayedAgents, time: Date.now() });++ return { agents: this.displayedAgents, totalPages, total: filtered.length };+ }++ /**+ * Register a callback for card clicks.+ * @param {Function} fn Called with agent object when card is clicked+ */+ onCardClick(fn) {+ this.cardClickHandler = fn;+ }++ /**+ * Set up lazy loading for avatar thumbnails.+ */+ setupLazyLoad() {+ if (!('IntersectionObserver' in window)) return;+ this.lazyObserver = new IntersectionObserver((entries) => {+ for (const entry of entries) {+ if (!entry.isIntersecting) continue;+ const img = entry.target;+ const src = img.dataset.src;+ if (src) {+ img.src = src;+ img.removeAttribute('data-src');+ this.lazyObserver.unobserve(img);+ }+ }+ });+ // Observe on next render+ requestAnimationFrame(() => {+ this.container+ .querySelectorAll('img[data-src]')+ .forEach((img) => this.lazyObserver.observe(img));+ });+ }++ /**+ * Render agent cards as HTML. Call after load().+ */+ render() {+ const html = this.displayedAgents+ .map((agent) => this._renderCard(agent))+ .join('');+ this.container.innerHTML = html;+ this._attachEventListeners();+ this.setupLazyLoad();+ }++ /**+ * Return pagination info for current state.+ */+ getPaginationInfo() {+ const totalPages = Math.ceil(+ this._applyFilters().length / ITEMS_PER_PAGE+ );+ return {+ page: this.currentPage,+ totalPages,+ itemsPerPage: ITEMS_PER_PAGE,+ hasNextPage: this.currentPage < totalPages,+ hasPrevPage: this.currentPage > 1,+ };+ }++ // ─────────────────────────────────────────────────────────────────────────++ async _fetchAllAgents() {+ const agents = [];+ const chains = ['all'].includes(this.filters.chain)+ ? Object.keys(CHAIN_META).map(Number)+ : [Number(this.filters.chain.split('-')[0]) || 8453]; // Default to Base if unclear++ for (const chainId of chains) {+ try {+ const events = await listRegisteredEvents({+ chainId,+ limit: 500, // Adjust as needed+ });++ for (const ev of events) {+ try {+ const agentId = String(ev.agentId);+ const onchain = await getAgentOnchain({+ chainId,+ agentId,+ });++ let metadata = {};+ if (ev.agentURI) {+ metadata = await fetchAgentMetadata(ev.agentURI).catch(() => ({}));+ }++ const avatar = await findAvatar3D(metadata).catch(() => null);++ agents.push({+ id: agentId,+ chainId,+ name: metadata.name || `Agent #${agentId}`,+ description: metadata.description || '',+ avatar: avatar?.url || null,+ owner: onchain.owner || ev.owner,+ createdAt: ev.blockNumber+ ? new Date(ev.blockNumber * 12000) // Rough estimate+ : new Date(),+ registeredBlock: ev.blockNumber,+ txHash: ev.txHash,+ });+ } catch (err) {+ console.warn(`Failed to fetch agent ${ev.agentId}:`, err);+ }+ }+ } catch (err) {+ console.warn(`Failed to fetch chain ${chainId}:`, err);+ }+ }++ this.agents = agents;+ }++ _applyFilters() {+ return this.agents.filter((agent) => {+ // Chain filter+ if (this.filters.chain !== 'all') {+ const targetChain = Number(this.filters.chain.split('-')[0]) || 8453;+ if (agent.chainId !== targetChain) return false;+ }++ // Search filter+ if (this.filters.search.trim()) {+ const term = this.filters.search.toLowerCase();+ if (+ !agent.name.toLowerCase().includes(term) &&+ !agent.id.includes(term) &&+ !agent.description.toLowerCase().includes(term)+ ) {+ return false;+ }+ }++ return true;+ });+ }++ _applySorting(agents) {+ const sorted = [...agents];+ switch (this.filters.sort) {+ case 'name':+ sorted.sort((a, b) => a.name.localeCompare(b.name));+ break;+ case 'oldest':+ sorted.sort((a, b) => a.createdAt - b.createdAt);+ break;+ case 'newest':+ default:+ sorted.sort((a, b) => b.createdAt - a.createdAt);+ }+ return sorted;+ }++ _renderCard(agent) {+ const avatarUrl = agent.avatar || '';+ const cleanName = this._escapeHtml(agent.name);+ const cleanDesc = this._escapeHtml(agent.description.slice(0, 100));+ const chainName = CHAIN_META[agent.chainId]?.name || `Chain ${agent.chainId}`;++ return `+ <div class="agent-card" data-agent-id="${agent.id}" data-chain-id="${agent.chainId}">+ <div class="card-avatar">+ ${+ avatarUrl+ ? `<img data-src="${this._escapeHtml(avatarUrl)}" alt="${cleanName}" loading="lazy">`+ : '<div class="avatar-placeholder">👤</div>'+ }+ </div>+ <div class="card-content">+ <h3 class="card-name">${cleanName}</h3>+ <p class="card-desc">${cleanDesc}${agent.description.length > 100 ? '…' : ''}</p>+ <div class="card-meta">+ <span class="chain-badge">${chainName}</span>+ <span class="agent-id">#${agent.id}</span>+ </div>+ </div>+ </div>+ `;+ }++ _escapeHtml(text) {+ const map = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };+ return String(text).replace(/[&<>"']/g, (m) => map[m]);+ }++ _attachEventListeners() {+ this.container.querySelectorAll('.agent-card').forEach((card) => {+ card.addEventListener('click', () => {+ const agentId = card.dataset.agentId;+ const chainId = card.dataset.chainId;+ const agent = this.agents.find(+ (a) => a.id === agentId && a.chainId === Number(chainId)+ );+ if (agent && this.cardClickHandler) {+ this.cardClickHandler(agent);+ }+ });+ });+ }+}diff --git a/src/artifact/entry.js b/src/artifact/entry.jsnew file mode 100644index 000000000..2015a8b0c--- /dev/null+++ b/src/artifact/entry.js@@ -0,0 +1,139 @@+// 3D Agent Claude Artifact Bundle+// Lightweight viewer for agents inside Claude Artifacts+// Loads three.js from CDN (esm.sh is allowed in artifact sandboxes)+// Usage: <script src="artifact.js"></script>+// <div id="agent3d" data-agent-id="123"></div>++(async function initArtifact() {+ const container = document.getElementById('agent3d');+ if (!container) return;++ // Setup container+ container.style.cssText = 'position: relative; width: 100%; height: 100%; min-height: 400px; background: #000;';++ // Add caption+ const caption = document.createElement('div');+ caption.className = 'agent3d-caption';+ caption.style.cssText = `+ position: absolute;+ bottom: 0;+ left: 0;+ right: 0;+ background: rgba(0, 0, 0, 0.6);+ color: #fff;+ padding: 12px 16px;+ font-family: system-ui, -apple-system, sans-serif;+ font-size: 14px;+ z-index: 5;+ text-align: center;+ `;+ caption.textContent = 'Loading...';+ container.appendChild(caption);++ // Get agent ID from config or data attributes+ 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';++ if (!agentId) {+ caption.textContent = 'Missing agent ID';+ return;+ }++ 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 { OrbitControls } = await import(+ 'https://esm.sh/[email protected]/examples/jsm/controls/OrbitControls.js'+ );++ // Fetch agent data+ const agentRes = await fetch(`${origin}/api/agents/${agentId}`, {+ mode: 'cors',+ credentials: 'omit',+ });++ if (!agentRes.ok) {+ caption.textContent = 'Agent not found';+ return;+ }++ const agentData = await agentRes.json();+ const agent = agentData.agent;++ // Update caption with agent name+ caption.textContent = agent.name || 'Agent';++ // Setup scene+ const width = container.clientWidth;+ const height = container.clientHeight;++ const scene = new THREE.Scene();+ scene.background = new THREE.Color(0x000000);+ scene.fog = new THREE.Fog(0x000000, 1, 1000);++ // Lighting+ const ambientLight = new THREE.AmbientLight(0xffffff, 1.0);+ scene.add(ambientLight);++ const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);+ directionalLight.position.set(5, 10, 7);+ directionalLight.castShadow = true;+ directionalLight.shadow.mapSize.width = 2048;+ directionalLight.shadow.mapSize.height = 2048;+ directionalLight.shadow.camera.near = 0.5;+ directionalLight.shadow.camera.far = 500;+ scene.add(directionalLight);++ // Camera+ const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);+ camera.position.set(0, 1.5, 3);++ // Renderer+ const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });+ renderer.setSize(width, height);+ renderer.setPixelRatio(window.devicePixelRatio);+ renderer.shadowMap.enabled = true;+ renderer.shadowMap.type = THREE.PCFShadowMap;+ renderer.outputColorSpace = THREE.SRGBColorSpace;+ renderer.toneMapping = THREE.ACESFilmicToneMapping;+ renderer.toneMappingExposure = 1.0;++ const canvas = container.querySelector('canvas');+ if (canvas) canvas.remove();+ container.insertBefore(renderer.domElement, caption);++ // Controls+ const controls = new OrbitControls(camera, renderer.domElement);+ controls.enableDamping = true;+ controls.dampingFactor = 0.05;+ controls.enableZoom = true;+ controls.autoRotate = true;+ controls.autoRotateSpeed = 2;+ controls.enablePan = false;+ controls.minDistance = 2;+ controls.maxDistance = 10;++ // Animation loop+ function animate() {+ requestAnimationFrame(animate);+ controls.update();+ renderer.render(scene, camera);+ }+ animate();++ // Handle resize+ window.addEventListener('resize', () => {+ const w = container.clientWidth;+ const h = container.clientHeight;+ camera.aspect = w / h;+ camera.updateProjectionMatrix();+ renderer.setSize(w, h);+ });+ } catch (err) {+ console.error('[artifact] error:', err);+ caption.textContent = 'Failed to load viewer';+ }+})();diff --git a/src/auth/README.md b/src/auth/README.mdnew file mode 100644index 000000000..601413339--- /dev/null+++ b/src/auth/README.md@@ -0,0 +1,72 @@+# src/auth++WalletConnect → SIWE bridge for mobile-wallet sign-in without Privy.++## Environment variable++```+VITE_WALLETCONNECT_PROJECT_ID=<your_wc_project_id>+```++Get a project ID at [cloud.walletconnect.com](https://cloud.walletconnect.com). Add it to `.env.local` for local development and to Vercel environment variables for production.++If the variable is missing the bridge returns a `wc/no_project_id` error immediately — it does not throw an unhandled exception.++## CDN++The WalletConnect provider is lazy-loaded at call time (never in the main bundle):++```+https://esm.sh/@walletconnect/[email protected]+```++**Pinned version:** `2.17.0`. To upgrade, update the `WC_CDN` constant at the top of `walletconnect-bridge.js` and re-run the smoke test.++## Usage++```js+import {+ signInWithWalletConnect,+ getWalletConnectProvider,+ disconnectWalletConnect,+} from './auth/walletconnect-bridge.js';++// Opens WC modal, signs SIWE message, verifies with server, sets session cookie.+const { user, address } = await signInWithWalletConnect();++// Get the raw EIP-1193 provider (after connect).+const provider = getWalletConnectProvider();++// Disconnect.+await disconnectWalletConnect();+```++## Error codes++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 |++## Known issues++- **Domain validation in local dev:** `/api/auth/siwe/verify` validates that the SIWE `domain` field matches `APP_ORIGIN`. Ensure `.env.local` includes `APP_ORIGIN=http://localhost:3000` (matching the Vite dev port) or the verify call will fail with `invalid_domain`.+- **CSP + CDN:** If the app sets a strict `script-src` CSP, add `https://esm.sh` to the allowlist, or self-host the WC provider package.+- **QR modal on iOS Safari:** The WC modal's clipboard copy requires a user gesture; Safari blocks it otherwise. The QR scan path still works.++## Smoke test++Open [`walletconnect-bridge.test.html`](./walletconnect-bridge.test.html) via the dev server:++```+npm run dev+# navigate to http://localhost:3000/src/auth/walletconnect-bridge.test.html+```diff --git a/src/auth/walletconnect-bridge.js b/src/auth/walletconnect-bridge.jsnew file mode 100644index 000000000..ac8fe4b81--- /dev/null+++ b/src/auth/walletconnect-bridge.js@@ -0,0 +1,167 @@+// WalletConnect v2 → SIWE bridge.+// Lazy-loads @walletconnect/ethereum-provider from CDN so it never ships in+// the main bundle unless the user explicitly triggers WC sign-in.++const WC_CDN = 'https://esm.sh/@walletconnect/[email protected]';++let _provider = null;++async function _loadEthereumProvider() {+ const { EthereumProvider } = await import(/* @vite-ignore */ WC_CDN);+ return EthereumProvider;+}++async function _resolveProjectId(override) {+ if (override) return override;++ // Vite injects VITE_* vars at build time.+ if (typeof import.meta !== 'undefined' && import.meta.env?.VITE_WALLETCONNECT_PROJECT_ID) {+ return import.meta.env.VITE_WALLETCONNECT_PROJECT_ID;+ }++ // /api/config fallback for deployments that set walletConnectProjectId there.+ try {+ const res = await fetch('/api/config');+ if (res.ok) {+ const cfg = await res.json();+ if (cfg.walletConnectProjectId) return cfg.walletConnectProjectId;+ }+ } catch { /* network failure — fall through */ }++ return null;+}++function _wcError(stage, message) {+ const err = new Error(message);+ err.code = `wc/${stage}`;+ return err;+}++/**+ * Full WalletConnect → SIWE sign-in.+ * @param {{ projectId?: string, chains?: number[] }} [opts]+ * @returns {Promise<{ user: object, address: string }>}+ */+export async function signInWithWalletConnect({ projectId, chains } = {}) {+ const pid = await _resolveProjectId(projectId);+ if (!pid) {+ throw _wcError(+ 'no_project_id',+ 'WalletConnect projectId is required. Set VITE_WALLETCONNECT_PROJECT_ID.',+ );+ }++ // 1. Load provider.+ let EthereumProvider;+ try {+ EthereumProvider = await _loadEthereumProvider();+ } catch (e) {+ throw _wcError('load_failed', `Failed to load WalletConnect provider: ${e.message}`);+ }++ // 2. Init + open modal.+ try {+ _provider = await EthereumProvider.init({+ projectId: pid,+ chains: chains || [1],+ showQrModal: true,+ methods: ['eth_requestAccounts', 'personal_sign'],+ events: ['chainChanged', 'accountsChanged'],+ });+ } catch (e) {+ throw _wcError('init_failed', `Provider init failed: ${e.message}`);+ }++ try {+ await _provider.enable();+ } catch (e) {+ throw _wcError('connect_rejected', `Connection rejected or failed: ${e.message}`);+ }++ const accounts = _provider.accounts;+ if (!accounts?.length) throw _wcError('no_accounts', 'No accounts returned after connect.');+ const address = accounts[0];++ // 3. Fetch nonce.+ let nonce;+ try {+ const nr = await fetch('/api/auth/siwe/nonce', { credentials: 'include' });+ if (!nr.ok) throw new Error(`HTTP ${nr.status}`);+ ({ nonce } = await nr.json());+ } catch (e) {+ throw _wcError('nonce_failed', `Nonce request failed: ${e.message}`);+ }++ // 4. Build EIP-4361 message matching the format expected by /api/auth/siwe/verify.+ const chainId = _provider.chainId || (chains?.[0] ?? 1);+ const domain = location.host;+ const uri = location.origin;+ const issuedAt = new Date().toISOString();++ const message = [+ `${domain} wants you to sign in with your Ethereum account:`,+ address,+ '',+ 'Sign in to 3D Agent.',+ '',+ `URI: ${uri}`,+ 'Version: 1',+ `Chain ID: ${chainId}`,+ `Nonce: ${nonce}`,+ `Issued At: ${issuedAt}`,+ ].join('\n');++ // 5. Sign.+ let signature;+ try {+ signature = await _provider.request({ method: 'personal_sign', params: [message, address] });+ } catch (e) {+ throw _wcError('sign_rejected', `User rejected signing: ${e.message}`);+ }++ // 6. Verify on server — server sets session cookie on success.+ let result;+ try {+ const vr = await fetch('/api/auth/siwe/verify', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ message, signature }),+ });+ result = await vr.json();+ if (!vr.ok) throw new Error(result.error_description || `HTTP ${vr.status}`);+ } catch (e) {+ throw _wcError('verify_failed', `SIWE verify failed: ${e.message}`);+ }++ // 7. Refresh auth hint via getMe (writes localStorage hint internally).+ try {+ const { getMe } = await import('../account.js');+ await getMe();+ } catch { /* non-fatal: hint just won't be refreshed */ }++ return {+ user: result.user,+ address: result.wallet?.address ?? address,+ };+}++/**+ * Returns the active EIP-1193 provider, or null if not connected.+ * @returns {object|null}+ */+export function getWalletConnectProvider() {+ return _provider;+}++/**+ * Disconnects the active WalletConnect session and clears the provider.+ */+export async function disconnectWalletConnect() {+ if (!_provider) return;+ try {+ await _provider.disconnect();+ } finally {+ _provider = null;+ }+}diff --git a/src/auth/walletconnect-bridge.test.html b/src/auth/walletconnect-bridge.test.htmlnew file mode 100644index 000000000..f029dbc80--- /dev/null+++ b/src/auth/walletconnect-bridge.test.html@@ -0,0 +1,73 @@+<!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>++ <script type="module">+ import { signInWithWalletConnect, getWalletConnectProvider, disconnectWalletConnect }+ from './walletconnect-bridge.js';++ const log = document.getElementById('log');++ 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;+ }++ function escHtml(s) {+ return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');+ }++ 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/cz-flow.js b/src/cz-flow.jsnew file mode 100644index 000000000..7c271e8ac--- /dev/null+++ b/src/cz-flow.js@@ -0,0 +1,139 @@+/**+ * CZ demo claim flow — manages wallet connection, claiming, and transfer flows.+ */++import { connectWallet, getIdentityRegistry } from './erc8004/agent-registry.js';+import { REGISTRY_DEPLOYMENTS } from './erc8004/abi.js';++/**+ * Start the claim flow based on the current state.+ *+ * @param {object} opts+ * @param {object} opts.state Current state (status, chainId, agentId, ownerAddress, etc.)+ * @param {(progress) => void} opts.onProgress Callback with { step, status, txHash?, error? }+ * @returns {Promise<{ ok: true, txHash? } | { ok: false, error }>}+ */+export async function startClaim({ state, onProgress }) {+ const log = (step, status, extra = {}) => {+ onProgress?.({ step, status, ...extra });+ };++ try {+ // Step 1: Connect wallet+ log('connect_wallet', 'connecting');+ const { address, chainId, signer } = await connectWallet();+ log('connect_wallet', 'connected', { address, chainId });++ // 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.',+ });+ return { ok: true, message: 'pre_onchain' };+ }++ // Step 3: If ownerAddress is 0x0 (unclaimed), call claim()+ if (state.ownerAddress === '0x0000000000000000000000000000000000000000') {+ log('claim', 'submitting');+ const registry = getIdentityRegistry(chainId, signer);+ const tx = await registry.claim(state.agentId);+ log('claim', 'pending', { txHash: tx.hash });++ const receipt = await tx.wait();+ log('claim', 'confirmed', { txHash: tx.hash });++ fireAnalytics('claim_tx_sent', { txHash: tx.hash, agentId: state.agentId });+ fireAnalytics('claim_complete', { agentId: state.agentId });+ return { ok: true, txHash: tx.hash };+ }++ // Step 4: If state.ownerAddress is known demo EOA, guide transfer+ const DEMO_EOAS = [+ '0x1234567890123456789012345678901234567890', // placeholder+ ];+ if (DEMO_EOAS.includes(state.ownerAddress?.toLowerCase())) {+ log('transfer', 'guide', {+ from: state.ownerAddress,+ to: address,+ message: 'This agent is owned by the demo account. Transfer to your wallet?',+ });++ // Real implementation would show a modal and call transferOwner() if approved+ // For now, return guidance+ return { ok: true, message: 'transfer_available' };+ }++ log('claim', 'already_owned', { owner: state.ownerAddress });+ return { ok: true, message: 'already_owned' };+ } catch (err) {+ log('claim', 'error', { error: err.message });+ fireAnalytics('claim_error', { error: err.message });+ return { ok: false, error: err.message };+ }+}++/**+ * Mount the embed copy CTA to a container.+ * Copies an <agent-3d> snippet to clipboard with chain/agentId interpolated.+ *+ * @param {HTMLElement} container+ * @param {object} opts+ * @param {object} opts.state Current state+ */+export function mountEmbedCopy(container, { state }) {+ const button = document.createElement('button');+ button.id = 'cz-embed-copy';+ button.textContent = 'Copy embed';+ button.setAttribute('aria-label', 'Copy embed code to clipboard');++ button.addEventListener('click', async () => {+ const snippet = buildEmbedSnippet(state);+ try {+ await navigator.clipboard.writeText(snippet);+ const orig = button.textContent;+ button.textContent = 'Copied!';+ fireAnalytics('embed_copied', { hasChainId: !!state.chainId, hasAgentId: !!state.agentId });+ setTimeout(() => {+ button.textContent = orig;+ }, 2000);+ } catch (err) {+ console.error('Copy failed:', err);+ button.textContent = 'Copy failed';+ setTimeout(() => {+ button.textContent = 'Copy embed';+ }, 2000);+ }+ });++ container.appendChild(button);+ return button;+}++/**+ * Build the embed snippet HTML based on state.+ */+function buildEmbedSnippet(state) {+ let agentAttr = '';+ if (state.chainId && state.agentId) {+ agentAttr = ` agent-id="onchain:${state.chainId}:${state.agentId}"`;+ } else {+ // Fallback: just use the GLB directly+ agentAttr = ` body="${state.avatarUrl}"`;+ }++ return `<agent-3d${agentAttr} src="${state.avatarUrl}" eager></agent-3d>+<script src="https://3dagent.vercel.app/dist-lib/agent-3d.umd.cjs"><\/script>`;+}++/**+ * Fire a custom event for analytics.+ */+function fireAnalytics(event, props = {}) {+ window.dispatchEvent(+ new CustomEvent('cz-demo-event', {+ detail: { event, props, timestamp: Date.now() },+ }),+ );+}++export { fireAnalytics };diff --git a/src/editor/regenerate-panel.js b/src/editor/regenerate-panel.jsnew file mode 100644index 000000000..6bd0901ba--- /dev/null+++ b/src/editor/regenerate-panel.js@@ -0,0 +1,284 @@+/**+ * RegeneratePanel — UI for avatar mesh/texture/rig regeneration.+ *+ * Usage:+ * import { mountRegeneratePanel } from './regenerate-panel.js';+ * const container = document.getElementById('regen-container');+ * mountRegeneratePanel(container, {+ * avatarId: 'uuid-...',+ * onResult: (newAvatarId) => { ... }+ * });+ *+ * Do NOT auto-mount. Caller controls where and when the panel appears.+ */++/**+ * Mount the regenerate panel into a DOM container.+ * @param {HTMLElement} container - Target container element+ * @param {Object} options+ * @param {string} options.avatarId - Avatar UUID to regenerate+ * @param {(resultId: string) => void} options.onResult - Callback on successful regen+ * @returns {Object} Control object with methods like .unmount()+ */+export function mountRegeneratePanel(container, { avatarId, onResult }) {+ const panel = new RegeneratePanel(container, { avatarId, onResult });+ panel.render();+ return panel;+}++class RegeneratePanel {+ constructor(container, { avatarId, onResult }) {+ this.container = container;+ this.avatarId = avatarId;+ this.onResult = onResult;+ this.state = {+ mode: 'remesh',+ params: '{}',+ inFlight: false,+ unconfigured: false,+ jobId: null,+ status: null,+ error: null,+ };+ this.pollTimer = null;+ }++ render() {+ this.container.innerHTML = '';+ this.container.style.padding = '16px';+ this.container.style.borderTop = '1px solid #ccc';+ this.container.style.marginTop = '16px';++ const wrapper = document.createElement('div');+ wrapper.innerHTML = `+ <h3 style="margin: 0 0 12px 0; font-size: 14px; font-weight: 600;">+ Regenerate Avatar+ </h3>+ `;+ this.container.appendChild(wrapper);++ // Render unconfigured banner if needed+ if (this.state.unconfigured) {+ this._renderUnconfiguredBanner();+ return;+ }++ // Mode select+ const modeLabel = document.createElement('label');+ modeLabel.style.display = 'block';+ modeLabel.style.marginBottom = '8px';+ modeLabel.style.fontSize = '12px';+ modeLabel.style.fontWeight = '500';+ modeLabel.textContent = 'Mode';+ this.container.appendChild(modeLabel);++ const modeSelect = document.createElement('select');+ modeSelect.value = this.state.mode;+ modeSelect.style.width = '100%';+ modeSelect.style.padding = '6px';+ modeSelect.style.marginBottom = '12px';+ modeSelect.style.borderRadius = '4px';+ modeSelect.style.border = '1px solid #ccc';+ modeSelect.innerHTML = `+ <option value="remesh">Re-mesh (regenerate topology)</option>+ <option value="retex">Re-texture (materials + textures)</option>+ <option value="rerig">Re-rig (skeleton binding)</option>+ <option value="restyle">Re-style (appearance from description)</option>+ `;+ modeSelect.addEventListener('change', (e) => {+ this.state.mode = e.target.value;+ });+ this.container.appendChild(modeSelect);++ // Params textarea+ const paramsLabel = document.createElement('label');+ paramsLabel.style.display = 'block';+ paramsLabel.style.marginBottom = '8px';+ paramsLabel.style.fontSize = '12px';+ paramsLabel.style.fontWeight = '500';+ paramsLabel.textContent = 'Parameters (JSON)';+ this.container.appendChild(paramsLabel);++ const paramsTextarea = document.createElement('textarea');+ paramsTextarea.value = this.state.params;+ paramsTextarea.style.width = '100%';+ paramsTextarea.style.height = '100px';+ paramsTextarea.style.padding = '6px';+ paramsTextarea.style.marginBottom = '12px';+ paramsTextarea.style.borderRadius = '4px';+ paramsTextarea.style.border = '1px solid #ccc';+ paramsTextarea.style.fontFamily = 'monospace';+ paramsTextarea.style.fontSize = '11px';+ paramsTextarea.addEventListener('change', (e) => {+ this.state.params = e.target.value;+ });+ this.container.appendChild(paramsTextarea);++ // Submit button+ const submitBtn = document.createElement('button');+ submitBtn.textContent = 'Start Regeneration';+ submitBtn.style.padding = '8px 16px';+ submitBtn.style.borderRadius = '4px';+ submitBtn.style.border = 'none';+ submitBtn.style.background = '#0066ff';+ submitBtn.style.color = 'white';+ submitBtn.style.cursor = this.state.inFlight ? 'not-allowed' : 'pointer';+ submitBtn.style.opacity = this.state.inFlight ? '0.6' : '1';+ submitBtn.disabled = this.state.inFlight;+ submitBtn.addEventListener('click', () => this._submit());+ this.container.appendChild(submitBtn);++ // Status / error display+ if (this.state.error) {+ const errorDiv = document.createElement('div');+ errorDiv.style.marginTop = '12px';+ errorDiv.style.padding = '8px';+ errorDiv.style.backgroundColor = '#fee';+ errorDiv.style.color = '#c00';+ errorDiv.style.borderRadius = '4px';+ errorDiv.style.fontSize = '12px';+ errorDiv.textContent = this.state.error;+ this.container.appendChild(errorDiv);+ }++ if (this.state.jobId) {+ const statusDiv = document.createElement('div');+ statusDiv.style.marginTop = '12px';+ statusDiv.style.padding = '8px';+ statusDiv.style.backgroundColor = '#eef';+ statusDiv.style.color = '#006';+ statusDiv.style.borderRadius = '4px';+ statusDiv.style.fontSize = '12px';+ statusDiv.innerHTML = `+ <strong>Job:</strong> ${this.state.jobId}<br/>+ <strong>Status:</strong> ${this.state.status || 'pending'}+ `;+ this.container.appendChild(statusDiv);+ }+ }++ _renderUnconfiguredBanner() {+ const banner = document.createElement('div');+ banner.style.padding = '12px';+ banner.style.backgroundColor = '#fef3cd';+ banner.style.border = '1px solid #ffeaa7';+ banner.style.borderRadius = '4px';+ banner.style.fontSize = '13px';+ banner.style.color = '#856404';+ banner.innerHTML = `+ <strong>Avatar regeneration is not yet live.</strong>+ Join the waitlist: <a href="mailto:[email protected]" style="color: #0066ff;">[email protected]</a><br/>+ <small style="display: block; margin-top: 6px;">+ ML backend integration is in progress. We'll notify you when it's ready.+ </small>+ `;+ this.container.appendChild(banner);+ }++ async _submit() {+ if (this.state.inFlight) return;++ // Validate JSON+ let params;+ try {+ params = JSON.parse(this.state.params);+ } catch (e) {+ this.state.error = `Invalid JSON in params: ${e.message}`;+ this.render();+ return;+ }++ this.state.inFlight = true;+ this.state.error = null;+ this.render();++ try {+ const resp = await fetch('/api/avatars/regenerate', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({+ sourceAvatarId: this.avatarId,+ mode: this.state.mode,+ params,+ }),+ });++ if (!resp.ok) {+ const body = await resp.json();++ // Handle 501 unconfigured case+ if (resp.status === 501 && body.error === 'regen_unconfigured') {+ this.state.unconfigured = true;+ this.state.inFlight = false;+ this.render();+ return;+ }++ throw new Error(body.error_description || `HTTP ${resp.status}`);+ }++ const body = await resp.json();+ this.state.jobId = body.jobId;+ this.state.status = body.status;+ this.state.inFlight = false;+ this.render();++ // Start polling for completion+ this._startPolling();+ } catch (err) {+ this.state.error = err.message;+ this.state.inFlight = false;+ this.render();+ }+ }++ _startPolling() {+ this.pollTimer = setInterval(async () => {+ try {+ const resp = await fetch(+ `/api/avatars/regenerate-status?jobId=${this.state.jobId}`,+ {+ credentials: 'include',+ },+ );++ if (!resp.ok) {+ throw new Error(`HTTP ${resp.status}`);+ }++ const body = await resp.json();+ this.state.status = body.status;++ if (body.error) {+ this.state.error = body.error;+ }++ this.render();++ // Terminal state — stop polling+ if (body.status === 'done' || body.status === 'failed') {+ clearInterval(this.pollTimer);+ this.pollTimer = null;++ if (body.status === 'done' && body.resultAvatarId && this.onResult) {+ this.onResult(body.resultAvatarId);+ }+ }+ } catch (err) {+ this.state.error = err.message;+ this.render();+ clearInterval(this.pollTimer);+ this.pollTimer = null;+ }+ }, 3000);+ }++ unmount() {+ if (this.pollTimer) {+ clearInterval(this.pollTimer);+ this.pollTimer = null;+ }+ this.container.innerHTML = '';+ }+}diff --git a/src/erc8004/hydrate.js b/src/erc8004/hydrate.jsnew file mode 100644index 000000000..af3ba5424--- /dev/null+++ b/src/erc8004/hydrate.js@@ -0,0 +1,45 @@+/**+ * Client-side agent hydrator.+ * Fetches agents from /api/erc8004/hydrate and /api/erc8004/import.+ */++/**+ * Fetch discovered agents owned by the user's linked wallets.+ * @returns {Promise<Array<{ chainId, agentId, name, description, image, glbUrl, owner, alreadyImported }>>}+ */+export async function fetchDiscoveredAgents() {+ const res = await fetch('/api/erc8004/hydrate', {+ method: 'GET',+ credentials: 'include',+ });++ if (!res.ok) {+ const error = await res.json().catch(() => ({}));+ throw new Error(error.error_description || `HTTP ${res.status}`);+ }++ const data = await res.json();+ return data.agents || [];+}++/**+ * Import an on-chain agent.+ * @param {{ chainId: number, agentId: string }} agent+ * @returns {Promise<{ id, erc8004_agent_id, erc8004_agent_id_chain_id, name, avatar_url }>}+ */+export async function importAgent({ chainId, agentId }) {+ const res = await fetch('/api/erc8004/import', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ chainId, agentId }),+ });++ if (!res.ok) {+ const error = await res.json().catch(() => ({}));+ throw new Error(error.error_description || `HTTP ${res.status}`);+ }++ const data = await res.json();+ return data.agent;+}diff --git a/src/reputation-page.js b/src/reputation-page.jsnew file mode 100644index 000000000..35951a4f6--- /dev/null+++ b/src/reputation-page.js@@ -0,0 +1,10 @@+/**+ * Reputation page entry point for Vite bundling.+ * Exports the main reputation page logic.+ */++import { getReputation, getRecentReviews, submitReputation } from './erc8004/reputation.js';+import { JsonRpcProvider, BrowserProvider } from 'ethers';+import { REGISTRY_DEPLOYMENTS } from './erc8004/abi.js';++export { getReputation, getRecentReviews, submitReputation, JsonRpcProvider, BrowserProvider, REGISTRY_DEPLOYMENTS };diff --git a/src/reputation-ui.js b/src/reputation-ui.jsnew file mode 100644index 000000000..e5b9a750b--- /dev/null+++ b/src/reputation-ui.js@@ -0,0 +1,494 @@+/**+ * ReputationDashboard — UI controller for on-chain agent reviews.+ *+ * Fetches reputation data (aggregated stats + recent reviews) from the ERC-8004+ * Reputation Registry, renders them into a container, and handles wallet-gated+ * review submissions with optimistic updates.+ */++import { JsonRpcProvider } from 'ethers';+import { getReputation, getRecentReviews, submitReputation } from './erc8004/reputation.js';+import { connectWallet } from './erc8004/agent-registry.js';+import { REGISTRY_DEPLOYMENTS } from './erc8004/abi.js';++const CHAIN_NAMES = {+ 1: 'Ethereum',+ 10: 'Optimism',+ 56: 'BSC',+ 100: 'Gnosis',+ 137: 'Polygon',+ 250: 'Fantom',+ 324: 'zkSync Era',+ 1284: 'Moonbeam',+ 5000: 'Mantle',+ 8453: 'Base',+ 42161: 'Arbitrum One',+ 42220: 'Celo',+ 43114: 'Avalanche',+ 59144: 'Linea',+ 534352: 'Scroll',+ 97: 'BSC Testnet',+ 11155111: 'Ethereum Sepolia',+ 84532: 'Base Sepolia',+ 421614: 'Arbitrum Sepolia',+ 11155420: 'Optimism Sepolia',+ 80002: 'Polygon Amoy',+ 43113: 'Avalanche Fuji',+};++function getExplorerUrl(chainId, txHash) {+ const base = {+ 1: 'https://etherscan.io',+ 10: 'https://optimistic.etherscan.io',+ 56: 'https://bscscan.com',+ 100: 'https://gnosisscan.io',+ 137: 'https://polygonscan.com',+ 250: 'https://ftmscan.com',+ 324: 'https://explorer.zksync.io',+ 1284: 'https://moonscan.io',+ 5000: 'https://explorer.mantle.xyz',+ 8453: 'https://basescan.org',+ 42161: 'https://arbiscan.io',+ 42220: 'https://celoscan.io',+ 43114: 'https://snowtrace.io',+ 59144: 'https://lineascan.build',+ 534352: 'https://scrollscan.com',+ 97: 'https://testnet.bscscan.com',+ 11155111: 'https://sepolia.etherscan.io',+ 84532: 'https://sepolia.basescan.org',+ 421614: 'https://sepolia.arbiscan.io',+ 11155420: 'https://sepolia-optimism.etherscan.io',+ 80002: 'https://amoy.polygonscan.com',+ 43113: 'https://testnet.snowtrace.io',+ }[chainId];++ if (!base) return null;+ return `${base}/tx/${txHash}`;+}++export class ReputationDashboard {+ constructor(container, { agentId, chainId = 84532 }) {+ this.container = container;+ this.agentId = agentId;+ this.chainId = chainId;+ this.reviews = [];+ this.reputation = { total: 0, count: 0, average: 0 };+ this.connectedAddress = null;+ this.reviewListeners = [];+ this.pollInterval = null;+ this.lastTxHash = null;+ }++ /**+ * Load reputation data and render.+ */+ async load() {+ try {+ await this._fetchReputation();+ this._render();+ } catch (err) {+ console.error('[ReputationDashboard] load failed:', err);+ this._renderError(err);+ }+ }++ /**+ * Fetch getReputation + getRecentReviews using ethers.js provider.+ */+ async _fetchReputation() {+ if (!REGISTRY_DEPLOYMENTS[this.chainId]) {+ throw new Error(`Chain ${this.chainId} is not supported.`);+ }++ // Pick an RPC URL per chain.+ const rpcUrl = this._getRpcUrl(this.chainId);+ const provider = new JsonRpcProvider(rpcUrl);++ const reputation = await getReputation({+ agentId: this.agentId,+ runner: provider,+ chainId: this.chainId,+ });++ const reviews = await getRecentReviews({+ agentId: this.agentId,+ runner: provider,+ chainId: this.chainId,+ fromBlock: 0,+ });++ this.reputation = reputation;+ this.reviews = reviews.sort((a, b) => b.blockNumber - a.blockNumber);+ }++ _getRpcUrl(chainId) {+ const rpcMap = {+ 1: 'https://eth.llamarpc.com',+ 10: 'https://optimism.llamarpc.com',+ 56: 'https://bsc.llamarpc.com',+ 100: 'https://gnosischain.publicnode.com',+ 137: 'https://polygon.llamarpc.com',+ 250: 'https://fantom.publicnode.com',+ 324: 'https://zksync.publicnode.com',+ 1284: 'https://moonbeam.publicnode.com',+ 5000: 'https://mantle.publicnode.com',+ 8453: 'https://base.llamarpc.com',+ 42161: 'https://arbitrum.llamarpc.com',+ 42220: 'https://celo.publicnode.com',+ 43114: 'https://avalanche.publicnode.com',+ 59144: 'https://linea.publicnode.com',+ 534352: 'https://scroll.publicnode.com',+ 97: 'https://bsc-testnet.publicnode.com',+ 11155111: 'https://ethereum-sepolia.publicnode.com',+ 84532: 'https://base-sepolia.publicnode.com',+ 421614: 'https://arbitrum-sepolia.publicnode.com',+ 11155420: 'https://optimism-sepolia.publicnode.com',+ 80002: 'https://polygon-amoy.publicnode.com',+ 43113: 'https://avalanche-fuji.publicnode.com',+ };+ return rpcMap[chainId] || 'https://eth.llamarpc.com';+ }++ /**+ * Submit a reputation review.+ */+ async submit({ rating, comment }) {+ if (!Number.isInteger(rating) || rating < 1 || rating > 5) {+ throw new Error('Rating must be 1-5.');+ }++ try {+ const walletInfo = await connectWallet();+ this.connectedAddress = walletInfo.address;++ const txHash = await submitReputation({+ agentId: this.agentId,+ score: rating,+ comment,+ signer: walletInfo.signer,+ chainId: this.chainId,+ });++ this.lastTxHash = txHash;++ // Optimistically add review to list (marked as pending).+ const optimisticReview = {+ agentId: this.agentId,+ from: this.connectedAddress,+ score: rating,+ comment,+ blockNumber: -1, // Pending marker+ txHash,+ pending: true,+ };+ this.reviews.unshift(optimisticReview);++ // Notify listeners+ this.reviewListeners.forEach((fn) => fn(optimisticReview));++ // Start polling to replace pending with confirmed+ this._startPolling();++ return txHash;+ } catch (err) {+ if (err.code === 'ACTION_REJECTED' || err.message.includes('user rejected')) {+ throw new Error('Transaction rejected.');+ }+ throw err;+ }+ }++ _startPolling() {+ if (this.pollInterval) return;+ this.pollInterval = setInterval(() => this._pollForConfirmation(), 5000);+ setTimeout(() => this._stopPolling(), 120000); // Stop after 2 minutes+ }++ _stopPolling() {+ if (this.pollInterval) {+ clearInterval(this.pollInterval);+ this.pollInterval = null;+ }+ }++ async _pollForConfirmation() {+ try {+ const rpcUrl = this._getRpcUrl(this.chainId);+ const provider = new JsonRpcProvider(rpcUrl);++ const receipt = await provider.getTransactionReceipt(this.lastTxHash);+ if (receipt) {+ // Transaction confirmed; reload reviews.+ await this._fetchReputation();+ this._render();+ this._stopPolling();+ }+ } catch (err) {+ console.warn('[ReputationDashboard] poll failed:', err.message);+ }+ }++ onReviewAdded(fn) {+ this.reviewListeners.push(fn);+ }++ _render() {+ this.container.innerHTML = '';+ this.container.appendChild(this._createHeader());+ this.container.appendChild(this._createStatsRow());+ this.container.appendChild(this._createReviewList());+ this.container.appendChild(this._createSubmitForm());+ }++ _renderError(err) {+ const errorMsg = err.message || String(err);+ this.container.innerHTML = `+ <div class="rep-error">+ <h3>Unable to load reputation</h3>+ <p>${this._escapeHtml(errorMsg)}</p>+ <button onclick="location.reload()">Retry</button>+ </div>+ `;+ }++ _createHeader() {+ const div = document.createElement('div');+ div.className = 'rep-header';++ const chainName = CHAIN_NAMES[this.chainId] || `Chain ${this.chainId}`;+ const agentDisplay = `${chainName} • Agent #${this.agentId}`;++ div.innerHTML = `+ <div class="rep-header-content">+ <h1>Agent Reputation</h1>+ <p class="rep-header-meta">${agentDisplay}</p>+ </div>+ `;++ return div;+ }++ _createStatsRow() {+ const div = document.createElement('div');+ div.className = 'rep-stats';++ const lastReviewTime = this._getLastReviewTime();++ div.innerHTML = `+ <div class="rep-stat">+ <span class="rep-stat-label">Reviews</span>+ <span class="rep-stat-value">${this.reputation.count}</span>+ </div>+ <div class="rep-stat">+ <span class="rep-stat-label">Rating</span>+ <span class="rep-stat-value">${this.reputation.average.toFixed(1)}</span>+ </div>+ <div class="rep-stat">+ <span class="rep-stat-label">Last Review</span>+ <span class="rep-stat-value">${lastReviewTime}</span>+ </div>+ `;++ return div;+ }++ _getLastReviewTime() {+ if (this.reviews.length === 0) return '—';+ const blockNum = this.reviews[0].blockNumber;+ if (blockNum < 0) return 'Just now';+ // Approximate: 12s per block+ const secondsAgo = Math.round(Date.now() / 1000) - Math.round(blockNum * 12);+ return this._formatTimeAgo(secondsAgo);+ }++ _formatTimeAgo(seconds) {+ if (seconds < 60) return 'just now';+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;+ if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;+ return `${Math.floor(seconds / 86400)}d ago`;+ }++ _createReviewList() {+ const div = document.createElement('div');+ div.className = 'rep-reviews';++ if (this.reviews.length === 0) {+ div.innerHTML = '<p class="rep-empty">No reviews yet. Be the first!</p>';+ return div;+ }++ const title = document.createElement('h3');+ title.textContent = 'Reviews';+ div.appendChild(title);++ const list = document.createElement('div');+ list.className = 'rep-review-list';++ this.reviews.slice(0, 10).forEach((review) => {+ list.appendChild(this._createReviewItem(review));+ });++ div.appendChild(list);++ if (this.reviews.length > 10) {+ const more = document.createElement('p');+ more.className = 'rep-more-reviews';+ more.textContent = `+${this.reviews.length - 10} more reviews`;+ div.appendChild(more);+ }++ return div;+ }++ _createReviewItem(review) {+ const div = document.createElement('div');+ div.className = `rep-review-item ${review.pending ? 'pending' : ''}`;++ const starHtml = this._renderStars(review.score);+ const explorerUrl = getExplorerUrl(this.chainId, review.txHash);+ const txLink = explorerUrl+ ? `<a href="${explorerUrl}" target="_blank" rel="noopener">View tx</a>`+ : `<span class="rep-tx-hash">${review.txHash.slice(0, 10)}…</span>`;++ div.innerHTML = `+ <div class="rep-review-header">+ <span class="rep-reviewer">${this._truncateAddress(review.from)}</span>+ <span class="rep-stars">${starHtml}</span>+ </div>+ ${review.comment ? `<p class="rep-comment">${this._escapeHtml(review.comment)}</p>` : ''}+ <div class="rep-review-footer">+ ${txLink}+ ${review.pending ? '<span class="rep-pending-badge">Pending</span>' : ''}+ </div>+ `;++ return div;+ }++ _renderStars(score) {+ const full = Math.floor(score);+ let html = '';+ for (let i = 0; i < 5; i++) {+ html += i < full ? '★' : '☆';+ }+ return html;+ }++ _truncateAddress(addr) {+ if (!addr) return 'Anonymous';+ return `${addr.slice(0, 6)}…${addr.slice(-4)}`;+ }++ _createSubmitForm() {+ const div = document.createElement('div');+ div.className = 'rep-submit-form';++ div.innerHTML = `+ <h3>Leave a Review</h3>+ <form id="rep-form">+ <div class="rep-form-group">+ <label>Rating</label>+ <div class="rep-stars-input">+ ${[1, 2, 3, 4, 5]+ .map(+ (n) => `+ <button+ type="button"+ class="rep-star-btn"+ data-rating="${n}"+ title="${n} star${n > 1 ? 's' : ''}"+ >★</button>+ `,+ )+ .join('')}+ </div>+ <input type="hidden" id="rep-rating" name="rating" value="" />+ </div>++ <div class="rep-form-group">+ <label for="rep-comment">Comment (optional)</label>+ <textarea+ id="rep-comment"+ name="comment"+ placeholder="Share your experience…"+ rows="4"+ maxlength="500"+ ></textarea>+ <small id="rep-char-count">0/500</small>+ </div>++ <button type="submit" class="rep-submit-btn">Submit Review</button>+ <small class="rep-form-hint">Connect wallet to submit</small>+ </form>+ `;++ const form = div.querySelector('#rep-form');+ const ratingInput = form.querySelector('#rep-rating');+ const commentInput = form.querySelector('#rep-comment');+ const charCount = form.querySelector('#rep-char-count');+ const starBtns = form.querySelectorAll('.rep-star-btn');+ let selectedRating = 0;++ starBtns.forEach((btn) => {+ btn.addEventListener('click', (e) => {+ e.preventDefault();+ selectedRating = Number(btn.dataset.rating);+ ratingInput.value = selectedRating;++ starBtns.forEach((b, i) => {+ b.classList.toggle('selected', i < selectedRating);+ });+ });+ });++ commentInput.addEventListener('input', () => {+ charCount.textContent = `${commentInput.value.length}/500`;+ });++ form.addEventListener('submit', async (e) => {+ e.preventDefault();++ if (!selectedRating) {+ alert('Please select a rating.');+ return;+ }++ const comment = commentInput.value.trim();+ const submitBtn = form.querySelector('button[type="submit"]');+ const originalText = submitBtn.textContent;++ try {+ submitBtn.disabled = true;+ submitBtn.textContent = 'Submitting…';++ await this.submit({ rating: selectedRating, comment });++ commentInput.value = '';+ charCount.textContent = '0/500';+ selectedRating = 0;+ ratingInput.value = '';+ starBtns.forEach((b) => b.classList.remove('selected'));++ submitBtn.textContent = 'Review submitted!';+ setTimeout(() => {+ submitBtn.textContent = originalText;+ submitBtn.disabled = false;+ }, 2000);++ this._render();+ } catch (err) {+ alert(`Error: ${err.message}`);+ submitBtn.textContent = originalText;+ submitBtn.disabled = false;+ }+ });++ return div;+ }++ _escapeHtml(text) {+ const div = document.createElement('div');+ div.textContent = text;+ return div.innerHTML;+ }+}diff --git a/src/validation-ui.js b/src/validation-ui.jsnew file mode 100644index 000000000..7cb3728af--- /dev/null+++ b/src/validation-ui.js@@ -0,0 +1,288 @@+/**+ * ValidationDashboard — UI controller for browsing and submitting validation records on-chain.+ *+ * Uses:+ * - getLatestValidation() to fetch past validation records+ * - recordValidation() to submit new reports+ * - hashReport() to compute client-side hash+ * - pinFile() for IPFS storage+ * - ethers for wallet connection+ */++import { connectWallet, getSigner } from './erc8004/agent-registry.js';+import { getLatestValidation, recordValidation, hashReport } from './erc8004/validation-recorder.js';+import { keccak256, toUtf8Bytes } from 'ethers';++export class ValidationDashboard {+ constructor(root, els) {+ this.root = root;+ this.els = els;+ this.currentAgentId = null;+ this.currentChainId = null;+ this.currentReport = null;+ this.currentReportHash = null;+ this.signer = null;++ this.setupEventListeners();+ }++ setupEventListeners() {+ this.els.loadBtn.addEventListener('click', () => this.loadRecords());+ this.els.submitBtn.addEventListener('click', () => this.openModal());+ this.els.reportFile.addEventListener('change', (e) => this.handleFileSelect(e));+ this.els.submitReportBtn.addEventListener('click', () => this.submitReport());++ document.addEventListener('dragover', (e) => {+ if (this.els.submitModal.classList.contains('open')) {+ e.preventDefault();+ }+ });++ document.addEventListener('drop', (e) => {+ if (this.els.submitModal.classList.contains('open')) {+ e.preventDefault();+ const files = e.dataTransfer.files;+ if (files.length > 0) {+ this.els.reportFile.files = files;+ this.handleFileSelect({ target: { files } });+ }+ }+ });+ }++ showError(msg) {+ this.els.errorEl.textContent = msg;+ this.els.errorEl.style.display = 'block';+ }++ hideError() {+ this.els.errorEl.style.display = 'none';+ }++ showInfo(msg) {+ this.els.infoEl.textContent = msg;+ this.els.infoEl.style.display = 'block';+ }++ hideInfo() {+ this.els.infoEl.style.display = 'none';+ }++ showToast(msg, isError = false) {+ const toast = document.createElement('div');+ toast.className = `toast ${isError ? 'err' : ''}`;+ toast.textContent = msg;+ document.body.appendChild(toast);+ setTimeout(() => toast.remove(), 3000);+ }++ async loadRecords() {+ this.hideError();+ this.hideInfo();++ const agentId = this.els.agentInput.value.trim();+ const chainId = this.els.chainInput.value.trim();++ if (!agentId || !chainId) {+ this.showError('Please enter both Agent ID and Chain ID');+ return;+ }++ this.currentAgentId = Number(agentId);+ this.currentChainId = Number(chainId);++ try {+ this.els.loadBtn.disabled = true;+ this.showInfo('Loading validation records...');++ const result = await getLatestValidation({+ agentId: this.currentAgentId,+ runner: null,+ chainId: this.currentChainId,+ });++ this.hideInfo();+ this.renderRecords(result);+ } catch (err) {+ this.showError(`Failed to load records: ${err.message}`);+ this.els.recordsContainer.innerHTML = '';+ this.els.emptyState.style.display = 'block';+ } finally {+ this.els.loadBtn.disabled = false;+ }+ }++ renderRecords(records) {+ if (!records || (Array.isArray(records) && records.length === 0)) {+ this.els.recordsContainer.innerHTML = '';+ this.els.emptyState.style.display = 'block';+ return;+ }++ this.els.emptyState.style.display = 'none';+ const recordArray = Array.isArray(records) ? records : [records];++ this.els.recordsContainer.innerHTML = recordArray+ .map((r) => this.renderRecord(r))+ .join('');+ }++ renderRecord(record) {+ const verdict = record.verdict || (record.passed ? 'pass' : 'fail');+ const timestamp = record.timestamp+ ? new Date(Number(record.timestamp) * 1000).toLocaleString()+ : 'Unknown';++ const reportUri = record.reportUri || record.proofURI || '';+ const reportHash = record.reportHash || record.proofHash || '';+ const validator = record.validator || 'Unknown';++ return `+ <div class="record">+ <div class="record-header">+ <div class="record-title">+ <h3>${this.escapeHtml(record.kind || 'glb-schema')} Validation</h3>+ <span class="badge ${verdict}">${verdict.toUpperCase()}</span>+ </div>+ </div>+ <div class="record-meta">+ <div class="record-meta-item">+ <div class="record-meta-label">Validator</div>+ <div class="record-meta-value">${this.escapeHtml(validator.substring(0, 10))}…${this.escapeHtml(validator.substring(validator.length - 8))}</div>+ </div>+ <div class="record-meta-item">+ <div class="record-meta-label">Timestamp</div>+ <div class="record-meta-value">${timestamp}</div>+ </div>+ </div>+ <div class="record-meta">+ <div class="record-meta-item" style="flex: 1">+ <div class="record-meta-label">Report Hash</div>+ <div class="record-meta-value">${this.escapeHtml(reportHash.substring(0, 20))}…</div>+ </div>+ </div>+ <div class="record-actions">+ ${reportUri ? `<a href="${this.resolveIPFS(reportUri)}" target="_blank" class="btn">View Report ↗</a>` : ''}+ <button class="btn sec" onclick="navigator.clipboard.writeText('${this.escapeHtml(reportHash)}').then(() => alert('Copied!'))">Copy Hash</button>+ </div>+ </div>+ `;+ }++ openModal() {+ this.els.submitModal.classList.add('open');+ this.currentReport = null;+ this.currentReportHash = null;+ this.els.previewSection.style.display = 'none';+ this.els.hashSection.style.display = 'none';+ this.els.reportFile.value = '';+ this.els.fileStatus.textContent = '';+ this.els.submitReportBtn.disabled = true;+ }++ closeModal() {+ this.els.submitModal.classList.remove('open');+ }++ async handleFileSelect(e) {+ const file = e.target.files?.[0];+ if (!file) {+ this.els.fileStatus.textContent = '';+ this.els.previewSection.style.display = 'none';+ this.els.hashSection.style.display = 'none';+ this.els.submitReportBtn.disabled = true;+ return;+ }++ try {+ const text = await file.text();+ const report = JSON.parse(text);++ this.currentReport = report;+ this.currentReportHash = hashReport(report);++ this.els.fileStatus.textContent = `✓ ${file.name} (${(file.size / 1024).toFixed(1)} KB)`;+ this.els.fileStatus.style.color = '#76d776';++ this.els.previewJson.textContent = JSON.stringify(report, null, 2);+ this.els.previewSection.style.display = 'block';+ this.els.previewError.style.display = 'none';++ this.els.reportHash.value = this.currentReportHash;+ this.els.hashSection.style.display = 'block';++ this.els.submitReportBtn.disabled = false;+ } catch (err) {+ this.els.fileStatus.textContent = '✗ Invalid JSON';+ this.els.fileStatus.style.color = '#ffb3b3';+ this.els.previewError.textContent = err.message;+ this.els.previewError.style.display = 'block';+ this.els.submitReportBtn.disabled = true;+ this.currentReport = null;+ this.currentReportHash = null;+ }+ }++ async submitReport() {+ if (!this.currentReport || !this.currentReportHash) {+ this.showToast('No valid report selected', true);+ return;+ }++ if (!this.currentAgentId || !this.currentChainId) {+ this.showToast('Please load records first to set agent ID and chain', true);+ return;+ }++ try {+ this.els.submitReportBtn.disabled = true;+ this.showToast('Connecting wallet...');++ const wallet = await connectWallet();+ const signer = wallet.signer;++ this.showToast('Submitting validation record on-chain...');++ const result = await recordValidation({+ agentId: this.currentAgentId,+ report: this.currentReport,+ signer,+ chainId: this.currentChainId,+ apiToken: import.meta.env.VITE_IPFS_API_TOKEN,+ pin: true,+ });++ this.showToast(+ `✓ Validation submitted! TX: ${result.txHash.substring(0, 10)}...`,+ false,+ );++ this.closeModal();++ await new Promise((r) => setTimeout(r, 2000));+ await this.loadRecords();+ } catch (err) {+ this.showToast(`Error: ${err.message}`, true);+ this.els.submitReportBtn.disabled = false;+ }+ }++ resolveIPFS(uri) {+ if (uri?.startsWith('ipfs://')) {+ const cid = uri.slice(7);+ return `https://dweb.link/ipfs/${cid}`;+ }+ return uri;+ }++ escapeHtml(str) {+ const map = {+ '&': '&',+ '<': '<',+ '>': '>',+ '"': '"',+ "'": ''',+ };+ return str.replace(/[&<>"']/g, (m) => map[m]);+ }+}diff --git a/vercel.json b/vercel.jsonindex 340dd7173..7baf0f61e 100644--- a/vercel.json+++ b/vercel.json@@ -22,6 +22,7 @@{ "src": "/oauth/introspect", "dest": "/api/oauth/introspect" },{ "src": "/login", "dest": "/public/login.html" },+ { "src": "/wallet-login.js", "dest": "/wallet-login.js" },{ "src": "/deploy", "dest": "/app.html" },{ "src": "/dashboard", "dest": "/public/dashboard/index.html" },{ "src": "/dashboard/", "dest": "/public/dashboard/index.html" },@@ -71,6 +72,18 @@{ "src": "/widgets/(.*)", "dest": "/public/widgets-gallery/$1" },{ "src": "/docs/widgets", "dest": "/public/docs-widgets.html" },+ { "src": "/artifact", "dest": "/public/artifact/index.html" },+ { "src": "/artifact/", "dest": "/public/artifact/index.html" },+ { "src": "/artifact/(.*)", "dest": "/public/artifact/$1" },++ { "src": "/cz", "dest": "/public/cz/index.html" },+ { "src": "/cz/", "dest": "/public/cz/index.html" },+ { "src": "/cz/(.*)", "dest": "/public/cz/$1" },++ { "src": "/validation", "dest": "/public/validation/index.html" },+ { "src": "/validation/", "dest": "/public/validation/index.html" },+ { "src": "/validation/(.*)", "dest": "/public/validation/$1" },+{ "src": "/api/llm/anthropic", "dest": "/api/llm/anthropic.js" },{ "src": "/api/agents/([^/]+)/usage", "dest": "/api/agents/[id]/usage?id=$1" },{ "src": "/dashboard/usage", "dest": "/public/dashboard/usage.html" },diff --git a/vite.config.artifact.js b/vite.config.artifact.jsnew file mode 100644index 000000000..e670671fc--- /dev/null+++ b/vite.config.artifact.js@@ -0,0 +1,24 @@+import { defineConfig } from 'vite';+import { resolve } from 'path';++// Artifact bundle build — lightweight IIFE that loads three.js from CDN+export default defineConfig({+ build: {+ outDir: 'dist-artifact',+ emptyOutDir: true,+ lib: {+ entry: resolve(__dirname, 'src/artifact/entry.js'),+ name: 'Agent3DArtifact',+ formats: ['iife'],+ fileName: () => 'artifact.js',+ },+ rollupOptions: {+ output: {+ inlineDynamicImports: false,+ },+ },+ minify: 'terser',+ target: 'ES2020',+ chunkSizeWarningLimit: 500,+ },+});diff --git a/vite.config.js b/vite.config.jsindex f324f5d58..2c24dc8f3 100644--- a/vite.config.js+++ b/vite.config.js@@ -33,6 +33,7 @@ const appConfig = {'agent-edit': resolve(__dirname, 'agent-edit.html'),'agent-embed': resolve(__dirname, 'agent-embed.html'),'a-embed': resolve(__dirname, 'a-embed.html'),+ reputation: resolve(__dirname, 'public/reputation/index.html'),},},},@@ -47,12 +48,20 @@ const appConfig = {'/deploy': resolve(root, 'app.html'),'/explore': resolve(root, 'public/explore/index.html'),'/explore/': resolve(root, 'public/explore/index.html'),+ '/agents': resolve(root, 'public/agents/index.html'),+ '/agents/': resolve(root, 'public/agents/index.html'),'/features': resolve(root, 'features.html'),'/create': resolve(root, 'create.html'),'/dashboard': resolve(root, 'public/dashboard/index.html'),'/studio': resolve(root, 'public/studio/index.html'),'/widgets': resolve(root, 'public/widgets-gallery/index.html'),'/docs/widgets': resolve(root, 'public/docs-widgets.html'),+ '/cz': resolve(root, 'public/cz/index.html'),+ '/cz/': resolve(root, 'public/cz/index.html'),+ '/validation': resolve(root, 'public/validation/index.html'),+ '/validation/': resolve(root, 'public/validation/index.html'),+ '/reputation': resolve(root, 'public/reputation/index.html'),+ '/reputation/': resolve(root, 'public/reputation/index.html'),'/agent': resolve(root, 'agent-home.html'),};server.middlewares.use(async (req, res, next) => {