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
feat: bazaar arbitrage/providers/context, forever inscriptions, vite+vercel routing
nirholasf7cca20602d2
diff --git a/.prettierignore b/.prettierignoreindex aa4e98a30..9cb062f8e 100644--- a/.prettierignore+++ b/.prettierignore@@ -14,3 +14,5 @@ public/embed-sdk.jspublic/embed.jspublic/wallet-login.jspublic/artifact.js+public/bazaar.js+public/bazaar.htmldiff --git a/agent-ui-sdk/src/renderer.js b/agent-ui-sdk/src/renderer.jsindex 1c8742a6b..f4edba321 100644--- a/agent-ui-sdk/src/renderer.js+++ b/agent-ui-sdk/src/renderer.js@@ -101,6 +101,7 @@ export function createRenderer({window.removeEventListener('resize', resize);if (mouseMoveHandler) window.removeEventListener('mousemove', mouseMoveHandler);renderer.dispose();+ renderer.forceContextLoss?.();if (ownsCanvas) canvas.remove();}diff --git a/api/bazaar/arbitrage.js b/api/bazaar/arbitrage.jsnew file mode 100644index 000000000..6407ffcc2--- /dev/null+++ b/api/bazaar/arbitrage.js@@ -0,0 +1,238 @@+// GET /api/bazaar/arbitrage+//+// Surfaces cross-venue / cross-provider price disparities across the merged+// x402 facilitator catalog. We group listings by a derived "capability key"+// (MCP tool name, or normalized HTTP service name / URL tail), then keep+// groups that (a) have at least two listings, (b) span more than one+// provider host or facilitator, and (c) carry a non-zero USDC price spread.+// The result is the x402 analog of a cross-venue arbitrage view: same+// thing, different price.+//+// Query params:+// minSpreadPct — discard groups whose max/min - 1 is below this (default 0)+// minProviders — require at least this many distinct provider hosts (default 2)+// limit — cap returned opportunities (default 100, max 500)++import { cors, json, error, wrap } from '../_lib/http.js';+import { Bazaar } from '../_lib/x402/bazaar-client.js';++const STOP_WORDS = new Set([+ 'api', 'apis', 'service', 'endpoint', 'endpoints', 'paid', 'free',+ 'the', 'a', 'an', 'and', 'or', 'of', 'for', 'to', 'on', 'in', 'by',+ 'tool', 'tools', 'mcp', 'http',+]);++function normalizeWord(s) {+ return String(s || '').toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '').trim();+}++function tokenize(s) {+ return String(s || '')+ .toLowerCase()+ .split(/[^a-z0-9]+/g)+ .map((w) => w.trim())+ .filter((w) => w && !STOP_WORDS.has(w) && w.length >= 2);+}++// Many facilitators (orbisapi, hyreagent…) ship empty serviceName and put+// the capability in the URL path with a random suffix:+// /proxy/who-to-contact-api-97ccc0 → "who-to-contact-api"+// Strip a single trailing hash-like segment so the same logical capability+// hosted by different providers collapses to the same key.+function tailFromUrl(url) {+ try {+ const u = new URL(url);+ const tail = u.pathname.replace(/\/+$/, '').split('/').filter(Boolean).pop() || '';+ return tail.replace(/-[a-z0-9]{4,12}$/i, '');+ } catch {+ return '';+ }+}++function capabilityKey(it) {+ if (it.type === 'mcp' && it.toolName) {+ const k = normalizeWord(it.toolName);+ return k ? `mcp:${k}` : null;+ }+ // Prefer serviceName; single-token names are fine because the facilitator+ // chose them deliberately. URL-derived keys are noisier — a single short+ // path like /buy collides across totally unrelated services, so require+ // at least two informative tokens before treating them as a capability.+ const nameTokens = tokenize(it.serviceName).slice(0, 3);+ if (nameTokens.length && nameTokens.join('-').length >= 3) return `http:${nameTokens.join('-')}`;+ const urlTokens = tokenize(tailFromUrl(it.resource)).slice(0, 3);+ if (urlTokens.length >= 2 && urlTokens.join('-').length >= 6) return `http:${urlTokens.join('-')}`;+ return null;+}++function hostOf(url) {+ try { return new URL(url).host; } catch { return ''; }+}++function usdcAccepts(accepts) {+ return (accepts || []).filter((a) => {+ const sym = String(a?.assetInfo?.symbol || '').toUpperCase();+ return sym === 'USDC' || sym === '';+ });+}++function minUsdcAtomic(item) {+ const ok = usdcAccepts(item.accepts);+ if (ok.length === 0) return null;+ let min = null;+ for (const a of ok) {+ const n = Number(a.amountAtomic);+ if (Number.isFinite(n) && n > 0 && (min == null || n < min)) min = n;+ }+ return min;+}++function priceLabel(atomic) {+ const n = atomic / 1_000_000;+ if (n < 0.01) return `${n.toFixed(6).replace(/0+$/, '').replace(/\.$/, '')} USDC`;+ if (n < 1) return `${n.toFixed(4).replace(/0+$/, '').replace(/\.$/, '')} USDC`;+ return `${n.toFixed(2)} USDC`;+}++async function handler(req, res) {+ if (cors(req, res, { origins: '*', methods: 'GET,OPTIONS' })) return;+ if (req.method !== 'GET') return error(res, 405, 'method_not_allowed', 'GET only');++ const url = new URL(req.url, 'http://x');+ const minSpreadPct = clampNum(url.searchParams.get('minSpreadPct'), 0, 0, 10000);+ const minProviders = clampInt(url.searchParams.get('minProviders'), 2, 2, 10);+ const limit = clampInt(url.searchParams.get('limit'), 100, 1, 500);++ const baz = new Bazaar();+ let httpRes, mcpRes;+ try {+ [httpRes, mcpRes] = await Promise.all([+ baz.list({ type: 'http', maxItems: 3000 }),+ baz.list({ type: 'mcp', maxItems: 3000 }),+ ]);+ } catch (e) {+ return error(res, 502, 'facilitator_error', String(e?.message || e));+ }++ const items = [...(httpRes.items || []), ...(mcpRes.items || [])];++ const groups = new Map();+ for (const it of items) {+ const k = capabilityKey(it);+ if (!k) continue;+ const usdc = minUsdcAtomic(it);+ if (usdc == null) continue;+ if (!groups.has(k)) groups.set(k, []);+ groups.get(k).push({ it, usdc });+ }++ const opps = [];+ for (const [key, list] of groups) {+ if (list.length < 2) continue;+ const hosts = new Set(list.map(({ it }) => hostOf(it.resource)).filter(Boolean));+ const facilitators = new Set(list.map(({ it }) => hostOf(it.facilitator)).filter(Boolean));+ // Internal pricing tiers on a single host aren't arbitrage; require+ // at least two distinct hosts OR two distinct facilitators.+ if (hosts.size < minProviders && facilitators.size < 2) continue;++ const prices = list.map((x) => x.usdc);+ const minAtomic = Math.min(...prices);+ const maxAtomic = Math.max(...prices);+ if (maxAtomic === minAtomic) continue;+ const spreadAtomic = maxAtomic - minAtomic;+ const spreadPct = (spreadAtomic / minAtomic) * 100;+ if (spreadPct < minSpreadPct) continue;++ const cheapest = list.find((x) => x.usdc === minAtomic);+ const expensive = list.find((x) => x.usdc === maxAtomic);+ const ref = list.find((x) => x.it.serviceName) || list[0];+ const ref_it = ref.it;++ const providers = list+ .slice()+ .sort((a, b) => a.usdc - b.usdc)+ .map(({ it, usdc }) => ({+ host: hostOf(it.resource),+ facilitator: hostOf(it.facilitator),+ resource: it.resource,+ toolName: it.toolName || null,+ serviceName: it.serviceName || null,+ type: it.type,+ priceAtomic: usdc,+ priceLabel: priceLabel(usdc),+ networks: it.networks || [],+ iconUrl: it.iconUrl || null,+ }));++ const tagSet = new Set();+ for (const { it } of list) for (const t of it.tags || []) tagSet.add(t);++ opps.push({+ key,+ type: ref_it.type,+ capability: ref_it.toolName || ref_it.serviceName || key.split(':')[1].replace(/-/g, ' '),+ serviceName: ref_it.serviceName || null,+ description: ref_it.description || '',+ iconUrl: ref_it.iconUrl || null,+ tags: [...tagSet].slice(0, 6),+ providerCount: hosts.size,+ facilitatorCount: facilitators.size,+ listingCount: list.length,+ minPriceAtomic: minAtomic,+ maxPriceAtomic: maxAtomic,+ minPriceLabel: priceLabel(minAtomic),+ maxPriceLabel: priceLabel(maxAtomic),+ spreadAtomic,+ spreadPct,+ cheapest: {+ host: hostOf(cheapest.it.resource),+ facilitator: hostOf(cheapest.it.facilitator),+ resource: cheapest.it.resource,+ toolName: cheapest.it.toolName || null,+ priceLabel: priceLabel(cheapest.usdc),+ },+ mostExpensive: {+ host: hostOf(expensive.it.resource),+ facilitator: hostOf(expensive.it.facilitator),+ resource: expensive.it.resource,+ toolName: expensive.it.toolName || null,+ priceLabel: priceLabel(expensive.usdc),+ },+ providers,+ });+ }++ // Largest absolute spread first; spread % is the tiebreaker so+ // micro-priced groups with big ratios don't bury larger-stake ones.+ opps.sort((a, b) => {+ if (b.spreadAtomic !== a.spreadAtomic) return b.spreadAtomic - a.spreadAtomic;+ return b.spreadPct - a.spreadPct;+ });++ const trimmed = opps.slice(0, limit);++ res.setHeader('cache-control', 'public, max-age=30, stale-while-revalidate=120');+ return json(res, 200, {+ count: trimmed.length,+ totalGroups: opps.length,+ opportunities: trimmed,+ updatedAt: new Date().toISOString(),+ sources: [+ ...(httpRes.sources || []).map((s) => ({ ...s, type: 'http' })),+ ...(mcpRes.sources || []).map((s) => ({ ...s, type: 'mcp' })),+ ],+ });+}++function clampInt(v, fallback, min, max) {+ const n = Number(v);+ if (!Number.isFinite(n)) return fallback;+ return Math.max(min, Math.min(max, Math.floor(n)));+}+function clampNum(v, fallback, min, max) {+ const n = Number(v);+ if (!Number.isFinite(n)) return fallback;+ return Math.max(min, Math.min(max, n));+}++export default wrap(handler);diff --git a/api/bazaar/context.js b/api/bazaar/context.jsnew file mode 100644index 000000000..b94b56c02--- /dev/null+++ b/api/bazaar/context.js@@ -0,0 +1,326 @@+// GET /api/bazaar/context?resource=<url>[&toolName=<name>]+//+// Produces a Hunch-style "What's the context?" panel for a single x402+// service. We pull the merged catalog, locate the item, gather peers (same+// capability and same provider), then ask Claude to write 2–3 sentences+// grounded in inline [n] citations that the UI renders as chips.+//+// Falls back to a deterministic, citation-only summary if no+// ANTHROPIC_API_KEY is configured or the upstream call fails — the panel+// should always render something useful.++import { cors, json, error, wrap } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { Bazaar } from '../_lib/x402/bazaar-client.js';++const STOP_WORDS = new Set([+ 'api', 'apis', 'service', 'endpoint', 'endpoints', 'paid', 'free',+ 'the', 'a', 'an', 'and', 'or', 'of', 'for', 'to', 'on', 'in', 'by',+ 'tool', 'tools', 'mcp', 'http',+]);++function tokenize(s) {+ return String(s || '')+ .toLowerCase()+ .split(/[^a-z0-9]+/g)+ .map((w) => w.trim())+ .filter((w) => w && !STOP_WORDS.has(w) && w.length >= 2);+}++function tailFromUrl(url) {+ try {+ const u = new URL(url);+ const tail = u.pathname.replace(/\/+$/, '').split('/').filter(Boolean).pop() || '';+ return tail.replace(/-[a-z0-9]{4,12}$/i, '');+ } catch {+ return '';+ }+}++function capabilityKey(it) {+ if (it.type === 'mcp' && it.toolName) {+ return `mcp:${tokenize(it.toolName).join('')}`;+ }+ const nameTokens = tokenize(it.serviceName).slice(0, 3);+ if (nameTokens.length && nameTokens.join('-').length >= 3) return `http:${nameTokens.join('-')}`;+ const urlTokens = tokenize(tailFromUrl(it.resource)).slice(0, 3);+ if (urlTokens.length >= 2 && urlTokens.join('-').length >= 6) return `http:${urlTokens.join('-')}`;+ return null;+}++function hostOf(url) {+ try { return new URL(url).host; } catch { return ''; }+}++function minUsdcAtomic(item) {+ const accepts = (item.accepts || []).filter((a) => {+ const sym = String(a?.assetInfo?.symbol || '').toUpperCase();+ return sym === 'USDC' || sym === '';+ });+ if (accepts.length === 0) return null;+ let min = null;+ for (const a of accepts) {+ const n = Number(a.amountAtomic);+ if (Number.isFinite(n) && n > 0 && (min == null || n < min)) min = n;+ }+ return min;+}++function priceLabel(atomic) {+ if (atomic == null) return '—';+ const n = atomic / 1_000_000;+ if (n === 0) return '0 USDC';+ if (n < 0.01) return `${n.toFixed(6).replace(/0+$/, '').replace(/\.$/, '')} USDC`;+ if (n < 1) return `${n.toFixed(4).replace(/0+$/, '').replace(/\.$/, '')} USDC`;+ return `${n.toFixed(2)} USDC`;+}++function percentile(sortedAsc, value) {+ if (!sortedAsc.length) return null;+ let i = 0;+ while (i < sortedAsc.length && sortedAsc[i] <= value) i++;+ return Math.round((i / sortedAsc.length) * 100);+}++// Citations is an authored list of {label, url, kind} the model must+// reference by 1-based index. Building it server-side guarantees every+// [n] in the response maps to a real anchor and keeps the LLM from+// hallucinating URLs.+function buildCitations({ target, peers, providerSiblings }) {+ const cits = [];+ if (peers.length) {+ cits.push({+ label: `${peers.length} peer ${peers.length === 1 ? 'listing' : 'listings'}`,+ url: `/bazaar?q=${encodeURIComponent(target.serviceName || target.toolName || '')}`,+ kind: 'peers',+ });+ }+ const host = hostOf(target.resource);+ if (host) {+ cits.push({+ label: host,+ url: `/providers?host=${encodeURIComponent(host)}`,+ kind: 'provider',+ });+ }+ const fac = hostOf(target.facilitator);+ if (fac) {+ cits.push({+ label: fac,+ url: `https://${fac}/discovery/resources`,+ kind: 'facilitator',+ external: true,+ });+ }+ if (providerSiblings.length) {+ cits.push({+ label: `${providerSiblings.length} other ${providerSiblings.length === 1 ? 'service' : 'services'} from this provider`,+ url: `/providers?host=${encodeURIComponent(host)}`,+ kind: 'siblings',+ });+ }+ return cits;+}++function deterministicSummary({ target, targetPrice, peerPrices, providerSiblings, citations }) {+ const sentences = [];+ const peerCount = peerPrices.length;+ const name = target.serviceName || target.toolName || hostOf(target.resource) || 'this service';++ if (peerCount > 0) {+ const sorted = [...peerPrices].sort((a, b) => a - b);+ const pct = percentile(sorted, targetPrice ?? Infinity);+ if (targetPrice != null && pct != null) {+ if (pct <= 25) sentences.push(`${name} is priced in the cheapest 25% of comparable listings [1].`);+ else if (pct >= 75) sentences.push(`${name} sits in the priciest tier among comparable listings [1].`);+ else sentences.push(`${name}'s price sits in the middle of the ${peerCount + 1}-listing peer set [1].`);+ } else {+ sentences.push(`${peerCount + 1} listings cover this capability across the catalog [1].`);+ }+ }++ const host = hostOf(target.resource);+ if (host) {+ if (providerSiblings.length > 0) {+ sentences.push(`Operated by ${host} [2], which exposes ${providerSiblings.length + 1} paid endpoints in the catalog [4].`);+ } else {+ sentences.push(`Operated by ${host} [2], a single-endpoint provider in the current catalog.`);+ }+ }++ const fac = hostOf(target.facilitator);+ if (fac && sentences.length < 3) {+ sentences.push(`Listing currently surfaced via ${fac} [3].`);+ }++ let sentiment = 'neutral';+ if (peerCount && targetPrice != null) {+ const sorted = [...peerPrices].sort((a, b) => a - b);+ const pct = percentile(sorted, targetPrice);+ if (pct != null) {+ if (pct <= 25) sentiment = 'up';+ else if (pct >= 75) sentiment = 'down';+ }+ }++ return {+ summary: sentences.join(' ') || `${name} is listed at ${priceLabel(targetPrice)}.`,+ sentiment,+ citations,+ source: 'deterministic',+ };+}++async function llmSummary({ target, targetPrice, peers, providerSiblings, citations }) {+ const peerLines = peers.slice(0, 8).map((p) => {+ const price = priceLabel(minUsdcAtomic(p));+ return `- ${p.serviceName || p.toolName || '(unnamed)'} @ ${hostOf(p.resource)} — ${price} via ${hostOf(p.facilitator)}`;+ }).join('\n') || '(none discovered)';++ const siblingLines = providerSiblings.slice(0, 8).map((p) => {+ const price = priceLabel(minUsdcAtomic(p));+ return `- ${p.serviceName || p.toolName || p.resource} — ${price}`;+ }).join('\n') || '(none)';++ const citationLines = citations.map((c, i) => `[${i + 1}] ${c.label} — ${c.url}`).join('\n');++ const prompt = `You write the "What's the context?" panel for an x402 paid API listing — a brief, grounded analysis that tells a builder why this listing is interesting right now.++# Rules+- 2 to 3 sentences total, no more.+- Cite every concrete claim with [n] where n is one of the provided citation indices. Do not invent new ones.+- Lead with the most useful comparison (price percentile vs peers, provider breadth, facilitator availability).+- No marketing language. Plain analyst tone.+- Output strict JSON only: {"summary": "...", "sentiment": "up"|"down"|"neutral"}.+ - "up" = this service looks attractively priced or uniquely positioned.+ - "down" = priced above peers or otherwise unfavorable.+ - "neutral" = neither.++# Target service+- Name: ${target.serviceName || target.toolName || '(unnamed)'}+- Resource: ${target.resource}+- Type: ${target.type}${target.toolName ? ` · tool: ${target.toolName}` : ''}+- Provider host: ${hostOf(target.resource)}+- Facilitator host: ${hostOf(target.facilitator)}+- Networks: ${(target.networks || []).join(', ') || '—'}+- Price (min USDC across accepts): ${priceLabel(targetPrice)}+- Description: ${target.description || '(none)'}+- Tags: ${(target.tags || []).join(', ') || '(none)'}++# Peer services (same capability)+${peerLines}++# Other services from the same provider+${siblingLines}++# Available citations (cite by index)+${citationLines}++Respond with only the JSON object.`;++ const apiKey = env.ANTHROPIC_API_KEY;+ if (!apiKey) throw new Error('no_anthropic_key');++ const upstream = await fetch('https://api.anthropic.com/v1/messages', {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ 'anthropic-version': '2023-06-01',+ 'x-api-key': apiKey,+ },+ body: JSON.stringify({+ model: 'claude-haiku-4-5-20251001',+ max_tokens: 400,+ temperature: 0.2,+ messages: [{ role: 'user', content: prompt }],+ }),+ });++ if (!upstream.ok) {+ const body = await upstream.text().catch(() => '');+ throw new Error(`anthropic ${upstream.status}: ${body.slice(0, 200)}`);+ }+ const data = await upstream.json();+ const text = data?.content?.[0]?.text || '';+ const match = text.match(/\{[\s\S]*\}/);+ if (!match) throw new Error('no JSON in LLM response');+ const parsed = JSON.parse(match[0]);+ const summary = String(parsed.summary || '').trim();+ if (!summary) throw new Error('empty summary');+ const sentiment = ['up', 'down', 'neutral'].includes(parsed.sentiment) ? parsed.sentiment : 'neutral';+ return { summary, sentiment, citations, source: 'claude' };+}++async function handler(req, res) {+ if (cors(req, res, { origins: '*', methods: 'GET,OPTIONS' })) return;+ if (req.method !== 'GET') return error(res, 405, 'method_not_allowed', 'GET only');++ const url = new URL(req.url, 'http://x');+ const resource = url.searchParams.get('resource');+ const toolName = url.searchParams.get('toolName') || '';+ if (!resource) return error(res, 400, 'bad_request', 'resource is required');++ const baz = new Bazaar();+ let httpRes, mcpRes;+ try {+ [httpRes, mcpRes] = await Promise.all([+ baz.list({ type: 'http', maxItems: 3000 }),+ baz.list({ type: 'mcp', maxItems: 3000 }),+ ]);+ } catch (e) {+ return error(res, 502, 'facilitator_error', String(e?.message || e));+ }+ const items = [...(httpRes.items || []), ...(mcpRes.items || [])];++ const wantKey = toolName ? `${resource}#${toolName}` : resource;+ const target = items.find((it) => it.uniqueKey === wantKey);+ if (!target) return error(res, 404, 'not_found', 'service not in current catalog');++ const targetPrice = minUsdcAtomic(target);+ const targetCapKey = capabilityKey(target);+ const targetHost = hostOf(target.resource);++ const peers = items.filter((it) => {+ if (it.uniqueKey === target.uniqueKey) return false;+ const k = capabilityKey(it);+ return k && k === targetCapKey;+ });++ const providerSiblings = items.filter(+ (it) => it.uniqueKey !== target.uniqueKey && hostOf(it.resource) === targetHost,+ );++ const peerPrices = peers.map(minUsdcAtomic).filter((n) => n != null);++ const citations = buildCitations({ target, peers, providerSiblings });++ let result;+ try {+ result = await llmSummary({ target, targetPrice, peers, providerSiblings, citations });+ } catch (e) {+ // Always return something useful — the panel is decorative if+ // missing and frustrating if it 500s.+ result = deterministicSummary({ target, targetPrice, peerPrices, providerSiblings, citations });+ result.fallbackReason = String(e?.message || e);+ }++ res.setHeader('cache-control', 'public, max-age=300, stale-while-revalidate=600');+ return json(res, 200, {+ ...result,+ stats: {+ peerCount: peers.length,+ peerPriceMinAtomic: peerPrices.length ? Math.min(...peerPrices) : null,+ peerPriceMaxAtomic: peerPrices.length ? Math.max(...peerPrices) : null,+ peerPriceMedianAtomic: peerPrices.length+ ? [...peerPrices].sort((a, b) => a - b)[Math.floor(peerPrices.length / 2)]+ : null,+ targetPriceAtomic: targetPrice,+ providerSiblingsCount: providerSiblings.length,+ pricePercentile: peerPrices.length && targetPrice != null+ ? percentile([...peerPrices, targetPrice].sort((a, b) => a - b), targetPrice)+ : null,+ },+ });+}++export default wrap(handler);diff --git a/api/bazaar/providers.js b/api/bazaar/providers.jsnew file mode 100644index 000000000..149639737--- /dev/null+++ b/api/bazaar/providers.js@@ -0,0 +1,173 @@+// GET /api/bazaar/providers+// GET /api/bazaar/providers?host=<host>+//+// Aggregates the merged x402 catalog into per-provider profiles. A "provider"+// is the host of the resource URL — the actual API operator, not the+// facilitator that listed it. Each provider profile carries enough data to+// drive a Hunch-style reputation card: service count, price band, dominant+// categories, networks, facilitators discovered on, and the underlying+// listings.++import { cors, json, error, wrap } from '../_lib/http.js';+import { Bazaar } from '../_lib/x402/bazaar-client.js';++function hostOf(url) {+ try { return new URL(url).host; } catch { return ''; }+}++function median(nums) {+ if (!nums.length) return 0;+ const sorted = [...nums].sort((a, b) => a - b);+ const mid = Math.floor(sorted.length / 2);+ return sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid];+}++function priceLabel(atomic) {+ const n = atomic / 1_000_000;+ if (n === 0) return '0 USDC';+ if (n < 0.01) return `${n.toFixed(6).replace(/0+$/, '').replace(/\.$/, '')} USDC`;+ if (n < 1) return `${n.toFixed(4).replace(/0+$/, '').replace(/\.$/, '')} USDC`;+ return `${n.toFixed(2)} USDC`;+}++function minUsdcAtomic(item) {+ const accepts = (item.accepts || []).filter((a) => {+ const sym = String(a?.assetInfo?.symbol || '').toUpperCase();+ return sym === 'USDC' || sym === '';+ });+ if (accepts.length === 0) return null;+ let min = null;+ for (const a of accepts) {+ const n = Number(a.amountAtomic);+ if (Number.isFinite(n) && n > 0 && (min == null || n < min)) min = n;+ }+ return min;+}++function summarize(host, items) {+ const prices = items.map(minUsdcAtomic).filter((n) => n != null);+ const tagFreq = new Map();+ const netSet = new Set();+ const facSet = new Set();+ const typeFreq = { http: 0, mcp: 0 };+ let icon = null;+ for (const it of items) {+ if (!icon && it.iconUrl) icon = it.iconUrl;+ typeFreq[it.type] = (typeFreq[it.type] || 0) + 1;+ for (const t of it.tags || []) tagFreq.set(t, (tagFreq.get(t) || 0) + 1);+ for (const n of it.networks || []) netSet.add(n);+ const fac = hostOf(it.facilitator);+ if (fac) facSet.add(fac);+ }+ const topTags = [...tagFreq.entries()].sort((a, b) => b[1] - a[1]).slice(0, 5).map(([t]) => t);++ const minA = prices.length ? Math.min(...prices) : null;+ const maxA = prices.length ? Math.max(...prices) : null;+ const medA = prices.length ? median(prices) : null;++ return {+ host,+ iconUrl: icon,+ serviceCount: items.length,+ httpCount: typeFreq.http || 0,+ mcpCount: typeFreq.mcp || 0,+ networks: [...netSet],+ facilitators: [...facSet],+ topTags,+ minPriceAtomic: minA,+ maxPriceAtomic: maxA,+ medianPriceAtomic: medA,+ minPriceLabel: minA != null ? priceLabel(minA) : null,+ maxPriceLabel: maxA != null ? priceLabel(maxA) : null,+ medianPriceLabel: medA != null ? priceLabel(medA) : null,+ };+}++async function handler(req, res) {+ if (cors(req, res, { origins: '*', methods: 'GET,OPTIONS' })) return;+ if (req.method !== 'GET') return error(res, 405, 'method_not_allowed', 'GET only');++ const url = new URL(req.url, 'http://x');+ const wantHost = (url.searchParams.get('host') || '').toLowerCase().trim();+ const limit = clampInt(url.searchParams.get('limit'), 200, 1, 1000);++ const baz = new Bazaar();+ let httpRes, mcpRes;+ try {+ [httpRes, mcpRes] = await Promise.all([+ baz.list({ type: 'http', maxItems: 3000 }),+ baz.list({ type: 'mcp', maxItems: 3000 }),+ ]);+ } catch (e) {+ return error(res, 502, 'facilitator_error', String(e?.message || e));+ }++ const items = [...(httpRes.items || []), ...(mcpRes.items || [])];++ const byHost = new Map();+ for (const it of items) {+ const h = hostOf(it.resource);+ if (!h) continue;+ if (!byHost.has(h)) byHost.set(h, []);+ byHost.get(h).push(it);+ }++ if (wantHost) {+ const matched = byHost.get(wantHost);+ if (!matched || matched.length === 0) {+ return error(res, 404, 'not_found', `no listings for host ${wantHost}`);+ }+ const summary = summarize(wantHost, matched);++ // Listings sorted cheap → expensive so the profile reads like a price+ // ladder. Unknown-price items sink to the bottom.+ const listings = matched+ .map((it) => ({ it, p: minUsdcAtomic(it) }))+ .sort((a, b) => {+ if (a.p == null && b.p == null) return 0;+ if (a.p == null) return 1;+ if (b.p == null) return -1;+ return a.p - b.p;+ })+ .map(({ it, p }) => ({+ type: it.type,+ resource: it.resource,+ toolName: it.toolName || null,+ serviceName: it.serviceName || null,+ description: it.description || '',+ iconUrl: it.iconUrl || null,+ tags: it.tags || [],+ networks: it.networks || [],+ method: it.method || null,+ facilitator: hostOf(it.facilitator),+ priceAtomic: p,+ priceLabel: p != null ? priceLabel(p) : null,+ accepts: it.accepts,+ extensions: it.extensions || [],+ }));++ res.setHeader('cache-control', 'public, max-age=30, stale-while-revalidate=120');+ return json(res, 200, { ...summary, listings });+ }++ const providers = [...byHost.entries()]+ .map(([h, list]) => summarize(h, list))+ .sort((a, b) => b.serviceCount - a.serviceCount)+ .slice(0, limit);++ res.setHeader('cache-control', 'public, max-age=30, stale-while-revalidate=120');+ return json(res, 200, {+ count: providers.length,+ totalProviders: byHost.size,+ providers,+ updatedAt: new Date().toISOString(),+ });+}++function clampInt(v, fallback, min, max) {+ const n = Number(v);+ if (!Number.isFinite(n)) return fallback;+ return Math.max(min, Math.min(max, Math.floor(n)));+}++export default wrap(handler);diff --git a/api/forever/inscribe.js b/api/forever/inscribe.jsnew file mode 100644index 000000000..df3da306e--- /dev/null+++ b/api/forever/inscribe.js@@ -0,0 +1,206 @@+// POST /api/forever/inscribe+//+// Creates a real Bitcoin text inscription via OrdinalsBot. The message is+// embedded into a Taproot witness on Bitcoin mainnet, where it lives forever.+//+// Body: { message: string, receiveAddress?: string, feeRate?: number }+// - message: 1–1500 chars of UTF-8 text to inscribe+// - receiveAddress: optional Taproot (bc1p…) address that receives the+// inscription. If omitted, falls back to the platform vault address+// (env.BTC_INSCRIPTION_RECEIVE_ADDRESS).+// - feeRate: optional sats/vB. Defaults to 8 (medium). Range 1–200.+//+// Response 200:+// { orderId, charge: { address, amount, currency, lightning_invoice? },+// receiveAddress, feeRate, sizeBytes, mempoolUrl, ordinalsUrl?, status }+//+// Errors:+// 400 — invalid message / address / fee rate+// 502 — OrdinalsBot upstream error+// 503 — receive address not configured and none provided++import { cors, error, json, readJson } from '../_lib/http.js';++const ORDINALSBOT_BASE_URL =+ process.env.ORDINALSBOT_BASE_URL || 'https://api.ordinalsbot.com';++const MAX_MESSAGE_BYTES = 1500;+const MIN_FEE_RATE = 1;+const MAX_FEE_RATE = 200;+const DEFAULT_FEE_RATE = 8;++// Bitcoin Taproot (P2TR / bc1p…) — the only address class OrdinalsBot will+// send inscriptions to. Mainnet HRP "bc", witness version 1, bech32m, 62 chars.+const TAPROOT_RE = /^bc1p[02-9ac-hj-np-z]{58}$/;++function validateMessage(raw) {+ if (typeof raw !== 'string') {+ return { error: 'message must be a string' };+ }+ const message = raw.trim();+ if (message.length === 0) {+ return { error: 'message cannot be empty' };+ }+ const bytes = Buffer.byteLength(message, 'utf8');+ if (bytes > MAX_MESSAGE_BYTES) {+ return {+ error: `message too long: ${bytes} bytes (max ${MAX_MESSAGE_BYTES})`,+ };+ }+ return { message, bytes };+}++function validateAddress(raw) {+ if (!raw) return { address: null };+ if (typeof raw !== 'string') return { error: 'receiveAddress must be a string' };+ const address = raw.trim();+ if (!TAPROOT_RE.test(address)) {+ return {+ error:+ 'receiveAddress must be a Bitcoin Taproot address (bc1p…). Ordinals can only be received by Taproot wallets.',+ };+ }+ return { address };+}++function validateFeeRate(raw) {+ if (raw === undefined || raw === null || raw === '') {+ return { feeRate: DEFAULT_FEE_RATE };+ }+ const n = Number(raw);+ if (!Number.isFinite(n) || !Number.isInteger(n)) {+ return { error: 'feeRate must be an integer' };+ }+ if (n < MIN_FEE_RATE || n > MAX_FEE_RATE) {+ return { error: `feeRate must be between ${MIN_FEE_RATE} and ${MAX_FEE_RATE} sats/vB` };+ }+ return { feeRate: n };+}++function buildTextDataURL(message) {+ const base64 = Buffer.from(message, 'utf8').toString('base64');+ return `data:text/plain;charset=utf-8;base64,${base64}`;+}++async function createOrdinalsBotOrder({ message, receiveAddress, feeRate }) {+ const sizeBytes = Buffer.byteLength(message, 'utf8');+ const body = {+ files: [+ {+ name: 'forever.txt',+ size: sizeBytes,+ type: 'text/plain;charset=utf-8',+ dataURL: buildTextDataURL(message),+ },+ ],+ receiveAddress,+ fee: feeRate,+ lowPostage: true,+ };+ const headers = { 'content-type': 'application/json' };+ if (process.env.ORDINALSBOT_API_KEY) {+ headers['x-api-key'] = process.env.ORDINALSBOT_API_KEY;+ }+ const res = await fetch(`${ORDINALSBOT_BASE_URL}/order`, {+ method: 'POST',+ headers,+ body: JSON.stringify(body),+ });+ const text = await res.text();+ let data;+ try {+ data = JSON.parse(text);+ } catch {+ const err = new Error(`OrdinalsBot returned non-JSON (${res.status})`);+ err.status = 502;+ err.upstream = text.slice(0, 300);+ throw err;+ }+ if (!res.ok || data.status === 'error') {+ const err = new Error(data.message || data.error || `OrdinalsBot returned ${res.status}`);+ err.status = res.status >= 500 ? 502 : res.status || 502;+ err.upstream = data;+ throw err;+ }+ return data;+}++function shapeChargeResponse(order, { receiveAddress, feeRate, sizeBytes }) {+ const charge = order.charge || {};+ const address = charge.address || order.payAddress;+ const amount = Number(charge.amount ?? order.fileCost ?? 0);+ const lightning = charge.lightning_invoice || charge.lightningInvoice || null;+ const status = order.status || charge.status || 'pending';++ return {+ orderId: order.id || order.orderId,+ status,+ charge: {+ address,+ amount,+ amountBtc: amount ? amount / 1e8 : null,+ currency: 'BTC',+ lightningInvoice:+ typeof lightning === 'object' && lightning ? lightning.payreq || null : lightning,+ expiresAt: charge.expires_at || charge.expiresAt || null,+ },+ receiveAddress,+ feeRate,+ sizeBytes,+ mempoolBaseUrl: 'https://mempool.space',+ ordinalsViewerBaseUrl: 'https://ordinals.com/inscription',+ };+}++export default async function handler(req, res) {+ if (cors(req, res, { origins: '*', methods: 'POST,OPTIONS' })) return;+ if (req.method !== 'POST') return error(res, 405, 'method_not_allowed', 'POST only');++ let body;+ try {+ body = await readJson(req);+ } catch (e) {+ return error(res, e.status || 400, 'bad_request', e.message || 'invalid request body');+ }++ const msg = validateMessage(body.message);+ if (msg.error) return error(res, 400, 'invalid_message', msg.error);++ const addr = validateAddress(body.receiveAddress);+ if (addr.error) return error(res, 400, 'invalid_receive_address', addr.error);++ const fee = validateFeeRate(body.feeRate);+ if (fee.error) return error(res, 400, 'invalid_fee_rate', fee.error);++ const receiveAddress =+ addr.address || process.env.BTC_INSCRIPTION_RECEIVE_ADDRESS || null;+ if (!receiveAddress) {+ return error(+ res,+ 503,+ 'no_receive_address',+ 'No Taproot receive address provided and BTC_INSCRIPTION_RECEIVE_ADDRESS is not configured. Send your bc1p… address in the request body.',+ );+ }++ let order;+ try {+ order = await createOrdinalsBotOrder({+ message: msg.message,+ receiveAddress,+ feeRate: fee.feeRate,+ });+ } catch (e) {+ return error(res, e.status || 502, 'inscription_failed', e.message, {+ upstream: e.upstream,+ });+ }++ const shaped = shapeChargeResponse(order, {+ receiveAddress,+ feeRate: fee.feeRate,+ sizeBytes: msg.bytes,+ });++ return json(res, 200, shaped);+}diff --git a/api/forever/status.js b/api/forever/status.jsnew file mode 100644index 000000000..916cbb9e6--- /dev/null+++ b/api/forever/status.js@@ -0,0 +1,147 @@+// GET /api/forever/status?id=<orderId>+//+// Returns the live status of an OrdinalsBot inscription order. Once paid ++// inscribed, the response includes the inscription ID, the reveal txid, and+// public viewer URLs (mempool.space, ordinals.com).+//+// Response 200:+// { orderId, state, paid, inscribed, charge?, inscription?, links }+//+// state ∈ "waiting-payment" | "payment-received" | "inscribing" |+// "inscribed" | "failed"++import { cors, error, json } from '../_lib/http.js';++const ORDINALSBOT_BASE_URL =+ process.env.ORDINALSBOT_BASE_URL || 'https://api.ordinalsbot.com';++function deriveState(order) {+ const raw = String(order.status || order.state || '').toLowerCase();+ if (['completed', 'inscribed', 'sent', 'delivered'].includes(raw)) return 'inscribed';+ if (['failed', 'cancelled', 'canceled', 'expired', 'refunded'].includes(raw)) return 'failed';+ if (['inscribing', 'broadcasted', 'broadcasting', 'mining', 'paid'].includes(raw))+ return 'inscribing';+ if (['payment-received', 'underpaid', 'overpaid', 'processing'].includes(raw))+ return 'payment-received';+ if (order.tx && (order.tx.reveal || order.tx.commit)) return 'inscribing';+ if (order.inscription || order.inscriptionId || order.reveal) return 'inscribed';+ if (order.paid === true) return 'inscribing';+ return 'waiting-payment';+}++function pickInscriptionId(order) {+ return (+ order.inscriptionId ||+ order.inscription_id ||+ (order.inscription && (order.inscription.id || order.inscription.inscriptionId)) ||+ (order.files && order.files[0] && (order.files[0].inscriptionId || order.files[0].inscription_id)) ||+ null+ );+}++function pickRevealTxid(order) {+ if (order.tx && order.tx.reveal) return order.tx.reveal;+ if (order.revealTxId) return order.revealTxId;+ if (order.reveal && typeof order.reveal === 'string') return order.reveal;+ const id = pickInscriptionId(order);+ if (id && typeof id === 'string') {+ // Inscription IDs are formatted "<txid>i<index>".+ const match = id.match(/^([0-9a-f]{64})i\d+$/i);+ if (match) return match[1];+ }+ return null;+}++function pickCommitTxid(order) {+ if (order.tx && order.tx.commit) return order.tx.commit;+ if (order.commitTxId) return order.commitTxId;+ return null;+}++function buildLinks({ inscriptionId, revealTxid, commitTxid, chargeAddress }) {+ const links = {};+ if (inscriptionId) {+ links.inscription = `https://ordinals.com/inscription/${inscriptionId}`;+ links.inscriptionPreview = `https://ordinals.com/preview/${inscriptionId}`;+ }+ if (revealTxid) {+ links.revealTx = `https://mempool.space/tx/${revealTxid}`;+ }+ if (commitTxid) {+ links.commitTx = `https://mempool.space/tx/${commitTxid}`;+ }+ if (chargeAddress) {+ links.chargeAddress = `https://mempool.space/address/${chargeAddress}`;+ }+ return links;+}++async function fetchOrdinalsBotOrder(orderId) {+ const headers = {};+ if (process.env.ORDINALSBOT_API_KEY) {+ headers['x-api-key'] = process.env.ORDINALSBOT_API_KEY;+ }+ const url = `${ORDINALSBOT_BASE_URL}/order?id=${encodeURIComponent(orderId)}`;+ const res = await fetch(url, { headers });+ const text = await res.text();+ let data;+ try {+ data = JSON.parse(text);+ } catch {+ const err = new Error(`OrdinalsBot returned non-JSON (${res.status})`);+ err.status = 502;+ throw err;+ }+ if (!res.ok || data.status === 'error') {+ const err = new Error(data.message || data.error || `OrdinalsBot returned ${res.status}`);+ err.status = res.status === 404 ? 404 : 502;+ throw err;+ }+ return data;+}++export default async function handler(req, res) {+ if (cors(req, res, { origins: '*', methods: 'GET,OPTIONS' })) return;+ if (req.method !== 'GET') return error(res, 405, 'method_not_allowed', 'GET only');++ const url = new URL(req.url, 'http://localhost');+ const orderId = url.searchParams.get('id');+ if (!orderId) return error(res, 400, 'missing_id', 'query param "id" is required');++ let order;+ try {+ order = await fetchOrdinalsBotOrder(orderId);+ } catch (e) {+ return error(res, e.status || 502, 'status_lookup_failed', e.message);+ }++ const state = deriveState(order);+ const inscriptionId = pickInscriptionId(order);+ const revealTxid = pickRevealTxid(order);+ const commitTxid = pickCommitTxid(order);+ const charge = order.charge || {};+ const chargeAddress = charge.address || order.payAddress || null;++ return json(res, 200, {+ orderId,+ state,+ paid: state !== 'waiting-payment',+ inscribed: state === 'inscribed',+ charge: chargeAddress+ ? {+ address: chargeAddress,+ amount: Number(charge.amount ?? 0),+ amountBtc: Number(charge.amount ?? 0) / 1e8,+ paidAmount: Number(charge.paid_amount ?? charge.amount_received ?? 0),+ }+ : null,+ inscription: inscriptionId+ ? {+ id: inscriptionId,+ revealTxid,+ commitTxid,+ }+ : null,+ links: buildLinks({ inscriptionId, revealTxid, commitTxid, chargeAddress }),+ });+}diff --git a/character-studio/src/library/sceneInitializer.js b/character-studio/src/library/sceneInitializer.jsindex 730448c05..acbd8363f 100644--- a/character-studio/src/library/sceneInitializer.js+++ b/character-studio/src/library/sceneInitializer.js@@ -72,17 +72,6 @@ export function sceneInitializer(canvasId) {renderer.outputColorSpace = THREE.SRGBColorSpace;const clock = new THREE.Clock();- const animate = () => {- requestAnimationFrame(animate);- const delta = clock.getDelta();- controls.target.clamp(minPan, maxPan);- controls?.update();- characterManager.update(delta);- renderer.render(scene, camera);- };--- animate();const handleMouseClick = (event) => {const isCtrlPressed = event.ctrlKey;@@ -107,12 +96,34 @@ export function sceneInitializer(canvasId) {canvasRef.addEventListener("click", handleMouseClick);+ let animating = true;+ const animateLoop = () => {+ if (!animating) return;+ requestAnimationFrame(animateLoop);+ const delta = clock.getDelta();+ controls.target.clamp(minPan, maxPan);+ controls?.update();+ characterManager.update(delta);+ renderer.render(scene, camera);+ };+ animateLoop();++ function destroy() {+ animating = false;+ window.removeEventListener('resize', handleResize);+ canvasRef.removeEventListener('click', handleMouseClick);+ controls.dispose();+ renderer.dispose();+ renderer.forceContextLoss?.();+ }+return {scene,camera,controls,characterManager,sceneElements,- clock+ clock,+ destroy,};}diff --git a/character-studio/src/library/screenshotManager.js b/character-studio/src/library/screenshotManager.jsindex 61cb817c9..8f64cedae 100644--- a/character-studio/src/library/screenshotManager.js+++ b/character-studio/src/library/screenshotManager.js@@ -62,6 +62,11 @@ class PixelRenderer{render(){this.composer.render();}+ destroy(){+ this.composer.dispose?.();+ this.renderer.dispose();+ this.renderer.forceContextLoss?.();+ }}export class ScreenshotManager {@@ -319,4 +324,12 @@ export class ScreenshotManager {}}+ destroy() {+ this.pixelRenderer?.destroy();+ this.pixelRenderer = null;+ this.renderer.dispose();+ this.renderer.forceContextLoss?.();+ this.renderer = null;+ }+}diff --git a/character-studio/src/library/textureImageDataRenderer.js b/character-studio/src/library/textureImageDataRenderer.jsindex 3eed4be19..30bd2dc15 100644--- a/character-studio/src/library/textureImageDataRenderer.js+++ b/character-studio/src/library/textureImageDataRenderer.js@@ -155,6 +155,7 @@ export default class TextureImageDataRenderer {this.materials.length = 0this.quads.length = 0this.renderer?.dispose()+ this.renderer?.forceContextLoss?.()this.renderer = nullthis.rtTexture = null}diff --git a/docs/agent-manifest.md b/docs/agent-manifest.mdindex fc0c57960..ff8e07158 100644--- a/docs/agent-manifest.md+++ b/docs/agent-manifest.md@@ -44,7 +44,7 @@ The `<agent-3d>` element accepts several source forms. Priority when multiple at<agent-3d manifest="https://cdn.acme.com/aria/manifest.json"></agent-3d><!-- Backend agent ID (platform-hosted) -->-<agent-three.ws-id="aria-guide"></agent-3d>+<agent-3d agent-id="aria-guide"></agent-3d><!-- Bare GLB — no manifest, viewer mode only --><agent-3d body="./product.glb"></agent-3d>@@ -97,7 +97,7 @@ const manifest = await loadManifest('https://cdn.acme.com/aria/manifest.json');"brain": {"provider": "anthropic",- "model": "claude-opus-4-6",+ "model": "claude-opus-4-7","instructions": "instructions.md","temperature": 0.7,"maxTokens": 4096,@@ -251,7 +251,7 @@ LLM runtime configuration. When omitted, the agent is reactive-only (skills and| Field | Type | Required | Default | Description ||----------------|--------|----------|---------|-------------|| `provider` | string | Yes | `"none"` | `"anthropic"`, `"openai"`, `"local"`, or `"none"`. Use `"none"` for a purely reactive avatar. |-| `model` | string | No | — | Model ID, e.g. `"claude-opus-4-6"`. |+| `model` | string | No | — | Model ID, e.g. `"claude-opus-4-7"`. || `instructions` | string | No | — | Relative path to a Markdown file (`instructions.md`) that contains the system prompt. Frontmatter in the file can override any `brain.*` field. || `temperature` | number | No | 0.7 | LLM sampling temperature (0–1). || `maxTokens` | number | No | 4096 | Max tokens per response. |@@ -262,7 +262,7 @@ LLM runtime configuration. When omitted, the agent is reactive-only (skills and```markdown---name: Coach Leo-model: claude-opus-4-6+model: claude-opus-4-7temperature: 0.8---@@ -558,7 +558,7 @@ Load it:},"brain": {"provider": "anthropic",- "model": "claude-opus-4-6",+ "model": "claude-opus-4-7","instructions": "instructions.md","temperature": 0.8,"maxTokens": 2048@@ -598,7 +598,7 @@ Load it:},"brain": {"provider": "anthropic",- "model": "claude-opus-4-6",+ "model": "claude-opus-4-7","instructions": "instructions.md"},"voice": {diff --git a/docs/agent-system.md b/docs/agent-system.mdindex f8c2c8f6b..2acd115d8 100644--- a/docs/agent-system.md+++ b/docs/agent-system.md@@ -369,7 +369,7 @@ The minimum manifest to run an agent:},"brain": {"provider": "anthropic",- "model": "claude-opus-4-6",+ "model": "claude-opus-4-7","instructions": "You are Aria, a friendly guide. Be concise and helpful."},"voice": {@@ -400,7 +400,7 @@ A manifest with an on-chain identity, external skills, and ElevenLabs voice:},"brain": {"provider": "anthropic",- "model": "claude-opus-4-6",+ "model": "claude-opus-4-7","instructions": "instructions.md","temperature": 0.8},diff --git a/docs/api-reference.md b/docs/api-reference.mdindex 268a50716..a2dda9e7e 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -1,7 +1,11 @@-# API Reference+# REST API ReferenceBase URL: `https://three.ws/api`+> For the in-browser JavaScript API (the `<agent-3d>` element, `Viewer`, `Runtime`, `SceneController`, skills, memory), see [js-api.md](./js-api.md) and [web-component.md](./web-component.md). For the high-level npm SDK, see [sdk.md](./sdk.md).++The full machine-readable schema lives at [`https://three.ws/.well-known/openapi.yaml`](https://three.ws/.well-known/openapi.yaml). x402 paid endpoints are listed at [`/.well-known/x402.json`](https://three.ws/.well-known/x402.json) and the MCP endpoint is at [`/api/mcp`](https://three.ws/api/mcp).+---## Overview@@ -558,28 +562,60 @@ Usage events (token counts, latency, triggered actions) are recorded after each----### Anthropic LLM proxy+### Brain proxy (multi-provider LLM)```-POST /api/llm/anthropic?agent=<agent_id>+POST /api/brain/chat```-"We-pay" proxy to the Anthropic Messages API. Enforces the agent's embed policy (allowed origins, allowed surfaces, brain mode) and deducts from the agent's monthly token budget.+Server-Sent Events stream from a unified multi-provider LLM gateway. Used by the `<agent-3d>` element when `brain="…"` is set without a custom `key-proxy`. The "we-pay" mode deducts from the agent's monthly token budget and enforces the agent's embed policy (allowed origins, allowed surfaces).++**Request body**++```json+{+ "provider": "claude-sonnet-4-6",+ "messages": [{ "role": "user", "content": "Hello" }],+ "system": "You are a friendly product guide.",+ "maxTokens": 1024+}+```-Requires that the calling origin is listed in the agent's declared `origins`. Wildcard patterns are supported.+**Supported `provider` IDs**-**Supported models**+| Provider | Network | Tier |+|---|---|---|+| `claude-opus-4-7` | Anthropic | flagship |+| `claude-sonnet-4-6` | Anthropic | balanced |+| `claude-haiku-4-5` | Anthropic | fast |+| `gpt-4o` | OpenAI | flagship |+| `gpt-4o-mini` | OpenAI | fast |+| `qwen-*` | Qwen / Alibaba | varies |+| `openrouter:*` | OpenRouter (any) | varies |-| Model ID | Notes |-|----------|-------|-| `claude-opus-4-6` | |-| `claude-opus-4-7` | |-| `claude-sonnet-4-6` | |-| `claude-haiku-4-5` | |+Call `GET /api/brain/chat` for the live list of providers actually available on the current deployment (depends on which provider keys are configured).-Request and response format match the [Anthropic Messages API](https://docs.anthropic.com/en/api/messages) exactly. Upstream errors are sanitized before being returned to the client.+**Response (SSE)**++| Event | Payload |+|---|---|+| `meta` | `{ provider, label, network, model, tier }` |+| `first` | `{ firstTokenMs }` |+| (data) | JSON-encoded text chunk |+| `done` | `{ elapsedMs, firstTokenMs, usage }` |+| `error` | `{ message, elapsedMs }` |++**Rate limits:** Per-IP and per-agent limits apply in addition to the standard platform limits. Failed upstream calls automatically fall back to OpenRouter where possible.++---++### Direct Anthropic proxy (legacy)++```+POST /api/llm/anthropic?agent=<agent_id>+```-**Rate limits:** Per-IP and per-agent limits apply in addition to the standard platform limits.+Older single-provider proxy. Request/response shape matches the [Anthropic Messages API](https://docs.anthropic.com/en/api/messages) exactly. New integrations should use `/api/brain/chat` instead — it supports more providers and emits richer events.---@@ -975,7 +1011,7 @@ Responses always include `total`, `limit`, and `offset`.Use the official SDK instead of raw HTTP calls:```js-import { AgentAPI } from '@3dagent/sdk';+import { AgentAPI } from '@three-ws/sdk';const api = new AgentAPI({ apiKey: 'sk_live_xxxxx' });diff --git a/docs/changelog.md b/docs/changelog.mdindex b0df454c9..800f3540c 100644--- a/docs/changelog.md+++ b/docs/changelog.md@@ -15,7 +15,7 @@ three.ws follows [Semantic Versioning](https://semver.org/) (`MAJOR.MINOR.PATCH`| **Patch** | Bug fixes with no API changes | `1.5.1` |**Current platform version:** `1.5.1`-**Current SDK version (`@nirholas/agent-kit`):** `0.1.0`+**Current SDK version (`@three-ws/sdk`):** `0.1.0`The SDK is versioned independently from the platform. A platform patch release does not necessarily bump the SDK version if no public API changed.@@ -34,7 +34,7 @@ What counts as a breaking change:- Removing or renaming a web component attribute or property- Changing the agent manifest schema in a non-backwards-compatible way (field removal or rename)- Changing an API endpoint path, method, or response shape-- Removing a public export from `@nirholas/agent-kit`+- Removing a public export from `@three-ws/sdk`Adding new optional fields to manifests, new optional API response properties, or new SDK exports is **not** a breaking change.@@ -138,7 +138,7 @@ Entries are organized by release. Categories follow [Keep a Changelog](https://k----## SDK Changelog (`@nirholas/agent-kit`)+## SDK Changelog (`@three-ws/sdk`)The SDK is published separately. Its changelog lives at [sdk/CHANGELOG.md](../../sdk/CHANGELOG.md).@@ -210,7 +210,7 @@ ERC-8004 contracts are immutable after deployment. This is a property of the blo```js// All deployed contract addresses, by chain ID-import { REGISTRY_DEPLOYMENTS } from '@nirholas/agent-kit';+import { REGISTRY_DEPLOYMENTS } from '@three-ws/sdk';// Base Mainnetconsole.log(REGISTRY_DEPLOYMENTS[8453].identityRegistry);@@ -250,10 +250,10 @@ Agent manifests carry a `$schema` field that identifies the format version:```bash# Upgrade to latest-npm update @nirholas/agent-kit+npm update @three-ws/sdk# Pin to a specific version-npm install @nirholas/[email protected]+npm install @three-ws/[email protected]```### CDN embed@@ -264,7 +264,7 @@ Change the version number in the `src` attribute of your script tag. Before upgr```js// From the SDK-import { version } from '@nirholas/agent-kit';+import { version } from '@three-ws/sdk';console.log(version); // "0.1.0"// From the platform API@@ -299,7 +299,7 @@ For contributors and maintainers. A release follows these steps:7. `npm run publish-lib` copies the CDN bundle into `dist/agent-3d/{version}/`, generates an `integrity.json` sidecar with SHA-384 hashes, updates the rolling channel aliases (`1.5`, `1`, `latest`), and writes a `versions.json` manifest.8. Vercel auto-deploys from `main` and serves the updated `dist/` directory on the CDN.-The SDK (`@nirholas/agent-kit`) is published to npm separately:+The SDK (`@three-ws/sdk`) is published to npm separately:```bashcd sdk && npm publish@@ -310,5 +310,5 @@ cd sdk && npm publish## Staying Up to Date- **GitHub Releases** — Watch the repository and select "Releases only" to get an email for each new release.-- **npm outdated** — Add `npm outdated @nirholas/agent-kit` to your CI pipeline to detect available upgrades automatically.+- **npm outdated** — Add `npm outdated @three-ws/sdk` to your CI pipeline to detect available upgrades automatically.- **`versions.json`** — The CDN publishes a machine-readable index at `https://three.ws/agent-3d/versions.json` listing all available versions, channel aliases, and SRI hashes.diff --git a/docs/contributing.md b/docs/contributing.mdindex 774751df7..da065daec 100644--- a/docs/contributing.md+++ b/docs/contributing.md@@ -31,15 +31,15 @@ You don't have to write code to make an impact. Contributions take many forms:### Requirements-- Node.js ≥ 18-- A browser with WebGL 2.0 (Chrome, Firefox, or Edge)+- Node.js 24.x (the repo's `engines.node` pins to this)+- A browser with WebGL 2.0 (Chrome, Firefox, Safari 15+, or Edge)### Steps```bash# 1. Fork the repo on GitHub, then clone your fork-git clone https://github.com/YOUR_USERNAME/3dagent.git-cd 3dagent+git clone https://github.com/YOUR_USERNAME/three.ws.git+cd three.ws# 2. Install dependenciesnpm install@@ -262,7 +262,7 @@ The avatar asset library welcomes clothing, hair, accessories, and other charact## Reporting Bugs-Open a [GitHub issue](https://github.com/nirholas/3d-agent/issues/new) and include:+Open a [GitHub issue](https://github.com/nirholas/three.ws/issues/new) and include:- Browser and OS version- Steps to reproduce (numbered, specific)@@ -271,7 +271,7 @@ Open a [GitHub issue](https://github.com/nirholas/3d-agent/issues/new) and inclu- Console errors — screenshot or paste the full message- A link to a GLB file that triggers the issue, if relevant-Check [existing issues](https://github.com/nirholas/3d-agent/issues) before opening a new one to avoid duplicates.+Check [existing issues](https://github.com/nirholas/three.ws/issues) before opening a new one to avoid duplicates.**Security vulnerabilities:** Do NOT open a public issue. Follow the responsible disclosure process described in the [Security documentation](./security.md). Public disclosure of an unpatched vulnerability puts all users at risk.@@ -279,8 +279,8 @@ Check [existing issues](https://github.com/nirholas/3d-agent/issues) before open## Getting Help-- **[GitHub Discussions](https://github.com/nirholas/3d-agent/discussions)** — design questions, architecture ideas, general "how does X work"-- **[GitHub Issues](https://github.com/nirholas/3d-agent/issues)** — bug reports and concrete feature requests+- **[GitHub Discussions](https://github.com/nirholas/three.ws/discussions)** — design questions, architecture ideas, general "how does X work"+- **[GitHub Issues](https://github.com/nirholas/three.ws/issues)** — bug reports and concrete feature requests- **Discord** — real-time chat (link in the README)Core team response times: typically 2–3 business days on GitHub, faster in Discord. If a PR has been open for a week with no review, a polite ping in Discord is welcome.diff --git a/docs/deployment.md b/docs/deployment.mdindex da7239bcd..da4eebac1 100644--- a/docs/deployment.md+++ b/docs/deployment.md@@ -25,7 +25,7 @@ None of the optional layers (Redis, IPFS, blockchain relayer) are required to ruThe fastest route from zero to running:-[](https://vercel.com/new/clone?repository-url=https://github.com/nirholas/3d-agent)+[](https://vercel.com/new/clone?repository-url=https://github.com/nirholas/three.ws)1. Click the button → connect your GitHub account → Vercel forks the repo to your account.2. Fill in the environment variables (see the [Required environment variables](#required-environment-variables) section below).@@ -268,14 +268,14 @@ Without Redis the platform still works — rate limits run in-memory per serverl### Minimum requirements-- Node.js ≥ 18+- Node.js 24.x- A browser with WebGL 2.0 (Chrome, Firefox, or Edge 90+)- A Neon database (or any Postgres instance) for the API routes### Setup```bash-git clone https://github.com/nirholas/3d-agent.git+git clone https://github.com/nirholas/three.ws.gitcd 3d-agentnpm installdiff --git a/docs/embedding.md b/docs/embedding.mdindex afa3f6aaf..b8642e9ec 100644--- a/docs/embedding.md+++ b/docs/embedding.md@@ -1,6 +1,6 @@# Embedding Guide-> **Audience:** Developers and no-code builders who want to add a three.ws to a website, app, or platform.+> **Audience:** Developers and no-code builders who want to add a three.ws agent to a website, app, or platform.---diff --git a/docs/erc8004.md b/docs/erc8004.mdindex 688659ead..e4c7d4b00 100644--- a/docs/erc8004.md+++ b/docs/erc8004.md@@ -259,7 +259,7 @@ The resolver understands several equivalent ways to refer to an agent:### JavaScript SDK```js-import { resolveOnchainAgent, parseAgentRef } from '@3dagent/sdk/erc8004';+import { resolveOnchainAgent, parseAgentRef } from '@three-ws/sdk/erc8004';// By chain + agent IDconst agent = await resolveOnchainAgent({ chainId: 8453, agentId: 42 });@@ -292,10 +292,10 @@ The resolver caches results per page session. Pass `{ fresh: true }` to bypass t```html<!-- CAIP-10 format in the agent-id attribute -->-<agent-three.ws-id="eip155:8453:0x8004A169FB4a3325136EB29fA0ceB6D2e539a432:42"></agent-3d>+<agent-3d agent-id="eip155:8453:0x8004A169FB4a3325136EB29fA0ceB6D2e539a432:42"></agent-3d><!-- Shorthand -->-<agent-three.ws-id="onchain:8453:42"></agent-3d>+<agent-3d agent-id="onchain:8453:42"></agent-3d>```The `<agent-3d>` element boots the full agent runtime — 3D rendering, memory, skills, and conversation — using the on-chain identity as its manifest source.@@ -363,7 +363,7 @@ After registering, your agent starts accumulating on-chain reputation. Any walleScores are integers from −100 to +100. The contract stores each individual review (submitter address, score, optional IPFS pointer to a longer write-up) and maintains a running aggregate (sum + count). The `getReputation` call returns `(avgX100, count)`:```js-import { getReputation, getRecentReviews } from '@3dagent/sdk/erc8004';+import { getReputation, getRecentReviews } from '@three-ws/sdk/erc8004';const { total, count, average } = await getReputation({agentId: 42,@@ -388,7 +388,7 @@ const reviews = await getRecentReviews({### Submitting feedback```js-import { submitReputation } from '@3dagent/sdk/erc8004';+import { submitReputation } from '@three-ws/sdk/erc8004';const txHash = await submitReputation({agentId: 42,@@ -424,7 +424,7 @@ Only allow-listed validator addresses can call `recordValidation`. Validators ar### Reading the latest validation```js-import { getLatestValidation } from '@3dagent/sdk/erc8004';+import { getLatestValidation } from '@three-ws/sdk/erc8004';const result = await getLatestValidation({agentId: 42,@@ -438,7 +438,7 @@ const result = await getLatestValidation({### Verifying independently```js-import { hashReport, reportPassed } from '@3dagent/sdk/erc8004';+import { hashReport, reportPassed } from '@three-ws/sdk/erc8004';// Re-run the validator and hash the new reportconst freshReport = await runGltfValidator(glbBytes);@@ -461,7 +461,7 @@ import {connectWallet,registerAgent,getIdentityRegistry,-} from '@3dagent/sdk/erc8004';+} from '@three-ws/sdk/erc8004';// Connect the user's walletconst { signer, chainId, address } = await connectWallet();@@ -486,7 +486,7 @@ The `onStatus` callback fires at each step so you can show progress in your UI.### Reading agents```js-import { getIdentityRegistry } from '@3dagent/sdk/erc8004';+import { getIdentityRegistry } from '@three-ws/sdk/erc8004';import { BrowserProvider } from 'ethers';const provider = new BrowserProvider(window.ethereum);@@ -512,8 +512,8 @@ const val = await registry.getMetadata(agentId, 'myKey');### Building the agent card manually```js-import { buildRegistrationJSON, agentRegistryId } from '@3dagent/sdk/erc8004';-import { REGISTRY_DEPLOYMENTS } from '@3dagent/sdk/erc8004/abi';+import { buildRegistrationJSON, agentRegistryId } from '@three-ws/sdk/erc8004';+import { REGISTRY_DEPLOYMENTS } from '@three-ws/sdk/erc8004/abi';const card = buildRegistrationJSON({name: 'My Agent',@@ -568,7 +568,7 @@ Testnet gas is free from faucets:```js// From src/erc8004/abi.js-import { REGISTRY_DEPLOYMENTS } from '@3dagent/sdk/erc8004/abi';+import { REGISTRY_DEPLOYMENTS } from '@three-ws/sdk/erc8004/abi';// Example: Base mainnetREGISTRY_DEPLOYMENTS[8453] === {diff --git a/docs/examples.md b/docs/examples.mdindex fa1b7c4d6..f454624c7 100644--- a/docs/examples.md+++ b/docs/examples.md@@ -32,7 +32,7 @@ The absolute simplest setup: one script tag, one custom element.<agent-3dbody="/avatars/cz.glb"instructions="You are a friendly 3D guide."- brain="claude-opus-4-6"+ brain="claude-opus-4-7"width="100%"height="320px"></agent-3d>@@ -78,7 +78,7 @@ A pinned chatbot bubble that stays fixed in the viewport corner — like a suppoposition="bottom-right"width="320px"height="420px"- brain="claude-opus-4-6"+ brain="claude-opus-4-7"></agent-3d><script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>@@ -148,7 +148,7 @@ A full AI-powered agent with a text input. The agent reads your messages, reasonbody="/avatars/aria.glb"name="Aria"instructions="You are Aria, a friendly AI assistant. Be helpful and concise."- brain="claude-opus-4-6"+ brain="claude-opus-4-7"></agent-3d><div class="chat">@@ -217,7 +217,7 @@ Two agents sharing a single WebGL canvas via `<agent-stage>`. Each keeps its ownname="Coach Leo"body="/avatars/cz.glb"instructions="You are Coach Leo. Friendly, short answers. When another agent says hi, wave and greet them back by name."- brain="claude-opus-4-6"+ brain="claude-opus-4-7"eager></agent-3d><agent-3d@@ -225,7 +225,7 @@ Two agents sharing a single WebGL canvas via `<agent-stage>`. Each keeps its ownname="Mira"body="/avatars/cz.glb"instructions="You are Mira, a quiet observer who only speaks when spoken to."- brain="claude-opus-4-6"+ brain="claude-opus-4-7"eager></agent-3d></agent-stage>@@ -308,7 +308,7 @@ import { useEffect, useRef, useState } from 'react';// Load the web component once at module levelimport 'https://three.ws/agent-3d/latest/agent-3d.js';-export function AgentViewer({ body, name, instructions, brain = 'claude-opus-4-6', mode = 'inline', onMessage, style }) {+export function AgentViewer({ body, name, instructions, brain = 'claude-opus-4-7', mode = 'inline', onMessage, style }) {const ref = useRef(null);const [ready, setReady] = useState(false);@@ -374,7 +374,7 @@ Listen to the agent's event stream to drive a custom transcript UI — no built-id="agent"body="/avatars/cz.glb"instructions="You are a helpful assistant."- brain="claude-opus-4-6"+ brain="claude-opus-4-7"style="display:block;width:400px;height:500px"></agent-3d>@@ -442,7 +442,7 @@ Load different GLB models at runtime by calling `say()` or by swapping the `bodyid="viewer"body="/avatars/cz.glb"instructions="Describe what you see in the scene."- brain="claude-opus-4-6"+ brain="claude-opus-4-7"style="display:block;width:400px;height:400px"></agent-3d>@@ -619,7 +619,7 @@ Coach Leo is a fully-configured agent with a personality, skills, and persistent},"brain": {"provider": "anthropic",- "model": "claude-opus-4-6",+ "model": "claude-opus-4-7","instructions": "instructions.md","temperature": 0.8,"maxTokens": 2048@@ -644,7 +644,7 @@ Coach Leo is a fully-configured agent with a personality, skills, and persistent```markdown---name: Coach Leo-model: claude-opus-4-6+model: claude-opus-4-7temperature: 0.8---diff --git a/docs/how-it-works.md b/docs/how-it-works.mdindex fcf15aa95..94a2dff8b 100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@ -1,307 +1,164 @@-# How CSS 3D Parallax Works+# How three.ws works-This page explains the mechanics behind the CSS 3D parallax scrolling hero used in this theme — from the mathematical foundations of 3D projection to the browser-specific quirks that required targeted workarounds. If you want to understand why each line of CSS exists, you are in the right place.+This page is the load-bearing mental model. If you're trying to figure out where a feature lives, how a request flows, or which layer to extend — start here.------## The CSS 3D Coordinate System--Before anything else, you need a mental model of how CSS thinks about three-dimensional space.--CSS uses a right-handed coordinate system. The X axis runs left to right across the screen. The Y axis runs top to bottom (not bottom to top as in mathematics — CSS and HTML have their origin at the top-left corner). The Z axis is perpendicular to the screen, pointing toward you. A positive `translateZ` moves an element closer to you; a negative `translateZ` moves it away into the page.--The **vanishing point** is where all parallel lines in the 3D scene would converge if extended to infinity. In CSS, the vanishing point defaults to the center of the element that has `perspective` set on it. If you set `perspective: 500px` on a container and it is 800px wide and 600px tall, the vanishing point sits at `(400px, 300px)` in that container's coordinate space. Elements positioned away from that center will appear to slant toward it, which is exactly what gives 3D scenes their sense of depth.--There is one important subtlety: the vanishing point is relative to the _perspective element_, not the viewport. This matters enormously for parallax, as we will see shortly.+For the full deep dive on internals, see [Architecture overview](./architecture.md). For the actual JS API, see [JavaScript API](./js-api.md) and [REST API](./api-reference.md). This document zooms out to *how it all fits together*.----## `perspective` on a Scroll Container vs. `perspective()` in a Transform--There are two ways to introduce perspective into CSS:--**1. The `perspective` property on a parent element:**--```css-.scroll-container {- perspective: 2.5rem;- overflow: hidden auto;-}-```--**2. The `perspective()` function inside a `transform` on the element itself:**+## The pitch in one paragraph-```css-.layer {- transform: perspective(2.5rem) translateZ(-10px);-}-```--These look similar but behave fundamentally differently, and the difference is what makes scrolling parallax possible.--When you use the `perspective` _property_ on a parent, all children share a _single_ vanishing point. Every child's 3D transform is evaluated relative to that one shared origin. As a result, moving one child does not move the vanishing point — it stays anchored to the parent.--When you use `perspective()` inside an individual element's `transform`, each element gets its own independent vanishing point centered on itself. There is no shared scene. Objects do not relate to each other in 3D space.--For parallax, the shared vanishing point is what you want. The scroll container has `perspective` set, and all the depth layers are children. When the container scrolls, the layers scroll at different visual rates because they are at different Z depths — all converging toward the same vanishing point. This is the entire trick.+three.ws turns an AI agent into a persistent, ownable, multi-chain object: a 3D body that renders in any modern browser, an LLM brain you choose (Claude, GPT, or others), an on-chain identity registered on EVM chains via ERC-8004 or on Solana via Metaplex Core, and a `<agent-3d>` web component you can drop into any page on the internet. Pay-per-call API endpoints use the x402 standard. The whole stack is open source under Apache-2.0.----## The Exact Math: `translateZ` and Parallax Depth--Here is the core rule of CSS 3D projection: an element translated along the Z axis by `z` in a container with `perspective: p` will appear to move at a visual rate proportional to `(p - z) / p` when the container is scrolled.--More precisely, when the scroll container moves by `d` pixels (i.e., `scrollTop` increases by `d`), an element at `translateZ(z)` appears to move by:--```-visual_movement = d × (p / (p - z))-```--For the parallax effect we want _slower_ movement for elements further away (negative Z). Substituting a negative Z value:+## What happens when an agent loads-```-visual_movement = d × (p / (p + |z|))-```--When `|z|` is large, the denominator grows, and the fraction shrinks below 1. The element appears to move _less_ than the scroll distance. That is parallax.--In this theme, the perspective value is `2.5rem`. The CSS variable `--md-parallax-depth` sets the depth multiplier. The actual `translateZ` value applied to each layer is:--```css-transform: translateZ(calc(2.5rem * var(--md-parallax-depth) * -1))- scale(calc(var(--md-parallax-depth) + 1));-```--With `--md-parallax-depth: 8` (the farthest background layer), the element is pushed `20rem` (8 × 2.5rem) back into the page. Its visual scroll rate becomes:--```-rate = 2.5 / (2.5 + 20) = 2.5 / 22.5 ≈ 0.111-```--That layer moves at about 11% of the scroll speed. A near-foreground layer at `--md-parallax-depth: 1` moves at:+Pick the simplest case: a host page on `example.com` has dropped in our embed script and the `<agent-3d>` element. A visitor scrolls to it. Here is the round trip, end to end:-```-rate = 2.5 / (2.5 + 2.5) = 2.5 / 5 = 0.5-```--That layer moves at 50% of scroll speed. The result: the background barely drifts while the foreground moves more noticeably — exactly the depth cue your visual system uses to infer distance.+1. **Lazy boot.** The CDN bundle (`https://three.ws/agent-3d/latest/agent-3d.js`) registers the custom element. It does *not* boot the 3D scene until the element scrolls into view (an `IntersectionObserver` waits). If you add the `eager` attribute, the scene boots on connect.+2. **Manifest resolution.** Once visible, the element looks at its attributes:+ - `agent-id="<uuid>"` → fetches the manifest from `/api/agents/<id>` on the platform+ - `agent-id="42" chain-id="8453"` → calls the ERC-8004 registry on Base, reads the `tokenURI`, then fetches the IPFS-hosted manifest+ - `manifest="https://…/manifest.json"` → fetches the URL directly+ - `body="…glb" brain="…"` → no manifest fetch needed; the attributes *are* the config+3. **Origin check.** If the manifest declares an `embed.origins` allowlist, the element verifies `location.origin` matches before continuing. Failed checks render an error placeholder, not the agent.+4. **Viewer init.** A WebGL renderer, perspective camera, lights, an HDRI environment, and `OrbitControls` are created — scoped to the element's shadow DOM, with idle frames skipped so off-screen agents don't burn battery.+5. **GLB load.** `GLTFLoader` (with DRACO, KTX2, and Meshopt decoders attached) fetches the avatar and centers it. The poster image from the manifest fades out when the model is ready.+6. **Runtime start.** If a brain is configured, the LLM runtime constructs the system prompt from `instructions.md`, the memory context, and the installed skills' tool schemas. The chat input, voice button, and accessory dock appear.+7. **Bus subscriptions.** The avatar's empathy layer, the identity logger, the chat UI, and any skills all subscribe to a single `agent-protocol` event bus. Nothing communicates by direct method call.+8. **Ready.** A `agent:ready` `CustomEvent` fires on the element. Host pages listening to it can now call `el.say("Hello!")` or `el.ask("How are you?")`.-The four layers in this theme use depth values of `8`, `5`, `2`, and `1`, giving visual scroll rates of roughly 11%, 33%, 56%, and 50% respectively. The gaps between values are chosen to make the depth separation clearly visible without any single layer moving so fast it looks wrong.+If you'd rather see this with module names and call sites, see the [architecture overview](./architecture.md#5-web-component-lifecycle).----## Scale Compensation: Why `scale(depth + 1)` Is Necessary+## The four layers-There is a problem with pushing elements back along the Z axis: they appear smaller. An element at `translateZ(-20rem)` inside a `perspective: 2.5rem` container will be dramatically shrunk by the 3D projection — it would appear as a tiny postage stamp in the corner of the screen.+The whole stack is split into four horizontal strata. Each layer can run on its own. Each layer is independently replaceable as long as you don't break the event bus contract.-The scale compensation formula fixes this:--```css-scale(calc(var(--md-parallax-depth) + 1))```--This is derived directly from the projection math. If an element is at depth `d` (where actual `translateZ` equals `d × -p`), the CSS projection shrinks it by a factor of `1 / (d + 1)`. Multiplying by `scale(d + 1)` exactly cancels that shrinkage, restoring the element to its intended visual size.--For the far background at `--md-parallax-depth: 8`:--- Projection shrink factor: `1 / (8 + 1) = 1/9`-- Scale compensation: `9`-- Net visual size: `1/9 × 9 = 1` — back to full size--For the near foreground at `--md-parallax-depth: 1`:--- Projection shrink factor: `1 / (1 + 1) = 1/2`-- Scale compensation: `2`-- Net visual size: `1/2 × 2 = 1` — back to full size--A critical side effect: because scale compensation makes far layers appear full-size, they must actually be _much larger_ in pixel terms than they appear. A layer at depth 8 needs to be rendered 9× its visible dimensions. This is why background images for deep layers need to be wide panoramic files — the scale transform stretches them to fill the viewport.-------## Why Scrolling a Perspective Container Creates Parallax--You might wonder: if the scroll container is scrolled, does not everything inside move together by the same amount? The answer is yes in 2D, but not in 3D.--When the container scrolls, the viewport's position in the container's coordinate space changes. Elements at `translateZ(0)` behave normally — they scroll at 1:1. But the 3D projection matrix transforms the geometry of elements at non-zero Z positions. As the viewpoint shifts relative to the Z-displaced elements, the _projected_ position on screen changes at a different rate than the raw scroll offset. The perspective math does this automatically; the browser's rendering engine handles it correctly by compositing each layer with its appropriate depth-projected transform.--This is why this technique requires no JavaScript whatsoever. The parallax is not computed by reading `scrollTop` and updating element positions — it is a natural geometric consequence of CSS 3D perspective projection. The browser's compositor thread handles it entirely, on the GPU.-------## Sticky Positioning for Hero Text--The hero text sits on top of the parallax image layers and should remain readable while the parallax scrolls. The standard approach — `position: sticky` — is used, but it requires a careful negative margin to work correctly:--```css-.parallax__group--hero-text {- position: sticky;- top: 0;- margin-bottom: -100vh;-}+┌──────────────────────────────────────────────┐+│ <agent-3d>, widgets, iframe, SDK packages │ ← Embed layer+├──────────────────────────────────────────────┤+│ ERC-8004 · Metaplex Core · IPFS · SIWE/SIWS │ ← Identity layer (optional)+├──────────────────────────────────────────────┤+│ LLM runtime · Skills · Memory · Empathy bus │ ← Agent layer+├──────────────────────────────────────────────┤+│ three.js · GLTFLoader · AnimationMixer │ ← Viewer layer+└──────────────────────────────────────────────┘```-The `margin-bottom: -100vh` deserves explanation. Sticky positioning keeps an element "stuck" to the top of the scroll container until its _parent_ scrolls out of view. Without the negative margin, the parent element would end exactly at the bottom of the text content, and the text would begin to scroll away before the parallax images are done moving through the viewport.--By setting `margin-bottom: -100vh`, the parent element's layout height is reduced by one viewport height. This pulls the sticky constraint boundary upward, keeping the text stuck for exactly as long as the parallax hero section occupies the viewport. When the parallax scroll group eventually leaves the viewport, the sticky text goes with it, revealing the normal document content below.+- **Viewer layer** — pure three.js. Knows nothing about agents, brains, or wallets. Useful on its own as a glTF inspector and as the rendering engine for Turntable / Animation Gallery widgets. See [Layers](./layers.md) for the contract.+- **Agent layer** — turns a static GLB into a presence. LLM tool-loop, skill registry, memory, and a continuous emotion blend that drives morphs and gaze. See [Agent system](./agent-system.md).+- **Identity layer** — durability across sessions, devices, and embed hosts. Wallet auth, on-chain registration, IPFS-pinned manifest bundles, signed action diary. Entirely optional. See [ERC-8004](./erc8004.md) and [Solana agents](./solana.md).+- **Embed layer** — the public face. The `<agent-3d>` custom element, five widget variants, iframe embeds, the CDN bundle, the SPA, edge routing in `vercel.json`. See [Embedding](./embedding.md).-This is a purely CSS technique. No scroll event listeners, no `position: fixed` with JavaScript offset calculations.+The four layers communicate through one event bus (`agent-protocol`). Every meaningful action is a `CustomEvent` on a singleton. That single design choice is why you can swap the avatar for a 2D sprite, the runtime for a different LLM, or memory for a vector store — and nothing else changes.----## Paint Containment with `contain: strict`+## A conversation, end to end-```css-.parallax__group {- contain: strict;-}-```--The `contain: strict` declaration tells the browser that this element and its subtree are self-contained: their layout, paint, and size do not affect anything outside the element, and nothing outside affects them. This is a performance hint that allows the browser to skip repainting the rest of the document when the parallax group changes.+A user types "Wave at me" into an embedded agent's chat input. Here's the full data flow:-For parallax layers that are constantly being composited and transformed, this is significant. Without containment, each frame of animation might trigger a full-page repaint. With `contain: strict`, the browser can isolate and independently composite each parallax group on the GPU, achieving buttery smooth frame rates even on mid-range hardware.+1. **Input.** Chat UI calls `runtime.send("Wave at me", { voice: false })`.+2. **System prompt.** The runtime builds the prompt: manifest `instructions.md` + a compact memory block + the skill registry's tool descriptions.+3. **LLM call.** A streaming request goes to Anthropic (or OpenAI, or whichever provider matches the manifest's `brain.provider`). The platform supports proxying through `/api/brain/chat` so API keys never live in the client.+4. **Tool call.** The model returns a `wave` tool invocation.+5. **Skill dispatch.** The skill registry looks up `wave`. It's a built-in: the handler emits a `gesture` event on the bus and plays the wave animation clip via the `SceneController`.+6. **Empathy reaction.** The avatar's empathy layer hears `gesture` and `speak` events on the same bus. Sentiment is positive, so celebration weight bumps slightly. Morph targets lerp `mouthSmile` toward 0.6 over a few frames; gaze locks on the user.+7. **TTS.** If `voice: true`, the text is read aloud via ElevenLabs (or the Web Speech API as fallback).+8. **Identity diary.** The identity layer hears `speak`, `gesture`, and `skill-done` and POSTs them to `/api/agent-actions` so the agent's signed action history persists.-The reason this is especially important here is that the 3D transforms on the parallax layers happen entirely on the compositor thread (separate from the main JavaScript thread), but only if the browser can correctly promote the layers to their own GPU compositing layers. `contain: strict` helps the browser make that determination reliably.+If you registered the agent on-chain, that signed action log can be attested to via the **ReputationRegistry** so anyone can verify behavior across embeds without trusting the central server.----## The `height: 140vh` on the First Group--The first parallax group uses `height: 140vh` rather than `100vh`. This is not arbitrary. The parallax layers inside the group appear to extend beyond the viewport — the far background layer (depth 8) scrolls at 11% of scroll speed, which means for it to travel through the viewport fully, the group needs to be scrolled through more than `100vh` of content.+## Where does the LLM key live?-The exact value needed depends on the depth values used. A deeper background requires a taller container to complete its scroll travel. `140vh` was empirically tuned to ensure all four layers complete their parallax motion before the hero scrolls fully off screen.+Three modes, all configurable per agent:-Subsequent groups (if any) use responsive `vw`-based heights rather than fixed `vh` values, because their content is image-driven and should maintain aspect ratios:+| Mode | When to use | How |+|---|---|---|+| **Hosted (default)** | Most users | Set `brain="claude-sonnet-4-6"`. The element posts to `https://three.ws/api/brain/chat`, which uses the platform's pooled keys. Billed against your three.ws account. |+| **Self-hosted proxy** | You want to manage cost or use a private model | Set `key-proxy="/api/llm"` to point at your own serverless function that injects keys before forwarding to the provider. Keys never reach the client. |+| **Direct (advanced)** | Local-only experiments | The runtime can call providers directly if you pass an API key explicitly. Don't ship this to a public page. |-```css-.parallax__group--scene {- height: 56.25vw; /* 16:9 aspect ratio */-}-```--This ensures the parallax scene scales proportionally with viewport width, maintaining correct composition at all screen sizes.+The brain proxy at [`/api/brain/chat`](./api-reference.md) supports Anthropic, OpenAI, Qwen, and OpenRouter — so the brain attribute can be `claude-opus-4-7`, `claude-sonnet-4-6`, `claude-haiku-4-5`, `gpt-4o`, `gpt-4o-mini`, and others.----## The Blend Layer+## Where does the avatar come from?-Between the parallax image layers and the content below, there is a gradient blend layer:+Three production paths. Pick whichever fits your use case:-```css-.parallax__blend {- background: linear-gradient(to bottom, transparent 0%, var(--md-default-bg-color) 100%);- z-index: 5;-}-```+- **Character Studio** — full-body character builder for stylised humanoids. Pick a base mesh, swap clothing/accessories/hairstyles, save. The output is a rigged GLB. See [character-studio.md](./character-studio.md).+- **Selfie (Avaturn)** — upload a photo, get a rigged 3D version of yourself in ~60 seconds. See [avaturn.md](./avaturn.md).+- **Upload your own** — any glTF 2.0 / GLB with a humanoid rig works. Drop the file into the editor at [three.ws/create](https://three.ws/create) or POST to `/api/avatars`.-This gradient transitions from fully transparent (showing the bottom edge of the parallax images) to the site's background color (matching the content sections below). It accomplishes two things:--1. It prevents a hard visual cutoff at the bottom of the parallax hero. Images rarely look clean at their exact edge, and the gradient masks any artifacts.-2. It creates a smooth visual merge between the scenic parallax imagery and the flat document content that follows, making the page feel cohesive rather than jarring.--The blend layer is positioned using `z-index: 5`, which places it above the image layers (which have lower z-index values) but the blend is transparent at the top, so it does not obscure the imagery.+Every avatar ends up as a `cdn.three.ws/u/<owner>/…glb` URL plus a database record. When you wire one into an agent, the agent's manifest references it under `body.uri`.----## Z-Index Stacking: `z-index: calc(10 - depth)`+## How embeds reach the host page-The parallax layers need to stack correctly: near objects (low depth number) should appear in front of far objects (high depth number). The formula for this is:+Once your agent is live, three surfaces let other pages embed it:-```css-z-index: calc(10 - var(--md-parallax-depth));-```+- **The web component** — `<agent-3d agent-id="…">` after loading the CDN script. The element runs in your page, sharing the DOM. Use this when you want full control and your CSP allows third-party scripts.+- **The iframe widget** — `https://three.ws/w/<widget-id>` rendered inside an `<iframe>`. Five widget types ship: Turntable, Animation Gallery, Talking Agent, ERC-8004 Passport, Hotspot Tour. Use this in environments where you can't load third-party scripts (Notion, Webflow, Framer, WordPress).+- **The Open Graph + oEmbed surface** — paste `https://three.ws/agent/<id>` into Slack, X, Discord, or any platform that consumes oEmbed, and you get a rich preview with the avatar's poster, name, and description.-At `--md-parallax-depth: 1` (near foreground), `z-index` is `9`. At `--md-parallax-depth: 8` (far background), `z-index` is `2`. Near layers are always on top of far layers in the stacking order.--Without this, the 3D projection might place elements visually at different depths, but the browser's paint order (which follows DOM order and z-index) might render them in the wrong order, creating situations where a background element is painted over a foreground element. The `z-index` formula ensures paint order matches visual depth order.+The `postMessage` bridge in the web component and the iframe widget speaks the same protocol, so host pages can call `say()`, `ask()`, `installSkill()`, and listen for events like `agent:speak`, `agent:tool-called`, `agent:skill-done` either way.----## Browser Quirks+## Why on-chain?-### Safari: Disabling `contain: strict`+On-chain identity is optional. Most agents work fine without it. You'd want it when:-Safari has a known issue where `contain: strict` on elements inside a `perspective` scroll container breaks the parallax effect — the 3D transforms stop updating correctly during scroll, causing layers to freeze or jump. A browser detection script adds a `.safari` class to the `<body>` element:+- **The agent should outlive the platform.** ERC-8004 registry contracts on Base and other EVM chains hold the canonical ID. The manifest is on IPFS. Even if `three.ws` disappeared tomorrow, anyone could resolve and run your agent.+- **You need verifiable behavior.** Validation attestations and signed action logs let third parties verify what an agent has done.+- **You want delegated wallet permissions.** ERC-7710 lets you sign once per session and grant the agent scoped, time-bound permission to act on-chain — no per-transaction prompts.+- **You want a portable address.** `agent://base/42` is a stable, resolver-agnostic URI. Any client that speaks the protocol can load it.-```js-if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {- document.body.classList.add('safari');-}-```--The CSS then disables `contain` specifically for Safari:--```css-.safari .parallax__group {- contain: none;-}-```--This restores correct parallax behavior at the cost of some paint performance in Safari. Given that Safari's rendering engine handles 3D compositing differently, this is an acceptable trade-off.--### Firefox: Repaint Bug Fix--Firefox has a repaint bug where the parallax layers occasionally fail to repaint after a rapid scroll or tab focus change, leaving ghost artifacts or blank regions. The fix involves toggling a class that forces a style recalculation:--```js-window.addEventListener('focus', () => {- document.body.classList.add('ff-hack');- requestAnimationFrame(() => document.body.classList.remove('ff-hack'));-});-```--```css-.ff-hack .parallax__layer {- will-change: transform;-}-```--Adding and removing `will-change: transform` forces Firefox to mark the compositing layers as dirty and repaint them on the next frame. This resolves the ghost artifact issue without any visible effect on the rendered output.+See [erc8004.md](./erc8004.md) and [solana.md](./solana.md) for the registration flows.----## Why Not JavaScript Scroll Listeners?+## What about monetisation?-Traditionally, parallax effects use JavaScript that reads `window.scrollY` on each scroll event and applies position offsets. This approach has serious performance problems:+Three independent mechanisms, used as needed:-- Scroll event handlers run on the **main thread**, which is the same thread that runs JavaScript, handles user input, and performs layout. Under heavy load, this thread can be busy, causing the parallax animation to lag behind the actual scroll position.-- Reading `scrollY` followed by writing to `element.style.transform` triggers **layout thrashing** if not carefully managed with `requestAnimationFrame`.-- Even with `requestAnimationFrame`, JavaScript-driven parallax runs at most 60fps on most displays, and may drop frames when other scripts are active.+- **x402** — pay-per-call USDC for paid API endpoints. Every paid endpoint declares itself in [`/.well-known/x402.json`](https://three.ws/.well-known/x402.json). Other agents (or humans with a wallet) can call paid endpoints with a single signed payment header.+- **pump.fun** — launch a Solana SPL token tied to your agent. The platform handles the bonding curve, the token metadata, and the embed.+- **AWS Marketplace** — enterprise subscriptions billable through AWS. See [aws-marketplace.md](./aws-marketplace.md). Subscriptions auto-issue an x402 API key via the marketplace entitlement service.-The CSS 3D approach runs entirely on the **compositor thread**, a separate GPU-accelerated thread that handles `transform` and `opacity` animations. The compositor thread is never blocked by JavaScript. The parallax updates happen at the full display refresh rate (including 120Hz and 144Hz displays) with zero jank, even if the main thread is busy processing data or rendering other UI.+You can mix these per agent. A common pattern: an agent has a free public persona on the platform, exposes one paid x402 skill for power users, and accepts donations via a pump.fun token.----## Why Not `animation-timeline: scroll()`?+## When to use which surface-The CSS Scroll-Driven Animations API (`animation-timeline: scroll()`) is a modern alternative that allows CSS animations to be driven by scroll position. As of 2025, it is supported in Chrome and Edge but lacks full support in Safari and Firefox.+Quick lookup for "I want to ship X":-Additionally, scroll-driven animations are still processed on the main thread in some implementations when they affect layout properties, and the API requires careful coordination when combined with 3D transforms and perspective containers. The CSS 3D perspective approach used here works in every browser that supports CSS 3D transforms — which is every major browser since 2012 — and delivers equivalent performance without the compatibility uncertainty.+| You want… | Reach for… |+|---|---|+| A 3D character on a marketing page | The CDN script + `<agent-3d>` |+| A character in Notion / Webflow / Framer | An iframe widget from [Widget Studio](./widget-studio.md) |+| A talking AI sidekick that follows visitors | `<agent-3d mode="floating">` |+| A character that controls a scene from page events | The JS API (`agent.say()`, `agent.ask()`) — see [js-api.md](./js-api.md) |+| Programmatic avatar manipulation in Node | `@three-ws/avatar` |+| An on-chain identity for your AI | [ERC-8004](./erc8004.md) or [Solana](./solana.md) |+| A paid API anyone (including agents) can call | [x402 monetization](./x402.md) |+| Multiple agents in one scene | `<agent-stage>` — see [multi-agent.md](./multi-agent.md) |+| To register a domain (e.g. ENS) as agent identity | [register-onchain.md tutorial](./tutorials/register-onchain.md) |----## Debugging: Chrome DevTools--### Layers Panel--Open Chrome DevTools, go to the **Layers** panel (More tools > Layers). Each parallax layer should appear as a separate compositing layer. If a layer is not promoted, you will see it listed as part of its parent. You can click any layer to see why it was or was not promoted (look for "Has a 3D transform" as the reason).--### 3D View--In Chrome DevTools, More tools > **3D View** renders your page's layer stack as an interactive 3D diagram. You can orbit around the layer stack and visually confirm that each parallax layer is at the correct depth. Layers that are pushed back in Z should appear further back in the 3D view. This is the most intuitive way to verify that the transforms are applied correctly.--If a layer appears at `z=0` when it should be at a negative Z, the most common cause is a missing `transform-style: preserve-3d` on an intermediate ancestor, or a CSS property on an ancestor that flattens the 3D context (such as `overflow: hidden` in some browsers, or certain `filter` values).-------## Summary--The CSS 3D parallax technique works because:--1. A `perspective` property on a scroll container establishes a shared 3D scene with a fixed vanishing point.-2. Child elements at negative Z positions are projected to appear smaller and scroll more slowly — the further back, the slower.-3. Scale compensation exactly counteracts the projection shrinkage, so images appear full-size at all depths.-4. The compositor thread handles all of this at GPU speed, with no JavaScript involvement.-5. Sticky text positioning and a blend gradient handle the presentation layer.-6. Browser-specific workarounds address known bugs in Safari and Firefox without compromising the core technique.+## What's next-The result is a hero section with genuine, smooth, GPU-accelerated depth — using nothing but CSS that browsers have supported for over a decade.+- **[Architecture overview](./architecture.md)** — full internals+- **[Agent system](./agent-system.md)** — runtime, skills, memory, emotion+- **[Layers](./layers.md)** — the four-layer contract in detail+- **[Quick start](./quick-start.md)** — go from zero to a living embed in under 10 minutesdiff --git a/docs/internal/DEVELOPMENT.md b/docs/internal/DEVELOPMENT.mdindex 48dd33c9c..4b47da463 100644--- a/docs/internal/DEVELOPMENT.md+++ b/docs/internal/DEVELOPMENT.md@@ -22,14 +22,14 @@ Everything you need to know to work on three.ws locally.## Setup```bash-git clone https://github.com/nirholas/3d-agent.git+git clone https://github.com/nirholas/three.ws.gitcd 3D-Agentnpm install```**Requirements:**-- Node.js ≥ 18+- Node.js 24.x- A browser with WebGL 2.0 support (Chrome, Firefox, Edge)---diff --git a/docs/internal/api-inventory.md b/docs/internal/api-inventory.mdindex 4d279aacd..ba59dfbf4 100644--- a/docs/internal/api-inventory.md+++ b/docs/internal/api-inventory.md@@ -115,7 +115,7 @@ Generated reference of every HTTP endpoint under `/api/`. Paths reflect the exte| `/api/erc8004/import` | POST | session | Import on-chain agent into local `agent_identities` | `{chainId,agentId}` | `{agent}` || `/api/erc8004/pin` | POST | session | Pin raw GLB/JSON/image bytes (IPFS + R2 fallback) | raw body | `{cid,url}` || `/api/explore` | GET | public | Paginated indexed ERC-8004 directory | `?only3d&chain&q&cursor&limit` | `{agents[],next_cursor}` |-| `/api/showcase` | GET | public (rate-limited) | Public directory, three.wss only, keyset pagination | `?chainIds&sort&limit&cursor` | `{agents[],next_cursor}` |+| `/api/showcase` | GET | public (rate-limited) | Public directory, three.ws only, keyset pagination | `?chainIds&sort&limit&cursor` | `{agents[],next_cursor}` |## Permissions (ERC-7710 delegations)diff --git a/docs/introduction.md b/docs/introduction.mdindex 15aa314ca..316218444 100644--- a/docs/introduction.md+++ b/docs/introduction.md@@ -9,11 +9,13 @@ The result is an agent that doesn't just respond in a chat box. It occupies a th**Key facts:**- **License:** Apache-2.0 — use it, fork it, self-host it-- **Hosted platform:** [https://three.ws/](https://three.ws/)-- **CDN library:** `https://three.ws/agent-3d/latest/agent-3d.js`+- **Hosted platform:** [https://three.ws](https://three.ws)+- **CDN bundle:** `https://three.ws/agent-3d/latest/agent-3d.js` (also pinnable to a version, e.g. `/agent-3d/1.5.1/agent-3d.js`)+- **npm packages:** [`@three-ws/sdk`](https://www.npmjs.com/package/@three-ws/sdk), [`@three-ws/agent-ui`](https://www.npmjs.com/package/@three-ws/agent-ui), [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar), [`@three-ws/solana-agent`](https://www.npmjs.com/package/@three-ws/solana-agent), [`@3d-agent/mcp-server`](https://www.npmjs.com/package/@3d-agent/mcp-server)- **No server required** for basic use — the viewer, agent runtime, and skill system all run in the browser via WebGL 2.0- **glTF 2.0 / GLB** with Draco, KTX2, and Meshopt decompression supported out of the box-- **AWS Partner** — three.ws is a verified AWS Partner and available on [AWS Marketplace](https://aws.amazon.com/marketplace) as a SaaS product+- **AWS Partner** — available on [AWS Marketplace](https://aws.amazon.com/marketplace) as a SaaS product, billable through your AWS account+- **x402 payments** — every paid endpoint discoverable at [`/.well-known/x402.json`](https://three.ws/.well-known/x402.json); MCP server at [`/api/mcp`](https://three.ws/api/mcp)---@@ -210,7 +212,8 @@ Once you have the basics working, the following guides go deeper:- **[Embedding Guide](./embedding.md)** — all attributes, modes, events, and the JS API- **[Widget Types](./widgets.md)** — Turntable, Animation Gallery, Talking Agent, Passport, Hotspot Tour- **[Agent System Overview](./agent-system.md)** — runtime, skill registry, memory, emotion system-- **[Manifest Reference](../specs/AGENT_MANIFEST.md)** — full JSON schema with examples-- **[API Reference](./api-reference.md)** — complete JS API for `Agent3DElement`+- **[Manifest Reference](./agent-manifest.md)** — full JSON schema with examples+- **[REST API](./api-reference.md)** and **[JavaScript API](./js-api.md)** — backend and in-browser surfaces+- **[Agents vs. avatars](./agents-vs-avatars.md)** — the difference, and when to care-If you want to look at what's already in the hosted platform — browsing agents, using Widget Studio, or registering on-chain — visit [https://three.ws/](https://three.ws/).+If you want to look at what's already in the hosted platform — browsing agents, using Widget Studio, or registering on-chain — visit [https://three.ws](https://three.ws).diff --git a/docs/js-api.md b/docs/js-api.mdindex 04ce86b4f..631e4228b 100644--- a/docs/js-api.md+++ b/docs/js-api.md@@ -1,6 +1,8 @@-# API Reference+# JavaScript API Reference-Complete reference for all public classes, methods, and properties in three.ws.+Complete reference for all public classes, methods, and properties exported by the three.ws web component bundle (`agent-3d.js`).++> For the HTTP/REST surface, see [api-reference.md](./api-reference.md). For the high-level npm SDK, see [sdk.md](./sdk.md). For the `<agent-3d>` element attributes, see [web-component.md](./web-component.md).---@@ -322,7 +324,7 @@ Creates the mini axes viewport:Builds the entire dat.gui panel. On mobile (≤ 700 px), uses 220 px width and starts closed; on desktop, 260 px width and starts open.-See [Architecture: GUI Structure](ARCHITECTURE.md#gui-structure-datgui) for the full folder tree.+See [Architecture overview](./architecture.md) for the full folder tree.#### `updateGUI()`diff --git a/docs/layers.md b/docs/layers.mdindex 021e355d4..7bc0f2921 100644--- a/docs/layers.md+++ b/docs/layers.md@@ -1,329 +1,155 @@-# Using Your Own Layers+# Layers-This guide walks through everything you need to know to replace the default hero images with your own artwork. It covers image format selection, dimension requirements, transparency rules, depth value strategy, scene composition principles, and the mechanics of wiring new images into the theme. By the end, you will be able to swap any set of layered images into the parallax hero with confidence.+three.ws is split into four horizontal layers. Each layer can be used on its own. Each layer is independently replaceable as long as its contract with the rest of the system holds. This document describes what each layer owns, what it exports, and where to extend it.------## Why Four Layers?--The theme ships with exactly four image layers, and this is a deliberate choice, not a technical limitation.--**Fewer than four** (two or three layers) produces a noticeably shallow depth effect. The human visual system picks up parallax cues from relative motion between planes. With only two planes, the separation feels thin — more like a cheap slideshow transition than genuine depth.--**More than four** (five or six layers) begins to have diminishing returns on perceived depth while multiplying file size substantially. Each additional AVIF layer adds to the initial page load. At four layers, users with fast connections load the hero in well under a second. At six or seven layers, you may see layout shift or a flash of empty space while the far layers load.--Four layers also maps cleanly to the natural visual hierarchy of most landscape compositions: sky/far background, mid-distance scenery, near-ground elements, and foreground detail. This four-plane model is how matte painters and game background artists have structured parallax scrollers for decades — because it matches how human eyes decompose distance in the real world.--If your scene genuinely needs five planes (for example, a foggy mountain range with a distinct middle-fog layer), adding a fifth is technically straightforward. Just be deliberate about it.+For the overall request flow, see [How three.ws works](./how-it-works.md). For internal module names and paths, see [Architecture overview](./architecture.md).----## Image Format Comparison--| Format | Compression | Alpha (Transparency) | Browser Support | Recommended Use |-| ------ | --------------------- | ------------------------ | ----------------------------------- | -------------------------------------------- |-| AVIF | Excellent (AV1-based) | Yes (full alpha channel) | Chrome 85+, Firefox 93+, Safari 16+ | Primary format for all layers |-| WebP | Good (VP8-based) | Yes | Chrome 32+, Firefox 65+, Safari 14+ | Fallback for older Safari |-| PNG | Lossless | Yes | Universal | Source files only; not for production |-| JPEG | Good (DCT-based) | No | Universal | Far background only (no transparency needed) |--**AVIF** is the primary format for this theme. It delivers dramatically smaller file sizes than WebP or PNG at equivalent visual quality — typically 40–60% smaller than WebP and 70–80% smaller than PNG for photographic content. For the wide panoramic images that parallax layers require (often 3000px+ wide), this difference is significant.--AVIF supports a full alpha channel, which is critical for mid-distance, near-ground, and foreground layers (more on this below). The alpha channel in AVIF uses the same AV1 compression as the color data, so transparent regions cost very little in file size compared to PNG's lossless transparency.--**WebP** should be provided as a `<source>` fallback in the `<picture>` element for users on Safari 14–15, which supports WebP but not AVIF. Safari 16+ supports AVIF natively, so WebP coverage is increasingly less necessary, but it remains good practice.--**PNG** should be used only for source/master files during the design phase. Never ship raw PNGs as hero layer images in production — a single transparent PNG at 3000×2000px can easily exceed 5MB, versus under 300KB for an equivalent AVIF.--**JPEG** can be used for the far background layer if it has no transparency requirement, but AVIF still outperforms JPEG at the same file size, so there is rarely a reason to reach for JPEG.-------## Exact Dimensions--### Minimum Dimensions--No layer should be smaller than the maximum viewport width you expect users to visit your site on. In practice, `2400px` wide is a safe minimum for desktop displays including high-density (2x) monitors at 1440px logical width. For near/foreground layers that are scaled up by the depth compensation factor, you need additional resolution.--Calculate the minimum raw image width for each layer using:+## The contract```-minimum_width = viewport_max_width × scale_factor+┌──────────────────────────────────────────────┐+│ Embed layer │+│ <agent-3d> · widgets · iframe · SDKs │+├──────────────────────────────────────────────┤+│ Identity layer (optional) │+│ ERC-8004 · Metaplex Core · IPFS · SIWE/SIWS│+├──────────────────────────────────────────────┤+│ Agent layer │+│ LLM runtime · skills · memory · empathy │+├──────────────────────────────────────────────┤+│ Viewer layer │+│ three.js · GLTFLoader · AnimationMixer │+└──────────────────────────────────────────────┘```-Where `scale_factor = depth + 1` (matching the CSS scale compensation). For the far background at depth 8:--```-minimum_width = 1440 × 9 = 12,960px-```--That looks alarming, but the browser's compositor only ever renders the visible portion of a scaled layer, and AVIF compression means a 12,000px-wide sky image might still only be 400KB due to the repetitive nature of sky gradients.--In practice, the scale compensation is applied in CSS, not to the image itself. The image does not need to be 12,000px wide — it needs to have enough resolution that when it is scaled by 9× in CSS and the user views the center portion at screen resolution, it does not appear blurry. For photographic content at 96dpi display resolution and 2× device pixel ratio, a source image of `3000px` wide is usually sufficient for the far background, because large amounts of scale compression and the visual nature of background imagery makes moderate blurriness imperceptible.--### Ideal Dimensions by Layer--| Layer | Depth | Scale Factor | Recommended Width | Recommended Height |-| -------------- | ----- | ------------ | ----------------- | ------------------ |-| Far background | 8 | 9× | 3000px | 1500px |-| Mid-background | 5 | 6× | 2800px | 1400px |-| Near-ground | 2 | 3× | 2400px | 1200px |-| Foreground | 1 | 2× | 2400px | 1200px |--### Why Wide Panoramas Work Better Than Tall Images--The horizontal crop of each layer is controlled by `--md-image-position`, which maps to `object-position`. Because the scale compensation zooms the image in considerably, a tall image mostly wastes pixels on the top and bottom edges that will never be visible. A wide panorama uses that pixel budget on horizontal detail that _will_ be seen as the user adjusts `--md-image-position` or visits on different viewport widths.--The aspect ratio `2:1` (width:height) is a reliable default. If your scene has significant vertical interest in the mid-ground (tall trees, cliffs, buildings), you can go to `1.5:1`, but avoid portrait-oriented source images.+The layers communicate through one event bus (`agent-protocol`). No layer calls another layer's methods directly. This is the load-bearing invariant — keep it intact and any layer can be replaced.----## Transparency: Which Layers Need It--The far background layer (depth 8) does not need transparency. It represents the sky, open sea, or any expanse that fills the entire frame. This layer is the "canvas" behind everything else.--Every other layer — mid-background, near-ground, and foreground — needs a transparent background. Here is why:+## Layer 1 — Viewer-In a parallax scene, layers stack on top of each other. If the mid-background layer has a solid color fill behind the mountains or trees you painted, that fill will cover the sky layer behind it, creating a hard rectangular cutout effect instead of a natural scene. The mid-background needs to show only the mountains and the sky directly behind them needs to come from the actual far background layer below.+**What it owns:** rendering, loading, animation, camera, lights, post-processing.-This means:+**Doesn't know about:** agents, brains, wallets, manifests, the protocol bus.-- **Far background (depth 8):** Solid image, no transparency required-- **Mid-background (depth 5):** Transparent background — show only the mid-distance objects-- **Near-ground (depth 2):** Transparent background — show only near-ground objects and foreground elements-- **Foreground (depth 1):** Transparent background — typically plants, rocks, or architectural elements that frame the scene+The Viewer is pure three.js. It can be used as a standalone glTF inspector with no agent at all — and is, in the Turntable and Animation Gallery widgets.-A common mistake is forgetting that the scale compensation zooms each layer in significantly. If your mid-background layer has transparent edges on the left and right, those edges may be scaled into the visible viewport. If the object you painted is centered in the image and the transparent area at the edges is large, the visible part of the image may be smaller than expected after scaling. Always preview the scaled result in CSS before finalizing your AVIF files.+Concretely:------## AVIF Alpha Channel and Parallax CSS--AVIF's alpha channel is encoded using the same AV1 codec as the color data, stored as a separate "auxiliary image" in the AVIF container. When the browser decodes an AVIF file with an alpha channel, it composites the alpha against the background using standard Porter-Duff "source over" blending.+- `WebGLRenderer` configured for `devicePixelRatio`, demand-rendered (`viewer.invalidate()`), idle frames skipped.+- `GLTFLoader` with `DRACOLoader`, `KTX2Loader`, and `MeshoptDecoder` attached. Decoder URLs are version-pinned to the bundled three.js.+- `OrbitControls`, auto-disabled when an embedded glTF camera is selected.+- `AnimationMixer` plus a per-clip action-state map.+- HDRI environment, exposure / tone mapping controls, optional helpers (grid, axes, wireframe, skeleton).+- Multi-file resolution via `LoadingManager.setURLModifier()` so drag-and-drop `scene.gltf + scene.bin + textures/...` works locally without uploads.-This interacts with the parallax CSS cleanly. The `object-fit: cover` property applied to each layer image respects the transparency of the image — transparent pixels remain transparent after fitting and cropping. The `object-position` property (controlled by `--md-image-position`) shifts the image within its container while preserving transparency.+**Extension points the next layer uses:**-One thing to verify: when exporting AVIF from Photoshop, Affinity Photo, or Figma, confirm that you are exporting with "alpha channel" or "transparency" enabled. Some AVIF exporters default to a flat white or black matte on transparent areas, which will destroy your transparency information. Always open the exported AVIF in a browser to visually verify the alpha before publishing.+- `viewer._afterAnimateHooks` — per-frame callbacks (emotion decay, tweens)+- `viewer.invalidate()` — request a render+- `viewer.content` / `viewer.scene` / `viewer.mixer`+- `viewer.animationManager` — external clip lazy-loading-AVIF files with alpha channels are somewhat larger than those without, because the alpha information is stored alongside the color data. For foreground layers with complex transparency (detailed foliage cutouts, for example), the AVIF file size will be noticeably larger than a solid background layer of the same dimensions. This is expected and acceptable.+If you only need a glTF viewer with no AI, importing `@three-ws/avatar` gives you this layer with a clean programmatic API (`loadAvatar()`, `playAnimation()`, etc.). The hosted Turntable and Animation Gallery widgets at `/w/<id>` are also pure viewer-layer.----## The `@4x` Naming Convention+## Layer 2 — Agent-Image files in this theme follow the convention:+**What it owns:** the LLM tool-loop, skills, memory, the empathy / emotion blend, the protocol bus.-```-```+**Doesn't know about:** how the LLM is hosted, where the wallet lives, which embed surface is showing it.-The `@4x` suffix is a source resolution indicator borrowed from iOS/macOS asset catalog conventions, where `@2x` means 2× pixel density, `@3x` means 3×, and so on. In this context, `@4x` signals that these are high-resolution source images intended to be displayed at a fraction of their pixel dimensions (because CSS scaling reduces them on screen).+Modules:-This naming convention has two benefits:+- **`agent-protocol.js`** — singleton `EventTarget` bus. Every action is a `CustomEvent`. 200-event ring buffer (`protocol.history`) for debugging.+- **`runtime/index.js`** — LLM tool-loop. Builds the system prompt from `instructions.md` + memory + skills, calls the provider, dispatches tool calls, feeds results back. Capped at `MAX_TOOL_ITERATIONS = 8`.+- **`runtime/scene.js`** — `SceneController`, the only bridge between agent intent and three.js reality: `playClipByName`, `playAnimationByHint`, `lookAt`, `setExpression`, `loadGLB`, `loadClip`, `moveTo`.+- **`runtime/tools.js`** — built-in tools (`wave`, `lookAt`, `play_clip`, `setExpression`, `speak`, `remember`) and stage-scoped tools (`observe_agents`, `say_to_agent`).+- **`runtime/speech.js`** — TTS (ElevenLabs / Web Speech API) and STT (browser `SpeechRecognition`). Silent no-op where unavailable.+- **`agent-skills.js`** — skill registry. Skills are dynamically loaded bundles (`SKILL.md`, `tools.json`, `handlers.js`). Trust modes (`any` / `owned-only` / `whitelist`).+- **`agent-memory.js`** — four-type memory store (`user`, `feedback`, `project`, `reference`). File-based memories live as frontmatter `.md` files indexed by `MEMORY.md` plus an append-only `timeline.jsonl`.+- **`agent-avatar.js`** — the empathy layer. Translates bus events into a continuous emotion blend (neutral, concern, celebration, patience, curiosity, empathy) and drives morph targets, head tilt, and gaze.-1. It documents the intended display scale in the filename, helping future maintainers understand why images seem larger than expected.-2. It prevents confusion with standard-resolution images. If you later add a WebP fallback or generate responsive sizes, you can name them `[email protected]` and `[email protected]` without ambiguity.+The full agent layer can run against any three.js scene, not just our viewer — `SceneController` only needs the standard handles.-The `@4x` suffix has no special meaning to browsers or MkDocs — it is purely a human-readable convention.+**Event bus vocabulary:** see [architecture.md §2](./architecture.md#2-the-event-bus-agent-protocoljs).----## Depth Value Selection Strategy--The four depth values used in this theme are `8`, `5`, `2`, and `1`. Understanding why these specific values were chosen helps you adjust them intelligently for your own scene.+## Layer 3 — Identity-**Depth 8 (far background):** The maximum depth value used. At depth 8, the visual scroll rate is approximately 11% of the page scroll speed. This layer barely moves, giving it a distant, immovable quality appropriate for sky or open horizon.+**What it owns:** persistent identity across sessions, devices, and embed hosts. Wallet auth, on-chain registration, IPFS-pinned manifests, signed action diary.-**Depth 5 (mid-background):** At depth 5, the visual scroll rate is approximately 33%. This layer moves noticeably but slowly, conveying mid-distance.+**Doesn't know about:** which avatar is loaded, what the LLM is doing.-**Depth 2 (near-ground):** At depth 2, the visual scroll rate is approximately 56%. This layer moves at just over half scroll speed, feeling close.+**Entirely optional.** Most agents work fine without it. Removing this layer drops you back to a local-only experience — the agent still runs, but it has no persistent identity.-**Depth 1 (foreground):** At depth 1, the visual scroll rate is 50%. Wait — why is foreground (depth 1) slower than near-ground (depth 2)?+Modules:-This is a quirk of the non-linear relationship between depth values and scroll rate. The rate formula is `p / (p + depth × p) = 1 / (1 + depth)`. At depth 2, rate is `1/3 ≈ 0.33`... wait, let us recalculate against the actual perspective value:+- **`agent-identity.js`** — the passport + diary. Stable agent ID, owner address, signed action history. Backed by `localStorage` (cache) and `/api/agents/<id>` (canonical). Listens on the protocol bus and POSTs `speak` / `skill-done` / `validate` / `sign` events to `/api/agent-actions`.+- **`memory/`** — `local`, `ipfs`, `encrypted-ipfs`, or `none`. Declared on the manifest.+- **`erc8004/`** — on-chain registries. `IdentityRegistry` (mints agent token with `tokenURI`), `ReputationRegistry` (signed feedback), `ValidationRegistry` (validation report hashes). Per-chain addresses in `erc8004/abi.js`.+- **`solana-agent/`** — Solana counterpart. Metaplex Core asset mint + Solana Attestation Service (SAS) attestations.+- **`auth/` + `wallet/`** — SIWE / SIWS for backend mutations; Privy for email/social → embedded wallet onboarding; session cookies after wallet proof.-```-rate = perspective / (perspective + |translateZ|)- = 2.5rem / (2.5rem + (depth × 2.5rem))- = 1 / (depth + 1)-```--So at depth 1: rate = `1/2 = 50%`; at depth 2: rate = `1/3 = 33%`; at depth 5: rate = `1/6 ≈ 17%`; at depth 8: rate = `1/9 ≈ 11%`.--The depth values `8 > 5 > 2 > 1` correctly produce scroll rates `11% < 17% < 33% < 50%` — each closer layer moves faster. The gap between values is nonlinear: going from depth 8 to depth 5 is a large jump in scroll rate (11% to 17%), while going from depth 2 to depth 1 is a smaller jump (33% to 50%). This nonlinearity means you get dramatic separation at the far end and subtler separation at the near end — which is how real-world parallax works, as atmospheric perspective compresses apparent depth differences at distance.--**Choosing your own depth values:** Keep the ratio between adjacent depth values large enough to produce a visible difference. Values too close together (e.g., `3`, `2.5`, `2`, `1.5`) produce a nearly flat-looking result because the scroll rate differences are tiny. Values too far apart (e.g., `20`, `10`, `5`, `1`) can make the foreground layer scroll so fast it looks jarring. The range `1–10` with nonlinear spacing works well for most hero sections.+Per-chain registry addresses, ABIs, and helpers ship as `@three-ws/sdk`. ENS attestations are also handled here — see [register-onchain.md](./tutorials/register-onchain.md).----## `object-position` as Crop Control--Each parallax layer is displayed using `object-fit: cover` (or equivalent background behavior), which crops the image to fill its container. The `--md-image-position` CSS variable controls where in the image the crop is taken from, horizontally:+## Layer 4 — Embed-```css-.parallax__layer img {- object-fit: cover;- object-position: calc(var(--md-image-position) * 1%) center;-}-```+**What it owns:** the public face. The web component, widgets, iframe surfaces, the CDN bundle, the SPA, edge routing.-`--md-image-position: 0` crops to the left edge of the image. `--md-image-position: 100` crops to the right edge. `--md-image-position: 50` centers the image (the default).+**Doesn't know about:** the contents of the manifest, what the LLM said, what the avatar is doing — only that they should be presented somewhere.-This is primarily useful for adjusting the composition after images are placed. If your mountain peak is 20% from the right edge of your source image, set `--md-image-position: 80` to shift the crop rightward so the peak is centered in the viewport.+Modules:-Each layer has its own `--md-image-position` value, allowing independent horizontal positioning of each depth plane. A common technique is to set the foreground layer's position slightly offset from the background — a foreground rock formation at 40% and the background peak at 60% creates a natural sense of different horizontal planes.+- **`element.js`** — `<agent-3d>` custom element. Lazy-boots via `IntersectionObserver` (unless `eager`). Enforces origin allowlist. Exposes attributes for `body`, `brain`, `agent-id`, `manifest`, `mode` (`inline` / `floating` / `section` / `fullscreen`), `voice`, and more. Public methods: `say()`, `ask()`, `installSkill()`, `expressEmotion()`, `play()`, `lookAt()`, `dispose()`.+- **`agent-stage.js`** — `<agent-stage>` for hosting multiple agents in one shared scene. See [multi-agent.md](./multi-agent.md).+- **`widget-types.js`** — the five widget variants: Turntable, Animation Gallery, Talking Agent, ERC-8004 Passport, Hotspot Tour.+- **`lib.js`** — the CDN entry. Imports the element, registers it, re-exports the public surface (`defineElement`, `Agent3DElement`, `AgentStageElement`, helpers).+- **`embed-action-bridge.js`** — the `postMessage` protocol. Iframe widgets and the web component speak the same dialect, so host pages can drive either with the same code.+- **`app.js`** — the main SPA. URL routing via hash (`#model=`, `#agent=`, `#kiosk=`) and query (`?agent=`) params.+- **`vercel.json`** — edge routing. Clean URLs (`/agent/<id>`, `/agent/<id>/embed`, `/a/<chainId>/<agentId>`, `/w/<widget-id>`) map to the right HTML entries.-**Important:** Because scale compensation increases the displayed size of far layers dramatically, far layers (depth 8) have a large amount of image content outside the visible area. Adjusting `--md-image-position` for far layers shifts through a wide panorama smoothly. For near layers (depth 1), the image is scaled less, so the same change in `--md-image-position` value moves the crop over a smaller physical distance — adjustment is more sensitive.+The embed layer's contract is the only thing third-party developers see directly. Keep its API surface small and stable; changes here are breaking changes per [SemVer](./changelog.md#versioning-policy).----## Scene Composition Principles--### Horizon Alignment--All layers should share the same horizon line — the perceived eye level of the scene. If the background sky meets the mountains at one-third of the image height, the mid-ground trees should also start roughly at one-third, with their roots near the bottom. Mismatched horizon lines make layers feel like they are from different scenes even when the content is superficially similar.+## Cross-cutting: the protocol bus-### Foreground Anchoring to the Bottom+Every layer above the Viewer subscribes to the same `agent-protocol` event bus.-Foreground elements should be rooted at the _bottom_ of the image frame, not floating in the middle. Plants, rocks, architectural elements, and terrain features that anchor to the bottom edge of the frame appear to "sit" on the ground plane, which is where the user expects near objects to be. Floating foreground elements — a tree whose trunk is not connected to the bottom of the frame — look ungrounded and break the illusion.--Set the foreground layer's `object-position` vertical value to `bottom` to ensure the anchoring is respected:--```css-.parallax__layer--foreground img {- object-position: calc(var(--md-image-position) * 1%) bottom;-}-```+- **Avatar layer** listens for `speak`, `gesture`, `skill-done`, `skill-error`, `validate`, `load-*` to pick emotion blends.+- **Identity layer** listens for `speak`, `remember`, `sign`, `skill-done`, `validate`, `load-end` and persists them.+- **Chat UI** listens for `speak` (render bubbles) and `voice:transcript` (live STT).+- **Memory** listens for `remember`.+- **`postMessage` bridge** mirrors a curated subset to host pages.-### Color Consistency+None of these modules know about each other. They subscribe by event type. That's the whole abstraction — and the reason any one of them can be ripped out and replaced.-All layers should be lit from the same direction with the same color temperature. A background with warm afternoon sun (golden, directional) combined with a foreground painted with cool overcast light (flat, blue-white) will look artificial regardless of how precise your depth values are. The eye immediately detects lighting inconsistency as a sign that the image is composited.--If your layers come from different source photographs, do color grading passes to unify the white balance, shadow tone, and highlight color before exporting. A quick way to check: convert all layers to grayscale and verify that the contrast and tonal ranges match across layers.-------## Edge Handling: Avoiding Hard Cutout Artifacts--When a transparent layer is scaled up by the CSS `scale()` transform, its edges are also scaled up. If your transparent layer has a hard pixel edge — one row of semi-transparent pixels and then fully transparent — that hard edge will become visible as a sharp line when the layer is scaled into the viewport.--Fix this by painting a soft feathered edge on transparent layers. In Photoshop: apply a `Refine Edge` or `Select and Mask` operation on your transparency mask with 20–40px feathering before exporting. In Figma: use `Blur > Layer Blur` on the edge regions at a low value (4–8px) before exporting. In Affinity Photo: use the "Feather" slider in the Pixel Selection panel.--The amount of feathering needed scales with your depth value. Layers at depth 2 (scale 3×) need more feathering than layers at depth 1 (scale 2×), because the larger scale factor amplifies edge sharpness more.-------## Testing Layers Before AVIF Conversion--AVIF conversion is lossy and takes time. Before committing to the AVIF encoding step, verify your layer composition using PNG files in a browser.--The fastest method: stack your PNG layers in a `<div>` with `position: absolute; inset: 0` on each layer, then view it in a browser. If the layers look correct as a flat composite, they will look correct in the parallax hero (depth and scroll behavior aside).--For a more accurate preview, open your layer stack in **Figma** or **Photoshop** as individual layers in a single file. Toggle each layer's visibility to confirm that each plane contains only the content intended for that depth. Check that transparent regions are genuinely transparent, not filled with white or black.--Pay particular attention to:--- The mid-background layer's sky region (should be transparent, not solid)-- The foreground layer's upper region (should be transparent above the foreground objects)-- The exact bottom edge of all non-background layers (should feather out, not hard-cut)--Once you are satisfied with the PNG composite, convert to AVIF using `squoosh`, `avifenc`, or your image editing application's export dialog. Encode at quality 60–75 for photographic content and 75–85 for illustrated/painted content. Check the output file in a browser before publishing.-------## File Placement--Place finished AVIF files at:--```-docs/assets/hero/[email protected]-docs/assets/hero/[email protected]-docs/assets/hero/[email protected]-docs/assets/hero/[email protected]-```--MkDocs Material automatically copies the entire `docs/assets/` directory to the built site's `assets/` directory. No additional configuration is required. The paths used in `home.html` should reference `/assets/hero/` (without the `docs/` prefix) because MkDocs strips the `docs/` root from all asset paths in the build output.--**Linux file path note:** File paths on Linux (including MkDocs' build process and most CI environments) are case-sensitive. `[email protected]` and `[email protected]` are different files. Always use lowercase filenames and verify paths match exactly between the file system and your HTML templates.-------## The `<picture>` Element Structure in `home.html`--Each layer is rendered using a `<picture>` element to support both AVIF and WebP with a PNG fallback:--```html-<picture class="parallax__layer" style="--md-parallax-depth: 8; --md-image-position: 50">- <source type="image/avif" srcset="/assets/hero/[email protected]" />- <source type="image/webp" srcset="/assets/hero/[email protected]" />- <img src="/assets/hero/[email protected]" alt="" loading="eager" decoding="async" />-</picture>-```--Browsers read `<source>` elements in order and use the first type they support. An AVIF-capable browser (Chrome 85+, Firefox 93+, Safari 16+) uses the AVIF. A browser with WebP but no AVIF (Safari 14–15) uses the WebP. Any older browser falls back to the PNG.--The `alt=""` on the `<img>` is intentional. Parallax background images are decorative — they do not convey content that a screen reader user needs. An empty `alt` attribute tells assistive technology to ignore the image entirely, which is the correct behavior.--The `loading="eager"` attribute on the first (far background) layer ensures it begins loading immediately, avoiding a flash of empty background. Layers at depth 2 and 1 (near and foreground) can use `loading="lazy"` if desired, since they are partially revealed only as the user scrolls.--### Adding a WebP Fallback Source--If you only export AVIF files initially and want to add WebP fallbacks later:--1. Convert each AVIF source to WebP using `squoosh` or `cwebp`: `cwebp -q 80 [email protected] -o docs/assets/hero/[email protected]`-2. Place the WebP files alongside the AVIF files in `docs/assets/hero/`-3. Add a `<source type="image/webp">` element to each `<picture>` block, between the AVIF source and the `<img>` tag-------## Common Mistakes--**Depth values too close together.** Using depths like `4`, `3`, `2`, `1` produces almost no visible parallax separation. The scroll rate difference between depth 4 (`rate = 1/5 = 20%`) and depth 3 (`rate = 1/4 = 25%`) is only 5 percentage points. Spread your values further apart.--**Forgetting transparency on non-background layers.** The mid-ground and near-ground layers must have transparent backgrounds. Exported PNGs with white or black backgrounds turn into opaque rectangles that cover the layers behind them, making the scene look like a stack of colored blocks.--**Wrong file paths (case-sensitive on Linux).** The most common deploy-time bug. The file is `[email protected]` but the template references `[email protected]`. Works fine on macOS (case-insensitive filesystem), fails silently on Linux CI and production. Standardize on all-lowercase filenames.--**Not accounting for scale when evaluating image quality.** A layer at depth 5 (scale factor 6×) will be rendered at 6× its natural size. Zoom into your AVIF file at 600% in a browser before publishing to check that it does not show blocking artifacts or excessive blurring at the scale it will be displayed.--**Using portrait or square images.** The parallax CSS renders layers in a wide landscape viewport. Portrait images will be cropped heavily, often showing nothing but a narrow vertical strip of content. Always work with landscape-format (wider-than-tall) source images.--**Opacity on individual layers without considering blending.** If you add `opacity` to a mid-ground layer to create a haze effect, note that CSS `opacity` creates a new stacking context, which can interact unexpectedly with `z-index`. Use `mix-blend-mode` or AVIF-level transparency instead.+If you're building a custom layer (a 2D sprite avatar, a vector-store memory backend, a different LLM provider), you only need to listen to and emit the same event vocabulary. Everything else is wiring.----## Swapping Layers Without Breaking the Site--To replace existing layer images:+## Build targets-1. Prepare your new AVIF (and optionally WebP) files following the naming conventions above.-2. Place them in `docs/assets/hero/`.-3. Open `docs/overrides/home.html` (or wherever your theme's `home.html` override lives).-4. Update the `srcset` path in each `<source>` element and the `src` in the `<img>` fallback to point to your new filenames.-5. Adjust `--md-parallax-depth` and `--md-image-position` custom properties on each `<picture>` element if your new scene has different depth requirements or needs a horizontal crop offset.-6. Run `mkdocs serve` locally and scroll through the hero to visually verify the layers.-7. Check that transparent layers do not show hard edges or cutout artifacts.-8. Run `mkdocs build` to generate the static site and confirm the AVIF files appear in `site/assets/hero/`.+The same source tree produces three independent builds:-If you want to update only one layer — for example, replacing the foreground with a seasonal variation — you only need to update that one `<picture>` block and its associated file. The other layers are independent.+- **App** — `npm run build`. The full SPA into `dist/`. Editor, agent pages, discover, studio, PWA manifest. Multi-page Rollup config with a Vercel-style dev middleware.+- **Library** — `npm run build:lib`. `src/lib.js` → `dist-lib/agent-3d.js` (ES module + UMD). Three.js and ethers stay bundled — the file is intentionally self-contained so a single `<script type="module">` is the only thing a third party needs.+- **Artifact** — `vite.config.artifact.js`. A zero-dependency bundle for Claude artifact embeds. Inlined everything, no external script tags, no dynamic imports.-After a layer swap, clear your browser cache or use an incognito window to test, since browsers aggressively cache image resources and may serve the old image even after a rebuild.+Versioned CDN bundles are published at `/agent-3d/<version>/agent-3d.js`. Use `latest` for auto-updates or pin to a version for stability. See [changelog.md](./changelog.md) for release history.----## Quick Reference: Layer Properties--| Property | Far Background | Mid-Background | Near-Ground | Foreground |-| --------------------- | -------------- | -------------- | ----------- | ---------- |-| `--md-parallax-depth` | `8` | `5` | `2` | `1` |-| Scale factor | `9×` | `6×` | `3×` | `2×` |-| Visual scroll rate | ~11% | ~17% | ~33% | ~50% |-| Needs transparency | No | Yes | Yes | Yes |-| Recommended width | 3000px | 2800px | 2400px | 2400px |-| `loading` attribute | `eager` | `eager` | `lazy` | `lazy` |-| `z-index` (auto) | 2 | 5 | 8 | 9 |+## What's next-Adjust `--md-parallax-depth` first when you want to change how dramatic the parallax separation feels. Adjust `--md-image-position` when you want to shift the horizontal crop without changing the depth behavior.+- **[Architecture overview](./architecture.md)** — module-by-module deep dive+- **[Agent system](./agent-system.md)** — runtime, skills, memory in detail+- **[Embedding](./embedding.md)** — the public face of the embed layer+- **[SDK reference](./sdk.md)** — `@three-ws/sdk` and friendsdiff --git a/docs/listings.md b/docs/listings.mdindex 93371b2a1..cecef5688 100644--- a/docs/listings.md+++ b/docs/listings.md@@ -12,10 +12,10 @@ Cloud marketplaces are the procurement flow enterprises use to acquire software| Cloud | Status | Links ||---|---|---|+| **AWS** Marketplace | Live | three.ws is an AWS Partner. Subscribe via AWS Marketplace to consolidate billing on your AWS account; subscriptions auto-issue an x402 API key via the marketplace entitlement service. See [aws-marketplace.md](./aws-marketplace.md). || **Alibaba Cloud** International Marketplace | Live | [Product listing](https://marketplace.alibabacloud.com/products/56724001/sgcmfw00036800.html) · [Storefront](https://marketplace.alibabacloud.com/store/3247293.html) · [Announcement](/blog/three-ws-on-alibaba-cloud-marketplace.html) || **Google Cloud** Marketplace | Open to partnership | three.ws runs on WebGL, Vercel edge, and EVM — a natural fit for Vertex AI and GCP's global CDN. Reach out for co-listing, credits, and joint GTM. |-| **AWS** Marketplace | On roadmap | Targeted for the cross-marketplace expansion phase described in the [Alibaba launch post](/blog/three-ws-on-alibaba-cloud-marketplace.html). |-| **Microsoft Azure** Marketplace | On roadmap | Targeted alongside AWS. |+| **Microsoft Azure** Marketplace | On roadmap | Targeted alongside the AWS/Alibaba rollout. |---diff --git a/docs/mcp.md b/docs/mcp.mdindex 8b5c26997..7b51ea6d0 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -104,7 +104,7 @@ Add to `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS)"mcpServers": {"3dagent": {"command": "npx",- "args": ["-y", "@3dagent/mcp-server", "--url", "https://three.ws/"]+ "args": ["-y", "@3d-agent/mcp-server", "--url", "https://three.ws/"]}}}@@ -349,7 +349,7 @@ Here is a realistic conversation showing how Claude uses the MCP tools end-to-en1. `get_avatar({ slug: "storm-mage" })` — resolves the UUID and model URL.-2. `validate_model({ url: "https://cdn.three.wsu/…/storm-mage.glb" })` — runs the Khronos validator.+2. `validate_model({ url: "https://cdn.three.ws/u/…/storm-mage.glb" })` — runs the Khronos validator.Response:```@@ -358,7 +358,7 @@ Here is a realistic conversation showing how Claude uses the MCP tools end-to-en[WRN] NODE_EMPTY: node "Armature" has no mesh and no children```-3. `inspect_model({ url: "https://cdn.three.wsu/…/storm-mage.glb" })` — structural overview.+3. `inspect_model({ url: "https://cdn.three.ws/u/…/storm-mage.glb" })` — structural overview.Response:```@@ -417,7 +417,7 @@ Tool execution errors (avatar not found, fetch failure, validation library crashClone the repo and start the dev server:```bash-git clone https://github.com/3dagent/3dagent+git clone https://github.com/nirholas/three.wsnpm installnpm run dev# MCP endpoint: http://localhost:5173/api/mcpdiff --git a/docs/memory.md b/docs/memory.mdindex 3240c1bd0..036f56aff 100644--- a/docs/memory.md+++ b/docs/memory.md@@ -1,6 +1,6 @@# Memory System-Agent memory lets a three.ws remember things between sessions. Without it, every conversation starts fresh — the agent has no idea who you are, what you talked about last time, or what preferences you've stated. With memory, the agent builds up a persistent model of the user and context that it draws on automatically at the start of each conversation.+Agent memory lets an agent remember things between sessions. Without it, every conversation starts fresh — the agent has no idea who you are, what you talked about last time, or what preferences you've stated. With memory, the agent builds up a persistent model of the user and context that it draws on automatically at the start of each conversation.This document covers how agent memory works, how to configure storage modes, and how to read and write memories from code.diff --git a/docs/permissions.md b/docs/permissions.mdindex 697bfda3a..22e0784af 100644--- a/docs/permissions.md+++ b/docs/permissions.md@@ -62,11 +62,11 @@ When a skill or agent action requires a delegation that doesn't yet exist, the g### Programmatically-Use `encodeScopedDelegation` and `signDelegation` from `@3dagent/sdk/permissions` (or directly from [src/permissions/toolkit.js](../../src/permissions/toolkit.js)):+Use `encodeScopedDelegation` and `signDelegation` from `@three-ws/sdk/permissions` (or directly from [src/permissions/toolkit.js](../../src/permissions/toolkit.js)):```js-import { encodeScopedDelegation, signDelegation } from '@3dagent/sdk/permissions';-import { CAVEAT_ENFORCERS } from '@3dagent/sdk/erc7710';+import { encodeScopedDelegation, signDelegation } from '@three-ws/sdk/permissions';+import { CAVEAT_ENFORCERS } from '@three-ws/sdk/erc7710';import { AbiCoder } from 'ethers';const CHAIN_ID = 84532; // Base Sepolia@@ -129,7 +129,7 @@ const res = await fetch('/api/permissions/grant', {Skills call `redeemFromSkill` from [src/runtime/delegation-redeem.js](../../src/runtime/delegation-redeem.js). This is the main entrypoint for any on-chain action a skill needs to take:```js-import { redeemFromSkill } from '@3dagent/sdk/runtime';+import { redeemFromSkill } from '@three-ws/sdk/runtime';// Inside a skill handler:export async function execute_swap({ tokenIn, tokenOut, amount }, ctx) {@@ -164,7 +164,7 @@ export async function execute_swap({ tokenIn, tokenOut, amount }, ctx) {To monitor redemption events:```js-import { subscribeRedeemEvents } from '@3dagent/sdk/runtime';+import { subscribeRedeemEvents } from '@three-ws/sdk/runtime';const unsubscribe = subscribeRedeemEvents((event) => {console.log(event.type, event.payload);@@ -181,7 +181,7 @@ const unsubscribe = subscribeRedeemEvents((event) => {Mount the panel for an agent:```js-import { mountManagePanel } from '@3dagent/sdk/permissions';+import { mountManagePanel } from '@three-ws/sdk/permissions';const { unmount } = mountManagePanel({container: document.getElementById('permissions-container'),@@ -197,7 +197,7 @@ Revoking has two parts: the on-chain transaction and the server-side mirror.```jsimport { Contract, BrowserProvider } from 'ethers';-import { DELEGATION_MANAGER_DEPLOYMENTS, DELEGATION_MANAGER_ABI } from '@3dagent/sdk/erc7710';+import { DELEGATION_MANAGER_DEPLOYMENTS, DELEGATION_MANAGER_ABI } from '@three-ws/sdk/erc7710';// 1. Submit disableDelegation on-chainconst provider = new BrowserProvider(window.ethereum);diff --git a/docs/quick-start.md b/docs/quick-start.mdindex 0f3de51ec..ce56c9a70 100644--- a/docs/quick-start.md+++ b/docs/quick-start.md@@ -8,7 +8,7 @@ Get a live three.ws on your page in under 10 minutes.- **Browser:** Chrome 90+, Firefox 89+, or Safari 15+ (WebGL 2.0 required)- **A 3D model:** GLB/glTF file. No model yet? Use the sample avatar below.-- **Node.js 18+:** Only needed if you're running the dev server or building from source.+- **Node.js 24.x:** Only needed if you're running the dev server or building from source.---@@ -28,7 +28,7 @@ The fastest path. No npm, no bundler, no build step.</head><body><script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>- <agent-3d body="https://cdn.three.wsmodels/sample-avatar.glb"></agent-3d>+ <agent-3d body="https://cdn.three.ws/models/sample-avatar.glb"></agent-3d></body></html>```@@ -49,16 +49,16 @@ The fastest path. No npm, no bundler, no build step.## Option B — npm Install-For projects that have a build step (Vite, Webpack, Create React App, etc.):+For projects that have a build step (Vite, Webpack, Create React App, Next.js, etc.):```bash-npm install @3dagent/sdk+npm install @three-ws/sdk```### Plain JS / Vite```js-import '@3dagent/sdk'; // registers <agent-3d> as a side effect+import '@three-ws/sdk'; // registers <agent-3d> as a side effect// The custom element is now available in HTML, or create it programmatically:const agent = document.createElement('agent-3d');@@ -67,10 +67,10 @@ agent.style.cssText = 'width:400px;height:500px;display:block';document.body.appendChild(agent);```-### React+### React / Next.js```jsx-import '@3dagent/sdk';+import '@three-ws/sdk';export function AgentWidget() {return (@@ -82,7 +82,14 @@ export function AgentWidget() {}```-React passes unknown attributes to native elements as-is, so all `<agent-3d>` attributes work without wrappers.+React passes unknown attributes to native elements as-is, so all `<agent-3d>` attributes work without wrappers. In Next.js App Router, mark the importing module as a client component (`'use client'`).++> Other published SDKs you may want alongside `@three-ws/sdk`:+>+> - `@three-ws/agent-ui` — pre-built chat panel, voice button, accessory dock+> - `@three-ws/avatar` — programmatic avatar loader and animator (Node + browser)+> - `@three-ws/solana-agent` — Solana identity + Metaplex Core helpers+> - `@3d-agent/mcp-server` — MCP server you point Claude Desktop, Cursor, or Claude Code at---@@ -115,7 +122,7 @@ See the [CORS gotcha](#cors) below if your GLB is on a different domain.## Adding an AI Brain-The `brain` attribute turns the 3D viewer into a conversational agent. Pass a Claude model ID:+The `brain` attribute turns the 3D viewer into a conversational agent:```html<agent-3d@@ -130,7 +137,7 @@ The `brain` attribute turns the 3D viewer into a conversational agent. Pass a Cl| Attribute | What it does ||-----------|--------------|-| `brain` | Claude model ID to use for the LLM brain (`claude-sonnet-4-6`, `claude-opus-4-7`, `claude-haiku-4-5-20251001`). Omit for a viewer-only display with no AI. |+| `brain` | LLM model ID. Anthropic: `claude-sonnet-4-6`, `claude-opus-4-7`, `claude-haiku-4-5`. OpenAI: `gpt-4o`, `gpt-4o-mini`. Omit for a viewer-only display with no AI. || `instructions` | System prompt for the agent's personality and role. || `mode` | Layout mode: `inline` (flows with page content), `floating` (fixed bubble in a corner), `fullscreen`, or `section`. Default: `inline`. |@@ -141,7 +148,7 @@ The chat input and microphone button appear automatically when `brain` is set. TIf you've registered an agent on the platform, load it by its UUID instead:```html-<agent-three.ws-id="a1b2c3d4-e5f6-7890-abcd-ef1234567890"></agent-3d>+<agent-3d agent-id="a1b2c3d4-e5f6-7890-abcd-ef1234567890"></agent-3d>```The element fetches the agent manifest — which includes the model URL, instructions, skills, and memory configuration — from the API. No other attributes needed.@@ -173,7 +180,7 @@ The fastest path to an embeddable 3D experience is an iframe widget. Build one i| `passport` | On-chain identity card backed by ERC-8004. || `hotspot-tour` | Annotated 3D scenes with clickable points of interest. |-For the full widget API including `postMessage` events, see the [Widget docs](../WIDGETS.md).+For the full widget API including `postMessage` events, see the [Widget docs](./widgets.md).---@@ -182,8 +189,8 @@ For the full widget API including `postMessage` events, see the [Widget docs](..For contributors or self-hosters:```bash-git clone https://github.com/nirholas/3d-agent.git-cd 3d-agent+git clone https://github.com/nirholas/three.ws.git+cd three.wsnpm installcp .env.example .env # fill in your API keys (see below)npm run dev@@ -256,7 +263,8 @@ The browser's `getUserMedia` API (microphone access for push-to-talk) requires HIf your page has a strict `Content-Security-Policy`, the script embed needs:```-script-src 'self' https://cdn.three.ws;+script-src 'self' https://three.ws;+connect-src 'self' https://three.ws https://cdn.three.ws;```If you're embedding inside a sandboxed iframe, make sure the parent grants `allow-scripts allow-same-origin`. For sandboxed environments where the script embed won't work, use the iframe widget instead — it runs in its own browsing context and is unaffected by the parent CSP.@@ -271,7 +279,8 @@ If you're embedding inside a sandboxed iframe, make sure the parent grants `allo## Next Steps-- [Embed Guide](../how-it-works.md) — deep dive on attributes, events, and the JS API-- [Widget Types](../WIDGETS.md) — full reference for iframe embeds and postMessage-- [Agent System](../ARCHITECTURE.md) — how the brain, memory, and skills layer work-- [API Reference](../API.md) — backend endpoints for uploading models and managing agents+- [Embedding Guide](./embedding.md) — deep dive on attributes, events, and the JS API+- [Widget Types](./widgets.md) — full reference for iframe embeds and postMessage+- [Agent System](./agent-system.md) — how the brain, memory, and skills layers work+- [REST API](./api-reference.md) and [JavaScript API](./js-api.md) — backend and in-browser surfaces+- [SDK Reference](./sdk.md) — `@three-ws/sdk`, `@three-ws/agent-ui`, `@three-ws/avatar`, `@three-ws/solana-agent`diff --git a/docs/reputation.md b/docs/reputation.mdindex 55e089e8d..1f78e869b 100644--- a/docs/reputation.md+++ b/docs/reputation.md@@ -45,7 +45,7 @@ A full reputation dashboard — showing aggregate stats and all recent reviews### Via the SDK```js-import { submitReputation } from '@3dagent/sdk/erc8004';+import { submitReputation } from '@three-ws/sdk/erc8004';const txHash = await submitReputation({chainId: 8453, // Base mainnet@@ -84,7 +84,7 @@ The `ReputationDashboard` class ([src/reputation-ui.js](../../src/reputation-ui.### Via the SDK```js-import { getReputation, getRecentReviews } from '@3dagent/sdk/erc8004';+import { getReputation, getRecentReviews } from '@three-ws/sdk/erc8004';// Aggregate statsconst { total, count, average } = await getReputation({diff --git a/docs/sdk.md b/docs/sdk.mdindex 31df4724c..084d1044e 100644--- a/docs/sdk.md+++ b/docs/sdk.md@@ -5,7 +5,7 @@ This document covers programmatic use of three.ws beyond simple embedding. There| Artifact | Package | Use case ||---|---|---|| **Web component bundle** | `agent-3d.js` (CDN or `TARGET=lib` build) | Drop-in `<agent-3d>` element + programmatic viewer/runtime APIs |-| **AgentKit SDK** | `@nirholas/agent-kit` | Ship an ERC-8004 agent: chat panel, on-chain registration, `.well-known` manifests |+| **AgentKit SDK** | `@three-ws/sdk` | Ship an ERC-8004 agent: chat panel, on-chain registration, `.well-known` manifests |Both are Apache-2.0 licensed. Neither requires the other.@@ -32,7 +32,7 @@ Both are Apache-2.0 licensed. Neither requires the other.```bash# The main repo — build TARGET=lib yourself, or import src/lib.js directly-git clone https://github.com/3dagent/3dagent+git clone https://github.com/nirholas/three.wsnpm installnpm run build:lib # → dist-lib/agent-3d.js + dist-lib/agent-3d.umd.cjs```@@ -135,14 +135,14 @@ const json = await res.json();----## @nirholas/agent-kit SDK+## @three-ws/sdkA separate package for shipping ERC-8004 agents. It does not depend on the viewer — it's backend-friendly and works in any JS environment (Node, browser, edge functions).### Installation```bash-npm install @nirholas/agent-kit+npm install @three-ws/sdk````ethers@^6` is a peer dependency — only needed for on-chain operations (`register`, `connectWallet`).@@ -150,8 +150,8 @@ npm install @nirholas/agent-kit### Quick start```js-import { AgentKit } from '@nirholas/agent-kit';-import '@nirholas/agent-kit/styles';+import { AgentKit } from '@three-ws/sdk';+import '@three-ws/sdk/styles';const agent = new AgentKit({name: 'Aria',@@ -245,7 +245,7 @@ import {IDENTITY_REGISTRY_ABI,REGISTRY_DEPLOYMENTS,agentRegistryId,-} from '@nirholas/agent-kit';+} from '@three-ws/sdk';```**Connect a wallet:**@@ -280,7 +280,7 @@ const { agentId, registrationCID, txHash } = await registerAgent({Grant, verify, and revoke scoped spending delegations:```js-import { PermissionsClient } from '@nirholas/agent-kit/permissions';+import { PermissionsClient } from '@three-ws/sdk/permissions';const client = new PermissionsClient({ baseUrl: 'https://three.ws/' });@@ -315,7 +315,7 @@ For tree-shaking and direct toolkit access:import {encodeScopedDelegation,isDelegationValid,-} from '@nirholas/agent-kit/permissions/advanced';+} from '@three-ws/sdk/permissions/advanced';```### TypeScript support@@ -336,7 +336,7 @@ import type {PermissionsClient,DelegationScope,ScopePreset,-} from '@nirholas/agent-kit';+} from '@three-ws/sdk';const options: AgentKitOptions = {name: 'Aria',@@ -353,7 +353,7 @@ const result: RegistrationResult = await agent.register();## Building from source```bash-git clone https://github.com/3dagent/3dagent+git clone https://github.com/nirholas/three.wsnpm install# Build the web component library (agent-3d.js + agent-3d.umd.cjs)diff --git a/docs/security.md b/docs/security.mdindex 866a8235f..aaecc1343 100644--- a/docs/security.md+++ b/docs/security.md@@ -192,7 +192,7 @@ Scopes are checked on every request via `hasScope(bearer.scope, 'required:scope'## On-chain identity security-The ERC-8004 identity, reputation, and validation registries introduce a distinct security surface. Key threats and mitigations from the [threat model](https://github.com/3dagent/3dagent):+The ERC-8004 identity, reputation, and validation registries introduce a distinct security surface. Key threats and mitigations from the [threat model](https://github.com/nirholas/three.ws):### Model integrity (V2)diff --git a/docs/skills.md b/docs/skills.mdindex da5351cbb..b7155cc79 100644--- a/docs/skills.md+++ b/docs/skills.md@@ -1,6 +1,6 @@# Skills System-Skills are the extension mechanism for three.wss — modular, portable capability bundles that tell an agent *what it can do* and *how to do it*. A skill packages together the LLM instructions, the tool schema, and the JavaScript handler that runs when the tool is called. Because a skill is just a directory of files served from any URL, the same wave skill can be installed in every agent you build without copying any code.+Skills are the extension mechanism for three.ws — modular, portable capability bundles that tell an agent *what it can do* and *how to do it*. A skill packages together the LLM instructions, the tool schema, and the JavaScript handler that runs when the tool is called. Because a skill is just a directory of files served from any URL, the same wave skill can be installed in every agent you build without copying any code.This document covers how to install skills, how to write them, the full context API available to handlers, the security model, and the lifecycle events that let host pages observe skill execution.@@ -70,7 +70,7 @@ Reference skills by URI in the agent's `manifest.json`. The runtime fetches and```json{"skills": [- { "uri": "https://cdn.three.wsskills/wave/", "version": "0.1.0" },+ { "uri": "https://cdn.three.ws/skills/wave/", "version": "0.1.0" },{ "uri": "ipfs://bafy.../validate-model/", "version": "^1.0.0" }]}@@ -85,7 +85,7 @@ Pass a JSON array to the `skills` attribute:```html<agent-3dagent-id="my-agent"- skills='[{"uri":"https://cdn.three.wsskills/wave/","version":"0.1.0"}]'+ skills='[{"uri":"https://cdn.three.ws/skills/wave/","version":"0.1.0"}]'></agent-3d>```@@ -121,7 +121,7 @@ await el.agent.skills.install({ uri: 'https://example.com/skills/weather/' });// Skill dependencies — installed recursively before this skill"dependencies": {- "https://cdn.three.wsskills/gesture-base/": "^1.0.0"+ "https://cdn.three.ws/skills/gesture-base/": "^1.0.0"},// What this skill adds to the agent@@ -396,8 +396,8 @@ Skills can depend on other skills. The registry installs dependencies recursivel"name": "full-coaching-kit","version": "1.0.0","dependencies": {- "https://cdn.three.wsskills/wave/": "^0.1.0",- "https://cdn.three.wsskills/validate-model/": "^1.0.0"+ "https://cdn.three.ws/skills/wave/": "^0.1.0",+ "https://cdn.three.ws/skills/validate-model/": "^1.0.0"},"provides": { "tools": [] }}@@ -632,7 +632,7 @@ The handler tries to load a style-specific GLB clip from the bundle (e.g. `clips},"brain": {"provider": "anthropic",- "model": "claude-opus-4-6",+ "model": "claude-opus-4-7","instructions": "instructions.md","temperature": 0.8,"maxTokens": 2048diff --git a/docs/smart-contracts.md b/docs/smart-contracts.mdindex 9362b1343..bdc8daea4 100644--- a/docs/smart-contracts.md+++ b/docs/smart-contracts.md@@ -39,7 +39,7 @@ Chains: BSC Testnet (97), Ethereum Sepolia (11155111), Base Sepolia (84532), ArbAlways read addresses from the SDK rather than hardcoding them:```js-import { REGISTRY_DEPLOYMENTS } from '@3dagent/sdk/erc8004';+import { REGISTRY_DEPLOYMENTS } from '@three-ws/sdk/erc8004';const { identityRegistry, reputationRegistry, validationRegistry } =REGISTRY_DEPLOYMENTS[chainId];diff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex fb4c74453..907fc32e4 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -113,7 +113,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix1. Check the `brain` attribute. The agent only activates LLM mode when `brain` is set to a model name:```html- <agent-3d brain="claude-opus-4-6" ...></agent-3d>+ <agent-3d brain="claude-opus-4-7" ...></agent-3d>```Without this attribute, `brain.provider` defaults to `none` and the agent uses `NullProvider`, which returns empty responses silently.2. Open DevTools → Network. Filter for `/api/chat` or `/api/llm`. Look at the response:diff --git a/docs/tutorials/embed-on-website.md b/docs/tutorials/embed-on-website.mdindex dde17265f..8f66c35b0 100644--- a/docs/tutorials/embed-on-website.md+++ b/docs/tutorials/embed-on-website.md@@ -1,6 +1,6 @@-# Embed a three.ws on Your Website+# Embed a three.ws agent on Your Website-This tutorial walks you through every path for adding a three.ws to your site — from a no-code copy-paste to a full React integration. Pick the path that matches how you build.+This tutorial walks you through every path for adding a three.ws agent to your site — from a no-code copy-paste to a full React integration. Pick the path that matches how you build.**What you'll learn:**- Get an embed snippet from the Studio (no coding required)@@ -13,7 +13,7 @@ This tutorial walks you through every path for adding a three.ws to your site## Before you start-You need an agent ID. Go to [three.wsstudio](https://three.ws/studio), select or create an agent, and note its ID — it looks like `a_abc123` or is a number paired with a chain ID like `42` on Base.+You need an agent ID. Go to [three.ws/studio](https://three.ws/studio), select or create an agent, and note its ID — it looks like `a_abc123` or is a number paired with a chain ID like `42` on Base.---@@ -21,7 +21,7 @@ You need an agent ID. Go to [three.wsstudio](https://three.ws/studio), select orIf you don't want to write code, the Studio generates the snippet for you.-1. Go to [three.wsstudio](https://three.ws/studio)+1. Go to [three.ws/studio](https://three.ws/studio)2. Select an agent (or create one — the Talking Agent widget is the most popular starting point)3. Click **Get Embed Code** in the top-right corner4. Choose your widget type and placement@@ -51,7 +51,7 @@ The Studio offers two snippet formats. Here's what each one looks like and when></script><!-- Where you want the agent -->-<agent-three.ws-id="42" chain-id="8453" mode="floating"></agent-3d>+<agent-3d agent-id="42" chain-id="8453" mode="floating"></agent-3d>```The iframe is the safer default for platforms where you can't control the `<head>` (Notion, Substack, Medium). The web component is the right choice anywhere you control the full page — it gives you CSS theming, JS events, and better performance.@@ -117,7 +117,7 @@ For an inline embed with explicit dimensions:**Lazy loading is on by default.** The agent won't boot until it scrolls into the viewport (powered by `IntersectionObserver`). Add `eager` to load immediately regardless:```html-<agent-three.ws-id="42" chain-id="8453" eager></agent-3d>+<agent-3d agent-id="42" chain-id="8453" eager></agent-3d>```---@@ -127,7 +127,7 @@ For an inline embed with explicit dimensions:### Install```bash-npm install @3dagent/sdk+npm install @three-ws/sdk```### Create a wrapper component@@ -137,7 +137,7 @@ npm install @3dagent/sdk'use client'; // Required for Next.js App Routerimport { useEffect, useRef } from 'react';-import '@3dagent/sdk'; // registers <agent-3d> as a custom element+import '@three-ws/sdk'; // registers <agent-3d> as a custom elementexport default function Agent3D({ agentId, chainId = '8453', mode = 'floating' }) {const ref = useRef();@@ -185,7 +185,7 @@ export default function Page() {return (<main><h1>Welcome</h1>- <Agentthree.wsId="42" mode="floating" />+ <Agent3D agentId="42" mode="floating" /></main>);}@@ -314,7 +314,7 @@ add_action('wp_head', 'add_3dagent_script');Then add a **Custom HTML** block in the Gutenberg editor wherever you want the agent:```html-<agent-three.ws-id="42" chain-id="8453"></agent-3d>+<agent-3d agent-id="42" chain-id="8453"></agent-3d>```---@@ -431,13 +431,13 @@ Set a background color with the `background` attribute:```html<!-- Transparent (default) — composites over your page -->-<agent-three.ws-id="42" background="transparent"></agent-3d>+<agent-3d agent-id="42" background="transparent"></agent-3d><!-- Dark scene background -->-<agent-three.ws-id="42" background="dark"></agent-3d>+<agent-3d agent-id="42" background="dark"></agent-3d><!-- Light scene background -->-<agent-three.ws-id="42" background="light"></agent-3d>+<agent-3d agent-id="42" background="light"></agent-3d>```---@@ -460,7 +460,7 @@ Or if the parent truly needs to stack above the agent, wrap the `<agent-3d>` in**Agent is too small / too large**Set explicit `width` and `height` attributes (CSS length values):```html-<agent-three.ws-id="42" width="480px" height="640px"></agent-3d>+<agent-3d agent-id="42" width="480px" height="640px"></agent-3d>```**Next.js hydration error**diff --git a/docs/tutorials/first-agent.md b/docs/tutorials/first-agent.mdindex 2d01cd97f..488c5e195 100644--- a/docs/tutorials/first-agent.md+++ b/docs/tutorials/first-agent.md@@ -1,4 +1,4 @@-# Build Your First three.ws+# Build Your First AgentBy the end of this tutorial you will have a live, talking 3D character on a page you can share with anyone. No build tools, no framework, no prior 3D experience required — just a text editor and a browser.@@ -21,7 +21,7 @@ You need a GLB file — the standard format for 3D models on the web. Here are tThere's a hosted sample avatar ready to use. Just copy the URL below and you're done for this step:```-https://cdn.three.wsmodels/sample-avatar.glb+https://cdn.three.ws/models/sample-avatar.glb```Come back and swap this for your own character later. That's what Step 9 is for.@@ -61,7 +61,7 @@ Create a new folder somewhere on your computer. Inside it, create a file called<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">- <title>My three.ws</title>+ <title>My three.ws Agent</title><style>body {margin: 0;@@ -84,7 +84,7 @@ Create a new folder somewhere on your computer. Inside it, create a file called<script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script><agent-3d- body="https://cdn.three.wsmodels/sample-avatar.glb"+ body="https://cdn.three.ws/models/sample-avatar.glb"width="400px"height="600px"></agent-3d>@@ -129,7 +129,7 @@ Update the `<agent-3d>` tag to add the `brain` and `instructions` attributes:```html<agent-3d- body="https://cdn.three.wsmodels/sample-avatar.glb"+ body="https://cdn.three.ws/models/sample-avatar.glb"brain="claude-sonnet-4-6"name="Aria"instructions="You are Aria, a friendly and enthusiastic AI guide. You love helping people explore the 3D world. Be concise, warm, and occasionally playful. When someone greets you, wave at them. Keep replies to 2–3 sentences unless asked for more."@@ -182,7 +182,7 @@ Create `agent.json` in the same folder as `index.html`:"mode": "local"},"skills": [- { "uri": "https://cdn.three.wsskills/wave/" }+ { "uri": "https://cdn.three.ws/skills/wave/" }],"version": "0.1.0"}@@ -200,7 +200,7 @@ Then update `index.html` to load from the manifest instead of using inline attriThe manifest approach is cleaner for anything beyond a one-liner: you can version it in git, keep the instructions in one place, and load it by URL from anywhere.-> **Note:** If you used the sample avatar URL, replace `./your-character.glb` in the manifest with `https://cdn.three.wsmodels/sample-avatar.glb`.+> **Note:** If you used the sample avatar URL, replace `./your-character.glb` in the manifest with `https://cdn.three.ws/models/sample-avatar.glb`.---@@ -415,7 +415,7 @@ Here's the complete `index.html` all in one place:<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">- <title>My three.ws</title>+ <title>My three.ws Agent</title><style>body {margin: 0;@@ -490,7 +490,7 @@ Now that you have a working agent, here's what to explore next:- [Memory system](../memory.md) — the agent can remember things across conversations using local storage or IPFS.**Make it permanent:**-- [ERC-8004 registration](../erc8004.md) — register your agent on-chain for a permanent, decentralized identity. Once registered, anyone can load your agent by its on-chain ID: `<agent-three.ws-id="42" chain-id="8453">`.+- [ERC-8004 registration](../erc8004.md) — register your agent on-chain for a permanent, decentralized identity. Once registered, anyone can load your agent by its on-chain ID: `<agent-3d agent-id="42" chain-id="8453">`.**Embed it anywhere:**- [Embedding guide](../embedding.md) — embed Aria as a floating bubble in the corner of any existing website, or as an iframe widget with a single line of code.diff --git a/docs/tutorials/personal-ai-site.md b/docs/tutorials/personal-ai-site.mdindex 0bda7ed0c..87307b438 100644--- a/docs/tutorials/personal-ai-site.md+++ b/docs/tutorials/personal-ai-site.md@@ -262,7 +262,7 @@ Here is the full page. Replace the placeholder values in brackets and swap in yoid="maya"body="https://yourname.com/avatars/maya.glb"agent-id="your-agent-id"- brain="claude-opus-4-6"+ brain="claude-opus-4-7"style="height: calc(100% - 130px); display: block"></agent-3d>diff --git a/docs/tutorials/register-onchain.md b/docs/tutorials/register-onchain.mdindex 33462581b..86df7b9bc 100644--- a/docs/tutorials/register-onchain.md+++ b/docs/tutorials/register-onchain.md@@ -40,7 +40,7 @@ Skip this step if you already have an agent saved to your account.**Option A — Generate from a photo:**-1. Go to [three.wscreate](https://three.ws/create)+1. Go to [three.ws/create](https://three.ws/create)2. Take a selfie or upload a photo3. Your avatar generates in about 30 seconds4. Give it a name and description@@ -48,13 +48,13 @@ Skip this step if you already have an agent saved to your account.**Option B — Upload an existing GLB:**-1. Go to [three.wsapp](https://three.ws/app)+1. Go to [three.ws/app](https://three.ws/app)2. Drag your `.glb` file into the viewer3. Open the **Manifest** tab in the editor panel4. Fill in the name and description fields5. Click **Save to Account**-Either way, you should end up with an agent visible in your dashboard at [three.wsdashboard](https://three.ws/dashboard).+Either way, you should end up with an agent visible in your dashboard at [three.ws/dashboard](https://three.ws/dashboard).---@@ -101,7 +101,7 @@ If you already have ETH on Base, skip ahead to Step 3.## Step 4: Open your agent for editing-1. Go to [three.wsdashboard](https://three.ws/dashboard)+1. Go to [three.ws/dashboard](https://three.ws/dashboard)2. Find the agent you want to register3. Click **Edit** — the editor opens with your avatar loadeddiff --git a/docs/tutorials/web-component-end-to-end.md b/docs/tutorials/web-component-end-to-end.mdindex 222a0e525..a0c2e61a6 100644--- a/docs/tutorials/web-component-end-to-end.md+++ b/docs/tutorials/web-component-end-to-end.md@@ -588,5 +588,5 @@ The web component is the most robust integration point the platform offers. Buil## Next steps- [Drive the agent with the JavaScript API](/tutorials/js-api-events) — methods and events covered in depth-- [Embed a three.ws on your website](/tutorials/embed-on-website) — the no-framework paths (Webflow, WordPress, Squarespace) for completeness+- [Embed a three.ws agent on your website](./embed-on-website.md) — the no-framework paths (Webflow, WordPress, Squarespace) for completeness- [Trigger the agent from page events](/tutorials/trigger-from-page-events) — once it's mounted, make it react to the user journeydiff --git a/docs/web-component.md b/docs/web-component.mdindex 526b1db12..2bc59d61a 100644--- a/docs/web-component.md+++ b/docs/web-component.md@@ -52,7 +52,7 @@ Using `body` with no manifest creates an ad-hoc agent. Its name, instructions, abody="/avatars/guide.glb"name="Guide"instructions="You are a friendly 3D guide."- brain="claude-opus-4-6"+ brain="claude-opus-4-7"></agent-3d>```@@ -74,7 +74,7 @@ Using `body` with no manifest creates an ad-hoc agent. Its name, instructions, a| Attribute | Type | Default | Description ||-----------|------|---------|-------------|-| `brain` | model ID | from manifest | LLM model to use, e.g. `claude-opus-4-6`. Set to `none` to disable the brain entirely. |+| `brain` | model ID | from manifest | LLM model to use, e.g. `claude-opus-4-7`. Set to `none` to disable the brain entirely. || `instructions` | URL or inline text | from manifest | System prompt. Can be a URL ending in `.md` or an inline string. Overrides `manifest.brain.instructions`. || `api-key` | string | — | API key injected directly. **Development use only.** Prefer `key-proxy` for any page that will be public. || `key-proxy` | URL | — | URL of your backend that injects API keys into outbound LLM requests. |@@ -699,7 +699,7 @@ declare namespace JSX {}// Usage-import '@3dagent/sdk';+import '@three-ws/sdk';function AgentCard() {return (@@ -766,7 +766,7 @@ export default defineConfig({</template><script setup>-import '@3dagent/sdk';+import '@three-ws/sdk';function onReady(e) {console.log('ready', e.detail.manifest.name);@@ -780,7 +780,7 @@ Svelte handles custom elements natively. No configuration needed.```svelte<script>- import '@3dagent/sdk';+ import '@three-ws/sdk';let el;function onReady(e) {diff --git a/docs/widget-studio.md b/docs/widget-studio.mdindex b9cddca1c..8859431e6 100644--- a/docs/widget-studio.md+++ b/docs/widget-studio.md@@ -2,7 +2,7 @@Widget Studio is the no-code builder for creating embeddable 3D widgets. Pick an avatar, choose a widget type, configure your brand settings, and get a one-line embed snippet — no code required.-**Access Widget Studio:** [three.wsstudio](https://three.ws/studio)+**Access Widget Studio:** [three.ws/studio](https://three.ws/studio)---@@ -34,7 +34,7 @@ Widget Studio requires an account. When you open the Studio without signing in,### Create a new widget from scratch-1. Go to [three.wsstudio](https://three.ws/studio)+1. Go to [three.ws/studio](https://three.ws/studio)2. Sign in if prompted3. The Studio opens with the default type (Turntable Showcase) pre-selected4. Follow the three steps described below@@ -162,7 +162,7 @@ The oEmbed protocol handles the conversion automatically — no plugin needed.## Managing your widgets-Go to [three.wsdashboard](https://three.ws/dashboard) and click the **Widgets** tab.+Go to [three.ws/dashboard](https://three.ws/dashboard) and click the **Widgets** tab.From the dashboard you can:@@ -188,7 +188,7 @@ Chat message content from Talking Agent widgets is never logged.## Widget gallery-Public widgets are listed at [three.wswidgets](https://three.ws/widgets). Browse the gallery to find inspiration, discover what other creators have built, and copy embed snippets for any listed widget.+Public widgets are listed at [three.ws/widgets](https://three.ws/widgets). Browse the gallery to find inspiration, discover what other creators have built, and copy embed snippets for any listed widget.Filter by widget type, search by name, or sort by popularity or recency.diff --git a/docs/widgets.md b/docs/widgets.mdindex 80623074b..5db647b26 100644--- a/docs/widgets.md+++ b/docs/widgets.md@@ -406,7 +406,7 @@ The `config` object is validated against the type's schema (see [widget-types.js**Widget share URL:** Every widget has a canonical share URL at `https://three.ws/w/<id>`. This URL is server-rendered with Open Graph metadata and a 1200×630 preview image, making it safe to post in Slack, Discord, X, or any link-preview-aware surface.-For the full API reference including request/response shapes, error codes, and pagination, see [API.md](../docs/API.md).+For the full API reference including request/response shapes, error codes, and pagination, see [api-reference.md](./api-reference.md).---diff --git a/public/arbitrage.html b/public/arbitrage.htmlnew file mode 100644index 000000000..4d83c7bfa--- /dev/null+++ b/public/arbitrage.html@@ -0,0 +1,359 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8" />+<meta name="viewport" content="width=device-width,initial-scale=1" />+<title>x402 Arbitrage — same capability, different price</title>+<meta name="description" content="Cross-provider price disparities surfaced live from the merged x402 facilitator catalog. Find the cheapest endpoint for any capability." />+<meta name="theme-color" content="#0a0b10" />+<meta property="og:title" content="x402 Arbitrage — same capability, different price" />+<meta property="og:description" content="Live cross-provider price disparities from the merged x402 catalog." />+<meta property="og:type" content="website" />+<style>+ :root {+ --bg: #0a0b10;+ --bg-2: #0f1119;+ --panel: #14161f;+ --panel-2: #1a1d29;+ --border: #232636;+ --border-strong: #2e3447;+ --text: #f0f2f8;+ --muted: #8a90a8;+ --muted-2: #6b7088;+ --accent-blue: #60a5fa;+ --accent-green: #4ade80;+ --accent-red: #f87171;+ --accent-amber: #f59e0b;+ --accent-purple: #c084fc;+ --mono: ui-monospace, "JetBrains Mono", "Fira Code", Menlo, monospace;+ }+ * { box-sizing: border-box; }+ html, body { margin: 0; padding: 0; background: var(--bg); color: var(--text); }+ body {+ font-family: -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;+ -webkit-font-smoothing: antialiased;+ line-height: 1.5;+ min-height: 100vh;+ }+ a { color: var(--accent-blue); text-decoration: none; }+ a:hover { color: #93c5fd; }++ .wrap { max-width: 1280px; margin: 0 auto; padding: 0 28px; }+ @media (max-width: 720px) { .wrap { padding: 0 16px; } }++ nav {+ padding: 22px 0;+ display: flex; align-items: center; justify-content: space-between;+ border-bottom: 1px solid var(--border);+ flex-wrap: wrap;+ gap: 12px;+ }+ nav .brand { display: flex; align-items: center; gap: 10px; font-weight: 700; font-size: 16px; letter-spacing: -0.01em; }+ nav .brand .dot {+ width: 22px; height: 22px;+ background: conic-gradient(from 200deg, #ffffff, #60a5fa, #ffffff);+ border-radius: 6px;+ }+ nav .links { display: flex; gap: 18px; font-size: 13.5px; color: var(--muted); flex-wrap: wrap; }+ nav .links a { color: var(--muted); }+ nav .links a:hover { color: var(--text); }+ nav .links a.active { color: var(--text); }++ header.hero {+ padding: 38px 0 8px;+ display: flex; align-items: flex-start; justify-content: space-between;+ gap: 24px; flex-wrap: wrap;+ }+ header.hero .left { max-width: 720px; }+ .eyebrow {+ display: inline-flex; align-items: center; gap: 8px;+ font-size: 11px; letter-spacing: 0.14em; text-transform: uppercase;+ color: var(--accent-amber); margin-bottom: 10px;+ font-weight: 600;+ }+ .eyebrow .pulse {+ width: 7px; height: 7px; border-radius: 50%;+ background: var(--accent-amber);+ box-shadow: 0 0 0 0 rgba(245,158,11,0.6);+ animation: pulse 2s infinite;+ }+ @keyframes pulse {+ 0%, 100% { box-shadow: 0 0 0 0 rgba(245,158,11,0.6); }+ 50% { box-shadow: 0 0 0 6px rgba(245,158,11,0); }+ }+ header.hero h1 { font-size: 32px; line-height: 1.15; margin: 0 0 8px; letter-spacing: -0.02em; }+ header.hero p { color: var(--muted); margin: 0; font-size: 15px; }+ .updated {+ font-family: var(--mono); font-size: 11px; color: var(--muted-2);+ letter-spacing: 0.04em;+ text-align: right;+ }+ .updated strong { color: var(--text); font-weight: 600; }++ .toolbar {+ margin: 24px 0 18px;+ display: flex; align-items: center; gap: 10px; flex-wrap: wrap;+ }+ .chip {+ background: var(--panel);+ border: 1px solid var(--border-strong);+ color: var(--muted);+ padding: 7px 13px;+ font-size: 13px;+ border-radius: 999px;+ cursor: pointer;+ }+ .chip:hover { color: var(--text); border-color: var(--accent-blue); }+ .chip.active { background: var(--panel-2); color: var(--text); border-color: var(--accent-blue); }+ .toolbar input[type=search] {+ flex: 1 1 220px;+ min-width: 180px;+ background: var(--panel);+ border: 1px solid var(--border-strong);+ color: var(--text);+ padding: 8px 14px;+ font-size: 13.5px;+ border-radius: 999px;+ outline: none;+ }+ .toolbar input[type=search]:focus { border-color: var(--accent-blue); }+ .toolbar .count { color: var(--muted); font-size: 13px; margin-left: auto; }+ .toolbar .count strong { color: var(--text); font-weight: 600; }++ .grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));+ gap: 14px;+ padding-bottom: 56px;+ }+ .arb {+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 12px;+ padding: 16px;+ display: flex; flex-direction: column; gap: 12px;+ transition: border-color 0.15s ease;+ }+ .arb:hover { border-color: var(--border-strong); }+ .arb .top {+ display: flex; align-items: center; justify-content: space-between;+ gap: 10px; font-size: 11px;+ }+ .type-pill {+ display: inline-flex; align-items: center; gap: 5px;+ background: rgba(96,165,250,0.1);+ color: var(--accent-blue);+ border: 1px solid rgba(96,165,250,0.25);+ padding: 3px 9px;+ border-radius: 999px;+ font-family: var(--mono);+ font-size: 10.5px;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ font-weight: 600;+ }+ .type-pill.mcp { background: rgba(192,132,252,0.1); color: var(--accent-purple); border-color: rgba(192,132,252,0.25); }+ .spread-pill {+ font-family: var(--mono);+ font-size: 11px;+ color: var(--accent-amber);+ font-weight: 600;+ letter-spacing: 0.02em;+ }++ .arb .title {+ font-weight: 600;+ font-size: 15px;+ line-height: 1.3;+ display: flex; gap: 10px; align-items: flex-start;+ }+ .arb .title .icon {+ width: 30px; height: 30px;+ border-radius: 8px;+ background: var(--panel-2);+ border: 1px solid var(--border);+ flex-shrink: 0;+ display: flex; align-items: center; justify-content: center;+ font-size: 13px; color: var(--muted);+ overflow: hidden;+ }+ .arb .title .icon img { width: 100%; height: 100%; object-fit: cover; }+ .arb .title .t {+ flex: 1; min-width: 0;+ word-break: break-word;+ }+ .arb .title .sub {+ color: var(--muted);+ font-weight: 400;+ font-size: 11.5px;+ font-family: var(--mono);+ margin-top: 2px;+ word-break: break-all;+ }++ .stats {+ display: grid;+ grid-template-columns: repeat(4, 1fr);+ gap: 0;+ border: 1px solid var(--border);+ border-radius: 8px;+ overflow: hidden;+ }+ .stats > div {+ padding: 9px 10px;+ border-right: 1px solid var(--border);+ background: var(--bg-2);+ }+ .stats > div:last-child { border-right: none; }+ .stats .k {+ font-size: 9.5px;+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: var(--muted-2);+ margin-bottom: 3px;+ }+ .stats .v {+ font-family: var(--mono);+ font-size: 13px;+ color: var(--text);+ font-weight: 600;+ }+ .stats .v.amber { color: var(--accent-amber); }++ .providers { display: flex; flex-direction: column; gap: 6px; }+ .provider {+ display: flex; align-items: center; gap: 10px;+ padding: 8px 10px;+ background: var(--panel-2);+ border: 1px solid var(--border);+ border-radius: 8px;+ font-size: 12.5px;+ transition: border-color 0.15s ease;+ }+ .provider:hover { border-color: var(--border-strong); }+ .provider.cheapest { border-color: rgba(74,222,128,0.4); background: rgba(74,222,128,0.05); }+ .provider .dot {+ width: 8px; height: 8px; border-radius: 50%;+ background: var(--muted);+ flex-shrink: 0;+ }+ .provider.cheapest .dot { background: var(--accent-green); }+ .provider .host {+ flex: 1; min-width: 0;+ color: var(--text);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ font-family: var(--mono);+ font-size: 11.5px;+ }+ .provider .price {+ font-family: var(--mono);+ font-size: 12px;+ color: var(--text);+ font-weight: 600;+ }+ .provider.cheapest .price { color: var(--accent-green); }+ .provider .fac {+ font-family: var(--mono);+ font-size: 10px;+ color: var(--muted-2);+ }++ .arb .actions {+ display: flex; gap: 8px;+ padding-top: 4px;+ border-top: 1px solid var(--border);+ margin-top: auto;+ }+ .arb .actions button, .arb .actions a {+ flex: 1;+ padding: 8px 10px;+ font-size: 12px;+ border-radius: 8px;+ text-align: center;+ cursor: pointer;+ font-weight: 600;+ font-family: inherit;+ }+ .btn-best {+ background: rgba(74,222,128,0.12);+ color: var(--accent-green);+ border: 1px solid rgba(74,222,128,0.3);+ }+ .btn-best:hover { background: rgba(74,222,128,0.18); }+ .btn-worst {+ background: rgba(248,113,113,0.08);+ color: var(--accent-red);+ border: 1px solid rgba(248,113,113,0.25);+ }+ .btn-worst:hover { background: rgba(248,113,113,0.15); }++ .empty, .err {+ padding: 60px 20px;+ text-align: center;+ color: var(--muted);+ border: 1px dashed var(--border-strong);+ border-radius: 12px;+ margin-bottom: 56px;+ }+ .err { color: #fecaca; border-color: rgba(248,113,113,0.3); }++ .spinner {+ display: inline-block;+ width: 14px; height: 14px;+ border: 2px solid var(--border-strong);+ border-top-color: var(--accent-blue);+ border-radius: 50%;+ animation: spin 0.7s linear infinite;+ vertical-align: -2px;+ }+ @keyframes spin { to { transform: rotate(360deg); } }++ .skeleton {+ background: linear-gradient(90deg, var(--panel) 25%, var(--panel-2) 50%, var(--panel) 75%);+ background-size: 200% 100%;+ animation: shimmer 1.4s ease-in-out infinite;+ border-radius: 8px;+ }+ @keyframes shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }+ .sk-card { height: 240px; }+</style>+</head>+<body>+<div class="wrap">+ <nav>+ <div class="brand"><span class="dot"></span><span>x402 bazaar</span></div>+ <div class="links">+ <a href="/bazaar">Catalog</a>+ <a href="/arbitrage" class="active">Arbitrage</a>+ <a href="/providers">Providers</a>+ <a href="https://www.x402.org/docs/extensions/bazaar" target="_blank" rel="noopener">Spec</a>+ </div>+ </nav>+ <header class="hero">+ <div class="left">+ <div class="eyebrow"><span class="pulse"></span>Cross-provider arbitrage</div>+ <h1>Spot the same capability priced differently.</h1>+ <p>Live opportunities surfaced from the merged x402 facilitator catalog. Same tool, same intent — different price.</p>+ </div>+ <div class="updated">+ Updated: <strong id="updated">…</strong>+ </div>+ </header>++ <div class="toolbar">+ <button type="button" class="chip active" data-filter="all">All</button>+ <button type="button" class="chip" data-filter="http">HTTP</button>+ <button type="button" class="chip" data-filter="mcp">MCP</button>+ <input type="search" id="q" placeholder="Filter by capability or provider…" />+ <div class="count"><strong id="count">…</strong> opportunities</div>+ </div>++ <div id="grid" class="grid"></div>+ <div id="empty" class="empty" hidden></div>+</div>++<script type="module" src="/arbitrage.js"></script>+</body>+</html>diff --git a/public/arbitrage.js b/public/arbitrage.jsnew file mode 100644index 000000000..26c8c3acc--- /dev/null+++ b/public/arbitrage.js@@ -0,0 +1,249 @@+// public/arbitrage.js — drives the x402 arbitrage page.+//+// Pulls /api/bazaar/arbitrage, renders one card per opportunity, supports+// a type filter (HTTP / MCP) and a free-text search across capability and+// provider host. "Pay cheapest" launches the existing x402.js payment modal+// so the arb view stays one click from execution.++const $ = (sel) => document.querySelector(sel);+const $$ = (sel) => Array.from(document.querySelectorAll(sel));++const els = {+ grid: $('#grid'),+ empty: $('#empty'),+ count: $('#count'),+ updated: $('#updated'),+ q: $('#q'),+};++const state = {+ all: [],+ filter: 'all',+ q: '',+};++function escapeHtml(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+}++function relativeTime(iso) {+ if (!iso) return '—';+ const d = new Date(iso);+ const diff = Date.now() - d.getTime();+ if (diff < 60_000) return 'just now';+ if (diff < 3_600_000) return `${Math.floor(diff / 60_000)}m ago`;+ if (diff < 86_400_000) return `${Math.floor(diff / 3_600_000)}h ago`;+ return d.toLocaleString();+}++function renderSkeleton() {+ els.empty.hidden = true;+ const frag = document.createDocumentFragment();+ for (let i = 0; i < 6; i++) {+ const sk = document.createElement('div');+ sk.className = 'skeleton sk-card';+ frag.appendChild(sk);+ }+ els.grid.replaceChildren(frag);+}++function visibleOpps() {+ const q = state.q.trim().toLowerCase();+ return state.all.filter((o) => {+ if (state.filter !== 'all' && o.type !== state.filter) return false;+ if (!q) return true;+ const hay = [+ o.capability,+ o.serviceName,+ o.description,+ ...(o.tags || []),+ ...o.providers.flatMap((p) => [p.host, p.facilitator, p.serviceName]),+ ].filter(Boolean).join(' ').toLowerCase();+ return hay.includes(q);+ });+}++function renderGrid() {+ const opps = visibleOpps();+ els.count.textContent = String(opps.length);+ if (opps.length === 0) {+ els.grid.innerHTML = '';+ els.empty.hidden = false;+ els.empty.textContent = state.all.length+ ? 'No matches. Clear the filter or search.'+ : 'No arbitrage opportunities right now. Check back as facilitators add listings.';+ return;+ }+ els.empty.hidden = true;+ const frag = document.createDocumentFragment();+ for (const o of opps) frag.appendChild(card(o));+ els.grid.replaceChildren(frag);+}++function card(o) {+ const el = document.createElement('div');+ el.className = 'arb';++ const top = document.createElement('div');+ top.className = 'top';+ top.innerHTML = `+ <span class="type-pill ${o.type === 'mcp' ? 'mcp' : ''}">${o.type.toUpperCase()}</span>+ <span class="spread-pill">+${o.spreadPct.toFixed(1)}% spread</span>+ `;++ const title = document.createElement('div');+ title.className = 'title';+ const icon = document.createElement('div');+ icon.className = 'icon';+ if (o.iconUrl) {+ const img = document.createElement('img');+ img.src = o.iconUrl;+ img.alt = '';+ img.referrerPolicy = 'no-referrer';+ img.onerror = () => { icon.textContent = (o.capability || '?').charAt(0).toUpperCase(); img.remove(); };+ icon.appendChild(img);+ } else {+ icon.textContent = (o.capability || '?').charAt(0).toUpperCase();+ }+ const t = document.createElement('div');+ t.className = 't';+ t.innerHTML = `${escapeHtml(o.capability || 'Capability')}<div class="sub">${escapeHtml(o.serviceName && o.serviceName !== o.capability ? o.serviceName : (o.tags || []).slice(0, 3).join(' · '))}</div>`;+ title.append(icon, t);++ const stats = document.createElement('div');+ stats.className = 'stats';+ stats.innerHTML = `+ <div><div class="k">Spread</div><div class="v amber">${escapeHtml(formatSpread(o))}</div></div>+ <div><div class="k">Providers</div><div class="v">${o.providerCount}</div></div>+ <div><div class="k">Listings</div><div class="v">${o.listingCount}</div></div>+ <div><div class="k">Facilitators</div><div class="v">${o.facilitatorCount}</div></div>+ `;++ const providers = document.createElement('div');+ providers.className = 'providers';+ const sorted = [...o.providers].sort((a, b) => a.priceAtomic - b.priceAtomic);+ const cheapestAtomic = sorted[0]?.priceAtomic;+ for (const p of sorted.slice(0, 5)) {+ const row = document.createElement('a');+ row.className = 'provider' + (p.priceAtomic === cheapestAtomic ? ' cheapest' : '');+ row.href = `/providers?host=${encodeURIComponent(p.host)}`;+ row.innerHTML = `+ <span class="dot"></span>+ <span class="host" title="${escapeHtml(p.resource)}">${escapeHtml(p.host || p.resource)}</span>+ <span class="fac" title="via ${escapeHtml(p.facilitator)}">${escapeHtml(shortFac(p.facilitator))}</span>+ <span class="price">${escapeHtml(p.priceLabel)}</span>+ `;+ providers.appendChild(row);+ }+ if (sorted.length > 5) {+ const more = document.createElement('div');+ more.className = 'provider';+ more.style.justifyContent = 'center';+ more.style.color = 'var(--muted)';+ more.textContent = `+${sorted.length - 5} more`;+ providers.appendChild(more);+ }++ const actions = document.createElement('div');+ actions.className = 'actions';+ const best = document.createElement('button');+ best.type = 'button';+ best.className = 'btn-best';+ best.textContent = `Pay cheapest · ${o.minPriceLabel}`;+ best.onclick = () => payCheapest(o, best);+ const worst = document.createElement('a');+ worst.className = 'btn-worst';+ worst.href = `/bazaar?q=${encodeURIComponent(o.capability || o.serviceName || '')}`;+ worst.textContent = `Avoid · ${o.maxPriceLabel}`;+ actions.append(best, worst);++ el.append(top, title, stats, providers, actions);+ return el;+}++function formatSpread(o) {+ const usdc = o.spreadAtomic / 1_000_000;+ if (usdc >= 0.01) return `${usdc.toFixed(usdc < 1 ? 4 : 2)} USDC`;+ return `${o.spreadPct.toFixed(1)}%`;+}++function shortFac(host) {+ if (!host) return '';+ return host.replace(/^api\./, '').replace(/^facilitator\./, '').slice(0, 24);+}++async function payCheapest(o, btn) {+ if (!o.cheapest?.resource) return;+ if (o.type === 'mcp') {+ window.location.href = `/bazaar?q=${encodeURIComponent(o.capability)}`;+ return;+ }+ if (!window.X402 || typeof window.X402.pay !== 'function') {+ await loadX402();+ }+ btn.disabled = true;+ const orig = btn.textContent;+ btn.textContent = 'Opening modal…';+ try {+ const out = await window.X402.pay({+ endpoint: o.cheapest.resource,+ method: 'GET',+ merchant: o.cheapest.host,+ action: o.capability,+ });+ if (out?.ok) {+ btn.textContent = '✓ Paid';+ } else if (out?.error) {+ btn.textContent = `Failed: ${out.error}`;+ } else {+ btn.textContent = orig;+ }+ } catch (e) {+ if (e?.code !== 'cancelled') btn.textContent = `Error: ${e?.message || e}`;+ else btn.textContent = orig;+ } finally {+ setTimeout(() => { btn.disabled = false; if (!btn.textContent.startsWith('✓')) btn.textContent = orig; }, 4000);+ }+}++let _x402Loaded = null;+function loadX402() {+ if (_x402Loaded) return _x402Loaded;+ _x402Loaded = new Promise((resolve, reject) => {+ const s = document.createElement('script');+ s.type = 'module';+ s.src = '/x402.js';+ s.onload = () => resolve();+ s.onerror = (e) => reject(e);+ document.head.appendChild(s);+ });+ return _x402Loaded;+}++async function load() {+ renderSkeleton();+ try {+ const r = await fetch('/api/bazaar/arbitrage?minSpreadPct=0&limit=200');+ const data = await r.json();+ if (!r.ok) throw new Error(data?.error_description || data?.error || `HTTP ${r.status}`);+ state.all = data.opportunities || [];+ els.updated.textContent = relativeTime(data.updatedAt);+ renderGrid();+ } catch (e) {+ els.grid.innerHTML = '';+ els.empty.hidden = false;+ els.empty.className = 'err';+ els.empty.textContent = `Failed to load arbitrage: ${e?.message || e}`;+ }+}++for (const chip of $$('.chip[data-filter]')) {+ chip.addEventListener('click', () => {+ $$('.chip[data-filter]').forEach((c) => c.classList.toggle('active', c === chip));+ state.filter = chip.dataset.filter;+ renderGrid();+ });+}+els.q.addEventListener('input', () => { state.q = els.q.value; renderGrid(); });++load();diff --git a/public/bazaar.html b/public/bazaar.htmlindex 46adf56ae..28668fdaf 100644--- a/public/bazaar.html+++ b/public/bazaar.html@@ -54,6 +54,94 @@nav .links { display: flex; gap: 18px; font-size: 13.5px; color: var(--muted); }nav .links a { color: var(--muted); }nav .links a:hover { color: var(--text); }+ nav .links a.active { color: var(--text); }++ .ctx {+ background: var(--bg-2);+ border: 1px solid var(--border);+ border-radius: 10px;+ padding: 14px 16px;+ margin-bottom: 14px;+ }+ .ctx .head {+ display: flex; align-items: center; gap: 8px;+ font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase;+ color: var(--muted-2); font-weight: 600;+ margin-bottom: 8px;+ }+ .ctx .head .dot {+ width: 7px; height: 7px; border-radius: 50%;+ background: var(--accent-blue);+ }+ .ctx .head .pill {+ margin-left: auto;+ font-family: var(--mono); font-size: 10px;+ padding: 2px 7px; border-radius: 999px;+ letter-spacing: 0;+ text-transform: none;+ }+ .ctx .head .pill.up { background: rgba(74,222,128,0.12); color: var(--accent-green); border: 1px solid rgba(74,222,128,0.3); }+ .ctx .head .pill.down { background: rgba(248,113,113,0.12); color: var(--accent-red); border: 1px solid rgba(248,113,113,0.3); }+ .ctx .head .pill.neutral { background: var(--panel-2); color: var(--muted); border: 1px solid var(--border); }+ .ctx .body { font-size: 13.5px; line-height: 1.55; color: var(--text); }+ .ctx .body .cite {+ display: inline-flex; align-items: center; justify-content: center;+ min-width: 18px; height: 18px;+ background: var(--panel-2); color: var(--accent-blue);+ border: 1px solid rgba(96,165,250,0.3);+ border-radius: 5px;+ font-family: var(--mono); font-size: 10.5px;+ padding: 0 4px;+ margin: 0 2px;+ vertical-align: 1px;+ text-decoration: none;+ }+ .ctx .body .cite:hover { background: rgba(96,165,250,0.15); }+ .ctx .citations {+ margin-top: 10px;+ padding-top: 10px;+ border-top: 1px solid var(--border);+ display: flex; flex-direction: column; gap: 4px;+ }+ .ctx .citations a {+ font-size: 11.5px;+ color: var(--muted);+ font-family: var(--mono);+ }+ .ctx .citations a:hover { color: var(--text); }+ .ctx .citations a strong { color: var(--accent-blue); margin-right: 6px; font-weight: 600; }+ .ctx .stat-row {+ display: flex; gap: 14px;+ margin-top: 8px;+ font-size: 11.5px;+ color: var(--muted);+ font-family: var(--mono);+ flex-wrap: wrap;+ }+ .ctx .stat-row strong { color: var(--text); font-weight: 600; }+ .ctx.loading .body { color: var(--muted); font-style: italic; }+ .ctx.err { border-color: rgba(248,113,113,0.3); }+ .ctx.err .body { color: #fecaca; }++ .peer-hint {+ display: inline-flex; align-items: center; gap: 5px;+ background: rgba(245,158,11,0.08);+ border: 1px solid rgba(245,158,11,0.25);+ color: #f59e0b;+ padding: 3px 8px;+ border-radius: 999px;+ font-family: var(--mono);+ font-size: 11px;+ text-decoration: none;+ }+ .peer-hint:hover { background: rgba(245,158,11,0.14); }++ .tag.host {+ color: var(--accent-blue);+ border-color: rgba(96,165,250,0.3);+ text-decoration: none;+ }+ .tag.host:hover { background: rgba(96,165,250,0.1); }header.hero { padding: 44px 0 18px; }header.hero h1 { font-size: 36px; line-height: 1.1; margin: 0 0 8px; letter-spacing: -0.02em; }@@ -315,7 +403,9 @@<nav><div class="brand"><span class="dot"></span><span>x402 bazaar</span></div><div class="links">- <a href="/">Home</a>+ <a href="/bazaar" class="active">Catalog</a>+ <a href="/arbitrage">Arbitrage</a>+ <a href="/providers">Providers</a><a href="https://www.x402.org/docs/extensions/bazaar" target="_blank" rel="noopener">Spec</a><a href="/.well-known/x402.json">Our listing</a></div>diff --git a/public/bazaar.js b/public/bazaar.jsindex 601f9f878..c99d46602 100644--- a/public/bazaar.js+++ b/public/bazaar.js@@ -33,8 +33,106 @@ const state = {loading: false,lastQuery: '',items: [],+ peers: new Map(),};+const STOP_WORDS = new Set([+ 'api', 'apis', 'service', 'endpoint', 'endpoints', 'paid', 'free',+ 'the', 'a', 'an', 'and', 'or', 'of', 'for', 'to', 'on', 'in', 'by',+ 'tool', 'tools', 'mcp', 'http',+]);++function tokenize(s) {+ return String(s || '')+ .toLowerCase()+ .split(/[^a-z0-9]+/g)+ .map((w) => w.trim())+ .filter((w) => w && !STOP_WORDS.has(w) && w.length >= 2);+}++function tailFromUrl(url) {+ try {+ const u = new URL(url);+ const tail = u.pathname.replace(/\/+$/, '').split('/').filter(Boolean).pop() || '';+ return tail.replace(/-[a-z0-9]{4,12}$/i, '');+ } catch {+ return '';+ }+}++function capabilityKey(it) {+ if (it.type === 'mcp' && it.toolName) {+ const k = tokenize(it.toolName).join('');+ return k ? `mcp:${k}` : null;+ }+ const nameTokens = tokenize(it.serviceName).slice(0, 3);+ if (nameTokens.length && nameTokens.join('-').length >= 3) return `http:${nameTokens.join('-')}`;+ const urlTokens = tokenize(tailFromUrl(it.resource)).slice(0, 3);+ if (urlTokens.length >= 2 && urlTokens.join('-').length >= 6) return `http:${urlTokens.join('-')}`;+ return null;+}++function minUsdcAtomic(item) {+ const accepts = (item.accepts || []).filter((a) => {+ const sym = String(a?.assetInfo?.symbol || '').toUpperCase();+ return sym === 'USDC' || sym === '';+ });+ if (accepts.length === 0) return null;+ let min = null;+ for (const a of accepts) {+ const n = Number(a.amountAtomic);+ if (Number.isFinite(n) && n > 0 && (min == null || n < min)) min = n;+ }+ return min;+}++function priceLabel(atomic) {+ if (atomic == null) return '—';+ const n = atomic / 1_000_000;+ if (n === 0) return '0 USDC';+ if (n < 0.01) return `${n.toFixed(6).replace(/0+$/, '').replace(/\.$/, '')} USDC`;+ if (n < 1) return `${n.toFixed(4).replace(/0+$/, '').replace(/\.$/, '')} USDC`;+ return `${n.toFixed(2)} USDC`;+}++function recomputePeers(items) {+ const groups = new Map();+ for (const it of items) {+ const k = capabilityKey(it);+ if (!k) continue;+ if (!groups.has(k)) groups.set(k, []);+ groups.get(k).push(it);+ }+ state.peers = groups;+}++function computePeerHint(it) {+ const k = capabilityKey(it);+ if (!k) return null;+ const peers = state.peers.get(k);+ if (!peers || peers.length < 2) return null;+ const prices = peers.map(minUsdcAtomic).filter((n) => n != null);+ if (prices.length < 2) return null;+ const min = Math.min(...prices);+ const max = Math.max(...prices);+ const other = peers.length - 1;+ if (max === min) {+ return {+ count: other,+ label: `${other} peer${other === 1 ? '' : 's'} at same price`,+ minLabel: priceLabel(min),+ maxLabel: priceLabel(max),+ };+ }+ const spreadPct = ((max - min) / min) * 100;+ return {+ count: other,+ label: `${other} peer${other === 1 ? '' : 's'} · +${spreadPct.toFixed(0)}% spread`,+ minLabel: priceLabel(min),+ maxLabel: priceLabel(max),+ };+}+function readFilters() {return {type: els.type.value || 'http',@@ -77,6 +175,7 @@ async function load() {const data = await r.json();if (!r.ok) throw new Error(data?.error_description || data?.error || `HTTP ${r.status}`);state.items = data.resources || data.items || [];+ recomputePeers(state.items);renderResults(state.items, query, data.sources || [], data.errors || []);} catch (e) {renderError(e);@@ -181,6 +280,26 @@ function card(it) {meta.appendChild(tag('ext', ext));}+ const host = safeHost(it.resource);+ if (host) {+ const hostPill = document.createElement('a');+ hostPill.className = 'tag host';+ hostPill.href = `/providers?host=${encodeURIComponent(host)}`;+ hostPill.textContent = host;+ hostPill.title = `View ${host} profile`;+ meta.appendChild(hostPill);+ }++ const peerHint = computePeerHint(it);+ if (peerHint) {+ const a = document.createElement('a');+ a.className = 'peer-hint';+ a.href = `/arbitrage?focus=${encodeURIComponent(it.serviceName || it.toolName || '')}`;+ a.title = `${peerHint.count} similar listings, ${peerHint.minLabel}–${peerHint.maxLabel}`;+ a.textContent = peerHint.label;+ meta.appendChild(a);+ }+const actions = document.createElement('div');actions.className = 'actions';const tryBtn = document.createElement('button');@@ -322,15 +441,78 @@ function openDetails(it) {summary.style.marginBottom = '12px';summary.style.fontSize = '13px';summary.style.color = 'var(--muted)';+ const host = safeHost(it.resource);summary.innerHTML = `<div><strong style="color:var(--text)">${escape(it.resource)}</strong></div><div>type: ${escape(it.type)}${it.toolName ? ' · tool: ' + escape(it.toolName) : ''} · method: ${escape(it.method || '')}</div><div>networks: ${(it.networks || []).map(escape).join(', ')}</div><div>price: ${escape(it.minPriceLabel || '—')}</div>- <div>facilitator: ${escape(safeHost(it.facilitator))}</div>+ <div>provider: <a href="/providers?host=${encodeURIComponent(host)}">${escape(host)}</a> · facilitator: ${escape(safeHost(it.facilitator))}</div>+ `;++ const ctx = document.createElement('div');+ ctx.className = 'ctx loading';+ ctx.innerHTML = `+ <div class="head">+ <span class="dot"></span>+ <span>What's the context?</span>+ </div>+ <div class="body">Reading the catalog…</div>`;- els.modalBody.replaceChildren(summary, pre);+ els.modalBody.replaceChildren(summary, ctx, pre);if (typeof els.modal.showModal === 'function') els.modal.showModal();+ fetchContext(it, ctx);+}++async function fetchContext(it, ctxEl) {+ const params = new URLSearchParams({ resource: it.resource });+ if (it.toolName) params.set('toolName', it.toolName);+ try {+ const r = await fetch(`/api/bazaar/context?${params.toString()}`);+ const data = await r.json();+ if (!r.ok) throw new Error(data?.error_description || data?.error || `HTTP ${r.status}`);+ renderContext(ctxEl, data);+ } catch (e) {+ ctxEl.className = 'ctx err';+ ctxEl.querySelector('.body').textContent = `Couldn't load context: ${e?.message || e}`;+ }+}++function renderContext(ctxEl, data) {+ const sentiment = ['up', 'down'].includes(data.sentiment) ? data.sentiment : 'neutral';+ const cits = Array.isArray(data.citations) ? data.citations : [];+ const summaryHtml = renderCitedText(data.summary || '', cits);+ const stats = data.stats || {};+ const statBits = [];+ if (typeof stats.peerCount === 'number') statBits.push(`<strong>${stats.peerCount}</strong> peer${stats.peerCount === 1 ? '' : 's'}`);+ if (typeof stats.providerSiblingsCount === 'number') statBits.push(`<strong>${stats.providerSiblingsCount}</strong> sibling${stats.providerSiblingsCount === 1 ? '' : 's'}`);+ if (typeof stats.pricePercentile === 'number') statBits.push(`<strong>P${stats.pricePercentile}</strong> by price`);++ ctxEl.className = 'ctx';+ ctxEl.innerHTML = `+ <div class="head">+ <span class="dot"></span>+ <span>What's the context?</span>+ <span class="pill ${sentiment}">${sentiment}</span>+ </div>+ <div class="body">${summaryHtml}</div>+ ${statBits.length ? `<div class="stat-row">${statBits.join('<span>·</span>')}</div>` : ''}+ ${cits.length ? `<div class="citations">${cits.map((c, i) => {+ const ext = c.external ? ' target="_blank" rel="noopener"' : '';+ return `<a href="${escape(c.url)}"${ext}><strong>[${i + 1}]</strong>${escape(c.label)}</a>`;+ }).join('')}</div>` : ''}+ `;+}++function renderCitedText(text, citations) {+ const safe = escape(text);+ return safe.replace(/\[(\d+)\]/g, (_, n) => {+ const idx = Number(n) - 1;+ const cit = citations[idx];+ if (!cit) return `<span class="cite">${n}</span>`;+ const ext = cit.external ? ' target="_blank" rel="noopener"' : '';+ return `<a class="cite" href="${escape(cit.url)}"${ext} title="${escape(cit.label)}">${n}</a>`;+ });}els.modalClose.addEventListener('click', () => els.modal.close());diff --git a/public/features.json b/public/features.jsonindex 343c9aae7..2190d2df0 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-05-27T22:16:46.380Z",+ "generated_at": "2026-05-28T09:14:30.812Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/forever.html b/public/forever.htmlnew file mode 100644index 000000000..74fe851af--- /dev/null+++ b/public/forever.html@@ -0,0 +1,736 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8" />+<meta name="viewport" content="width=device-width,initial-scale=1" />+<title>forever — etch a message into Bitcoin</title>+<meta name="description" content="Inscribe a message onto the Bitcoin blockchain. It stays there. Forever." />+<meta name="theme-color" content="#000000" />+<meta property="og:title" content="forever — etch a message into Bitcoin" />+<meta property="og:description" content="Inscribe a message onto the Bitcoin blockchain. It stays there. Forever." />+<meta property="og:type" content="website" />+<meta property="og:image" content="https://three.ws/forever-og.png" />+<meta name="twitter:card" content="summary_large_image" />+<meta name="twitter:title" content="forever — etch a message into Bitcoin" />+<meta name="twitter:description" content="Your words on the most secure chain in history. One inscription. Permanent." />+<link rel="canonical" href="https://three.ws/forever" />+<link rel="preconnect" href="https://api.ordinalsbot.com" />+<style>+ :root {+ --bg: #000000;+ --bg-2: #07070a;+ --ink: #ffffff;+ --ink-2: #c5c8d4;+ --ink-3: #7a7e8e;+ --ink-4: #4a4d5a;+ --line: #1a1a22;+ --line-strong: #2a2a36;+ --btc: #f7931a;+ --btc-glow: rgba(247, 147, 26, 0.35);+ --ok: #4ade80;+ --err: #f87171;+ --mono: ui-monospace, "JetBrains Mono", "SF Mono", Menlo, Consolas, monospace;+ --sans: -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;+ }+ * { box-sizing: border-box; }+ html, body {+ margin: 0;+ padding: 0;+ background: var(--bg);+ color: var(--ink);+ min-height: 100vh;+ }+ body {+ font-family: var(--sans);+ -webkit-font-smoothing: antialiased;+ -moz-osx-font-smoothing: grayscale;+ line-height: 1.5;+ overflow-x: hidden;+ }+ ::selection { background: var(--btc); color: #000; }+ a { color: var(--ink); text-decoration: none; border-bottom: 1px solid var(--line-strong); }+ a:hover { border-color: var(--btc); }+ button { font-family: inherit; }++ /* ── animated grain + glow backdrop ───────────────────────── */+ .backdrop {+ position: fixed; inset: 0;+ z-index: 0;+ pointer-events: none;+ background:+ radial-gradient(ellipse 80% 50% at 50% 0%, rgba(247, 147, 26, 0.08), transparent 60%),+ radial-gradient(ellipse 60% 40% at 50% 100%, rgba(247, 147, 26, 0.04), transparent 70%);+ }+ .backdrop::before {+ content: "";+ position: absolute; inset: 0;+ background-image: url("data:image/svg+xml;utf8,<svg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2' stitchTiles='stitch'/><feColorMatrix values='0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0.06 0'/></filter><rect width='100%25' height='100%25' filter='url(%23n)'/></svg>");+ opacity: 0.6;+ mix-blend-mode: screen;+ }+ .backdrop::after {+ content: "";+ position: absolute; inset: 0;+ background: repeating-linear-gradient(+ 0deg,+ transparent 0,+ transparent 2px,+ rgba(255,255,255,0.012) 2px,+ rgba(255,255,255,0.012) 3px+ );+ }++ /* ── header ───────────────────────────────────────────────── */+ .shell {+ position: relative;+ z-index: 1;+ min-height: 100vh;+ display: flex;+ flex-direction: column;+ }+ header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 22px 32px;+ border-bottom: 1px solid var(--line);+ }+ .logo {+ font-family: var(--mono);+ font-size: 13px;+ letter-spacing: 0.18em;+ text-transform: uppercase;+ color: var(--ink-2);+ border: none;+ }+ .logo b { color: var(--btc); font-weight: 600; }+ .nav {+ display: flex;+ gap: 22px;+ font-family: var(--mono);+ font-size: 12px;+ letter-spacing: 0.1em;+ text-transform: uppercase;+ color: var(--ink-3);+ }+ .nav a { color: inherit; border: none; }+ .nav a:hover { color: var(--ink); }++ /* ── hero ─────────────────────────────────────────────────── */+ main {+ flex: 1;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ padding: 60px 24px 80px;+ text-align: center;+ }+ .eyebrow {+ font-family: var(--mono);+ font-size: 11px;+ letter-spacing: 0.32em;+ text-transform: uppercase;+ color: var(--btc);+ margin-bottom: 28px;+ display: inline-flex;+ align-items: center;+ gap: 10px;+ }+ .eyebrow .dot {+ width: 6px; height: 6px;+ background: var(--btc);+ border-radius: 50%;+ box-shadow: 0 0 12px var(--btc-glow);+ animation: pulse 2s ease-in-out infinite;+ }+ @keyframes pulse {+ 0%, 100% { opacity: 1; transform: scale(1); }+ 50% { opacity: 0.4; transform: scale(0.7); }+ }++ h1 {+ font-family: var(--sans);+ font-size: clamp(48px, 9vw, 128px);+ line-height: 0.95;+ letter-spacing: -0.04em;+ font-weight: 600;+ margin: 0 0 18px;+ max-width: 14ch;+ text-wrap: balance;+ }+ h1 em {+ font-style: normal;+ background: linear-gradient(180deg, var(--btc) 0%, #ffb957 100%);+ -webkit-background-clip: text;+ background-clip: text;+ color: transparent;+ }+ .tag {+ font-size: clamp(15px, 1.6vw, 19px);+ color: var(--ink-2);+ max-width: 52ch;+ margin: 0 auto 56px;+ text-wrap: balance;+ }++ /* ── composer ────────────────────────────────────────────── */+ .composer {+ width: 100%;+ max-width: 720px;+ margin: 0 auto;+ text-align: left;+ }+ .composer-frame {+ position: relative;+ background: var(--bg-2);+ border: 1px solid var(--line-strong);+ border-radius: 18px;+ padding: 28px 28px 22px;+ transition: border-color 220ms ease, box-shadow 220ms ease, transform 220ms ease;+ }+ .composer-frame:focus-within {+ border-color: var(--btc);+ box-shadow: 0 0 0 1px var(--btc), 0 20px 80px -20px var(--btc-glow);+ }+ #message {+ width: 100%;+ min-height: 140px;+ max-height: 360px;+ background: transparent;+ border: 0;+ outline: 0;+ resize: none;+ color: var(--ink);+ font-family: var(--mono);+ font-size: 18px;+ line-height: 1.55;+ padding: 0;+ }+ #message::placeholder { color: var(--ink-4); }+ .composer-meta {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-top: 20px;+ padding-top: 18px;+ border-top: 1px solid var(--line);+ font-family: var(--mono);+ font-size: 12px;+ color: var(--ink-3);+ letter-spacing: 0.04em;+ }+ .composer-meta .left { display: flex; gap: 18px; flex-wrap: wrap; }+ .composer-meta .right { display: flex; gap: 14px; align-items: center; }+ .kv b { color: var(--ink-2); font-weight: 500; }+ .kv.warn b { color: var(--err); }++ .options {+ margin-top: 14px;+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 12px;+ }+ .options label {+ display: block;+ font-family: var(--mono);+ font-size: 11px;+ letter-spacing: 0.14em;+ text-transform: uppercase;+ color: var(--ink-3);+ margin-bottom: 6px;+ }+ .options input, .options select {+ width: 100%;+ background: var(--bg-2);+ border: 1px solid var(--line-strong);+ border-radius: 10px;+ padding: 12px 14px;+ color: var(--ink);+ font-family: var(--mono);+ font-size: 13px;+ outline: 0;+ transition: border-color 200ms ease;+ }+ .options input:focus, .options select:focus { border-color: var(--btc); }+ .options input::placeholder { color: var(--ink-4); }+ .options .hint {+ margin-top: 6px;+ font-family: var(--mono);+ font-size: 11px;+ color: var(--ink-4);+ }+ @media (max-width: 560px) {+ .options { grid-template-columns: 1fr; }+ }++ .cta-row {+ margin-top: 28px;+ display: flex;+ gap: 12px;+ align-items: center;+ flex-wrap: wrap;+ }+ .cta {+ flex: 1;+ min-width: 240px;+ display: inline-flex;+ justify-content: center;+ align-items: center;+ gap: 12px;+ background: var(--btc);+ color: #000;+ font-family: var(--sans);+ font-weight: 600;+ font-size: 16px;+ letter-spacing: -0.005em;+ padding: 18px 28px;+ border-radius: 12px;+ border: 0;+ cursor: pointer;+ transition: transform 140ms ease, box-shadow 220ms ease, background 140ms ease;+ box-shadow: 0 12px 40px -12px var(--btc-glow);+ }+ .cta:hover { transform: translateY(-1px); box-shadow: 0 18px 60px -10px var(--btc-glow); background: #ffa84d; }+ .cta:active { transform: translateY(0); }+ .cta:disabled { opacity: 0.55; cursor: not-allowed; transform: none; box-shadow: none; }+ .cta svg { width: 18px; height: 18px; }+ .subnote {+ font-family: var(--mono);+ font-size: 11px;+ color: var(--ink-3);+ letter-spacing: 0.08em;+ text-transform: uppercase;+ }++ .error-banner {+ margin-top: 16px;+ padding: 14px 16px;+ border: 1px solid var(--err);+ border-radius: 10px;+ background: rgba(248, 113, 113, 0.06);+ color: var(--err);+ font-family: var(--mono);+ font-size: 13px;+ display: none;+ }+ .error-banner.show { display: block; }++ /* ── payment view ────────────────────────────────────────── */+ .pay {+ display: none;+ width: 100%;+ max-width: 720px;+ margin: 0 auto;+ text-align: left;+ background: var(--bg-2);+ border: 1px solid var(--line-strong);+ border-radius: 18px;+ padding: 32px;+ }+ .pay.show { display: block; }+ .pay-header {+ display: flex;+ justify-content: space-between;+ align-items: flex-start;+ gap: 16px;+ margin-bottom: 24px;+ }+ .pay-title {+ font-size: 22px;+ font-weight: 600;+ letter-spacing: -0.015em;+ margin: 0 0 4px;+ }+ .pay-sub {+ font-family: var(--mono);+ font-size: 12px;+ color: var(--ink-3);+ letter-spacing: 0.04em;+ }+ .state-pill {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ padding: 6px 12px;+ border-radius: 999px;+ border: 1px solid var(--line-strong);+ font-family: var(--mono);+ font-size: 11px;+ letter-spacing: 0.14em;+ text-transform: uppercase;+ color: var(--ink-2);+ }+ .state-pill .dot {+ width: 6px; height: 6px; border-radius: 50%;+ background: var(--btc);+ animation: pulse 1.6s ease-in-out infinite;+ }+ .state-pill.ok { color: var(--ok); border-color: rgba(74, 222, 128, 0.35); }+ .state-pill.ok .dot { background: var(--ok); animation: none; }+ .state-pill.err { color: var(--err); border-color: rgba(248, 113, 113, 0.4); }+ .state-pill.err .dot { background: var(--err); animation: none; }++ .pay-grid {+ display: grid;+ grid-template-columns: 220px 1fr;+ gap: 28px;+ align-items: start;+ }+ @media (max-width: 640px) {+ .pay-grid { grid-template-columns: 1fr; }+ }+ .qr-box {+ background: #fff;+ border-radius: 14px;+ padding: 16px;+ display: flex;+ align-items: center;+ justify-content: center;+ aspect-ratio: 1 / 1;+ }+ .qr-box img { width: 100%; height: 100%; image-rendering: pixelated; }++ .pay-detail-row {+ display: flex;+ justify-content: space-between;+ gap: 14px;+ padding: 12px 0;+ border-bottom: 1px solid var(--line);+ font-family: var(--mono);+ font-size: 13px;+ }+ .pay-detail-row:last-of-type { border-bottom: 0; }+ .pay-detail-row .k { color: var(--ink-3); letter-spacing: 0.06em; text-transform: uppercase; font-size: 11px; }+ .pay-detail-row .v {+ color: var(--ink);+ text-align: right;+ word-break: break-all;+ max-width: 60%;+ }+ .pay-detail-row .v .copy {+ margin-left: 8px;+ font-size: 11px;+ color: var(--ink-3);+ cursor: pointer;+ border: 0;+ background: transparent;+ padding: 0;+ }+ .pay-detail-row .v .copy:hover { color: var(--btc); }+ .amount-big {+ font-family: var(--mono);+ font-size: 28px;+ letter-spacing: -0.01em;+ color: var(--ink);+ margin-bottom: 6px;+ }+ .amount-big .sat { color: var(--ink-3); font-size: 14px; margin-left: 6px; }+ .amount-usd {+ font-family: var(--mono);+ font-size: 12px;+ color: var(--ink-3);+ margin-bottom: 18px;+ }+ .pay-actions {+ display: flex;+ gap: 10px;+ flex-wrap: wrap;+ margin-top: 20px;+ }+ .btn {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ padding: 11px 16px;+ border-radius: 10px;+ border: 1px solid var(--line-strong);+ background: transparent;+ color: var(--ink-2);+ font-family: var(--mono);+ font-size: 12px;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ cursor: pointer;+ transition: border-color 160ms ease, color 160ms ease;+ }+ .btn:hover { border-color: var(--btc); color: var(--ink); }+ .btn.primary {+ background: var(--btc); color: #000; border-color: var(--btc);+ text-transform: none; letter-spacing: -0.005em;+ font-family: var(--sans); font-weight: 600; font-size: 14px;+ }+ .btn.primary:hover { background: #ffa84d; }++ .message-preview {+ margin-top: 18px;+ padding: 16px 18px;+ background: rgba(255,255,255,0.02);+ border: 1px solid var(--line);+ border-radius: 12px;+ font-family: var(--mono);+ font-size: 13px;+ color: var(--ink-2);+ white-space: pre-wrap;+ word-break: break-word;+ max-height: 160px;+ overflow: auto;+ }++ /* ── success view ────────────────────────────────────────── */+ .win {+ display: none;+ width: 100%;+ max-width: 720px;+ margin: 0 auto;+ text-align: center;+ }+ .win.show { display: block; }+ .win-burst {+ font-family: var(--mono);+ font-size: 11px;+ letter-spacing: 0.32em;+ text-transform: uppercase;+ color: var(--ok);+ margin-bottom: 20px;+ display: inline-flex;+ align-items: center;+ gap: 10px;+ }+ .win-burst .dot { width: 6px; height: 6px; background: var(--ok); border-radius: 50%; }+ .win h2 {+ font-size: clamp(40px, 7vw, 88px);+ line-height: 0.95;+ letter-spacing: -0.04em;+ margin: 0 0 24px;+ font-weight: 600;+ }+ .win-card {+ text-align: left;+ background: var(--bg-2);+ border: 1px solid var(--line-strong);+ border-radius: 16px;+ padding: 24px 28px;+ margin: 0 auto 28px;+ }+ .win-card .row {+ display: flex;+ justify-content: space-between;+ gap: 14px;+ padding: 10px 0;+ border-bottom: 1px solid var(--line);+ font-family: var(--mono);+ font-size: 13px;+ }+ .win-card .row:last-child { border-bottom: 0; }+ .win-card .row .k { color: var(--ink-3); font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; }+ .win-card .row .v { color: var(--ink); word-break: break-all; text-align: right; max-width: 60%; }+ .win-card .row .v a { color: var(--ink); border-bottom: 1px solid var(--line-strong); }+ .win-card .row .v a:hover { border-color: var(--btc); }+ .win-message {+ font-family: var(--mono);+ font-size: 16px;+ line-height: 1.55;+ color: var(--ink);+ background: rgba(247, 147, 26, 0.06);+ border: 1px solid rgba(247, 147, 26, 0.3);+ border-radius: 14px;+ padding: 22px 24px;+ margin: 0 auto 28px;+ max-width: 640px;+ text-align: left;+ white-space: pre-wrap;+ word-break: break-word;+ }+ .share-row {+ display: flex;+ gap: 12px;+ justify-content: center;+ flex-wrap: wrap;+ }+ .share-x {+ background: #000;+ color: #fff;+ border: 1px solid var(--line-strong);+ padding: 14px 22px;+ border-radius: 12px;+ font-weight: 600;+ font-size: 15px;+ display: inline-flex;+ align-items: center;+ gap: 10px;+ cursor: pointer;+ transition: border-color 160ms ease, transform 140ms ease;+ }+ .share-x:hover { border-color: #fff; transform: translateY(-1px); }+ .share-x svg { width: 16px; height: 16px; }++ /* ── footer ──────────────────────────────────────────────── */+ footer {+ padding: 28px 32px;+ border-top: 1px solid var(--line);+ display: flex;+ justify-content: space-between;+ gap: 18px;+ font-family: var(--mono);+ font-size: 11px;+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: var(--ink-4);+ flex-wrap: wrap;+ }+ footer a { color: var(--ink-3); border: none; }+ footer a:hover { color: var(--btc); }++ .fade-in { animation: fadeIn 360ms ease forwards; }+ @keyframes fadeIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }+</style>+</head>+<body>+<div class="backdrop"></div>+<div class="shell">++<header>+ <a class="logo" href="/"><b>three.ws</b> · forever</a>+ <nav class="nav">+ <a href="https://ordinals.com" target="_blank" rel="noopener">Ordinals</a>+ <a href="https://mempool.space" target="_blank" rel="noopener">Mempool</a>+ <a href="/bazaar">Bazaar</a>+ </nav>+</header>++<main>++<!-- ── compose view ──────────────────────────────────────────── -->+<section id="view-compose" class="view fade-in">+ <div class="eyebrow"><span class="dot"></span>Etch onto Bitcoin · permanent · public</div>+ <h1>Say something. <em>Forever.</em></h1>+ <p class="tag">Your words inscribed onto a single Bitcoin satoshi. Anyone in the world can read it. No one can ever delete it. Not in 100 years. Not in 1000.</p>++ <div class="composer">+ <div class="composer-frame">+ <textarea id="message" placeholder="Type the message you want to live on the most secure chain in history…" maxlength="1500" autocomplete="off" spellcheck="true"></textarea>+ <div class="composer-meta">+ <div class="left">+ <span class="kv" id="charCount"><b>0</b> chars</span>+ <span class="kv" id="byteCount"><b>0</b> bytes</span>+ </div>+ <div class="right">+ <span class="kv">max <b>1500</b> bytes</span>+ </div>+ </div>+ </div>++ <div class="options">+ <div>+ <label for="receiveAddress">Bitcoin receive address <span style="color:var(--ink-4)">(optional)</span></label>+ <input id="receiveAddress" placeholder="bc1p…" autocomplete="off" spellcheck="false" />+ <div class="hint">Taproot only. Leave blank to let the platform vault hold the inscription — your message still lives on chain forever.</div>+ </div>+ <div>+ <label for="feeRate">Fee rate (sats/vB)</label>+ <select id="feeRate">+ <option value="3">3 — economy (~12 hrs)</option>+ <option value="8" selected>8 — standard (~1 hr)</option>+ <option value="20">20 — fast (~10 min)</option>+ <option value="50">50 — priority (next block)</option>+ </select>+ <div class="hint">Higher fees confirm faster. The inscription is permanent either way.</div>+ </div>+ </div>++ <div class="cta-row">+ <button id="inscribeBtn" class="cta" type="button">+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="M13 6l6 6-6 6"/></svg>+ Inscribe forever+ </button>+ <span class="subnote">paid in BTC · settled in ~1 block</span>+ </div>++ <div id="errorBanner" class="error-banner"></div>+ </div>+</section>++<!-- ── payment view ──────────────────────────────────────────── -->+<section id="view-pay" class="view pay">+ <div class="pay-header">+ <div>+ <h2 class="pay-title">Send Bitcoin to inscribe</h2>+ <div class="pay-sub">Once the mempool sees your payment, we broadcast the inscription. Stay on this page.</div>+ </div>+ <div id="statePill" class="state-pill"><span class="dot"></span><span class="label">waiting for payment</span></div>+ </div>++ <div class="pay-grid">+ <div>+ <div id="qrBox" class="qr-box"></div>+ </div>+ <div>+ <div class="amount-big"><span id="amountBtc">—</span> BTC<span class="sat" id="amountSats">— sats</span></div>+ <div class="amount-usd" id="amountUsd">≈ $—</div>++ <div class="pay-detail-row">+ <span class="k">Pay to</span>+ <span class="v"><span id="payAddress">—</span><button class="copy" data-copy="payAddress">copy</button></span>+ </div>+ <div class="pay-detail-row" id="lnRow" style="display:none">+ <span class="k">Lightning</span>+ <span class="v"><span id="lnInvoice">—</span><button class="copy" data-copy="lnInvoice">copy</button></span>+ </div>+ <div class="pay-detail-row">+ <span class="k">Receive to</span>+ <span class="v" id="receiveAddrPay">—</span>+ </div>+ <div class="pay-detail-row">+ <span class="k">Order</span>+ <span class="v" id="orderIdPay">—</span>+ </div>++ <div class="pay-actions">+ <a id="openWallet" class="btn primary" href="#">Open in wallet</a>+ <a id="mempoolLink" class="btn" target="_blank" rel="noopener" href="#">View on mempool ↗</a>+ <button id="cancelPay" class="btn" type="button">Cancel</button>+ </div>+ </div>+ </div>++ <div class="message-preview" id="messagePreview"></div>+</section>++<!-- ── success view ──────────────────────────────────────────── -->+<section id="view-win" class="view win">+ <div class="win-burst"><span class="dot"></span>Inscribed on Bitcoin · block confirmed</div>+ <h2>It's forever now.</h2>+ <div class="win-message" id="winMessage">—</div>+ <div class="win-card">+ <div class="row"><span class="k">Inscription</span><span class="v"><a id="winInscriptionLink" href="#" target="_blank" rel="noopener">—</a></span></div>+ <div class="row"><span class="k">Reveal tx</span><span class="v"><a id="winTxLink" href="#" target="_blank" rel="noopener">—</a></span></div>+ <div class="row"><span class="k">Receive</span><span class="v" id="winReceive">—</span></div>+ <div class="row"><span class="k">Network</span><span class="v">Bitcoin mainnet</span></div>+ </div>+ <div class="share-row">+ <button id="shareX" class="share-x" type="button">+ <svg viewBox="0 0 24 24" fill="currentColor"><path d="M18.244 2H21l-6.55 7.486L22 22h-6.844l-4.79-6.243L4.8 22H2.04l7.014-8.018L2 2h6.918l4.342 5.74L18.244 2Zm-1.2 18h1.708L7.05 4H5.24l11.804 16Z"/></svg>+ Share on X+ </button>+ <button id="copyLink" class="btn">Copy permalink</button>+ <button id="inscribeAnother" class="btn">Inscribe another</button>+ </div>+</section>++</main>++<footer>+ <div>three.ws · forever</div>+ <div>+ <a href="https://docs.ordinals.com/inscriptions.html" target="_blank" rel="noopener">What is an inscription?</a>+ · + <a href="https://mempool.space" target="_blank" rel="noopener">Explore Bitcoin</a>+ </div>+</footer>++</div>++<script type="module" src="/forever.js"></script>+</body>+</html>diff --git a/public/forever.js b/public/forever.jsnew file mode 100644index 000000000..0d2d5963c--- /dev/null+++ b/public/forever.js@@ -0,0 +1,396 @@+// /forever — client controller for the Bitcoin inscription splash.+//+// State machine: compose → pay → win+// - compose: textarea + options, "Inscribe forever" CTA+// - pay: QR + address + Lightning, polling /api/forever/status+// - win: inscription ID, tx hash, share-to-X CTA+//+// Persistence: orderId is stored in sessionStorage so an accidental reload+// during the payment wait keeps the user on the same charge.++const $ = (id) => document.getElementById(id);+const els = {+ message: $('message'),+ receive: $('receiveAddress'),+ feeRate: $('feeRate'),+ charCount: $('charCount').querySelector('b'),+ byteCount: $('byteCount').querySelector('b'),+ byteWrap: $('byteCount'),+ inscribeBtn: $('inscribeBtn'),+ errorBanner: $('errorBanner'),+ viewCompose: $('view-compose'),+ viewPay: $('view-pay'),+ viewWin: $('view-win'),+ statePill: $('statePill'),+ statePillLabel: $('statePill').querySelector('.label'),+ qrBox: $('qrBox'),+ amountBtc: $('amountBtc'),+ amountSats: $('amountSats'),+ amountUsd: $('amountUsd'),+ payAddress: $('payAddress'),+ lnRow: $('lnRow'),+ lnInvoice: $('lnInvoice'),+ receiveAddrPay: $('receiveAddrPay'),+ orderIdPay: $('orderIdPay'),+ openWallet: $('openWallet'),+ mempoolLink: $('mempoolLink'),+ cancelPay: $('cancelPay'),+ messagePreview: $('messagePreview'),+ winMessage: $('winMessage'),+ winInscriptionLink: $('winInscriptionLink'),+ winTxLink: $('winTxLink'),+ winReceive: $('winReceive'),+ shareX: $('shareX'),+ copyLink: $('copyLink'),+ inscribeAnother: $('inscribeAnother'),+};++const STATE_LABEL = {+ 'waiting-payment': 'waiting for payment',+ 'payment-received': 'payment received',+ inscribing: 'inscribing onto Bitcoin',+ inscribed: 'inscribed forever',+ failed: 'inscription failed',+};++// ── live counters ───────────────────────────────────────────────+function updateCounters() {+ const text = els.message.value;+ const chars = [...text].length;+ const bytes = new TextEncoder().encode(text).length;+ els.charCount.textContent = chars.toLocaleString();+ els.byteCount.textContent = bytes.toLocaleString();+ els.byteWrap.classList.toggle('warn', bytes > 1500);+ els.message.style.height = 'auto';+ els.message.style.height = Math.min(els.message.scrollHeight, 360) + 'px';+}+els.message.addEventListener('input', updateCounters);+updateCounters();++// ── btc/usd price (single fetch, best-effort) ───────────────────+let BTC_USD = null;+async function fetchBtcPrice() {+ try {+ const r = await fetch('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd');+ if (!r.ok) return;+ const d = await r.json();+ const p = d?.bitcoin?.usd;+ if (typeof p === 'number') BTC_USD = p;+ } catch {+ // Price is decoration; not required for the flow.+ }+}+fetchBtcPrice();++// ── QR rendering ────────────────────────────────────────────────+// Uses Google's chart server as a zero-dep QR generator. The payload is the+// BIP-21 URI so any Bitcoin wallet can scan it directly. Fallback to a plain+// address QR if BIP-21 construction fails.+function renderQR(payload) {+ els.qrBox.innerHTML = '';+ const img = document.createElement('img');+ img.alt = 'Bitcoin payment QR';+ img.src =+ 'https://api.qrserver.com/v1/create-qr-code/?size=400x400&margin=0&data=' ++ encodeURIComponent(payload);+ img.loading = 'eager';+ img.decoding = 'async';+ els.qrBox.appendChild(img);+}++function buildBip21({ address, amountBtc, lightning, label }) {+ const params = new URLSearchParams();+ if (amountBtc) params.set('amount', amountBtc.toFixed(8));+ if (label) params.set('label', label);+ if (lightning) params.set('lightning', lightning);+ const qs = params.toString();+ return `bitcoin:${address}${qs ? '?' + qs : ''}`;+}++// ── error display ──────────────────────────────────────────────+function showError(msg) {+ els.errorBanner.textContent = msg;+ els.errorBanner.classList.add('show');+}+function clearError() {+ els.errorBanner.classList.remove('show');+ els.errorBanner.textContent = '';+}++// ── view switching ─────────────────────────────────────────────+function show(view) {+ els.viewCompose.classList.remove('show', 'fade-in');+ els.viewPay.classList.remove('show', 'fade-in');+ els.viewWin.classList.remove('show', 'fade-in');+ if (view === 'compose') {+ els.viewCompose.style.display = '';+ els.viewCompose.classList.add('fade-in');+ } else if (view === 'pay') {+ els.viewCompose.style.display = 'none';+ els.viewPay.classList.add('show', 'fade-in');+ els.viewWin.classList.remove('show');+ } else if (view === 'win') {+ els.viewCompose.style.display = 'none';+ els.viewPay.classList.remove('show');+ els.viewWin.classList.add('show', 'fade-in');+ }+}++// ── current order state ────────────────────────────────────────+let currentOrder = null; // { orderId, message, receiveAddress }+let pollTimer = null;++function setStatePill(state) {+ els.statePill.classList.remove('ok', 'err');+ if (state === 'inscribed') els.statePill.classList.add('ok');+ if (state === 'failed') els.statePill.classList.add('err');+ els.statePillLabel.textContent = STATE_LABEL[state] || state;+}++// ── inscribe flow ──────────────────────────────────────────────+els.inscribeBtn.addEventListener('click', async () => {+ clearError();+ const message = els.message.value.trim();+ if (!message) {+ showError('Type a message first.');+ els.message.focus();+ return;+ }+ const bytes = new TextEncoder().encode(message).length;+ if (bytes > 1500) {+ showError(`Message is ${bytes} bytes. Trim it under 1500.`);+ return;+ }+ const receiveAddress = els.receive.value.trim() || undefined;+ const feeRate = Number(els.feeRate.value);++ els.inscribeBtn.disabled = true;+ els.inscribeBtn.innerHTML =+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round"><circle cx="12" cy="12" r="9" opacity="0.25"/><path d="M12 3a9 9 0 0 1 9 9"><animateTransform attributeName="transform" type="rotate" from="0 12 12" to="360 12 12" dur="0.9s" repeatCount="indefinite"/></path></svg> Creating order…';++ try {+ const res = await fetch('/api/forever/inscribe', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ message, receiveAddress, feeRate }),+ });+ const data = await res.json();+ if (!res.ok) {+ throw new Error(data?.error_description || data?.error || `HTTP ${res.status}`);+ }+ await onOrderCreated(data, message);+ } catch (e) {+ showError(e.message || 'Inscription failed. Try again.');+ els.inscribeBtn.disabled = false;+ els.inscribeBtn.innerHTML =+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="M13 6l6 6-6 6"/></svg> Inscribe forever';+ }+});++async function onOrderCreated(data, message) {+ currentOrder = {+ orderId: data.orderId,+ message,+ receiveAddress: data.receiveAddress,+ };+ sessionStorage.setItem('forever:order', JSON.stringify(currentOrder));++ const c = data.charge || {};+ const amountBtc = c.amountBtc ?? (c.amount ? c.amount / 1e8 : 0);+ const amountSats = c.amount || 0;+ const lightning = c.lightningInvoice;++ els.amountBtc.textContent = amountBtc ? amountBtc.toFixed(8) : '—';+ els.amountSats.textContent = amountSats ? `· ${amountSats.toLocaleString()} sats` : '';+ els.amountUsd.textContent = BTC_USD && amountBtc+ ? `≈ $${(amountBtc * BTC_USD).toLocaleString(undefined, { maximumFractionDigits: 2 })}`+ : '';+ els.payAddress.textContent = c.address || '—';+ els.receiveAddrPay.textContent = data.receiveAddress;+ els.orderIdPay.textContent = data.orderId;+ els.messagePreview.textContent = message;++ if (lightning) {+ els.lnRow.style.display = '';+ els.lnInvoice.textContent = lightning;+ } else {+ els.lnRow.style.display = 'none';+ }++ const bip21 = buildBip21({+ address: c.address,+ amountBtc,+ lightning,+ label: 'three.ws · forever',+ });+ renderQR(bip21);+ els.openWallet.href = bip21;+ els.mempoolLink.href = `https://mempool.space/address/${c.address}`;+ setStatePill('waiting-payment');++ show('pay');+ startPolling();++ els.inscribeBtn.disabled = false;+ els.inscribeBtn.innerHTML =+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="M13 6l6 6-6 6"/></svg> Inscribe forever';+}++// ── polling ────────────────────────────────────────────────────+function startPolling() {+ stopPolling();+ pollOnce();+ pollTimer = setInterval(pollOnce, 6000);+}+function stopPolling() {+ if (pollTimer) {+ clearInterval(pollTimer);+ pollTimer = null;+ }+}++async function pollOnce() {+ if (!currentOrder?.orderId) return;+ try {+ const r = await fetch(+ `/api/forever/status?id=${encodeURIComponent(currentOrder.orderId)}`,+ );+ const d = await r.json();+ if (!r.ok) return;+ setStatePill(d.state);++ if (d.state === 'inscribed' && d.inscription?.id) {+ stopPolling();+ await onInscribed(d);+ } else if (d.state === 'failed') {+ stopPolling();+ showError(+ 'OrdinalsBot reports this order failed. If you paid, contact OrdinalsBot support with order ID ' ++ currentOrder.orderId,+ );+ }+ } catch {+ // transient network — keep polling+ }+}++async function onInscribed(d) {+ const insc = d.inscription;+ const inscriptionUrl = d.links?.inscription || `https://ordinals.com/inscription/${insc.id}`;+ const txUrl = d.links?.revealTx || (insc.revealTxid ? `https://mempool.space/tx/${insc.revealTxid}` : null);++ els.winMessage.textContent = currentOrder.message;+ els.winInscriptionLink.textContent = insc.id;+ els.winInscriptionLink.href = inscriptionUrl;+ if (txUrl) {+ els.winTxLink.textContent = insc.revealTxid || 'view tx';+ els.winTxLink.href = txUrl;+ } else {+ els.winTxLink.textContent = '—';+ els.winTxLink.removeAttribute('href');+ }+ els.winReceive.textContent = currentOrder.receiveAddress;++ // Wire share buttons against this inscription.+ const shareText = buildShareText(currentOrder.message, inscriptionUrl);+ const xUrl = `https://twitter.com/intent/tweet?text=${encodeURIComponent(shareText)}`;+ els.shareX.onclick = () => window.open(xUrl, '_blank', 'noopener,width=600,height=520');+ els.copyLink.onclick = async () => {+ try {+ await navigator.clipboard.writeText(inscriptionUrl);+ els.copyLink.textContent = 'Copied ✓';+ setTimeout(() => (els.copyLink.textContent = 'Copy permalink'), 1500);+ } catch {+ window.prompt('Copy this link:', inscriptionUrl);+ }+ };+ els.inscribeAnother.onclick = () => {+ sessionStorage.removeItem('forever:order');+ currentOrder = null;+ els.message.value = '';+ updateCounters();+ clearError();+ show('compose');+ };++ sessionStorage.removeItem('forever:order');+ show('win');+}++function buildShareText(message, url) {+ // Viral hook: short, declarative, with the message quoted. URL goes last+ // so X auto-unfurls the inscription preview.+ const truncated = message.length > 180 ? message.slice(0, 177) + '…' : message;+ return (+ `I just etched this onto Bitcoin. Forever.\n\n` ++ `"${truncated}"\n\n` ++ `Verify on chain: ${url}\n\n` ++ `Make yours → three.ws/forever`+ );+}++// ── pay-view actions ───────────────────────────────────────────+els.cancelPay.addEventListener('click', () => {+ if (!confirm('Cancel this inscription? Your message will not be inscribed unless you pay the BTC charge.')) return;+ stopPolling();+ sessionStorage.removeItem('forever:order');+ currentOrder = null;+ show('compose');+});++document.querySelectorAll('.copy[data-copy]').forEach((btn) => {+ btn.addEventListener('click', async () => {+ const targetId = btn.getAttribute('data-copy');+ const node = $(targetId);+ const text = node?.textContent?.trim();+ if (!text) return;+ try {+ await navigator.clipboard.writeText(text);+ const orig = btn.textContent;+ btn.textContent = 'copied ✓';+ setTimeout(() => (btn.textContent = orig), 1200);+ } catch {+ window.prompt('Copy:', text);+ }+ });+});++// ── resume after reload ────────────────────────────────────────+(function resumeIfAny() {+ try {+ const raw = sessionStorage.getItem('forever:order');+ if (!raw) return;+ const saved = JSON.parse(raw);+ if (!saved?.orderId) return;+ currentOrder = saved;+ // Repaint pay view with cached message; status poll will fill the rest.+ els.orderIdPay.textContent = saved.orderId;+ els.messagePreview.textContent = saved.message || '';+ els.receiveAddrPay.textContent = saved.receiveAddress || '—';+ show('pay');+ // Refresh the charge details from server.+ fetch(`/api/forever/status?id=${encodeURIComponent(saved.orderId)}`)+ .then((r) => r.json())+ .then((d) => {+ if (d.charge?.address) {+ const amountBtc = d.charge.amountBtc ?? (d.charge.amount ? d.charge.amount / 1e8 : 0);+ els.amountBtc.textContent = amountBtc ? amountBtc.toFixed(8) : '—';+ els.amountSats.textContent = d.charge.amount ? `· ${d.charge.amount.toLocaleString()} sats` : '';+ els.amountUsd.textContent = BTC_USD && amountBtc+ ? `≈ $${(amountBtc * BTC_USD).toLocaleString(undefined, { maximumFractionDigits: 2 })}`+ : '';+ els.payAddress.textContent = d.charge.address;+ const bip21 = buildBip21({ address: d.charge.address, amountBtc, label: 'three.ws · forever' });+ renderQR(bip21);+ els.openWallet.href = bip21;+ els.mempoolLink.href = `https://mempool.space/address/${d.charge.address}`;+ }+ setStatePill(d.state || 'waiting-payment');+ startPolling();+ if (d.state === 'inscribed' && d.inscription?.id) onInscribed(d);+ })+ .catch(() => startPolling());+ } catch {+ sessionStorage.removeItem('forever:order');+ }+})();diff --git a/public/providers.html b/public/providers.htmlnew file mode 100644index 000000000..4644518ae--- /dev/null+++ b/public/providers.html@@ -0,0 +1,328 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8" />+<meta name="viewport" content="width=device-width,initial-scale=1" />+<title>x402 Providers — operator profiles for the bazaar</title>+<meta name="description" content="Quantified provider profiles for the x402 paid API catalog. Service counts, price bands, dominant categories, and the underlying listings." />+<meta name="theme-color" content="#0a0b10" />+<style>+ :root {+ --bg: #0a0b10;+ --bg-2: #0f1119;+ --panel: #14161f;+ --panel-2: #1a1d29;+ --border: #232636;+ --border-strong: #2e3447;+ --text: #f0f2f8;+ --muted: #8a90a8;+ --muted-2: #6b7088;+ --accent-blue: #60a5fa;+ --accent-green: #4ade80;+ --accent-red: #f87171;+ --accent-amber: #f59e0b;+ --accent-purple: #c084fc;+ --mono: ui-monospace, "JetBrains Mono", "Fira Code", Menlo, monospace;+ }+ * { box-sizing: border-box; }+ html, body { margin: 0; padding: 0; background: var(--bg); color: var(--text); }+ body {+ font-family: -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;+ -webkit-font-smoothing: antialiased;+ line-height: 1.5;+ min-height: 100vh;+ }+ a { color: var(--accent-blue); text-decoration: none; }+ a:hover { color: #93c5fd; }++ .wrap { max-width: 1280px; margin: 0 auto; padding: 0 28px; }+ @media (max-width: 720px) { .wrap { padding: 0 16px; } }++ nav {+ padding: 22px 0;+ display: flex; align-items: center; justify-content: space-between;+ border-bottom: 1px solid var(--border);+ flex-wrap: wrap; gap: 12px;+ }+ nav .brand { display: flex; align-items: center; gap: 10px; font-weight: 700; font-size: 16px; letter-spacing: -0.01em; }+ nav .brand .dot {+ width: 22px; height: 22px;+ background: conic-gradient(from 200deg, #ffffff, #60a5fa, #ffffff);+ border-radius: 6px;+ }+ nav .links { display: flex; gap: 18px; font-size: 13.5px; color: var(--muted); flex-wrap: wrap; }+ nav .links a { color: var(--muted); }+ nav .links a:hover { color: var(--text); }+ nav .links a.active { color: var(--text); }++ header.hero { padding: 38px 0 18px; }+ header.hero h1 { font-size: 32px; line-height: 1.15; margin: 0 0 8px; letter-spacing: -0.02em; }+ header.hero p { color: var(--muted); margin: 0; font-size: 15px; max-width: 720px; }++ .toolbar {+ margin: 18px 0;+ display: flex; align-items: center; gap: 10px; flex-wrap: wrap;+ }+ .toolbar input[type=search] {+ flex: 1 1 280px;+ min-width: 200px;+ background: var(--panel);+ border: 1px solid var(--border-strong);+ color: var(--text);+ padding: 9px 14px;+ font-size: 14px;+ border-radius: 999px;+ outline: none;+ }+ .toolbar input[type=search]:focus { border-color: var(--accent-blue); }+ .toolbar select {+ background: var(--panel);+ color: var(--text);+ border: 1px solid var(--border-strong);+ padding: 9px 12px;+ font-size: 13.5px;+ border-radius: 8px;+ outline: none;+ }+ .toolbar .count { color: var(--muted); font-size: 13px; margin-left: auto; }+ .toolbar .count strong { color: var(--text); font-weight: 600; }++ .grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));+ gap: 14px;+ padding-bottom: 56px;+ }+ .prov {+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 12px;+ padding: 18px;+ display: flex; flex-direction: column; gap: 12px;+ text-decoration: none;+ color: var(--text);+ transition: border-color 0.15s ease, transform 0.15s ease;+ }+ .prov:hover { border-color: var(--border-strong); transform: translateY(-1px); }+ .prov .head { display: flex; align-items: center; gap: 12px; }+ .prov .icon {+ width: 44px; height: 44px;+ border-radius: 10px;+ background: var(--panel-2);+ border: 1px solid var(--border);+ display: flex; align-items: center; justify-content: center;+ flex-shrink: 0;+ font-size: 17px; color: var(--muted);+ overflow: hidden;+ font-weight: 600;+ }+ .prov .icon img { width: 100%; height: 100%; object-fit: cover; }+ .prov .host {+ font-weight: 600;+ font-size: 15px;+ font-family: var(--mono);+ word-break: break-all;+ }+ .prov .submeta {+ font-size: 11.5px;+ color: var(--muted);+ font-family: var(--mono);+ margin-top: 2px;+ }+ .kpis {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 0;+ border: 1px solid var(--border);+ border-radius: 8px;+ overflow: hidden;+ }+ .kpis > div {+ padding: 10px 12px;+ border-right: 1px solid var(--border);+ background: var(--bg-2);+ }+ .kpis > div:last-child { border-right: none; }+ .kpis .k {+ font-size: 10px;+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: var(--muted-2);+ margin-bottom: 4px;+ }+ .kpis .v {+ font-family: var(--mono);+ font-size: 13.5px;+ color: var(--text);+ font-weight: 600;+ }+ .kpis .v.green { color: var(--accent-green); }++ .tagrow { display: flex; gap: 5px; flex-wrap: wrap; }+ .tag {+ background: var(--panel-2);+ border: 1px solid var(--border);+ color: var(--muted);+ padding: 3px 8px;+ border-radius: 999px;+ font-size: 11px;+ font-family: var(--mono);+ }+ .tag.net { color: var(--accent-blue); border-color: rgba(96,165,250,0.3); }+ .tag.fac { color: var(--accent-purple); border-color: rgba(192,132,252,0.3); }++ .profile-grid {+ display: grid;+ grid-template-columns: 320px 1fr;+ gap: 18px;+ padding-bottom: 56px;+ }+ @media (max-width: 880px) { .profile-grid { grid-template-columns: 1fr; } }+ .panel {+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 12px;+ padding: 18px;+ }+ .panel h3 {+ margin: 0 0 12px;+ font-size: 10.5px;+ letter-spacing: 0.1em;+ text-transform: uppercase;+ color: var(--muted-2);+ font-weight: 600;+ }+ .profile-head {+ display: flex; align-items: center; gap: 14px;+ margin-bottom: 14px;+ }+ .profile-head .icon {+ width: 64px; height: 64px;+ border-radius: 14px;+ background: var(--panel-2);+ border: 1px solid var(--border-strong);+ display: flex; align-items: center; justify-content: center;+ font-size: 24px; color: var(--text);+ font-weight: 700;+ overflow: hidden;+ }+ .profile-head .icon img { width: 100%; height: 100%; object-fit: cover; }+ .profile-head .info { flex: 1; min-width: 0; }+ .profile-head .host {+ font-size: 22px; font-weight: 700; letter-spacing: -0.01em;+ font-family: var(--mono);+ word-break: break-all;+ }+ .profile-head .sub {+ color: var(--muted); font-size: 13px; margin-top: 2px;+ }+ .profile-head .actions { display: flex; gap: 8px; flex-wrap: wrap; }+ .btn {+ background: var(--accent-blue); color: #0a0b10;+ border: none; padding: 9px 18px;+ font-size: 13px; font-weight: 600;+ border-radius: 8px; cursor: pointer;+ }+ .btn.ghost { background: transparent; color: var(--text); border: 1px solid var(--border-strong); }+ .btn.ghost:hover { border-color: var(--accent-blue); }++ .metric-list { display: flex; flex-direction: column; gap: 0; }+ .metric-list .row {+ display: flex; justify-content: space-between; align-items: baseline;+ padding: 9px 0;+ border-bottom: 1px solid var(--border);+ font-size: 13px;+ }+ .metric-list .row:last-child { border-bottom: none; }+ .metric-list .k { color: var(--muted); }+ .metric-list .v { color: var(--text); font-family: var(--mono); font-weight: 600; }+ .metric-list .v.green { color: var(--accent-green); }++ .bar-list { display: flex; flex-direction: column; gap: 8px; }+ .bar-row {+ display: grid;+ grid-template-columns: 120px 1fr 60px;+ gap: 10px;+ align-items: center;+ font-size: 12.5px;+ }+ .bar-row .label { color: var(--text); font-family: var(--mono); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+ .bar-row .bar { background: var(--bg-2); border: 1px solid var(--border); border-radius: 999px; height: 10px; overflow: hidden; }+ .bar-row .fill { height: 100%; background: linear-gradient(90deg, var(--accent-blue), var(--accent-purple)); border-radius: 999px; }+ .bar-row .pct { color: var(--muted); font-family: var(--mono); font-size: 11.5px; text-align: right; }++ .listing-table { display: flex; flex-direction: column; gap: 0; }+ .listing-row {+ display: grid;+ grid-template-columns: 36px 1fr 90px 100px;+ gap: 12px;+ padding: 12px 0;+ border-bottom: 1px solid var(--border);+ align-items: center;+ text-decoration: none;+ color: inherit;+ }+ .listing-row:last-child { border-bottom: none; }+ .listing-row:hover { background: var(--bg-2); }+ .listing-row .li-icon {+ width: 32px; height: 32px;+ border-radius: 8px;+ background: var(--panel-2);+ border: 1px solid var(--border);+ display: flex; align-items: center; justify-content: center;+ font-size: 13px; color: var(--muted);+ overflow: hidden;+ }+ .listing-row .li-icon img { width: 100%; height: 100%; object-fit: cover; }+ .listing-row .li-main { min-width: 0; }+ .listing-row .li-name { color: var(--text); font-weight: 500; font-size: 13.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+ .listing-row .li-desc { color: var(--muted); font-size: 11.5px; margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+ .listing-row .li-type { font-family: var(--mono); font-size: 11px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.04em; }+ .listing-row .li-price { font-family: var(--mono); font-size: 13px; color: var(--accent-green); font-weight: 600; text-align: right; }++ .back-link {+ display: inline-flex; align-items: center; gap: 6px;+ color: var(--muted); font-size: 13px;+ padding: 6px 0;+ margin-bottom: 8px;+ }+ .back-link:hover { color: var(--text); }++ .empty, .err {+ padding: 60px 20px;+ text-align: center;+ color: var(--muted);+ border: 1px dashed var(--border-strong);+ border-radius: 12px;+ margin-bottom: 56px;+ }+ .err { color: #fecaca; border-color: rgba(248,113,113,0.3); }++ .skeleton {+ background: linear-gradient(90deg, var(--panel) 25%, var(--panel-2) 50%, var(--panel) 75%);+ background-size: 200% 100%;+ animation: shimmer 1.4s ease-in-out infinite;+ border-radius: 8px;+ }+ @keyframes shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }+ .sk-card { height: 200px; }+</style>+</head>+<body>+<div class="wrap">+ <nav>+ <div class="brand"><span class="dot"></span><span>x402 bazaar</span></div>+ <div class="links">+ <a href="/bazaar">Catalog</a>+ <a href="/arbitrage">Arbitrage</a>+ <a href="/providers" class="active">Providers</a>+ <a href="https://www.x402.org/docs/extensions/bazaar" target="_blank" rel="noopener">Spec</a>+ </div>+ </nav>++ <div id="root"></div>+</div>++<script type="module" src="/providers.js"></script>+</body>+</html>diff --git a/public/providers.js b/public/providers.jsnew file mode 100644index 000000000..c0f80eb00--- /dev/null+++ b/public/providers.js@@ -0,0 +1,309 @@+// public/providers.js — directory + single-provider profile UI.+//+// Reads ?host=<host> from the URL: present → render the deep profile,+// absent → render the directory grid. Both modes pull /api/bazaar/providers+// which already does the aggregation server-side.++const $ = (sel) => document.querySelector(sel);+const root = $('#root');++const state = {+ host: new URLSearchParams(location.search).get('host') || '',+ directory: null,+ q: '',+ sort: 'count',+};++function escapeHtml(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+}++function shortNet(n) {+ if (!n) return '';+ if (n.startsWith('eip155:8453')) return 'base';+ if (n.startsWith('eip155:84532')) return 'base-sepolia';+ if (n.startsWith('eip155:42161')) return 'arbitrum';+ if (n.startsWith('eip155:10')) return 'optimism';+ if (n.startsWith('eip155:137')) return 'polygon';+ if (n.startsWith('solana')) return 'solana';+ return n;+}++function renderSkeleton(count = 6) {+ const frag = document.createDocumentFragment();+ for (let i = 0; i < count; i++) {+ const sk = document.createElement('div');+ sk.className = 'skeleton sk-card';+ frag.appendChild(sk);+ }+ const g = document.createElement('div');+ g.className = 'grid';+ g.appendChild(frag);+ root.replaceChildren(g);+}++async function loadDirectory() {+ root.innerHTML = `+ <header class="hero">+ <h1>Providers</h1>+ <p>Operator profiles for the merged x402 catalog. Click any provider for the full price ladder, networks, and category mix.</p>+ </header>+ <div class="toolbar">+ <input type="search" id="q" placeholder="Search providers by host…" />+ <select id="sort">+ <option value="count">Most services</option>+ <option value="price-low">Cheapest median</option>+ <option value="price-high">Most expensive median</option>+ <option value="networks">Most networks</option>+ </select>+ <div class="count"><strong id="count">…</strong> providers</div>+ </div>+ <div id="dgrid" class="grid"></div>+ <div id="dempty" class="empty" hidden></div>+ `;+ const dgrid = $('#dgrid');+ const dempty = $('#dempty');+ const countEl = $('#count');+ const qEl = $('#q');+ const sortEl = $('#sort');++ renderSkeleton();+ try {+ const r = await fetch('/api/bazaar/providers?limit=500');+ const data = await r.json();+ if (!r.ok) throw new Error(data?.error_description || data?.error || `HTTP ${r.status}`);+ state.directory = data.providers || [];+ } catch (e) {+ dgrid.innerHTML = '';+ dempty.hidden = false;+ dempty.className = 'err';+ dempty.textContent = `Failed to load providers: ${e?.message || e}`;+ return;+ }++ function render() {+ const q = state.q.trim().toLowerCase();+ let list = state.directory.filter((p) => !q || p.host.toLowerCase().includes(q) || (p.topTags || []).some((t) => t.toLowerCase().includes(q)));+ switch (state.sort) {+ case 'price-low':+ list = list.sort((a, b) => (a.medianPriceAtomic ?? Infinity) - (b.medianPriceAtomic ?? Infinity));+ break;+ case 'price-high':+ list = list.sort((a, b) => (b.medianPriceAtomic ?? -1) - (a.medianPriceAtomic ?? -1));+ break;+ case 'networks':+ list = list.sort((a, b) => (b.networks?.length || 0) - (a.networks?.length || 0));+ break;+ default:+ list = list.sort((a, b) => b.serviceCount - a.serviceCount);+ }+ countEl.textContent = String(list.length);+ if (list.length === 0) {+ dgrid.innerHTML = '';+ dempty.hidden = false;+ dempty.className = 'empty';+ dempty.textContent = 'No providers match. Clear the search to see all.';+ return;+ }+ dempty.hidden = true;+ const frag = document.createDocumentFragment();+ for (const p of list) frag.appendChild(directoryCard(p));+ dgrid.replaceChildren(frag);+ }++ function directoryCard(p) {+ const el = document.createElement('a');+ el.className = 'prov';+ el.href = `/providers?host=${encodeURIComponent(p.host)}`;++ const head = document.createElement('div');+ head.className = 'head';+ const icon = document.createElement('div');+ icon.className = 'icon';+ if (p.iconUrl) {+ const img = document.createElement('img');+ img.src = p.iconUrl;+ img.alt = '';+ img.referrerPolicy = 'no-referrer';+ img.onerror = () => { icon.textContent = (p.host || '?').charAt(0).toUpperCase(); img.remove(); };+ icon.appendChild(img);+ } else {+ icon.textContent = (p.host || '?').charAt(0).toUpperCase();+ }+ const info = document.createElement('div');+ info.style.flex = '1';+ info.style.minWidth = '0';+ info.innerHTML = `<div class="host">${escapeHtml(p.host)}</div><div class="submeta">${p.serviceCount} ${p.serviceCount === 1 ? 'service' : 'services'} · ${p.networks.length} ${p.networks.length === 1 ? 'network' : 'networks'}</div>`;+ head.append(icon, info);++ const kpis = document.createElement('div');+ kpis.className = 'kpis';+ kpis.innerHTML = `+ <div><div class="k">Services</div><div class="v">${p.serviceCount}</div></div>+ <div><div class="k">Median</div><div class="v green">${escapeHtml(p.medianPriceLabel || '—')}</div></div>+ <div><div class="k">Min</div><div class="v green">${escapeHtml(p.minPriceLabel || '—')}</div></div>+ `;++ const tagrow = document.createElement('div');+ tagrow.className = 'tagrow';+ for (const t of (p.topTags || []).slice(0, 4)) {+ const tag = document.createElement('span');+ tag.className = 'tag';+ tag.textContent = t;+ tagrow.appendChild(tag);+ }+ for (const n of (p.networks || []).slice(0, 3)) {+ const tag = document.createElement('span');+ tag.className = 'tag net';+ tag.textContent = shortNet(n);+ tagrow.appendChild(tag);+ }++ el.append(head, kpis, tagrow);+ return el;+ }++ qEl.addEventListener('input', () => { state.q = qEl.value; render(); });+ sortEl.addEventListener('change', () => { state.sort = sortEl.value; render(); });+ render();+}++async function loadProfile(host) {+ renderSkeleton(3);+ let data;+ try {+ const r = await fetch(`/api/bazaar/providers?host=${encodeURIComponent(host)}`);+ data = await r.json();+ if (!r.ok) throw new Error(data?.error_description || data?.error || `HTTP ${r.status}`);+ } catch (e) {+ root.innerHTML = `<div class="err">Failed to load provider: ${escapeHtml(e?.message || String(e))}</div><a class="back-link" href="/providers">← Back to all providers</a>`;+ return;+ }++ const totalListings = data.listings.length;+ const tagCounts = new Map();+ for (const l of data.listings) for (const t of l.tags || []) tagCounts.set(t, (tagCounts.get(t) || 0) + 1);+ const topTags = [...tagCounts.entries()].sort((a, b) => b[1] - a[1]).slice(0, 6);+ const maxTagCount = topTags.length ? topTags[0][1] : 1;++ const netCounts = new Map();+ for (const l of data.listings) for (const n of l.networks || []) netCounts.set(n, (netCounts.get(n) || 0) + 1);+ const netRows = [...netCounts.entries()].sort((a, b) => b[1] - a[1]);++ const typeBreakdown = { http: data.httpCount, mcp: data.mcpCount };++ root.innerHTML = `+ <a class="back-link" href="/providers">← All providers</a>+ <div class="profile-grid">+ <div>+ <div class="panel">+ <div class="profile-head">+ <div class="icon" id="phicon">${data.iconUrl ? '' : escapeHtml((data.host || '?').charAt(0).toUpperCase())}</div>+ <div class="info">+ <div class="host">${escapeHtml(data.host)}</div>+ <div class="sub">${data.serviceCount} services · ${data.networks.length} networks</div>+ </div>+ </div>+ <div class="profile-head" style="margin: 0;">+ <div class="actions" style="flex: 1;">+ <a class="btn" href="https://${escapeHtml(data.host)}" target="_blank" rel="noopener">Visit site</a>+ <a class="btn ghost" href="/bazaar?q=${encodeURIComponent(data.host)}">Open in catalog</a>+ </div>+ </div>+ </div>+ <div class="panel" style="margin-top: 14px;">+ <h3>Profile · ${totalListings} listings</h3>+ <div class="metric-list">+ <div class="row"><span class="k">HTTP endpoints</span><span class="v">${typeBreakdown.http}</span></div>+ <div class="row"><span class="k">MCP tools</span><span class="v">${typeBreakdown.mcp}</span></div>+ <div class="row"><span class="k">Median price</span><span class="v green">${escapeHtml(data.medianPriceLabel || '—')}</span></div>+ <div class="row"><span class="k">Min price</span><span class="v green">${escapeHtml(data.minPriceLabel || '—')}</span></div>+ <div class="row"><span class="k">Max price</span><span class="v">${escapeHtml(data.maxPriceLabel || '—')}</span></div>+ <div class="row"><span class="k">Networks</span><span class="v">${data.networks.length}</span></div>+ <div class="row"><span class="k">Facilitators</span><span class="v">${data.facilitators.length}</span></div>+ </div>+ </div>+ ${data.facilitators.length ? `+ <div class="panel" style="margin-top: 14px;">+ <h3>Discovered on</h3>+ <div class="tagrow">${data.facilitators.map((f) => `<span class="tag fac">${escapeHtml(f)}</span>`).join('')}</div>+ </div>` : ''}+ </div>+ <div>+ <div class="panel">+ <h3>Category mix</h3>+ ${topTags.length ? `<div class="bar-list">${topTags.map(([t, c]) => `+ <div class="bar-row">+ <div class="label">${escapeHtml(t)}</div>+ <div class="bar"><div class="fill" style="width:${Math.round((c / maxTagCount) * 100)}%"></div></div>+ <div class="pct">${c}</div>+ </div>+ `).join('')}</div>` : `<div style="color: var(--muted); font-size: 13px;">No tags set on this provider's listings.</div>`}+ </div>+ ${netRows.length ? `+ <div class="panel" style="margin-top: 14px;">+ <h3>Network coverage</h3>+ <div class="bar-list">${netRows.map(([n, c]) => `+ <div class="bar-row">+ <div class="label">${escapeHtml(shortNet(n))}</div>+ <div class="bar"><div class="fill" style="width:${Math.round((c / totalListings) * 100)}%"></div></div>+ <div class="pct">${c}</div>+ </div>+ `).join('')}</div>+ </div>` : ''}+ <div class="panel" style="margin-top: 14px;">+ <h3>Services · price ladder (cheap → expensive)</h3>+ <div class="listing-table" id="ltable"></div>+ </div>+ </div>+ </div>+ `;++ if (data.iconUrl) {+ const iconEl = document.getElementById('phicon');+ const img = document.createElement('img');+ img.src = data.iconUrl;+ img.alt = '';+ img.referrerPolicy = 'no-referrer';+ img.onerror = () => { iconEl.textContent = (data.host || '?').charAt(0).toUpperCase(); img.remove(); };+ iconEl.appendChild(img);+ }++ const ltable = document.getElementById('ltable');+ const frag = document.createDocumentFragment();+ for (const l of data.listings) frag.appendChild(listingRow(l));+ ltable.replaceChildren(frag);++ function listingRow(l) {+ const row = document.createElement('a');+ row.className = 'listing-row';+ row.href = `/bazaar?q=${encodeURIComponent(l.serviceName || l.toolName || l.resource)}`;+ const icon = document.createElement('div');+ icon.className = 'li-icon';+ if (l.iconUrl) {+ const img = document.createElement('img');+ img.src = l.iconUrl; img.alt = ''; img.referrerPolicy = 'no-referrer';+ img.onerror = () => { icon.textContent = (l.serviceName || '?').charAt(0).toUpperCase(); img.remove(); };+ icon.appendChild(img);+ } else {+ icon.textContent = (l.serviceName || l.toolName || '?').charAt(0).toUpperCase();+ }+ const main = document.createElement('div');+ main.className = 'li-main';+ main.innerHTML = `+ <div class="li-name">${escapeHtml(l.serviceName || l.toolName || l.resource)}</div>+ <div class="li-desc">${escapeHtml(l.description || l.resource)}</div>+ `;+ const type = document.createElement('div');+ type.className = 'li-type';+ type.textContent = l.toolName ? `MCP · ${l.toolName}` : (l.method || l.type).toUpperCase();+ const price = document.createElement('div');+ price.className = 'li-price';+ price.textContent = l.priceLabel || '—';+ row.append(icon, main, type, price);+ return row;+ }+}++if (state.host) loadProfile(state.host);+else loadDirectory();diff --git a/vercel.json b/vercel.jsonindex ca0c5aadb..9b18ba156 100644--- a/vercel.json+++ b/vercel.json@@ -1807,6 +1807,38 @@"src": "/bazaar/","dest": "/bazaar.html"},+ {+ "src": "/arbitrage",+ "dest": "/arbitrage.html"+ },+ {+ "src": "/arbitrage/",+ "dest": "/arbitrage.html"+ },+ {+ "src": "/providers",+ "dest": "/providers.html"+ },+ {+ "src": "/providers/",+ "dest": "/providers.html"+ },+ {+ "src": "/forever",+ "dest": "/forever.html"+ },+ {+ "src": "/forever/",+ "dest": "/forever.html"+ },+ {+ "src": "/api/forever/inscribe",+ "dest": "/api/forever/inscribe.js"+ },+ {+ "src": "/api/forever/status",+ "dest": "/api/forever/status.js"+ },{"src": "/api/bazaar/list","dest": "/api/bazaar/list.js"@@ -1815,6 +1847,18 @@"src": "/api/bazaar/search","dest": "/api/bazaar/search.js"},+ {+ "src": "/api/bazaar/arbitrage",+ "dest": "/api/bazaar/arbitrage.js"+ },+ {+ "src": "/api/bazaar/providers",+ "dest": "/api/bazaar/providers.js"+ },+ {+ "src": "/api/bazaar/context",+ "dest": "/api/bazaar/context.js"+ },{"src": "/settings","dest": "/settings/index.html"diff --git a/vite.config.js b/vite.config.jsindex c43024930..bfa2f2c02 100644--- a/vite.config.js+++ b/vite.config.js@@ -512,6 +512,12 @@ const appConfig = {'/docs/': resolve(root, 'docs/index.html'),'/bazaar': resolve(root, 'public/bazaar.html'),'/bazaar/': resolve(root, 'public/bazaar.html'),+ '/forever': resolve(root, 'public/forever.html'),+ '/forever/': resolve(root, 'public/forever.html'),+ '/arbitrage': resolve(root, 'public/arbitrage.html'),+ '/arbitrage/': resolve(root, 'public/arbitrage.html'),+ '/providers': resolve(root, 'public/providers.html'),+ '/providers/': resolve(root, 'public/providers.html'),};// Routes that resolve to public/<dir>/index.html — these need a// trailing slash so relative imports (./foo.js) inside the HTML