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
milday
nirholas65f9a0448bd1
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex 44377f754..4c49e403f 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -96,6 +96,8 @@ export const limits = {pinUser: (userId) => getLimiter('pin:user', { limit: 30, window: '1 h' }).limit(userId),pinStatusIp: (ip) => getLimiter('pin:status:ip', { limit: 60, window: '1 m' }).limit(ip),agentByAddress: (ip) => getLimiter('agents:by-address', { limit: 120, window: '1 m' }).limit(ip),+ walletLink: (userId) => getLimiter('wallet:link', { limit: 10, window: '10 m' }).limit(userId),+ agentSuggest: (ip) => getLimiter('agents:suggest', { limit: 120, window: '1 m' }).limit(ip),};// Trust only proxy headers that Vercel itself sets and signs. Naively readingdiff --git a/api/_lib/siwe.js b/api/_lib/siwe.jsnew file mode 100644index 000000000..8f9c2189c--- /dev/null+++ b/api/_lib/siwe.js@@ -0,0 +1,52 @@+// Shared EIP-4361 (SIWE) message parser.+// verify.js has its own copy — do not delete that one until it imports from here.++export function parseSiweMessage(msg) {+ const lines = msg.split('\n');+ if (lines.length < 6) return null;++ const header = lines[0];+ const m = /^([^\s]+) wants you to sign in with your Ethereum account:$/.exec(header);+ if (!m) return null;+ const domain = m[1];++ const address = (lines[1] || '').trim();+ if (!/^0x[a-fA-F0-9]{40}$/.test(address)) return null;++ const out = { domain, address };+ for (let i = 2; i < lines.length; i++) {+ const line = lines[i];+ const kv = /^([A-Za-z -]+):\s*(.*)$/.exec(line);+ if (!kv) continue;+ const key = kv[1].trim();+ const val = kv[2].trim();+ switch (key) {+ case 'URI':+ out.uri = val;+ break;+ case 'Version':+ out.version = val;+ break;+ case 'Chain ID':+ out.chainId = parseInt(val, 10) || null;+ break;+ case 'Nonce':+ out.nonce = val;+ break;+ case 'Issued At':+ out.issuedAt = val;+ break;+ case 'Expiration Time':+ out.expirationTime = val;+ break;+ case 'Not Before':+ out.notBefore = val;+ break;+ case 'Request ID':+ out.requestId = val;+ break;+ }+ }+ if (!out.uri || !out.nonce || !out.version) return null;+ return out;+}diff --git a/api/agents/by-address/[addr].js b/api/agents/by-address/[addr].jsindex fad0d4cff..43c78a5e9 100644--- a/api/agents/by-address/[addr].js+++ b/api/agents/by-address/[addr].js@@ -69,7 +69,9 @@ async function queryChain(addr, chainId, meta) {const agentIds = await Promise.all(Array.from({ length: count }, (_, i) =>- withTimeout(registry.tokenOfOwnerByIndex(addr, BigInt(i)), RPC_TIMEOUT).catch(() => null),+ withTimeout(registry.tokenOfOwnerByIndex(addr, BigInt(i)), RPC_TIMEOUT).catch(+ () => null,+ ),),);@@ -102,7 +104,7 @@ export default wrap(async (req, res) => {const rl = await limits.agentByAddress(clientIp(req));if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');- const raw = ((req.query?.addr) || '').trim().toLowerCase();+ const raw = (req.query?.addr || '').trim().toLowerCase();if (!/^0x[a-f0-9]{40}$/.test(raw)) {return error(res, 400, 'validation_error', 'invalid wallet address');}diff --git a/api/agents/suggest.js b/api/agents/suggest.jsnew file mode 100644index 000000000..c83b23dec--- /dev/null+++ b/api/agents/suggest.js@@ -0,0 +1,60 @@+// GET /api/agents/suggest?q=<query>[&limit=<n>]+// Public autocomplete for @-mention surfaces. Returns ranked agents matching q.++import { sql } from '../_lib/db.js';+import { publicUrl } from '../_lib/r2.js';+import { cors, json, method, wrap, error } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';++const Q_RE = /[^a-zA-Z0-9_-]/g;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.agentSuggest(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const url = new URL(req.url, 'http://x');+ const raw = (url.searchParams.get('q') || '').trim();+ const q = raw.replace(Q_RE, '').slice(0, 32);++ if (!q) return json(res, 200, { agents: [] }, { 'cache-control': 'public, max-age=60' });++ const limitParam = parseInt(url.searchParams.get('limit') || '8', 10);+ const lim = Math.min(20, Math.max(1, Number.isFinite(limitParam) ? limitParam : 8));++ // Rank: 0 = exact, 1 = name prefix, 2 = ILIKE fuzzy.+ // No slug column exists; name is used for both name and slug ranking tiers.+ // No private/hidden columns exist; deleted_at IS NULL is the only exclusion.+ const rows = await sql`+ SELECT+ ai.id,+ ai.name,+ ai.chain_id,+ ai.erc8004_agent_id,+ av.thumbnail_key,+ CASE+ WHEN lower(ai.name) = lower(${q}) THEN 0+ WHEN lower(ai.name) LIKE lower(${q}) || '%' THEN 1+ ELSE 2+ END AS rank+ FROM agent_identities ai+ LEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULL+ WHERE ai.deleted_at IS NULL+ AND lower(ai.name) LIKE '%' || lower(${q}) || '%'+ ORDER BY rank, ai.name+ LIMIT ${lim}+ `;++ const agents = rows.map((r) => ({+ id: r.id,+ name: r.name,+ slug: r.name.toLowerCase().replace(/[^a-z0-9-]/g, '-'),+ thumbnailUrl: r.thumbnail_key ? publicUrl(r.thumbnail_key) : null,+ ...(r.chain_id != null ? { chainId: r.chain_id } : {}),+ onChain: r.erc8004_agent_id != null,+ }));++ return json(res, 200, { agents }, { 'cache-control': 'public, max-age=60' });+});diff --git a/api/auth/wallet/link.js b/api/auth/wallet/link.jsnew file mode 100644index 000000000..e1d7d24db--- /dev/null+++ b/api/auth/wallet/link.js@@ -0,0 +1,123 @@+// Link a wallet to an existing session-authenticated account via SIWE.++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 { limits, clientIp } from '../../_lib/rate-limit.js';+import { env } from '../../_lib/env.js';+import { parse } from '../../_lib/validate.js';+import { parseSiweMessage } from '../../_lib/siwe.js';++const bodySchema = z.object({+ message: z.string().min(64).max(4000),+ signature: z.string().regex(/^0x[a-fA-F0-9]+$/),+});++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ const rl = await limits.walletLink(String(user.id));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many attempts');++ const body = parse(bodySchema, await readJson(req));++ // 1. Parse the SIWE message.+ const fields = parseSiweMessage(body.message);+ if (!fields) return error(res, 400, 'invalid_message', 'malformed SIWE message');++ // 2. Domain + URI must match this deployment (replay protection).+ const appOrigin = env.APP_ORIGIN;+ const appHost = new URL(appOrigin).host;+ const vercelHost = process.env.VERCEL_URL || null;+ const allowedHosts = new Set([appHost, vercelHost].filter(Boolean));+ if (!allowedHosts.has(fields.domain)) {+ return error(res, 400, 'invalid_domain', `domain must be ${appHost}`);+ }+ try {+ const u = new URL(fields.uri);+ const allowedOrigins = new Set(+ [appOrigin, vercelHost ? `https://${vercelHost}` : null].filter(Boolean),+ );+ if (!allowedOrigins.has(u.origin))+ return error(res, 400, 'invalid_uri', 'uri origin mismatch');+ } catch {+ return error(res, 400, 'invalid_uri', 'uri not a valid URL');+ }++ // 3. Temporal checks.+ const now = Date.now();+ if (fields.expirationTime && Date.parse(fields.expirationTime) < now) {+ return error(res, 400, 'expired', 'message expired');+ }+ if (fields.notBefore && Date.parse(fields.notBefore) > now) {+ return error(res, 400, 'not_yet_valid', 'message not yet valid');+ }++ // 4. Nonce: must exist, be unconsumed, and not expired. Burn on success.+ const [nonceRow] = await sql`+ select nonce, expires_at, consumed_at+ from siwe_nonces+ where nonce = ${fields.nonce}+ limit 1+ `;+ if (!nonceRow) return error(res, 400, 'invalid_nonce', 'unknown nonce');+ if (nonceRow.consumed_at) return error(res, 400, 'nonce_reused', 'nonce already used');+ if (new Date(nonceRow.expires_at) < new Date()) {+ return error(res, 400, 'nonce_expired', 'nonce expired');+ }++ // 5. Verify signature recovers the claimed address.+ let recovered;+ try {+ recovered = verifyMessage(body.message, body.signature);+ } catch {+ return error(res, 401, 'invalid_signature', 'signature verification failed');+ }+ let claimed;+ try {+ claimed = getAddress(fields.address);+ } catch {+ return error(res, 400, 'invalid_address', 'address not checksummed correctly');+ }+ if (recovered.toLowerCase() !== claimed.toLowerCase()) {+ return error(res, 401, 'invalid_signature', 'signer does not match address');+ }++ // Burn the nonce (race-safe: reject if already consumed).+ const burned = await sql`+ update siwe_nonces+ set consumed_at = now(), address = ${claimed.toLowerCase()}+ where nonce = ${fields.nonce} and consumed_at is null+ returning nonce+ `;+ if (!burned[0]) return error(res, 400, 'nonce_reused', 'nonce already used');++ const addrLower = claimed.toLowerCase();+ const chainId = fields.chainId || null;++ // 6. Check if the address is already linked to any account.+ const [existing] = await sql`+ select user_id from user_wallets where address = ${addrLower} limit 1+ `;+ if (existing) {+ if (String(existing.user_id) !== String(user.id)) {+ return error(res, 409, 'wallet_taken', 'wallet already linked to another account');+ }+ // Already linked to this user — idempotent success.+ return json(res, 200, { ok: true, address: claimed, chainId });+ }++ // 7. Link the wallet to the current session user.+ await sql`+ insert into user_wallets (user_id, address, chain_id, is_primary)+ values (${user.id}, ${addrLower}, ${chainId}, false)+ `;++ return json(res, 200, { ok: true, address: claimed, chainId });+});diff --git a/api/auth/wallet/unlink.js b/api/auth/wallet/unlink.jsnew file mode 100644index 000000000..52629ccb2--- /dev/null+++ b/api/auth/wallet/unlink.js@@ -0,0 +1,78 @@+// Unlink a wallet address from the current session-authenticated account.++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 { limits, clientIp } from '../../_lib/rate-limit.js';+import { parse } from '../../_lib/validate.js';++const bodySchema = z.object({+ address: z.string().regex(/^0x[a-fA-F0-9]{40}$/),+});++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many attempts');++ const body = parse(bodySchema, await readJson(req));+ const addrLower = body.address.toLowerCase();++ // 1. Confirm this wallet belongs to the current user.+ const [walletRow] = await sql`+ select address, is_primary+ from user_wallets+ where user_id = ${user.id} and address = ${addrLower}+ limit 1+ `;+ if (!walletRow) return error(res, 404, 'not_found', 'wallet not linked to your account');++ // 2. Refuse if this is the last auth method available.+ const [userRow] = await sql`+ select password_hash from users where id = ${user.id} limit 1+ `;+ const hasPassword = !!userRow?.password_hash;++ if (!hasPassword) {+ const [{ count }] = await sql`+ select count(*)::int as count from user_wallets where user_id = ${user.id}+ `;+ if (count <= 1) {+ return error(+ res,+ 409,+ 'last_auth_method',+ 'cannot remove your only authentication method',+ );+ }+ }++ // 3. If removing the primary wallet, promote the most-recently-used remaining one.+ if (walletRow.is_primary) {+ await sql`+ update user_wallets+ set is_primary = true+ where user_id = ${user.id}+ and address != ${addrLower}+ and address = (+ select address from user_wallets+ where user_id = ${user.id} and address != ${addrLower}+ order by last_used_at desc nulls last+ limit 1+ )+ `;+ }++ // 4. Delete the wallet row.+ await sql`+ delete from user_wallets where user_id = ${user.id} and address = ${addrLower}+ `;++ return json(res, 200, { ok: true });+});diff --git a/api/cz/claim.js b/api/cz/claim.jsnew file mode 100644index 000000000..be4e7fd4e--- /dev/null+++ b/api/cz/claim.js@@ -0,0 +1,138 @@+// POST /api/cz/claim — verify ECDSA signature, record claim intent, return on-chain tx payload+// GET /api/cz/claim?address=0x... — issue a fresh nonce for signing+//+// Requires this table (run once before deploy):+// create table if not exists cz_claims (+// id uuid primary key default gen_random_uuid(),+// address text not null,+// nonce text not null unique,+// status text not null default 'pending', -- pending | claimed+// created_at timestamptz not null default now(),+// claimed_at timestamptz+// );++import { randomBytes } from 'crypto';+import { verifyMessage, Interface } from 'ethers';+import { sql } from '../_lib/db.js';+import { cors, json, error, wrap, readJson } from '../_lib/http.js';+import { clientIp } from '../_lib/rate-limit.js';++// Pre-registered agent details — update these once the agent is registered on-chain.+const CZ_AGENT_ID = 'cz-preview';+const CZ_AGENT_NAME = 'CZ Agent';+// On-chain registry address (placeholder — update to real address before mainnet).+const REGISTRY_CONTRACT = '0x0000000000000000000000000000000000000000';++// ABI fragment for the ownership transfer call.+// Replace the function signature when the final contract ABI is known.+const _iface = new Interface(['function transferAgent(string agentId, address newOwner)']);+function encodeTransferAgent(agentId, newOwner) {+ return _iface.encodeFunctionData('transferAgent', [agentId, newOwner]);+}++// Inline sliding-window rate limiter: 5 requests / hour per IP.+// Using in-memory here because this is a one-shot flow with minimal traffic.+const _buckets = new Map();+function checkRate(ip) {+ const now = Date.now();+ const window = 60 * 60 * 1000;+ const kept = (_buckets.get(ip) || []).filter((t) => t > now - window);+ if (kept.length >= 5) return false;+ kept.push(now);+ _buckets.set(ip, kept);+ return true;+}++function claimMessage(nonce) {+ return `Claim CZ Agent\n\nNonce: ${nonce}`;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;++ const ip = clientIp(req);++ // ── GET: issue nonce ──────────────────────────────────────────────────────+ if (req.method === 'GET') {+ const address = new URL(req.url, 'http://x').searchParams.get('address') || '';+ if (!/^0x[0-9a-fA-F]{40}$/.test(address))+ return error(+ res,+ 400,+ 'validation_error',+ 'address must be a 0x-prefixed Ethereum address',+ );++ if (!checkRate(ip))+ return error(res, 429, 'rate_limited', 'too many requests — try again in an hour');++ const nonce = randomBytes(16).toString('hex');+ await sql`+ insert into cz_claims (address, nonce, status)+ values (${address.toLowerCase()}, ${nonce}, 'pending')+ `;+ return json(res, 200, { nonce });+ }++ // ── POST: verify signature and record claim ───────────────────────────────+ if (req.method === 'POST') {+ let body;+ try {+ body = await readJson(req);+ } catch (e) {+ return error(res, e.status || 400, 'validation_error', e.message);+ }++ const { signerAddress = '', signature = '', nonce = '' } = body ?? {};+ if (!signerAddress || !signature || !nonce)+ return error(+ res,+ 400,+ 'validation_error',+ 'signerAddress, signature, and nonce are required',+ );+ if (!/^0x[0-9a-fA-F]{40}$/.test(signerAddress))+ return error(res, 400, 'validation_error', 'invalid signerAddress format');++ if (!checkRate(ip))+ return error(res, 429, 'rate_limited', 'too many requests — try again in an hour');++ const rows = await sql`+ select id, address, status from cz_claims where nonce = ${nonce} limit 1+ `;+ const row = rows[0];+ if (!row) return error(res, 400, 'invalid_nonce', 'nonce not found');+ if (row.status !== 'pending') return error(res, 409, 'conflict', 'nonce already used');+ if (row.address !== signerAddress.toLowerCase())+ return error(res, 403, 'forbidden', 'address does not match nonce');++ let recovered;+ try {+ recovered = verifyMessage(claimMessage(nonce), signature);+ } catch {+ return error(res, 400, 'invalid_signature', 'could not parse signature');+ }+ if (recovered.toLowerCase() !== signerAddress.toLowerCase())+ return error(res, 403, 'forbidden', 'signature does not match signer address');++ await sql`+ update cz_claims set status = 'claimed', claimed_at = now() where id = ${row.id}+ `;++ const txPayload = {+ to: REGISTRY_CONTRACT,+ data: encodeTransferAgent(CZ_AGENT_ID, signerAddress),+ value: '0x0',+ };++ return json(res, 200, {+ ok: true,+ agentId: CZ_AGENT_ID,+ agentName: CZ_AGENT_NAME,+ txPayload,+ });+ }++ res.setHeader('allow', 'GET, POST, OPTIONS');+ return error(res, 405, 'method_not_allowed', 'method not allowed');+});diff --git a/api/pinning/pin.js b/api/pinning/pin.jsindex 29a763d9f..10f07bff9 100644--- a/api/pinning/pin.js+++ b/api/pinning/pin.js@@ -48,7 +48,10 @@ async function pinViaWeb3Storage(buf, filename) {});if (!resp.ok) {const detail = await resp.text().catch(() => '');- throw Object.assign(new Error(`Web3.Storage error ${resp.status}`), { status: 502, detail });+ throw Object.assign(new Error(`Web3.Storage error ${resp.status}`), {+ status: 502,+ detail,+ });}const data = await resp.json();return { cid: data.cid, provider: 'web3.storage' };@@ -74,7 +77,8 @@ export default wrap(async (req, res) => {const session = await getSessionUser(req);const bearer = session ? null : await authenticateBearer(extractBearer(req));- if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');+ if (!session && !bearer)+ return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');const userId = session?.id ?? bearer.userId;const rl = await limits.pinUser(userId);@@ -117,7 +121,12 @@ export default wrap(async (req, res) => {}} else {if (!isOwnedR2Url(sourceUrl)) {- return error(res, 400, 'validation_error', 'sourceUrl must be an owned R2 URL or a data: URL');+ return error(+ res,+ 400,+ 'validation_error',+ 'sourceUrl must be an owned R2 URL or a data: URL',+ );}const head = await fetch(sourceUrl, { method: 'HEAD' });if (!head.ok) return error(res, 400, 'validation_error', 'source URL is not accessible');diff --git a/api/pinning/status.js b/api/pinning/status.jsindex 84b344997..e608c7b06 100644--- a/api/pinning/status.js+++ b/api/pinning/status.js@@ -17,7 +17,12 @@ export default wrap(async (req, res) => {const cid = req.query?.cid || new URL(req.url, 'http://x').searchParams.get('cid');if (!cid || !CID_RE.test(cid)) {- return error(res, 400, 'validation_error', 'cid query parameter is required and must be alphanumeric');+ return error(+ res,+ 400,+ 'validation_error',+ 'cid query parameter is required and must be alphanumeric',+ );}const pinataJwt = process.env.PINATA_JWT;diff --git a/index.html b/index.htmlindex e48e6f905..a9359f50f 100644--- a/index.html+++ b/index.html@@ -500,6 +500,7 @@<a href="/widgets">Widgets</a><a href="/dashboard" class="nav-dashboard">Dashboard</a><a href="/login" class="nav-sign-in" id="nav-sign-in">Sign in</a>+ <button id="btn-wallet-signin" style="cursor:pointer;">Sign in with wallet</button></nav></header>@@ -931,5 +932,10 @@});})();</script>+ <script type="module">+ import { wireSigninButton } from '/src/wallet-auth.js';+ const btn = document.getElementById('btn-wallet-signin');+ if (btn) wireSigninButton(btn);+ </script></body></html>diff --git a/public/cz/cz.css b/public/cz/cz.cssnew file mode 100644index 000000000..4ebf7601a--- /dev/null+++ b/public/cz/cz.css@@ -0,0 +1,220 @@+:root {+ color-scheme: dark;+ --accent: #f0b429;+ --border: #1e1e2a;+ --bg: #080814;+ --panel: #0f0f18;+ --text: #e8e8ee;+ --text-dim: #6b6b80;+ --radius: 12px;+}++* {+ box-sizing: border-box;+}++body {+ margin: 0;+ background: var(--bg);+ color: var(--text);+ font:+ 15px/1.6 -apple-system,+ system-ui,+ Segoe UI,+ Roboto,+ sans-serif;+ min-height: 100vh;+ overflow-x: hidden;+}++header {+ display: flex;+ align-items: center;+ padding: 18px 32px;+ border-bottom: 1px solid var(--border);+ position: sticky;+ top: 0;+ background: rgba(8, 8, 20, 0.85);+ backdrop-filter: blur(12px);+ -webkit-backdrop-filter: blur(12px);+ z-index: 10;+}++.logo {+ font-size: 17px;+ font-weight: 700;+ letter-spacing: -0.3px;+ color: var(--accent);+}++main {+ display: grid;+ grid-template-columns: 1fr 440px;+ min-height: calc(100vh - 57px);+}++.agent-wrap {+ position: relative;+ background: radial-gradient(ellipse 80% 70% at 50% 40%, #1a1630 0%, var(--bg) 75%);+}++agent-3d {+ display: block;+ width: 100%;+ height: 100%;+ min-height: 520px;+}++.claim-panel {+ display: flex;+ flex-direction: column;+ justify-content: center;+ padding: 56px 40px;+ border-left: 1px solid var(--border);+ background: var(--panel);+ gap: 0;+}++h1 {+ font-size: 28px;+ font-weight: 700;+ line-height: 1.2;+ margin: 0 0 36px;+ letter-spacing: -0.5px;+}++.step {+ display: flex;+ flex-direction: column;+ gap: 14px;+}++.step.hidden {+ display: none;+}++.btn-primary {+ padding: 14px 28px;+ background: var(--accent);+ color: #000;+ border: none;+ border-radius: var(--radius);+ font-size: 15px;+ font-weight: 700;+ cursor: pointer;+ transition: opacity 0.15s;+ align-self: flex-start;+}++.btn-primary:hover:not(:disabled) {+ opacity: 0.85;+}++.btn-primary:disabled {+ opacity: 0.45;+ cursor: not-allowed;+}++.btn-secondary {+ padding: 12px 22px;+ background: transparent;+ color: var(--text);+ border: 1px solid var(--border);+ border-radius: var(--radius);+ font-size: 14px;+ cursor: pointer;+ align-self: flex-start;+ transition: border-color 0.15s;+}++.btn-secondary:hover {+ border-color: #44445a;+}++.wallet-addr {+ font-size: 12px;+ color: var(--text-dim);+ font-family: ui-monospace, 'Cascadia Code', 'Courier New', monospace;+ margin: 0;+ word-break: break-all;+ background: rgba(255, 255, 255, 0.03);+ border: 1px solid var(--border);+ border-radius: 8px;+ padding: 8px 12px;+}++.success-msg {+ font-size: 16px;+ margin: 0;+ color: #7ee787;+ line-height: 1.5;+}++.snippet-wrap {+ display: flex;+ flex-direction: column;+ gap: 8px;+ margin-top: 4px;+}++pre {+ margin: 0;+ padding: 10px 12px;+ background: rgba(0, 0, 0, 0.3);+ border: 1px solid var(--border);+ border-radius: 8px;+ font-size: 11px;+ line-height: 1.5;+ color: #9a8cff;+ overflow-x: auto;+ white-space: pre-wrap;+ word-break: break-all;+ font-family: ui-monospace, 'Cascadia Code', 'Courier New', monospace;+}++.error-msg {+ color: #f87171;+ margin: 0;+ font-size: 14px;+}++.rehearsal-badge {+ display: inline-block;+ margin-top: 28px;+ padding: 3px 10px;+ background: rgba(240, 180, 41, 0.12);+ color: var(--accent);+ border: 1px solid rgba(240, 180, 41, 0.25);+ border-radius: 20px;+ font-size: 11px;+ font-weight: 600;+ letter-spacing: 0.8px;+ text-transform: uppercase;+}++.rehearsal-badge.hidden {+ display: none;+}++@media (max-width: 860px) {+ main {+ grid-template-columns: 1fr;+ }++ .claim-panel {+ border-left: none;+ border-top: 1px solid var(--border);+ padding: 40px 24px;+ }++ agent-3d {+ min-height: 300px;+ }+}++@media (prefers-reduced-motion: reduce) {+ .btn-primary,+ .btn-secondary {+ transition: none;+ }+}diff --git a/public/cz/cz.js b/public/cz/cz.jsnew file mode 100644index 000000000..cb7540549--- /dev/null+++ b/public/cz/cz.js@@ -0,0 +1,147 @@+// Hardcoded pre-registered agent id — coordinate with whoever ran the on-chain registration.+const AGENT_ID = 'cz-preview';+const AGENT_NAME = 'CZ Agent';++const REHEARSAL = new URLSearchParams(location.search).has('rehearsal');++// --- DOM refs ---+const stepConnect = document.getElementById('step-connect');+const stepSign = document.getElementById('step-sign');+const stepSuccess = document.getElementById('step-success');+const stepError = document.getElementById('step-error');+const btnConnect = document.getElementById('btn-connect');+const btnSign = document.getElementById('btn-sign');+const btnRetry = document.getElementById('btn-retry');+const walletAddrEl = document.getElementById('wallet-addr');+const agentNameDisplay = document.getElementById('agent-name-display');+const snippetScript = document.getElementById('snippet-script');+const snippetTag = document.getElementById('snippet-tag');+const snippetIframe = document.getElementById('snippet-iframe');+const errorMsgEl = document.getElementById('error-msg');+const rehearsalBadge = document.getElementById('rehearsal-badge');++// Wire agent-id into the embed element+document.getElementById('preview').setAttribute('agent-id', AGENT_ID);++if (REHEARSAL) rehearsalBadge.classList.remove('hidden');++let _address = null;+let _nonce = null;++function show(step) {+ for (const s of [stepConnect, stepSign, stepSuccess, stepError]) s.classList.add('hidden');+ step.classList.remove('hidden');+}++// --- Connect wallet ---+btnConnect.addEventListener('click', async () => {+ btnConnect.disabled = true;+ btnConnect.textContent = 'Connecting…';+ try {+ _address = await connectWallet();+ walletAddrEl.textContent = _address;++ const nonceRes = await fetch(`/api/cz/claim?address=${encodeURIComponent(_address)}`);+ const nonceData = await nonceRes.json();+ if (!nonceRes.ok) throw new Error(nonceData.error_description || 'Failed to get nonce');+ _nonce = nonceData.nonce;++ show(stepSign);+ } catch (err) {+ showError(err.message);+ } finally {+ btnConnect.disabled = false;+ btnConnect.textContent = 'Connect wallet to claim';+ }+});++// --- Sign and claim ---+btnSign.addEventListener('click', async () => {+ btnSign.disabled = true;+ btnSign.textContent = 'Signing…';+ try {+ if (REHEARSAL) {+ // Stub: 2-second fake success, no chain interaction+ await new Promise((r) => setTimeout(r, 2000));+ showSuccess();+ return;+ }++ const message = claimMessage(_nonce);+ const signature = await signMessage(message, _address);++ const claimRes = await fetch('/api/cz/claim', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ signerAddress: _address, signature, nonce: _nonce }),+ });+ const claimData = await claimRes.json();+ if (!claimRes.ok) throw new Error(claimData.error_description || 'Claim failed');++ if (+ claimData.txPayload &&+ claimData.txPayload.to !== '0x0000000000000000000000000000000000000000'+ ) {+ btnSign.textContent = 'Broadcasting…';+ await broadcastTx(claimData.txPayload, _address);+ }++ showSuccess();+ } catch (err) {+ showError(err.message);+ } finally {+ btnSign.disabled = false;+ btnSign.textContent = '⬢ Sign claim transaction';+ }+});++btnRetry.addEventListener('click', () => {+ _address = null;+ _nonce = null;+ show(stepConnect);+});++function claimMessage(nonce) {+ return `Claim CZ Agent\n\nNonce: ${nonce}`;+}++function showSuccess() {+ agentNameDisplay.textContent = AGENT_NAME;+ const origin = location.origin;+ snippetScript.textContent = `<script type="module"\n src="${origin}/agent-3d/latest/agent-3d.js">\n<\/script>`;+ snippetTag.textContent = `<agent-3d agent-id="${AGENT_ID}" kiosk></agent-3d>`;+ snippetIframe.textContent = `<iframe\n src="${origin}/agent/${AGENT_ID}/embed"\n allow="microphone"\n width="400" height="600">\n</iframe>`;+ show(stepSuccess);+}++function showError(msg) {+ errorMsgEl.textContent = msg;+ show(stepError);+}++// --- Wallet helpers (injected provider; Privy available once loaded on the main app) ---++async function connectWallet() {+ if (!window.ethereum)+ throw new Error('No wallet detected. Install MetaMask or a compatible browser wallet.');+ const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });+ if (!accounts?.[0]) throw new Error('No account returned from wallet.');+ return accounts[0];+}++async function signMessage(message, address) {+ // personal_sign encodes message with the Ethereum prefix before signing.+ const msgHex =+ '0x' ++ Array.from(new TextEncoder().encode(message), (b) => b.toString(16).padStart(2, '0')).join(+ '',+ );+ return window.ethereum.request({ method: 'personal_sign', params: [msgHex, address] });+}++async function broadcastTx({ to, data, value }, from) {+ return window.ethereum.request({+ method: 'eth_sendTransaction',+ params: [{ from, to, data, value: value || '0x0' }],+ });+}diff --git a/public/cz/index.html b/public/cz/index.htmlindex 38d649ee6..5f3fc6b36 100644--- a/public/cz/index.html+++ b/public/cz/index.html@@ -1,321 +1,61 @@<!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>+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>CZ · Claim Your 3D Agent</title>+ <meta name="description" content="Connect your wallet and claim your on-chain 3D agent." />+ <meta name="theme-color" content="#080814" />+ <link rel="icon" href="/favicon.ico" />+ <link rel="stylesheet" href="./cz.css" />+ <script+ type="module"+ src="https://3dagent.vercel.app/agent-3d/latest/agent-3d.js"+ crossorigin+ ></script>+ </head>+ <body>+ <header>+ <span class="logo">⬡ 3D Agent</span>+ </header>+ <main>+ <div class="agent-wrap">+ <!-- agent-id is hardcoded once at top of cz.js and set here via JS -->+ <agent-3d id="preview" kiosk eager></agent-3d></div>- </div>- </div>- <script type="module" src="./boot.js"></script>-</body>+ <section class="claim-panel">+ <h1>Welcome, CZ.<br />Claim your on-chain agent.</h1>++ <div id="step-connect" class="step">+ <button id="btn-connect" class="btn-primary">Connect wallet to claim</button>+ </div>++ <div id="step-sign" class="step hidden">+ <p class="wallet-addr" id="wallet-addr"></p>+ <button id="btn-sign" class="btn-primary">⬢ Sign claim transaction</button>+ </div>++ <div id="step-success" class="step hidden">+ <p class="success-msg">+ You now own <strong id="agent-name-display"></strong>. Here's your embed+ snippet.+ </p>+ <div class="snippet-wrap">+ <pre id="snippet-script"></pre>+ <pre id="snippet-tag"></pre>+ <pre id="snippet-iframe"></pre>+ </div>+ </div>++ <div id="step-error" class="step hidden">+ <p class="error-msg" id="error-msg"></p>+ <button id="btn-retry" class="btn-secondary">Try again</button>+ </div>++ <span id="rehearsal-badge" class="rehearsal-badge hidden">rehearsal mode</span>+ </section>+ </main>+ <script type="module" src="./cz.js"></script>+ </body></html>diff --git a/src/camera-capture.js b/src/camera-capture.jsnew file mode 100644index 000000000..542e2f31d--- /dev/null+++ b/src/camera-capture.js@@ -0,0 +1,321 @@+import './camera-capture.css';++// Guard SSR environments — module must be importable without a DOM.+const _hasNav = typeof navigator !== 'undefined';++export class CameraCapture {+ /**+ * @param {object} opts+ * @param {HTMLElement} opts.container+ * @param {(blob: Blob, meta: {width:number, height:number, mimeType:string}) => void} opts.onCapture+ * @param {() => void} [opts.onCancel]+ * @param {number} [opts.aspect]+ */+ constructor({ container, onCapture, onCancel, aspect = 1 }) {+ this._container = container;+ this._onCapture = onCapture;+ this._onCancel = onCancel ?? (() => {});+ this._aspect = aspect;++ this._stream = null;+ this._facingMode = 'user';+ this._root = null;+ this._video = null;+ this._canvas = null;+ this._snapshot = null; // current preview blob URL+ this._stopped = false;+ this._abortCtrl = new AbortController();+ }++ async start() {+ if (this._stopped) return;++ this._root = document.createElement('div');+ this._root.className = 'camera-capture-root';+ this._container.appendChild(this._root);++ if (!_hasNav || !navigator.mediaDevices?.getUserMedia) {+ this._renderFallback('Camera not available in this browser.');+ return;+ }++ try {+ await this._startStream();+ this._renderLive();+ } catch (err) {+ const msg =+ err.name === 'NotAllowedError' || err.name === 'PermissionDeniedError'+ ? 'Camera permission denied.'+ : 'Could not access camera.';+ this._renderFallback(msg);+ }+ }++ stop() {+ if (this._stopped) return;+ this._stopped = true;+ this._abortCtrl.abort();+ this._releaseStream();+ if (this._snapshot) {+ URL.revokeObjectURL(this._snapshot);+ this._snapshot = null;+ }+ if (this._root && this._root.parentNode) {+ this._root.parentNode.removeChild(this._root);+ }+ this._root = null;+ }++ // ── private ────────────────────────────────────────────────────────────++ async _startStream() {+ this._releaseStream();+ this._stream = await navigator.mediaDevices.getUserMedia({+ video: {+ facingMode: this._facingMode,+ width: { ideal: 1280 },+ height: { ideal: 1280 },+ },+ });+ }++ _releaseStream() {+ if (this._stream) {+ for (const track of this._stream.getTracks()) track.stop();+ this._stream = null;+ }+ if (this._video) {+ this._video.srcObject = null;+ }+ }++ _listen(el, event, handler) {+ el.addEventListener(event, handler, { signal: this._abortCtrl.signal });+ }++ // ── live view ──────────────────────────────────────────────────────────++ _renderLive() {+ this._root.innerHTML = '';++ const wrap = document.createElement('div');+ wrap.className = 'cc-preview-wrap';++ const video = document.createElement('video');+ video.className = 'cc-video';+ video.autoplay = true;+ video.muted = true;+ video.setAttribute('playsinline', ''); // iOS Safari requires this attribute+ video.setAttribute('webkit-playsinline', ''); // older Safari compat+ video.srcObject = this._stream;+ this._video = video;++ wrap.appendChild(video);+ this._root.appendChild(wrap);++ const controls = document.createElement('div');+ controls.className = 'cc-controls';++ // Switch-camera button — only useful on mobile (multiple cameras)+ const btnSwitch = document.createElement('button');+ btnSwitch.className = 'cc-btn-switch';+ btnSwitch.title = 'Switch camera';+ btnSwitch.textContent = '⇄';+ this._listen(btnSwitch, 'click', () => this._switchCamera());++ const btnCapture = document.createElement('button');+ btnCapture.className = 'cc-btn-capture';+ btnCapture.setAttribute('aria-label', 'Capture photo');+ this._listen(btnCapture, 'click', () => this._capture());++ // Spacer so layout is symmetric around the large button+ const spacer = document.createElement('div');+ spacer.style.width = '44px';++ controls.appendChild(btnSwitch);+ controls.appendChild(btnCapture);+ controls.appendChild(spacer);+ this._root.appendChild(controls);++ const uploadLink = document.createElement('button');+ uploadLink.className = 'cc-link-upload';+ uploadLink.textContent = 'Use upload instead';+ this._listen(uploadLink, 'click', () => {+ this._releaseStream();+ this._renderFallback(null);+ });+ this._root.appendChild(uploadLink);+ }++ async _switchCamera() {+ this._facingMode = this._facingMode === 'user' ? 'environment' : 'user';+ try {+ await this._startStream();+ if (this._video) this._video.srcObject = this._stream;+ } catch (_) {+ // revert if the back camera isn't available+ this._facingMode = this._facingMode === 'user' ? 'environment' : 'user';+ }+ }++ _capture() {+ if (!this._video || !this._stream) return;++ const v = this._video;+ const side = Math.min(v.videoWidth || 1280, v.videoHeight || 1280);+ const ox = ((v.videoWidth || side) - side) / 2;+ const oy = ((v.videoHeight || side) - side) / 2;++ const canvas = document.createElement('canvas');+ canvas.width = side;+ canvas.height = side;+ const ctx = canvas.getContext('2d');++ // Mirror to match the CSS transform on the live preview+ ctx.save();+ ctx.translate(side, 0);+ ctx.scale(-1, 1);+ ctx.drawImage(v, ox, oy, side, side, 0, 0, side, side);+ ctx.restore();++ this._canvas = canvas;++ canvas.toBlob(+ (blob) => {+ if (!blob || this._stopped) return;+ this._renderPreview(blob, side, side);+ },+ 'image/jpeg',+ 0.92,+ );+ }++ // ── preview (post-capture) ─────────────────────────────────────────────++ _renderPreview(blob, width, height) {+ if (this._snapshot) URL.revokeObjectURL(this._snapshot);+ this._snapshot = URL.createObjectURL(blob);++ this._root.innerHTML = '';++ const wrap = document.createElement('div');+ wrap.className = 'cc-preview-wrap';++ const img = document.createElement('img');+ img.className = 'cc-snapshot';+ img.src = this._snapshot;+ img.alt = 'Captured photo preview';+ wrap.appendChild(img);+ this._root.appendChild(wrap);++ const controls = document.createElement('div');+ controls.className = 'cc-controls';++ const btnRetake = document.createElement('button');+ btnRetake.className = 'cc-btn-retake';+ btnRetake.textContent = 'Retake';+ this._listen(btnRetake, 'click', async () => {+ try {+ await this._startStream();+ this._renderLive();+ } catch (err) {+ this._renderFallback('Could not restart camera.');+ }+ });++ const btnUse = document.createElement('button');+ btnUse.className = 'cc-btn-use';+ btnUse.textContent = 'Use this photo';+ this._listen(btnUse, 'click', () => {+ this._releaseStream();+ this._onCapture(blob, { width, height, mimeType: 'image/jpeg' });+ });++ controls.appendChild(btnRetake);+ controls.appendChild(btnUse);+ this._root.appendChild(controls);+ }++ // ── file-upload fallback ───────────────────────────────────────────────++ _renderFallback(reason) {+ this._root.innerHTML = '';++ const wrap = document.createElement('div');+ wrap.className = 'cc-fallback';++ if (reason) {+ const err = document.createElement('p');+ err.className = 'cc-error';+ err.textContent = reason;+ wrap.appendChild(err);+ }++ const p = document.createElement('p');+ p.textContent = 'Choose a photo from your device to continue.';+ wrap.appendChild(p);++ const input = document.createElement('input');+ input.type = 'file';+ input.accept = 'image/*';+ input.setAttribute('capture', 'user');+ input.className = 'cc-hidden-input';++ const btnPick = document.createElement('button');+ btnPick.className = 'cc-btn-file-pick';+ btnPick.textContent = 'Choose photo';+ this._listen(btnPick, 'click', () => input.click());++ this._listen(input, 'change', () => {+ const file = input.files?.[0];+ if (!file) return;+ this._handleFileBlob(file);+ });++ wrap.appendChild(btnPick);+ wrap.appendChild(input);++ const cancelBtn = document.createElement('button');+ cancelBtn.className = 'cc-link-upload';+ cancelBtn.textContent = 'Cancel';+ this._listen(cancelBtn, 'click', () => {+ this.stop();+ this._onCancel();+ });+ wrap.appendChild(cancelBtn);++ this._root.appendChild(wrap);+ }++ _handleFileBlob(file) {+ const url = URL.createObjectURL(file);+ const img = new Image();+ img.onload = () => {+ const side = Math.min(img.naturalWidth, img.naturalHeight);+ const ox = (img.naturalWidth - side) / 2;+ const oy = (img.naturalHeight - side) / 2;++ const canvas = document.createElement('canvas');+ canvas.width = side;+ canvas.height = side;+ const ctx = canvas.getContext('2d');+ ctx.drawImage(img, ox, oy, side, side, 0, 0, side, side);+ URL.revokeObjectURL(url);++ canvas.toBlob(+ (blob) => {+ if (!blob || this._stopped) return;+ this._onCapture(blob, {+ width: side,+ height: side,+ mimeType: 'image/jpeg',+ });+ },+ 'image/jpeg',+ 0.92,+ );+ };+ img.onerror = () => URL.revokeObjectURL(url);+ img.src = url;+ }+}diff --git a/src/claim-transfer.js b/src/claim-transfer.jsnew file mode 100644index 000000000..a35f5d9bd--- /dev/null+++ b/src/claim-transfer.js@@ -0,0 +1,198 @@+/**+ * Claim / transfer flow for ERC-8004 agents.+ *+ * Uses standard ERC-721 safeTransferFrom — no custom claim entry point needed.+ * The IdentityRegistry inherits ERC-721 transfer mechanics verbatim.+ */++import { BrowserProvider, Contract, Interface } from 'ethers';+import { IDENTITY_REGISTRY_ABI, REGISTRY_DEPLOYMENTS } from './erc8004/abi.js';++// ---------------------------------------------------------------------------+// ClaimError+// ---------------------------------------------------------------------------++export class ClaimError extends Error {+ /**+ * @param {string} message+ * @param {'wrong-owner'|'already-claimed'|'user-rejected'|'network'|'unsupported-chain'} code+ */+ constructor(message, code) {+ super(message);+ this.name = 'ClaimError';+ this.code = code;+ }+}++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++/** @returns {{ identityRegistry: string }} */+function _deployment(chainId) {+ const dep = REGISTRY_DEPLOYMENTS[chainId];+ if (!dep || !dep.identityRegistry) {+ throw new ClaimError(+ `No IdentityRegistry deployment for chain ${chainId}`,+ 'unsupported-chain',+ );+ }+ return dep;+}++/**+ * Ask the wallet to switch to `chainId` (EIP-3326).+ * No-ops when the wallet is already on the right chain.+ */+async function _ensureChain(chainId) {+ if (!window.ethereum) return;+ const hexId = '0x' + chainId.toString(16);+ try {+ await window.ethereum.request({+ method: 'wallet_switchEthereumChain',+ params: [{ chainId: hexId }],+ });+ } catch (err) {+ // 4902 = chain not added to wallet — surface as network error+ throw new ClaimError(+ `Wallet chain switch failed (${err.message})`,+ 'network',+ );+ }+}++/** Wrap ethers user-rejection errors into ClaimError. */+function _wrapTxError(err) {+ const msg = err?.message || String(err);+ if (+ err?.code === 'ACTION_REJECTED' ||+ msg.includes('user rejected') ||+ msg.includes('User denied')+ ) {+ return new ClaimError('User rejected the transaction', 'user-rejected');+ }+ return new ClaimError(msg, 'network');+}++// ---------------------------------------------------------------------------+// claimAgent+// ---------------------------------------------------------------------------++/**+ * Execute the on-chain ownership transfer for an ERC-8004 agent.+ *+ * `signer` must be either the current owner (fromAddress) or an address that+ * the owner has approved via `approve()` / `setApprovalForAll()`.+ *+ * Steps emitted via `onStep`:+ * permit — validating ownership + chain+ * sign — waiting for wallet signature+ * broadcast — tx submitted, waiting for inclusion+ * confirm — tx confirmed+ *+ * @param {object} opts+ * @param {number|string} opts.agentId+ * @param {string} opts.fromAddress Current owner (ops/mint wallet)+ * @param {string} opts.toAddress Claimer address+ * @param {import('ethers').Signer} opts.signer+ * @param {(step: {step: string, pct: number, txHash?: string}) => void} [opts.onStep]+ * @returns {Promise<{ok: true, txHash: string, blockNumber: number}>}+ */+export async function claimAgent({ agentId, fromAddress, toAddress, signer, onStep }) {+ const step = (s, pct, txHash) => onStep?.({ step: s, pct, ...(txHash ? { txHash } : {}) });++ step('permit', 0);++ // Resolve chain from the signer's provider+ const network = await signer.provider.getNetwork();+ const chainId = Number(network.chainId);++ _deployment(chainId); // throws 'unsupported-chain' if unknown++ await _ensureChain(chainId);++ const dep = _deployment(chainId);+ const registry = new Contract(dep.identityRegistry, IDENTITY_REGISTRY_ABI, signer);++ // Validate current ownership+ let currentOwner;+ try {+ currentOwner = await registry.ownerOf(agentId);+ } catch (err) {+ throw new ClaimError(`Could not fetch owner for agentId ${agentId}: ${err.message}`, 'network');+ }++ const normalize = (a) => a.toLowerCase();++ if (normalize(currentOwner) !== normalize(fromAddress)) {+ throw new ClaimError(+ `Agent ${agentId} is owned by ${currentOwner}, not ${fromAddress}`,+ 'wrong-owner',+ );+ }++ if (normalize(currentOwner) === normalize(toAddress)) {+ throw new ClaimError(`Agent ${agentId} is already owned by ${toAddress}`, 'already-claimed');+ }++ step('sign', 25);++ let tx;+ try {+ tx = await registry['safeTransferFrom(address,address,uint256)'](+ fromAddress,+ toAddress,+ agentId,+ );+ } catch (err) {+ throw _wrapTxError(err);+ }++ step('broadcast', 60, tx.hash);++ let receipt;+ try {+ receipt = await tx.wait();+ } catch (err) {+ throw _wrapTxError(err);+ }++ step('confirm', 100, tx.hash);++ return { ok: true, txHash: tx.hash, blockNumber: receipt.blockNumber };+}++// ---------------------------------------------------------------------------+// buildClaimPayload+// ---------------------------------------------------------------------------++/**+ * Build a raw `eth_sendTransaction` payload for a claim transfer.+ * Pure function — no wallet connection required.+ *+ * Useful when the signing step is split from the payload build (e.g. the+ * server builds the call data, the client signs and sends it).+ *+ * @param {object} opts+ * @param {number|string} opts.agentId+ * @param {string} opts.toAddress Recipient address+ * @param {number} opts.chainId+ * @param {string} opts.fromAddress Current owner (required for safeTransferFrom calldata)+ * @returns {{ to: string, data: string, value: string }}+ */+export function buildClaimPayload({ agentId, toAddress, chainId, fromAddress }) {+ const dep = _deployment(chainId); // throws 'unsupported-chain' if unknown++ const iface = new Interface(IDENTITY_REGISTRY_ABI);+ const data = iface.encodeFunctionData('safeTransferFrom(address,address,uint256)', [+ fromAddress,+ toAddress,+ agentId,+ ]);++ return {+ to: dep.identityRegistry,+ data,+ value: '0x0',+ };+}diff --git a/src/embed-action-bridge.js b/src/embed-action-bridge.jsnew file mode 100644index 000000000..b6f48db58--- /dev/null+++ b/src/embed-action-bridge.js@@ -0,0 +1,134 @@+import { ACTION_TYPES } from './agent-protocol.js';++const _debugLogged = new Set();++function _debugOnce(msg) {+ if (!_debugLogged.has(msg)) {+ _debugLogged.add(msg);+ console.debug('[EmbedActionBridge]', msg);+ }+}++/**+ * Glue layer between EmbedHostBridge postMessage events and the agent protocol bus.+ * Host → Agent: translates `host.*` events into protocol.emit() calls.+ * Agent → Host: relays protocol events back to the host via bridge.send('embed.event').+ */+export class EmbedActionBridge {+ /**+ * @param {{ bridge: EventTarget & { send: Function }, protocol: import('./agent-protocol.js').AgentProtocol }} opts+ */+ constructor({ bridge, protocol }) {+ this._bridge = bridge;+ this._protocol = protocol;+ this._hostHandlers = new Map();+ this._protocolHandlers = new Map();+ }++ start() {+ this._listenHost('host.chat.message', (e) => this._onChatMessage(e));+ this._listenHost('host.action', (e) => this._onHostAction(e));+ this._listenHost('host.theme', (e) => this._onHostTheme(e));++ // Agent → Host relay+ this._listenProtocol(ACTION_TYPES.SPEAK, (a) => this._relayEvent('agent.speaking', { text: a.payload.text, sentiment: a.payload.sentiment }));+ this._listenProtocol(ACTION_TYPES.EMOTE, (a) => this._relayEvent('agent.emote', a.payload));+ this._listenProtocol(ACTION_TYPES.REMEMBER,(a) => this._relayEvent('agent.memory', a.payload));+ this._listenProtocol(ACTION_TYPES.PRESENCE,(a) => this._relayEvent('agent.idle', a.payload));+ }++ stop() {+ for (const [type, fn] of this._hostHandlers) {+ this._bridge.removeEventListener(type, fn);+ }+ this._hostHandlers.clear();++ for (const [type, fn] of this._protocolHandlers) {+ this._protocol.off(type, fn);+ }+ this._protocolHandlers.clear();+ }++ // ── Host → Agent ─────────────────────────────────────────────────────────++ _onChatMessage(e) {+ const p = e.payload;+ if (!p || typeof p.text !== 'string') {+ _debugOnce('host.chat.message missing text — ignored');+ return;+ }+ if (p.role === 'user') {+ // User spoke into the host chat; treat as input directed at the agent.+ this._protocol.emit({ type: ACTION_TYPES.SPEAK, payload: { text: p.text, sentiment: 0, _from: 'user' } });+ } else if (p.role === 'assistant') {+ // Assistant turn delivered from the host — agent should voice/display it.+ // TTS does not auto-fire here; runtime/speech.js may consume SPEAK events if wired.+ this._protocol.emit({ type: ACTION_TYPES.SPEAK, payload: { text: p.text, sentiment: 0.3, _from: 'assistant' } });+ } else {+ _debugOnce(`host.chat.message unknown role "${p.role}" — ignored`);+ }+ }++ _onHostAction(e) {+ const p = e.payload;+ if (!p || typeof p.action !== 'string') {+ _debugOnce('host.action missing action string — ignored');+ return;+ }++ const action = p.action;+ const args = p.args && typeof p.args === 'object' ? p.args : {};++ if (action === 'speak') {+ if (typeof args.text !== 'string') {+ _debugOnce('host.action speak missing args.text — ignored');+ return;+ }+ this._protocol.emit({ type: ACTION_TYPES.SPEAK, payload: { text: args.text, sentiment: 0, _from: 'host' } });+ return;+ }++ if (action.startsWith('emote.')) {+ const suffix = action.slice('emote.'.length);+ if (!suffix) {+ _debugOnce('host.action emote with no suffix — ignored');+ return;+ }+ // Capitalize first letter for conventional clip names (wave → Wave)+ const name = suffix.charAt(0).toUpperCase() + suffix.slice(1);+ this._protocol.emit({ type: ACTION_TYPES.GESTURE, payload: { name, duration: args.duration ?? 2 } });+ return;+ }++ _debugOnce(`host.action unknown action "${action}" — ignored`);+ }++ _onHostTheme(e) {+ const p = e.payload;+ if (!p || typeof p.mode !== 'string') {+ _debugOnce('host.theme missing mode — ignored');+ return;+ }+ if (typeof document !== 'undefined') {+ document.body.dataset.theme = p.mode;+ }+ }++ // ── Agent → Host ─────────────────────────────────────────────────────────++ _relayEvent(event, data) {+ this._bridge.send('embed.event', { event, data: data ?? {} });+ }++ // ── Helpers ───────────────────────────────────────────────────────────────++ _listenHost(type, fn) {+ this._bridge.addEventListener(type, fn);+ this._hostHandlers.set(type, fn);+ }++ _listenProtocol(type, fn) {+ this._protocol.on(type, fn);+ this._protocolHandlers.set(type, fn);+ }+}diff --git a/src/wallet-auth.js b/src/wallet-auth.jsnew file mode 100644index 000000000..b836ce4e9--- /dev/null+++ b/src/wallet-auth.js@@ -0,0 +1,158 @@+import { connectWallet } from './erc8004/agent-registry.js';+import { isPrivyConfigured } from './erc8004/privy.js';++// ─── Public API ─────────────────────────────────────────────────────────────++/**+ * @returns {Promise<{user: object, wallet: object}>}+ */+export async function signInWithWallet() {+ const { signer, address, chainId } = await connectWallet();++ // GET nonce — sets __Host-csrf-siwe cookie, returns csrf token+ const nonceRes = await fetch('/api/auth/siwe/nonce', {+ credentials: 'include',+ });+ if (!nonceRes.ok) {+ const body = await nonceRes.json().catch(() => ({}));+ throw new Error(body.error_description || 'Failed to fetch nonce');+ }+ const { nonce, csrf } = await nonceRes.json();++ const message = [+ `${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()}`,+ ].join('\n');++ const signature = await signer.signMessage(message);++ 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().catch(() => ({}));+ if (!verifyRes.ok) {+ throw new Error(data.error_description || data.error || 'Sign-in failed');+ }+ return data;+}++/** @returns {Promise<void>} */+export async function signOut() {+ await fetch('/api/auth/signout', {+ method: 'POST',+ credentials: 'include',+ }).catch(() => {});+}++/** @returns {Promise<object|null>} */+export async function getCurrentUser() {+ 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;+ }+}++/**+ * Attaches click handler + swaps UI for signed-in chip.+ * @param {HTMLElement} buttonEl+ */+export function wireSigninButton(buttonEl) {+ getCurrentUser().then((user) => {+ if (user) {+ _renderChip(buttonEl, user);+ } else {+ _wireClickHandler(buttonEl);+ }+ });+}++// ─── Internal ────────────────────────────────────────────────────────────────++function _shortAddr(addr) {+ return `${addr.slice(0, 6)}…${addr.slice(-4)}`;+}++function _renderChip(buttonEl, user) {+ const addr = user.wallet_address || '';+ const label = addr ? _shortAddr(addr) : user.display_name || 'Account';++ const chip = document.createElement('span');+ chip.id = 'wallet-chip';+ chip.style.cssText =+ 'display:inline-flex;align-items:center;gap:0.5em;font-size:0.85em;cursor:default;';++ const addrSpan = document.createElement('span');+ addrSpan.textContent = label;+ addrSpan.title = addr;++ const divider = document.createElement('span');+ divider.textContent = '·';+ divider.style.opacity = '0.4';++ const signOutBtn = document.createElement('button');+ signOutBtn.textContent = 'sign out';+ signOutBtn.style.cssText =+ 'background:none;border:none;padding:0;cursor:pointer;text-decoration:underline;font-size:inherit;color:inherit;';+ signOutBtn.addEventListener('click', async () => {+ signOutBtn.disabled = true;+ signOutBtn.textContent = 'signing out…';+ await signOut();+ location.reload();+ });++ chip.append(addrSpan, divider, signOutBtn);+ buttonEl.replaceWith(chip);+}++function _wireClickHandler(buttonEl) {+ const statusEl = document.createElement('span');+ statusEl.style.cssText = 'display:none;font-size:0.8em;margin-left:0.75em;opacity:0.7;';+ buttonEl.insertAdjacentElement('afterend', statusEl);++ let _busy = false;++ buttonEl.addEventListener('click', async () => {+ if (_busy) return;++ if (!window.ethereum && !isPrivyConfigured()) {+ statusEl.style.display = 'inline';+ statusEl.textContent =+ 'No wallet detected — install MetaMask or use a wallet-enabled browser.';+ return;+ }++ _busy = true;+ buttonEl.disabled = true;+ statusEl.style.display = 'inline';+ statusEl.textContent = 'Waiting for wallet…';++ try {+ await signInWithWallet();+ statusEl.textContent = 'Signed in — reloading…';+ location.reload();+ } catch (err) {+ statusEl.textContent = err.message || 'Sign-in failed.';+ buttonEl.disabled = false;+ _busy = false;+ }+ });+}diff --git a/vercel.json b/vercel.jsonindex 726eed2c0..ab6026092 100644--- a/vercel.json+++ b/vercel.json@@ -34,6 +34,7 @@{ "src": "/studio/(.*)", "dest": "/public/studio/$1" },{ "src": "/api/agents/me", "dest": "/api/agents" },+ { "src": "/api/agents/suggest", "dest": "/api/agents/suggest" },{ "src": "/api/agents/by-wallet", "dest": "/api/agents/by-wallet" },{ "src": "/api/agents/by-address/([^/]+)", "dest": "/api/agents/by-address/[addr]?addr=$1" },{ "src": "/api/agents/([^/]+)/wallet", "dest": "/api/agents/[id]" },