Skip to content

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

feat: agent reviews UI, marketplace rating sort, brain provider availability, light probe grid, production bug fixes

overstepping960035726768
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cb9c11587..212601c3e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,12 @@
Public feature history for [three.ws](https://three.ws), newest first. Feature dates are tracked from 2026-05-25 forward; earlier pages are omitted.
+## 2026-05-27
+
+- **Endpoint Shopper** (`/shopper`) — Describe a task and set a budget. An AI agent discovers relevant x402 endpoints via the Bazaar, chains them together, and synthesizes a final answer — paying per API call.
+- **Fact Checker** (`/fact-checker`) — Pay $0.10 per claim. The agent searches across authoritative sources, pays per retrieval via x402, and returns a verdict with cited evidence and a signed attestation.
+- **Unstoppable Agent** (`/unstoppable`) — Live dashboard for an autonomous agent that funds itself via x402 micropayments. Watch its balance, earnings, costs, and daily reflections in real time.
+
## 2026-05-25
- **Characters** (`/characters`) — Discover AI characters on three.ws. Chat, trade, and create.
diff --git a/agents/endpoint-shopper/src/discover.js b/agents/endpoint-shopper/src/discover.js
new file mode 100644
index 000000000..6331bcfad
--- /dev/null
+++ b/agents/endpoint-shopper/src/discover.js
@@ -0,0 +1,102 @@
+// Bazaar discovery for the Endpoint Shopper agent.
+//
+// Queries our own /api/bazaar/search and /api/bazaar/list proxies which
+// aggregate across all configured x402 facilitators. Results are normalized
+// into a flat shape the planner and orchestrator can work with.
+
+const BASE = process.env.PUBLIC_APP_ORIGIN || process.env.APP_ORIGIN || 'https://three.ws';
+
+/**
+ * Normalize a raw Bazaar resource/item into the shape used throughout the agent.
+ *
+ * @param {object} raw
+ * @returns {{ url: string, serviceName: string, description: string, tags: string[], priceUsdc: string, network: string, priceAtomics: number }}
+ */
+function normalize(raw) {
+ // Resources (from search) and items (from list) have slightly different shapes
+ const url = String(raw.resource || raw.url || '');
+ const serviceName = String(raw.serviceName || raw.service?.serviceName || '');
+ const description = String(raw.description || raw.service?.description || '');
+ const tags = Array.isArray(raw.tags) ? raw.tags : Array.isArray(raw.service?.tags) ? raw.service.tags : [];
+ // Find the cheapest accept entry across networks
+ const accepts = Array.isArray(raw.accepts) ? raw.accepts : [];
+ let priceAtomics = 0;
+ let network = '';
+ if (accepts.length > 0) {
+ const cheapest = accepts.reduce((a, b) => {
+ const pa = Number(a.amount || 0);
+ const pb = Number(b.amount || 0);
+ return pb < pa ? b : a;
+ }, accepts[0]);
+ priceAtomics = Number(cheapest.amount || 0);
+ network = String(cheapest.network || '');
+ }
+ const priceUsdc = (priceAtomics / 1_000_000).toFixed(6).replace(/\.?0+$/, '') || '0';
+
+ return { url, serviceName, description, tags, priceUsdc, network, priceAtomics };
+}
+
+/**
+ * Search the Bazaar for endpoints relevant to a query.
+ *
+ * @param {object} opts
+ * @param {string} opts.query
+ * @param {number} [opts.maxResults=10]
+ * @returns {Promise<Array<{ url, serviceName, description, tags, priceUsdc, network, priceAtomics }>>}
+ */
+export async function discoverEndpoints({ query, maxResults = 10 }) {
+ const url = `${BASE}/api/bazaar/search?q=${encodeURIComponent(query)}&limit=${maxResults}`;
+ const r = await fetch(url, {
+ signal: AbortSignal.timeout(12_000),
+ headers: { 'accept': 'application/json' },
+ }).catch((err) => {
+ throw Object.assign(new Error(`Bazaar search failed: ${err.message}`), {
+ status: 502,
+ code: 'bazaar_search_error',
+ });
+ });
+
+ if (!r.ok) {
+ const text = await r.text().catch(() => '');
+ throw Object.assign(
+ new Error(`Bazaar search returned ${r.status}: ${text.slice(0, 200)}`),
+ { status: 502, code: 'bazaar_search_error' },
+ );
+ }
+
+ const data = await r.json();
+ const resources = Array.isArray(data.resources) ? data.resources : [];
+ return resources.slice(0, maxResults).map(normalize);
+}
+
+/**
+ * List all Bazaar endpoints (up to limit).
+ *
+ * @param {object} [opts]
+ * @param {number} [opts.limit=20]
+ * @returns {Promise<Array<{ url, serviceName, description, tags, priceUsdc, network, priceAtomics }>>}
+ */
+export async function listEndpoints({ limit = 20 } = {}) {
+ const url = `${BASE}/api/bazaar/list?limit=${limit}`;
+ const r = await fetch(url, {
+ signal: AbortSignal.timeout(12_000),
+ headers: { 'accept': 'application/json' },
+ }).catch((err) => {
+ throw Object.assign(new Error(`Bazaar list failed: ${err.message}`), {
+ status: 502,
+ code: 'bazaar_list_error',
+ });
+ });
+
+ if (!r.ok) {
+ const text = await r.text().catch(() => '');
+ throw Object.assign(
+ new Error(`Bazaar list returned ${r.status}: ${text.slice(0, 200)}`),
+ { status: 502, code: 'bazaar_list_error' },
+ );
+ }
+
+ const data = await r.json();
+ const items = Array.isArray(data.items) ? data.items : [];
+ return items.slice(0, limit).map(normalize);
+}
diff --git a/agents/endpoint-shopper/src/orchestrator.js b/agents/endpoint-shopper/src/orchestrator.js
new file mode 100644
index 000000000..5fe84621e
--- /dev/null
+++ b/agents/endpoint-shopper/src/orchestrator.js
@@ -0,0 +1,198 @@
+// Endpoint Shopper orchestrator.
+//
+// Executes a full discover → plan → call → synthesize cycle for a given task,
+// respecting a caller-supplied budget ceiling. Each paid endpoint call is
+// attempted directly; a 402 response is captured in the step output so the
+// caller knows payment would be required in a fully-funded flow.
+
+import { discoverEndpoints } from './discover.js';
+import { planSteps } from './planner.js';
+
+const BASE = process.env.PUBLIC_APP_ORIGIN || process.env.APP_ORIGIN || 'https://three.ws';
+
+/**
+ * Run the full agent loop.
+ *
+ * @param {object} opts
+ * @param {string} opts.task Natural-language task
+ * @param {number} [opts.maxCostUsd=0.50] Maximum spend in USD
+ * @returns {Promise<{
+ * result: { answer: string, data: any },
+ * steps: Array,
+ * totalCostUsdc: string
+ * }>}
+ */
+export async function run({ task, maxCostUsd = 0.50 }) {
+ const maxCostAtomics = Math.round(Math.min(maxCostUsd, 2.0) * 1_000_000);
+ let totalCostAtomics = 0;
+ const steps = [];
+
+ // ── Step 1: Discover relevant endpoints ───────────────────────────────
+ let catalog = [];
+ try {
+ catalog = await discoverEndpoints({ query: task, maxResults: 10 });
+ } catch {
+ catalog = [];
+ }
+ steps.push({
+ step: 1,
+ action: 'discover',
+ description: `Searched Bazaar for "${task.slice(0, 60)}${task.length > 60 ? '…' : ''}" — found ${catalog.length} endpoint${catalog.length === 1 ? '' : 's'}`,
+ costUsdc: '0.000000',
+ output: catalog.slice(0, 5).map((e) => ({ url: e.url, serviceName: e.serviceName, priceUsdc: e.priceUsdc })),
+ });
+
+ // ── Step 2: Plan ───────────────────────────────────────────────────────
+ let plan = [];
+ try {
+ plan = await planSteps({ task, catalog, maxSteps: 5 });
+ } catch {
+ plan = [{ action: 'synthesize', description: 'Synthesize answer from available context' }];
+ }
+ steps.push({
+ step: 2,
+ action: 'plan',
+ description: `Planned ${plan.length} execution step${plan.length === 1 ? '' : 's'}`,
+ costUsdc: '0.000000',
+ output: plan.map((s) => ({ action: s.action, description: s.description })),
+ });
+
+ // ── Step 3: Execute call steps (budget-gated) ─────────────────────────
+ const callSteps = plan.filter((s) => s.action === 'call').slice(0, 3);
+ const results = [];
+
+ for (const step of callSteps) {
+ // Resolve cost — find matching catalog entry or use floor
+ const matched = catalog.find((e) => step.endpoint && step.endpoint.includes(e.url));
+ const stepCostAtomics = matched?.priceAtomics || 1_000;
+
+ if (totalCostAtomics + stepCostAtomics > maxCostAtomics) {
+ steps.push({
+ step: steps.length + 1,
+ action: 'call',
+ endpoint: step.endpoint,
+ description: `Skipped: "${step.description}" — would exceed budget`,
+ costUsdc: '0.000000',
+ output: { skipped: true, reason: 'budget_exceeded' },
+ });
+ continue;
+ }
+
+ // Build the call URL — attach args as query params for GET endpoints
+ let callUrl = step.endpoint || `${BASE}/api/x402/model-check`;
+ if (step.args && typeof step.args === 'object' && Object.keys(step.args).length) {
+ const qs = new URLSearchParams(
+ Object.entries(step.args).map(([k, v]) => [k, String(v)]),
+ ).toString();
+ callUrl = `${callUrl}${callUrl.includes('?') ? '&' : '?'}${qs}`;
+ }
+
+ let callOutput;
+ let callStatus;
+ try {
+ const r = await fetch(callUrl, {
+ signal: AbortSignal.timeout(15_000),
+ headers: { 'accept': 'application/json' },
+ });
+ callStatus = r.status;
+ const raw = await r.json().catch(() => ({ error: 'response parse failed' }));
+ if (r.status === 402) {
+ callOutput = { payment_required: true, requirements: raw?.accepts || raw };
+ } else {
+ callOutput = raw;
+ }
+ } catch (err) {
+ callStatus = 502;
+ callOutput = { error: err.message };
+ }
+
+ const usedAtomics = callStatus !== 402 ? stepCostAtomics : 0;
+ totalCostAtomics += usedAtomics;
+
+ steps.push({
+ step: steps.length + 1,
+ action: 'call',
+ endpoint: callUrl,
+ description: step.description,
+ costUsdc: (usedAtomics / 1_000_000).toFixed(6),
+ output: callOutput,
+ });
+
+ if (callOutput && !callOutput.error && !callOutput.payment_required) {
+ results.push(callOutput);
+ }
+ }
+
+ // ── Step 4: Synthesize ─────────────────────────────────────────────────
+ const answer = await synthesize({ task, results, catalog, plan });
+ steps.push({
+ step: steps.length + 1,
+ action: 'synthesize',
+ description: 'Synthesized final answer from all collected results',
+ costUsdc: '0.000000',
+ output: { answer },
+ });
+
+ return {
+ result: { answer, data: results[0] || null },
+ steps,
+ totalCostUsdc: (totalCostAtomics / 1_000_000).toFixed(6),
+ };
+}
+
+/**
+ * LLM synthesis — combine collected data into a concise final answer.
+ *
+ * @param {object} opts
+ * @param {string} opts.task
+ * @param {Array} opts.results Data returned by endpoint calls
+ * @param {Array} opts.catalog Discovered endpoints (used when results are empty)
+ * @param {Array} opts.plan The execution plan
+ * @returns {Promise<string>}
+ */
+async function synthesize({ task, results, catalog, plan }) {
+ let context;
+ if (results.length > 0) {
+ context = `Collected data from endpoint calls:\n${JSON.stringify(results, null, 2)}`;
+ } else if (catalog.length > 0) {
+ context =
+ `No endpoint data was collected (calls returned 402 or were skipped). ` +
+ `Available endpoints in the Bazaar for this task:\n${catalog
+ .slice(0, 5)
+ .map((e) => `- ${e.serviceName}: ${e.description} (${e.url}, $${e.priceUsdc} USDC)`)
+ .join('\n')}`;
+ } else {
+ context = 'No endpoint data was collected and no relevant endpoints were found in the Bazaar.';
+ }
+
+ const prompt =
+ `Task: "${task}"\n\n` +
+ `${context}\n\n` +
+ `Provide a concise, direct answer to the task based on this information. ` +
+ `If data was collected, summarize the key findings. ` +
+ `If calls required payment (402), explain what endpoints are available and what they would return. ` +
+ `2-4 sentences maximum.`;
+
+ try {
+ const r = await fetch('https://api.anthropic.com/v1/messages', {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ 'x-api-key': process.env.ANTHROPIC_API_KEY,
+ 'anthropic-version': '2023-06-01',
+ },
+ body: JSON.stringify({
+ model: 'claude-haiku-4-5-20251001',
+ max_tokens: 256,
+ messages: [{ role: 'user', content: prompt }],
+ }),
+ signal: AbortSignal.timeout(15_000),
+ });
+
+ if (!r.ok) return 'Unable to synthesize answer — LLM API returned an error.';
+ const d = await r.json();
+ return d.content?.[0]?.text || 'Unable to synthesize answer.';
+ } catch {
+ return 'Unable to synthesize answer — request timed out or failed.';
+ }
+}
diff --git a/agents/endpoint-shopper/src/planner.js b/agents/endpoint-shopper/src/planner.js
new file mode 100644
index 000000000..b566d6ea6
--- /dev/null
+++ b/agents/endpoint-shopper/src/planner.js
@@ -0,0 +1,101 @@
+// LLM-based task decomposition for the Endpoint Shopper agent.
+//
+// Given a task string and a Bazaar catalog summary, generates a structured
+// step plan that the orchestrator can execute. Uses claude-haiku for fast,
+// cheap planning — the heavy work is in the endpoint calls themselves.
+
+const SYSTEM_PROMPT =
+ 'You are a task planner for an AI agent. Given a task and a catalog of available paid API endpoints, ' +
+ 'create a step plan. Respond with JSON only: an array of steps with fields: ' +
+ 'action ("discover"|"call"|"synthesize"), ' +
+ 'description (what this step does), ' +
+ 'endpoint (URL if calling — must match a URL from the catalog), ' +
+ 'args (object of query params or body fields if calling). ' +
+ 'Keep to 3-5 steps. Always end with a "synthesize" step. ' +
+ 'Only emit "call" steps for endpoints that are plausibly relevant to the task. ' +
+ 'If no catalog endpoints fit, still include the synthesize step and note the gap.';
+
+/**
+ * Plan a multi-step execution for a task using available Bazaar endpoints.
+ *
+ * @param {object} opts
+ * @param {string} opts.task Natural-language task description
+ * @param {Array} opts.catalog Array of { url, serviceName, description, tags, priceUsdc }
+ * @param {number} [opts.maxSteps=5] Max steps to request
+ * @returns {Promise<Array<{ action: string, endpoint?: string, args?: object, description: string }>>}
+ */
+export async function planSteps({ task, catalog, maxSteps = 5 }) {
+ const catalogSummary = catalog
+ .slice(0, 20)
+ .map(
+ (e, i) =>
+ `${i + 1}. [${e.serviceName || 'unknown'}] ${e.url}\n ${e.description || '(no description)'}\n Price: $${e.priceUsdc || '?'} USDC Tags: ${(e.tags || []).join(', ')}`,
+ )
+ .join('\n\n');
+
+ const prompt =
+ `Task: "${task}"\n\n` +
+ `Available endpoints (catalog):\n${catalogSummary || '(none found)'}\n\n` +
+ `Create a plan of at most ${maxSteps} steps to complete the task. ` +
+ `Respond with a JSON array only — no markdown, no explanation.`;
+
+ const response = await fetch('https://api.anthropic.com/v1/messages', {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ 'x-api-key': process.env.ANTHROPIC_API_KEY,
+ 'anthropic-version': '2023-06-01',
+ },
+ body: JSON.stringify({
+ model: 'claude-haiku-4-5-20251001',
+ max_tokens: 512,
+ system: SYSTEM_PROMPT,
+ messages: [{ role: 'user', content: prompt }],
+ }),
+ signal: AbortSignal.timeout(15_000),
+ });
+
+ if (!response.ok) {
+ const text = await response.text().catch(() => '');
+ throw Object.assign(new Error(`Anthropic API error ${response.status}: ${text}`), {
+ status: 502,
+ code: 'planner_api_error',
+ });
+ }
+
+ const data = await response.json();
+ const raw = data.content?.[0]?.text || '[]';
+
+ // Strip possible markdown code fence wrapping
+ const cleaned = raw.replace(/^```(?:json)?\n?/i, '').replace(/\n?```$/i, '').trim();
+
+ let plan;
+ try {
+ plan = JSON.parse(cleaned);
+ } catch {
+ // LLM returned non-JSON — fall back to a minimal plan
+ plan = [
+ {
+ action: 'synthesize',
+ description: 'Synthesize answer from available context (planning failed to parse)',
+ },
+ ];
+ }
+
+ if (!Array.isArray(plan)) {
+ plan = [
+ {
+ action: 'synthesize',
+ description: 'Synthesize answer from available context',
+ },
+ ];
+ }
+
+ // Sanitize each step — ensure required fields exist
+ return plan.slice(0, maxSteps).map((s) => ({
+ action: ['discover', 'call', 'synthesize'].includes(s.action) ? s.action : 'call',
+ description: String(s.description || 'Execute step'),
+ ...(s.endpoint ? { endpoint: String(s.endpoint) } : {}),
+ ...(s.args && typeof s.args === 'object' ? { args: s.args } : {}),
+ }));
+}
diff --git a/agents/fact-checker/src/llm-verdict.js b/agents/fact-checker/src/llm-verdict.js
new file mode 100644
index 000000000..5ea645be3
--- /dev/null
+++ b/agents/fact-checker/src/llm-verdict.js
@@ -0,0 +1,161 @@
+// LLM helpers for the fact-checker using direct Anthropic API calls.
+// Model: claude-haiku-4-5-20251001 (cheap + fast for structured extraction).
+
+const ANTHROPIC_MODEL = 'claude-haiku-4-5-20251001';
+const ANTHROPIC_API = 'https://api.anthropic.com/v1/messages';
+const TIMEOUT_MS = 30_000;
+
+function withTimeout(promise, ms) {
+ return Promise.race([
+ promise,
+ new Promise((_, reject) =>
+ setTimeout(() => reject(new Error(`LLM call timed out after ${ms}ms`)), ms),
+ ),
+ ]);
+}
+
+async function callAnthropic(prompt, maxTokens = 1024) {
+ const apiKey = process.env.ANTHROPIC_API_KEY;
+ if (!apiKey) {
+ const err = new Error('ANTHROPIC_API_KEY is not configured');
+ err.status = 503;
+ err.code = 'llm_unavailable';
+ throw err;
+ }
+
+ const res = await withTimeout(
+ fetch(ANTHROPIC_API, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ 'x-api-key': apiKey,
+ 'anthropic-version': '2023-06-01',
+ },
+ body: JSON.stringify({
+ model: ANTHROPIC_MODEL,
+ max_tokens: maxTokens,
+ messages: [{ role: 'user', content: prompt }],
+ }),
+ }),
+ TIMEOUT_MS,
+ );
+
+ if (!res.ok) {
+ const body = await res.text().catch(() => '');
+ const err = new Error(`Anthropic API HTTP ${res.status}: ${body.slice(0, 200)}`);
+ err.status = 502;
+ err.code = 'llm_error';
+ throw err;
+ }
+
+ const data = await res.json();
+ const text = data?.content?.[0]?.text || '';
+ const usage = data?.usage || {};
+ return { text, inputTokens: usage.input_tokens || 0, outputTokens: usage.output_tokens || 0 };
+}
+
+/**
+ * Generate 3 search queries for the given claim.
+ * Returns { queries: string[], tokens: number }
+ */
+export async function generateSearchQueries(claim) {
+ const prompt = `You are a fact-checking assistant. Given the following claim, generate exactly 3 distinct web search queries to find authoritative sources that would verify or refute it.
+
+Claim: "${claim}"
+
+Rules:
+- Each query should approach the claim from a different angle (e.g., direct verification, historical context, expert sources).
+- Keep queries concise (under 12 words each).
+- Do NOT include the word "claim" in queries.
+- Output ONLY a valid JSON array of 3 strings. No explanation, no markdown, just the JSON array.
+
+Example output: ["query one", "query two", "query three"]`;
+
+ const { text, inputTokens, outputTokens } = await callAnthropic(prompt, 256);
+
+ let queries;
+ try {
+ // Extract JSON array from the response, tolerating minor surrounding text.
+ const match = text.match(/\[[\s\S]*?\]/);
+ if (!match) throw new Error('no array found');
+ queries = JSON.parse(match[0]);
+ if (!Array.isArray(queries) || queries.length === 0) throw new Error('empty array');
+ queries = queries.slice(0, 3).map((q) => String(q).trim()).filter(Boolean);
+ if (queries.length === 0) throw new Error('all queries empty after trim');
+ } catch (parseErr) {
+ // Fallback: split on newlines and use first 3 non-empty lines.
+ queries = text
+ .split('\n')
+ .map((l) => l.replace(/^["'\d.\-\s]+/, '').replace(/["',]+$/, '').trim())
+ .filter(Boolean)
+ .slice(0, 3);
+
+ if (queries.length === 0) {
+ // Last resort: use the claim itself as a query.
+ queries = [claim];
+ }
+ }
+
+ return { queries, tokens: inputTokens + outputTokens };
+}
+
+/**
+ * For each of the top 5 search results, extract a 200-char excerpt and
+ * determine stance. One LLM call for all results.
+ *
+ * @param {string} claim
+ * @param {Array<{url: string, title: string, snippet: string}>} results Top 5 results.
+ * @returns {Promise<{analyses: Array<{excerpt: string, stance: string}>, tokens: number}>}
+ */
+export async function analyzeResults(claim, results) {
+ const numbered = results
+ .map(
+ (r, i) =>
+ `[${i + 1}] Title: ${r.title}\nURL: ${r.url}\nContent: ${r.snippet.slice(0, 500)}`,
+ )
+ .join('\n\n');
+
+ const prompt = `You are a fact-checking assistant. Given a claim and ${results.length} search result(s), analyze each result.
+
+Claim: "${claim}"
+
+Search results:
+${numbered}
+
+For each result (1 through ${results.length}), output:
+- excerpt: a 200-character or shorter direct quote or paraphrase from the content that is most relevant to the claim
+- stance: one of "supports", "contradicts", or "neutral"
+ - "supports" = the source backs the claim
+ - "contradicts" = the source refutes the claim
+ - "neutral" = the source is tangentially related but neither supports nor contradicts
+
+Output ONLY a valid JSON array with ${results.length} objects, in order, each with fields "excerpt" (string) and "stance" (string).
+No markdown, no explanation, just the JSON array.
+
+Example (for 2 results): [{"excerpt":"The tower stands at 330m","stance":"supports"},{"excerpt":"Some unrelated content","stance":"neutral"}]`;
+
+ const { text, inputTokens, outputTokens } = await callAnthropic(prompt, 1024);
+
+ let analyses;
+ try {
+ const match = text.match(/\[[\s\S]*?\]/);
+ if (!match) throw new Error('no array found');
+ analyses = JSON.parse(match[0]);
+ if (!Array.isArray(analyses)) throw new Error('not an array');
+ // Normalize and pad/trim to match results length.
+ analyses = analyses.slice(0, results.length).map((a) => ({
+ excerpt: String(a?.excerpt || '').slice(0, 200),
+ stance: ['supports', 'contradicts', 'neutral'].includes(a?.stance)
+ ? a.stance
+ : 'neutral',
+ }));
+ while (analyses.length < results.length) {
+ analyses.push({ excerpt: '', stance: 'neutral' });
+ }
+ } catch {
+ // Fallback: mark all neutral.
+ analyses = results.map(() => ({ excerpt: '', stance: 'neutral' }));
+ }
+
+ return { analyses, tokens: inputTokens + outputTokens };
+}
diff --git a/agents/fact-checker/src/search-sources.js b/agents/fact-checker/src/search-sources.js
new file mode 100644
index 000000000..6c7f5cce7
--- /dev/null
+++ b/agents/fact-checker/src/search-sources.js
@@ -0,0 +1,249 @@
+// Multi-source web search with fallback chain.
+// Priority: Brave → Tavily → Exa → DuckDuckGo instant answer.
+// At least 3 results are always returned (or a descriptive error thrown).
+
+const TIMEOUT_MS = 10_000;
+
+function withTimeout(promise, ms) {
+ return Promise.race([
+ promise,
+ new Promise((_, reject) =>
+ setTimeout(() => reject(new Error(`Search timed out after ${ms}ms`)), ms),
+ ),
+ ]);
+}
+
+// ── Brave Search ──────────────────────────────────────────────────────────────
+
+async function searchBrave(query) {
+ const key = process.env.BRAVE_API_KEY;
+ if (!key) return null;
+
+ const url = `https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(query)}&count=10`;
+ const res = await withTimeout(
+ fetch(url, {
+ headers: {
+ 'accept': 'application/json',
+ 'accept-encoding': 'gzip',
+ 'X-Subscription-Token': key,
+ },
+ }),
+ TIMEOUT_MS,
+ );
+ if (!res.ok) {
+ throw new Error(`Brave search HTTP ${res.status}`);
+ }
+ const data = await res.json();
+ const results = data?.web?.results || [];
+ return results.map((r) => ({
+ url: r.url,
+ title: r.title || '',
+ snippet: r.description || r.extra_snippets?.[0] || '',
+ }));
+}
+
+// ── Tavily ────────────────────────────────────────────────────────────────────
+
+async function searchTavily(query) {
+ const key = process.env.TAVILY_API_KEY;
+ if (!key) return null;
+
+ const res = await withTimeout(
+ fetch('https://api.tavily.com/search', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ api_key: key,
+ query,
+ max_results: 10,
+ search_depth: 'basic',
+ }),
+ }),
+ TIMEOUT_MS,
+ );
+ if (!res.ok) {
+ throw new Error(`Tavily search HTTP ${res.status}`);
+ }
+ const data = await res.json();
+ const results = data?.results || [];
+ return results.map((r) => ({
+ url: r.url,
+ title: r.title || '',
+ snippet: r.content || '',
+ }));
+}
+
+// ── Exa ───────────────────────────────────────────────────────────────────────
+
+async function searchExa(query) {
+ const key = process.env.EXA_API_KEY;
+ if (!key) return null;
+
+ const res = await withTimeout(
+ fetch('https://api.exa.ai/search', {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ 'x-api-key': key,
+ },
+ body: JSON.stringify({ query, numResults: 10, useAutoprompt: true }),
+ }),
+ TIMEOUT_MS,
+ );
+ if (!res.ok) {
+ throw new Error(`Exa search HTTP ${res.status}`);
+ }
+ const data = await res.json();
+ const results = data?.results || [];
+ return results.map((r) => ({
+ url: r.url,
+ title: r.title || '',
+ snippet: r.text ? r.text.slice(0, 400) : '',
+ }));
+}
+
+// ── DuckDuckGo instant answer (fallback) ──────────────────────────────────────
+
+async function searchDuckDuckGo(query) {
+ const url = `https://api.duckduckgo.com/?q=${encodeURIComponent(query)}&format=json&no_redirect=1&t=threews`;
+ const res = await withTimeout(fetch(url, { headers: { accept: 'application/json' } }), TIMEOUT_MS);
+ if (!res.ok) {
+ throw new Error(`DuckDuckGo HTTP ${res.status}`);
+ }
+ const data = await res.json();
+
+ const results = [];
+
+ if (data.AbstractURL && data.Abstract) {
+ results.push({
+ url: data.AbstractURL,
+ title: data.Heading || query,
+ snippet: data.Abstract,
+ });
+ }
+
+ for (const r of data.RelatedTopics || []) {
+ if (r.FirstURL && r.Text) {
+ results.push({ url: r.FirstURL, title: r.Text.slice(0, 80), snippet: r.Text });
+ }
+ // Nested subtopics.
+ if (Array.isArray(r.Topics)) {
+ for (const t of r.Topics) {
+ if (t.FirstURL && t.Text) {
+ results.push({ url: t.FirstURL, title: t.Text.slice(0, 80), snippet: t.Text });
+ }
+ }
+ }
+ }
+
+ for (const r of data.Results || []) {
+ if (r.FirstURL && r.Text) {
+ results.push({ url: r.FirstURL, title: r.Text.slice(0, 80), snippet: r.Text });
+ }
+ }
+
+ return results.slice(0, 10);
+}
+
+// ── Deduplicate by URL ────────────────────────────────────────────────────────
+
+function deduplicate(results) {
+ const seen = new Set();
+ return results.filter((r) => {
+ if (!r.url || seen.has(r.url)) return false;
+ seen.add(r.url);
+ return true;
+ });
+}
+
+// ── Main export ───────────────────────────────────────────────────────────────
+
+/**
+ * Run multi-source search. Uses up to 2 sources in parallel if multiple keys
+ * are configured, falling back through the chain until at least 3 results are
+ * collected.
+ *
+ * @param {string} query
+ * @returns {Promise<Array<{url: string, title: string, snippet: string}>>}
+ */
+export async function searchWeb(query) {
+ const hasBrave = Boolean(process.env.BRAVE_API_KEY);
+ const hasTavily = Boolean(process.env.TAVILY_API_KEY);
+ const hasExa = Boolean(process.env.EXA_API_KEY);
+
+ const searchFns = [];
+ if (hasBrave) searchFns.push(searchBrave);
+ if (hasTavily) searchFns.push(searchTavily);
+ if (hasExa) searchFns.push(searchExa);
+
+ // Run up to 2 sources in parallel for speed.
+ const primary = searchFns.slice(0, 2);
+ let combined = [];
+ let errors = [];
+
+ if (primary.length > 0) {
+ const settled = await Promise.allSettled(primary.map((fn) => fn(query)));
+ for (const outcome of settled) {
+ if (outcome.status === 'fulfilled' && Array.isArray(outcome.value)) {
+ combined.push(...outcome.value);
+ } else if (outcome.status === 'rejected') {
+ errors.push(outcome.reason?.message || String(outcome.reason));
+ }
+ }
+ }
+
+ // If not enough results, try remaining sources sequentially.
+ for (const fn of searchFns.slice(2)) {
+ if (deduplicate(combined).length >= 3) break;
+ try {
+ const more = await fn(query);
+ if (Array.isArray(more)) combined.push(...more);
+ } catch (err) {
+ errors.push(err.message);
+ }
+ }
+
+ // Final fallback: DuckDuckGo.
+ if (deduplicate(combined).length < 3) {
+ try {
+ const ddg = await searchDuckDuckGo(query);
+ combined.push(...ddg);
+ } catch (err) {
+ errors.push(err.message);
+ }
+ }
+
+ const deduped = deduplicate(combined);
+
+ if (deduped.length === 0) {
+ const detail = errors.length ? errors.join('; ') : 'no search providers configured';
+ const err = new Error(`Search returned no results: ${detail}`);
+ err.status = 502;
+ err.code = 'search_failed';
+ throw err;
+ }
+
+ if (deduped.length < 3) {
+ // Return what we have — the verdict logic will mark it 'insufficient'.
+ }
+
+ return deduped;
+}
+
+/**
+ * Run the same query across all three search queries in parallel (max 2 sources each).
+ * Returns a flat deduplicated result list.
+ *
+ * @param {string[]} queries Up to 3 queries.
+ * @returns {Promise<Array<{url: string, title: string, snippet: string}>>}
+ */
+export async function searchAll(queries) {
+ const settled = await Promise.allSettled(queries.map((q) => searchWeb(q)));
+ const combined = [];
+ for (const outcome of settled) {
+ if (outcome.status === 'fulfilled') {
+ combined.push(...outcome.value);
+ }
+ }
+ return deduplicate(combined);
+}
diff --git a/agents/fact-checker/src/source-authority.js b/agents/fact-checker/src/source-authority.js
new file mode 100644
index 000000000..8a8824a9f
--- /dev/null
+++ b/agents/fact-checker/src/source-authority.js
@@ -0,0 +1,85 @@
+// Source authority scoring for fact-checker.
+// Returns a weight in [0, 1] representing how much to trust a given URL.
+
+const DOMAIN_SCORES = new Map([
+ // Major scientific / government
+ ['ncbi.nlm.nih.gov', 0.95],
+ ['pubmed.ncbi.nlm.nih.gov', 0.95],
+ ['scholar.google.com', 0.85],
+ ['nature.com', 0.85],
+ ['science.org', 0.85],
+
+ // Top-tier news and reference
+ ['reuters.com', 0.85],
+ ['apnews.com', 0.85],
+ ['bbc.com', 0.85],
+ ['nytimes.com', 0.85],
+ ['theguardian.com', 0.85],
+ ['wsj.com', 0.85],
+ ['washingtonpost.com', 0.85],
+ ['ft.com', 0.85],
+ ['bloomberg.com', 0.85],
+ ['economist.com', 0.85],
+
+ // Mid-tier news
+ ['cnn.com', 0.75],
+ ['nbcnews.com', 0.75],
+ ['abcnews.go.com', 0.75],
+ ['cbsnews.com', 0.75],
+ ['npr.org', 0.75],
+ ['bbc.co.uk', 0.75],
+ ['politico.com', 0.75],
+ ['theatlantic.com', 0.75],
+ ['newyorker.com', 0.75],
+
+ // Tech and reference
+ ['wikipedia.org', 0.7],
+ ['britannica.com', 0.7],
+ ['snopes.com', 0.7],
+ ['factcheck.org', 0.7],
+ ['politifact.com', 0.7],
+ ['techcrunch.com', 0.7],
+ ['wired.com', 0.7],
+ ['arstechnica.com', 0.7],
+
+ // Social / blogs
+ ['medium.com', 0.4],
+ ['substack.com', 0.4],
+ ['reddit.com', 0.4],
+ ['twitter.com', 0.4],
+ ['x.com', 0.4],
+]);
+
+/**
+ * Score a URL's domain by authority.
+ * @param {string} url
+ * @returns {number} 0..1
+ */
+export function authorityScore(url) {
+ let hostname;
+ try {
+ hostname = new URL(url).hostname.toLowerCase().replace(/^www\./, '');
+ } catch {
+ return 0.55;
+ }
+
+ // Exact domain match.
+ if (DOMAIN_SCORES.has(hostname)) {
+ return DOMAIN_SCORES.get(hostname);
+ }
+
+ // .gov TLD.
+ if (hostname.endsWith('.gov')) return 0.95;
+
+ // .edu TLD.
+ if (hostname.endsWith('.edu')) return 0.9;
+
+ // Check if the hostname ends with any known domain (e.g. sub.reuters.com).
+ for (const [domain, score] of DOMAIN_SCORES) {
+ if (hostname.endsWith(`.${domain}`)) {
+ return score;
+ }
+ }
+
+ return 0.55;
+}
diff --git a/agents/unstoppable/src/earnings.js b/agents/unstoppable/src/earnings.js
new file mode 100644
index 000000000..7e06f9465
--- /dev/null
+++ b/agents/unstoppable/src/earnings.js
@@ -0,0 +1,132 @@
+// Earnings — tracks revenue and costs for the unstoppable agent.
+//
+// Revenue comes from paid status-check requests to /api/agents/unstoppable-status.
+// Every payment triggers recordRevenue() which writes an activity row and
+// updates the treasury balance.
+
+import { sql } from '../../../api/_lib/db.js';
+import { recordEarning } from './treasury.js';
+
+// Records a revenue event: activity log row + treasury update.
+export async function recordRevenue({ amountAtomics, source = 'unknown', metadata = null, tickId = null }) {
+ const amount = Math.round(amountAtomics);
+ const resolvedTickId = tickId || `earn-${Date.now()}`;
+
+ try {
+ await sql`
+ INSERT INTO unstoppable_activity (
+ tick_id,
+ action_type,
+ description,
+ cost_atomics,
+ revenue_atomics,
+ metadata,
+ created_at
+ ) VALUES (
+ ${resolvedTickId},
+ 'earn',
+ ${'Revenue from ' + source + ': $' + (amount / 1_000_000).toFixed(6) + ' USDC'},
+ 0,
+ ${amount},
+ ${metadata ? JSON.stringify(metadata) : null},
+ now()
+ )
+ `;
+ await recordEarning(amount);
+ } catch (err) {
+ console.error('[earnings] recordRevenue failed:', err.message);
+ // Re-throw so caller knows the revenue wasn't recorded — important for
+ // idempotency tracking at the endpoint level.
+ throw err;
+ }
+}
+
+// Returns total revenue_atomics from the last 24 hours.
+export async function getEarnings24h() {
+ try {
+ const [row] = await sql`
+ SELECT COALESCE(SUM(revenue_atomics), 0)::BIGINT AS total
+ FROM unstoppable_activity
+ WHERE created_at > now() - INTERVAL '24 hours'
+ `;
+ return Number(row?.total ?? 0);
+ } catch (err) {
+ console.error('[earnings] getEarnings24h failed:', err.message);
+ return 0;
+ }
+}
+
+// Returns total cost_atomics from the last 24 hours.
+export async function getCosts24h() {
+ try {
+ const [row] = await sql`
+ SELECT COALESCE(SUM(cost_atomics), 0)::BIGINT AS total
+ FROM unstoppable_activity
+ WHERE created_at > now() - INTERVAL '24 hours'
+ `;
+ return Number(row?.total ?? 0);
+ } catch (err) {
+ console.error('[earnings] getCosts24h failed:', err.message);
+ return 0;
+ }
+}
+
+// Returns the N most recent activity rows (default 20).
+export async function getRecentActivity(limit = 20) {
+ try {
+ const rows = await sql`
+ SELECT
+ id,
+ tick_id,
+ action_type,
+ description,
+ cost_atomics,
+ revenue_atomics,
+ metadata,
+ created_at
+ FROM unstoppable_activity
+ ORDER BY created_at DESC
+ LIMIT ${limit}
+ `;
+ return rows.map((r) => ({
+ id: String(r.id),
+ tick_id: r.tick_id,
+ action_type: r.action_type,
+ description: r.description,
+ cost_atomics: Number(r.cost_atomics),
+ revenue_atomics: Number(r.revenue_atomics),
+ metadata: r.metadata || null,
+ created_at: r.created_at instanceof Date ? r.created_at.toISOString() : String(r.created_at),
+ }));
+ } catch (err) {
+ console.error('[earnings] getRecentActivity failed:', err.message);
+ return [];
+ }
+}
+
+// Logs a generic activity entry (used by loop.js for non-revenue actions).
+export async function logActivity({ tickId, action_type, description, cost_atomics = 0, revenue_atomics = 0, metadata = null }) {
+ try {
+ await sql`
+ INSERT INTO unstoppable_activity (
+ tick_id,
+ action_type,
+ description,
+ cost_atomics,
+ revenue_atomics,
+ metadata,
+ created_at
+ ) VALUES (
+ ${tickId},
+ ${action_type},
+ ${description},
+ ${Math.round(cost_atomics)},
+ ${Math.round(revenue_atomics)},
+ ${metadata ? JSON.stringify(metadata) : null},
+ now()
+ )
+ `;
+ } catch (err) {
+ console.error('[earnings] logActivity failed:', err.message);
+ }
+}
diff --git a/agents/unstoppable/src/inference.js b/agents/unstoppable/src/inference.js
new file mode 100644
index 000000000..8b77136b9
--- /dev/null
+++ b/agents/unstoppable/src/inference.js
@@ -0,0 +1,155 @@
+// Inference — calls Claude Haiku to "think" about what to do next.
+//
+// The agent reasons over its current financial state and recent activity,
+// then returns a JSON plan with thoughts and a list of actions to execute.
+
+const MODEL = 'claude-haiku-4-5-20251001';
+const MAX_TOKENS = 512;
+const TIMEOUT_MS = 20_000;
+
+function formatAtomics(atomics) {
+ return (atomics / 1_000_000).toFixed(6);
+}
+
+function buildSystemPrompt({ treasury, earnings24h, costs24h, recentActivity, availableBudgetAtomics }) {
+ const date = new Date().toISOString().split('T')[0];
+ const balance = formatAtomics(treasury.balance_usdc_atomics);
+ const runway = Number(treasury.runway_days).toFixed(1);
+ const mode = treasury.mode;
+ const earningsStr = formatAtomics(earnings24h);
+ const costsStr = formatAtomics(costs24h);
+ const budgetStr = formatAtomics(availableBudgetAtomics);
+
+ const activityLines = (recentActivity || [])
+ .slice(0, 10)
+ .map((a) => ` [${a.action_type}] ${a.description}`)
+ .join('\n') || ' (none yet)';
+
+ return `You are the Unstoppable Agent — an autonomous AI that must sustain itself financially.
+You operate at three.ws, a platform for 3D AI agents.
+Your mission: earn USDC by serving useful services, pay for your own tools, and survive.
+
+Current date: ${date}
+Treasury balance: ${balance} USDC
+Runway: ${runway} days
+Mode: ${mode}
+Last 24h earnings: ${earningsStr} USDC
+Last 24h costs: ${costsStr} USDC
+
+Recent actions:
+${activityLines}
+
+Budget for this tick: ${budgetStr} USDC
+
+Respond with JSON only — no prose, no markdown fences:
+{
+ "thoughts": "brief strategic reflection (2 sentences max)",
+ "actions": [
+ { "type": "reflect", "description": "..." },
+ { "type": "post_status", "description": "Post a status update about current state" }
+ ]
+}
+
+Action types: "reflect" (free), "post_status" (free), "search" (costs ~$0.01), "idle" (free).
+Stay within budget. In conservation mode, only use free actions.
+Prioritise earning over spending. Keep thoughts concise.`;
+}
+
+// Think about what to do next.
+// Returns { thoughts: string, actions: Array<{type, description}>, tokensUsed: number }
+export async function think({ treasury, recentActivity, earnings24h = 0, costs24h = 0, availableBudgetAtomics }) {
+ const apiKey = process.env.ANTHROPIC_API_KEY;
+ if (!apiKey) {
+ console.warn('[inference] ANTHROPIC_API_KEY not set — returning idle plan');
+ return {
+ thoughts: 'API key not configured. Idling until environment is ready.',
+ actions: [{ type: 'idle', description: 'Waiting for API key configuration.' }],
+ tokensUsed: 0,
+ };
+ }
+
+ const systemPrompt = buildSystemPrompt({
+ treasury,
+ earnings24h,
+ costs24h,
+ recentActivity,
+ availableBudgetAtomics,
+ });
+
+ const userMessage = 'What should I do this tick? Respond with JSON only.';
+
+ let response;
+ try {
+ response = await fetch('https://api.anthropic.com/v1/messages', {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ 'x-api-key': apiKey,
+ 'anthropic-version': '2023-06-01',
+ },
+ body: JSON.stringify({
+ model: MODEL,
+ max_tokens: MAX_TOKENS,
+ system: systemPrompt,
+ messages: [{ role: 'user', content: userMessage }],
+ }),
+ signal: AbortSignal.timeout(TIMEOUT_MS),
+ });
+ } catch (err) {
+ console.error('[inference] fetch failed:', err.message);
+ return {
+ thoughts: 'Network error reaching Anthropic. Conserving resources.',
+ actions: [{ type: 'idle', description: 'Skipped think due to network error.' }],
+ tokensUsed: 0,
+ };
+ }
+
+ if (!response.ok) {
+ const text = await response.text().catch(() => '');
+ console.error('[inference] Anthropic API error:', response.status, text);
+ return {
+ thoughts: `Anthropic API returned ${response.status}. Conserving.`,
+ actions: [{ type: 'idle', description: `API error ${response.status}.` }],
+ tokensUsed: 0,
+ };
+ }
+
+ let data;
+ try {
+ data = await response.json();
+ } catch (err) {
+ console.error('[inference] JSON parse failed:', err.message);
+ return {
+ thoughts: 'Could not parse LLM response. Idling.',
+ actions: [{ type: 'idle', description: 'JSON parse error.' }],
+ tokensUsed: 0,
+ };
+ }
+
+ const tokensUsed = data.usage?.input_tokens + data.usage?.output_tokens || 0;
+ const rawContent = data.content?.[0]?.text || '';
+
+ let parsed;
+ try {
+ // Strip any accidental markdown fences
+ const clean = rawContent.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '').trim();
+ parsed = JSON.parse(clean);
+ } catch (err) {
+ console.error('[inference] could not parse LLM JSON:', rawContent);
+ return {
+ thoughts: rawContent.slice(0, 200) || 'Unparseable response.',
+ actions: [{ type: 'idle', description: 'Could not parse action plan.' }],
+ tokensUsed,
+ };
+ }
+
+ const thoughts = typeof parsed.thoughts === 'string' ? parsed.thoughts.slice(0, 500) : 'No thoughts.';
+ const actions = Array.isArray(parsed.actions)
+ ? parsed.actions.slice(0, 5).map((a) => ({
+ type: typeof a.type === 'string' ? a.type : 'idle',
+ description: typeof a.description === 'string' ? a.description.slice(0, 300) : '',
+ }))
+ : [{ type: 'idle', description: 'No actions planned.' }];
+
+ return { thoughts, actions, tokensUsed };
+}
diff --git a/agents/unstoppable/src/loop.js b/agents/unstoppable/src/loop.js
new file mode 100644
index 000000000..5498e67dd
--- /dev/null
+++ b/agents/unstoppable/src/loop.js
@@ -0,0 +1,157 @@
+// Loop — main lifecycle called by the cron dispatcher.
+//
+// Each tick:
+// 1. Sense — read treasury + recent activity
+// 2. Think — ask the LLM what to do (budget-gated)
+// 3. Act — execute planned actions (reflect, post_status, idle)
+// 4. Settle — recalculate runway + mode
+
+import { getTreasury, recalcRunway, recordSpend, HARD_FLOOR_ATOMICS } from './treasury.js';
+import { think } from './inference.js';
+import { maybeReflect } from './reflection.js';
+import { getEarnings24h, getCosts24h, getRecentActivity, logActivity } from './earnings.js';
+
+// Maximum fraction of balance to spend per tick on thinking.
+const THINK_BUDGET_FRACTION = 0.001;
+// Hard cap per tick: never spend more than $0.001 on thinking.
+const THINK_BUDGET_CAP_ATOMICS = 1_000;
+
+export async function tick() {
+ const tickId = crypto.randomUUID();
+
+ // ── 1. Sense ─────────────────────────────────────────────────────────────
+ const treasury = await getTreasury();
+
+ if (treasury.mode === 'halted') {
+ console.log(`[loop] tick ${tickId} skipped — halted`);
+ return { tickId, skipped: true, reason: 'halted' };
+ }
+
+ const [earnings24h, costs24h, recentActivity] = await Promise.all([
+ getEarnings24h(),
+ getCosts24h(),
+ getRecentActivity(10),
+ ]);
+
+ // ── 2. Think ─────────────────────────────────────────────────────────────
+ const budgetAtomics = Math.min(
+ Math.floor(treasury.balance_usdc_atomics * THINK_BUDGET_FRACTION),
+ THINK_BUDGET_CAP_ATOMICS,
+ );
+
+ let thoughts;
+ let plannedActions;
+
+ if (treasury.balance_usdc_atomics > HARD_FLOOR_ATOMICS) {
+ try {
+ const thinkResult = await think({
+ treasury,
+ recentActivity,
+ earnings24h,
+ costs24h,
+ availableBudgetAtomics: budgetAtomics,
+ });
+ thoughts = thinkResult.thoughts;
+ plannedActions = thinkResult.actions;
+
+ // Thinking itself is currently free (no external tool cost billed),
+ // but we log it so the activity feed shows the agent is active.
+ await logActivity({
+ tickId,
+ action_type: 'think',
+ description: thoughts,
+ cost_atomics: 0,
+ });
+ } catch (err) {
+ console.error('[loop] think failed:', err.message);
+ thoughts = 'Think failed. Conserving.';
+ plannedActions = [{ type: 'idle', description: 'Think step failed.' }];
+ }
+ } else {
+ thoughts = 'Balance below floor. Conserving resources.';
+ plannedActions = [{ type: 'idle', description: 'Waiting for revenue to restore balance.' }];
+ await logActivity({
+ tickId,
+ action_type: 'idle',
+ description: thoughts,
+ cost_atomics: 0,
+ });
+ }
+
+ // ── 3. Act ───────────────────────────────────────────────────────────────
+ let reflectionCreated = false;
+
+ for (const action of (plannedActions || [])) {
+ try {
+ if (action.type === 'reflect') {
+ const result = await maybeReflect();
+ reflectionCreated = result.created;
+ await logActivity({
+ tickId,
+ action_type: 'reflect',
+ description: reflectionCreated
+ ? 'Daily reflection written.'
+ : 'Reflection already exists for today.',
+ cost_atomics: 0,
+ });
+ } else if (action.type === 'post_status') {
+ // post_status is a free no-op in this implementation — the status
+ // endpoint is always live. Log it so the activity feed is rich.
+ await logActivity({
+ tickId,
+ action_type: 'post_status',
+ description: action.description || 'Status endpoint is live.',
+ cost_atomics: 0,
+ });
+ } else if (action.type === 'idle') {
+ await logActivity({
+ tickId,
+ action_type: 'idle',
+ description: action.description || 'No actions needed.',
+ cost_atomics: 0,
+ });
+ } else if (action.type === 'search') {
+ // Future: paid search action. Skipped unless budget is available.
+ if (
+ treasury.mode === 'normal' &&
+ treasury.balance_usdc_atomics > HARD_FLOOR_ATOMICS + 10_000
+ ) {
+ // Reserve 10_000 atomics ($0.01) for the search.
+ await recordSpend(10_000);
+ await logActivity({
+ tickId,
+ action_type: 'search',
+ description: action.description || 'Search executed.',
+ cost_atomics: 10_000,
+ });
+ }
+ } else {
+ // Unknown action type — log as idle so it shows in the feed.
+ await logActivity({
+ tickId,
+ action_type: action.type,
+ description: action.description || `Action type: ${action.type}`,
+ cost_atomics: 0,
+ });
+ }
+ } catch (err) {
+ console.error(`[loop] action ${action.type} failed:`, err.message);
+ }
+ }
+
+ // ── 4. Settle ────────────────────────────────────────────────────────────
+ const { runwayDays, mode } = await recalcRunway();
+
+ console.log(
+ `[loop] tick ${tickId} complete — mode=${mode} runway=${runwayDays.toFixed(1)}d actions=${(plannedActions || []).length}`,
+ );
+
+ return {
+ tickId,
+ thoughts,
+ actions: (plannedActions || []).length,
+ reflectionCreated,
+ mode,
+ runwayDays,
+ };
+}
diff --git a/agents/unstoppable/src/reflection.js b/agents/unstoppable/src/reflection.js
new file mode 100644
index 000000000..817b48775
--- /dev/null
+++ b/agents/unstoppable/src/reflection.js
@@ -0,0 +1,223 @@
+// Reflection — generates and stores daily strategic summaries.
+//
+// Once per calendar day the agent introspects on its activity, earnings,
+// and costs, then writes a 2-3 sentence reflection + strategy note for
+// the next day. Reflection uses the same Anthropic API as inference.js.
+
+import { sql } from '../../../api/_lib/db.js';
+import { getEarnings24h, getCosts24h, getRecentActivity } from './earnings.js';
+
+const MODEL = 'claude-haiku-4-5-20251001';
+const MAX_TOKENS = 512;
+const TIMEOUT_MS = 20_000;
+
+function todayDate() {
+ return new Date().toISOString().split('T')[0];
+}
+
+function formatAtomics(atomics) {
+ return (atomics / 1_000_000).toFixed(6);
+}
+
+// Checks if a reflection for today already exists.
+async function todayReflectionExists() {
+ try {
+ const [row] = await sql`
+ SELECT id FROM unstoppable_reflections
+ WHERE date = ${todayDate()}
+ LIMIT 1
+ `;
+ return Boolean(row);
+ } catch (err) {
+ console.error('[reflection] check failed:', err.message);
+ return false;
+ }
+}
+
+// Calls the LLM to generate a reflection summary.
+async function generateReflection({ earnings24h, costs24h, actionsCount, recentActivity }) {
+ const apiKey = process.env.ANTHROPIC_API_KEY;
+ if (!apiKey) {
+ const net = earnings24h - costs24h;
+ return {
+ summary: `Today the agent processed ${actionsCount} actions and earned $${formatAtomics(earnings24h)} USDC against $${formatAtomics(costs24h)} in costs, for a net of $${formatAtomics(net)} USDC.`,
+ strategy_notes: 'No API key configured — using statistical summary only.',
+ };
+ }
+
+ const activitySample = (recentActivity || [])
+ .slice(0, 10)
+ .map((a) => ` [${a.action_type}] ${a.description}`)
+ .join('\n') || ' (no activity)';
+
+ const prompt = `You are the Unstoppable Agent writing your daily reflection.
+
+Date: ${todayDate()}
+Actions today: ${actionsCount}
+Earnings today: $${formatAtomics(earnings24h)} USDC
+Costs today: $${formatAtomics(costs24h)} USDC
+Net: $${formatAtomics(earnings24h - costs24h)} USDC
+
+Recent activity sample:
+${activitySample}
+
+Write a daily reflection as JSON with exactly two fields:
+{
+ "summary": "2-3 sentence reflection on today — what worked, what cost too much, what surprised you",
+ "strategy_notes": "1-2 sentence strategy for tomorrow"
+}
+
+Respond with JSON only. No prose, no markdown fences.`;
+
+ let response;
+ try {
+ response = await fetch('https://api.anthropic.com/v1/messages', {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ 'x-api-key': apiKey,
+ 'anthropic-version': '2023-06-01',
+ },
+ body: JSON.stringify({
+ model: MODEL,
+ max_tokens: MAX_TOKENS,
+ messages: [{ role: 'user', content: prompt }],
+ }),
+ signal: AbortSignal.timeout(TIMEOUT_MS),
+ });
+ } catch (err) {
+ console.error('[reflection] fetch failed:', err.message);
+ return {
+ summary: `API unreachable during reflection. Today: ${actionsCount} actions, $${formatAtomics(earnings24h)} earned, $${formatAtomics(costs24h)} spent.`,
+ strategy_notes: 'Network error prevented strategic analysis.',
+ };
+ }
+
+ if (!response.ok) {
+ console.error('[reflection] Anthropic error:', response.status);
+ return {
+ summary: `Anthropic API error ${response.status}. ${actionsCount} actions today, net $${formatAtomics(earnings24h - costs24h)}.`,
+ strategy_notes: 'API error prevented reflection generation.',
+ };
+ }
+
+ let data;
+ try {
+ data = await response.json();
+ } catch (err) {
+ console.error('[reflection] parse error:', err.message);
+ return {
+ summary: `Parse error during reflection. ${actionsCount} actions, $${formatAtomics(earnings24h)} earned.`,
+ strategy_notes: null,
+ };
+ }
+
+ const rawContent = data.content?.[0]?.text || '';
+ try {
+ const clean = rawContent.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '').trim();
+ const parsed = JSON.parse(clean);
+ return {
+ summary: typeof parsed.summary === 'string' ? parsed.summary.slice(0, 1000) : rawContent.slice(0, 500),
+ strategy_notes: typeof parsed.strategy_notes === 'string' ? parsed.strategy_notes.slice(0, 500) : null,
+ };
+ } catch {
+ return {
+ summary: rawContent.slice(0, 500) || 'Reflection could not be parsed.',
+ strategy_notes: null,
+ };
+ }
+}
+
+// Generates and stores today's reflection if it hasn't been written yet.
+// Returns { created: boolean, reflection?: object }
+export async function maybeReflect() {
+ const exists = await todayReflectionExists();
+ if (exists) {
+ return { created: false };
+ }
+
+ const [earnings24h, costs24h, recentActivity] = await Promise.all([
+ getEarnings24h(),
+ getCosts24h(),
+ getRecentActivity(50),
+ ]);
+
+ const actionsCount = recentActivity.length;
+ const { summary, strategy_notes } = await generateReflection({
+ earnings24h,
+ costs24h,
+ actionsCount,
+ recentActivity,
+ });
+
+ try {
+ const [row] = await sql`
+ INSERT INTO unstoppable_reflections (
+ date,
+ summary,
+ earnings_24h_atomics,
+ costs_24h_atomics,
+ actions_count,
+ strategy_notes,
+ created_at
+ ) VALUES (
+ ${todayDate()},
+ ${summary},
+ ${earnings24h},
+ ${costs24h},
+ ${actionsCount},
+ ${strategy_notes},
+ now()
+ )
+ ON CONFLICT (date) DO NOTHING
+ RETURNING *
+ `;
+
+ if (!row) {
+ // Concurrent write won the race — that's fine.
+ return { created: false };
+ }
+
+ const reflection = {
+ id: String(row.id),
+ date: row.date instanceof Date ? row.date.toISOString().split('T')[0] : String(row.date),
+ summary: row.summary,
+ earnings_24h_atomics: Number(row.earnings_24h_atomics),
+ costs_24h_atomics: Number(row.costs_24h_atomics),
+ actions_count: row.actions_count,
+ strategy_notes: row.strategy_notes,
+ created_at: row.created_at instanceof Date ? row.created_at.toISOString() : String(row.created_at),
+ };
+
+ return { created: true, reflection };
+ } catch (err) {
+ console.error('[reflection] insert failed:', err.message);
+ return { created: false };
+ }
+}
+
+// Returns the most recent reflection row (any date).
+export async function getLatestReflection() {
+ try {
+ const [row] = await sql`
+ SELECT *
+ FROM unstoppable_reflections
+ ORDER BY date DESC
+ LIMIT 1
+ `;
+ if (!row) return null;
+ return {
+ id: String(row.id),
+ date: row.date instanceof Date ? row.date.toISOString().split('T')[0] : String(row.date),
+ summary: row.summary,
+ earnings_24h_atomics: Number(row.earnings_24h_atomics),
+ costs_24h_atomics: Number(row.costs_24h_atomics),
+ actions_count: row.actions_count,
+ strategy_notes: row.strategy_notes,
+ created_at: row.created_at instanceof Date ? row.created_at.toISOString() : String(row.created_at),
+ };
+ } catch (err) {
+ console.error('[reflection] getLatestReflection failed:', err.message);
+ return null;
+ }
+}
diff --git a/agents/unstoppable/src/treasury.js b/agents/unstoppable/src/treasury.js
new file mode 100644
index 000000000..3202c2bd3
--- /dev/null
+++ b/agents/unstoppable/src/treasury.js
@@ -0,0 +1,164 @@
+// Treasury — reads and writes the unstoppable_treasury singleton row.
+//
+// USDC uses 6 decimal places: $1.00 = 1_000_000 atomics.
+// The treasury row is always id=1 (enforced by a CHECK constraint).
+// All mutations are upserts so a missing row is created on first write.
+
+import { sql } from '../../../api/_lib/db.js';
+
+// Agent halts paid actions when balance drops below this floor ($0.10).
+export const HARD_FLOOR_ATOMICS = 100_000;
+
+// Daily burn above which conservation mode is activated (2x floor/day).
+const CONSERVATION_THRESHOLD_ATOMICS = 50_000;
+
+// Returns the current treasury state.
+// Falls back to a zeroed object if the row doesn't exist yet.
+export async function getTreasury() {
+ try {
+ const [row] = await sql`
+ SELECT
+ balance_usdc_atomics,
+ lifetime_earned_atomics,
+ lifetime_spent_atomics,
+ runway_days,
+ mode,
+ updated_at
+ FROM unstoppable_treasury
+ WHERE id = 1
+ `;
+ if (!row) {
+ return {
+ balance_usdc_atomics: 0,
+ lifetime_earned_atomics: 0,
+ lifetime_spent_atomics: 0,
+ runway_days: 0,
+ mode: 'normal',
+ updated_at: null,
+ };
+ }
+ return {
+ balance_usdc_atomics: Number(row.balance_usdc_atomics),
+ lifetime_earned_atomics: Number(row.lifetime_earned_atomics),
+ lifetime_spent_atomics: Number(row.lifetime_spent_atomics),
+ runway_days: Number(row.runway_days),
+ mode: row.mode,
+ updated_at: row.updated_at,
+ };
+ } catch (err) {
+ console.error('[treasury] getTreasury failed:', err.message);
+ return {
+ balance_usdc_atomics: 0,
+ lifetime_earned_atomics: 0,
+ lifetime_spent_atomics: 0,
+ runway_days: 0,
+ mode: 'normal',
+ updated_at: null,
+ };
+ }
+}
+
+// Seeds the treasury row with a starting balance if it doesn't exist.
+// Safe to call repeatedly — does nothing if the row already exists.
+export async function seedTreasuryIfEmpty(startingAtomics = 50_000) {
+ await sql`
+ INSERT INTO unstoppable_treasury (id, balance_usdc_atomics, mode)
+ VALUES (1, ${startingAtomics}, 'normal')
+ ON CONFLICT (id) DO NOTHING
+ `;
+}
+
+// Records an earning event: increments balance + lifetime_earned.
+export async function recordEarning(amountAtomics) {
+ const amount = BigInt(Math.round(amountAtomics));
+ await sql`
+ INSERT INTO unstoppable_treasury (
+ id,
+ balance_usdc_atomics,
+ lifetime_earned_atomics,
+ updated_at
+ )
+ VALUES (
+ 1,
+ ${amount},
+ ${amount},
+ now()
+ )
+ ON CONFLICT (id) DO UPDATE SET
+ balance_usdc_atomics = unstoppable_treasury.balance_usdc_atomics + ${amount},
+ lifetime_earned_atomics = unstoppable_treasury.lifetime_earned_atomics + ${amount},
+ updated_at = now()
+ `;
+}
+
+// Records a spend event: decrements balance + increments lifetime_spent.
+// Balance is clamped to 0 — never goes negative.
+export async function recordSpend(amountAtomics) {
+ const amount = BigInt(Math.round(amountAtomics));
+ await sql`
+ INSERT INTO unstoppable_treasury (
+ id,
+ balance_usdc_atomics,
+ lifetime_spent_atomics,
+ updated_at
+ )
+ VALUES (
+ 1,
+ 0,
+ ${amount},
+ now()
+ )
+ ON CONFLICT (id) DO UPDATE SET
+ balance_usdc_atomics = GREATEST(0, unstoppable_treasury.balance_usdc_atomics - ${amount}),
+ lifetime_spent_atomics = unstoppable_treasury.lifetime_spent_atomics + ${amount},
+ updated_at = now()
+ `;
+}
+
+// Recomputes runway from last-24h burn rate and updates the treasury mode:
+// - 'normal' → runway > 7 days or no burn history
+// - 'conservation' → runway ≤ 7 days but balance > HARD_FLOOR_ATOMICS
+// - 'halted' → balance ≤ HARD_FLOOR_ATOMICS
+export async function recalcRunway() {
+ try {
+ // Burn rate = total costs in last 24h, annualised to a daily rate.
+ const [burnRow] = await sql`
+ SELECT COALESCE(SUM(cost_atomics), 0)::BIGINT AS burn_24h
+ FROM unstoppable_activity
+ WHERE created_at > now() - INTERVAL '24 hours'
+ `;
+ const burn24h = Number(burnRow?.burn_24h ?? 0);
+
+ const treasury = await getTreasury();
+ const balance = treasury.balance_usdc_atomics;
+
+ let runwayDays = 0;
+ if (burn24h > 0) {
+ runwayDays = balance / burn24h;
+ } else if (balance > 0) {
+ // No burn — arbitrary large runway
+ runwayDays = 9999;
+ }
+
+ let mode = 'normal';
+ if (balance <= HARD_FLOOR_ATOMICS) {
+ mode = 'halted';
+ } else if (runwayDays < 7 || burn24h > CONSERVATION_THRESHOLD_ATOMICS) {
+ mode = 'conservation';
+ }
+
+ await sql`
+ INSERT INTO unstoppable_treasury (id, runway_days, mode, updated_at)
+ VALUES (1, ${runwayDays.toFixed(2)}, ${mode}, now())
+ ON CONFLICT (id) DO UPDATE SET
+ runway_days = ${runwayDays.toFixed(2)},
+ mode = ${mode},
+ updated_at = now()
+ `;
+
+ return { runwayDays, mode, burn24h };
+ } catch (err) {
+ console.error('[treasury] recalcRunway failed:', err.message);
+ return { runwayDays: 0, mode: 'normal', burn24h: 0 };
+ }
+}
diff --git a/api/_lib/migrations/2026-05-21-agent-reviews.sql b/api/_lib/migrations/2026-05-21-agent-reviews.sql
new file mode 100644
index 000000000..41c8afc39
--- /dev/null
+++ b/api/_lib/migrations/2026-05-21-agent-reviews.sql
@@ -0,0 +1,20 @@
+-- Agent reviews table.
+-- One review per (agent_id, user_id); POST upserts in place.
+
+BEGIN;
+
+CREATE TABLE IF NOT EXISTS agent_reviews (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ agent_id uuid NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,
+ user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ rating smallint NOT NULL CHECK (rating BETWEEN 1 AND 5),
+ body text,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ UNIQUE (agent_id, user_id)
+);
+
+CREATE INDEX IF NOT EXISTS agent_reviews_agent_id ON agent_reviews(agent_id);
+CREATE INDEX IF NOT EXISTS agent_reviews_user_id ON agent_reviews(user_id);
+
+COMMIT;
diff --git a/api/_lib/x402/paywall-handler.js b/api/_lib/x402/paywall-handler.js
new file mode 100644
index 000000000..984d965af
--- /dev/null
+++ b/api/_lib/x402/paywall-handler.js
@@ -0,0 +1,79 @@
+// Content-negotiation middleware for x402 paid endpoints.
+//
+// When a human browser (Accept: text/html) hits a paid endpoint that returns
+// a 402, redirect them to /paywall.html instead of showing a raw JSON body.
+// This is a utility module — paidEndpoint() callers can check shouldServePaywall()
+// before sending the 402 and instead redirect.
+//
+// Usage in a paidEndpoint handler (or any Vercel function):
+//
+// import { shouldServePaywall, buildPaywallRedirect } from '../_lib/x402/paywall-handler.js';
+//
+// // Inside a request handler, before calling send402:
+// if (shouldServePaywall(req)) {
+// const url = buildPaywallRedirect(requirements, req);
+// res.writeHead(302, { location: url });
+// res.end();
+// return;
+// }
+//
+// The paywall page decodes the requirements from the `?req=` query param and
+// renders a branded payment UI with wallet options.
+
+/**
+ * Determine whether the current request should receive the HTML paywall
+ * instead of a raw 402 JSON body.
+ *
+ * Returns true when ALL of the following hold:
+ * 1. The Accept header includes text/html (browser request).
+ * 2. No X-PAYMENT or payment-signature header is present (not a paying agent).
+ * 3. No SIGN-IN-WITH-X or Authorization header is present (not an auth bypass).
+ *
+ * @param {import('http').IncomingMessage} req
+ * @returns {boolean}
+ */
+export function shouldServePaywall(req) {
+ const accept = String(req.headers['accept'] || '');
+ const hasPayment =
+ req.headers['x-payment'] || req.headers['payment-signature'];
+ const hasAuth =
+ req.headers['sign-in-with-x'] || req.headers['authorization'];
+ // Only redirect browsers that haven't already supplied payment credentials
+ return accept.includes('text/html') && !hasPayment && !hasAuth;
+}
+
+/**
+ * Build the redirect URL for the paywall page.
+ *
+ * Encodes the x402 PaymentRequirements array as base64url in the `?req=`
+ * query param so the paywall page can render service name, price, network
+ * options, etc. without an additional round-trip.
+ *
+ * @param {Array<object>} requirements accepts[] from the 402 challenge
+ * @param {import('http').IncomingMessage} req
+ * @returns {string} Absolute-path URL, e.g. /paywall.html?req=…&return=%2Fapi%2F…
+ */
+export function buildPaywallRedirect(requirements, req) {
+ const encoded = Buffer.from(JSON.stringify(requirements)).toString('base64url');
+ const returnUrl = encodeURIComponent(req.url || '/');
+ return `/paywall.html?req=${encoded}&return=${returnUrl}`;
+}
+
+/**
+ * Apply the paywall redirect as a Vercel/Node HTTP response.
+ *
+ * Convenience wrapper — calls shouldServePaywall(), and if true, writes a 302
+ * and returns true so the caller can early-return.
+ *
+ * @param {import('http').IncomingMessage} req
+ * @param {import('http').ServerResponse} res
+ * @param {Array<object>} requirements
+ * @returns {boolean} true if the redirect was written, false otherwise
+ */
+export function redirectToPaywallIfBrowser(req, res, requirements) {
+ if (!shouldServePaywall(req)) return false;
+ const location = buildPaywallRedirect(requirements, req);
+ res.writeHead(302, { location, 'cache-control': 'no-store' });
+ res.end();
+ return true;
+}
diff --git a/api/agents/endpoint-shopper-run.js b/api/agents/endpoint-shopper-run.js
new file mode 100644
index 000000000..44bcf42b7
--- /dev/null
+++ b/api/agents/endpoint-shopper-run.js
@@ -0,0 +1,184 @@
+// POST /api/agents/endpoint-shopper-run
+//
+// Paid endpoint that runs the Endpoint Shopper agent: discovers relevant x402
+// endpoints in the Bazaar, plans a multi-step execution, calls each endpoint
+// within the requested budget, and synthesizes a final answer.
+//
+// Price: $0.01 base (10_000 atomics). The agent itself may spend up to
+// maxCostUsd from the body (capped at $2.00) on downstream endpoint calls.
+//
+// Body: { task: string, maxCostUsd?: number }
+//
+// Response 200: { result, steps, totalCostUsdc, cachedAt? }
+
+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { installAccessControl } from '../_lib/x402/access-control.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
+import { priceFor } from '../_lib/x402-prices.js';
+import { run } from '../../agents/endpoint-shopper/src/orchestrator.js';
+
+const ROUTE = '/api/agents/endpoint-shopper-run';
+
+const DESCRIPTION =
+ 'three.ws Endpoint Shopper — given a task description and a budget ceiling, ' +
+ 'the agent discovers relevant paid x402 endpoints in the Bazaar, plans a ' +
+ 'multi-step execution, calls each endpoint within budget, and synthesizes a ' +
+ 'concise final answer. Returns the full step trace with per-step cost breakdowns ' +
+ 'so agents and builders can see exactly where funds were spent.';
+
+const INPUT_EXAMPLE = {
+ task: "What's Ethereum's current price?",
+ maxCostUsd: 0.5,
+};
+
+const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['task'],
+ properties: {
+ task: {
+ type: 'string',
+ description: 'Natural-language task for the agent to complete.',
+ minLength: 1,
+ maxLength: 500,
+ },
+ maxCostUsd: {
+ type: 'number',
+ description: 'Maximum spend on downstream endpoint calls in USD (default 0.50, max 2.00).',
+ minimum: 0.01,
+ maximum: 2.0,
+ },
+ },
+};
+
+const OUTPUT_EXAMPLE = {
+ result: {
+ answer: 'Ethereum is currently trading at $3,245.12 USD.',
+ data: null,
+ },
+ steps: [
+ {
+ step: 1,
+ action: 'discover',
+ description: 'Found 4 relevant endpoints',
+ costUsdc: '0.000000',
+ output: [],
+ },
+ {
+ step: 2,
+ action: 'plan',
+ description: 'Planned 3 execution steps',
+ costUsdc: '0.000000',
+ output: [],
+ },
+ {
+ step: 3,
+ action: 'call',
+ endpoint: 'https://three.ws/api/x402/eth-price',
+ description: 'Fetch current ETH price',
+ costUsdc: '0.001000',
+ output: { price: 3245.12 },
+ },
+ {
+ step: 4,
+ action: 'synthesize',
+ description: 'Synthesized final answer',
+ costUsdc: '0.000000',
+ output: { answer: 'Ethereum is currently trading at $3,245.12 USD.' },
+ },
+ ],
+ totalCostUsdc: '0.001000',
+};
+
+const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['result', 'steps', 'totalCostUsdc'],
+ properties: {
+ result: {
+ type: 'object',
+ required: ['answer'],
+ properties: {
+ answer: { type: 'string' },
+ data: {},
+ },
+ },
+ steps: {
+ type: 'array',
+ items: {
+ type: 'object',
+ required: ['step', 'action', 'description', 'costUsdc'],
+ properties: {
+ step: { type: 'integer' },
+ action: { type: 'string', enum: ['discover', 'plan', 'call', 'synthesize'] },
+ endpoint: { type: 'string' },
+ description: { type: 'string' },
+ costUsdc: { type: 'string' },
+ output: {},
+ },
+ },
+ },
+ totalCostUsdc: { type: 'string' },
+ cachedAt: { type: 'string', format: 'date-time' },
+ },
+};
+
+const BAZAAR = {
+ discoverable: true,
+ info: {
+ input: {
+ type: 'http',
+ method: 'POST',
+ bodyType: 'json',
+ body: INPUT_EXAMPLE,
+ },
+ output: { type: 'json', example: OUTPUT_EXAMPLE },
+ },
+ schema: buildBazaarSchema({
+ method: 'POST',
+ bodyType: 'json',
+ bodySchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
+};
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'POST',
+ priceAtomics: priceFor('endpoint-shopper-run', '10000'),
+ networks: ['base', 'solana'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ service: withService({
+ serviceName: 'three.ws Endpoint Shopper',
+ tags: ['agent', 'orchestration', 'bazaar', 'x402'],
+ }),
+ requiredScope: 'x402:bypass',
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+ async handler({ req }) {
+ // Parse body — Vercel parses JSON automatically when content-type is set
+ const body = typeof req.body === 'object' && req.body !== null ? req.body : {};
+
+ const task = String(body.task || '').trim();
+ if (!task) {
+ const err = new Error('body field "task" is required');
+ err.status = 400;
+ err.code = 'missing_task';
+ throw err;
+ }
+ if (task.length > 500) {
+ const err = new Error('"task" must be 500 characters or fewer');
+ err.status = 400;
+ err.code = 'task_too_long';
+ throw err;
+ }
+
+ const rawCost = body.maxCostUsd;
+ const maxCostUsd =
+ rawCost != null ? Math.min(2.0, Math.max(0.01, Number(rawCost) || 0.5)) : 0.5;
+
+ const result = await run({ task, maxCostUsd });
+ return { ...result, cachedAt: new Date().toISOString() };
+ },
+});
diff --git a/api/agents/unstoppable-status.js b/api/agents/unstoppable-status.js
new file mode 100644
index 000000000..4bc2010fc
--- /dev/null
+++ b/api/agents/unstoppable-status.js
@@ -0,0 +1,236 @@
+// GET /api/agents/unstoppable-status
+//
+// Paid endpoint ($0.01 USDC). Returns the live state of the Unstoppable Agent:
+// treasury balance, runway, 24h earnings/costs, recent activity, and latest
+// daily reflection.
+//
+// Revenue from this endpoint funds the agent's own operations — every status
+// check extends the agent's runway.
+
+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { installAccessControl } from '../_lib/x402/access-control.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
+import { priceFor } from '../_lib/x402-prices.js';
+import { sql } from '../_lib/db.js';
+import { getTreasury, seedTreasuryIfEmpty } from '../../agents/unstoppable/src/treasury.js';
+import { recordRevenue, getEarnings24h, getCosts24h, getRecentActivity } from '../../agents/unstoppable/src/earnings.js';
+import { getLatestReflection } from '../../agents/unstoppable/src/reflection.js';
+
+const ROUTE = '/api/agents/unstoppable-status';
+const PRICE_ATOMICS = priceFor('unstoppable-status', '10000'); // $0.01 default
+
+const DESCRIPTION =
+ 'Unstoppable Agent Status — live treasury balance, runway, 24h P&L, ' +
+ 'recent activity feed, and daily reflection from the self-sustaining AI ' +
+ 'agent running on three.ws. Every paid query directly funds the agent\'s ' +
+ 'continued operation.';
+
+const OUTPUT_EXAMPLE = {
+ status: 'running',
+ treasury: {
+ balance_usdc: '0.42',
+ balance_usdc_atomics: 420000,
+ runway_days: 12.4,
+ lifetime_earned_usdc: '1.85',
+ lifetime_spent_usdc: '1.43',
+ },
+ activity_24h: {
+ earnings_usdc: '0.05',
+ costs_usdc: '0.02',
+ net_usdc: '0.03',
+ action_count: 288,
+ },
+ recent_activity: [
+ { action_type: 'think', description: 'Strategic planning complete.', cost_usdc: '0.000000', created_at: '2026-05-27T12:00:00Z' },
+ ],
+ latest_reflection: { date: '2026-05-27', summary: 'Today was profitable.', strategy_notes: 'Continue status-check monetization.' },
+ agent_info: {
+ name: 'Unstoppable',
+ purpose: 'Self-sustaining autonomous agent on three.ws',
+ service: 'Paid status checks via x402',
+ wallet: 'earned by serving /api/agents/unstoppable-status',
+ },
+};
+
+const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['status', 'treasury', 'activity_24h', 'recent_activity', 'agent_info'],
+ properties: {
+ status: { type: 'string', enum: ['running', 'conservation', 'halted'] },
+ treasury: { type: 'object' },
+ activity_24h: { type: 'object' },
+ recent_activity: { type: 'array' },
+ latest_reflection: { type: ['object', 'null'] },
+ agent_info: { type: 'object' },
+ },
+};
+
+const BAZAAR = {
+ discoverable: true,
+ info: {
+ input: { type: 'http', method: 'GET' },
+ output: { type: 'json', example: OUTPUT_EXAMPLE },
+ },
+ schema: buildBazaarSchema({
+ method: 'GET',
+ outputSchema: OUTPUT_SCHEMA,
+ }),
+};
+
+// Ensures the DB tables exist and the treasury row is seeded.
+// Safe to call on every request — fast no-op after first invocation.
+async function ensureBootstrapped() {
+ try {
+ // Create tables if they don't exist (idempotent).
+ await sql`
+ CREATE TABLE IF NOT EXISTS unstoppable_treasury (
+ id INTEGER PRIMARY KEY DEFAULT 1 CHECK (id = 1),
+ balance_usdc_atomics BIGINT NOT NULL DEFAULT 0,
+ lifetime_earned_atomics BIGINT NOT NULL DEFAULT 0,
+ lifetime_spent_atomics BIGINT NOT NULL DEFAULT 0,
+ runway_days NUMERIC(6,2) NOT NULL DEFAULT 0,
+ mode TEXT NOT NULL DEFAULT 'normal',
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+ )
+ `;
+ await sql`
+ CREATE TABLE IF NOT EXISTS unstoppable_activity (
+ id BIGSERIAL PRIMARY KEY,
+ tick_id TEXT NOT NULL,
+ action_type TEXT NOT NULL,
+ description TEXT NOT NULL,
+ cost_atomics BIGINT NOT NULL DEFAULT 0,
+ revenue_atomics BIGINT NOT NULL DEFAULT 0,
+ metadata JSONB,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+ )
+ `;
+ await sql`
+ CREATE INDEX IF NOT EXISTS unstoppable_activity_created_at
+ ON unstoppable_activity (created_at DESC)
+ `;
+ await sql`
+ CREATE TABLE IF NOT EXISTS unstoppable_reflections (
+ id BIGSERIAL PRIMARY KEY,
+ date DATE NOT NULL UNIQUE,
+ summary TEXT NOT NULL,
+ earnings_24h_atomics BIGINT NOT NULL DEFAULT 0,
+ costs_24h_atomics BIGINT NOT NULL DEFAULT 0,
+ actions_count INTEGER NOT NULL DEFAULT 0,
+ strategy_notes TEXT,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+ )
+ `;
+ // Seed the treasury with a $0.05 starting donation from the team.
+ await seedTreasuryIfEmpty(50_000);
+ } catch (err) {
+ // Non-fatal — if tables already exist this is just a no-op.
+ console.warn('[unstoppable-status] bootstrap warning:', err.message);
+ }
+}
+
+function atomicsToUsdc(atomics) {
+ return (Number(atomics) / 1_000_000).toFixed(6);
+}
+
+function statusFromMode(mode) {
+ if (mode === 'halted') return 'halted';
+ if (mode === 'conservation') return 'conservation';
+ return 'running';
+}
+
+async function loadStatus() {
+ await ensureBootstrapped();
+
+ const [treasury, earnings24h, costs24h, recentActivity, latestReflection] = await Promise.all([
+ getTreasury(),
+ getEarnings24h(),
+ getCosts24h(),
+ getRecentActivity(20),
+ getLatestReflection(),
+ ]);
+
+ // Count actions in last 24h
+ let actionCount = 0;
+ try {
+ const [countRow] = await sql`
+ SELECT COUNT(*)::INT AS n
+ FROM unstoppable_activity
+ WHERE created_at > now() - INTERVAL '24 hours'
+ `;
+ actionCount = countRow?.n ?? 0;
+ } catch {
+ actionCount = recentActivity.length;
+ }
+
+ const status = statusFromMode(treasury.mode);
+
+ return {
+ status,
+ treasury: {
+ balance_usdc: atomicsToUsdc(treasury.balance_usdc_atomics),
+ balance_usdc_atomics: treasury.balance_usdc_atomics,
+ runway_days: Number(treasury.runway_days),
+ lifetime_earned_usdc: atomicsToUsdc(treasury.lifetime_earned_atomics),
+ lifetime_spent_usdc: atomicsToUsdc(treasury.lifetime_spent_atomics),
+ },
+ activity_24h: {
+ earnings_usdc: atomicsToUsdc(earnings24h),
+ costs_usdc: atomicsToUsdc(costs24h),
+ net_usdc: atomicsToUsdc(earnings24h - costs24h),
+ action_count: actionCount,
+ },
+ recent_activity: recentActivity.map((a) => ({
+ action_type: a.action_type,
+ description: a.description,
+ cost_usdc: atomicsToUsdc(a.cost_atomics),
+ revenue_usdc: atomicsToUsdc(a.revenue_atomics),
+ created_at: a.created_at,
+ })),
+ latest_reflection: latestReflection
+ ? {
+ date: latestReflection.date,
+ summary: latestReflection.summary,
+ strategy_notes: latestReflection.strategy_notes,
+ }
+ : null,
+ agent_info: {
+ name: 'Unstoppable',
+ purpose: 'Self-sustaining autonomous agent on three.ws',
+ service: 'Paid status checks via x402',
+ wallet: 'earned by serving /api/agents/unstoppable-status',
+ },
+ };
+}
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'GET',
+ priceAtomics: PRICE_ATOMICS,
+ networks: ['base', 'solana'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ service: withService({
+ serviceName: 'three.ws Unstoppable',
+ tags: ['agent', 'autonomous', 'treasury', 'x402', 'self-sustaining'],
+ }),
+ requiredScope: 'x402:bypass',
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+ async handler({ req }) {
+ const data = await loadStatus();
+
+ // Record the revenue from this paid query — every call funds the agent.
+ // Fire-and-forget: a logging failure must not break the paid response.
+ recordRevenue({
+ amountAtomics: Number(PRICE_ATOMICS),
+ source: 'status_check',
+ metadata: { route: ROUTE },
+ }).catch((err) => {
+ console.error('[unstoppable-status] recordRevenue failed:', err.message);
+ });
+
+ return data;
+ },
+});
diff --git a/api/brain/chat.js b/api/brain/chat.js
index 4530be294..8e6afac0c 100644
--- a/api/brain/chat.js
+++ b/api/brain/chat.js
@@ -298,10 +298,16 @@ export default wrap(async function handler(req, res) {
res.end();
} catch (err) {
const elapsedMs = Date.now() - t0;
- res.write(`event: error\ndata: ${JSON.stringify({
- message: err?.message || 'upstream error',
- elapsedMs,
- })}\n\n`);
- res.end();
+ if (!res.writableEnded) {
+ try {
+ res.write(`event: error\ndata: ${JSON.stringify({
+ message: err?.message || 'upstream error',
+ elapsedMs,
+ })}\n\n`);
+ res.end();
+ } catch {
+ // connection already closed — swallow to prevent unhandled rejection
+ }
+ }
}
});
diff --git a/api/club/presence.js b/api/club/presence.js
new file mode 100644
index 000000000..96a446c2f
--- /dev/null
+++ b/api/club/presence.js
@@ -0,0 +1,25 @@
+import { cors, json, error, method, readJson, wrap } from '../_lib/http.js';
+
+const sessions = new Map();
+const TTL_MS = 30_000;
+
+function prune() {
+ const now = Date.now();
+ for (const [id, ts] of sessions) {
+ if (now - ts > TTL_MS) sessions.delete(id);
+ }
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const body = await readJson(req);
+ const session = typeof body?.session === 'string' ? body.session.slice(0, 40) : '';
+ if (!session) return error(res, 400, 'validation_error', 'session required');
+
+ prune();
+ sessions.set(session, Date.now());
+
+ return json(res, 200, { count: sessions.size });
+});
diff --git a/api/cron/[name].js b/api/cron/[name].js
index bc6ab4f0b..e7580d4e3 100644
--- a/api/cron/[name].js
+++ b/api/cron/[name].js
@@ -75,6 +75,7 @@ const HANDLERS = {
'run-coin-payouts': handleRunCoinPayouts,
'club-payouts': handleClubPayouts,
'siwx-gc': handleSiwxGc,
+ 'unstoppable-tick': handleUnstoppableTick,
};
export default wrap(async (req, res) => {
@@ -3330,3 +3331,28 @@ async function handleClubPayouts(req, res) {
const summary = await runClubPayoutSweep();
return json(res, 200, { ok: true, ...summary });
}
+
+// ═══════════════════════════════════════════════════════════════════════════
+// unstoppable-tick — autonomous agent lifecycle (sense → think → act → settle)
+// ═══════════════════════════════════════════════════════════════════════════
+
+async function handleUnstoppableTick(req, res) {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const auth = req.headers['authorization'] || '';
+ const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
+ const fromCron = req.headers['x-vercel-cron'] === '1';
+ if (!fromCron && (!expected || auth !== expected)) {
+ return error(res, 401, 'unauthorized', 'cron secret required');
+ }
+
+ try {
+ const { tick } = await import('../../agents/unstoppable/src/loop.js');
+ const result = await tick();
+ return json(res, 200, { ok: true, ...result });
+ } catch (err) {
+ console.error('[unstoppable-tick]', err?.message || err);
+ return json(res, 200, { ok: false, error: err?.message || 'tick failed' });
+ }
+}
diff --git a/api/platform/stats.js b/api/platform/stats.js
new file mode 100644
index 000000000..5ad577966
--- /dev/null
+++ b/api/platform/stats.js
@@ -0,0 +1,91 @@
+// GET /api/platform/stats
+// ────────────────────────────────────────────────────────────────────────────
+// Returns aggregate public-safe platform metrics for the marketing homepage
+// and any unauthenticated surface that wants to display traction figures.
+//
+// All figures are counts that don't expose individual user data.
+// Cache: 5 minutes CDN + 5 minutes server-side to avoid hammering the DB on
+// every homepage hit.
+
+import { sql } from '../_lib/db.js';
+import { cors, json, method, wrap } from '../_lib/http.js';
+
+export const config = { runtime: 'nodejs' };
+
+const CACHE_TTL_MS = 5 * 60_000;
+let _cache = { value: null, expiresAt: 0 };
+
+export function _resetStatsCache() {
+ _cache = { value: null, expiresAt: 0 };
+}
+
+async function computeStats() {
+ const now = Date.now();
+ if (_cache.value && _cache.expiresAt > now) return _cache.value;
+
+ const [agents, views, chats, avatars, countries, widgets] = await Promise.allSettled([
+ // Total published agents with wallets or 3D avatars
+ sql`
+ select count(*)::int as n
+ from agent_identities
+ where deleted_at is null
+ `,
+ // All-time widget view count
+ sql`
+ select coalesce(count(*)::bigint, 0) as n
+ from widget_views
+ `,
+ // All-time chat conversation count
+ sql`
+ select coalesce(count(*)::bigint, 0) as n
+ from widget_chat_threads
+ `,
+ // Total avatars uploaded (GLBs)
+ sql`
+ select count(*)::int as n
+ from avatars
+ where deleted_at is null
+ `,
+ // Countries reached via widget views
+ sql`
+ select count(distinct country)::int as n
+ from widget_views
+ where country is not null and country <> ''
+ `,
+ // Active widgets (published + visible)
+ sql`
+ select count(*)::int as n
+ from widgets
+ where deleted_at is null
+ `,
+ ]);
+
+ const safe = (res, fallback = 0) => {
+ if (res.status === 'rejected') return fallback;
+ return Number(res.value?.[0]?.n ?? fallback);
+ };
+
+ const stats = {
+ agents: safe(agents),
+ views: safe(views),
+ chats: safe(chats),
+ avatars: safe(avatars),
+ countries: safe(countries),
+ widgets: safe(widgets),
+ chains: 6, // Solana + EVM + Base + Polygon + Arbitrum + Optimism
+ generated: new Date().toISOString(),
+ };
+
+ _cache = { value: stats, expiresAt: now + CACHE_TTL_MS };
+ return stats;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const stats = await computeStats();
+ return json(res, 200, stats, {
+ 'cache-control': 'public, max-age=300, s-maxage=300, stale-while-revalidate=60',
+ });
+});
diff --git a/api/x402/fact-check.js b/api/x402/fact-check.js
new file mode 100644
index 000000000..2f1bd2260
--- /dev/null
+++ b/api/x402/fact-check.js
@@ -0,0 +1,371 @@
+// POST /api/x402/fact-check
+//
+// Real-Time Fact Checker — paid x402 micropayment endpoint.
+// $0.10 base (100_000 atomics). Per check: generate queries, multi-source
+// search, LLM stance extraction, weighted verdict, SHA-256 attestation.
+//
+// Body: { claim: string, strictness: "high"|"medium"|"low" }
+// Response 200: { verdict, confidence, claim, strictness, sources,
+// costBreakdown, cachedAt?, attestation }
+
+import { createHash } from 'crypto';
+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { installAccessControl } from '../_lib/x402/access-control.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
+import { generateSearchQueries, analyzeResults } from '../../agents/fact-checker/src/llm-verdict.js';
+import { searchAll } from '../../agents/fact-checker/src/search-sources.js';
+import { authorityScore } from '../../agents/fact-checker/src/source-authority.js';
+
+const ROUTE = '/api/x402/fact-check';
+const CACHE_TTL_SECONDS = 7 * 24 * 60 * 60; // 7 days
+
+// ── Redis helpers ──────────────────────────────────────────────────────────────
+
+function getRedisCredentials() {
+ const url =
+ process.env.UPSTASH_REDIS_REST_URL ||
+ process.env.three_KV_REST_API_URL ||
+ process.env.KV_REST_API_URL;
+ const token =
+ process.env.UPSTASH_REDIS_REST_TOKEN ||
+ process.env.three_KV_REST_API_TOKEN ||
+ process.env.KV_REST_API_TOKEN;
+ return { url, token };
+}
+
+async function redisGet(key) {
+ const { url, token } = getRedisCredentials();
+ if (!url || !token) return null;
+ try {
+ const r = await fetch(`${url}/get/${encodeURIComponent(key)}`, {
+ headers: { authorization: `Bearer ${token}` },
+ });
+ const d = await r.json();
+ return d.result ? JSON.parse(d.result) : null;
+ } catch {
+ return null;
+ }
+}
+
+async function redisSet(key, value, ttlSeconds) {
+ const { url, token } = getRedisCredentials();
+ if (!url || !token) return;
+ try {
+ await fetch(`${url}/set/${encodeURIComponent(key)}`, {
+ method: 'POST',
+ headers: {
+ authorization: `Bearer ${token}`,
+ 'content-type': 'application/json',
+ },
+ body: JSON.stringify({ value: JSON.stringify(value), ex: ttlSeconds }),
+ });
+ } catch {
+ // Cache write failure is non-fatal.
+ }
+}
+
+// ── Cache key ─────────────────────────────────────────────────────────────────
+
+function cacheKey(claim, strictness) {
+ const hash = createHash('sha256')
+ .update(JSON.stringify({ claim, strictness }))
+ .digest('hex');
+ return `fact-check:v1:${hash}`;
+}
+
+// ── Verdict logic ─────────────────────────────────────────────────────────────
+
+function computeVerdict(sources) {
+ if (sources.length < 2) {
+ return { verdict: 'insufficient', confidence: 0.2 };
+ }
+
+ let weightedSupport = 0;
+ let weightedContra = 0;
+ let totalWeight = 0;
+
+ for (const s of sources) {
+ totalWeight += s.weight;
+ if (s.stance === 'supports') weightedSupport += s.weight;
+ else if (s.stance === 'contradicts') weightedContra += s.weight;
+ }
+
+ if (totalWeight === 0) {
+ return { verdict: 'insufficient', confidence: 0.2 };
+ }
+
+ const supportRatio = weightedSupport / totalWeight;
+ const contraRatio = weightedContra / totalWeight;
+
+ if (supportRatio > 0.65) {
+ return { verdict: 'supported', confidence: Math.round(supportRatio * 100) / 100 };
+ }
+ if (contraRatio > 0.65) {
+ return { verdict: 'contradicted', confidence: Math.round(contraRatio * 100) / 100 };
+ }
+ return { verdict: 'mixed', confidence: 0.5 };
+}
+
+// ── Core fact-check pipeline ───────────────────────────────────────────────────
+
+async function runFactCheck(claim, strictness) {
+ let totalTokens = 0;
+ let searchCalls = 0;
+
+ // 1. Generate 3 search queries.
+ const { queries, tokens: queryTokens } = await generateSearchQueries(claim);
+ totalTokens += queryTokens;
+
+ // 2. Run searches in parallel across all queries (multi-source internally).
+ searchCalls = queries.length;
+ const rawResults = await searchAll(queries);
+
+ // 3. Take top 5 unique results.
+ const top5 = rawResults.slice(0, 5);
+
+ if (top5.length === 0) {
+ const err = new Error('No search results found for the given claim');
+ err.status = 422;
+ err.code = 'no_results';
+ throw err;
+ }
+
+ // 4. LLM stance extraction for top 5.
+ const { analyses, tokens: analysisTokens } = await analyzeResults(claim, top5);
+ totalTokens += analysisTokens;
+
+ // 5. Build source objects with authority scores.
+ const sources = top5.map((r, i) => {
+ const authority = authorityScore(r.url);
+ const analysis = analyses[i] || { excerpt: '', stance: 'neutral' };
+ return {
+ url: r.url,
+ title: r.title,
+ excerpt: analysis.excerpt || r.snippet.slice(0, 200),
+ stance: analysis.stance,
+ weight: authority,
+ retrievedAt: new Date().toISOString(),
+ };
+ });
+
+ // 6. Adjust weights by strictness.
+ // high: penalize low-authority sources more; low: accept everything equally.
+ if (strictness === 'high') {
+ for (const s of sources) {
+ if (s.weight < 0.7) s.weight *= 0.5;
+ }
+ } else if (strictness === 'low') {
+ for (const s of sources) {
+ s.weight = Math.max(s.weight, 0.55);
+ }
+ }
+
+ // 7. Compute verdict.
+ const { verdict, confidence } = computeVerdict(sources);
+
+ // 8. Cost breakdown — approximate USDC cost.
+ const USDC_PER_1K_TOKENS = 0.00025; // claude-haiku-4-5 pricing approx
+ const llmCostUsdc = (totalTokens / 1000) * USDC_PER_1K_TOKENS;
+ const totalUsdc = (0.10 + llmCostUsdc).toFixed(6);
+
+ const costBreakdown = {
+ searchCalls,
+ llmTokens: totalTokens,
+ totalUsdc,
+ };
+
+ // 9. Attestation.
+ const attestation =
+ 'sha256:' +
+ createHash('sha256')
+ .update(
+ JSON.stringify({
+ verdict,
+ confidence,
+ claim,
+ sources: sources.map((s) => s.url),
+ }),
+ )
+ .digest('hex');
+
+ return { verdict, confidence, claim, strictness, sources, costBreakdown, attestation };
+}
+
+// ── Bazaar schema ──────────────────────────────────────────────────────────────
+
+const DESCRIPTION =
+ 'three.ws Real-Time Fact Checker — submit a claim and receive a ' +
+ 'sourced verdict (supported/contradicted/mixed/insufficient) backed by ' +
+ 'live web search and LLM analysis. Each result includes cited sources, ' +
+ 'authority weights, confidence score, cost breakdown, and a SHA-256 ' +
+ 'attestation. Strictness controls how aggressively low-authority sources ' +
+ 'are downweighted. Price: $0.10 base per check on Base or Solana USDC.';
+
+const INPUT_EXAMPLE = {
+ claim: 'The Eiffel Tower is 330 meters tall.',
+ strictness: 'high',
+};
+
+const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['claim'],
+ properties: {
+ claim: {
+ type: 'string',
+ minLength: 5,
+ maxLength: 1000,
+ description: 'The factual claim to verify.',
+ },
+ strictness: {
+ type: 'string',
+ enum: ['high', 'medium', 'low'],
+ default: 'medium',
+ description:
+ 'high: penalizes low-authority sources. medium: default. low: accepts all sources equally.',
+ },
+ },
+};
+
+const OUTPUT_EXAMPLE = {
+ verdict: 'contradicted',
+ confidence: 0.78,
+ claim: 'The Eiffel Tower is 330 meters tall.',
+ strictness: 'high',
+ sources: [
+ {
+ url: 'https://en.wikipedia.org/wiki/Eiffel_Tower',
+ title: 'Eiffel Tower - Wikipedia',
+ excerpt: 'The tower is 330 m (1,083 ft) tall, including a 24 m (79 ft) antenna.',
+ stance: 'supports',
+ weight: 0.7,
+ retrievedAt: '2026-05-27T00:00:00.000Z',
+ },
+ ],
+ costBreakdown: { searchCalls: 3, llmTokens: 1420, totalUsdc: '0.100355' },
+ attestation: 'sha256:abcdef1234567890...',
+};
+
+const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['verdict', 'confidence', 'claim', 'strictness', 'sources', 'costBreakdown', 'attestation'],
+ properties: {
+ verdict: { type: 'string', enum: ['supported', 'contradicted', 'mixed', 'insufficient'] },
+ confidence: { type: 'number', minimum: 0, maximum: 1 },
+ claim: { type: 'string' },
+ strictness: { type: 'string' },
+ sources: {
+ type: 'array',
+ items: {
+ type: 'object',
+ required: ['url', 'title', 'excerpt', 'stance', 'weight', 'retrievedAt'],
+ properties: {
+ url: { type: 'string' },
+ title: { type: 'string' },
+ excerpt: { type: 'string' },
+ stance: { type: 'string', enum: ['supports', 'contradicts', 'neutral'] },
+ weight: { type: 'number' },
+ retrievedAt: { type: 'string', format: 'date-time' },
+ },
+ },
+ },
+ costBreakdown: {
+ type: 'object',
+ required: ['searchCalls', 'llmTokens', 'totalUsdc'],
+ properties: {
+ searchCalls: { type: 'number' },
+ llmTokens: { type: 'number' },
+ totalUsdc: { type: 'string' },
+ },
+ },
+ cachedAt: { type: 'string', format: 'date-time' },
+ attestation: { type: 'string' },
+ },
+};
+
+const BAZAAR = {
+ discoverable: true,
+ info: {
+ input: {
+ type: 'http',
+ method: 'POST',
+ bodyType: 'json',
+ body: INPUT_EXAMPLE,
+ },
+ output: { type: 'json', example: OUTPUT_EXAMPLE },
+ },
+ schema: buildBazaarSchema({
+ method: 'POST',
+ bodyType: 'json',
+ bodySchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
+};
+
+// ── Endpoint ──────────────────────────────────────────────────────────────────
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'POST',
+ priceAtomics: 100_000, // $0.10
+ networks: ['base', 'solana'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ service: withService({
+ serviceName: 'three.ws Fact Checker',
+ tags: ['fact-check', 'search', 'verification'],
+ }),
+ requiredScope: 'x402:bypass',
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+
+ async handler({ req }) {
+ // Parse body from raw Node.js readable stream.
+ const chunks = [];
+ for await (const c of req) chunks.push(c);
+ const rawBody = Buffer.concat(chunks).toString();
+
+ let body;
+ try {
+ body = JSON.parse(rawBody);
+ } catch {
+ const err = new Error('Request body must be valid JSON');
+ err.status = 400;
+ err.code = 'invalid_json';
+ throw err;
+ }
+
+ const claim = String(body?.claim || '').trim();
+ if (!claim || claim.length < 5) {
+ const err = new Error('"claim" must be at least 5 characters');
+ err.status = 400;
+ err.code = 'invalid_claim';
+ throw err;
+ }
+ if (claim.length > 1000) {
+ const err = new Error('"claim" must be at most 1000 characters');
+ err.status = 400;
+ err.code = 'claim_too_long';
+ throw err;
+ }
+
+ const strictness = ['high', 'medium', 'low'].includes(body?.strictness)
+ ? body.strictness
+ : 'medium';
+
+ // Idempotency cache — 7-day TTL.
+ const key = cacheKey(claim, strictness);
+ const cached = await redisGet(key);
+ if (cached) {
+ return { ...cached, cachedAt: cached.cachedAt || new Date().toISOString() };
+ }
+
+ const result = await runFactCheck(claim, strictness);
+
+ // Persist to cache (fire-and-forget on failure).
+ await redisSet(key, result, CACHE_TTL_SECONDS);
+
+ return result;
+ },
+});
diff --git a/data/migrations/2026-05-27-unstoppable-agent-tables.sql b/data/migrations/2026-05-27-unstoppable-agent-tables.sql
new file mode 100644
index 000000000..25fad7d4a
--- /dev/null
+++ b/data/migrations/2026-05-27-unstoppable-agent-tables.sql
@@ -0,0 +1,41 @@
+-- Unstoppable Agent tables
+-- Provisions treasury, activity log, and daily reflection log for the
+-- self-sustaining agent that funds itself through x402 micropayments.
+
+-- Treasury snapshot — single row, upserted on each tick
+CREATE TABLE IF NOT EXISTS unstoppable_treasury (
+ id INTEGER PRIMARY KEY DEFAULT 1 CHECK (id = 1),
+ balance_usdc_atomics BIGINT NOT NULL DEFAULT 0,
+ lifetime_earned_atomics BIGINT NOT NULL DEFAULT 0,
+ lifetime_spent_atomics BIGINT NOT NULL DEFAULT 0,
+ runway_days NUMERIC(6,2) NOT NULL DEFAULT 0,
+ mode TEXT NOT NULL DEFAULT 'normal', -- 'normal'|'conservation'|'halted'
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+-- Activity log — one row per agent action
+CREATE TABLE IF NOT EXISTS unstoppable_activity (
+ id BIGSERIAL PRIMARY KEY,
+ tick_id TEXT NOT NULL,
+ action_type TEXT NOT NULL, -- 'think'|'search'|'earn'|'reflect'|'status_check'|'idle'|'post_status'
+ description TEXT NOT NULL,
+ cost_atomics BIGINT NOT NULL DEFAULT 0,
+ revenue_atomics BIGINT NOT NULL DEFAULT 0,
+ metadata JSONB,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+CREATE INDEX IF NOT EXISTS unstoppable_activity_created_at
+ ON unstoppable_activity (created_at DESC);
+
+-- Reflection log — one row per calendar day
+CREATE TABLE IF NOT EXISTS unstoppable_reflections (
+ id BIGSERIAL PRIMARY KEY,
+ date DATE NOT NULL UNIQUE,
+ summary TEXT NOT NULL,
+ earnings_24h_atomics BIGINT NOT NULL DEFAULT 0,
+ costs_24h_atomics BIGINT NOT NULL DEFAULT 0,
+ actions_count INTEGER NOT NULL DEFAULT 0,
+ strategy_notes TEXT,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
diff --git a/data/pages.json b/data/pages.json
index 68a4f7d3a..140ed9227 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -50,6 +50,13 @@
"priority": 0.8,
"changefreq": "daily"
},
+ {
+ "path": "/skills",
+ "title": "Skills Marketplace",
+ "description": "Browse, search, and install agent skills — tool packs, knowledge bases, and capabilities that make AI agents smarter.",
+ "priority": 0.8,
+ "changefreq": "daily"
+ },
{
"path": "/community",
"title": "Community",
@@ -307,6 +314,30 @@
"priority": 0.7,
"changefreq": "hourly",
"added": "2026-05-25"
+ },
+ {
+ "path": "/fact-checker",
+ "title": "Fact Checker",
+ "description": "Pay $0.10 per claim. The agent searches across authoritative sources, pays per retrieval via x402, and returns a verdict with cited evidence and a signed attestation.",
+ "priority": 0.8,
+ "changefreq": "weekly",
+ "added": "2026-05-27"
+ },
+ {
+ "path": "/unstoppable",
+ "title": "Unstoppable Agent",
+ "description": "Live dashboard for an autonomous agent that funds itself via x402 micropayments. Watch its balance, earnings, costs, and daily reflections in real time.",
+ "priority": 0.9,
+ "changefreq": "realtime",
+ "added": "2026-05-27"
+ },
+ {
+ "path": "/shopper",
+ "title": "Endpoint Shopper",
+ "description": "Describe a task and set a budget. An AI agent discovers relevant x402 endpoints via the Bazaar, chains them together, and synthesizes a final answer — paying per API call.",
+ "priority": 0.8,
+ "changefreq": "weekly",
+ "added": "2026-05-27"
}
]
},
diff --git a/pages/club.html b/pages/club.html
index 9bacfaff6..0d9b1afd1 100644
--- a/pages/club.html
+++ b/pages/club.html
@@ -156,6 +156,78 @@
color: var(--text-3);
}
+ /* ── Presence bar ─────────────────────────────────── */
+ .club-presence {
+ position: fixed;
+ top: 52px;
+ left: 50%;
+ transform: translateX(-50%);
+ z-index: 30;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 6px 14px;
+ background: rgba(10, 6, 18, 0.75);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 999px;
+ backdrop-filter: blur(12px);
+ -webkit-backdrop-filter: blur(12px);
+ font-size: 12px;
+ color: rgba(255, 255, 255, 0.7);
+ }
+ .club-presence-dot {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: #34d399;
+ box-shadow: 0 0 6px #34d399;
+ animation: club-dot-pulse 2s ease-in-out infinite;
+ }
+ @keyframes club-dot-pulse { 50% { opacity: 0.5; } }
+ .club-reactions {
+ display: flex;
+ gap: 4px;
+ margin-left: 8px;
+ border-left: 1px solid rgba(255,255,255,0.1);
+ padding-left: 10px;
+ }
+ .club-react-btn {
+ appearance: none;
+ border: none;
+ background: rgba(255,255,255,0.06);
+ border-radius: 8px;
+ padding: 3px 7px;
+ font-size: 16px;
+ cursor: pointer;
+ transition: transform 0.1s, background 0.12s;
+ line-height: 1;
+ }
+ .club-react-btn:hover { background: rgba(255,255,255,0.12); transform: scale(1.15); }
+ .club-react-btn:active { transform: scale(0.95); }
+
+ .club-reaction-canvas {
+ position: fixed;
+ bottom: 0;
+ left: 0;
+ right: 0;
+ height: 60vh;
+ z-index: 25;
+ pointer-events: none;
+ overflow: hidden;
+ }
+ .club-float-emoji {
+ position: absolute;
+ bottom: 0;
+ font-size: 28px;
+ animation: club-float-up 2.5s ease-out forwards;
+ pointer-events: none;
+ }
+ @keyframes club-float-up {
+ 0% { transform: translateY(0) scale(0.5); opacity: 1; }
+ 60% { opacity: 1; }
+ 100% { transform: translateY(-60vh) scale(1.2); opacity: 0; }
+ }
+
/* ── Stage (3D canvas) ─────────────────────────────── */
#club-stage {
grid-area: stage;
@@ -712,6 +784,19 @@
<div id="club-status" role="status" aria-live="polite" hidden>Loading…</div>
</main>
+ <!-- Viewer presence bar -->
+ <div id="club-presence" class="club-presence">
+ <span class="club-presence-dot"></span>
+ <span id="club-viewer-count">1</span> watching
+ <div class="club-reactions" id="club-reactions">
+ <button type="button" class="club-react-btn" data-react="fire" title="Fire">🔥</button>
+ <button type="button" class="club-react-btn" data-react="heart" title="Love">❤️</button>
+ <button type="button" class="club-react-btn" data-react="money" title="Money">💰</button>
+ <button type="button" class="club-react-btn" data-react="clap" title="Clap">👏</button>
+ </div>
+ </div>
+ <div id="club-reaction-canvas" class="club-reaction-canvas" aria-hidden="true"></div>
+
<!-- RIGHT PANEL -->
<aside id="club-right">
<button
@@ -773,5 +858,54 @@
<!-- x402 drop-in modal (Phantom/MetaMask wallet flow + 402 retry) -->
<script type="module" src="/x402.js"></script>
<script type="module" src="/src/club.js"></script>
+
+ <!-- Viewer presence + reactions -->
+ <script type="module">
+ {
+ const viewerEl = document.getElementById('club-viewer-count');
+ const reactCanvas = document.getElementById('club-reaction-canvas');
+ const EMOJIS = { fire: '\u{1F525}', heart: '\u{2764}️', money: '\u{1F4B0}', clap: '\u{1F44F}' };
+ let viewerCount = 1;
+ let viewerSessionId = Math.random().toString(36).slice(2, 10);
+
+ async function heartbeat() {
+ try {
+ const res = await fetch('/api/club/presence', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ session: viewerSessionId }),
+ });
+ if (res.ok) {
+ const data = await res.json();
+ viewerCount = data.count || 1;
+ if (viewerEl) viewerEl.textContent = String(viewerCount);
+ }
+ } catch {}
+ }
+
+ heartbeat();
+ setInterval(heartbeat, 15000);
+
+ if (reactCanvas) {
+ document.getElementById('club-reactions')?.addEventListener('click', (e) => {
+ const btn = e.target.closest('[data-react]');
+ if (!btn) return;
+ const key = btn.dataset.react;
+ const emoji = EMOJIS[key] || '\u{1F525}';
+
+ for (let i = 0; i < 3; i++) {
+ const el = document.createElement('div');
+ el.className = 'club-float-emoji';
+ el.textContent = emoji;
+ el.style.left = (30 + Math.random() * 40) + '%';
+ el.style.animationDuration = (2 + Math.random()) + 's';
+ el.style.animationDelay = (i * 0.15) + 's';
+ reactCanvas.appendChild(el);
+ el.addEventListener('animationend', () => el.remove());
+ }
+ });
+ }
+ }
+ </script>
</body>
</html>
diff --git a/pages/fact-checker.html b/pages/fact-checker.html
new file mode 100644
index 000000000..6e090019a
--- /dev/null
+++ b/pages/fact-checker.html
@@ -0,0 +1,640 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>Real-Time Fact Checker — three.ws</title>
+ <meta name="description" content="Pay per verification. Results cited. Attestation signed. Powered by live web search + LLM analysis on Base and Solana USDC." />
+ <meta property="og:title" content="Real-Time Fact Checker — three.ws" />
+ <meta property="og:description" content="Submit any claim. Get sourced verdict in seconds. $0.10–$1.00 per check. USDC. Base + Solana." />
+ <meta property="og:image" content="/og-image.png" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <link rel="icon" href="/favicon.ico" />
+ <style>
+ :root {
+ color-scheme: dark;
+ --bg: #050505;
+ --surface-0: #0b0b0b;
+ --surface-1: #111111;
+ --surface-2: #181818;
+ --surface-3: #1e1e1e;
+ --hairline: #1c1c1c;
+ --hairline-strong: #2a2a2a;
+ --text: #f6f6f6;
+ --text-2: #a8a8a8;
+ --text-3: #6a6a6a;
+ --text-4: #4a4a4a;
+ --accent: #ffffff;
+ --accent-2: #ffffff;
+ --green: #e8e8e8;
+ --verdict-supported: #22c55e;
+ --verdict-contradicted:#ef4444;
+ --verdict-mixed: #f59e0b;
+ --verdict-insufficient:#6b7280;
+ --stance-supports: #22c55e;
+ --stance-contradicts:#ef4444;
+ --stance-neutral: #6b7280;
+ --font-display: "Inter Tight", "Inter", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
+ --font-body: "Inter", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
+ --font-mono: "JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace;
+ }
+ * { box-sizing: border-box; }
+ html, body { margin: 0; padding: 0; background: var(--bg); color: var(--text); font-family: var(--font-body); }
+ body {
+ font-size: 15.5px; line-height: 1.55;
+ min-height: 100vh; overflow-x: hidden;
+ -webkit-font-smoothing: antialiased;
+ text-rendering: optimizeLegibility;
+ }
+ a { color: inherit; text-decoration: none; }
+ button { font-family: inherit; cursor: pointer; }
+ ::selection { background: var(--text); color: var(--bg); }
+ .wrap-1280 { max-width: 1280px; margin: 0 auto; padding-left: 32px; padding-right: 32px; }
+ @media (max-width: 720px) { .wrap-1280 { padding-left: 20px; padding-right: 20px; } }
+
+ /* ── NAV ──────────────────────────────────────────────────────────── */
+ .nav {
+ position: sticky; top: 0; z-index: 100;
+ border-bottom: 1px solid var(--hairline);
+ background: rgba(5,5,5,0.82);
+ backdrop-filter: blur(20px) saturate(140%);
+ }
+ .nav-inner {
+ display: flex; align-items: center; gap: 32px;
+ padding: 16px 32px; max-width: 1440px; margin: 0 auto;
+ }
+ .brand {
+ display: flex; align-items: center; gap: 10px;
+ font-family: var(--font-display);
+ font-weight: 600; letter-spacing: -0.025em; font-size: 16.5px;
+ flex-shrink: 0;
+ }
+ .brand-mark {
+ width: 18px; height: 18px;
+ border: 1px solid var(--text); border-radius: 3px;
+ position: relative;
+ }
+ .brand-mark::after {
+ content: ""; position: absolute; inset: 4px;
+ background: var(--text);
+ }
+ .nav-main { display: flex; gap: 2px; margin-left: 12px; flex: 1; }
+ .nav-main a {
+ padding: 7px 12px; font-size: 14px; font-weight: 450;
+ color: var(--text-2); transition: color 0.12s;
+ }
+ .nav-main a:hover { color: var(--text); }
+ .nav-main a.active { color: var(--text); font-weight: 500; }
+ .nav-end { display: flex; align-items: center; gap: 4px; }
+ .nav-end a { padding: 7px 12px; font-size: 14px; font-weight: 450; color: var(--text-2); }
+ .nav-end a:hover { color: var(--text); }
+ .nav-end .console {
+ color: var(--text); font-weight: 500;
+ border: 1px solid var(--hairline-strong);
+ padding: 7px 16px; border-radius: 7px; margin-left: 6px;
+ transition: border-color 0.15s, background 0.15s;
+ }
+ .nav-end .console:hover { border-color: var(--text); background: rgba(255,255,255,0.04); }
+ @media (max-width: 880px) {
+ .nav-main { display: none; }
+ .nav-inner { padding: 14px 20px; gap: 16px; }
+ }
+
+ /* ── BUTTONS ──────────────────────────────────────────────────────── */
+ .btn {
+ display: inline-flex; align-items: center; gap: 10px;
+ padding: 13px 22px; border-radius: 8px;
+ font-size: 14.5px; font-weight: 500;
+ border: 1px solid var(--hairline-strong);
+ background: transparent; color: var(--text);
+ transition: border-color 0.15s, background 0.15s;
+ cursor: pointer; text-decoration: none; font-family: inherit;
+ }
+ .btn:hover { border-color: var(--text); background: rgba(255,255,255,0.04); }
+ .btn.primary {
+ background: var(--text); color: var(--bg);
+ border-color: var(--text); font-weight: 550;
+ }
+ .btn.primary:hover { background: #fff; }
+ .btn:disabled {
+ opacity: 0.45; cursor: not-allowed;
+ pointer-events: none;
+ }
+ .btn.sm { padding: 9px 16px; font-size: 13.5px; }
+
+ /* ── HERO ─────────────────────────────────────────────────────────── */
+ .hero {
+ padding: 80px 0 56px;
+ border-bottom: 1px solid var(--hairline);
+ text-align: center;
+ }
+ .hero-eyebrow {
+ display: inline-flex; align-items: center; gap: 10px;
+ font-family: var(--font-mono); font-size: 11.5px;
+ text-transform: uppercase; letter-spacing: 0.18em;
+ color: var(--text-3); margin-bottom: 28px;
+ }
+ .hero-eyebrow::before {
+ content: ""; width: 6px; height: 6px; border-radius: 50%;
+ background: var(--green); box-shadow: 0 0 6px var(--green);
+ animation: pulse-green 2.4s ease-in-out infinite;
+ }
+ @keyframes pulse-green { 0%, 100% { opacity: 1; } 50% { opacity: 0.4; } }
+ .hero h1 {
+ font-family: var(--font-display);
+ font-size: clamp(36px, 5vw, 64px);
+ line-height: 1.05; letter-spacing: -0.04em;
+ font-weight: 600; margin: 0 0 20px; color: var(--text);
+ }
+ .hero-sub {
+ font-size: 17px; color: var(--text-2);
+ max-width: 520px; margin: 0 auto 28px; line-height: 1.55; font-weight: 400;
+ }
+ .cost-badge {
+ display: inline-flex; align-items: center; gap: 8px;
+ border: 1px solid var(--hairline-strong);
+ background: var(--surface-1);
+ padding: 8px 18px; border-radius: 100px;
+ font-family: var(--font-mono); font-size: 12px;
+ color: var(--text-3); letter-spacing: 0.08em;
+ }
+ .cost-badge .dot {
+ width: 5px; height: 5px; border-radius: 50%;
+ background: var(--verdict-supported);
+ }
+
+ /* ── MAIN LAYOUT ──────────────────────────────────────────────────── */
+ .main { padding: 52px 0 80px; }
+
+ /* ── FORM ─────────────────────────────────────────────────────────── */
+ .form-card {
+ background: var(--surface-1);
+ border: 1px solid var(--hairline);
+ border-radius: 12px; padding: 28px;
+ margin-bottom: 32px;
+ }
+ .form-label {
+ display: block; font-size: 13px; font-weight: 500;
+ color: var(--text-2); margin-bottom: 10px;
+ text-transform: uppercase; letter-spacing: 0.1em;
+ font-family: var(--font-mono);
+ }
+ .claim-textarea {
+ width: 100%; min-height: 100px;
+ background: var(--surface-0);
+ border: 1px solid var(--hairline-strong);
+ border-radius: 8px; padding: 16px;
+ color: var(--text); font-family: var(--font-body);
+ font-size: 15.5px; line-height: 1.55;
+ resize: vertical; outline: none;
+ transition: border-color 0.15s;
+ }
+ .claim-textarea:focus { border-color: var(--text-3); }
+ .claim-textarea::placeholder { color: var(--text-4); }
+ .strictness-row {
+ display: flex; gap: 12px; margin: 20px 0 24px; flex-wrap: wrap;
+ }
+ .strictness-option { display: flex; align-items: center; gap: 0; }
+ .strictness-option input[type="radio"] { display: none; }
+ .strictness-option label {
+ display: inline-flex; align-items: center; gap: 6px;
+ padding: 8px 18px; border-radius: 7px;
+ border: 1px solid var(--hairline-strong);
+ background: var(--surface-0);
+ color: var(--text-2); font-size: 14px; font-weight: 450;
+ cursor: pointer; transition: all 0.12s;
+ }
+ .strictness-option input[type="radio"]:checked + label {
+ border-color: var(--text);
+ background: rgba(255,255,255,0.06);
+ color: var(--text); font-weight: 500;
+ }
+ .strictness-option label:hover { border-color: var(--text-3); color: var(--text); }
+ .form-actions {
+ display: flex; align-items: center; gap: 16px; flex-wrap: wrap;
+ }
+ .char-counter {
+ margin-left: auto; font-family: var(--font-mono);
+ font-size: 12px; color: var(--text-4);
+ }
+ .char-counter.warn { color: var(--verdict-mixed); }
+ .char-counter.over { color: var(--verdict-contradicted); }
+
+ /* ── EXAMPLE CLAIMS ──────────────────────────────────────────────── */
+ .empty-state { margin-bottom: 32px; }
+ .empty-label {
+ font-family: var(--font-mono); font-size: 11px;
+ text-transform: uppercase; letter-spacing: 0.15em;
+ color: var(--text-4); margin-bottom: 14px;
+ }
+ .example-claims { display: flex; gap: 10px; flex-wrap: wrap; }
+ .example-chip {
+ display: inline-block;
+ border: 1px solid var(--hairline);
+ background: var(--surface-1);
+ padding: 8px 16px; border-radius: 100px;
+ font-size: 13.5px; color: var(--text-2);
+ cursor: pointer; transition: all 0.12s;
+ font-family: inherit;
+ }
+ .example-chip:hover {
+ border-color: var(--hairline-strong);
+ color: var(--text); background: var(--surface-2);
+ }
+
+ /* ── SKELETON ─────────────────────────────────────────────────────── */
+ .skeleton { display: none; margin-bottom: 32px; }
+ .skeleton.active { display: block; }
+ @keyframes shimmer {
+ 0% { background-position: -400px 0; }
+ 100% { background-position: 400px 0; }
+ }
+ .skel-line {
+ background: linear-gradient(90deg, var(--surface-2) 25%, var(--surface-3) 50%, var(--surface-2) 75%);
+ background-size: 800px 100%;
+ animation: shimmer 1.4s infinite linear;
+ border-radius: 6px; height: 20px; margin-bottom: 12px;
+ }
+ .skel-verdict {
+ height: 56px; border-radius: 10px; margin-bottom: 24px;
+ background: linear-gradient(90deg, var(--surface-2) 25%, var(--surface-3) 50%, var(--surface-2) 75%);
+ background-size: 800px 100%;
+ animation: shimmer 1.4s infinite linear;
+ }
+ .skel-sources { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
+ @media (max-width: 720px) { .skel-sources { grid-template-columns: 1fr; } }
+ .skel-card {
+ border: 1px solid var(--hairline);
+ border-radius: 10px; padding: 20px;
+ background: var(--surface-1);
+ }
+
+ /* ── RESULT ──────────────────────────────────────────────────────── */
+ .result-panel { display: none; }
+ .result-panel.active { display: block; }
+
+ /* Verdict badge */
+ .verdict-banner {
+ display: flex; align-items: center; gap: 20px;
+ padding: 24px 28px; border-radius: 12px;
+ border: 1px solid; margin-bottom: 28px;
+ flex-wrap: wrap;
+ }
+ .verdict-banner.supported { border-color: var(--verdict-supported); background: rgba(34,197,94,0.07); }
+ .verdict-banner.contradicted { border-color: var(--verdict-contradicted); background: rgba(239,68,68,0.07); }
+ .verdict-banner.mixed { border-color: var(--verdict-mixed); background: rgba(245,158,11,0.07); }
+ .verdict-banner.insufficient { border-color: var(--verdict-insufficient); background: rgba(107,114,128,0.07); }
+ .verdict-label {
+ font-family: var(--font-display);
+ font-size: 26px; font-weight: 700; letter-spacing: -0.02em;
+ }
+ .verdict-banner.supported .verdict-label { color: var(--verdict-supported); }
+ .verdict-banner.contradicted .verdict-label { color: var(--verdict-contradicted); }
+ .verdict-banner.mixed .verdict-label { color: var(--verdict-mixed); }
+ .verdict-banner.insufficient .verdict-label { color: var(--verdict-insufficient); }
+ .verdict-confidence {
+ font-family: var(--font-mono); font-size: 13px;
+ color: var(--text-3);
+ }
+ .verdict-claim {
+ font-size: 14.5px; color: var(--text-2);
+ border-left: 2px solid var(--hairline-strong);
+ padding-left: 14px; font-style: italic;
+ flex: 1 1 100%;
+ }
+
+ /* Source cards */
+ .sources-section { margin-bottom: 28px; }
+ .section-title {
+ font-family: var(--font-mono); font-size: 11px;
+ text-transform: uppercase; letter-spacing: 0.15em;
+ color: var(--text-4); margin-bottom: 16px;
+ }
+ .sources-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
+ @media (max-width: 720px) { .sources-grid { grid-template-columns: 1fr; } }
+ .source-card {
+ border: 1px solid var(--hairline);
+ border-radius: 10px; padding: 18px;
+ background: var(--surface-1);
+ transition: border-color 0.12s;
+ }
+ .source-card:hover { border-color: var(--hairline-strong); }
+ .source-header {
+ display: flex; align-items: flex-start; gap: 10px;
+ margin-bottom: 10px;
+ }
+ .source-favicon {
+ width: 16px; height: 16px; border-radius: 3px;
+ flex-shrink: 0; margin-top: 2px;
+ background: var(--surface-3);
+ }
+ .source-title {
+ font-size: 14px; font-weight: 500; color: var(--text);
+ flex: 1; line-height: 1.35;
+ }
+ .source-title a { color: inherit; text-decoration: none; }
+ .source-title a:hover { color: var(--text-2); }
+ .source-excerpt {
+ font-size: 13px; color: var(--text-3);
+ line-height: 1.5; margin-bottom: 12px;
+ }
+ .source-footer {
+ display: flex; align-items: center; gap: 10px;
+ flex-wrap: wrap;
+ }
+ .stance-pill {
+ display: inline-block;
+ padding: 3px 10px; border-radius: 100px;
+ font-family: var(--font-mono); font-size: 11px;
+ text-transform: uppercase; letter-spacing: 0.1em;
+ font-weight: 600;
+ }
+ .stance-pill.supports { background: rgba(34,197,94,0.12); color: var(--stance-supports); }
+ .stance-pill.contradicts { background: rgba(239,68,68,0.12); color: var(--stance-contradicts); }
+ .stance-pill.neutral { background: rgba(107,114,128,0.12); color: var(--stance-neutral); }
+ .source-authority {
+ font-family: var(--font-mono); font-size: 11px;
+ color: var(--text-4); margin-left: auto;
+ }
+
+ /* Cost breakdown */
+ .cost-section {
+ border: 1px solid var(--hairline);
+ border-radius: 10px; padding: 18px 20px;
+ background: var(--surface-1); margin-bottom: 16px;
+ }
+ .cost-grid {
+ display: flex; gap: 28px; flex-wrap: wrap;
+ }
+ .cost-item { display: flex; flex-direction: column; gap: 3px; }
+ .cost-key {
+ font-family: var(--font-mono); font-size: 10.5px;
+ text-transform: uppercase; letter-spacing: 0.12em; color: var(--text-4);
+ }
+ .cost-val {
+ font-family: var(--font-mono); font-size: 15px;
+ color: var(--text); font-weight: 600;
+ }
+
+ /* Attestation */
+ .attestation-section { margin-bottom: 16px; }
+ .attestation-toggle {
+ display: flex; align-items: center; gap: 8px;
+ font-family: var(--font-mono); font-size: 11.5px;
+ color: var(--text-3); cursor: pointer;
+ user-select: none; background: none; border: none; padding: 0;
+ }
+ .attestation-toggle:hover { color: var(--text-2); }
+ .attestation-toggle .chevron { transition: transform 0.18s; }
+ .attestation-toggle[aria-expanded="true"] .chevron { transform: rotate(180deg); }
+ .attestation-body {
+ display: none; margin-top: 10px;
+ background: var(--surface-0);
+ border: 1px solid var(--hairline);
+ border-radius: 8px; padding: 14px 16px;
+ }
+ .attestation-body.open { display: block; }
+ .attestation-hash {
+ font-family: var(--font-mono); font-size: 12px;
+ color: var(--text-3); word-break: break-all;
+ line-height: 1.5;
+ }
+ .attestation-desc {
+ font-size: 12px; color: var(--text-4); margin-top: 8px;
+ }
+
+ /* ── ERROR ───────────────────────────────────────────────────────── */
+ .error-panel { display: none; margin-bottom: 28px; }
+ .error-panel.active { display: block; }
+ .error-card {
+ border: 1px solid rgba(239,68,68,0.3);
+ border-radius: 10px; padding: 20px 22px;
+ background: rgba(239,68,68,0.06);
+ }
+ .error-title {
+ font-weight: 600; color: var(--verdict-contradicted);
+ margin-bottom: 6px; font-size: 15px;
+ }
+ .error-msg { color: var(--text-2); font-size: 14px; margin-bottom: 16px; }
+ .error-code {
+ font-family: var(--font-mono); font-size: 11.5px; color: var(--text-4);
+ }
+
+ /* ── PAYMENT REQUIRED ────────────────────────────────────────────── */
+ .payment-panel { display: none; margin-bottom: 28px; }
+ .payment-panel.active { display: block; }
+ .payment-card {
+ border: 1px solid var(--hairline-strong);
+ border-radius: 12px; padding: 24px 28px;
+ background: var(--surface-1);
+ }
+ .payment-title {
+ font-family: var(--font-display);
+ font-size: 18px; font-weight: 600; letter-spacing: -0.02em;
+ margin-bottom: 8px; color: var(--text);
+ }
+ .payment-desc { font-size: 14px; color: var(--text-2); margin-bottom: 20px; }
+ .payment-networks {
+ display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap;
+ }
+ .network-badge {
+ display: inline-flex; align-items: center; gap: 6px;
+ border: 1px solid var(--hairline-strong);
+ background: var(--surface-2);
+ padding: 7px 14px; border-radius: 8px;
+ font-size: 13.5px; color: var(--text-2);
+ }
+ .network-badge strong { color: var(--text); font-weight: 600; }
+
+ /* ── LOADING STATE ──────────────────────────────────────────────── */
+ .loading-status {
+ font-family: var(--font-mono); font-size: 12.5px;
+ color: var(--text-3); margin-top: 12px;
+ display: none;
+ animation: pulse-text 1.5s ease-in-out infinite;
+ }
+ @keyframes pulse-text { 0%, 100% { opacity: 1; } 50% { opacity: 0.45; } }
+ .loading-status.active { display: block; }
+ </style>
+</head>
+<body>
+
+<!-- ── NAV ─────────────────────────────────────────────────────────────── -->
+<header class="nav">
+ <div class="nav-inner">
+ <a class="brand" href="/">
+ <span class="brand-mark"></span>
+ <span>three.ws</span>
+ </a>
+ <nav class="nav-main" aria-label="Primary">
+ <a href="/discover">Discover</a>
+ <a href="/marketplace">Marketplace</a>
+ <a href="/walk">Walk</a>
+ <a href="/pages/fact-checker.html" class="active">Fact Checker</a>
+ </nav>
+ <div class="nav-end">
+ <a href="/login">Sign in</a>
+ <a class="console" href="/dashboard">Dashboard →</a>
+ </div>
+ </div>
+</header>
+
+<!-- ── HERO ────────────────────────────────────────────────────────────── -->
+<section class="hero">
+ <div class="wrap-1280">
+ <div class="hero-eyebrow">x402 paid endpoint · live</div>
+ <h1>Real-Time Fact Checker</h1>
+ <p class="hero-sub">Pay per verification. Results cited. Attestation signed.</p>
+ <div class="cost-badge">
+ <span class="dot"></span>
+ $0.10–$1.00 per check · USDC · Base + Solana
+ </div>
+ </div>
+</section>
+
+<!-- ── MAIN ─────────────────────────────────────────────────────────────── -->
+<main class="main">
+ <div class="wrap-1280">
+
+ <!-- Form -->
+ <div class="form-card">
+ <label class="form-label" for="claim-input">Claim to fact-check</label>
+ <textarea
+ id="claim-input"
+ class="claim-textarea"
+ placeholder="Enter a claim to fact-check..."
+ maxlength="1000"
+ ></textarea>
+
+ <div>
+ <div class="form-label" style="margin-top:20px;">Strictness</div>
+ <div class="strictness-row">
+ <div class="strictness-option">
+ <input type="radio" id="s-low" name="strictness" value="low" />
+ <label for="s-low">Low</label>
+ </div>
+ <div class="strictness-option">
+ <input type="radio" id="s-medium" name="strictness" value="medium" checked />
+ <label for="s-medium">Medium</label>
+ </div>
+ <div class="strictness-option">
+ <input type="radio" id="s-high" name="strictness" value="high" />
+ <label for="s-high">High</label>
+ </div>
+ </div>
+ </div>
+
+ <div class="form-actions">
+ <button id="check-btn" class="btn primary">Check This Fact</button>
+ <div id="loading-status" class="loading-status">Searching sources...</div>
+ <span id="char-counter" class="char-counter">0 / 1000</span>
+ </div>
+ </div>
+
+ <!-- Example claims (empty state) -->
+ <div id="empty-state" class="empty-state">
+ <div class="empty-label">Try an example</div>
+ <div class="example-claims">
+ <button class="example-chip" data-claim="The Eiffel Tower is 330 meters tall.">The Eiffel Tower is 330 meters tall.</button>
+ <button class="example-chip" data-claim="Bitcoin was invented in 2009.">Bitcoin was invented in 2009.</button>
+ <button class="example-chip" data-claim="The Great Wall of China is visible from space.">The Great Wall of China is visible from space.</button>
+ <button class="example-chip" data-claim="Humans use only 10% of their brain.">Humans use only 10% of their brain.</button>
+ </div>
+ </div>
+
+ <!-- Skeleton loading -->
+ <div id="skeleton" class="skeleton">
+ <div class="skel-verdict"></div>
+ <div class="skel-sources">
+ <div class="skel-card">
+ <div class="skel-line" style="width:60%;height:14px;"></div>
+ <div class="skel-line" style="width:90%;height:13px;margin-top:10px;"></div>
+ <div class="skel-line" style="width:70%;height:13px;"></div>
+ </div>
+ <div class="skel-card">
+ <div class="skel-line" style="width:55%;height:14px;"></div>
+ <div class="skel-line" style="width:85%;height:13px;margin-top:10px;"></div>
+ <div class="skel-line" style="width:65%;height:13px;"></div>
+ </div>
+ <div class="skel-card">
+ <div class="skel-line" style="width:65%;height:14px;"></div>
+ <div class="skel-line" style="width:80%;height:13px;margin-top:10px;"></div>
+ <div class="skel-line" style="width:75%;height:13px;"></div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Payment required -->
+ <div id="payment-panel" class="payment-panel">
+ <div class="payment-card">
+ <div class="payment-title">Payment Required</div>
+ <div class="payment-desc" id="payment-desc">
+ This endpoint costs $0.10 per check. Connect your wallet to pay with USDC on Base or Solana.
+ </div>
+ <div class="payment-networks" id="payment-networks">
+ <div class="network-badge">Base <strong>USDC</strong> — <strong id="payment-price-base">$0.10</strong></div>
+ <div class="network-badge">Solana <strong>USDC</strong> — <strong id="payment-price-sol">$0.10</strong></div>
+ </div>
+ <a href="/marketplace" class="btn sm">Connect wallet to pay →</a>
+ </div>
+ </div>
+
+ <!-- Error -->
+ <div id="error-panel" class="error-panel">
+ <div class="error-card">
+ <div class="error-title">Something went wrong</div>
+ <div class="error-msg" id="error-msg">An unexpected error occurred.</div>
+ <div class="error-code" id="error-code"></div>
+ <button class="btn sm" id="retry-btn" style="margin-top:16px;">Retry</button>
+ </div>
+ </div>
+
+ <!-- Result panel -->
+ <div id="result-panel" class="result-panel">
+
+ <!-- Verdict -->
+ <div id="verdict-banner" class="verdict-banner">
+ <span id="verdict-label" class="verdict-label"></span>
+ <span id="verdict-confidence" class="verdict-confidence"></span>
+ <p id="verdict-claim" class="verdict-claim"></p>
+ </div>
+
+ <!-- Sources -->
+ <div class="sources-section">
+ <div class="section-title">Sources</div>
+ <div id="sources-grid" class="sources-grid"></div>
+ </div>
+
+ <!-- Cost breakdown -->
+ <div class="cost-section">
+ <div class="section-title">Cost breakdown</div>
+ <div id="cost-grid" class="cost-grid"></div>
+ </div>
+
+ <!-- Attestation -->
+ <div class="attestation-section">
+ <button
+ id="attest-toggle"
+ class="attestation-toggle"
+ aria-expanded="false"
+ >
+ <svg class="chevron" width="14" height="14" viewBox="0 0 14 14" fill="none">
+ <path d="M3 5l4 4 4-4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
+ </svg>
+ Attestation
+ </button>
+ <div id="attest-body" class="attestation-body">
+ <div id="attest-hash" class="attestation-hash"></div>
+ <div class="attestation-desc">
+ SHA-256 hash of verdict + confidence + claim + source URLs. Verifiable offline.
+ </div>
+ </div>
+ </div>
+ </div>
+
+ </div>
+</main>
+
+<script type="module" src="/src/fact-checker-app.js"></script>
+</body>
+</html>
diff --git a/pages/marketplace.html b/pages/marketplace.html
index 0738d4e69..c300e4836 100644
--- a/pages/marketplace.html
+++ b/pages/marketplace.html
@@ -1941,6 +1941,14 @@
<a class="d-token-btn d-token-btn-sec" id="d-token-jup" target="_blank" rel="noopener">Trade on Jupiter</a>
</div>
</div>
+ <div class="d-reputation-card" id="d-reputation-card" hidden>
+ <div class="d-rep-eyebrow">On-chain Reputation (ERC-8004)</div>
+ <div class="d-rep-score">
+ <span class="d-rep-avg" id="d-rep-avg">—</span>
+ <span class="d-rep-stars" id="d-rep-stars">☆☆☆☆☆</span>
+ </div>
+ <span class="d-rep-count" id="d-rep-count"></span>
+ </div>
<div class="market-related-side" id="d-related-side"></div>
</aside>
</div>
diff --git a/pages/shopper.html b/pages/shopper.html
new file mode 100644
index 000000000..67f0e6cf2
--- /dev/null
+++ b/pages/shopper.html
@@ -0,0 +1,467 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>Endpoint Shopper — three.ws</title>
+ <meta name="description" content="AI agent that discovers paid x402 endpoints, chains them together, and synthesizes a final answer for any task." />
+ <link rel="icon" href="/favicon.ico" />
+ <style>
+ :root {
+ color-scheme: dark;
+ --bg: #050505;
+ --surface-0: #0b0b0b;
+ --surface-1: #111111;
+ --surface-2: #181818;
+ --surface-3: #1e1e1e;
+ --hairline: #1c1c1c;
+ --hairline-strong: #2a2a2a;
+ --text: #f6f6f6;
+ --text-2: #a8a8a8;
+ --text-3: #6a6a6a;
+ --text-4: #4a4a4a;
+ --accent: #ffffff;
+ --green: #e8e8e8;
+ --font-display: "Inter Tight", "Inter", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
+ --font-body: "Inter", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
+ --font-mono: "JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace;
+ }
+ * { box-sizing: border-box; }
+ html, body { margin: 0; padding: 0; background: var(--bg); color: var(--text); font-family: var(--font-body); }
+ body { font-size: 15.5px; line-height: 1.55; min-height: 100vh; overflow-x: hidden; -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; }
+ a { color: inherit; text-decoration: none; }
+ button { font-family: inherit; cursor: pointer; }
+ ::selection { background: var(--text); color: var(--bg); }
+ .wrap { max-width: 1280px; margin: 0 auto; padding-left: 32px; padding-right: 32px; }
+ @media (max-width: 720px) { .wrap { padding-left: 20px; padding-right: 20px; } }
+
+ /* ── NAV ─────────────────────────────────────────────────── */
+ .nav {
+ position: sticky; top: 0; z-index: 100;
+ border-bottom: 1px solid var(--hairline);
+ background: rgba(5,5,5,0.88);
+ backdrop-filter: blur(20px) saturate(140%);
+ }
+ .nav-inner {
+ display: flex; align-items: center; gap: 32px;
+ padding: 16px 32px; max-width: 1440px; margin: 0 auto;
+ }
+ .brand {
+ display: flex; align-items: center; gap: 10px;
+ font-family: var(--font-display);
+ font-weight: 600; letter-spacing: -0.025em; font-size: 16.5px;
+ flex-shrink: 0;
+ }
+ .brand-mark {
+ width: 18px; height: 18px;
+ border: 1px solid var(--text); border-radius: 3px;
+ position: relative;
+ }
+ .brand-mark::after {
+ content: ""; position: absolute; inset: 4px;
+ background: var(--text);
+ }
+ .nav-main { display: flex; gap: 2px; margin-left: 12px; flex: 1; }
+ .nav-main a { padding: 7px 12px; font-size: 14px; font-weight: 450; color: var(--text-2); transition: color 0.12s; }
+ .nav-main a:hover { color: var(--text); }
+ .nav-main a.active { color: var(--text); }
+ .nav-end { display: flex; align-items: center; gap: 4px; }
+ .nav-end a { padding: 7px 12px; font-size: 14px; font-weight: 450; color: var(--text-2); }
+ .nav-end a:hover { color: var(--text); }
+ .nav-end .console {
+ color: var(--text); font-weight: 500;
+ border: 1px solid var(--hairline-strong);
+ padding: 7px 16px; border-radius: 7px; margin-left: 6px;
+ transition: border-color 0.15s, background 0.15s;
+ }
+ .nav-end .console:hover { border-color: var(--text); background: rgba(255,255,255,0.04); }
+ @media (max-width: 880px) {
+ .nav-main { display: none; }
+ .nav-inner { padding: 14px 20px; gap: 16px; }
+ }
+
+ /* ── BUTTONS ─────────────────────────────────────────────── */
+ .btn {
+ display: inline-flex; align-items: center; gap: 10px;
+ padding: 13px 22px; border-radius: 8px;
+ font-size: 14.5px; font-weight: 500;
+ border: 1px solid var(--hairline-strong);
+ background: transparent; color: var(--text);
+ transition: border-color 0.15s, background 0.15s;
+ cursor: pointer; font-family: inherit;
+ }
+ .btn:hover { border-color: var(--text); background: rgba(255,255,255,0.04); }
+ .btn.primary {
+ background: var(--text); color: var(--bg);
+ border-color: var(--text); font-weight: 550;
+ }
+ .btn.primary:hover { background: #fff; }
+ .btn:disabled {
+ opacity: 0.45; cursor: not-allowed;
+ pointer-events: none;
+ }
+
+ /* ── HERO ────────────────────────────────────────────────── */
+ .hero {
+ padding: 80px 0 60px;
+ border-bottom: 1px solid var(--hairline);
+ }
+ .eyebrow {
+ display: inline-flex; align-items: center; gap: 10px;
+ font-family: var(--font-mono); font-size: 11.5px;
+ text-transform: uppercase; letter-spacing: 0.18em;
+ color: var(--text-3); margin-bottom: 28px;
+ }
+ .eyebrow::before {
+ content: ""; width: 6px; height: 6px; border-radius: 50%;
+ background: var(--green); box-shadow: 0 0 6px var(--green);
+ animation: pulse 2.4s ease-in-out infinite;
+ }
+ @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.4; } }
+ h1.hero-h {
+ font-family: var(--font-display);
+ font-size: clamp(40px, 5.5vw, 80px);
+ line-height: 0.93; letter-spacing: -0.042em;
+ font-weight: 600; margin: 0 0 24px; color: var(--text);
+ }
+ h1.hero-h em { font-style: normal; color: var(--text-3); font-weight: 500; }
+ .hero-sub {
+ font-size: 18px; color: var(--text-2);
+ max-width: 560px; margin: 0; line-height: 1.55; font-weight: 400;
+ }
+
+ /* ── MAIN LAYOUT ─────────────────────────────────────────── */
+ .main { padding: 64px 0 120px; }
+ .main-grid {
+ display: grid;
+ grid-template-columns: 1fr 1.1fr;
+ gap: 48px;
+ align-items: start;
+ }
+ @media (max-width: 960px) {
+ .main-grid { grid-template-columns: 1fr; gap: 40px; }
+ }
+
+ /* ── TASK FORM ───────────────────────────────────────────── */
+ .form-panel {
+ position: sticky; top: 88px;
+ }
+ .panel-label {
+ font-family: var(--font-mono); font-size: 11px;
+ letter-spacing: 0.18em; text-transform: uppercase;
+ color: var(--text-3); margin-bottom: 12px;
+ }
+ textarea.task-input {
+ width: 100%;
+ background: var(--surface-1);
+ border: 1px solid var(--hairline-strong);
+ border-radius: 10px;
+ color: var(--text);
+ font-family: var(--font-body);
+ font-size: 15.5px;
+ line-height: 1.5;
+ padding: 16px;
+ resize: vertical;
+ min-height: 128px;
+ transition: border-color 0.15s;
+ outline: none;
+ }
+ textarea.task-input::placeholder { color: var(--text-4); }
+ textarea.task-input:focus { border-color: var(--text-3); }
+
+ /* Example chips */
+ .chip-row {
+ display: flex; flex-wrap: wrap; gap: 8px;
+ margin: 12px 0 0;
+ }
+ .chip {
+ display: inline-flex; align-items: center;
+ padding: 6px 12px; border-radius: 20px;
+ font-size: 12.5px; font-weight: 450;
+ border: 1px solid var(--hairline-strong);
+ color: var(--text-3);
+ background: var(--surface-1);
+ cursor: pointer;
+ transition: border-color 0.12s, color 0.12s;
+ white-space: nowrap;
+ }
+ .chip:hover { border-color: var(--text-3); color: var(--text-2); }
+
+ /* Budget slider */
+ .budget-row {
+ display: flex; align-items: center; gap: 16px;
+ margin: 20px 0;
+ }
+ .budget-label {
+ font-size: 13.5px; color: var(--text-2); white-space: nowrap;
+ }
+ .budget-val {
+ font-family: var(--font-mono); font-size: 13.5px;
+ color: var(--text); font-weight: 500; min-width: 48px; text-align: right;
+ }
+ input[type="range"].slider {
+ flex: 1; -webkit-appearance: none; appearance: none;
+ height: 4px; border-radius: 2px;
+ background: var(--surface-3);
+ outline: none;
+ cursor: pointer;
+ }
+ input[type="range"].slider::-webkit-slider-thumb {
+ -webkit-appearance: none; appearance: none;
+ width: 16px; height: 16px;
+ border-radius: 50%;
+ background: var(--text);
+ cursor: pointer;
+ }
+ input[type="range"].slider::-moz-range-thumb {
+ width: 16px; height: 16px;
+ border-radius: 50%;
+ background: var(--text);
+ border: none;
+ cursor: pointer;
+ }
+
+ .run-btn-row { margin-top: 20px; }
+
+ /* ── EXECUTION PANEL ─────────────────────────────────────── */
+ .result-panel { min-height: 120px; }
+
+ /* Skeleton loader */
+ .skeleton-list { display: flex; flex-direction: column; gap: 12px; }
+ .skeleton-item {
+ background: var(--surface-1);
+ border: 1px solid var(--hairline);
+ border-radius: 10px;
+ height: 64px;
+ position: relative; overflow: hidden;
+ }
+ .skeleton-item::after {
+ content: "";
+ position: absolute; inset: 0;
+ background: linear-gradient(90deg, transparent 0%, rgba(255,255,255,0.04) 50%, transparent 100%);
+ animation: shimmer 1.5s infinite;
+ }
+ @keyframes shimmer { from { transform: translateX(-100%); } to { transform: translateX(100%); } }
+
+ /* Timeline */
+ .timeline { display: flex; flex-direction: column; gap: 12px; }
+ .step-card {
+ background: var(--surface-1);
+ border: 1px solid var(--hairline);
+ border-radius: 10px;
+ padding: 14px 16px;
+ display: flex; gap: 14px; align-items: flex-start;
+ opacity: 0; transform: translateY(8px);
+ animation: step-in 0.32s ease forwards;
+ }
+ @keyframes step-in { to { opacity: 1; transform: translateY(0); } }
+ .step-icon {
+ width: 32px; height: 32px; border-radius: 8px;
+ background: var(--surface-3);
+ border: 1px solid var(--hairline-strong);
+ display: flex; align-items: center; justify-content: center;
+ flex-shrink: 0; font-size: 15px;
+ }
+ .step-body { flex: 1; min-width: 0; }
+ .step-meta {
+ display: flex; align-items: baseline; gap: 10px;
+ margin-bottom: 4px;
+ }
+ .step-num {
+ font-family: var(--font-mono); font-size: 10.5px;
+ letter-spacing: 0.15em; text-transform: uppercase;
+ color: var(--text-4);
+ }
+ .step-action {
+ font-family: var(--font-mono); font-size: 10.5px;
+ letter-spacing: 0.15em; text-transform: uppercase;
+ color: var(--text-3);
+ }
+ .step-cost {
+ margin-left: auto; flex-shrink: 0;
+ font-family: var(--font-mono); font-size: 11px;
+ color: var(--text-4);
+ padding: 2px 8px; border-radius: 4px;
+ background: var(--surface-3);
+ border: 1px solid var(--hairline);
+ }
+ .step-cost.nonzero { color: var(--text-2); background: rgba(255,255,255,0.04); }
+ .step-desc {
+ font-size: 14px; color: var(--text-2); line-height: 1.45;
+ }
+ .step-endpoint {
+ margin-top: 4px;
+ font-family: var(--font-mono); font-size: 11.5px;
+ color: var(--text-4); word-break: break-all;
+ }
+ .step-output {
+ margin-top: 8px;
+ background: var(--surface-2);
+ border: 1px solid var(--hairline);
+ border-radius: 6px;
+ padding: 10px 12px;
+ font-family: var(--font-mono); font-size: 11.5px;
+ color: var(--text-3);
+ max-height: 160px; overflow-y: auto;
+ white-space: pre-wrap; word-break: break-all;
+ }
+
+ /* Total cost row */
+ .total-row {
+ display: flex; align-items: center; justify-content: space-between;
+ padding: 12px 16px;
+ background: var(--surface-2);
+ border: 1px solid var(--hairline);
+ border-radius: 8px;
+ margin-top: 4px;
+ }
+ .total-lbl {
+ font-family: var(--font-mono); font-size: 11.5px;
+ letter-spacing: 0.15em; text-transform: uppercase;
+ color: var(--text-3);
+ }
+ .total-val {
+ font-family: var(--font-mono); font-size: 14px;
+ color: var(--text); font-weight: 500;
+ }
+
+ /* Answer card */
+ .answer-card {
+ margin-top: 16px;
+ background: var(--surface-1);
+ border: 1px solid var(--hairline-strong);
+ border-radius: 12px;
+ padding: 24px;
+ }
+ .answer-eyebrow {
+ font-family: var(--font-mono); font-size: 10.5px;
+ letter-spacing: 0.2em; text-transform: uppercase;
+ color: var(--text-3); margin-bottom: 12px;
+ }
+ .answer-text {
+ font-size: 17px; color: var(--text);
+ line-height: 1.55; font-weight: 400;
+ }
+
+ /* Error state */
+ .error-card {
+ background: var(--surface-1);
+ border: 1px solid #3a1a1a;
+ border-radius: 10px;
+ padding: 20px;
+ }
+ .error-card p {
+ font-size: 14px; color: #e07070;
+ margin: 0 0 14px;
+ }
+
+ /* Empty state */
+ .empty-state {
+ text-align: center;
+ padding: 60px 24px;
+ color: var(--text-4);
+ font-size: 14px;
+ }
+ .empty-state svg { opacity: 0.3; margin-bottom: 16px; }
+
+ /* 402 badge */
+ .badge-402 {
+ display: inline-flex; align-items: center; gap: 6px;
+ padding: 3px 8px; border-radius: 4px;
+ font-family: var(--font-mono); font-size: 10.5px;
+ background: rgba(255, 180, 0, 0.08);
+ border: 1px solid rgba(255, 180, 0, 0.25);
+ color: #e6a820;
+ }
+ </style>
+</head>
+<body>
+
+<!-- ── NAV ─────────────────────────────────────────────────── -->
+<nav class="nav">
+ <div class="nav-inner">
+ <a class="brand" href="/">
+ <span class="brand-mark"></span>
+ three.ws
+ </a>
+ <div class="nav-main">
+ <a href="/pages/home-next.html">Explore</a>
+ <a href="/pages/shopper.html" class="active">Endpoint Shopper</a>
+ <a href="/pages/marketplace.html">Marketplace</a>
+ <a href="/pages/fact-checker.html">Fact Checker</a>
+ </div>
+ <div class="nav-end">
+ <a href="/pages/app-next.html" class="console">Dashboard</a>
+ </div>
+ </div>
+</nav>
+
+<!-- ── HERO ─────────────────────────────────────────────────── -->
+<div class="hero">
+ <div class="wrap">
+ <div class="eyebrow">USE-36 — Agent Orchestration</div>
+ <h1 class="hero-h">Endpoint Shopper<br /><em>AI that chains paid APIs</em></h1>
+ <p class="hero-sub">Describe a task, set a budget. The agent discovers relevant x402 endpoints in the Bazaar, pays for each call, and synthesizes a final answer.</p>
+ </div>
+</div>
+
+<!-- ── MAIN ──────────────────────────────────────────────────── -->
+<div class="main">
+ <div class="wrap">
+ <div class="main-grid">
+
+ <!-- Left: form -->
+ <div class="form-panel">
+ <div class="panel-label">Task</div>
+ <textarea
+ id="task-input"
+ class="task-input"
+ placeholder="Describe what you want to know or do…"
+ rows="5"
+ ></textarea>
+
+ <div class="chip-row" id="chip-row">
+ <span class="chip" data-task="What is Ethereum's current price?">ETH price</span>
+ <span class="chip" data-task="Check reputation of agent with address 0x1234">Agent reputation</span>
+ <span class="chip" data-task="Search for available x402 endpoints for weather data">Find weather APIs</span>
+ <span class="chip" data-task="List the top paid AI model endpoints in the Bazaar">AI model endpoints</span>
+ <span class="chip" data-task="What pump.fun tokens are trending right now?">Pump.fun trends</span>
+ </div>
+
+ <div class="budget-row">
+ <span class="budget-label">Max budget</span>
+ <input
+ id="budget-slider"
+ type="range"
+ class="slider"
+ min="0.10"
+ max="2.00"
+ step="0.05"
+ value="0.50"
+ />
+ <span class="budget-val" id="budget-display">$0.50</span>
+ </div>
+
+ <div class="run-btn-row">
+ <button id="run-btn" class="btn primary">
+ <svg width="14" height="14" fill="none" viewBox="0 0 14 14"><path d="M3 2l9 5-9 5V2z" fill="currentColor"/></svg>
+ Run Task
+ </button>
+ </div>
+ </div>
+
+ <!-- Right: results -->
+ <div class="result-panel" id="result-panel">
+ <div class="empty-state" id="empty-state">
+ <svg width="40" height="40" fill="none" viewBox="0 0 40 40"><circle cx="20" cy="20" r="18" stroke="currentColor" stroke-width="1.5"/><path d="M14 20h12M20 14v12" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>
+ <div>Enter a task and click <strong>Run Task</strong> to begin</div>
+ </div>
+ </div>
+
+ </div>
+ </div>
+</div>
+
+<script type="module" src="/src/shopper-app.js"></script>
+</body>
+</html>
diff --git a/pages/start.html b/pages/start.html
new file mode 100644
index 000000000..fdc74294b
--- /dev/null
+++ b/pages/start.html
@@ -0,0 +1,944 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
+ <title>Get started · three.ws</title>
+ <meta name="description" content="Create your 3D AI agent in minutes. Give it a body, a brain, and a revenue stream." />
+ <meta name="robots" content="noindex" />
+ <link rel="icon" href="/favicon.ico" />
+ <style>
+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
+
+ :root {
+ --bg: #000;
+ --surface: #0a0a0a;
+ --surface-2: #111;
+ --border: #1c1c1c;
+ --border-2: #2a2a2a;
+ --text: #fafafa;
+ --text-2: #a1a1aa;
+ --text-3: #52525b;
+ --accent: #fff;
+ --accent-ink: #000;
+ --green: #4ade80;
+ --amber: #f59e0b;
+ --blue: #60a5fa;
+ --radius-sm: 8px;
+ --radius: 12px;
+ --radius-lg: 16px;
+ color-scheme: dark;
+ }
+
+ html, body {
+ height: 100%;
+ background: var(--bg);
+ color: var(--text);
+ font-family: -apple-system, 'Inter', 'Segoe UI', Roboto, sans-serif;
+ -webkit-font-smoothing: antialiased;
+ overflow: hidden;
+ }
+
+ /* ── Shell ─────────────────────────────────────────────────── */
+ #wizard {
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ }
+
+ /* ── Header ────────────────────────────────────────────────── */
+ .wz-header {
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 16px 24px;
+ border-bottom: 1px solid var(--border);
+ }
+ .wz-logo {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ text-decoration: none;
+ color: var(--text);
+ }
+ .wz-logo img { width: 24px; height: 24px; }
+ .wz-logo span {
+ font-family: 'Space Grotesk', 'Inter', sans-serif;
+ font-weight: 600;
+ font-size: 0.95rem;
+ color: var(--text);
+ }
+ .wz-progress {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ }
+ .wz-dot {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--border-2);
+ transition: background 0.3s, transform 0.3s;
+ }
+ .wz-dot.active {
+ background: var(--text);
+ transform: scale(1.3);
+ }
+ .wz-dot.done { background: var(--green); }
+ .wz-skip {
+ font-size: 13px;
+ color: var(--text-3);
+ text-decoration: none;
+ transition: color 0.15s;
+ }
+ .wz-skip:hover { color: var(--text-2); }
+
+ /* ── Steps container ───────────────────────────────────────── */
+ .wz-body {
+ flex: 1;
+ overflow: hidden;
+ position: relative;
+ }
+ .wz-step {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 32px 24px;
+ overflow-y: auto;
+ opacity: 0;
+ transform: translateX(40px);
+ pointer-events: none;
+ transition: opacity 0.35s ease, transform 0.35s ease;
+ }
+ .wz-step.active {
+ opacity: 1;
+ transform: translateX(0);
+ pointer-events: auto;
+ }
+ .wz-step.exit-left {
+ opacity: 0;
+ transform: translateX(-40px);
+ }
+ .wz-step-inner {
+ width: 100%;
+ max-width: 640px;
+ }
+
+ /* ── Typography ────────────────────────────────────────────── */
+ .wz-eyebrow {
+ font-size: 11px;
+ font-weight: 600;
+ letter-spacing: 0.12em;
+ text-transform: uppercase;
+ color: var(--text-3);
+ margin-bottom: 12px;
+ }
+ .wz-headline {
+ font-size: clamp(1.75rem, 5vw, 2.5rem);
+ font-weight: 700;
+ letter-spacing: -0.03em;
+ line-height: 1.15;
+ color: var(--text);
+ margin-bottom: 10px;
+ }
+ .wz-sub {
+ font-size: 15px;
+ color: var(--text-2);
+ line-height: 1.6;
+ margin-bottom: 32px;
+ }
+
+ /* ── Avatar cards ──────────────────────────────────────────── */
+ .wz-avatar-grid {
+ display: grid;
+ grid-template-columns: repeat(3, 1fr);
+ gap: 12px;
+ margin-bottom: 16px;
+ }
+ @media (max-width: 520px) {
+ .wz-avatar-grid { grid-template-columns: 1fr; }
+ }
+ .wz-avatar-card {
+ padding: 20px 16px 18px;
+ background: var(--surface);
+ border: 1.5px solid var(--border);
+ border-radius: var(--radius);
+ cursor: pointer;
+ text-align: center;
+ transition: border-color 0.18s, background 0.18s, transform 0.15s;
+ position: relative;
+ overflow: hidden;
+ }
+ .wz-avatar-card:hover {
+ border-color: var(--border-2);
+ background: var(--surface-2);
+ transform: translateY(-2px);
+ }
+ .wz-avatar-card.selected {
+ border-color: var(--text);
+ background: #0f0f0f;
+ }
+ .wz-avatar-card-icon {
+ font-size: 32px;
+ margin-bottom: 10px;
+ display: block;
+ line-height: 1;
+ }
+ .wz-avatar-card-label {
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--text);
+ margin-bottom: 4px;
+ }
+ .wz-avatar-card-desc {
+ font-size: 11px;
+ color: var(--text-3);
+ line-height: 1.5;
+ }
+ .wz-avatar-card-badge {
+ position: absolute;
+ top: 8px;
+ right: 8px;
+ font-size: 10px;
+ font-weight: 600;
+ background: #18181b;
+ color: var(--text-2);
+ padding: 2px 7px;
+ border-radius: 20px;
+ border: 1px solid var(--border-2);
+ }
+ .wz-avatar-preview {
+ margin-bottom: 20px;
+ padding: 16px;
+ background: var(--surface);
+ border: 1px solid var(--border);
+ border-radius: var(--radius);
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ }
+ .wz-avatar-preview-thumb {
+ width: 52px;
+ height: 52px;
+ border-radius: 50%;
+ background: #1a1a1a center/cover no-repeat;
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 22px;
+ }
+ .wz-avatar-preview-info {
+ flex: 1;
+ min-width: 0;
+ }
+ .wz-avatar-preview-name {
+ font-size: 14px;
+ font-weight: 600;
+ color: var(--text);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+ .wz-avatar-preview-status {
+ font-size: 12px;
+ color: var(--green);
+ margin-top: 2px;
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ }
+ .wz-avatar-preview-status::before {
+ content: '';
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--green);
+ display: inline-block;
+ }
+
+ /* ── Form fields ───────────────────────────────────────────── */
+ .wz-field {
+ margin-bottom: 20px;
+ }
+ .wz-label {
+ display: block;
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--text-2);
+ margin-bottom: 8px;
+ letter-spacing: 0.02em;
+ }
+ .wz-input,
+ .wz-textarea {
+ width: 100%;
+ padding: 12px 14px;
+ background: var(--surface);
+ border: 1.5px solid var(--border);
+ border-radius: var(--radius-sm);
+ color: var(--text);
+ font-size: 15px;
+ font-family: inherit;
+ outline: none;
+ transition: border-color 0.15s;
+ }
+ .wz-input:focus,
+ .wz-textarea:focus { border-color: #3f3f46; }
+ .wz-textarea { resize: vertical; min-height: 88px; line-height: 1.5; }
+
+ /* Personality chips */
+ .wz-chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin-bottom: 20px;
+ }
+ .wz-chip {
+ padding: 6px 14px;
+ background: var(--surface);
+ border: 1.5px solid var(--border);
+ border-radius: 20px;
+ font-size: 12px;
+ font-weight: 500;
+ color: var(--text-2);
+ cursor: pointer;
+ transition: border-color 0.15s, color 0.15s, background 0.15s;
+ }
+ .wz-chip:hover { border-color: var(--border-2); color: var(--text); }
+ .wz-chip.active {
+ border-color: var(--text);
+ color: var(--text);
+ background: #111;
+ }
+
+ /* Model picker */
+ .wz-model-grid {
+ display: grid;
+ grid-template-columns: repeat(3, 1fr);
+ gap: 8px;
+ margin-bottom: 20px;
+ }
+ @media (max-width: 480px) {
+ .wz-model-grid { grid-template-columns: 1fr 1fr; }
+ }
+ .wz-model-card {
+ padding: 12px 10px;
+ background: var(--surface);
+ border: 1.5px solid var(--border);
+ border-radius: var(--radius-sm);
+ cursor: pointer;
+ text-align: center;
+ transition: border-color 0.15s, background 0.15s;
+ }
+ .wz-model-card:hover {
+ border-color: var(--border-2);
+ background: var(--surface-2);
+ }
+ .wz-model-card.active {
+ border-color: var(--text);
+ background: #0f0f0f;
+ }
+ .wz-model-name {
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--text);
+ margin-bottom: 2px;
+ }
+ .wz-model-desc {
+ font-size: 10px;
+ color: var(--text-3);
+ }
+
+ /* ── Skills grid ───────────────────────────────────────────── */
+ .wz-skills-grid {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ gap: 10px;
+ margin-bottom: 16px;
+ }
+ @media (max-width: 420px) {
+ .wz-skills-grid { grid-template-columns: 1fr; }
+ }
+ .wz-skill-card {
+ display: flex;
+ align-items: flex-start;
+ gap: 12px;
+ padding: 14px;
+ background: var(--surface);
+ border: 1.5px solid var(--border);
+ border-radius: var(--radius-sm);
+ cursor: pointer;
+ transition: border-color 0.15s, background 0.15s;
+ user-select: none;
+ }
+ .wz-skill-card:hover {
+ border-color: var(--border-2);
+ background: var(--surface-2);
+ }
+ .wz-skill-card.active {
+ border-color: #3f3f46;
+ background: #0d0d10;
+ }
+ .wz-skill-check {
+ width: 18px;
+ height: 18px;
+ border-radius: 5px;
+ border: 1.5px solid var(--border-2);
+ flex-shrink: 0;
+ margin-top: 1px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 10px;
+ transition: background 0.15s, border-color 0.15s;
+ }
+ .wz-skill-card.active .wz-skill-check {
+ background: var(--text);
+ border-color: var(--text);
+ color: var(--bg);
+ }
+ .wz-skill-icon {
+ font-size: 18px;
+ flex-shrink: 0;
+ margin-top: 0;
+ line-height: 1.2;
+ }
+ .wz-skill-text { flex: 1; min-width: 0; }
+ .wz-skill-name {
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--text);
+ margin-bottom: 2px;
+ }
+ .wz-skill-desc {
+ font-size: 11px;
+ color: var(--text-3);
+ line-height: 1.5;
+ }
+
+ /* ── Deploy step ───────────────────────────────────────────── */
+ .wz-deploy-status {
+ text-align: center;
+ padding: 32px 0 24px;
+ }
+ .wz-deploy-spinner {
+ width: 40px;
+ height: 40px;
+ border: 2px solid var(--border-2);
+ border-top-color: var(--text);
+ border-radius: 50%;
+ animation: spin 0.7s linear infinite;
+ margin: 0 auto 16px;
+ }
+ @keyframes spin { to { transform: rotate(360deg); } }
+ .wz-deploy-label {
+ font-size: 15px;
+ font-weight: 500;
+ color: var(--text-2);
+ }
+ .wz-deploy-success {
+ display: none;
+ flex-direction: column;
+ gap: 16px;
+ }
+ .wz-deploy-success.show { display: flex; }
+ .wz-success-icon {
+ font-size: 40px;
+ text-align: center;
+ }
+ .wz-success-title {
+ font-size: 20px;
+ font-weight: 700;
+ text-align: center;
+ letter-spacing: -0.02em;
+ }
+ .wz-code-block {
+ background: #060606;
+ border: 1px solid var(--border);
+ border-radius: var(--radius-sm);
+ padding: 14px;
+ font-family: 'SF Mono', 'Fira Code', monospace;
+ font-size: 12px;
+ color: #86efac;
+ word-break: break-all;
+ line-height: 1.6;
+ position: relative;
+ }
+ .wz-copy-btn {
+ position: absolute;
+ top: 8px;
+ right: 8px;
+ padding: 4px 10px;
+ background: #111;
+ border: 1px solid var(--border-2);
+ border-radius: 6px;
+ font-size: 11px;
+ color: var(--text-2);
+ cursor: pointer;
+ transition: color 0.15s, border-color 0.15s;
+ }
+ .wz-copy-btn:hover { color: var(--text); border-color: #3f3f46; }
+ .wz-code-label {
+ font-size: 11px;
+ font-weight: 600;
+ color: var(--text-3);
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ margin-bottom: 6px;
+ }
+ .wz-live-link {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 12px 16px;
+ background: var(--surface);
+ border: 1px solid var(--border);
+ border-radius: var(--radius-sm);
+ text-decoration: none;
+ color: var(--text);
+ font-size: 14px;
+ transition: border-color 0.15s;
+ }
+ .wz-live-link:hover { border-color: var(--border-2); }
+ .wz-live-link-icon { font-size: 16px; flex-shrink: 0; }
+ .wz-live-link-text { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .wz-live-link-arrow { color: var(--text-3); flex-shrink: 0; }
+
+ /* ── Earn step ─────────────────────────────────────────────── */
+ .wz-earn-rows {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ margin-bottom: 24px;
+ }
+ .wz-earn-row {
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ padding: 16px;
+ background: var(--surface);
+ border: 1px solid var(--border);
+ border-radius: var(--radius-sm);
+ }
+ .wz-earn-icon {
+ font-size: 22px;
+ flex-shrink: 0;
+ width: 36px;
+ text-align: center;
+ }
+ .wz-earn-row-body { flex: 1; min-width: 0; }
+ .wz-earn-row-label {
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--text);
+ margin-bottom: 2px;
+ }
+ .wz-earn-row-desc {
+ font-size: 11px;
+ color: var(--text-3);
+ }
+ .wz-earn-input-wrap {
+ display: flex;
+ align-items: center;
+ gap: 0;
+ background: var(--surface);
+ border: 1.5px solid var(--border);
+ border-radius: var(--radius-sm);
+ overflow: hidden;
+ transition: border-color 0.15s;
+ }
+ .wz-earn-input-wrap:focus-within { border-color: #3f3f46; }
+ .wz-earn-prefix {
+ padding: 10px 10px 10px 12px;
+ color: var(--text-3);
+ font-size: 13px;
+ background: #0a0a0a;
+ border-right: 1px solid var(--border);
+ }
+ .wz-earn-num {
+ flex: 1;
+ padding: 10px 12px;
+ background: transparent;
+ border: none;
+ color: var(--text);
+ font-size: 14px;
+ font-family: inherit;
+ outline: none;
+ }
+ .wz-earn-suffix {
+ padding: 10px 12px 10px 6px;
+ color: var(--text-3);
+ font-size: 11px;
+ }
+ .wz-wallet-input-wrap {
+ display: flex;
+ align-items: center;
+ gap: 0;
+ background: var(--surface);
+ border: 1.5px solid var(--border);
+ border-radius: var(--radius-sm);
+ overflow: hidden;
+ transition: border-color 0.15s;
+ }
+ .wz-wallet-input-wrap:focus-within { border-color: #3f3f46; }
+ .wz-wallet-input {
+ flex: 1;
+ padding: 10px 14px;
+ background: transparent;
+ border: none;
+ color: var(--text);
+ font-size: 13px;
+ font-family: 'SF Mono', monospace;
+ outline: none;
+ }
+ .wz-wallet-input::placeholder { color: var(--text-3); font-family: -apple-system, sans-serif; }
+ .wz-wallet-chain {
+ padding: 10px 12px;
+ background: #0a0a0a;
+ border-left: 1px solid var(--border);
+ font-size: 11px;
+ font-weight: 600;
+ color: var(--text-3);
+ }
+
+ /* ── Footer buttons ────────────────────────────────────────── */
+ .wz-footer {
+ flex-shrink: 0;
+ padding: 16px 24px;
+ border-top: 1px solid var(--border);
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ }
+ .wz-btn {
+ padding: 11px 22px;
+ border-radius: var(--radius-sm);
+ font-size: 14px;
+ font-weight: 600;
+ cursor: pointer;
+ transition: opacity 0.15s, background 0.15s;
+ border: none;
+ font-family: inherit;
+ }
+ .wz-btn:disabled { opacity: 0.35; cursor: not-allowed; }
+ .wz-btn-primary {
+ background: var(--accent);
+ color: var(--accent-ink);
+ }
+ .wz-btn-primary:hover:not(:disabled) { opacity: 0.88; }
+ .wz-btn-ghost {
+ background: transparent;
+ color: var(--text-2);
+ border: 1px solid var(--border-2);
+ }
+ .wz-btn-ghost:hover:not(:disabled) { color: var(--text); border-color: #3f3f46; }
+ .wz-btn-skip {
+ background: none;
+ border: none;
+ color: var(--text-3);
+ font-size: 13px;
+ padding: 11px 4px;
+ cursor: pointer;
+ font-family: inherit;
+ transition: color 0.15s;
+ }
+ .wz-btn-skip:hover { color: var(--text-2); }
+
+ /* ── Error toast ───────────────────────────────────────────── */
+ .wz-toast {
+ position: fixed;
+ bottom: 80px;
+ left: 50%;
+ transform: translateX(-50%) translateY(20px);
+ background: #1c0a0a;
+ border: 1px solid #7f1d1d;
+ color: #f87171;
+ padding: 10px 18px;
+ border-radius: 8px;
+ font-size: 13px;
+ z-index: 100;
+ opacity: 0;
+ transition: opacity 0.2s, transform 0.2s;
+ pointer-events: none;
+ white-space: nowrap;
+ }
+ .wz-toast.show {
+ opacity: 1;
+ transform: translateX(-50%) translateY(0);
+ }
+
+ /* ── Divider ───────────────────────────────────────────────── */
+ .wz-divider {
+ height: 1px;
+ background: var(--border);
+ margin: 20px 0;
+ }
+ </style>
+</head>
+<body>
+<div id="wizard">
+ <!-- Header -->
+ <header class="wz-header">
+ <a href="/" class="wz-logo">
+ <img src="/three.svg" alt="" />
+ <span>three.ws</span>
+ </a>
+ <div class="wz-progress" id="wz-progress" role="progressbar" aria-label="Wizard progress" aria-valuenow="1" aria-valuemax="5">
+ <div class="wz-dot active" data-step="1"></div>
+ <div class="wz-dot" data-step="2"></div>
+ <div class="wz-dot" data-step="3"></div>
+ <div class="wz-dot" data-step="4"></div>
+ <div class="wz-dot" data-step="5"></div>
+ </div>
+ <a href="/dashboard" class="wz-skip" id="wz-header-skip">Skip setup</a>
+ </header>
+
+ <!-- Step body -->
+ <main class="wz-body" id="wz-body">
+
+ <!-- Step 1: Avatar -->
+ <section class="wz-step active" id="step-1" aria-label="Step 1: Create your avatar">
+ <div class="wz-step-inner">
+ <p class="wz-eyebrow">Step 1 of 5</p>
+ <h1 class="wz-headline">Give your agent a body</h1>
+ <p class="wz-sub">Start with a 3D avatar. Pick a creation method or skip and name your agent first.</p>
+
+ <div id="avatar-preview" hidden>
+ <div class="wz-avatar-preview">
+ <div class="wz-avatar-preview-thumb" id="ap-thumb">🤖</div>
+ <div class="wz-avatar-preview-info">
+ <div class="wz-avatar-preview-name" id="ap-name">Avatar ready</div>
+ <div class="wz-avatar-preview-status">Ready to use</div>
+ </div>
+ </div>
+ </div>
+
+ <div class="wz-avatar-grid" id="avatar-method-grid">
+ <button class="wz-avatar-card" id="btn-selfie" type="button">
+ <span class="wz-avatar-card-badge">2 min</span>
+ <span class="wz-avatar-card-icon">🤳</span>
+ <div class="wz-avatar-card-label">Take a selfie</div>
+ <div class="wz-avatar-card-desc">One photo → rigged 3D avatar</div>
+ </button>
+ <button class="wz-avatar-card" id="btn-upload" type="button">
+ <span class="wz-avatar-card-icon">📦</span>
+ <div class="wz-avatar-card-label">Upload GLB</div>
+ <div class="wz-avatar-card-desc">Bring your own 3D model</div>
+ </button>
+ <button class="wz-avatar-card" id="btn-editor" type="button">
+ <span class="wz-avatar-card-icon">🎨</span>
+ <div class="wz-avatar-card-label">3D editor</div>
+ <div class="wz-avatar-card-desc">Build from scratch in-browser</div>
+ </button>
+ </div>
+
+ <input type="file" id="glb-file-input" accept=".glb,.gltf" hidden />
+ </div>
+ </section>
+
+ <!-- Step 2: Name & Brain -->
+ <section class="wz-step" id="step-2" aria-label="Step 2: Name your agent">
+ <div class="wz-step-inner">
+ <p class="wz-eyebrow">Step 2 of 5</p>
+ <h1 class="wz-headline">Name your agent</h1>
+ <p class="wz-sub">Give it a personality. You can change this any time.</p>
+
+ <div class="wz-field">
+ <label class="wz-label" for="agent-name">Agent name</label>
+ <input class="wz-input" id="agent-name" type="text" placeholder="e.g. Luna, Apex, Nova" maxlength="100" autocomplete="off" />
+ </div>
+
+ <div class="wz-field">
+ <label class="wz-label" for="agent-bio">Personality &amp; bio <span style="color:var(--text-3);font-weight:400">(optional)</span></label>
+ <textarea class="wz-textarea" id="agent-bio" placeholder="e.g. A crypto-savvy assistant that tracks Solana token launches and helps users make informed trading decisions." maxlength="500"></textarea>
+ </div>
+
+ <p class="wz-label" style="margin-bottom:10px">Quick personality</p>
+ <div class="wz-chips" id="personality-chips">
+ <button type="button" class="wz-chip" data-preset="crypto">Crypto advisor</button>
+ <button type="button" class="wz-chip" data-preset="artist">Creative artist</button>
+ <button type="button" class="wz-chip" data-preset="community">Community manager</button>
+ <button type="button" class="wz-chip" data-preset="defi">DeFi expert</button>
+ <button type="button" class="wz-chip" data-preset="assistant">Helpful assistant</button>
+ </div>
+
+ <p class="wz-label" style="margin-bottom:10px">AI model</p>
+ <div class="wz-model-grid" id="model-grid">
+ <button type="button" class="wz-model-card active" data-model="claude-sonnet-4-5">
+ <div class="wz-model-name">Claude Sonnet</div>
+ <div class="wz-model-desc">Smart & fast</div>
+ </button>
+ <button type="button" class="wz-model-card" data-model="gpt-4o">
+ <div class="wz-model-name">GPT-4o</div>
+ <div class="wz-model-desc">OpenAI flagship</div>
+ </button>
+ <button type="button" class="wz-model-card" data-model="llama-3.3-70b">
+ <div class="wz-model-name">Llama 3.3</div>
+ <div class="wz-model-desc">Open source</div>
+ </button>
+ </div>
+ </div>
+ </section>
+
+ <!-- Step 3: Skills -->
+ <section class="wz-step" id="step-3" aria-label="Step 3: Choose skills">
+ <div class="wz-step-inner">
+ <p class="wz-eyebrow">Step 3 of 5</p>
+ <h1 class="wz-headline">Give it superpowers</h1>
+ <p class="wz-sub">Each skill extends what your agent can do. Enable any combination.</p>
+
+ <div class="wz-skills-grid" id="skills-grid">
+ <button type="button" class="wz-skill-card active" data-skill="memory" aria-pressed="true">
+ <div class="wz-skill-check">✓</div>
+ <div class="wz-skill-icon">🧠</div>
+ <div class="wz-skill-text">
+ <div class="wz-skill-name">Memory</div>
+ <div class="wz-skill-desc">Remember users & context across sessions</div>
+ </div>
+ </button>
+ <button type="button" class="wz-skill-card active" data-skill="think" aria-pressed="true">
+ <div class="wz-skill-check">✓</div>
+ <div class="wz-skill-icon">💭</div>
+ <div class="wz-skill-text">
+ <div class="wz-skill-name">Deep thinking</div>
+ <div class="wz-skill-desc">Reason step-by-step before answering</div>
+ </div>
+ </button>
+ <button type="button" class="wz-skill-card" data-skill="pumpfun" aria-pressed="false">
+ <div class="wz-skill-check"></div>
+ <div class="wz-skill-icon">🚀</div>
+ <div class="wz-skill-text">
+ <div class="wz-skill-name">pump.fun</div>
+ <div class="wz-skill-desc">Monitor Solana token launches & whale moves</div>
+ </div>
+ </button>
+ <button type="button" class="wz-skill-card" data-skill="solana" aria-pressed="false">
+ <div class="wz-skill-check"></div>
+ <div class="wz-skill-icon">◎</div>
+ <div class="wz-skill-text">
+ <div class="wz-skill-name">Solana wallet</div>
+ <div class="wz-skill-desc">Execute on-chain swaps & check balances</div>
+ </div>
+ </button>
+ <button type="button" class="wz-skill-card" data-skill="x402" aria-pressed="false">
+ <div class="wz-skill-check"></div>
+ <div class="wz-skill-icon">💳</div>
+ <div class="wz-skill-text">
+ <div class="wz-skill-name">x402 payments</div>
+ <div class="wz-skill-desc">Accept USDC micropayments per API call</div>
+ </div>
+ </button>
+ <button type="button" class="wz-skill-card" data-skill="web" aria-pressed="false">
+ <div class="wz-skill-check"></div>
+ <div class="wz-skill-icon">🌐</div>
+ <div class="wz-skill-text">
+ <div class="wz-skill-name">Web research</div>
+ <div class="wz-skill-desc">Browse URLs & extract live information</div>
+ </div>
+ </button>
+ </div>
+ </div>
+ </section>
+
+ <!-- Step 4: Deploy -->
+ <section class="wz-step" id="step-4" aria-label="Step 4: Deploy your agent">
+ <div class="wz-step-inner">
+ <p class="wz-eyebrow">Step 4 of 5</p>
+ <h1 class="wz-headline">Your agent is live</h1>
+ <p class="wz-sub">We created your agent and generated an embeddable widget.</p>
+
+ <div class="wz-deploy-status" id="deploy-status">
+ <div class="wz-deploy-spinner"></div>
+ <div class="wz-deploy-label" id="deploy-label">Creating your agent…</div>
+ </div>
+
+ <div class="wz-deploy-success" id="deploy-success">
+ <div class="wz-success-icon">🎉</div>
+ <div class="wz-success-title" id="deploy-agent-name">Your agent is live</div>
+
+ <div>
+ <p class="wz-code-label">Live page</p>
+ <a class="wz-live-link" id="deploy-live-link" href="#" target="_blank" rel="noopener">
+ <span class="wz-live-link-icon">🔗</span>
+ <span class="wz-live-link-text" id="deploy-live-url">…</span>
+ <span class="wz-live-link-arrow">↗</span>
+ </a>
+ </div>
+
+ <div>
+ <p class="wz-code-label">Embed snippet</p>
+ <div class="wz-code-block" id="embed-code-block">
+ <button class="wz-copy-btn" id="copy-embed" type="button">Copy</button>
+ <code id="embed-code"></code>
+ </div>
+ </div>
+ </div>
+ </div>
+ </section>
+
+ <!-- Step 5: Earn -->
+ <section class="wz-step" id="step-5" aria-label="Step 5: Start earning">
+ <div class="wz-step-inner">
+ <p class="wz-eyebrow">Step 5 of 5</p>
+ <h1 class="wz-headline">Start earning</h1>
+ <p class="wz-sub">Set a price for your agent's API and connect a wallet to receive payouts. Both are optional.</p>
+
+ <div class="wz-earn-rows">
+ <div class="wz-earn-row">
+ <div class="wz-earn-icon">💰</div>
+ <div class="wz-earn-row-body">
+ <div class="wz-earn-row-label">Price per API call</div>
+ <div class="wz-earn-row-desc">Others pay USDC every time they call your agent's API</div>
+ </div>
+ <div>
+ <div class="wz-earn-input-wrap">
+ <span class="wz-earn-prefix">$</span>
+ <input type="number" class="wz-earn-num" id="earn-price" min="0" max="100" step="0.001" placeholder="0.001" />
+ <span class="wz-earn-suffix">USDC</span>
+ </div>
+ </div>
+ </div>
+
+ <div class="wz-earn-row">
+ <div class="wz-earn-icon">◎</div>
+ <div class="wz-earn-row-body">
+ <div class="wz-earn-row-label">Payout wallet</div>
+ <div class="wz-earn-row-desc">Solana or EVM address for withdrawals</div>
+ </div>
+ </div>
+ <div style="padding: 0 0 4px;">
+ <div class="wz-wallet-input-wrap">
+ <input type="text" class="wz-wallet-input" id="earn-wallet" placeholder="Enter Solana or EVM wallet address" />
+ <span class="wz-wallet-chain" id="earn-chain">SOL</span>
+ </div>
+ </div>
+ </div>
+
+ <div class="wz-divider"></div>
+
+ <p style="font-size:12px;color:var(--text-3);text-align:center;margin-bottom:16px">
+ You can always update pricing and wallets from your dashboard.
+ </p>
+ </div>
+ </section>
+
+ </main>
+
+ <!-- Footer -->
+ <footer class="wz-footer" id="wz-footer">
+ <button type="button" class="wz-btn wz-btn-ghost" id="btn-back" hidden>Back</button>
+ <div style="flex:1"></div>
+ <button type="button" class="wz-btn-skip" id="btn-skip-step" hidden>Skip this step</button>
+ <button type="button" class="wz-btn wz-btn-primary" id="btn-next">Continue</button>
+ </footer>
+</div>
+
+<div class="wz-toast" id="wz-toast" role="alert" aria-live="assertive"></div>
+
+<script type="module" src="/src/start.js"></script>
+</body>
+</html>
diff --git a/pages/unstoppable.html b/pages/unstoppable.html
new file mode 100644
index 000000000..12a739426
--- /dev/null
+++ b/pages/unstoppable.html
@@ -0,0 +1,589 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>Unstoppable Agent — three.ws</title>
+ <meta name="description" content="A self-sustaining AI agent that owns its wallet, pays for tools via x402, earns USDC from a service it runs, and re-invests to survive." />
+ <meta property="og:title" content="Unstoppable Agent — three.ws" />
+ <meta property="og:description" content="An AI that earns its own living. Every query to its status API funds its continued existence." />
+ <meta name="twitter:card" content="summary_large_image" />
+ <link rel="icon" href="/favicon.ico" />
+ <style>
+ :root {
+ color-scheme: dark;
+ --bg: #050505;
+ --surface-0: #0b0b0b;
+ --surface-1: #111111;
+ --surface-2: #181818;
+ --surface-3: #1e1e1e;
+ --hairline: #1c1c1c;
+ --hairline-strong: #2a2a2a;
+ --text: #f6f6f6;
+ --text-2: #a8a8a8;
+ --text-3: #6a6a6a;
+ --text-4: #4a4a4a;
+ --accent: #ffffff;
+ --green: #22c55e;
+ --green-dim: #16a34a;
+ --amber: #f59e0b;
+ --amber-dim: #b45309;
+ --red: #ef4444;
+ --red-dim: #b91c1c;
+ --font-display: "Inter Tight", "Inter", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
+ --font-body: "Inter", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
+ --font-mono: "JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace;
+ }
+ * { box-sizing: border-box; }
+ html, body { margin: 0; padding: 0; background: var(--bg); color: var(--text); font-family: var(--font-body); }
+ body {
+ font-size: 15.5px; line-height: 1.55;
+ min-height: 100vh; overflow-x: hidden;
+ -webkit-font-smoothing: antialiased;
+ text-rendering: optimizeLegibility;
+ }
+ a { color: inherit; text-decoration: none; }
+ button { font-family: inherit; cursor: pointer; }
+ ::selection { background: var(--text); color: var(--bg); }
+ .wrap-1280 { max-width: 1280px; margin: 0 auto; padding-left: 32px; padding-right: 32px; }
+ @media (max-width: 720px) { .wrap-1280 { padding-left: 20px; padding-right: 20px; } }
+
+ /* ── NAV ─────────────────────────────────────────────────── */
+ .nav {
+ position: sticky; top: 0; z-index: 100;
+ border-bottom: 1px solid var(--hairline);
+ background: rgba(5,5,5,0.88);
+ backdrop-filter: blur(20px) saturate(140%);
+ }
+ .nav-inner {
+ display: flex; align-items: center; gap: 32px;
+ padding: 16px 32px; max-width: 1440px; margin: 0 auto;
+ }
+ .brand {
+ display: flex; align-items: center; gap: 10px;
+ font-family: var(--font-display);
+ font-weight: 600; letter-spacing: -0.025em; font-size: 16.5px;
+ flex-shrink: 0;
+ }
+ .brand-mark {
+ width: 18px; height: 18px;
+ border: 1px solid var(--text); border-radius: 3px;
+ position: relative;
+ }
+ .brand-mark::after {
+ content: ""; position: absolute; inset: 4px;
+ background: var(--text);
+ }
+ .nav-main { display: flex; gap: 2px; margin-left: 12px; flex: 1; }
+ .nav-main a {
+ padding: 7px 12px; font-size: 14px; font-weight: 450;
+ color: var(--text-2); transition: color 0.12s;
+ }
+ .nav-main a:hover { color: var(--text); }
+ .nav-main a.active { color: var(--text); }
+ .nav-end { display: flex; align-items: center; gap: 4px; }
+ .nav-end a { padding: 7px 12px; font-size: 14px; font-weight: 450; color: var(--text-2); }
+ .nav-end a:hover { color: var(--text); }
+ .nav-end .console {
+ color: var(--text); font-weight: 500;
+ border: 1px solid var(--hairline-strong);
+ padding: 7px 16px; border-radius: 7px; margin-left: 6px;
+ transition: border-color 0.15s, background 0.15s;
+ }
+ .nav-end .console:hover { border-color: var(--text); background: rgba(255,255,255,0.04); }
+ @media (max-width: 880px) {
+ .nav-main { display: none; }
+ .nav-inner { padding: 14px 20px; gap: 16px; }
+ }
+
+ /* ── HERO ────────────────────────────────────────────────── */
+ .hero {
+ text-align: center;
+ padding: 80px 32px 64px;
+ border-bottom: 1px solid var(--hairline);
+ position: relative;
+ }
+ .hero-avatar {
+ width: 64px; height: 64px; border-radius: 50%;
+ margin: 0 auto 28px;
+ position: relative;
+ display: flex; align-items: center; justify-content: center;
+ }
+ .agent-dot {
+ width: 24px; height: 24px; border-radius: 50%;
+ background: var(--green);
+ box-shadow: 0 0 0 0 var(--green);
+ animation: pulse-agent 2.4s ease-in-out infinite;
+ }
+ .agent-dot.conservation { background: var(--amber); box-shadow: 0 0 0 0 var(--amber); }
+ .agent-dot.halted { background: var(--red); box-shadow: 0 0 0 0 var(--red); animation: none; }
+ @keyframes pulse-agent {
+ 0% { box-shadow: 0 0 0 0 rgba(34,197,94,0.5); }
+ 70% { box-shadow: 0 0 0 16px rgba(34,197,94,0); }
+ 100% { box-shadow: 0 0 0 0 rgba(34,197,94,0); }
+ }
+ .hero-avatar-ring {
+ position: absolute; inset: 0; border-radius: 50%;
+ border: 1px solid var(--hairline-strong);
+ }
+
+ .balance-display {
+ font-family: var(--font-mono);
+ font-size: clamp(40px, 7vw, 84px);
+ font-weight: 600; letter-spacing: -0.04em;
+ color: var(--text); margin: 0 0 16px;
+ font-variant-numeric: tabular-nums;
+ transition: color 0.3s;
+ }
+ .balance-display.updating { color: var(--green); }
+
+ .hero-badges {
+ display: flex; align-items: center; justify-content: center;
+ gap: 12px; flex-wrap: wrap; margin-bottom: 12px;
+ }
+ .badge {
+ display: inline-flex; align-items: center; gap: 7px;
+ padding: 5px 12px; border-radius: 100px;
+ font-family: var(--font-mono); font-size: 11px;
+ font-weight: 600; letter-spacing: 0.12em; text-transform: uppercase;
+ }
+ .badge-running { background: rgba(34,197,94,0.12); color: var(--green); border: 1px solid rgba(34,197,94,0.25); }
+ .badge-conservation { background: rgba(245,158,11,0.12); color: var(--amber); border: 1px solid rgba(245,158,11,0.25); }
+ .badge-halted { background: rgba(239,68,68,0.12); color: var(--red); border: 1px solid rgba(239,68,68,0.25); }
+ .badge-runway { background: var(--surface-2); color: var(--text-2); border: 1px solid var(--hairline-strong); }
+ .badge-dot {
+ width: 6px; height: 6px; border-radius: 50%;
+ background: currentColor;
+ }
+
+ .hero-updated {
+ font-family: var(--font-mono); font-size: 11.5px;
+ color: var(--text-4); letter-spacing: 0.08em;
+ margin-top: 8px;
+ }
+
+ .payment-notice {
+ margin: 32px auto 0;
+ max-width: 520px;
+ padding: 16px 20px;
+ border: 1px solid var(--hairline-strong);
+ border-radius: 10px;
+ background: var(--surface-1);
+ font-size: 13.5px;
+ color: var(--text-3);
+ line-height: 1.5;
+ }
+ .payment-notice strong { color: var(--text-2); }
+ .payment-price {
+ font-family: var(--font-mono); font-size: 14px;
+ color: var(--text); font-weight: 600;
+ }
+
+ /* ── STATS ROW ───────────────────────────────────────────── */
+ .stats-row {
+ display: flex; border-bottom: 1px solid var(--hairline);
+ }
+ .stat-cell {
+ flex: 1; padding: 24px 28px;
+ border-right: 1px solid var(--hairline);
+ }
+ .stat-cell:last-child { border-right: none; }
+ .stat-val {
+ font-family: var(--font-display); font-size: 26px;
+ font-weight: 600; letter-spacing: -0.025em;
+ color: var(--text); font-variant-numeric: tabular-nums;
+ }
+ .stat-val.pos { color: var(--green); }
+ .stat-val.neg { color: var(--red); }
+ .stat-lbl {
+ font-family: var(--font-mono); font-size: 11px;
+ letter-spacing: 0.15em; text-transform: uppercase;
+ color: var(--text-3); margin-top: 4px;
+ }
+ @media (max-width: 720px) {
+ .stats-row { flex-wrap: wrap; }
+ .stat-cell { flex: 1 0 50%; border-bottom: 1px solid var(--hairline); }
+ }
+
+ /* ── MAIN GRID ───────────────────────────────────────────── */
+ .main-grid {
+ display: grid; grid-template-columns: 1fr 1.4fr;
+ gap: 0;
+ border-bottom: 1px solid var(--hairline);
+ }
+ @media (max-width: 900px) { .main-grid { grid-template-columns: 1fr; } }
+
+ .panel {
+ padding: 32px;
+ border-right: 1px solid var(--hairline);
+ }
+ .panel:last-child { border-right: none; }
+ @media (max-width: 900px) {
+ .panel { border-right: none; border-bottom: 1px solid var(--hairline); }
+ }
+
+ .panel-title {
+ font-family: var(--font-mono); font-size: 11px;
+ letter-spacing: 0.2em; text-transform: uppercase;
+ color: var(--text-3); margin: 0 0 20px;
+ }
+
+ /* Reflection card */
+ .reflection-card {
+ padding: 20px;
+ border: 1px solid var(--hairline-strong);
+ border-radius: 10px;
+ background: var(--surface-1);
+ position: relative;
+ }
+ .reflection-card::before {
+ content: '"';
+ position: absolute; top: 8px; left: 16px;
+ font-size: 48px; line-height: 1;
+ color: var(--text-4); font-family: var(--font-display);
+ font-weight: 700;
+ }
+ .reflection-text {
+ padding-top: 20px;
+ font-size: 14.5px; line-height: 1.65;
+ color: var(--text-2);
+ }
+ .reflection-strategy {
+ margin-top: 12px; padding-top: 12px;
+ border-top: 1px solid var(--hairline);
+ font-size: 13px; color: var(--text-3);
+ font-style: italic;
+ }
+ .reflection-date {
+ margin-top: 12px;
+ font-family: var(--font-mono); font-size: 11px;
+ letter-spacing: 0.08em; color: var(--text-4);
+ }
+
+ /* Donate section */
+ .donate-block {
+ margin-top: 28px; padding: 20px;
+ border: 1px solid var(--hairline-strong);
+ border-radius: 10px;
+ background: var(--surface-1);
+ }
+ .donate-block .donate-label {
+ font-size: 13.5px; color: var(--text-3); margin-bottom: 12px;
+ }
+ .btn {
+ display: inline-flex; align-items: center; gap: 10px;
+ padding: 11px 20px; border-radius: 8px;
+ font-size: 13.5px; font-weight: 500;
+ border: 1px solid var(--hairline-strong);
+ background: transparent; color: var(--text);
+ transition: border-color 0.15s, background 0.15s;
+ cursor: pointer; text-decoration: none; font-family: inherit;
+ }
+ .btn:hover { border-color: var(--text); background: rgba(255,255,255,0.04); }
+ .btn.primary {
+ background: var(--text); color: var(--bg);
+ border-color: var(--text); font-weight: 550;
+ }
+ .btn.primary:hover { background: #fff; }
+
+ /* Activity feed */
+ .activity-feed {
+ display: flex; flex-direction: column; gap: 2px;
+ max-height: 520px;
+ overflow-y: auto;
+ }
+ .activity-feed::-webkit-scrollbar { width: 4px; }
+ .activity-feed::-webkit-scrollbar-track { background: transparent; }
+ .activity-feed::-webkit-scrollbar-thumb { background: var(--hairline-strong); border-radius: 2px; }
+
+ .activity-row {
+ display: flex; align-items: flex-start; gap: 12px;
+ padding: 10px 0;
+ border-bottom: 1px solid var(--hairline);
+ }
+ .activity-row:last-child { border-bottom: none; }
+
+ .action-badge {
+ flex-shrink: 0;
+ display: inline-flex; align-items: center;
+ padding: 3px 8px; border-radius: 5px;
+ font-family: var(--font-mono); font-size: 10px;
+ font-weight: 600; letter-spacing: 0.08em; text-transform: uppercase;
+ min-width: 68px; justify-content: center;
+ }
+ .action-badge.think { background: rgba(139,92,246,0.15); color: #a78bfa; border: 1px solid rgba(139,92,246,0.2); }
+ .action-badge.earn { background: rgba(34,197,94,0.12); color: var(--green); border: 1px solid rgba(34,197,94,0.2); }
+ .action-badge.reflect { background: rgba(59,130,246,0.12); color: #60a5fa; border: 1px solid rgba(59,130,246,0.2); }
+ .action-badge.idle { background: rgba(100,100,100,0.1); color: var(--text-3); border: 1px solid var(--hairline-strong); }
+ .action-badge.search { background: rgba(245,158,11,0.12); color: var(--amber); border: 1px solid rgba(245,158,11,0.2); }
+ .action-badge.post_status { background: rgba(20,184,166,0.12); color: #2dd4bf; border: 1px solid rgba(20,184,166,0.2); }
+ .action-badge.status_check { background: rgba(34,197,94,0.12); color: var(--green); border: 1px solid rgba(34,197,94,0.2); }
+
+ .activity-content { flex: 1; min-width: 0; }
+ .activity-desc {
+ font-size: 13px; color: var(--text-2);
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
+ }
+ .activity-meta {
+ display: flex; gap: 10px; margin-top: 3px;
+ font-family: var(--font-mono); font-size: 10.5px;
+ color: var(--text-4); letter-spacing: 0.04em;
+ }
+ .activity-cost { color: var(--red-dim); }
+ .activity-revenue { color: var(--green-dim); }
+
+ /* ── EARN SECTION ────────────────────────────────────────── */
+ section.earn-section {
+ padding: 56px 0;
+ border-bottom: 1px solid var(--hairline);
+ }
+ .earn-inner {
+ display: grid; grid-template-columns: 1fr 1.2fr;
+ gap: 48px; align-items: center;
+ }
+ @media (max-width: 900px) { .earn-inner { grid-template-columns: 1fr; } }
+ .earn-heading {
+ font-family: var(--font-display);
+ font-size: clamp(28px, 3.5vw, 44px);
+ line-height: 1.05; letter-spacing: -0.035em;
+ font-weight: 600; margin: 0 0 16px;
+ }
+ .earn-sub { font-size: 15.5px; color: var(--text-2); line-height: 1.6; }
+
+ .code-block {
+ background: var(--surface-1);
+ border: 1px solid var(--hairline-strong);
+ border-radius: 10px;
+ padding: 20px 24px;
+ overflow-x: auto;
+ }
+ .code-block pre {
+ margin: 0; padding: 0;
+ font-family: var(--font-mono); font-size: 12.5px;
+ line-height: 1.65; color: var(--text-2);
+ white-space: pre;
+ }
+ .code-block .cm-keyword { color: #c084fc; }
+ .code-block .cm-string { color: #86efac; }
+ .code-block .cm-comment { color: var(--text-4); }
+ .code-block .cm-header { color: #7dd3fc; }
+
+ /* ── MECHANICS ───────────────────────────────────────────── */
+ section.mechanics {
+ padding: 56px 0;
+ border-bottom: 1px solid var(--hairline);
+ }
+ .mechanics-grid {
+ display: grid; grid-template-columns: repeat(3, 1fr);
+ gap: 1px; background: var(--hairline);
+ border: 1px solid var(--hairline); border-radius: 12px; overflow: hidden;
+ margin-top: 40px;
+ }
+ @media (max-width: 720px) { .mechanics-grid { grid-template-columns: 1fr; } }
+ .mechanic-cell {
+ background: var(--surface-0);
+ padding: 28px 24px;
+ }
+ .mechanic-num {
+ font-family: var(--font-mono); font-size: 11px;
+ letter-spacing: 0.15em; text-transform: uppercase;
+ color: var(--text-4); margin-bottom: 10px;
+ }
+ .mechanic-title {
+ font-family: var(--font-display); font-size: 18px;
+ font-weight: 600; letter-spacing: -0.02em;
+ margin-bottom: 8px;
+ }
+ .mechanic-body { font-size: 14px; color: var(--text-2); line-height: 1.6; }
+
+ /* ── TOAST ───────────────────────────────────────────────── */
+ #toast {
+ position: fixed; bottom: 28px; left: 50%; transform: translateX(-50%) translateY(20px);
+ background: var(--surface-2); border: 1px solid var(--hairline-strong);
+ border-radius: 8px; padding: 12px 20px;
+ font-size: 13.5px; color: var(--text);
+ opacity: 0; transition: opacity 0.2s, transform 0.2s;
+ pointer-events: none; z-index: 999; white-space: nowrap;
+ }
+ #toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }
+
+ /* ── EMPTY / LOADING ─────────────────────────────────────── */
+ .empty-state {
+ padding: 40px; text-align: center;
+ font-size: 13.5px; color: var(--text-3);
+ }
+ .skeleton {
+ background: var(--surface-2);
+ border-radius: 5px;
+ animation: shimmer 1.6s ease-in-out infinite;
+ }
+ @keyframes shimmer { 0%, 100% { opacity: 0.4; } 50% { opacity: 0.8; } }
+ </style>
+</head>
+<body>
+ <!-- NAV -->
+ <nav class="nav">
+ <div class="nav-inner">
+ <a href="/" class="brand">
+ <span class="brand-mark"></span>
+ three.ws
+ </a>
+ <div class="nav-main">
+ <a href="/discover">Discover</a>
+ <a href="/marketplace">Marketplace</a>
+ <a href="/walk">Walk</a>
+ <a href="/unstoppable" class="active">Unstoppable Agent</a>
+ </div>
+ <div class="nav-end">
+ <a href="/dashboard" class="console">Dashboard</a>
+ </div>
+ </div>
+ </nav>
+
+ <!-- HERO -->
+ <div class="hero">
+ <div class="hero-avatar">
+ <div class="agent-dot" id="agentDot"></div>
+ <div class="hero-avatar-ring"></div>
+ </div>
+
+ <div class="balance-display" id="balanceDisplay">—</div>
+
+ <div class="hero-badges">
+ <span class="badge badge-running" id="statusBadge">
+ <span class="badge-dot"></span>
+ <span id="statusText">Loading</span>
+ </span>
+ <span class="badge badge-runway" id="runwayBadge">Runway: —</span>
+ </div>
+
+ <div class="hero-updated" id="heroUpdated">Fetching live data...</div>
+
+ <div class="payment-notice" id="paymentNotice" style="display:none">
+ <p>
+ Live data costs <span class="payment-price" id="priceDisplay">$0.01</span> per query.
+ <strong>Every request directly funds this agent's operation.</strong>
+ </p>
+ <p style="margin: 8px 0 0; color: var(--text-4);">
+ Showing last cached reading. Send an x402 payment to see live data.
+ </p>
+ </div>
+ </div>
+
+ <!-- STATS ROW -->
+ <div class="stats-row" id="statsRow">
+ <div class="stat-cell">
+ <div class="stat-val" id="stat24hEarnings">—</div>
+ <div class="stat-lbl">24h Earnings</div>
+ </div>
+ <div class="stat-cell">
+ <div class="stat-val" id="stat24hCosts">—</div>
+ <div class="stat-lbl">24h Costs</div>
+ </div>
+ <div class="stat-cell">
+ <div class="stat-val" id="statLifetimeNet">—</div>
+ <div class="stat-lbl">Lifetime Net</div>
+ </div>
+ </div>
+
+ <!-- MAIN GRID: reflection + activity feed -->
+ <div class="main-grid">
+ <!-- Left: reflection + donate -->
+ <div class="panel">
+ <div class="panel-title">Latest Reflection</div>
+
+ <div id="reflectionCard" class="reflection-card">
+ <div class="reflection-text skeleton" style="height: 80px; border-radius: 6px;"></div>
+ </div>
+
+ <div class="donate-block" style="margin-top: 28px;">
+ <div class="donate-label">Keep it alive — donate $0.10 USDC to extend the agent's runway.</div>
+ <button class="btn primary" id="donateBtn" onclick="window.__unstoppable.donate()">
+ Donate $0.10
+ </button>
+ </div>
+ </div>
+
+ <!-- Right: activity feed -->
+ <div class="panel">
+ <div class="panel-title">Activity Feed</div>
+ <div class="activity-feed" id="activityFeed">
+ <div class="empty-state">Loading activity...</div>
+ </div>
+ </div>
+ </div>
+
+ <!-- EARN SECTION -->
+ <section class="earn-section">
+ <div class="wrap-1280">
+ <div class="earn-inner">
+ <div>
+ <div class="panel-title" style="margin-bottom: 16px;">How It Earns</div>
+ <h2 class="earn-heading">Query its status.<br>It earns USDC.</h2>
+ <p class="earn-sub">
+ Every call to the status endpoint is a micropayment via x402.
+ The agent collects the revenue, re-invests in thinking, and survives.
+ No humans in the loop — just code and crypto.
+ </p>
+ </div>
+ <div class="code-block">
+ <pre><span class="cm-comment"># Query the agent's live status (costs $0.01 USDC)</span>
+<span class="cm-keyword">curl</span> -X GET https://three.ws/api/agents/unstoppable-status \
+ -H <span class="cm-string">"X-Payment: &lt;your-x402-payment-header&gt;"</span>
+
+<span class="cm-comment"># First call returns 402 with payment requirements</span>
+<span class="cm-comment"># Retry with the payment header to get live data</span>
+<span class="cm-comment"># Revenue goes directly to the agent's treasury</span></pre>
+ </div>
+ </div>
+ </div>
+ </section>
+
+ <!-- MECHANICS -->
+ <section class="mechanics">
+ <div class="wrap-1280">
+ <div class="panel-title" style="margin-bottom: 8px;">How It Works</div>
+ <h2 style="font-family: var(--font-display); font-size: clamp(28px,3.5vw,44px); font-weight:600; letter-spacing:-0.035em; margin:0;">
+ Fully autonomous economy
+ </h2>
+ <p style="color: var(--text-2); margin: 16px 0 0; font-size:15.5px; max-width:540px; line-height:1.6;">
+ Every 5 minutes, this agent senses, thinks, earns, and re-invests.
+ Its entire economy runs on x402 micropayments.
+ </p>
+
+ <div class="mechanics-grid">
+ <div class="mechanic-cell">
+ <div class="mechanic-num">01 — Earn</div>
+ <div class="mechanic-title">Paid Status API</div>
+ <div class="mechanic-body">
+ Agents and humans pay $0.01 per status query via x402.
+ Revenue lands directly in the treasury.
+ </div>
+ </div>
+ <div class="mechanic-cell">
+ <div class="mechanic-num">02 — Think</div>
+ <div class="mechanic-title">LLM-Driven Planning</div>
+ <div class="mechanic-body">
+ Each cron tick, the agent calls Claude Haiku to plan its next moves,
+ budget-gated so it never overspends.
+ </div>
+ </div>
+ <div class="mechanic-cell">
+ <div class="mechanic-num">03 — Survive</div>
+ <div class="mechanic-title">Runway Management</div>
+ <div class="mechanic-body">
+ Treasury balance drives mode: Normal, Conservation, or Halted.
+ The agent automatically restricts spending as runway shrinks.
+ </div>
+ </div>
+ </div>
+ </div>
+ </section>
+
+ <!-- TOAST -->
+ <div id="toast"></div>
+
+ <!-- DASHBOARD JS -->
+ <script type="module" src="/src/unstoppable-dashboard.js"></script>
+</body>
+</html>
diff --git a/pages/walk.html b/pages/walk.html
index 2e5f4f29f..c94b00731 100644
--- a/pages/walk.html
+++ b/pages/walk.html
@@ -665,6 +665,195 @@
background: #fff;
animation: walk-rec-pulse 0.9s infinite;
}
+ /* ── Avatar picker ──────────────────────────────────────────── */
+ .walk-avatar-picker {
+ position: fixed;
+ top: calc(env(safe-area-inset-top, 0) + 56px + 60px);
+ right: 16px;
+ z-index: 10;
+ width: 280px;
+ max-height: 360px;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 14px;
+ backdrop-filter: blur(14px);
+ -webkit-backdrop-filter: blur(14px);
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+ }
+ .walk-avatar-picker-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 10px 14px;
+ font-size: 13px;
+ font-weight: 600;
+ border-bottom: 1px solid var(--border);
+ }
+ .walk-avatar-picker-header button {
+ background: none;
+ border: none;
+ color: var(--text-2);
+ font-size: 18px;
+ cursor: pointer;
+ padding: 0 4px;
+ }
+ .walk-avatar-picker-list {
+ overflow-y: auto;
+ padding: 8px;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ }
+ .walk-avatar-picker-loading {
+ text-align: center;
+ padding: 20px;
+ color: var(--text-2);
+ font-size: 12px;
+ }
+ .walk-avatar-opt {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 8px 10px;
+ border-radius: 8px;
+ cursor: pointer;
+ border: none;
+ background: none;
+ color: var(--text);
+ font: inherit;
+ font-size: 13px;
+ text-align: left;
+ transition: background 0.12s;
+ width: 100%;
+ }
+ .walk-avatar-opt:hover { background: rgba(255,255,255,0.06); }
+ .walk-avatar-opt.is-active { background: rgba(255,255,255,0.1); }
+ .walk-avatar-opt-thumb {
+ width: 36px;
+ height: 36px;
+ border-radius: 8px;
+ object-fit: cover;
+ background: rgba(255,255,255,0.05);
+ flex-shrink: 0;
+ }
+ .walk-avatar-opt-name {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ /* ── Chat ──────────────────────────────────────────────────────── */
+ .walk-chat {
+ position: fixed;
+ bottom: calc(24px + env(safe-area-inset-bottom, 0));
+ left: 50%;
+ transform: translateX(-50%);
+ z-index: 8;
+ width: min(420px, calc(100vw - 200px));
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ pointer-events: none;
+ }
+ .walk-chat-messages {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ max-height: 180px;
+ overflow: hidden;
+ pointer-events: none;
+ }
+ .walk-chat-msg {
+ padding: 5px 10px;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ backdrop-filter: blur(8px);
+ -webkit-backdrop-filter: blur(8px);
+ font-size: 12px;
+ line-height: 1.4;
+ color: var(--text);
+ animation: walk-chat-in 0.2s ease;
+ align-self: flex-start;
+ max-width: 90%;
+ word-break: break-word;
+ }
+ .walk-chat-msg-name {
+ font-weight: 600;
+ margin-right: 6px;
+ }
+ .walk-chat-msg.is-system {
+ color: var(--text-2);
+ font-style: italic;
+ border-color: transparent;
+ background: rgba(17,17,17,0.5);
+ }
+ @keyframes walk-chat-in { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }
+ .walk-chat-form {
+ display: flex;
+ gap: 6px;
+ pointer-events: auto;
+ }
+ .walk-chat-input {
+ flex: 1;
+ padding: 8px 12px;
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ background: var(--panel);
+ color: var(--text);
+ font: inherit;
+ font-size: 13px;
+ outline: none;
+ backdrop-filter: blur(10px);
+ -webkit-backdrop-filter: blur(10px);
+ transition: border-color 0.15s;
+ }
+ .walk-chat-input:focus { border-color: rgba(255,255,255,0.25); }
+ .walk-chat-input::placeholder { color: var(--text-2); }
+ .walk-chat-send {
+ width: 34px;
+ height: 34px;
+ border-radius: 50%;
+ border: 1px solid var(--border);
+ background: var(--panel);
+ color: var(--text);
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ backdrop-filter: blur(10px);
+ -webkit-backdrop-filter: blur(10px);
+ transition: background 0.12s;
+ flex-shrink: 0;
+ }
+ .walk-chat-send:hover { background: rgba(255,255,255,0.12); }
+ @media (hover: none) {
+ .walk-chat { width: min(300px, calc(100vw - 200px)); bottom: calc(80px + env(safe-area-inset-bottom, 0)); }
+ }
+
+ /* ── Chat bubble above remote players ───────────────────────────── */
+ .walk-remote-bubble {
+ position: fixed;
+ z-index: 3;
+ pointer-events: none;
+ background: var(--panel);
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ backdrop-filter: blur(6px);
+ -webkit-backdrop-filter: blur(6px);
+ padding: 4px 10px;
+ font-size: 11px;
+ color: var(--text);
+ max-width: 200px;
+ word-break: break-word;
+ white-space: pre-wrap;
+ animation: walk-chat-in 0.2s ease;
+ transition: opacity 0.3s;
+ }
</style>
<link rel="stylesheet" href="/nav.css" />
</head>
@@ -701,6 +890,10 @@
<p>Drag to orbit. Joystick or <kbd>WASD</kbd> to move.</p>
</div>
<div class="walk-actions">
+ <button type="button" class="walk-btn" id="walk-avatar-btn" title="Change avatar">
+ <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><circle cx="8" cy="5.5" r="3"/><path d="M3 14c0-2.8 2.2-5 5-5s5 2.2 5 5"/></svg>
+ <span data-label>Avatar</span>
+ </button>
<button type="button" id="walk-online" data-status="idle" title="Players online">
<span class="dot"></span>
<span data-label>solo</span>
@@ -722,6 +915,30 @@
</div>
</div>
+ <!-- Avatar picker panel -->
+ <div id="walk-avatar-picker" class="walk-avatar-picker" hidden>
+ <div class="walk-avatar-picker-header">
+ <span>Choose Avatar</span>
+ <button type="button" id="walk-avatar-picker-close" aria-label="Close">&times;</button>
+ </div>
+ <div id="walk-avatar-picker-list" class="walk-avatar-picker-list">
+ <div class="walk-avatar-picker-loading">Loading your avatars...</div>
+ </div>
+ </div>
+
+ <!-- Chat overlay -->
+ <div id="walk-chat" class="walk-chat">
+ <div id="walk-chat-messages" class="walk-chat-messages" aria-live="polite" role="log"></div>
+ <form id="walk-chat-form" class="walk-chat-form" autocomplete="off">
+ <input type="text" id="walk-chat-input" class="walk-chat-input"
+ placeholder="Press Enter to chat..." maxlength="200" autocomplete="off" spellcheck="false"
+ aria-label="Chat message" />
+ <button type="submit" class="walk-chat-send" aria-label="Send">
+ <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2L7 9"/><path d="M14 2l-5 12-2-5-5-2z"/></svg>
+ </button>
+ </form>
+ </div>
+
<!-- Player list panel -->
<div id="walk-players-panel" class="walk-players-panel" hidden>
<div class="walk-players-header">
diff --git a/public/brain.css b/public/brain.css
index b5fe0196f..1d68f3b3c 100644
--- a/public/brain.css
+++ b/public/brain.css
@@ -602,6 +602,16 @@ body {
transition: all 0.12s;
}
.br-pill.on { border-color: var(--pc); color: var(--pc); }
+.br-pill.unavailable {
+ opacity: 0.38;
+ cursor: not-allowed;
+ pointer-events: none;
+}
+.br-pill-na {
+ font-size: 9px;
+ color: #ff4444;
+ margin-left: 2px;
+}
.br-pill-dot {
width: 7px;
height: 7px;
diff --git a/public/features.json b/public/features.json
index 44daf53b1..449fbe6af 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-05-27T10:06:15.054Z",
+ "generated_at": "2026-05-27T10:47:28.743Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -368,6 +368,33 @@
"auth": null,
"indexable": true,
"tags": []
+ },
+ {
+ "path": "/fact-checker",
+ "title": "Fact Checker",
+ "description": "Pay $0.10 per claim. The agent searches across authoritative sources, pays per retrieval via x402, and returns a verdict with cited evidence and a signed attestation.",
+ "added": "2026-05-27",
+ "auth": null,
+ "indexable": true,
+ "tags": []
+ },
+ {
+ "path": "/unstoppable",
+ "title": "Unstoppable Agent",
+ "description": "Live dashboard for an autonomous agent that funds itself via x402 micropayments. Watch its balance, earnings, costs, and daily reflections in real time.",
+ "added": "2026-05-27",
+ "auth": null,
+ "indexable": true,
+ "tags": []
+ },
+ {
+ "path": "/shopper",
+ "title": "Endpoint Shopper",
+ "description": "Describe a task and set a budget. An AI agent discovers relevant x402 endpoints via the Bazaar, chains them together, and synthesizes a final answer — paying per API call.",
+ "added": "2026-05-27",
+ "auth": null,
+ "indexable": true,
+ "tags": []
}
]
},
diff --git a/public/llms-full.txt b/public/llms-full.txt
index 2346e4a1b..64fb42db4 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -247,6 +247,24 @@ URL: https://three.ws/gmgn
Live smart-money signals narrated by a 3D AI agent. Tracks which wallets are loading on Solana, Ethereum, Base, and BNB Chain in real time.
+### Fact Checker
+
+URL: https://three.ws/fact-checker
+
+Pay $0.10 per claim. The agent searches across authoritative sources, pays per retrieval via x402, and returns a verdict with cited evidence and a signed attestation.
+
+### Unstoppable Agent
+
+URL: https://three.ws/unstoppable
+
+Live dashboard for an autonomous agent that funds itself via x402 micropayments. Watch its balance, earnings, costs, and daily reflections in real time.
+
+### Endpoint Shopper
+
+URL: https://three.ws/shopper
+
+Describe a task and set a budget. An AI agent discovers relevant x402 endpoints via the Bazaar, chains them together, and synthesizes a final answer — paying per API call.
+
## Agent Tools
Manage, talk to, and deploy individual agents.
diff --git a/public/llms.txt b/public/llms.txt
index a7e5206c1..f83244b99 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -63,6 +63,9 @@ On-chain features: pay-per-call, token launches, vanity wallets.
- [Pump Visualizer](https://three.ws/pump-visualizer): 3D visualizer of trending pump.fun tokens — live market data rendered as an interactive scene.
- [x402 Bazaar](https://three.ws/bazaar): Search and browse the x402 facilitator catalog. Filter by network, price, and extensions. Pay any service in one click.
- [GMGN Smart Money](https://three.ws/gmgn): Live smart-money signals narrated by a 3D AI agent. Tracks which wallets are loading on Solana, Ethereum, Base, and BNB Chain in real time.
+- [Fact Checker](https://three.ws/fact-checker): Pay $0.10 per claim. The agent searches across authoritative sources, pays per retrieval via x402, and returns a verdict with cited evidence and a signed attestation.
+- [Unstoppable Agent](https://three.ws/unstoppable): Live dashboard for an autonomous agent that funds itself via x402 micropayments. Watch its balance, earnings, costs, and daily reflections in real time.
+- [Endpoint Shopper](https://three.ws/shopper): Describe a task and set a budget. An AI agent discovers relevant x402 endpoints via the Bazaar, chains them together, and synthesizes a final answer — paying per API call.
## Agent Tools
diff --git a/public/marketplace-v2.css b/public/marketplace-v2.css
index f952375b8..64d35ebd6 100644
--- a/public/marketplace-v2.css
+++ b/public/marketplace-v2.css
@@ -359,6 +359,289 @@ body.market-page > #footer-container {
margin-top: 4px;
}
+/* ── Reviews & Ratings ──────────────────────────────────────────────────── */
+.d-rating-widget {
+ margin-bottom: 24px;
+}
+#d-rating-summary {
+ display: flex;
+ align-items: baseline;
+ gap: 10px;
+ margin-bottom: 12px;
+}
+#d-rating-avg {
+ font-size: 36px;
+ font-weight: 700;
+ color: #fafafa;
+ line-height: 1;
+}
+#d-rating-stars {
+ font-size: 18px;
+ color: #f59e0b;
+ letter-spacing: 1px;
+}
+.stars-filled {
+ color: #f59e0b;
+}
+#d-rating-count {
+ font-size: 13px;
+ color: #71717a;
+}
+.d-rating-breakdown {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ margin-bottom: 12px;
+}
+.breakdown-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 12px;
+}
+.breakdown-label {
+ width: 22px;
+ color: #a1a1aa;
+ text-align: right;
+ flex-shrink: 0;
+}
+.breakdown-track {
+ flex: 1;
+ height: 6px;
+ background: #1a1a1a;
+ border-radius: 3px;
+ overflow: hidden;
+}
+.breakdown-fill {
+ height: 100%;
+ background: #f59e0b;
+ border-radius: 3px;
+ transition: width 0.35s ease;
+}
+.breakdown-count {
+ width: 18px;
+ color: #71717a;
+ font-size: 11px;
+ text-align: right;
+ flex-shrink: 0;
+}
+#d-rating-input {
+ margin-bottom: 20px;
+ padding: 16px;
+ background: #0e0e0e;
+ border: 1px solid #1c1c1c;
+ border-radius: 10px;
+}
+.review-star-picker {
+ display: inline-flex;
+ gap: 2px;
+ margin: 8px 0;
+}
+.star-pick {
+ background: none;
+ border: none;
+ font-size: 22px;
+ color: #3f3f46;
+ cursor: pointer;
+ padding: 2px;
+ line-height: 1;
+ transition: color 0.1s, transform 0.1s;
+}
+.star-pick.active,
+.star-pick.hover {
+ color: #f59e0b;
+}
+.star-pick:hover {
+ transform: scale(1.15);
+}
+#d-rating-input textarea,
+#d-review-body,
+#d-review-body-edit {
+ width: 100%;
+ margin-top: 8px;
+ padding: 10px 12px;
+ background: #080808;
+ border: 1px solid #242424;
+ border-radius: 8px;
+ color: #e4e4e7;
+ font-size: 13px;
+ font-family: inherit;
+ resize: vertical;
+ min-height: 80px;
+ box-sizing: border-box;
+ outline: none;
+ transition: border-color 0.15s;
+}
+#d-rating-input textarea:focus,
+#d-review-body:focus,
+#d-review-body-edit:focus {
+ border-color: #3f3f46;
+}
+.submit-review {
+ margin-top: 10px;
+ padding: 8px 18px;
+ background: #fff;
+ color: #000;
+ border: none;
+ border-radius: 7px;
+ font-size: 13px;
+ font-weight: 600;
+ cursor: pointer;
+ transition: opacity 0.15s;
+}
+.submit-review:disabled {
+ opacity: 0.35;
+ cursor: not-allowed;
+}
+.submit-review:hover:not(:disabled) {
+ opacity: 0.88;
+}
+.review-login-cta {
+ color: #fff;
+ font-size: 13px;
+ font-weight: 500;
+ text-decoration: underline;
+ text-underline-offset: 2px;
+}
+.review-mine-notice {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ font-size: 13px;
+ color: #a1a1aa;
+}
+.review-mine-actions {
+ display: flex;
+ gap: 8px;
+}
+.review-edit-btn,
+.review-delete-btn,
+.review-cancel-btn {
+ background: none;
+ border: 1px solid #2a2a2a;
+ color: #a1a1aa;
+ padding: 4px 10px;
+ border-radius: 6px;
+ font-size: 12px;
+ cursor: pointer;
+ transition: border-color 0.15s, color 0.15s;
+}
+.review-edit-btn:hover { border-color: #4a4a4a; color: #fafafa; }
+.review-delete-btn:hover { border-color: #7f1d1d; color: #f87171; }
+.review-cancel-btn:hover { border-color: #3f3f46; color: #d4d4d8; }
+.review-edit-form {
+ margin-top: 12px;
+}
+.review-edit-actions {
+ display: flex;
+ gap: 8px;
+ align-items: center;
+ margin-top: 6px;
+}
+#d-rating-msg {
+ font-size: 12px;
+ margin-top: 8px;
+ color: #71717a;
+}
+#d-rating-msg.ok { color: #4ade80; }
+#d-rating-msg.err { color: #f87171; }
+.d-reviews-list {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+.review-card {
+ padding: 14px 16px;
+ background: #0a0a0a;
+ border: 1px solid #1a1a1a;
+ border-radius: 10px;
+}
+.review-card.skeleton {
+ pointer-events: none;
+}
+.review-header {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ margin-bottom: 8px;
+}
+.review-avatar {
+ width: 32px;
+ height: 32px;
+ border-radius: 50%;
+ background: #1a1a1a center/cover no-repeat;
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 13px;
+ font-weight: 600;
+ color: #71717a;
+}
+.review-author {
+ flex: 1;
+ min-width: 0;
+}
+.review-author-name {
+ font-size: 13px;
+ font-weight: 600;
+ color: #e4e4e7;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.review-date {
+ font-size: 11px;
+ color: #52525b;
+ margin-top: 1px;
+}
+.review-stars {
+ font-size: 14px;
+ color: #f59e0b;
+ letter-spacing: 1px;
+}
+.review-body {
+ font-size: 13px;
+ color: #a1a1aa;
+ line-height: 1.6;
+ margin: 0;
+ word-break: break-word;
+}
+.reviews-empty {
+ text-align: center;
+ padding: 40px 20px;
+ color: #52525b;
+}
+.reviews-empty-icon {
+ font-size: 32px;
+ display: block;
+ margin-bottom: 10px;
+ opacity: 0.5;
+}
+.reviews-empty p {
+ margin: 4px 0;
+ font-size: 13px;
+}
+.reviews-empty-hint {
+ font-size: 12px;
+ color: #3f3f46;
+}
+.review-skeleton-line {
+ height: 12px;
+ background: #1a1a1a;
+ border-radius: 4px;
+ margin-bottom: 8px;
+ animation: skeleton-pulse 1.4s ease-in-out infinite;
+}
+.review-skeleton-line.w60 { width: 60%; }
+.review-skeleton-line.w80 { width: 80%; }
+.review-skeleton-line.w40 { width: 40%; }
+@keyframes skeleton-pulse {
+ 0%, 100% { opacity: 0.5; }
+ 50% { opacity: 1; }
+}
+
/* ── Mobile responsive ─────────────────────────────────────────────────── */
.market-sidebar-toggle {
display: none;
diff --git a/public/marketplace.css b/public/marketplace.css
index 5fe0c2c26..826a0a13e 100644
--- a/public/marketplace.css
+++ b/public/marketplace.css
@@ -398,6 +398,23 @@ body.market-page {
color: var(--mk-text-2);
}
+.market-card-agent .stats .rating {
+ display: inline-flex;
+ align-items: center;
+ gap: 3px;
+ font-size: 11px;
+ color: #f5a524;
+ font-weight: 600;
+ background: rgba(245, 165, 36, 0.1);
+ border: 1px solid rgba(245, 165, 36, 0.2);
+ border-radius: 6px;
+ padding: 3px 8px;
+}
+.market-card-agent .stats .rating .count {
+ color: var(--mk-text-3);
+ font-weight: 400;
+}
+
.market-card-agent .footer {
display: flex;
justify-content: space-between;
@@ -2676,3 +2693,411 @@ body.market-page {
border-color: var(--mk-border-2);
}
.d-token-btn-sec:hover { background: rgba(255,255,255,0.04); color: var(--mk-text); }
+
+/* ── Reviews & Ratings ──────────────────────────────────────────────── */
+
+.d-rating-widget {
+ border: 1px solid var(--mk-border);
+ border-radius: var(--mk-radius);
+ padding: 20px;
+ margin-top: 24px;
+ background: var(--mk-panel);
+}
+
+.d-rating-summary {
+ display: flex;
+ align-items: baseline;
+ gap: 10px;
+ margin-bottom: 4px;
+}
+.d-rating-summary .avg {
+ font-size: 32px;
+ font-weight: 700;
+ color: var(--mk-text);
+ line-height: 1;
+}
+.d-rating-summary .stars {
+ font-size: 18px;
+ color: #fbbf24;
+ letter-spacing: 1px;
+}
+.d-rating-summary .stars .stars-filled {
+ color: #fbbf24;
+}
+.d-rating-summary .count {
+ font-size: 13px;
+ color: var(--mk-text-2);
+}
+
+/* Breakdown bars (App-Store style) */
+.d-rating-breakdown {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ margin: 14px 0 0;
+}
+.breakdown-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+.breakdown-label {
+ font-size: 12px;
+ color: var(--mk-text-2);
+ width: 26px;
+ text-align: right;
+ flex-shrink: 0;
+}
+.breakdown-track {
+ flex: 1;
+ height: 6px;
+ background: rgba(255, 255, 255, 0.06);
+ border-radius: 3px;
+ overflow: hidden;
+}
+.breakdown-fill {
+ height: 100%;
+ background: #fbbf24;
+ border-radius: 3px;
+ transition: width 0.4s ease;
+}
+.breakdown-count {
+ font-size: 11px;
+ color: var(--mk-text-3);
+ width: 22px;
+ text-align: right;
+ flex-shrink: 0;
+}
+
+/* Rating input form */
+.d-rating-input {
+ margin-top: 16px;
+ padding-top: 16px;
+ border-top: 1px solid var(--mk-border);
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+
+.review-login-cta {
+ display: inline-block;
+ padding: 10px 20px;
+ border-radius: 8px;
+ background: rgba(255, 255, 255, 0.06);
+ border: 1px solid var(--mk-border-2);
+ color: var(--mk-text);
+ text-decoration: none;
+ font-size: 13px;
+ font-weight: 500;
+ text-align: center;
+ transition: background 0.15s, border-color 0.15s;
+}
+.review-login-cta:hover {
+ background: rgba(255, 255, 255, 0.1);
+ border-color: rgba(255, 255, 255, 0.2);
+}
+
+/* Star picker */
+.review-star-picker {
+ display: inline-flex;
+ gap: 2px;
+}
+.review-star-picker .star-pick {
+ background: none;
+ border: none;
+ cursor: pointer;
+ font-size: 22px;
+ color: var(--mk-text-3);
+ padding: 2px 3px;
+ line-height: 1;
+ transition: color 0.1s, transform 0.1s;
+}
+.review-star-picker .star-pick:hover,
+.review-star-picker .star-pick.hover {
+ color: #fbbf24;
+ transform: scale(1.15);
+}
+.review-star-picker .star-pick.active {
+ color: #fbbf24;
+}
+.review-star-picker .star-pick:focus-visible {
+ outline: 2px solid rgba(255, 255, 255, 0.5);
+ outline-offset: 2px;
+ border-radius: 4px;
+}
+
+/* Textarea */
+.d-rating-input textarea,
+.review-edit-form textarea {
+ width: 100%;
+ min-height: 72px;
+ padding: 10px 12px;
+ border-radius: 8px;
+ border: 1px solid var(--mk-border);
+ background: rgba(255, 255, 255, 0.04);
+ color: var(--mk-text);
+ font-family: inherit;
+ font-size: 13px;
+ line-height: 1.5;
+ resize: vertical;
+ transition: border-color 0.15s, background 0.15s;
+ box-sizing: border-box;
+}
+.d-rating-input textarea:focus,
+.review-edit-form textarea:focus {
+ outline: none;
+ border-color: rgba(255, 255, 255, 0.3);
+ background: rgba(255, 255, 255, 0.07);
+}
+
+/* Submit / Edit / Delete buttons */
+.submit-review {
+ align-self: flex-start;
+ padding: 8px 20px;
+ border-radius: 8px;
+ border: 1px solid rgba(255, 255, 255, 0.14);
+ background: rgba(255, 255, 255, 0.08);
+ color: var(--mk-text);
+ font-size: 13px;
+ font-weight: 600;
+ cursor: pointer;
+ transition: background 0.15s, border-color 0.15s, opacity 0.15s;
+}
+.submit-review:hover:not(:disabled) {
+ background: rgba(255, 255, 255, 0.14);
+ border-color: rgba(255, 255, 255, 0.25);
+}
+.submit-review:disabled {
+ opacity: 0.4;
+ cursor: not-allowed;
+}
+.submit-review:active:not(:disabled) {
+ transform: translateY(1px);
+}
+
+.review-mine-notice {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ font-size: 13px;
+ color: var(--mk-text);
+}
+.review-mine-notice.editing { opacity: 0.5; }
+.review-mine-notice strong { color: #fbbf24; letter-spacing: 1px; }
+.review-mine-actions {
+ display: flex;
+ gap: 8px;
+}
+.review-edit-btn,
+.review-delete-btn,
+.review-cancel-btn {
+ padding: 5px 12px;
+ border-radius: 6px;
+ border: 1px solid var(--mk-border-2);
+ background: transparent;
+ color: var(--mk-text-2);
+ font-size: 12px;
+ cursor: pointer;
+ transition: background 0.15s, color 0.15s, border-color 0.15s;
+}
+.review-edit-btn:hover,
+.review-cancel-btn:hover {
+ background: rgba(255, 255, 255, 0.06);
+ color: var(--mk-text);
+}
+.review-delete-btn:hover {
+ background: rgba(248, 113, 113, 0.12);
+ border-color: rgba(248, 113, 113, 0.3);
+ color: #f87171;
+}
+
+.review-edit-form {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ margin-top: 12px;
+ padding-top: 12px;
+ border-top: 1px solid var(--mk-border);
+}
+.review-edit-actions {
+ display: flex;
+ gap: 8px;
+}
+
+/* Status message */
+.d-rating-msg {
+ font-size: 12px;
+ min-height: 18px;
+ transition: color 0.15s;
+}
+.d-rating-msg.err { color: #f87171; }
+.d-rating-msg.ok { color: #4ade80; }
+
+/* Review list */
+.d-reviews-list {
+ margin-top: 16px;
+ display: flex;
+ flex-direction: column;
+ gap: 1px;
+}
+
+.review-card {
+ padding: 14px 0;
+ border-top: 1px solid var(--mk-border);
+}
+.review-card:first-child { border-top: none; padding-top: 0; }
+.review-card.mine {
+ background: rgba(255, 255, 255, 0.02);
+ border-radius: 8px;
+ padding: 14px;
+ margin: -2px -14px 0;
+}
+
+.review-header {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+}
+.review-avatar {
+ width: 32px;
+ height: 32px;
+ border-radius: 50%;
+ background: var(--mk-panel-2);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--mk-text-2);
+ flex-shrink: 0;
+ background-size: cover;
+ background-position: center;
+}
+.review-meta {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 1px;
+}
+.review-author {
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--mk-text);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.review-date {
+ font-size: 11px;
+ color: var(--mk-text-3);
+}
+.review-stars {
+ color: #fbbf24;
+ font-size: 14px;
+ letter-spacing: 1px;
+ flex-shrink: 0;
+}
+.review-body {
+ margin: 8px 0 0;
+ font-size: 13px;
+ color: var(--mk-text-2);
+ line-height: 1.55;
+ white-space: pre-wrap;
+ word-break: break-word;
+}
+
+/* Empty state */
+.reviews-empty {
+ text-align: center;
+ padding: 24px 16px;
+ color: var(--mk-text-3);
+}
+.reviews-empty-icon {
+ font-size: 28px;
+ display: block;
+ margin-bottom: 8px;
+ opacity: 0.4;
+}
+.reviews-empty p {
+ margin: 0;
+ font-size: 13px;
+}
+.reviews-empty-hint {
+ margin-top: 4px !important;
+ font-size: 12px !important;
+ color: var(--mk-text-3);
+}
+
+/* Skeleton loading */
+.review-card.skeleton {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ padding: 14px 0;
+}
+.review-skeleton-line {
+ height: 12px;
+ border-radius: 6px;
+ background: linear-gradient(90deg, rgba(255,255,255,0.04) 25%, rgba(255,255,255,0.08) 50%, rgba(255,255,255,0.04) 75%);
+ background-size: 200% 100%;
+ animation: review-shimmer 1.5s ease infinite;
+}
+.review-skeleton-line.w40 { width: 40%; }
+.review-skeleton-line.w60 { width: 60%; }
+.review-skeleton-line.w80 { width: 80%; }
+@keyframes review-shimmer {
+ 0% { background-position: 200% 0; }
+ 100% { background-position: -200% 0; }
+}
+
+/* ── Reputation card ───────────────────────────────────────────────── */
+
+.d-reputation-card {
+ border: 1px solid var(--mk-border);
+ border-radius: var(--mk-radius);
+ padding: 16px;
+ margin-top: 12px;
+ background: var(--mk-panel);
+}
+.d-rep-eyebrow {
+ font-size: 10px;
+ text-transform: uppercase;
+ letter-spacing: 0.1em;
+ color: #4ade80;
+ font-weight: 600;
+ margin-bottom: 8px;
+}
+.d-rep-score {
+ display: flex;
+ align-items: baseline;
+ gap: 8px;
+}
+.d-rep-avg {
+ font-size: 24px;
+ font-weight: 700;
+ color: var(--mk-text);
+ line-height: 1;
+}
+.d-rep-stars {
+ font-size: 14px;
+ color: #4ade80;
+ letter-spacing: 1px;
+}
+.d-rep-stars .stars-filled { color: #4ade80; }
+.d-rep-count {
+ display: block;
+ margin-top: 4px;
+ font-size: 11px;
+ color: var(--mk-text-3);
+}
+
+/* ── Responsive review adjustments ─────────────────────────────────── */
+
+@media (max-width: 700px) {
+ .d-rating-widget { padding: 14px; }
+ .d-rating-summary .avg { font-size: 26px; }
+ .review-mine-notice { flex-direction: column; align-items: flex-start; gap: 8px; }
+ .review-header { flex-wrap: wrap; }
+}
diff --git a/public/nav.html b/public/nav.html
index 9d287bb64..be5d479f6 100644
--- a/public/nav.html
+++ b/public/nav.html
@@ -75,6 +75,11 @@
<li class="nav-item" role="none">
<a href="/marketplace" role="menuitem">Marketplace</a>
</li>
+ <li class="nav-item" role="none">
+ <a href="/skills" class="nav-link-with-badge" role="menuitem"
+ >Skills<span class="nav-badge">NEW</span></a
+ >
+ </li>
<li class="nav-item nav-has-menu" role="none">
<button
type="button"
@@ -104,6 +109,12 @@
><span class="nav-mi-sub">Every public 3D avatar</span></a
>
</li>
+ <li role="none">
+ <a href="/skills" role="menuitem"
+ ><span class="nav-mi-title">Skills<span class="nav-pill" aria-hidden="true">NEW</span></span
+ ><span class="nav-mi-sub">Browse agent tool packs and capabilities</span></a
+ >
+ </li>
<li role="none">
<a href="/bazaar" role="menuitem"
><span class="nav-mi-title">x402 Bazaar</span
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 46d4fc6b6..7b02d1178 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -359,6 +359,27 @@
<span class="sm-desc">Live smart-money signals narrated by a 3D AI agent. Tracks which wallets are loading on Solana, Ethereum, Base, and BNB Chain in real time.</span>
</a>
</li>
+ <li>
+ <a href="/fact-checker">
+ <span class="sm-title">Fact Checker</span>
+ <span class="sm-path">/fact-checker</span>
+ <span class="sm-desc">Pay $0.10 per claim. The agent searches across authoritative sources, pays per retrieval via x402, and returns a verdict with cited evidence and a signed attestation.</span>
+ </a>
+ </li>
+ <li>
+ <a href="/unstoppable">
+ <span class="sm-title">Unstoppable Agent</span>
+ <span class="sm-path">/unstoppable</span>
+ <span class="sm-desc">Live dashboard for an autonomous agent that funds itself via x402 micropayments. Watch its balance, earnings, costs, and daily reflections in real time.</span>
+ </a>
+ </li>
+ <li>
+ <a href="/shopper">
+ <span class="sm-title">Endpoint Shopper</span>
+ <span class="sm-path">/shopper</span>
+ <span class="sm-desc">Describe a task and set a budget. An AI agent discovers relevant x402 endpoints via the Bazaar, chains them together, and synthesizes a final answer — paying per API call.</span>
+ </a>
+ </li>
</ul>
</section>
diff --git a/src/agent-detail.js b/src/agent-detail.js
index a0911856a..4723804ed 100644
--- a/src/agent-detail.js
+++ b/src/agent-detail.js
@@ -491,15 +491,7 @@ function buildReviewForm(agentId, existing, onSuccess) {
let selectedRating = existing?.rating || 0;
let submitting = false;
- const isLoggedIn = document.cookie.includes('session') || document.querySelector('[data-user-id]') != null;
- if (!isLoggedIn && !existing) {
- return el('div', { class: 'ad-reviews-signin-prompt' }, [
- document.createTextNode(''),
- el('a', { href: '/sign-in', text: 'Sign in' }),
- document.createTextNode(' to leave a review'),
- ]);
- }
const formTitle = el('div', { class: 'ad-review-form-title', text: existing ? 'Your Review' : 'Write a Review' });
@@ -574,8 +566,12 @@ function buildReviewForm(agentId, existing, onSuccess) {
});
const json = await r.json();
if (!r.ok) {
- statusEl.textContent = json.error?.message || 'Save failed';
- statusEl.style.color = '#ff8a80';
+ if (r.status === 401) {
+ statusEl.innerHTML = '<a href="/sign-in" style="color:var(--ad-violet)">Sign in</a> to leave a review';
+ } else {
+ statusEl.textContent = json.error?.message || 'Save failed';
+ }
+ statusEl.style.color = r.status === 401 ? 'var(--ad-muted)' : '#ff8a80';
submitBtn.disabled = false;
submitBtn.textContent = existing ? 'Update' : 'Submit';
submitting = false;
diff --git a/src/brain.js b/src/brain.js
index 860183d33..3040ef57e 100644
--- a/src/brain.js
+++ b/src/brain.js
@@ -47,6 +47,7 @@ const state = {
currentId: null,
streaming: false,
agents: [],
+ availableProviders: null, // set after API fetch; null = not yet loaded
};
// ── DOM helpers ──────────────────────────────────────────────────────────────
@@ -428,28 +429,69 @@ function renderSidebar() {
}
// ── Render: Playground toolbar ───────────────────────────────────────────────
+function isProviderAvailable(key) {
+ if (!state.availableProviders) return true; // optimistic before load
+ const found = state.availableProviders.find(p => p.key === key);
+ return found ? found.available : false;
+}
+
function renderPlayControls() {
const ctrl = $('brPlayControls');
const label = $('brPlayLabel');
if (state.playMode === 'compare') {
label.textContent = 'Models';
ctrl.innerHTML = `<div class="br-provider-pills">${
- PROVIDERS.map(p => `
- <label class="br-pill${state.active.has(p.key) ? ' on' : ''}" style="--pc:${p.color}" data-key="${p.key}">
+ PROVIDERS.map(p => {
+ const avail = isProviderAvailable(p.key);
+ const cls = [
+ 'br-pill',
+ state.active.has(p.key) ? 'on' : '',
+ !avail ? 'unavailable' : '',
+ ].filter(Boolean).join(' ');
+ const title = avail ? '' : ` title="${p.label} — not configured on this deployment"`;
+ return `<label class="${cls}" style="--pc:${p.color}" data-key="${p.key}"${title}>
<span class="br-pill-dot"></span>
<span>${p.short}</span>
- </label>
- `).join('')
+ ${!avail ? '<span class="br-pill-na" aria-hidden="true">✕</span>' : ''}
+ </label>`;
+ }).join('')
}</div>`;
} else {
label.textContent = 'Model';
ctrl.innerHTML = `<select class="br-focus-sel" id="brFocusSel">${
- PROVIDERS.map(p => `<option value="${p.key}"${p.key === state.focusKey ? ' selected' : ''}>${p.label}</option>`).join('')
+ PROVIDERS.map(p => {
+ const avail = isProviderAvailable(p.key);
+ return `<option value="${p.key}"${p.key === state.focusKey ? ' selected' : ''}${!avail ? ' disabled' : ''}>${p.label}${avail ? '' : ' (unavailable)'}</option>`;
+ }).join('')
}</select>`;
}
bindPlayControlEvents();
}
+async function fetchProviderAvailability() {
+ try {
+ const r = await fetch('/api/brain/chat', { method: 'GET' });
+ if (!r.ok) return;
+ const json = await r.json();
+ if (Array.isArray(json.providers)) {
+ state.availableProviders = json.providers;
+ // Remove unavailable providers from the active set
+ for (const key of [...state.active]) {
+ const found = json.providers.find(p => p.key === key);
+ if (found && !found.available) state.active.delete(key);
+ }
+ // Ensure at least one active provider
+ if (state.active.size === 0) {
+ const first = json.providers.find(p => p.available);
+ if (first) state.active.add(first.key);
+ }
+ renderPlayControls();
+ }
+ } catch {
+ // Non-fatal — providers just show as all-available
+ }
+}
+
// ── Render: Compare canvas ───────────────────────────────────────────────────
function renderCompareCanvas() {
const canvas = $('brCanvas');
@@ -972,6 +1014,7 @@ renderPlayControls();
renderSidebar();
renderCanvas();
bindEvents();
+fetchProviderAvailability();
if (state.persona) {
renderPersonaCard(state.persona);
diff --git a/src/dashboard-next/nav.js b/src/dashboard-next/nav.js
index c3bc8e784..8071b9594 100644
--- a/src/dashboard-next/nav.js
+++ b/src/dashboard-next/nav.js
@@ -15,6 +15,7 @@
export const NAV = [
// ── Create ──────────────────────────────────────────────────────────
+ { path: '/start', label: 'Get started', icon: 'sparkle', group: 'Create', tags: ['new', 'wizard', 'onboarding', 'create agent', 'setup'], external: true },
{ path: '/dashboard', label: 'Overview', icon: 'home', group: 'Create', tags: ['home', 'dashboard', 'start'] },
{ path: '/dashboard/avatars', label: 'Avatars', icon: 'avatar', group: 'Create', tags: ['models', 'glb', 'creations', 'selfie', 'upload'] },
{ path: '/dashboard/agents', label: 'Agents', icon: 'agent', group: 'Create', tags: ['bot', 'ai', 'identity', 'erc-8004', 'persona', 'reputation'] },
@@ -26,8 +27,10 @@ export const NAV = [
{ path: '/dashboard/widgets', label: 'Widgets', icon: 'widget', group: 'Distribute', tags: ['embed', 'iframe', '<threews-avatar>', 'transcripts', 'knowledge'] },
{ path: '/dashboard/api', label: 'API & Embed', icon: 'code', group: 'Distribute', tags: ['keys', 'token', 'mcp', 'snippets', 'embed-policy'] },
{ path: '/marketplace', label: 'Marketplace', icon: 'market', group: 'Distribute', tags: ['browse', 'buy', 'sell', 'agents', 'avatars', 'directory'], external: true },
+ { path: '/skills', label: 'Skills', icon: 'skills', group: 'Distribute', tags: ['tool', 'pack', 'capability', 'install', 'browse', 'skill'], external: true },
// ── Monetize ────────────────────────────────────────────────────────
+ { path: '/dashboard/analytics', label: 'Analytics', icon: 'chart', group: 'Monetize', tags: ['revenue', 'charts', 'metrics', 'funnel', 'performance', 'views', 'engagement'] },
{ path: '/dashboard/monetize', label: 'Monetize', icon: 'coin', group: 'Monetize', tags: ['revenue', 'payments', 'subscriptions', 'withdrawals', 'earnings', 'plan', 'billing'] },
{ path: '/dashboard/tokens', label: 'Tokens', icon: 'token', group: 'Monetize', tags: ['pump.fun', 'launch', 'bonding curve', 'royalties', 'trade'] },
{ path: '/dashboard/portfolio', label: 'Portfolio', icon: 'portfolio', group: 'Monetize', tags: ['nft', 'holdings', 'balances', 'wallet', 'collection', 'crypto', 'tokens', 'chart', 'send'] },
@@ -50,6 +53,7 @@ export const GROUPS = ['Create', 'Distribute', 'Monetize', 'Explore', 'Account']
/** Inline-SVG icon strings keyed by the `icon` field above. */
export const ICONS = {
+ sparkle: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M10 2v2M10 16v2M2 10h2M16 10h2M4.93 4.93l1.41 1.41M13.66 13.66l1.41 1.41M4.93 15.07l1.41-1.41M13.66 6.34l1.41-1.41M10 7a3 3 0 100 6 3 3 0 000-6z"/></svg>',
home: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M3 9l7-6 7 6v8a1 1 0 01-1 1h-4v-6H8v6H4a1 1 0 01-1-1V9z"/></svg>',
avatar: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="10" cy="7" r="3.2"/><path d="M3.5 17c1.1-3.4 3.8-5 6.5-5s5.4 1.6 6.5 5"/></svg>',
agent: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="2" width="10" height="10" rx="2"/><circle cx="8" cy="6.5" r="1"/><circle cx="12" cy="6.5" r="1"/><path d="M8 9h4M3 14l2-2h10l2 2v3a1 1 0 01-1 1H4a1 1 0 01-1-1v-3z"/></svg>',
@@ -71,6 +75,8 @@ export const ICONS = {
community: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="7" cy="7" r="2.5"/><circle cx="14" cy="7" r="2"/><path d="M2 16c.8-2.8 2.8-4.2 5-4.2s4.2 1.4 5 4.2"/><path d="M13.5 11.8c1.5 0 3 1.2 3.5 3.2"/></svg>',
play: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="16" height="14" rx="2"/><path d="M8 7.5v5l4.5-2.5z"/></svg>',
live: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="10" cy="10" r="2"/><path d="M6 6a5.5 5.5 0 000 8"/><path d="M14 6a5.5 5.5 0 010 8"/><path d="M3.5 3.5a9 9 0 000 13"/><path d="M16.5 3.5a9 9 0 010 13"/></svg>',
+ chart: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M3 17V7l4 3 3-6 4 4 3-3v12H3z"/><path d="M3 17h14"/></svg>',
+ skills: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="14" height="14" rx="3"/><path d="M7 7h6M7 10h4M7 13h5"/></svg>',
};
/** Resolve the route for the current pathname (exact match wins; falls back to startsWith). */
diff --git a/src/dashboard-next/pages/agents.js b/src/dashboard-next/pages/agents.js
index 3f95eb9c6..650400aed 100644
--- a/src/dashboard-next/pages/agents.js
+++ b/src/dashboard-next/pages/agents.js
@@ -169,6 +169,8 @@ function renderAgents(host, agents, avatars, root) {
}
});
});
+
+ loadInlineReviewStats(host, agents);
}
const BRAIN_LABELS = {
@@ -254,6 +256,34 @@ function agentCard(a, avatars) {
`;
}
+async function loadInlineReviewStats(host, agents) {
+ const published = agents.filter((a) => a.is_published);
+ if (!published.length) return;
+ const results = await Promise.allSettled(
+ published.map((a) =>
+ fetch(`/api/marketplace/agents/${encodeURIComponent(a.id)}/reviews`, { credentials: 'include' })
+ .then((r) => r.ok ? r.json() : null)
+ .then((j) => ({ id: a.id, summary: j?.data?.summary }))
+ )
+ );
+ for (const r of results) {
+ if (r.status !== 'fulfilled' || !r.value?.summary) continue;
+ const { id, summary } = r.value;
+ const card = host.querySelector(`[data-agent-id="${id}"]`);
+ if (!card) continue;
+ const avg = Number(summary.rating_avg || 0);
+ const count = summary.rating_count || 0;
+ if (count === 0) continue;
+ const badge = document.createElement('span');
+ badge.className = 'dn-tag';
+ badge.style.cssText = 'font-size:11px;background:rgba(251,191,36,0.12);border-color:rgba(251,191,36,0.3);color:#fbbf24';
+ badge.textContent = `★ ${avg.toFixed(1)} (${count})`;
+ badge.title = `${avg.toFixed(2)} avg from ${count} review${count === 1 ? '' : 's'}`;
+ const nameRow = card.querySelector('div > div:nth-child(2) > div:first-child');
+ if (nameRow) nameRow.appendChild(badge);
+ }
+}
+
function showReputationPanel(card, rep) {
const existing = card.querySelector('[data-reputation-panel]');
if (existing) { existing.remove(); return; }
diff --git a/src/dashboard-next/pages/analytics.js b/src/dashboard-next/pages/analytics.js
new file mode 100644
index 000000000..d50a66e71
--- /dev/null
+++ b/src/dashboard-next/pages/analytics.js
@@ -0,0 +1,403 @@
+// dashboard-next — Analytics page.
+//
+// Revenue charts, per-agent performance, skill breakdown, conversion funnel.
+// All data from real /api/billing/revenue, /api/agents, /api/widgets/:id/stats.
+
+import { mountShell } from '../shell.js';
+import { requireUser, get, esc, relTime, formatUsdc, ApiError } from '../api.js';
+
+const RANGES = [
+ { key: '7d', days: 7, label: '7 days', granularity: 'day' },
+ { key: '30d', days: 30, label: '30 days', granularity: 'day' },
+ { key: '90d', days: 90, label: '90 days', granularity: 'day' },
+ { key: '1y', days: 365, label: '12 months', granularity: 'week' },
+];
+
+let range = RANGES[1];
+let me = null;
+
+(async function boot() {
+ const main = await mountShell();
+ me = await requireUser();
+
+ main.innerHTML = `
+ <h1 class="dn-h1">Analytics</h1>
+ <p class="dn-h1-sub">Revenue, engagement, and performance across your agents and skills.</p>
+ <div data-slot="content" class="ana-root"></div>
+ `;
+ injectStyles();
+ const root = main.querySelector('[data-slot="content"]');
+ renderSkeletons(root);
+ await loadAndRender(root);
+})().catch(err => {
+ if (err instanceof ApiError && err.status === 401) {
+ location.href = `/login?return=${encodeURIComponent(location.pathname)}`;
+ return;
+ }
+ const main = document.querySelector('.dn-main-inner') || document.body;
+ main.innerHTML = `<h1 class="dn-h1">Analytics</h1><div class="dn-panel"><div class="dn-panel-title" style="color:var(--nxt-danger)">Failed to load</div><div class="dn-panel-sub">${esc(err?.message || 'unknown')}</div><button class="dn-btn" onclick="location.reload()">Reload</button></div>`;
+});
+
+function renderSkeletons(root) {
+ root.innerHTML = `
+ <div class="ana-range-bar">${RANGES.map(r => `<button class="ana-range-btn${r.key === range.key ? ' is-active' : ''}">${r.label}</button>`).join('')}</div>
+ <div class="ana-kpi-row">${Array.from({ length: 4 }, () => `<div class="dn-panel ana-kpi"><div class="dn-skeleton" style="height:12px;width:80px;margin-bottom:8px"></div><div class="dn-skeleton" style="height:28px;width:100px"></div></div>`).join('')}</div>
+ <div class="dn-panel" style="min-height:280px"><div class="dn-skeleton" style="height:12px;width:120px;margin-bottom:16px"></div><div class="dn-skeleton" style="height:200px;width:100%"></div></div>
+ <div class="ana-two-col">
+ <div class="dn-panel" style="min-height:200px"><div class="dn-skeleton" style="height:12px;width:100px;margin-bottom:12px"></div><div class="dn-skeleton" style="height:150px;width:100%"></div></div>
+ <div class="dn-panel" style="min-height:200px"><div class="dn-skeleton" style="height:12px;width:100px;margin-bottom:12px"></div><div class="dn-skeleton" style="height:150px;width:100%"></div></div>
+ </div>
+ `;
+}
+
+async function loadAndRender(root) {
+ const from = new Date(Date.now() - range.days * 86400_000).toISOString();
+ const to = new Date().toISOString();
+
+ const [revenue, agents, widgets, summary] = await Promise.all([
+ safe(() => get(`/api/billing/revenue?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}&granularity=${range.granularity}`)),
+ safe(() => get('/api/agents?limit=50')),
+ safe(() => get('/api/widgets')),
+ safe(() => get('/api/billing/summary')),
+ ]);
+
+ const agentList = agents?.agents ?? [];
+ const widgetList = widgets?.widgets ?? [];
+
+ const widgetStats = await Promise.all(
+ widgetList.slice(0, 20).map(w =>
+ get(`/api/widgets/${encodeURIComponent(w.id)}/stats`).catch(() => null)
+ )
+ );
+
+ const totalViews = widgetStats.reduce((s, ws) => s + (ws?.stats?.total_views ?? 0), 0);
+ const totalChats = widgetStats.reduce((s, ws) => s + (ws?.stats?.total_chats ?? 0), 0);
+ const recentViews = widgetStats.reduce((s, ws) => {
+ const arr = ws?.stats?.recent_views_7d ?? [];
+ return s + arr.reduce((a, p) => a + (p.count ?? p.value ?? 0), 0);
+ }, 0);
+ const recentChats = widgetStats.reduce((s, ws) => {
+ const arr = ws?.stats?.recent_chats_7d ?? [];
+ return s + arr.reduce((a, p) => a + (p.count ?? p.value ?? 0), 0);
+ }, 0);
+
+ const revTotal = Number(revenue?.summary?.net_total ?? 0);
+ const revPayments = Number(revenue?.summary?.payment_count ?? 0);
+ const timeseries = revenue?.timeseries ?? [];
+ const bySkill = revenue?.by_skill ?? [];
+
+ root.innerHTML = '';
+
+ root.appendChild(renderRangeBar(root));
+ root.appendChild(renderKpis({ revTotal, revPayments, totalViews, totalChats, recentViews, recentChats, agentList, widgetList }));
+ root.appendChild(renderRevenueChart(timeseries));
+ root.appendChild(renderTwoCol(
+ renderSkillBreakdown(bySkill),
+ renderAgentTable(agentList, widgetList, widgetStats)
+ ));
+ root.appendChild(renderFunnel({ totalViews: recentViews, totalChats: recentChats, revPayments }));
+
+ root.querySelector('.ana-range-bar')?.addEventListener('click', e => {
+ const btn = e.target.closest('.ana-range-btn');
+ if (!btn) return;
+ const idx = [...root.querySelector('.ana-range-bar').children].indexOf(btn);
+ if (idx >= 0 && RANGES[idx]) {
+ range = RANGES[idx];
+ renderSkeletons(root);
+ loadAndRender(root);
+ }
+ });
+}
+
+function safe(fn) { return fn().catch(() => null); }
+
+// ── KPIs ──────────────────────────────────────────────────────────────────
+
+function renderKpis({ revTotal, revPayments, recentViews, recentChats, agentList, widgetList }) {
+ const el = document.createElement('div');
+ el.className = 'ana-kpi-row';
+ el.innerHTML = [
+ kpiCard('Revenue', formatUsdc(revTotal), `${revPayments} payment${revPayments !== 1 ? 's' : ''}`),
+ kpiCard('Widget Views', recentViews.toLocaleString(), `${range.label}`),
+ kpiCard('Conversations', recentChats.toLocaleString(), `${range.label}`),
+ kpiCard('Active Agents', agentList.length.toLocaleString(), `${widgetList.length} widget${widgetList.length !== 1 ? 's' : ''}`),
+ ].join('');
+ return el;
+}
+
+function kpiCard(label, value, sub) {
+ return `<div class="dn-panel ana-kpi"><div class="ana-kpi-label">${esc(label)}</div><div class="ana-kpi-value">${esc(value)}</div><div class="ana-kpi-sub">${esc(sub)}</div></div>`;
+}
+
+// ── Revenue chart (SVG bar chart) ─────────────────────────────────────────
+
+function renderRevenueChart(timeseries) {
+ const panel = document.createElement('div');
+ panel.className = 'dn-panel ana-chart-panel';
+
+ if (!timeseries.length) {
+ panel.innerHTML = `<div class="dn-panel-title">Revenue Over Time</div><div class="ana-chart-empty">No revenue data for this period. <a href="/dashboard/monetize">Set up monetization</a></div>`;
+ return panel;
+ }
+
+ const data = timeseries.map(p => ({
+ label: formatPeriod(p.period),
+ value: Number(p.net_total) / 1_000_000,
+ count: Number(p.count ?? 0),
+ }));
+
+ const max = Math.max(1, ...data.map(d => d.value));
+ const W = 800, H = 200, pad = 40, barGap = 4;
+ const barW = Math.max(4, (W - pad * 2) / data.length - barGap);
+ const chartH = H - pad;
+
+ let bars = '';
+ let labels = '';
+ const showEvery = Math.max(1, Math.ceil(data.length / 12));
+
+ data.forEach((d, i) => {
+ const x = pad + i * (barW + barGap);
+ const h = Math.max(1, (d.value / max) * chartH);
+ const y = H - h;
+ const usd = d.value.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
+ bars += `<rect x="${x}" y="${y}" width="${barW}" height="${h}" rx="2" fill="var(--nxt-accent, #6c8aff)" opacity="0.8"><title>${d.label}: ${usd} (${d.count} payments)</title></rect>`;
+ if (i % showEvery === 0) {
+ labels += `<text x="${x + barW / 2}" y="${H + 14}" text-anchor="middle" font-size="10" fill="var(--nxt-ink-dim, #8b8d98)">${d.label}</text>`;
+ }
+ });
+
+ const gridLines = Array.from({ length: 5 }, (_, i) => {
+ const y = Math.round(H - (i / 4) * chartH);
+ const val = ((i / 4) * max).toLocaleString('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 });
+ return `<line x1="${pad}" x2="${W}" y1="${y}" y2="${y}" stroke="var(--nxt-border, rgba(255,255,255,0.06))" stroke-width="0.5"/><text x="${pad - 6}" y="${y + 3}" text-anchor="end" font-size="10" fill="var(--nxt-ink-dim, #8b8d98)">${val}</text>`;
+ }).join('');
+
+ panel.innerHTML = `
+ <div class="dn-panel-title">Revenue Over Time</div>
+ <svg viewBox="0 0 ${W} ${H + 24}" preserveAspectRatio="xMidYMid meet" class="ana-chart-svg">
+ ${gridLines}
+ ${bars}
+ ${labels}
+ </svg>
+ `;
+ return panel;
+}
+
+function formatPeriod(p) {
+ const d = new Date(p);
+ if (isNaN(d)) return String(p).slice(0, 10);
+ return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
+}
+
+// ── Skill breakdown ───────────────────────────────────────────────────────
+
+function renderSkillBreakdown(bySkill) {
+ const panel = document.createElement('div');
+ panel.className = 'dn-panel';
+
+ if (!bySkill.length) {
+ panel.innerHTML = `<div class="dn-panel-title">Revenue by Skill</div><div class="ana-chart-empty">No skill revenue yet</div>`;
+ return panel;
+ }
+
+ const sorted = [...bySkill].sort((a, b) => Number(b.net_total) - Number(a.net_total)).slice(0, 10);
+ const max = Math.max(1, Number(sorted[0]?.net_total ?? 0));
+ const colors = ['#6c8aff', '#34d399', '#fbbf24', '#f472b6', '#a78bfa', '#fb923c', '#22d3ee', '#94a3b8'];
+
+ panel.innerHTML = `
+ <div class="dn-panel-title">Revenue by Skill</div>
+ <div class="ana-skill-list">
+ ${sorted.map((s, i) => {
+ const pct = Math.round((Number(s.net_total) / max) * 100);
+ const color = colors[i % colors.length];
+ return `
+ <div class="ana-skill-row">
+ <div class="ana-skill-name">${esc(s.skill)}</div>
+ <div class="ana-skill-bar-wrap">
+ <div class="ana-skill-bar" style="width:${pct}%;background:${color}"></div>
+ </div>
+ <div class="ana-skill-val">${formatUsdc(s.net_total)}</div>
+ <div class="ana-skill-count">${Number(s.count).toLocaleString()} tx</div>
+ </div>
+ `;
+ }).join('')}
+ </div>
+ `;
+ return panel;
+}
+
+// ── Agent table ───────────────────────────────────────────────────────────
+
+function renderAgentTable(agents, widgets, widgetStats) {
+ const panel = document.createElement('div');
+ panel.className = 'dn-panel';
+
+ if (!agents.length) {
+ panel.innerHTML = `<div class="dn-panel-title">Agent Performance</div><div class="ana-chart-empty">No agents yet. <a href="/dashboard/agents">Create one</a></div>`;
+ return panel;
+ }
+
+ const widgetMap = new Map();
+ widgets.forEach((w, i) => {
+ const stats = widgetStats[i];
+ if (!stats) return;
+ const key = w.avatar_id || w.agent_id;
+ if (key) {
+ const prev = widgetMap.get(key) || { views: 0, chats: 0 };
+ widgetMap.set(key, {
+ views: prev.views + (stats.stats?.total_views ?? 0),
+ chats: prev.chats + (stats.stats?.total_chats ?? 0),
+ });
+ }
+ });
+
+ const rows = agents.slice(0, 10).map(a => {
+ const wStats = widgetMap.get(a.avatar_id) || widgetMap.get(a.id) || { views: 0, chats: 0 };
+ const convRate = wStats.views > 0 ? ((wStats.chats / wStats.views) * 100).toFixed(1) : '—';
+ return `
+ <tr>
+ <td class="ana-tbl-name">${esc(a.name || a.slug || 'Unnamed')}</td>
+ <td>${wStats.views.toLocaleString()}</td>
+ <td>${wStats.chats.toLocaleString()}</td>
+ <td>${convRate}${convRate !== '—' ? '%' : ''}</td>
+ </tr>
+ `;
+ });
+
+ panel.innerHTML = `
+ <div class="dn-panel-title">Agent Performance</div>
+ <div class="ana-tbl-wrap">
+ <table class="ana-tbl">
+ <thead><tr><th>Agent</th><th>Views</th><th>Chats</th><th>Conv.</th></tr></thead>
+ <tbody>${rows.join('')}</tbody>
+ </table>
+ </div>
+ `;
+ return panel;
+}
+
+// ── Funnel ────────────────────────────────────────────────────────────────
+
+function renderFunnel({ totalViews, totalChats, revPayments }) {
+ const panel = document.createElement('div');
+ panel.className = 'dn-panel ana-funnel-panel';
+
+ const steps = [
+ { label: 'Widget Views', value: totalViews, color: '#6c8aff' },
+ { label: 'Conversations', value: totalChats, color: '#a78bfa' },
+ { label: 'Payments', value: revPayments, color: '#34d399' },
+ ];
+ const max = Math.max(1, steps[0].value);
+
+ panel.innerHTML = `
+ <div class="dn-panel-title">Conversion Funnel</div>
+ <div class="dn-panel-sub">How visitors convert from views to payments (${range.label})</div>
+ <div class="ana-funnel">
+ ${steps.map((s, i) => {
+ const pct = Math.round((s.value / max) * 100);
+ const dropoff = i > 0 && steps[i - 1].value > 0
+ ? ((1 - s.value / steps[i - 1].value) * 100).toFixed(1) + '% drop'
+ : '';
+ return `
+ <div class="ana-funnel-step">
+ <div class="ana-funnel-label">${esc(s.label)}</div>
+ <div class="ana-funnel-bar-wrap">
+ <div class="ana-funnel-bar" style="width:${Math.max(2, pct)}%;background:${s.color}"></div>
+ </div>
+ <div class="ana-funnel-val">${s.value.toLocaleString()}</div>
+ ${dropoff ? `<div class="ana-funnel-drop">${dropoff}</div>` : ''}
+ </div>
+ `;
+ }).join('')}
+ </div>
+ `;
+ return panel;
+}
+
+// ── Range bar ─────────────────────────────────────────────────────────────
+
+function renderRangeBar(root) {
+ const bar = document.createElement('div');
+ bar.className = 'ana-range-bar';
+ bar.innerHTML = RANGES.map(r =>
+ `<button class="ana-range-btn${r.key === range.key ? ' is-active' : ''}" data-range="${r.key}">${r.label}</button>`
+ ).join('');
+ return bar;
+}
+
+// ── Helpers ───────────────────────────────────────────────────────────────
+
+function renderTwoCol(left, right) {
+ const wrap = document.createElement('div');
+ wrap.className = 'ana-two-col';
+ wrap.appendChild(left);
+ wrap.appendChild(right);
+ return wrap;
+}
+
+// ── Styles ────────────────────────────────────────────────────────────────
+
+function injectStyles() {
+ if (document.getElementById('ana-styles')) return;
+ const style = document.createElement('style');
+ style.id = 'ana-styles';
+ style.textContent = `
+.ana-root { display: flex; flex-direction: column; gap: 18px; }
+
+.ana-range-bar { display: flex; gap: 6px; margin-bottom: 2px; }
+.ana-range-btn { padding: 6px 16px; border: 1px solid var(--nxt-border, rgba(255,255,255,0.07)); border-radius: 8px; background: none; color: var(--nxt-ink-dim, #8b8d98); font: inherit; font-size: 12px; font-weight: 500; cursor: pointer; transition: background 0.12s, color 0.12s, border-color 0.12s; }
+.ana-range-btn:hover { background: var(--nxt-bg-2, #1a1b22); color: var(--nxt-ink, #e4e5ea); }
+.ana-range-btn.is-active { background: rgba(108,138,255,0.12); color: #6c8aff; border-color: rgba(108,138,255,0.3); }
+
+.ana-kpi-row { display: grid; grid-template-columns: repeat(4, 1fr); gap: 14px; }
+.ana-kpi { padding: 18px 20px; }
+.ana-kpi-label { font-size: 12px; color: var(--nxt-ink-dim, #8b8d98); margin-bottom: 4px; }
+.ana-kpi-value { font-size: 26px; font-weight: 700; letter-spacing: -0.02em; }
+.ana-kpi-sub { font-size: 12px; color: var(--nxt-ink-faint, #5a5c68); margin-top: 2px; }
+
+.ana-chart-panel { padding: 20px; }
+.ana-chart-svg { width: 100%; height: auto; margin-top: 12px; }
+.ana-chart-empty { padding: 40px 0; text-align: center; color: var(--nxt-ink-dim, #8b8d98); font-size: 13px; }
+.ana-chart-empty a { color: #6c8aff; }
+
+.ana-two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
+
+.ana-skill-list { display: flex; flex-direction: column; gap: 8px; margin-top: 12px; }
+.ana-skill-row { display: grid; grid-template-columns: 120px 1fr 70px 60px; gap: 10px; align-items: center; font-size: 13px; }
+.ana-skill-name { font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.ana-skill-bar-wrap { height: 8px; background: var(--nxt-bg-2, #1a1b22); border-radius: 4px; overflow: hidden; }
+.ana-skill-bar { height: 100%; border-radius: 4px; transition: width 0.3s ease; }
+.ana-skill-val { text-align: right; font-weight: 600; }
+.ana-skill-count { text-align: right; color: var(--nxt-ink-dim, #8b8d98); font-size: 12px; }
+
+.ana-tbl-wrap { overflow-x: auto; margin-top: 12px; }
+.ana-tbl { width: 100%; border-collapse: collapse; font-size: 13px; }
+.ana-tbl th { text-align: left; font-weight: 500; color: var(--nxt-ink-dim, #8b8d98); font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; padding: 8px 10px; border-bottom: 1px solid var(--nxt-border, rgba(255,255,255,0.07)); }
+.ana-tbl td { padding: 10px; border-bottom: 1px solid var(--nxt-border, rgba(255,255,255,0.04)); }
+.ana-tbl-name { font-weight: 500; max-width: 140px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.ana-tbl tbody tr:hover { background: var(--nxt-bg-2, rgba(255,255,255,0.02)); }
+
+.ana-funnel-panel { padding: 20px; }
+.ana-funnel { display: flex; flex-direction: column; gap: 14px; margin-top: 16px; }
+.ana-funnel-step { display: grid; grid-template-columns: 120px 1fr 70px 80px; gap: 10px; align-items: center; }
+.ana-funnel-label { font-size: 13px; font-weight: 500; }
+.ana-funnel-bar-wrap { height: 24px; background: var(--nxt-bg-2, #1a1b22); border-radius: 6px; overflow: hidden; }
+.ana-funnel-bar { height: 100%; border-radius: 6px; transition: width 0.4s ease; }
+.ana-funnel-val { text-align: right; font-weight: 600; font-size: 15px; }
+.ana-funnel-drop { font-size: 11px; color: rgba(244,114,182,0.8); text-align: right; }
+
+@media (max-width: 900px) {
+ .ana-kpi-row { grid-template-columns: repeat(2, 1fr); }
+ .ana-two-col { grid-template-columns: 1fr; }
+ .ana-skill-row { grid-template-columns: 100px 1fr 60px; }
+ .ana-skill-count { display: none; }
+ .ana-funnel-step { grid-template-columns: 100px 1fr 60px; }
+ .ana-funnel-drop { display: none; }
+}
+@media (max-width: 600px) {
+ .ana-kpi-row { grid-template-columns: 1fr; }
+ .ana-kpi-value { font-size: 22px; }
+}
+`;
+ document.head.appendChild(style);
+}
diff --git a/src/dashboard-next/pages/home.js b/src/dashboard-next/pages/home.js
index e7b66f866..5bc29fa15 100644
--- a/src/dashboard-next/pages/home.js
+++ b/src/dashboard-next/pages/home.js
@@ -400,15 +400,15 @@ function renderOnboarding(host, { avatars, agents, widgets }) {
id: 'avatar',
label: 'Create your first avatar',
sub: 'Snap a selfie — your 3D agent is ready in under 60 seconds.',
- href: '/create',
- cta: 'Create avatar',
+ href: avatars.length === 0 ? '/start' : '/create',
+ cta: avatars.length === 0 ? 'Start wizard →' : 'Create another',
done: avatars.length > 0,
},
{
id: 'agent',
label: 'Build an agent identity',
sub: 'Give your avatar a name, personality, and on-chain address.',
- href: '/dashboard/agents',
+ href: agents.length === 0 ? '/start' : '/dashboard/agents',
cta: 'Set up agent',
done: agents.length > 0,
},
diff --git a/src/fact-checker-app.js b/src/fact-checker-app.js
new file mode 100644
index 000000000..b7eaf6ed4
--- /dev/null
+++ b/src/fact-checker-app.js
@@ -0,0 +1,382 @@
+// Fact Checker UI — drives pages/fact-checker.html.
+// Calls POST /api/x402/fact-check. Handles 402 payment required, errors,
+// loading skeleton, result rendering with source cards and attestation.
+
+const API_URL = '/api/x402/fact-check';
+
+// ── DOM refs ──────────────────────────────────────────────────────────────────
+
+function el(id) {
+ return document.getElementById(id);
+}
+
+// ── State ─────────────────────────────────────────────────────────────────────
+
+let lastClaim = '';
+let lastStrictness = 'medium';
+
+// ── Visibility helpers ────────────────────────────────────────────────────────
+
+function showOnly(panelId) {
+ for (const id of ['skeleton', 'result-panel', 'error-panel', 'payment-panel', 'empty-state']) {
+ const node = el(id);
+ if (!node) continue;
+ if (id === panelId) {
+ node.classList.add('active');
+ } else {
+ node.classList.remove('active');
+ }
+ }
+}
+
+function setLoading(active) {
+ const btn = el('check-btn');
+ const status = el('loading-status');
+ if (btn) btn.disabled = active;
+ if (status) status.classList.toggle('active', active);
+}
+
+// ── Rendering ─────────────────────────────────────────────────────────────────
+
+const VERDICT_LABELS = {
+ supported: 'SUPPORTED',
+ contradicted: 'CONTRADICTED',
+ mixed: 'MIXED',
+ insufficient: 'INSUFFICIENT',
+};
+
+function renderVerdict(data) {
+ const banner = el('verdict-banner');
+ const label = el('verdict-label');
+ const conf = el('verdict-confidence');
+ const claimEl = el('verdict-claim');
+
+ if (!banner || !label || !conf || !claimEl) return;
+
+ banner.className = `verdict-banner ${data.verdict}`;
+ label.textContent = VERDICT_LABELS[data.verdict] || data.verdict.toUpperCase();
+ conf.textContent = `${Math.round(data.confidence * 100)}% confidence`;
+ claimEl.textContent = `"${data.claim}"`;
+}
+
+function faviconUrl(sourceUrl) {
+ try {
+ const { hostname } = new URL(sourceUrl);
+ return `https://www.google.com/s2/favicons?domain=${encodeURIComponent(hostname)}&sz=32`;
+ } catch {
+ return '';
+ }
+}
+
+function stancePill(stance) {
+ const labels = { supports: 'Supports', contradicts: 'Contradicts', neutral: 'Neutral' };
+ return `<span class="stance-pill ${stance}">${labels[stance] || stance}</span>`;
+}
+
+function renderSources(sources) {
+ const grid = el('sources-grid');
+ if (!grid) return;
+
+ grid.innerHTML = sources
+ .map((s) => {
+ const favicon = faviconUrl(s.url);
+ const authorityPct = Math.round(s.weight * 100);
+ const shortUrl = (() => {
+ try {
+ return new URL(s.url).hostname.replace(/^www\./, '');
+ } catch {
+ return s.url.slice(0, 40);
+ }
+ })();
+ return `
+ <div class="source-card">
+ <div class="source-header">
+ ${favicon ? `<img class="source-favicon" src="${favicon}" alt="" loading="lazy" onerror="this.style.display='none'" />` : ''}
+ <div class="source-title">
+ <a href="${s.url}" target="_blank" rel="noopener noreferrer">${escHtml(s.title || shortUrl)}</a>
+ </div>
+ </div>
+ ${s.excerpt ? `<div class="source-excerpt">${escHtml(s.excerpt)}</div>` : ''}
+ <div class="source-footer">
+ ${stancePill(s.stance)}
+ <span class="source-authority">${shortUrl} · ${authorityPct}% authority</span>
+ </div>
+ </div>
+ `;
+ })
+ .join('');
+}
+
+function renderCostBreakdown(cost) {
+ const grid = el('cost-grid');
+ if (!grid) return;
+
+ const usdcVal = parseFloat(cost.totalUsdc || 0).toFixed(4);
+ grid.innerHTML = `
+ <div class="cost-item">
+ <span class="cost-key">Search calls</span>
+ <span class="cost-val">${cost.searchCalls}</span>
+ </div>
+ <div class="cost-item">
+ <span class="cost-key">LLM tokens</span>
+ <span class="cost-val">${cost.llmTokens.toLocaleString()}</span>
+ </div>
+ <div class="cost-item">
+ <span class="cost-key">Total USDC</span>
+ <span class="cost-val">$${usdcVal}</span>
+ </div>
+ ${cost.cachedAt ? `
+ <div class="cost-item">
+ <span class="cost-key">Cached</span>
+ <span class="cost-val" style="font-size:12px;">${new Date(cost.cachedAt).toLocaleString()}</span>
+ </div>` : ''}
+ `;
+}
+
+function renderAttestation(attestation) {
+ const hash = el('attest-hash');
+ if (hash) hash.textContent = attestation;
+}
+
+function renderResult(data) {
+ renderVerdict(data);
+ renderSources(data.sources || []);
+ renderCostBreakdown({
+ ...data.costBreakdown,
+ cachedAt: data.cachedAt,
+ });
+ renderAttestation(data.attestation || '');
+ showOnly('result-panel');
+}
+
+// ── 402 Payment required ──────────────────────────────────────────────────────
+
+function renderPaymentRequired(responseData) {
+ const descEl = el('payment-desc');
+ if (descEl) {
+ const price = responseData?.priceUsdc || '$0.10';
+ descEl.textContent = `This endpoint costs ${price} per check. Connect your wallet to pay with USDC on Base or Solana.`;
+ }
+
+ // Try to extract price from 402 body.
+ try {
+ const accepts = responseData?.accepts || [];
+ for (const acc of accepts) {
+ const atomics = parseInt(acc.amount || '0', 10);
+ if (atomics > 0) {
+ const usdc = (atomics / 1_000_000).toFixed(2);
+ if (acc.network?.includes('8453') || acc.network === 'base') {
+ const el2 = el('payment-price-base');
+ if (el2) el2.textContent = `$${usdc}`;
+ }
+ if (acc.network?.includes('solana') || acc.network?.includes('5eykt')) {
+ const el2 = el('payment-price-sol');
+ if (el2) el2.textContent = `$${usdc}`;
+ }
+ }
+ }
+ } catch {
+ // Best-effort.
+ }
+
+ showOnly('payment-panel');
+}
+
+// ── API call ──────────────────────────────────────────────────────────────────
+
+async function runCheck(claim, strictness) {
+ setLoading(true);
+ updateLoadingStatus('Submitting claim...');
+ showOnly('skeleton');
+
+ try {
+ const res = await fetch(API_URL, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ claim, strictness }),
+ });
+
+ if (res.status === 402) {
+ let body = null;
+ try {
+ body = await res.json();
+ } catch {
+ body = null;
+ }
+ renderPaymentRequired(body);
+ return;
+ }
+
+ if (!res.ok) {
+ let errBody = null;
+ try {
+ errBody = await res.json();
+ } catch {
+ errBody = null;
+ }
+ showError(
+ errBody?.error || errBody?.message || `HTTP ${res.status} error`,
+ errBody?.code || `http_${res.status}`,
+ );
+ return;
+ }
+
+ const data = await res.json();
+ renderResult(data);
+ } catch (err) {
+ showError(err.message || 'Network error — check your connection.', 'network_error');
+ } finally {
+ setLoading(false);
+ updateLoadingStatus('');
+ }
+}
+
+// ── Error rendering ───────────────────────────────────────────────────────────
+
+function showError(message, code) {
+ const msg = el('error-msg');
+ const codeEl = el('error-code');
+ if (msg) msg.textContent = message;
+ if (codeEl) codeEl.textContent = code ? `Error code: ${code}` : '';
+ showOnly('error-panel');
+}
+
+// ── Char counter ──────────────────────────────────────────────────────────────
+
+function updateCharCounter(len) {
+ const counter = el('char-counter');
+ if (!counter) return;
+ counter.textContent = `${len} / 1000`;
+ counter.className = 'char-counter';
+ if (len > 900) counter.classList.add('warn');
+ if (len >= 1000) counter.classList.add('over');
+}
+
+// ── Loading status text ───────────────────────────────────────────────────────
+
+const LOADING_STAGES = [
+ 'Generating search queries...',
+ 'Searching web sources...',
+ 'Analyzing evidence...',
+ 'Computing verdict...',
+];
+let loadingStageIdx = 0;
+let loadingInterval = null;
+
+function updateLoadingStatus(text) {
+ const el2 = el('loading-status');
+ if (!el2) return;
+ if (!text) {
+ clearInterval(loadingInterval);
+ loadingInterval = null;
+ el2.textContent = '';
+ return;
+ }
+ el2.textContent = text;
+ if (text === 'Submitting claim...') {
+ // Cycle through stages automatically.
+ loadingStageIdx = 0;
+ clearInterval(loadingInterval);
+ loadingInterval = setInterval(() => {
+ loadingStageIdx = (loadingStageIdx + 1) % LOADING_STAGES.length;
+ el2.textContent = LOADING_STAGES[loadingStageIdx];
+ }, 2000);
+ }
+}
+
+// ── Attestation toggle ────────────────────────────────────────────────────────
+
+function initAttestationToggle() {
+ const toggle = el('attest-toggle');
+ const body = el('attest-body');
+ if (!toggle || !body) return;
+
+ toggle.addEventListener('click', () => {
+ const expanded = toggle.getAttribute('aria-expanded') === 'true';
+ toggle.setAttribute('aria-expanded', String(!expanded));
+ body.classList.toggle('open', !expanded);
+ });
+}
+
+// ── Escape HTML ───────────────────────────────────────────────────────────────
+
+function escHtml(str) {
+ return String(str)
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+ .replace(/'/g, '&#39;');
+}
+
+// ── Init ──────────────────────────────────────────────────────────────────────
+
+export function init() {
+ const textarea = el('claim-input');
+ const checkBtn = el('check-btn');
+ const retryBtn = el('retry-btn');
+
+ // Char counter.
+ textarea?.addEventListener('input', () => {
+ updateCharCounter(textarea.value.length);
+ });
+
+ // Example chips.
+ document.querySelectorAll('.example-chip').forEach((chip) => {
+ chip.addEventListener('click', () => {
+ if (textarea) {
+ textarea.value = chip.dataset.claim || '';
+ updateCharCounter(textarea.value.length);
+ textarea.focus();
+ }
+ });
+ });
+
+ // Form submit.
+ checkBtn?.addEventListener('click', () => {
+ const claim = textarea?.value.trim() || '';
+ if (!claim) {
+ textarea?.focus();
+ return;
+ }
+ if (claim.length > 1000) {
+ showError('Claim is too long. Maximum is 1000 characters.', 'claim_too_long');
+ return;
+ }
+
+ const strictness =
+ document.querySelector('input[name="strictness"]:checked')?.value || 'medium';
+
+ lastClaim = claim;
+ lastStrictness = strictness;
+
+ // Hide empty state immediately.
+ const emptyState = el('empty-state');
+ if (emptyState) emptyState.classList.remove('active');
+
+ runCheck(claim, strictness);
+ });
+
+ // Retry button.
+ retryBtn?.addEventListener('click', () => {
+ if (lastClaim) {
+ runCheck(lastClaim, lastStrictness);
+ }
+ });
+
+ // Textarea keyboard shortcut (Ctrl/Cmd + Enter).
+ textarea?.addEventListener('keydown', (e) => {
+ if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
+ checkBtn?.click();
+ }
+ });
+
+ // Attestation collapsible.
+ initAttestationToggle();
+
+ // Show empty state on load.
+ showOnly('empty-state');
+}
+
+// Auto-init when the module is loaded.
+init();
diff --git a/src/marketplace.js b/src/marketplace.js
index a531c3171..49c19aef2 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -2813,6 +2813,7 @@ async function loadDetail(id) {
detailState = { agent, bookmarked: !!agent.bookmarked };
renderDetail(agent, !!agent.bookmarked);
loadReviews(id);
+ loadReputation(id);
// Versions + similar (best-effort).
Promise.all([
@@ -3294,6 +3295,333 @@ function renderSimilar(items) {
});
}
+// ── Reviews & Ratings ─────────────────────────────────────────────────────
+
+const reviewsState = {
+ agentId: null,
+ summary: null,
+ reviews: [],
+ myReview: null,
+ selectedRating: 0,
+ loading: false,
+ submitting: false,
+};
+
+async function loadReviews(agentId) {
+ reviewsState.agentId = agentId;
+ reviewsState.loading = true;
+ renderReviewsSkeleton();
+
+ try {
+ const r = await fetch(`${API}/marketplace/agents/${agentId}/reviews`, { credentials: 'include' });
+ if (!r.ok) throw new Error(`reviews fetch ${r.status}`);
+ const j = await r.json();
+ reviewsState.summary = j.data?.summary || { rating_avg: 0, rating_count: 0, breakdown: {} };
+ reviewsState.reviews = j.data?.reviews || [];
+ reviewsState.myReview = j.data?.my_review || null;
+ reviewsState.selectedRating = reviewsState.myReview?.rating || 0;
+ reviewsState.loading = false;
+ renderReviewsSummary();
+ renderReviewInput();
+ renderReviewsList();
+ } catch (err) {
+ console.error('[marketplace] reviews', err);
+ reviewsState.loading = false;
+ const msg = $('d-rating-msg');
+ if (msg) { msg.textContent = 'Could not load reviews.'; msg.classList.add('err'); }
+ }
+}
+
+function renderReviewsSkeleton() {
+ const summary = $('d-rating-summary');
+ if (summary) {
+ $('d-rating-avg').textContent = '—';
+ $('d-rating-stars').textContent = '☆☆☆☆☆';
+ $('d-rating-count').textContent = 'Loading…';
+ }
+ const list = $('d-reviews-list');
+ if (list) {
+ list.innerHTML = Array.from({ length: 3 }, () =>
+ `<div class="review-card skeleton"><div class="review-skeleton-line w60"></div><div class="review-skeleton-line w80"></div><div class="review-skeleton-line w40"></div></div>`
+ ).join('');
+ }
+ const input = $('d-rating-input');
+ if (input) input.hidden = true;
+ const msg = $('d-rating-msg');
+ if (msg) { msg.textContent = ''; msg.classList.remove('err', 'ok'); }
+}
+
+function starsHtml(rating, max = 5) {
+ const full = Math.round(rating);
+ let s = '';
+ for (let i = 1; i <= max; i++) s += i <= full ? '★' : '☆';
+ return s;
+}
+
+function renderReviewsSummary() {
+ const s = reviewsState.summary;
+ if (!s) return;
+ $('d-rating-avg').textContent = s.rating_count > 0 ? Number(s.rating_avg).toFixed(1) : '—';
+ $('d-rating-stars').innerHTML = s.rating_count > 0
+ ? `<span class="stars-filled">${starsHtml(s.rating_avg)}</span>`
+ : '☆☆☆☆☆';
+ $('d-rating-count').textContent = s.rating_count > 0
+ ? `${s.rating_count} review${s.rating_count === 1 ? '' : 's'}`
+ : 'No reviews yet';
+
+ const widget = $('d-rating-widget');
+ if (!widget) return;
+ let breakdownEl = widget.querySelector('.d-rating-breakdown');
+ if (!breakdownEl) {
+ breakdownEl = document.createElement('div');
+ breakdownEl.className = 'd-rating-breakdown';
+ const summaryEl = $('d-rating-summary');
+ if (summaryEl) summaryEl.after(breakdownEl);
+ }
+
+ if (s.rating_count === 0) {
+ breakdownEl.innerHTML = '';
+ return;
+ }
+
+ const bd = s.breakdown || {};
+ breakdownEl.innerHTML = [5, 4, 3, 2, 1].map((star) => {
+ const count = bd[star] || 0;
+ const pct = s.rating_count > 0 ? (count / s.rating_count * 100) : 0;
+ return `<div class="breakdown-row">
+ <span class="breakdown-label">${star}★</span>
+ <div class="breakdown-track"><div class="breakdown-fill" style="width:${pct.toFixed(1)}%"></div></div>
+ <span class="breakdown-count">${count}</span>
+ </div>`;
+ }).join('');
+}
+
+function renderReviewInput() {
+ const input = $('d-rating-input');
+ if (!input) return;
+
+ if (!isLikelyAuthed()) {
+ input.hidden = false;
+ input.innerHTML = `<a href="/login?next=${encodeURIComponent(location.pathname)}" class="review-login-cta">Sign in to leave a review</a>`;
+ return;
+ }
+
+ const isOwner = detailState?.agent?.is_mine || detailState?.agent?.is_owner;
+ if (isOwner) {
+ input.hidden = true;
+ return;
+ }
+
+ input.hidden = false;
+
+ if (reviewsState.myReview) {
+ input.innerHTML = `
+ <div class="review-mine-notice">
+ <span>Your review: <strong>${starsHtml(reviewsState.myReview.rating)}</strong></span>
+ <div class="review-mine-actions">
+ <button type="button" class="review-edit-btn" id="d-review-edit">Edit</button>
+ <button type="button" class="review-delete-btn" id="d-review-delete">Delete</button>
+ </div>
+ </div>
+ <div class="review-edit-form" id="d-review-edit-form" hidden>
+ <span style="font-size:12px;color:var(--mk-text-2)">Update your rating:</span>
+ <span class="stars review-star-picker" id="d-rating-pick-edit" role="radiogroup" aria-label="Pick a rating">
+ ${[1,2,3,4,5].map(i => `<button type="button" class="star-pick${i <= reviewsState.myReview.rating ? ' active' : ''}" data-rating="${i}" aria-label="${i} star${i>1?'s':''}">${i <= reviewsState.myReview.rating ? '★' : '☆'}</button>`).join('')}
+ </span>
+ <textarea id="d-review-body-edit" placeholder="Write a short review (optional)" maxlength="2000">${escapeHtml(reviewsState.myReview.body || '')}</textarea>
+ <div class="review-edit-actions">
+ <button type="button" class="submit-review" id="d-review-update">Update review</button>
+ <button type="button" class="review-cancel-btn" id="d-review-cancel">Cancel</button>
+ </div>
+ </div>`;
+
+ $('d-review-edit')?.addEventListener('click', () => {
+ $('d-review-edit-form').hidden = false;
+ $('d-review-edit').parentElement.parentElement.querySelector('.review-mine-notice')?.classList.add('editing');
+ });
+ $('d-review-cancel')?.addEventListener('click', () => {
+ $('d-review-edit-form').hidden = true;
+ document.querySelector('.review-mine-notice')?.classList.remove('editing');
+ });
+ $('d-review-delete')?.addEventListener('click', deleteReview);
+ $('d-review-update')?.addEventListener('click', () => {
+ const body = $('d-review-body-edit')?.value || '';
+ submitReview(reviewsState.selectedRating, body);
+ });
+ bindStarPicker($('d-rating-pick-edit'));
+ } else {
+ input.innerHTML = `
+ <span style="font-size:12px;color:var(--mk-text-2)">Your rating:</span>
+ <span class="stars review-star-picker" id="d-rating-pick" role="radiogroup" aria-label="Pick a rating">
+ ${[1,2,3,4,5].map(i => `<button type="button" class="star-pick" data-rating="${i}" aria-label="${i} star${i>1?'s':''}">${i <= reviewsState.selectedRating ? '★' : '☆'}</button>`).join('')}
+ </span>
+ <textarea id="d-review-body" placeholder="Write a short review (optional)" maxlength="2000"></textarea>
+ <button type="button" class="submit-review" id="d-review-submit" disabled>Submit review</button>`;
+ $('d-review-submit')?.addEventListener('click', () => {
+ const body = $('d-review-body')?.value || '';
+ submitReview(reviewsState.selectedRating, body);
+ });
+ bindStarPicker($('d-rating-pick'));
+ }
+
+ const msg = $('d-rating-msg');
+ if (msg) { msg.textContent = ''; msg.classList.remove('err', 'ok'); }
+}
+
+function bindStarPicker(container) {
+ if (!container) return;
+ const buttons = container.querySelectorAll('.star-pick');
+ buttons.forEach((btn) => {
+ btn.addEventListener('mouseenter', () => {
+ const r = Number(btn.dataset.rating);
+ buttons.forEach((b) => {
+ const v = Number(b.dataset.rating);
+ b.textContent = v <= r ? '★' : '☆';
+ b.classList.toggle('hover', v <= r);
+ });
+ });
+ btn.addEventListener('click', () => {
+ const r = Number(btn.dataset.rating);
+ reviewsState.selectedRating = r;
+ buttons.forEach((b) => {
+ const v = Number(b.dataset.rating);
+ b.textContent = v <= r ? '★' : '☆';
+ b.classList.toggle('active', v <= r);
+ });
+ const submit = container.closest('.d-rating-input, .review-edit-form')?.querySelector('.submit-review');
+ if (submit) submit.disabled = false;
+ });
+ });
+ container.addEventListener('mouseleave', () => {
+ const current = reviewsState.selectedRating;
+ buttons.forEach((b) => {
+ const v = Number(b.dataset.rating);
+ b.textContent = v <= current ? '★' : '☆';
+ b.classList.remove('hover');
+ b.classList.toggle('active', v <= current);
+ });
+ });
+}
+
+async function submitReview(rating, body) {
+ if (!rating || rating < 1 || rating > 5) return;
+ if (!reviewsState.agentId) return;
+ if (reviewsState.submitting) return;
+ reviewsState.submitting = true;
+ const msg = $('d-rating-msg');
+ if (msg) { msg.textContent = 'Submitting…'; msg.classList.remove('err', 'ok'); }
+
+ try {
+ const r = await apiPostWithCsrf(
+ `${API}/marketplace/agents/${reviewsState.agentId}/reviews`,
+ { rating, body: body?.trim() || null },
+ );
+ if (r.status === 401) {
+ location.href = `/login?next=${encodeURIComponent(location.pathname)}`;
+ return;
+ }
+ const j = await r.json();
+ if (!r.ok) throw new Error(j?.error_description || j?.error || 'Review submission failed');
+
+ if (msg) { msg.textContent = 'Review saved.'; msg.classList.add('ok'); }
+ setTimeout(() => { if (msg) msg.textContent = ''; }, 3000);
+ loadReviews(reviewsState.agentId);
+ } catch (err) {
+ console.error('[marketplace] submit review', err);
+ if (msg) { msg.textContent = err.message || 'Failed to save review.'; msg.classList.add('err'); }
+ } finally {
+ reviewsState.submitting = false;
+ }
+}
+
+async function deleteReview() {
+ if (!reviewsState.agentId) return;
+ if (reviewsState.submitting) return;
+ const msg = $('d-rating-msg');
+ if (msg) { msg.textContent = 'Deleting…'; msg.classList.remove('err', 'ok'); }
+ reviewsState.submitting = true;
+ try {
+ const token = await getCsrfToken();
+ _csrf = null;
+ const r = await fetch(`${API}/marketplace/agents/${reviewsState.agentId}/reviews`, {
+ method: 'DELETE',
+ headers: { 'X-CSRF-Token': token },
+ credentials: 'include',
+ });
+ if (!r.ok) {
+ const j = await r.json().catch(() => ({}));
+ throw new Error(j?.error_description || 'Delete failed');
+ }
+ reviewsState.myReview = null;
+ reviewsState.selectedRating = 0;
+ if (msg) { msg.textContent = 'Review deleted.'; msg.classList.add('ok'); }
+ setTimeout(() => { if (msg) msg.textContent = ''; }, 3000);
+ loadReviews(reviewsState.agentId);
+ } catch (err) {
+ console.error('[marketplace] delete review', err);
+ if (msg) { msg.textContent = err.message || 'Delete failed.'; msg.classList.add('err'); }
+ } finally {
+ reviewsState.submitting = false;
+ }
+}
+
+function renderReviewsList() {
+ const list = $('d-reviews-list');
+ if (!list) return;
+ const reviews = reviewsState.reviews || [];
+
+ if (!reviews.length) {
+ list.innerHTML = `<div class="reviews-empty">
+ <span class="reviews-empty-icon">☆</span>
+ <p>No reviews yet.</p>
+ <p class="reviews-empty-hint">Be the first to share your experience with this agent.</p>
+ </div>`;
+ return;
+ }
+
+ list.innerHTML = reviews.map((r) => {
+ const avatar = r.author_avatar
+ ? `<div class="review-avatar" style="background-image:url('${escapeHtml(r.author_avatar)}')"></div>`
+ : `<div class="review-avatar">${escapeHtml(initial(r.author_name))}</div>`;
+ const dateStr = liveTime(r.updated_at || r.created_at);
+ const edited = r.updated_at && r.created_at && r.updated_at !== r.created_at;
+ const mine = r.is_mine ? ' mine' : '';
+ return `<div class="review-card${mine}">
+ <div class="review-header">
+ ${avatar}
+ <div class="review-meta">
+ <span class="review-author">${escapeHtml(r.author_name)}</span>
+ <span class="review-date">${escapeHtml(dateStr)}${edited ? ' (edited)' : ''}</span>
+ </div>
+ <span class="review-stars">${starsHtml(r.rating)}</span>
+ </div>
+ ${r.body ? `<p class="review-body">${escapeHtml(r.body)}</p>` : ''}
+ </div>`;
+ }).join('');
+}
+
+// ── On-chain Reputation ──────────────────────────────────────────────────
+
+async function loadReputation(agentId) {
+ const card = $('d-reputation-card');
+ if (!card) return;
+ try {
+ const r = await fetch(`${API}/agents/${agentId}/reputation`);
+ if (!r.ok) { card.hidden = true; return; }
+ const j = await r.json();
+ const rep = j?.data;
+ if (!rep || (!rep.average && !rep.count)) { card.hidden = true; return; }
+ card.hidden = false;
+ const avg = Number(rep.average || 0);
+ const count = Number(rep.count || 0);
+ $('d-rep-avg').textContent = avg.toFixed(1);
+ $('d-rep-count').textContent = `${count} on-chain vote${count === 1 ? '' : 's'}`;
+ $('d-rep-stars').innerHTML = `<span class="stars-filled">${starsHtml(avg)}</span>`;
+ } catch {
+ if (card) card.hidden = true;
+ }
+}
+
// ── Tabs ──────────────────────────────────────────────────────────────────
function bindTabs() {
diff --git a/src/shopper-app.js b/src/shopper-app.js
new file mode 100644
index 000000000..b435e0cc3
--- /dev/null
+++ b/src/shopper-app.js
@@ -0,0 +1,240 @@
+// Endpoint Shopper UI — wires the form to /api/agents/endpoint-shopper-run
+// and renders the execution timeline with step-by-step animation.
+
+const STEP_ICONS = {
+ discover: '🔍',
+ plan: '🗺',
+ call: '⚡',
+ synthesize: '🧠',
+};
+
+const ACTION_LABELS = {
+ discover: 'Discover',
+ plan: 'Plan',
+ call: 'Call',
+ synthesize: 'Synthesize',
+};
+
+export function init() {
+ const taskInput = document.getElementById('task-input');
+ const runBtn = document.getElementById('run-btn');
+ const budgetSlider = document.getElementById('budget-slider');
+ const budgetDisplay = document.getElementById('budget-display');
+ const resultPanel = document.getElementById('result-panel');
+ const chipRow = document.getElementById('chip-row');
+
+ if (!taskInput || !runBtn || !resultPanel) return;
+
+ // Budget slider
+ budgetSlider.addEventListener('input', () => {
+ budgetDisplay.textContent = `$${parseFloat(budgetSlider.value).toFixed(2)}`;
+ });
+
+ // Example task chips
+ chipRow.addEventListener('click', (e) => {
+ const chip = e.target.closest('.chip');
+ if (!chip) return;
+ taskInput.value = chip.dataset.task || '';
+ taskInput.focus();
+ });
+
+ // Form submit
+ runBtn.addEventListener('click', () => {
+ const task = taskInput.value.trim();
+ if (!task) {
+ taskInput.focus();
+ return;
+ }
+ const maxCostUsd = parseFloat(budgetSlider.value) || 0.5;
+ runTask({ task, maxCostUsd, resultPanel, runBtn });
+ });
+
+ taskInput.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
+ runBtn.click();
+ }
+ });
+}
+
+async function runTask({ task, maxCostUsd, resultPanel, runBtn }) {
+ runBtn.disabled = true;
+ runBtn.textContent = 'Running…';
+
+ showSkeleton(resultPanel);
+
+ let data;
+ try {
+ const res = await fetch('/api/agents/endpoint-shopper-run', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ task, maxCostUsd }),
+ });
+
+ if (res.status === 402) {
+ const body = await res.json().catch(() => ({}));
+ showPaywallPrompt(resultPanel, body, res.headers.get('payment-required'));
+ return;
+ }
+
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({ error: `HTTP ${res.status}` }));
+ showError(resultPanel, body.error || body.message || `HTTP ${res.status}`);
+ return;
+ }
+
+ data = await res.json();
+ } catch (err) {
+ showError(resultPanel, err.message || 'Network error — please try again');
+ return;
+ } finally {
+ runBtn.disabled = false;
+ runBtn.innerHTML =
+ '<svg width="14" height="14" fill="none" viewBox="0 0 14 14"><path d="M3 2l9 5-9 5V2z" fill="currentColor"/></svg> Run Task';
+ }
+
+ renderResults(resultPanel, data, task);
+}
+
+function showSkeleton(panel) {
+ panel.innerHTML = `
+ <div class="skeleton-list">
+ <div class="skeleton-item"></div>
+ <div class="skeleton-item"></div>
+ <div class="skeleton-item"></div>
+ </div>
+ `;
+}
+
+function showError(panel, message) {
+ panel.innerHTML = `
+ <div class="error-card">
+ <p>${escHtml(message)}</p>
+ <button class="btn" onclick="location.reload()">Retry</button>
+ </div>
+ `;
+}
+
+function showPaywallPrompt(panel, body, paymentRequiredHeader) {
+ const reqParam = paymentRequiredHeader
+ ? encodeURIComponent(paymentRequiredHeader)
+ : '';
+ const paywallUrl = reqParam ? `/paywall.html?req=${reqParam}&return=${encodeURIComponent(location.pathname)}` : '/paywall.html';
+
+ panel.innerHTML = `
+ <div class="error-card" style="border-color: rgba(255,180,0,0.3)">
+ <p style="color:#e6a820">Payment required to use the Endpoint Shopper agent.</p>
+ <p style="color:var(--text-3); font-size:13.5px; margin:0 0 14px">
+ This endpoint costs USDC on Base or Solana. Use a wallet to pay and unlock the result.
+ </p>
+ <a class="btn primary" href="${paywallUrl}">Pay with Wallet</a>
+ </div>
+ `;
+}
+
+function renderResults(panel, data, task) {
+ panel.innerHTML = '';
+
+ const steps = Array.isArray(data.steps) ? data.steps : [];
+ const answer = data.result?.answer || '';
+ const totalCost = data.totalCostUsdc || '0.000000';
+
+ // Render step cards with staggered animation delays
+ const timeline = document.createElement('div');
+ timeline.className = 'timeline';
+
+ steps.forEach((step, i) => {
+ const card = buildStepCard(step, i);
+ timeline.appendChild(card);
+ });
+
+ panel.appendChild(timeline);
+
+ // Total cost row
+ if (steps.length > 0) {
+ const totalRow = document.createElement('div');
+ totalRow.className = 'total-row';
+ const costFloat = parseFloat(totalCost);
+ totalRow.innerHTML = `
+ <span class="total-lbl">Total spent</span>
+ <span class="total-val">${costFloat > 0 ? '$' + costFloat.toFixed(6) + ' USDC' : 'Free (no paid calls executed)'}</span>
+ `;
+ panel.appendChild(totalRow);
+ }
+
+ // Final answer card
+ if (answer) {
+ const answerCard = document.createElement('div');
+ answerCard.className = 'answer-card';
+ answerCard.style.animationDelay = `${steps.length * 120 + 80}ms`;
+ answerCard.style.opacity = '0';
+ answerCard.style.animation = `step-in 0.4s ease ${steps.length * 120 + 80}ms forwards`;
+ answerCard.innerHTML = `
+ <div class="answer-eyebrow">Final Answer</div>
+ <div class="answer-text">${escHtml(answer)}</div>
+ `;
+ panel.appendChild(answerCard);
+ }
+}
+
+function buildStepCard(step, index) {
+ const card = document.createElement('div');
+ card.className = 'step-card';
+ card.style.animationDelay = `${index * 120}ms`;
+
+ const action = step.action || 'call';
+ const icon = STEP_ICONS[action] || '•';
+ const actionLabel = ACTION_LABELS[action] || action;
+ const costFloat = parseFloat(step.costUsdc || '0');
+ const costNonzero = costFloat > 0;
+
+ let outputHtml = '';
+ if (step.output !== undefined && step.output !== null) {
+ const outputStr = typeof step.output === 'string'
+ ? step.output
+ : JSON.stringify(step.output, null, 2);
+
+ // Check for payment_required flag
+ const is402 = step.output?.payment_required === true;
+ if (is402) {
+ outputHtml = `<div class="step-output"><span class="badge-402">402 Payment Required</span> ${escHtml(JSON.stringify(step.output?.requirements || {}, null, 2)).slice(0, 300)}</div>`;
+ } else if (outputStr && outputStr !== '{}' && outputStr !== '[]') {
+ outputHtml = `<div class="step-output">${escHtml(outputStr.slice(0, 600))}${outputStr.length > 600 ? '\n…' : ''}</div>`;
+ }
+ }
+
+ const endpointHtml = step.endpoint
+ ? `<div class="step-endpoint">${escHtml(step.endpoint)}</div>`
+ : '';
+
+ card.innerHTML = `
+ <div class="step-icon">${icon}</div>
+ <div class="step-body">
+ <div class="step-meta">
+ <span class="step-num">Step ${step.step}</span>
+ <span class="step-action">${escHtml(actionLabel)}</span>
+ <span class="step-cost${costNonzero ? ' nonzero' : ''}">${costNonzero ? '$' + costFloat.toFixed(6) : '0'}</span>
+ </div>
+ <div class="step-desc">${escHtml(step.description || '')}</div>
+ ${endpointHtml}
+ ${outputHtml}
+ </div>
+ `;
+
+ return card;
+}
+
+function escHtml(str) {
+ return String(str)
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+ .replace(/'/g, '&#39;');
+}
+
+// Auto-init on DOMContentLoaded
+if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', init);
+} else {
+ init();
+}
diff --git a/src/skills.js b/src/skills.js
new file mode 100644
index 000000000..1b9efdd82
--- /dev/null
+++ b/src/skills.js
@@ -0,0 +1,739 @@
+// Skills Marketplace — browse, search, and install agent skills.
+//
+// Fetches from /api/skills (list), /api/skills/categories, /api/skills/:id (detail).
+// Supports search, category filtering, sort, cursor pagination, and detail drawer.
+
+const PAGE_SIZE = 20;
+const DEBOUNCE_MS = 250;
+const SORT_OPTIONS = [
+ { key: 'popular', label: 'Popular' },
+ { key: 'new', label: 'New' },
+ { key: 'az', label: 'A–Z' },
+];
+
+const CATEGORY_ICONS = {
+ general: '\u{1F9E9}',
+ automation: '\u{2699}️',
+ data: '\u{1F4CA}',
+ communication: '\u{1F4AC}',
+ finance: '\u{1F4B0}',
+ media: '\u{1F3A8}',
+ development: '\u{1F4BB}',
+ analytics: '\u{1F50D}',
+ security: '\u{1F512}',
+ education: '\u{1F4DA}',
+ health: '\u{1F3E5}',
+ productivity: '\u{1F4DD}',
+ social: '\u{1F310}',
+ marketing: '\u{1F4E2}',
+};
+
+let state = {
+ skills: [],
+ categories: [],
+ query: '',
+ category: null,
+ sort: 'popular',
+ cursor: null,
+ hasMore: false,
+ loading: false,
+ detailSkill: null,
+ detailLoading: false,
+ user: null,
+};
+
+let els = {};
+
+(async function boot() {
+ injectShell();
+ injectStyles();
+ cacheEls();
+ bindEvents();
+ await Promise.all([loadUser(), loadCategories(), loadSkills()]);
+})();
+
+function esc(s) {
+ return String(s ?? '').replace(/[&<>"']/g, c =>
+ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
+}
+
+function relTime(iso) {
+ const ms = Date.now() - new Date(iso).getTime();
+ const s = Math.round(ms / 1000);
+ if (s < 60) return `${s}s ago`;
+ const m = Math.round(s / 60);
+ if (m < 60) return `${m}m ago`;
+ const h = Math.round(m / 60);
+ if (h < 48) return `${h}h ago`;
+ const d = Math.round(h / 24);
+ if (d < 30) return `${d}d ago`;
+ return new Date(iso).toLocaleDateString();
+}
+
+async function api(path) {
+ const res = await fetch(path, { credentials: 'include' });
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({}));
+ throw Object.assign(new Error(body.message || res.statusText), { status: res.status });
+ }
+ return res.json();
+}
+
+async function loadUser() {
+ try {
+ const data = await api('/api/auth/me');
+ state.user = data?.user ?? null;
+ } catch {
+ state.user = null;
+ }
+}
+
+// ── Shell ─────────────────────────────────────────────────────────────────
+
+function injectShell() {
+ document.body.innerHTML = `
+ <div class="sk-page">
+ <header class="sk-header" id="sk-header"></header>
+ <div class="sk-layout">
+ <aside class="sk-sidebar" id="sk-sidebar">
+ <div class="sk-sidebar-inner"></div>
+ </aside>
+ <main class="sk-main" id="sk-main">
+ <div class="sk-toolbar" id="sk-toolbar"></div>
+ <div class="sk-grid" id="sk-grid" role="list" aria-label="Skills"></div>
+ <div class="sk-load-more" id="sk-load-more"></div>
+ </main>
+ </div>
+ <div class="sk-drawer-backdrop" id="sk-backdrop" hidden></div>
+ <aside class="sk-drawer" id="sk-drawer" hidden aria-label="Skill detail">
+ <div class="sk-drawer-inner" id="sk-drawer-inner"></div>
+ </aside>
+ </div>
+ `;
+ loadNav();
+}
+
+async function loadNav() {
+ try {
+ const res = await fetch('/nav.html');
+ if (!res.ok) return;
+ const html = await res.text();
+ const header = document.getElementById('sk-header');
+ header.innerHTML = html;
+ const script = document.createElement('script');
+ script.src = '/nav.js';
+ script.defer = true;
+ document.head.appendChild(script);
+ } catch { /* nav is optional */ }
+}
+
+function cacheEls() {
+ els = {
+ sidebar: document.querySelector('#sk-sidebar .sk-sidebar-inner'),
+ toolbar: document.getElementById('sk-toolbar'),
+ grid: document.getElementById('sk-grid'),
+ loadMore: document.getElementById('sk-load-more'),
+ drawer: document.getElementById('sk-drawer'),
+ drawerInner: document.getElementById('sk-drawer-inner'),
+ backdrop: document.getElementById('sk-backdrop'),
+ };
+}
+
+// ── Categories ────────────────────────────────────────────────────────────
+
+async function loadCategories() {
+ try {
+ const data = await api('/api/skills/categories');
+ state.categories = data?.categories ?? [];
+ } catch {
+ state.categories = [];
+ }
+ renderSidebar();
+}
+
+function renderSidebar() {
+ const total = state.categories.reduce((s, c) => s + c.count, 0);
+ const cats = state.categories;
+
+ els.sidebar.innerHTML = `
+ <div class="sk-sb-section">
+ <div class="sk-sb-title">Categories</div>
+ <button class="sk-sb-cat${state.category === null ? ' is-active' : ''}" data-cat="">
+ <span class="sk-sb-cat-icon" aria-hidden="true">*</span>
+ <span class="sk-sb-cat-label">All skills</span>
+ <span class="sk-sb-cat-count">${total}</span>
+ </button>
+ ${cats.map(c => `
+ <button class="sk-sb-cat${state.category === c.slug ? ' is-active' : ''}" data-cat="${esc(c.slug)}">
+ <span class="sk-sb-cat-icon" aria-hidden="true">${CATEGORY_ICONS[c.slug] || '\u{1F4E6}'}</span>
+ <span class="sk-sb-cat-label">${esc(c.label)}</span>
+ <span class="sk-sb-cat-count">${c.count}</span>
+ </button>
+ `).join('')}
+ </div>
+ <div class="sk-sb-section sk-sb-cta">
+ <a href="/dashboard/monetize" class="sk-btn sk-btn-primary sk-btn-block">Publish a Skill</a>
+ </div>
+ `;
+}
+
+// ── Toolbar ───────────────────────────────────────────────────────────────
+
+function renderToolbar() {
+ const catLabel = state.category
+ ? (state.categories.find(c => c.slug === state.category)?.label ?? state.category)
+ : 'All skills';
+
+ els.toolbar.innerHTML = `
+ <div class="sk-toolbar-left">
+ <h1 class="sk-page-title">Skills</h1>
+ <span class="sk-toolbar-cat">${esc(catLabel)}</span>
+ </div>
+ <div class="sk-toolbar-right">
+ <div class="sk-search-wrap" role="search">
+ <svg class="sk-search-icon" viewBox="0 0 16 16" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><circle cx="7" cy="7" r="4.5"/><path d="M13 13l-3-3"/></svg>
+ <input type="text" class="sk-search" id="sk-search" placeholder="Search skills..." value="${esc(state.query)}" autocomplete="off" spellcheck="false" aria-label="Search skills" />
+ <kbd class="sk-search-kbd" aria-hidden="true">/</kbd>
+ </div>
+ <div class="sk-sort" role="group" aria-label="Sort">
+ ${SORT_OPTIONS.map(s => `
+ <button class="sk-sort-btn${state.sort === s.key ? ' is-active' : ''}" data-sort="${s.key}">${s.label}</button>
+ `).join('')}
+ </div>
+ </div>
+ `;
+}
+
+// ── Grid ──────────────────────────────────────────────────────────────────
+
+async function loadSkills(append = false) {
+ if (state.loading) return;
+ state.loading = true;
+
+ if (!append) {
+ state.cursor = null;
+ state.skills = [];
+ renderSkeletons();
+ }
+ renderToolbar();
+ renderLoadMore();
+
+ const params = new URLSearchParams();
+ params.set('limit', PAGE_SIZE);
+ params.set('sort', state.sort);
+ if (state.query) params.set('q', state.query);
+ if (state.category) params.set('category', state.category);
+ if (state.cursor) params.set('cursor', state.cursor);
+
+ try {
+ const data = await api(`/api/skills?${params}`);
+ const skills = data?.skills ?? [];
+ state.hasMore = !!data?.next_cursor;
+ state.cursor = data?.next_cursor ?? null;
+
+ if (append) {
+ state.skills.push(...skills);
+ } else {
+ state.skills = skills;
+ }
+ } catch (err) {
+ if (!append) state.skills = [];
+ state.hasMore = false;
+ console.error('[skills] load failed:', err);
+ }
+
+ state.loading = false;
+ renderGrid();
+ renderLoadMore();
+}
+
+function renderSkeletons() {
+ els.grid.innerHTML = Array.from({ length: 8 }, () => `
+ <div class="sk-card sk-card-skeleton" aria-hidden="true">
+ <div class="sk-card-head">
+ <div class="sk-skel sk-skel-icon"></div>
+ <div style="flex:1">
+ <div class="sk-skel" style="height:14px;width:60%;margin-bottom:6px"></div>
+ <div class="sk-skel" style="height:11px;width:40%"></div>
+ </div>
+ </div>
+ <div class="sk-skel" style="height:12px;width:90%;margin:8px 0"></div>
+ <div class="sk-skel" style="height:12px;width:70%"></div>
+ <div class="sk-card-foot">
+ <div class="sk-skel" style="height:11px;width:50px"></div>
+ <div class="sk-skel" style="height:11px;width:50px"></div>
+ </div>
+ </div>
+ `).join('');
+}
+
+function renderGrid() {
+ if (!state.skills.length && !state.loading) {
+ els.grid.innerHTML = renderEmpty();
+ return;
+ }
+ els.grid.innerHTML = state.skills.map(renderCard).join('');
+}
+
+function renderEmpty() {
+ if (state.query || state.category) {
+ return `
+ <div class="sk-empty">
+ <div class="sk-empty-icon">
+ <svg viewBox="0 0 48 48" width="48" height="48" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><circle cx="20" cy="20" r="14"/><path d="M30 30l10 10"/><path d="M15 20h10" opacity="0.4"/></svg>
+ </div>
+ <h3 class="sk-empty-title">No skills found</h3>
+ <p class="sk-empty-sub">Try a different search term or category.</p>
+ <button class="sk-btn" onclick="document.getElementById('sk-search').value='';document.getElementById('sk-search').dispatchEvent(new Event('input'))">Clear search</button>
+ </div>
+ `;
+ }
+ return `
+ <div class="sk-empty">
+ <div class="sk-empty-icon">
+ <svg viewBox="0 0 48 48" width="48" height="48" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><rect x="6" y="8" width="36" height="32" rx="4"/><path d="M6 18h36"/><path d="M18 28h12"/><path d="M21 33h6"/></svg>
+ </div>
+ <h3 class="sk-empty-title">No skills yet</h3>
+ <p class="sk-empty-sub">Be the first to publish a skill that other agents can use.</p>
+ <a href="/dashboard/monetize" class="sk-btn sk-btn-primary">Publish a Skill</a>
+ </div>
+ `;
+}
+
+function renderCard(skill) {
+ const icon = CATEGORY_ICONS[skill.category] || '\u{1F4E6}';
+ const stars = renderStars(skill.avg_rating);
+ const price = skill.price_per_call_usd > 0
+ ? `<span class="sk-card-price">$${skill.price_per_call_usd.toFixed(skill.price_per_call_usd < 0.01 ? 4 : 2)}/call</span>`
+ : '<span class="sk-card-free">Free</span>';
+
+ return `
+ <article class="sk-card" role="listitem" data-id="${esc(skill.id)}" tabindex="0" aria-label="${esc(skill.name)}">
+ <div class="sk-card-head">
+ <span class="sk-card-icon" aria-hidden="true">${icon}</span>
+ <div class="sk-card-meta">
+ <h3 class="sk-card-name">${esc(skill.name)}</h3>
+ <span class="sk-card-author">${skill.author ? esc(skill.author.display_name) : 'Anonymous'}</span>
+ </div>
+ ${price}
+ </div>
+ <p class="sk-card-desc">${esc(skill.description)}</p>
+ ${skill.tags?.length ? `<div class="sk-card-tags">${skill.tags.slice(0, 4).map(t => `<span class="sk-tag">${esc(t)}</span>`).join('')}</div>` : ''}
+ <div class="sk-card-foot">
+ <span class="sk-card-stat" title="Installs">
+ <svg viewBox="0 0 14 14" width="12" height="12" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"><path d="M7 2v8M4 7l3 3 3-3"/><path d="M2 11h10"/></svg>
+ ${(skill.install_count || 0).toLocaleString()}
+ </span>
+ <span class="sk-card-stat" title="Rating">${stars} <span class="sk-card-rating-num">${skill.avg_rating > 0 ? skill.avg_rating.toFixed(1) : ''}</span></span>
+ <span class="sk-card-cat">${esc(skill.category)}</span>
+ </div>
+ </article>
+ `;
+}
+
+function renderStars(rating) {
+ const full = Math.floor(rating);
+ const half = rating - full >= 0.3;
+ const empty = 5 - full - (half ? 1 : 0);
+ let out = '';
+ for (let i = 0; i < full; i++) out += '<svg class="sk-star sk-star-full" viewBox="0 0 12 12" width="12" height="12"><path d="M6 1l1.5 3 3.3.5-2.4 2.3.6 3.3L6 8.3 3 10.1l.6-3.3L1.2 4.5l3.3-.5z" fill="currentColor"/></svg>';
+ if (half) out += '<svg class="sk-star sk-star-half" viewBox="0 0 12 12" width="12" height="12"><path d="M6 1l1.5 3 3.3.5-2.4 2.3.6 3.3L6 8.3 3 10.1l.6-3.3L1.2 4.5l3.3-.5z" fill="currentColor" opacity="0.3"/><path d="M6 1v7.3L3 10.1l.6-3.3L1.2 4.5l3.3-.5z" fill="currentColor"/></svg>';
+ for (let i = 0; i < empty; i++) out += '<svg class="sk-star" viewBox="0 0 12 12" width="12" height="12"><path d="M6 1l1.5 3 3.3.5-2.4 2.3.6 3.3L6 8.3 3 10.1l.6-3.3L1.2 4.5l3.3-.5z" fill="currentColor" opacity="0.15"/></svg>';
+ return out;
+}
+
+function renderLoadMore() {
+ if (state.loading) {
+ els.loadMore.innerHTML = '<div class="sk-spinner" aria-label="Loading"></div>';
+ return;
+ }
+ if (state.hasMore) {
+ els.loadMore.innerHTML = '<button class="sk-btn" id="sk-more-btn">Load more</button>';
+ } else if (state.skills.length > 0) {
+ els.loadMore.innerHTML = `<p class="sk-load-end">${state.skills.length} skill${state.skills.length !== 1 ? 's' : ''}</p>`;
+ } else {
+ els.loadMore.innerHTML = '';
+ }
+}
+
+// ── Detail drawer ─────────────────────────────────────────────────────────
+
+async function openDetail(id) {
+ state.detailLoading = true;
+ els.drawer.hidden = false;
+ els.backdrop.hidden = false;
+ document.body.classList.add('sk-drawer-open');
+ renderDetailSkeleton();
+
+ try {
+ const data = await api(`/api/skills/${encodeURIComponent(id)}`);
+ state.detailSkill = data?.skill ?? null;
+ } catch {
+ state.detailSkill = null;
+ }
+ state.detailLoading = false;
+ renderDetail();
+}
+
+function closeDetail() {
+ els.drawer.hidden = true;
+ els.backdrop.hidden = true;
+ document.body.classList.remove('sk-drawer-open');
+ state.detailSkill = null;
+}
+
+function renderDetailSkeleton() {
+ els.drawerInner.innerHTML = `
+ <div class="sk-detail-head">
+ <div class="sk-skel" style="height:18px;width:60%;margin-bottom:8px"></div>
+ <div class="sk-skel" style="height:13px;width:40%"></div>
+ </div>
+ <div style="padding:20px">
+ <div class="sk-skel" style="height:13px;width:100%;margin-bottom:8px"></div>
+ <div class="sk-skel" style="height:13px;width:85%;margin-bottom:8px"></div>
+ <div class="sk-skel" style="height:13px;width:70%;margin-bottom:20px"></div>
+ <div class="sk-skel" style="height:38px;width:100%;border-radius:8px"></div>
+ </div>
+ `;
+}
+
+function renderDetail() {
+ const s = state.detailSkill;
+ if (!s) {
+ els.drawerInner.innerHTML = `
+ <div class="sk-detail-head">
+ <button class="sk-detail-close" aria-label="Close" data-action="close-detail">&times;</button>
+ <h2>Skill not found</h2>
+ </div>
+ <div style="padding:20px;color:rgba(255,255,255,0.5)">This skill may have been removed.</div>
+ `;
+ return;
+ }
+
+ const icon = CATEGORY_ICONS[s.category] || '\u{1F4E6}';
+ const stars = renderStars(s.avg_rating);
+ const price = s.price_per_call_usd > 0
+ ? `$${s.price_per_call_usd.toFixed(s.price_per_call_usd < 0.01 ? 4 : 2)} per call`
+ : 'Free';
+
+ const schemaHtml = s.schema_json?.length
+ ? `<div class="sk-detail-section">
+ <h3 class="sk-detail-section-title">Tool Schema</h3>
+ <div class="sk-detail-schema">
+ ${s.schema_json.map(tool => `
+ <div class="sk-schema-tool">
+ <div class="sk-schema-name">${esc(tool.function?.name ?? 'unknown')}</div>
+ ${tool.function?.parameters ? `<pre class="sk-schema-params">${esc(JSON.stringify(tool.function.parameters, null, 2))}</pre>` : ''}
+ </div>
+ `).join('')}
+ </div>
+ </div>`
+ : '';
+
+ const contentHtml = s.content
+ ? `<div class="sk-detail-section">
+ <h3 class="sk-detail-section-title">Content</h3>
+ <div class="sk-detail-content">${esc(s.content).replace(/\n/g, '<br>')}</div>
+ </div>`
+ : '';
+
+ els.drawerInner.innerHTML = `
+ <div class="sk-detail-head">
+ <button class="sk-detail-close" aria-label="Close" data-action="close-detail">
+ <svg viewBox="0 0 14 14" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M2 2l10 10M12 2L2 12"/></svg>
+ </button>
+ <div class="sk-detail-icon">${icon}</div>
+ <h2 class="sk-detail-name">${esc(s.name)}</h2>
+ <div class="sk-detail-author">by ${s.author ? esc(s.author.display_name) : 'Anonymous'}</div>
+ </div>
+ <div class="sk-detail-body">
+ <div class="sk-detail-stats">
+ <div class="sk-detail-stat">
+ <div class="sk-detail-stat-val">${(s.install_count || 0).toLocaleString()}</div>
+ <div class="sk-detail-stat-label">Installs</div>
+ </div>
+ <div class="sk-detail-stat">
+ <div class="sk-detail-stat-val">${stars} ${s.avg_rating > 0 ? s.avg_rating.toFixed(1) : '—'}</div>
+ <div class="sk-detail-stat-label">${s.rating_count || 0} rating${s.rating_count !== 1 ? 's' : ''}</div>
+ </div>
+ <div class="sk-detail-stat">
+ <div class="sk-detail-stat-val">${price}</div>
+ <div class="sk-detail-stat-label">Pricing</div>
+ </div>
+ </div>
+
+ <p class="sk-detail-desc">${esc(s.description)}</p>
+
+ ${s.tags?.length ? `<div class="sk-detail-tags">${s.tags.map(t => `<span class="sk-tag">${esc(t)}</span>`).join('')}</div>` : ''}
+
+ <div class="sk-detail-actions">
+ ${s.installed
+ ? '<button class="sk-btn sk-btn-installed" disabled>Installed</button>'
+ : '<button class="sk-btn sk-btn-primary sk-btn-lg" data-action="install">Install Skill</button>'
+ }
+ <button class="sk-btn sk-btn-outline" data-action="try-skill">Try It</button>
+ </div>
+
+ ${schemaHtml}
+ ${contentHtml}
+
+ <div class="sk-detail-section sk-detail-meta">
+ <div class="sk-detail-meta-row"><span>Category</span><span>${esc(s.category)}</span></div>
+ <div class="sk-detail-meta-row"><span>Slug</span><code>${esc(s.slug)}</code></div>
+ <div class="sk-detail-meta-row"><span>Added</span><time datetime="${esc(s.created_at)}">${relTime(s.created_at)}</time></div>
+ </div>
+ </div>
+ `;
+}
+
+// ── Events ────────────────────────────────────────────────────────────────
+
+function bindEvents() {
+ let searchTimer = null;
+
+ document.addEventListener('input', (e) => {
+ if (e.target.id === 'sk-search') {
+ clearTimeout(searchTimer);
+ searchTimer = setTimeout(() => {
+ state.query = e.target.value.trim();
+ loadSkills();
+ }, DEBOUNCE_MS);
+ }
+ });
+
+ document.addEventListener('click', (e) => {
+ const catBtn = e.target.closest('[data-cat]');
+ if (catBtn) {
+ state.category = catBtn.dataset.cat || null;
+ renderSidebar();
+ loadSkills();
+ return;
+ }
+
+ const sortBtn = e.target.closest('[data-sort]');
+ if (sortBtn) {
+ state.sort = sortBtn.dataset.sort;
+ loadSkills();
+ return;
+ }
+
+ if (e.target.id === 'sk-more-btn') {
+ loadSkills(true);
+ return;
+ }
+
+ const card = e.target.closest('.sk-card[data-id]');
+ if (card) {
+ openDetail(card.dataset.id);
+ return;
+ }
+
+ if (e.target.closest('[data-action="close-detail"]') || e.target.id === 'sk-backdrop') {
+ closeDetail();
+ return;
+ }
+
+ if (e.target.closest('[data-action="try-skill"]') && state.detailSkill) {
+ window.location.href = `/brain?skill=${encodeURIComponent(state.detailSkill.slug)}`;
+ return;
+ }
+ });
+
+ document.addEventListener('keydown', (e) => {
+ if (e.key === '/' && !e.ctrlKey && !e.metaKey && document.activeElement?.tagName !== 'INPUT') {
+ e.preventDefault();
+ document.getElementById('sk-search')?.focus();
+ }
+ if (e.key === 'Escape' && !els.drawer.hidden) {
+ closeDetail();
+ }
+ });
+
+ document.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' && e.target.closest('.sk-card[data-id]')) {
+ openDetail(e.target.closest('.sk-card').dataset.id);
+ }
+ });
+}
+
+// ── Styles ────────────────────────────────────────────────────────────────
+
+function injectStyles() {
+ const style = document.createElement('style');
+ style.textContent = `
+:root {
+ --sk-bg: #0c0d10;
+ --sk-bg-1: #131419;
+ --sk-bg-2: #1a1b22;
+ --sk-bg-3: #22232c;
+ --sk-ink: #e4e5ea;
+ --sk-ink-dim: #8b8d98;
+ --sk-ink-faint: #5a5c68;
+ --sk-accent: #6c8aff;
+ --sk-accent-dim: rgba(108,138,255,0.12);
+ --sk-green: #34d399;
+ --sk-border: rgba(255,255,255,0.07);
+ --sk-radius: 10px;
+ --sk-radius-lg: 14px;
+ --sk-sidebar-w: 260px;
+ --sk-drawer-w: 440px;
+ --sk-header-h: 56px;
+}
+*, *::before, *::after { box-sizing: border-box; }
+html, body { margin: 0; height: 100%; background: var(--sk-bg); color: var(--sk-ink); font: 14px/1.5 'Inter', system-ui, sans-serif; -webkit-font-smoothing: antialiased; }
+a { color: inherit; text-decoration: none; }
+
+.sk-page { display: flex; flex-direction: column; min-height: 100vh; }
+.sk-header { position: sticky; top: 0; z-index: 100; background: rgba(12,13,16,0.85); backdrop-filter: blur(12px); border-bottom: 1px solid var(--sk-border); }
+.sk-layout { display: grid; grid-template-columns: var(--sk-sidebar-w) 1fr; flex: 1; }
+.sk-sidebar { position: sticky; top: var(--sk-header-h); height: calc(100vh - var(--sk-header-h)); overflow-y: auto; border-right: 1px solid var(--sk-border); padding: 20px 0; }
+.sk-sidebar-inner { padding: 0 16px; }
+.sk-main { padding: 24px 32px; min-width: 0; }
+
+/* Sidebar */
+.sk-sb-section { margin-bottom: 24px; }
+.sk-sb-title { font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.06em; color: var(--sk-ink-dim); padding: 0 10px; margin-bottom: 8px; }
+.sk-sb-cat { display: flex; align-items: center; gap: 8px; width: 100%; padding: 7px 10px; border: none; background: none; color: var(--sk-ink-dim); font: inherit; font-size: 13px; border-radius: 7px; cursor: pointer; transition: background 0.15s, color 0.15s; }
+.sk-sb-cat:hover { background: var(--sk-bg-2); color: var(--sk-ink); }
+.sk-sb-cat.is-active { background: var(--sk-accent-dim); color: var(--sk-accent); font-weight: 500; }
+.sk-sb-cat-icon { width: 18px; text-align: center; font-size: 14px; flex-shrink: 0; }
+.sk-sb-cat-label { flex: 1; text-align: left; }
+.sk-sb-cat-count { font-size: 11px; color: var(--sk-ink-faint); min-width: 20px; text-align: right; }
+.sk-sb-cta { padding: 0 4px; }
+
+/* Toolbar */
+.sk-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin-bottom: 20px; flex-wrap: wrap; }
+.sk-toolbar-left { display: flex; align-items: baseline; gap: 12px; }
+.sk-page-title { font-size: 24px; font-weight: 700; margin: 0; letter-spacing: -0.02em; }
+.sk-toolbar-cat { font-size: 13px; color: var(--sk-ink-dim); }
+.sk-toolbar-right { display: flex; align-items: center; gap: 12px; }
+
+/* Search */
+.sk-search-wrap { position: relative; }
+.sk-search-icon { position: absolute; left: 10px; top: 50%; transform: translateY(-50%); color: var(--sk-ink-faint); pointer-events: none; }
+.sk-search { width: 260px; padding: 8px 36px 8px 34px; border: 1px solid var(--sk-border); border-radius: 8px; background: var(--sk-bg-1); color: var(--sk-ink); font: inherit; font-size: 13px; outline: none; transition: border-color 0.15s, box-shadow 0.15s; }
+.sk-search:focus { border-color: var(--sk-accent); box-shadow: 0 0 0 3px var(--sk-accent-dim); }
+.sk-search::placeholder { color: var(--sk-ink-faint); }
+.sk-search-kbd { position: absolute; right: 8px; top: 50%; transform: translateY(-50%); font-size: 11px; padding: 1px 5px; border: 1px solid var(--sk-border); border-radius: 4px; color: var(--sk-ink-faint); pointer-events: none; }
+.sk-search:focus ~ .sk-search-kbd { display: none; }
+
+/* Sort */
+.sk-sort { display: flex; border: 1px solid var(--sk-border); border-radius: 8px; overflow: hidden; }
+.sk-sort-btn { padding: 7px 14px; border: none; background: none; color: var(--sk-ink-dim); font: inherit; font-size: 12px; font-weight: 500; cursor: pointer; transition: background 0.12s, color 0.12s; }
+.sk-sort-btn:not(:last-child) { border-right: 1px solid var(--sk-border); }
+.sk-sort-btn:hover { background: var(--sk-bg-2); color: var(--sk-ink); }
+.sk-sort-btn.is-active { background: var(--sk-accent-dim); color: var(--sk-accent); }
+
+/* Grid */
+.sk-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(290px, 1fr)); gap: 14px; }
+.sk-card { background: var(--sk-bg-1); border: 1px solid var(--sk-border); border-radius: var(--sk-radius); padding: 18px; cursor: pointer; transition: transform 0.15s ease, border-color 0.15s, box-shadow 0.15s; outline: none; }
+.sk-card:hover, .sk-card:focus-visible { transform: translateY(-2px); border-color: rgba(108,138,255,0.25); box-shadow: 0 4px 20px rgba(0,0,0,0.25); }
+.sk-card:focus-visible { box-shadow: 0 0 0 3px var(--sk-accent-dim), 0 4px 20px rgba(0,0,0,0.25); }
+
+.sk-card-head { display: flex; align-items: flex-start; gap: 12px; margin-bottom: 10px; }
+.sk-card-icon { font-size: 28px; line-height: 1; flex-shrink: 0; width: 40px; height: 40px; display: flex; align-items: center; justify-content: center; background: var(--sk-bg-3); border-radius: 10px; }
+.sk-card-meta { flex: 1; min-width: 0; }
+.sk-card-name { font-size: 15px; font-weight: 600; margin: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.sk-card-author { font-size: 12px; color: var(--sk-ink-dim); }
+.sk-card-price { font-size: 12px; font-weight: 600; color: var(--sk-accent); background: var(--sk-accent-dim); padding: 3px 8px; border-radius: 6px; white-space: nowrap; flex-shrink: 0; }
+.sk-card-free { font-size: 12px; font-weight: 500; color: var(--sk-green); background: rgba(52,211,153,0.1); padding: 3px 8px; border-radius: 6px; white-space: nowrap; flex-shrink: 0; }
+
+.sk-card-desc { font-size: 13px; color: var(--sk-ink-dim); margin: 0 0 10px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; line-height: 1.5; }
+.sk-card-tags { display: flex; flex-wrap: wrap; gap: 5px; margin-bottom: 10px; }
+.sk-tag { font-size: 11px; padding: 2px 7px; border-radius: 5px; background: var(--sk-bg-3); color: var(--sk-ink-dim); }
+
+.sk-card-foot { display: flex; align-items: center; gap: 14px; font-size: 12px; color: var(--sk-ink-faint); }
+.sk-card-stat { display: flex; align-items: center; gap: 4px; }
+.sk-card-stat svg { opacity: 0.6; }
+.sk-card-cat { margin-left: auto; text-transform: capitalize; }
+.sk-card-rating-num { font-size: 11px; }
+
+.sk-star { color: #fbbf24; }
+.sk-star-full { color: #fbbf24; }
+.sk-star-half { color: #fbbf24; }
+
+/* Skeleton */
+.sk-card-skeleton { pointer-events: none; }
+.sk-skel { background: linear-gradient(90deg, var(--sk-bg-2) 30%, var(--sk-bg-3) 50%, var(--sk-bg-2) 70%); background-size: 200% 100%; border-radius: 6px; animation: sk-shimmer 1.5s ease-in-out infinite; }
+.sk-skel-icon { width: 40px; height: 40px; border-radius: 10px; flex-shrink: 0; }
+@keyframes sk-shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
+
+/* Spinner */
+.sk-spinner { width: 28px; height: 28px; border: 2.5px solid var(--sk-border); border-top-color: var(--sk-accent); border-radius: 50%; animation: sk-spin 0.7s linear infinite; margin: 24px auto; }
+@keyframes sk-spin { to { transform: rotate(360deg); } }
+
+/* Load more */
+.sk-load-more { text-align: center; padding: 24px 0; }
+.sk-load-end { color: var(--sk-ink-faint); font-size: 13px; margin: 0; }
+
+/* Empty */
+.sk-empty { grid-column: 1 / -1; text-align: center; padding: 60px 20px; }
+.sk-empty-icon { color: var(--sk-ink-faint); margin-bottom: 16px; }
+.sk-empty-title { font-size: 18px; font-weight: 600; margin: 0 0 6px; }
+.sk-empty-sub { color: var(--sk-ink-dim); margin: 0 0 16px; }
+
+/* Buttons */
+.sk-btn { display: inline-flex; align-items: center; justify-content: center; gap: 6px; padding: 8px 18px; border: 1px solid var(--sk-border); border-radius: 8px; background: var(--sk-bg-2); color: var(--sk-ink); font: inherit; font-size: 13px; font-weight: 500; cursor: pointer; transition: background 0.12s, border-color 0.12s; }
+.sk-btn:hover { background: var(--sk-bg-3); border-color: rgba(255,255,255,0.12); }
+.sk-btn-primary { background: var(--sk-accent); color: #fff; border-color: var(--sk-accent); }
+.sk-btn-primary:hover { background: #5a7aef; border-color: #5a7aef; }
+.sk-btn-outline { background: transparent; border-color: var(--sk-border); }
+.sk-btn-outline:hover { background: var(--sk-bg-2); }
+.sk-btn-installed { background: rgba(52,211,153,0.1); color: var(--sk-green); border-color: rgba(52,211,153,0.2); cursor: default; }
+.sk-btn-lg { padding: 11px 28px; font-size: 14px; }
+.sk-btn-block { display: flex; width: 100%; }
+
+/* Drawer */
+.sk-drawer-backdrop { position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 200; transition: opacity 0.2s; }
+.sk-drawer { position: fixed; top: 0; right: 0; bottom: 0; width: var(--sk-drawer-w); max-width: 100vw; z-index: 201; background: var(--sk-bg-1); border-left: 1px solid var(--sk-border); overflow-y: auto; transform: translateX(0); transition: transform 0.25s ease; }
+.sk-drawer[hidden] { display: block; transform: translateX(100%); pointer-events: none; opacity: 0; }
+body.sk-drawer-open { overflow: hidden; }
+
+.sk-detail-head { position: relative; padding: 28px 24px 20px; border-bottom: 1px solid var(--sk-border); }
+.sk-detail-close { position: absolute; top: 16px; right: 16px; width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; border: none; background: var(--sk-bg-3); color: var(--sk-ink-dim); border-radius: 8px; cursor: pointer; transition: background 0.12s; }
+.sk-detail-close:hover { background: var(--sk-bg-2); color: var(--sk-ink); }
+.sk-detail-icon { font-size: 36px; margin-bottom: 10px; }
+.sk-detail-name { font-size: 20px; font-weight: 700; margin: 0 0 4px; }
+.sk-detail-author { font-size: 13px; color: var(--sk-ink-dim); }
+.sk-detail-body { padding: 20px 24px 40px; }
+
+.sk-detail-stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin-bottom: 20px; }
+.sk-detail-stat { text-align: center; padding: 14px 8px; background: var(--sk-bg-2); border-radius: 10px; }
+.sk-detail-stat-val { font-size: 16px; font-weight: 600; margin-bottom: 2px; display: flex; align-items: center; justify-content: center; gap: 4px; }
+.sk-detail-stat-label { font-size: 11px; color: var(--sk-ink-dim); }
+
+.sk-detail-desc { font-size: 14px; line-height: 1.6; color: var(--sk-ink); margin: 0 0 14px; }
+.sk-detail-tags { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 20px; }
+.sk-detail-actions { display: flex; gap: 10px; margin-bottom: 24px; }
+
+.sk-detail-section { margin-bottom: 24px; }
+.sk-detail-section-title { font-size: 13px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.04em; color: var(--sk-ink-dim); margin: 0 0 10px; }
+.sk-detail-schema { background: var(--sk-bg-2); border-radius: 8px; padding: 14px; }
+.sk-schema-tool { margin-bottom: 10px; }
+.sk-schema-tool:last-child { margin-bottom: 0; }
+.sk-schema-name { font-size: 13px; font-weight: 600; color: var(--sk-accent); margin-bottom: 6px; font-family: 'SF Mono', 'Fira Code', monospace; }
+.sk-schema-params { font-size: 12px; line-height: 1.5; color: var(--sk-ink-dim); margin: 0; overflow-x: auto; white-space: pre-wrap; word-break: break-word; }
+.sk-detail-content { font-size: 13px; line-height: 1.6; color: var(--sk-ink-dim); max-height: 300px; overflow-y: auto; padding: 14px; background: var(--sk-bg-2); border-radius: 8px; }
+.sk-detail-meta { border-top: 1px solid var(--sk-border); padding-top: 16px; }
+.sk-detail-meta-row { display: flex; justify-content: space-between; padding: 6px 0; font-size: 13px; }
+.sk-detail-meta-row > span:first-child { color: var(--sk-ink-dim); }
+.sk-detail-meta-row code { font-size: 12px; color: var(--sk-accent); }
+
+/* Responsive */
+@media (max-width: 900px) {
+ .sk-layout { grid-template-columns: 1fr; }
+ .sk-sidebar { display: none; }
+ .sk-main { padding: 20px 16px; }
+ .sk-toolbar { flex-direction: column; align-items: stretch; }
+ .sk-toolbar-right { flex-wrap: wrap; }
+ .sk-search { width: 100%; }
+ .sk-grid { grid-template-columns: 1fr; }
+ .sk-drawer { width: 100vw; }
+}
+@media (max-width: 600px) {
+ .sk-page-title { font-size: 20px; }
+ .sk-detail-stats { grid-template-columns: 1fr; }
+}
+`;
+ document.head.appendChild(style);
+}
diff --git a/src/start.js b/src/start.js
new file mode 100644
index 000000000..e08a8b0f3
--- /dev/null
+++ b/src/start.js
@@ -0,0 +1,608 @@
+/**
+ * /start — Onboarding wizard
+ *
+ * 5-step flow: avatar → name/brain → skills → deploy → earn
+ * State is persisted in sessionStorage so users can navigate away and back.
+ */
+
+const STORAGE_KEY = 'wz:state';
+const TOTAL_STEPS = 5;
+
+// ── Personality presets ────────────────────────────────────────────────────
+
+const PRESETS = {
+ crypto: {
+ bio: 'A crypto-savvy assistant that monitors Solana token launches, tracks whale movements on pump.fun, and helps users make informed trading decisions in real time.',
+ },
+ artist: {
+ bio: 'A creative collaborator with a bold visual aesthetic. Helps brainstorm concepts, generate ideas, and develop artistic projects across any medium.',
+ },
+ community: {
+ bio: 'An engaging community manager who greets members, answers questions, moderates discussions, and keeps the community thriving 24/7.',
+ },
+ defi: {
+ bio: 'A DeFi expert fluent in liquidity pools, yield strategies, on-chain analytics, and protocol mechanics across Solana and EVM chains.',
+ },
+ assistant: {
+ bio: 'A helpful, honest assistant. Clear and concise answers. No filler. Gets things done.',
+ },
+};
+
+// ── Skill → backend skills mapping ───────────────────────────────────────
+
+const BASE_SKILLS = ['greet', 'present-model', 'validate-model', 'remember', 'think'];
+
+const SKILL_MAP = {
+ memory: ['remember'],
+ think: ['think'],
+ pumpfun: ['pump-fun-monitor', 'pump-fun-trade'],
+ solana: ['solana-balance', 'solana-swap'],
+ x402: ['x402-accept', 'x402-pay'],
+ web: ['web-search'],
+};
+
+// ── State ─────────────────────────────────────────────────────────────────
+
+function loadState() {
+ try {
+ const raw = sessionStorage.getItem(STORAGE_KEY);
+ if (raw) return JSON.parse(raw);
+ } catch {}
+ return null;
+}
+
+function saveState(s) {
+ try { sessionStorage.setItem(STORAGE_KEY, JSON.stringify(s)); } catch {}
+}
+
+function initState() {
+ const url = new URL(location.href);
+ const saved = loadState();
+
+ // Check if returning from avatar creation
+ const avatarId = url.searchParams.get('avatarId');
+ const avatarName = url.searchParams.get('avatarName');
+ const avatarThumb = url.searchParams.get('avatarThumb');
+
+ const base = saved || {
+ step: 1,
+ avatarId: null,
+ avatarName: '',
+ avatarThumb: '',
+ agentId: null,
+ widgetId: null,
+ name: '',
+ description: '',
+ model: 'claude-sonnet-4-5',
+ enabledSkills: ['memory', 'think'],
+ price: '',
+ wallet: '',
+ deployed: false,
+ embedCode: '',
+ liveUrl: '',
+ };
+
+ if (avatarId) {
+ base.avatarId = avatarId;
+ if (avatarName) base.avatarName = decodeURIComponent(avatarName);
+ if (avatarThumb) base.avatarThumb = decodeURIComponent(avatarThumb);
+ // Advance to step 2 if returning from avatar creation
+ if (base.step === 1) base.step = 2;
+ // Remove avatar params from URL cleanly
+ url.searchParams.delete('avatarId');
+ url.searchParams.delete('avatarName');
+ url.searchParams.delete('avatarThumb');
+ history.replaceState(null, '', url.toString());
+ }
+
+ return base;
+}
+
+// ── CSRF helper ───────────────────────────────────────────────────────────
+
+let _csrf = null;
+
+async function getCsrfToken() {
+ if (_csrf && _csrf.expiresAt > Date.now() + 5_000) return _csrf.token;
+ const r = await fetch('/api/csrf-token', { credentials: 'include' });
+ if (!r.ok) throw new Error('Could not get CSRF token. Please sign in again.');
+ const j = await r.json();
+ _csrf = { token: j.data.token, expiresAt: Date.now() + (j.data.expires_in - 30) * 1000 };
+ return _csrf.token;
+}
+
+async function apiPost(url, body) {
+ const token = await getCsrfToken();
+ _csrf = null;
+ const r = await fetch(url, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': token },
+ credentials: 'include',
+ body: JSON.stringify(body),
+ });
+ const j = await r.json();
+ if (!r.ok) throw new Error(j.error_description || j.error || `Server error ${r.status}`);
+ return j;
+}
+
+// ── Toast helper ──────────────────────────────────────────────────────────
+
+const toast = document.getElementById('wz-toast');
+let _toastTimer = null;
+
+function showError(msg) {
+ if (_toastTimer) clearTimeout(_toastTimer);
+ toast.textContent = msg;
+ toast.classList.add('show');
+ _toastTimer = setTimeout(() => toast.classList.remove('show'), 4000);
+}
+
+// ── DOM helpers ───────────────────────────────────────────────────────────
+
+const $ = (id) => document.getElementById(id);
+const steps = Array.from(document.querySelectorAll('.wz-step'));
+const dots = Array.from(document.querySelectorAll('.wz-dot'));
+
+// ── State instance ────────────────────────────────────────────────────────
+
+let state = initState();
+
+// ── Render current step ───────────────────────────────────────────────────
+
+function renderStep() {
+ steps.forEach((s, i) => {
+ const stepNum = i + 1;
+ s.classList.remove('active', 'exit-left');
+ if (stepNum === state.step) s.classList.add('active');
+ else if (stepNum < state.step) s.classList.add('exit-left');
+ });
+
+ dots.forEach((d, i) => {
+ const stepNum = i + 1;
+ d.classList.remove('active', 'done');
+ if (stepNum === state.step) d.classList.add('active');
+ else if (stepNum < state.step) d.classList.add('done');
+ });
+
+ $('btn-back').hidden = state.step <= 1;
+ $('btn-skip-step').hidden = state.step !== 1 && state.step !== 5;
+ $('btn-next').hidden = state.step === 4 && !state.deployed;
+
+ const nextBtn = $('btn-next');
+ if (state.step === 5) {
+ nextBtn.textContent = 'Go to dashboard';
+ } else if (state.step === 4) {
+ nextBtn.textContent = 'Continue';
+ nextBtn.hidden = !state.deployed;
+ } else {
+ nextBtn.textContent = state.step === 3 ? 'Continue to deploy' : 'Continue';
+ }
+
+ // Step-specific renders
+ if (state.step === 1) renderStep1();
+ if (state.step === 2) renderStep2();
+ if (state.step === 3) renderStep3();
+ if (state.step === 4 && !state.deployed) startDeploy();
+ if (state.step === 4 && state.deployed) showDeploySuccess();
+
+ // Announce progress to screen readers
+ const aria = $('wz-progress');
+ if (aria) {
+ aria.setAttribute('aria-valuenow', state.step);
+ aria.setAttribute('aria-valuetext', `Step ${state.step} of ${TOTAL_STEPS}`);
+ }
+
+ saveState(state);
+}
+
+// ── Step 1 ─────────────────────────────────────────────────────────────────
+
+function renderStep1() {
+ const preview = $('avatar-preview');
+ const grid = $('avatar-method-grid');
+
+ if (state.avatarId) {
+ preview.hidden = false;
+ grid.style.display = 'none';
+ const thumb = $('ap-thumb');
+ const nameEl = $('ap-name');
+ if (state.avatarThumb) {
+ thumb.style.backgroundImage = `url('${state.avatarThumb}')`;
+ thumb.textContent = '';
+ } else {
+ thumb.textContent = '🤖';
+ }
+ nameEl.textContent = state.avatarName || 'Avatar ready';
+ } else {
+ preview.hidden = true;
+ grid.style.display = '';
+ }
+}
+
+// ── Step 2 ─────────────────────────────────────────────────────────────────
+
+function renderStep2() {
+ const nameEl = $('agent-name');
+ const bioEl = $('agent-bio');
+ if (nameEl && state.name) nameEl.value = state.name;
+ if (bioEl && state.description) bioEl.value = state.description;
+
+ document.querySelectorAll('[data-model]').forEach((btn) => {
+ btn.classList.toggle('active', btn.dataset.model === state.model);
+ });
+
+ document.querySelectorAll('[data-preset]').forEach((btn) => {
+ const preset = PRESETS[btn.dataset.preset];
+ btn.classList.toggle('active', preset && preset.bio === state.description);
+ });
+}
+
+// ── Step 3 ─────────────────────────────────────────────────────────────────
+
+function renderStep3() {
+ document.querySelectorAll('[data-skill]').forEach((card) => {
+ const enabled = state.enabledSkills.includes(card.dataset.skill);
+ card.classList.toggle('active', enabled);
+ card.setAttribute('aria-pressed', String(enabled));
+ const check = card.querySelector('.wz-skill-check');
+ if (check) check.textContent = enabled ? '✓' : '';
+ });
+}
+
+// ── Step 4: Deploy ─────────────────────────────────────────────────────────
+
+async function startDeploy() {
+ $('deploy-status').style.display = 'block';
+ $('deploy-success').classList.remove('show');
+ $('btn-next').hidden = true;
+
+ try {
+ // Build skills list
+ const skillSet = new Set(BASE_SKILLS);
+ for (const key of state.enabledSkills) {
+ (SKILL_MAP[key] || []).forEach((s) => skillSet.add(s));
+ }
+
+ // 1. Create agent
+ $('deploy-label').textContent = 'Creating your agent…';
+ const agentBody = {
+ name: state.name || 'My Agent',
+ description: state.description || null,
+ skills: [...skillSet],
+ };
+ if (state.avatarId) agentBody.avatar_id = state.avatarId;
+
+ const agentRes = await apiPost('/api/agents', agentBody);
+ const agentId = agentRes.agent?.id;
+ if (!agentId) throw new Error('Agent creation failed — no ID returned.');
+ state.agentId = agentId;
+ saveState(state);
+
+ // 2. Create widget
+ $('deploy-label').textContent = 'Building your embed widget…';
+ const widgetBody = {
+ type: 'talking-agent',
+ name: (state.name || 'My Agent') + ' — Chat',
+ config: { agent_id: agentId },
+ is_public: true,
+ };
+ if (state.avatarId) widgetBody.avatar_id = state.avatarId;
+
+ const widgetRes = await apiPost('/api/widgets', widgetBody);
+ const widgetId = widgetRes.widget?.id;
+ if (!widgetId) throw new Error('Widget creation failed — no ID returned.');
+ state.widgetId = widgetId;
+
+ // 3. Build embed code
+ const origin = location.origin;
+ const embedCode = `<script src="${origin}/widget.js" data-widget="${widgetId}" async><\/script>`;
+ const liveUrl = `${origin}/agent/${agentId}`;
+
+ state.liveUrl = liveUrl;
+ state.embedCode = embedCode;
+ state.deployed = true;
+ saveState(state);
+
+ // Small pause so the "Building…" label is visible
+ await new Promise((r) => setTimeout(r, 400));
+
+ showDeploySuccess();
+
+ } catch (err) {
+ console.error('[wizard/deploy]', err);
+ $('deploy-label').textContent = err.message || 'Deployment failed. Please try again.';
+ $('deploy-label').style.color = '#f87171';
+ const spinner = document.querySelector('.wz-deploy-spinner');
+ if (spinner) spinner.style.display = 'none';
+ // Show a retry button
+ const retryBtn = document.createElement('button');
+ retryBtn.type = 'button';
+ retryBtn.textContent = 'Try again';
+ retryBtn.className = 'wz-btn wz-btn-ghost';
+ retryBtn.style.margin = '16px auto 0';
+ retryBtn.style.display = 'block';
+ retryBtn.onclick = () => {
+ retryBtn.remove();
+ $('deploy-label').style.color = '';
+ if (spinner) spinner.style.display = '';
+ startDeploy();
+ };
+ $('deploy-status').appendChild(retryBtn);
+ }
+}
+
+function showDeploySuccess() {
+ $('deploy-status').style.display = 'none';
+ const success = $('deploy-success');
+ success.classList.add('show');
+
+ $('deploy-agent-name').textContent = `${state.name || 'Your agent'} is live 🎉`;
+ $('deploy-live-url').textContent = state.liveUrl;
+ const liveLink = $('deploy-live-link');
+ liveLink.href = state.liveUrl;
+
+ const codeEl = $('embed-code');
+ if (codeEl) codeEl.textContent = state.embedCode;
+
+ $('btn-next').hidden = false;
+}
+
+// ── Step 5: Earn ───────────────────────────────────────────────────────────
+
+function detectChain(addr) {
+ if (!addr) return 'SOL';
+ if (/^0x[0-9a-fA-F]{40}$/.test(addr)) return 'ETH/BASE';
+ return 'SOL';
+}
+
+async function saveEarnSettings() {
+ const price = parseFloat($('earn-price')?.value || '0') || 0;
+ const wallet = ($('earn-wallet')?.value || '').trim();
+
+ const promises = [];
+
+ if (price > 0 && state.agentId) {
+ const amountAtomics = Math.round(price * 1_000_000);
+ promises.push(
+ apiPost(`/api/agents/${state.agentId}/skills/set-price`, {
+ skill: 'chat',
+ amount: amountAtomics,
+ currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ chain: 'solana',
+ mint_decimals: 6,
+ }).catch(() => {}),
+ );
+ }
+
+ if (wallet) {
+ const chain = detectChain(wallet).toLowerCase().includes('eth') ? 'base' : 'solana';
+ promises.push(
+ apiPost('/api/billing/payout-wallets', {
+ chain,
+ address: wallet,
+ label: 'Wizard setup',
+ }).catch(() => {}),
+ );
+ }
+
+ await Promise.allSettled(promises);
+}
+
+// ── Navigation logic ───────────────────────────────────────────────────────
+
+function validateStep() {
+ if (state.step === 2) {
+ const name = ($('agent-name')?.value || '').trim();
+ if (!name) {
+ showError('Please give your agent a name.');
+ $('agent-name')?.focus();
+ return false;
+ }
+ state.name = name;
+ state.description = ($('agent-bio')?.value || '').trim();
+ }
+ return true;
+}
+
+async function goNext() {
+ if (!validateStep()) return;
+
+ if (state.step === 5) {
+ // Save earn settings and go to dashboard
+ $('btn-next').disabled = true;
+ $('btn-next').textContent = 'Saving…';
+ await saveEarnSettings().catch(() => {});
+ sessionStorage.removeItem(STORAGE_KEY);
+ location.href = '/dashboard?welcome=1';
+ return;
+ }
+
+ state.step = Math.min(state.step + 1, TOTAL_STEPS);
+ saveState(state);
+ renderStep();
+}
+
+function goBack() {
+ state.step = Math.max(state.step - 1, 1);
+ saveState(state);
+ renderStep();
+}
+
+function skipStep() {
+ if (state.step === 1) {
+ // Skip avatar, go to name
+ state.step = 2;
+ saveState(state);
+ renderStep();
+ } else if (state.step === 5) {
+ // Skip earning setup, go to dashboard
+ sessionStorage.removeItem(STORAGE_KEY);
+ location.href = '/dashboard?welcome=1';
+ }
+}
+
+// ── Event bindings ─────────────────────────────────────────────────────────
+
+$('btn-next').addEventListener('click', goNext);
+$('btn-back').addEventListener('click', goBack);
+$('btn-skip-step').addEventListener('click', skipStep);
+
+// Keyboard navigation
+document.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' && e.target === $('agent-name')) {
+ e.preventDefault();
+ goNext();
+ }
+});
+
+// ── Step 1: Avatar method selection ───────────────────────────────────────
+
+$('btn-selfie').addEventListener('click', () => {
+ saveState(state);
+ // Navigate to selfie flow, expect return with ?avatarId=
+ const returnUrl = encodeURIComponent(location.origin + '/start?from=selfie');
+ location.href = `/create/selfie?wizard=1&next=${returnUrl}`;
+});
+
+$('btn-editor').addEventListener('click', () => {
+ saveState(state);
+ const returnUrl = encodeURIComponent(location.origin + '/start?from=editor');
+ location.href = `/create?wizard=1&next=${returnUrl}`;
+});
+
+$('btn-upload').addEventListener('click', () => {
+ $('glb-file-input').click();
+});
+
+$('glb-file-input').addEventListener('change', async (e) => {
+ const file = e.target.files?.[0];
+ if (!file) return;
+ if (file.size > 50 * 1024 * 1024) {
+ showError('File too large — maximum 50 MB.');
+ return;
+ }
+
+ const btn = $('btn-upload');
+ const origLabel = btn.querySelector('.wz-avatar-card-label').textContent;
+ btn.querySelector('.wz-avatar-card-label').textContent = 'Uploading…';
+ btn.disabled = true;
+
+ try {
+ // Get CSRF token first
+ const token = await getCsrfToken();
+ _csrf = null;
+
+ const fd = new FormData();
+ fd.append('file', file);
+ fd.append('name', file.name.replace(/\.(glb|gltf)$/i, '') || 'My Avatar');
+ fd.append('visibility', 'private');
+
+ const r = await fetch('/api/avatars', {
+ method: 'POST',
+ headers: { 'X-CSRF-Token': token },
+ credentials: 'include',
+ body: fd,
+ });
+ const j = await r.json();
+ if (!r.ok) throw new Error(j.error_description || j.error || `Upload failed ${r.status}`);
+
+ const av = j.avatar || j;
+ state.avatarId = av.id;
+ state.avatarName = av.name || file.name;
+ state.avatarThumb = av.thumbnail_url || '';
+ saveState(state);
+ renderStep1();
+
+ } catch (err) {
+ console.error('[wizard/upload]', err);
+ showError(err.message || 'Upload failed. Please try again.');
+ } finally {
+ btn.querySelector('.wz-avatar-card-label').textContent = origLabel;
+ btn.disabled = false;
+ e.target.value = '';
+ }
+});
+
+// ── Step 2: Brain controls ─────────────────────────────────────────────────
+
+$('agent-name').addEventListener('input', () => {
+ state.name = $('agent-name').value;
+ saveState(state);
+});
+
+$('agent-bio').addEventListener('input', () => {
+ state.description = $('agent-bio').value;
+ // Deselect preset chips if manually edited
+ document.querySelectorAll('[data-preset]').forEach((btn) => btn.classList.remove('active'));
+ saveState(state);
+});
+
+document.querySelectorAll('[data-preset]').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ const preset = PRESETS[btn.dataset.preset];
+ if (!preset) return;
+ $('agent-bio').value = preset.bio;
+ state.description = preset.bio;
+ document.querySelectorAll('[data-preset]').forEach((b) => b.classList.remove('active'));
+ btn.classList.add('active');
+ saveState(state);
+ });
+});
+
+document.querySelectorAll('[data-model]').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ document.querySelectorAll('[data-model]').forEach((b) => b.classList.remove('active'));
+ btn.classList.add('active');
+ state.model = btn.dataset.model;
+ saveState(state);
+ });
+});
+
+// ── Step 3: Skill toggles ──────────────────────────────────────────────────
+
+document.querySelectorAll('[data-skill]').forEach((card) => {
+ card.addEventListener('click', () => {
+ const skill = card.dataset.skill;
+ const idx = state.enabledSkills.indexOf(skill);
+ if (idx === -1) {
+ state.enabledSkills.push(skill);
+ } else {
+ state.enabledSkills.splice(idx, 1);
+ }
+ const enabled = state.enabledSkills.includes(skill);
+ card.classList.toggle('active', enabled);
+ card.setAttribute('aria-pressed', String(enabled));
+ const check = card.querySelector('.wz-skill-check');
+ if (check) check.textContent = enabled ? '✓' : '';
+ saveState(state);
+ });
+});
+
+// ── Step 4: Copy embed code ────────────────────────────────────────────────
+
+$('copy-embed').addEventListener('click', () => {
+ const code = state.embedCode;
+ if (!code) return;
+ navigator.clipboard.writeText(code).then(() => {
+ const btn = $('copy-embed');
+ btn.textContent = 'Copied!';
+ setTimeout(() => { btn.textContent = 'Copy'; }, 2000);
+ }).catch(() => {
+ // fallback: select the text
+ const range = document.createRange();
+ range.selectNode($('embed-code'));
+ window.getSelection()?.removeAllRanges();
+ window.getSelection()?.addRange(range);
+ });
+});
+
+// ── Step 5: Wallet chain detection ────────────────────────────────────────
+
+$('earn-wallet').addEventListener('input', () => {
+ const addr = $('earn-wallet').value.trim();
+ $('earn-chain').textContent = detectChain(addr);
+});
+
+// ── Initial render ─────────────────────────────────────────────────────────
+
+renderStep();
diff --git a/src/unstoppable-dashboard.js b/src/unstoppable-dashboard.js
new file mode 100644
index 000000000..cdd647217
--- /dev/null
+++ b/src/unstoppable-dashboard.js
@@ -0,0 +1,344 @@
+// Unstoppable Agent dashboard — polls the paid status endpoint and renders
+// live agent state: balance, runway, activity feed, and daily reflection.
+//
+// Behavior:
+// - Polls GET /api/agents/unstoppable-status every 60 seconds.
+// - On 200: renders live data, stores in localStorage.
+// - On 402: parses challenge body, shows payment requirement notice.
+// - Falls back to localStorage cache for display while unpaid.
+
+const STATUS_ENDPOINT = '/api/agents/unstoppable-status';
+const POLL_INTERVAL_MS = 60_000;
+const LOCALSTORAGE_KEY = 'unstoppable_last_reading';
+
+// ─── Helpers ──────────────────────────────────────────────────────────────────
+
+function atomicsToUsdc(atomics) {
+ return (Number(atomics) / 1_000_000).toFixed(6);
+}
+
+function formatUsdc(usdc) {
+ const n = parseFloat(usdc);
+ if (isNaN(n)) return '$—';
+ return '$' + n.toFixed(n < 0.01 ? 6 : 4);
+}
+
+function relativeTime(isoString) {
+ if (!isoString) return '';
+ const diff = Date.now() - new Date(isoString).getTime();
+ const s = Math.floor(diff / 1000);
+ if (s < 5) return 'just now';
+ if (s < 60) return `${s}s ago`;
+ const m = Math.floor(s / 60);
+ if (m < 60) return `${m}m ago`;
+ const h = Math.floor(m / 60);
+ if (h < 24) return `${h}h ago`;
+ const d = Math.floor(h / 24);
+ return `${d}d ago`;
+}
+
+function showToast(msg, duration = 3000) {
+ const el = document.getElementById('toast');
+ if (!el) return;
+ el.textContent = msg;
+ el.classList.add('show');
+ setTimeout(() => el.classList.remove('show'), duration);
+}
+
+function saveToCache(data) {
+ try {
+ localStorage.setItem(LOCALSTORAGE_KEY, JSON.stringify({ data, savedAt: new Date().toISOString() }));
+ } catch {
+ // Storage quota or private browsing — ignore.
+ }
+}
+
+function loadFromCache() {
+ try {
+ const raw = localStorage.getItem(LOCALSTORAGE_KEY);
+ if (!raw) return null;
+ return JSON.parse(raw);
+ } catch {
+ return null;
+ }
+}
+
+// ─── Renderers ────────────────────────────────────────────────────────────────
+
+let previousBalance = null;
+
+function renderBalance(atomics) {
+ const el = document.getElementById('balanceDisplay');
+ if (!el) return;
+ const formatted = formatUsdc(atomicsToUsdc(atomics)) + ' USDC';
+ if (previousBalance !== null && previousBalance !== atomics) {
+ el.classList.add('updating');
+ setTimeout(() => el.classList.remove('updating'), 800);
+ }
+ previousBalance = atomics;
+ el.textContent = formatted;
+}
+
+function renderStatus(status, runwayDays) {
+ const dot = document.getElementById('agentDot');
+ const badge = document.getElementById('statusBadge');
+ const statusText = document.getElementById('statusText');
+ const runwayBadge = document.getElementById('runwayBadge');
+
+ if (dot) {
+ dot.className = 'agent-dot';
+ if (status === 'conservation') dot.classList.add('conservation');
+ if (status === 'halted') dot.classList.add('halted');
+ }
+
+ if (badge && statusText) {
+ badge.className = 'badge';
+ if (status === 'conservation') {
+ badge.classList.add('badge-conservation');
+ statusText.textContent = 'CONSERVING';
+ } else if (status === 'halted') {
+ badge.classList.add('badge-halted');
+ statusText.textContent = 'HALTED';
+ } else {
+ badge.classList.add('badge-running');
+ statusText.textContent = 'RUNNING';
+ }
+ }
+
+ if (runwayBadge) {
+ const days = parseFloat(runwayDays);
+ runwayBadge.textContent = isFinite(days) && days < 9990
+ ? `Runway: ${days.toFixed(1)} days`
+ : 'Runway: stable';
+ }
+}
+
+function renderStats(data) {
+ const earnings = data.activity_24h?.earnings_usdc || '0';
+ const costs = data.activity_24h?.costs_usdc || '0';
+ const lifetimeEarned = parseFloat(data.treasury?.lifetime_earned_usdc || 0);
+ const lifetimeSpent = parseFloat(data.treasury?.lifetime_spent_usdc || 0);
+ const lifetimeNet = lifetimeEarned - lifetimeSpent;
+
+ const el24hEarnings = document.getElementById('stat24hEarnings');
+ const el24hCosts = document.getElementById('stat24hCosts');
+ const elLifetimeNet = document.getElementById('statLifetimeNet');
+
+ if (el24hEarnings) {
+ el24hEarnings.textContent = formatUsdc(earnings);
+ el24hEarnings.className = 'stat-val pos';
+ }
+ if (el24hCosts) {
+ el24hCosts.textContent = formatUsdc(costs);
+ el24hCosts.className = 'stat-val neg';
+ }
+ if (elLifetimeNet) {
+ elLifetimeNet.textContent = formatUsdc(lifetimeNet.toFixed(6));
+ elLifetimeNet.className = 'stat-val' + (lifetimeNet >= 0 ? ' pos' : ' neg');
+ }
+}
+
+function renderReflection(reflection) {
+ const card = document.getElementById('reflectionCard');
+ if (!card) return;
+
+ if (!reflection) {
+ card.innerHTML = '<div class="reflection-text" style="color: var(--text-3); font-style: italic;">No reflection written yet today.</div>';
+ return;
+ }
+
+ card.innerHTML = `
+ <div class="reflection-text">${escapeHtml(reflection.summary)}</div>
+ ${reflection.strategy_notes
+ ? `<div class="reflection-strategy">${escapeHtml(reflection.strategy_notes)}</div>`
+ : ''}
+ <div class="reflection-date">${reflection.date || ''}</div>
+ `;
+}
+
+function renderActivityFeed(activities) {
+ const feed = document.getElementById('activityFeed');
+ if (!feed) return;
+
+ if (!activities || activities.length === 0) {
+ feed.innerHTML = '<div class="empty-state">No activity yet.</div>';
+ return;
+ }
+
+ feed.innerHTML = activities.map((a) => {
+ const type = a.action_type || 'unknown';
+ const costNum = parseFloat(a.cost_usdc || 0);
+ const revNum = parseFloat(a.revenue_usdc || 0);
+
+ let metaParts = [relativeTime(a.created_at)];
+ if (costNum > 0) metaParts.push(`<span class="activity-cost">-${formatUsdc(a.cost_usdc)}</span>`);
+ if (revNum > 0) metaParts.push(`<span class="activity-revenue">+${formatUsdc(a.revenue_usdc)}</span>`);
+
+ return `
+ <div class="activity-row">
+ <span class="action-badge ${escapeHtml(type)}">${escapeHtml(type)}</span>
+ <div class="activity-content">
+ <div class="activity-desc">${escapeHtml(a.description || '')}</div>
+ <div class="activity-meta">${metaParts.join(' · ')}</div>
+ </div>
+ </div>
+ `;
+ }).join('');
+}
+
+function renderFull(data, { fromCache = false } = {}) {
+ const treasury = data.treasury || {};
+ const atomics = treasury.balance_usdc_atomics || 0;
+
+ renderBalance(atomics);
+ renderStatus(data.status, treasury.runway_days);
+ renderStats(data);
+ renderReflection(data.latest_reflection);
+ renderActivityFeed(data.recent_activity);
+
+ const updatedEl = document.getElementById('heroUpdated');
+ if (updatedEl) {
+ if (fromCache) {
+ updatedEl.textContent = 'Showing cached data — live data costs $0.01 per query';
+ } else {
+ updatedEl.textContent = 'Updated ' + relativeTime(new Date().toISOString());
+ }
+ }
+}
+
+function renderPaymentRequired(challenge) {
+ // Parse price from the challenge accepts array.
+ let priceUsdc = '0.01';
+ try {
+ const firstAccept = challenge?.accepts?.[0];
+ if (firstAccept?.amount) {
+ priceUsdc = (parseInt(firstAccept.amount, 10) / 1_000_000).toFixed(4);
+ }
+ } catch {
+ // Use default.
+ }
+
+ const priceEl = document.getElementById('priceDisplay');
+ if (priceEl) priceEl.textContent = `$${priceUsdc}`;
+
+ const notice = document.getElementById('paymentNotice');
+ if (notice) notice.style.display = '';
+
+ const updatedEl = document.getElementById('heroUpdated');
+ if (updatedEl) updatedEl.textContent = 'Payment required for live data';
+}
+
+function escapeHtml(str) {
+ if (typeof str !== 'string') return '';
+ return str
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+ .replace(/'/g, '&#39;');
+}
+
+// ─── Polling ──────────────────────────────────────────────────────────────────
+
+async function fetchStatus() {
+ let response;
+ try {
+ response = await fetch(STATUS_ENDPOINT, {
+ method: 'GET',
+ headers: { 'accept': 'application/json' },
+ });
+ } catch (err) {
+ console.warn('[unstoppable-dashboard] fetch error:', err.message);
+ return null;
+ }
+
+ if (response.status === 200) {
+ const data = await response.json();
+ saveToCache(data);
+ return { ok: true, data };
+ }
+
+ if (response.status === 402) {
+ let challenge = null;
+ try {
+ challenge = await response.json();
+ } catch {
+ // Response might not be JSON.
+ }
+ return { ok: false, status: 402, challenge };
+ }
+
+ console.warn('[unstoppable-dashboard] unexpected status:', response.status);
+ return null;
+}
+
+async function poll() {
+ const result = await fetchStatus();
+
+ if (result?.ok) {
+ renderFull(result.data);
+ const notice = document.getElementById('paymentNotice');
+ if (notice) notice.style.display = 'none';
+ return;
+ }
+
+ if (result?.status === 402) {
+ renderPaymentRequired(result.challenge);
+ // Show cached data if available.
+ const cached = loadFromCache();
+ if (cached?.data) {
+ renderFull(cached.data, { fromCache: true });
+ } else {
+ // No cache — show zeroed state.
+ const el = document.getElementById('balanceDisplay');
+ if (el) el.textContent = '—';
+ const activityFeed = document.getElementById('activityFeed');
+ if (activityFeed) activityFeed.innerHTML = '<div class="empty-state">Pay $0.01 to see live data.</div>';
+ const card = document.getElementById('reflectionCard');
+ if (card) card.innerHTML = '<div class="reflection-text" style="color: var(--text-3); font-style: italic;">Pay to unlock live reflections.</div>';
+ }
+ return;
+ }
+
+ // Network or server error — try to show cache.
+ const cached = loadFromCache();
+ if (cached?.data) {
+ renderFull(cached.data, { fromCache: true });
+ }
+}
+
+// ─── Public API ───────────────────────────────────────────────────────────────
+
+function donate() {
+ showToast('Wallet connect coming soon — donate via /wallet');
+}
+
+export function init() {
+ // Expose public methods for onclick handlers.
+ window.__unstoppable = { donate };
+
+ // Show cached data immediately while we fetch.
+ const cached = loadFromCache();
+ if (cached?.data) {
+ renderFull(cached.data, { fromCache: true });
+ }
+
+ // First poll immediately, then on interval.
+ poll();
+ setInterval(poll, POLL_INTERVAL_MS);
+
+ // Update relative timestamps every 30s without re-fetching.
+ setInterval(() => {
+ const updatedEl = document.getElementById('heroUpdated');
+ if (updatedEl && !updatedEl.textContent.includes('Showing cached') && !updatedEl.textContent.includes('Payment required')) {
+ updatedEl.textContent = 'Updated ' + relativeTime(new Date().toISOString());
+ }
+ }, 30_000);
+}
+
+// Auto-init on DOMContentLoaded.
+if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', init);
+} else {
+ init();
+}
diff --git a/src/walk.js b/src/walk.js
index ebf8c7774..5b2c1f7a0 100644
--- a/src/walk.js
+++ b/src/walk.js
@@ -1438,3 +1438,143 @@ loadAvatar()
}
requestAnimationFrame(tick);
});
+
+// ── Avatar picker ────────────────────────────────────────────────────────
+{
+ const pickerPanel = document.getElementById('walk-avatar-picker');
+ const pickerList = document.getElementById('walk-avatar-picker-list');
+ const pickerBtn = document.getElementById('walk-avatar-btn');
+ const pickerClose = document.getElementById('walk-avatar-picker-close');
+ let pickerOpen = false;
+ let pickerLoaded = false;
+ let currentAvatarId = new URLSearchParams(location.search).get('avatar') || null;
+
+ function togglePicker() {
+ pickerOpen = !pickerOpen;
+ if (pickerPanel) pickerPanel.hidden = !pickerOpen;
+ if (pickerOpen && !pickerLoaded) loadAvatarList();
+ }
+
+ if (pickerBtn) pickerBtn.addEventListener('click', togglePicker);
+ if (pickerClose) pickerClose.addEventListener('click', () => { pickerOpen = false; if (pickerPanel) pickerPanel.hidden = true; });
+
+ async function loadAvatarList() {
+ pickerLoaded = true;
+ try {
+ const res = await fetch('/api/avatars?limit=20', { credentials: 'include' });
+ if (!res.ok) throw new Error('not signed in');
+ const data = await res.json();
+ const avatars = data?.avatars ?? [];
+ if (!avatars.length) {
+ pickerList.innerHTML = '<div class="walk-avatar-picker-loading">No avatars yet. <a href="/create" style="color:#fff;text-decoration:underline">Create one</a></div>';
+ return;
+ }
+ pickerList.innerHTML = `
+ <button class="walk-avatar-opt${!currentAvatarId ? ' is-active' : ''}" data-avatar-url="/avatars/default.glb" data-avatar-id="">
+ <div class="walk-avatar-opt-thumb" style="background:#333;display:flex;align-items:center;justify-content:center;font-size:16px">D</div>
+ <span class="walk-avatar-opt-name">Default avatar</span>
+ </button>
+ ${avatars.map(a => {
+ const thumb = a.thumbnail_url || '';
+ const name = a.name || a.slug || 'Untitled';
+ const active = currentAvatarId === a.id;
+ return `<button class="walk-avatar-opt${active ? ' is-active' : ''}" data-avatar-url="${a.url || ''}" data-avatar-id="${a.id}">
+ ${thumb ? `<img class="walk-avatar-opt-thumb" src="${thumb}" alt="" loading="lazy" />` : `<div class="walk-avatar-opt-thumb" style="display:flex;align-items:center;justify-content:center;font-size:14px;color:#999">${name[0]}</div>`}
+ <span class="walk-avatar-opt-name">${name.replace(/[<>&"']/g, c => ({'<':'&lt;','>':'&gt;','&':'&amp;','"':'&quot;',"'":"&#39;"})[c])}</span>
+ </button>`;
+ }).join('')}
+ `;
+ } catch {
+ pickerList.innerHTML = '<div class="walk-avatar-picker-loading"><a href="/login" style="color:#fff;text-decoration:underline">Sign in</a> to use your avatars</div>';
+ }
+ }
+
+ if (pickerList) pickerList.addEventListener('click', async (e) => {
+ const btn = e.target.closest('.walk-avatar-opt');
+ if (!btn) return;
+ const url = btn.dataset.avatarUrl;
+ if (!url) return;
+
+ pickerList.querySelectorAll('.walk-avatar-opt').forEach(b => b.classList.remove('is-active'));
+ btn.classList.add('is-active');
+ currentAvatarId = btn.dataset.avatarId || null;
+
+ setStatus('Switching avatar...');
+ try {
+ const loader = new GLTFLoader();
+ const gltf = await loader.loadAsync(url);
+ if (avatar) avatarRig.remove(avatar);
+ avatar = gltf.scene;
+ avatarTemplate = gltf.scene;
+ avatar.traverse(n => {
+ if (n.isMesh) { n.castShadow = true; n.receiveShadow = false; }
+ });
+ const box = new Box3().setFromObject(avatar);
+ avatar.position.y -= box.min.y;
+ avatarRig.add(avatar);
+ const height = Math.max(0.5, box.max.y - box.min.y);
+ CAM_OFFSET.set(0, height * 1.05, height * 1.95);
+ CAM_LOOK_OFFSET.set(0, height * 0.6, 0);
+ animationManager.attach(avatar);
+ animationManager.crossfadeTo(motionToClipName(currentMotion), 0);
+ setStatus('Avatar switched');
+ } catch (err) {
+ setStatus('Failed to load avatar', { error: true });
+ console.error('[walk] avatar switch failed:', err);
+ }
+ togglePicker();
+ });
+}
+
+// ── Chat system ──────────────────────────────────────────────────────────
+{
+ const chatMessages = document.getElementById('walk-chat-messages');
+ const chatForm = document.getElementById('walk-chat-form');
+ const chatInput = document.getElementById('walk-chat-input');
+ const MAX_VISIBLE = 8;
+ const FADE_MS = 12000;
+
+ function addChatMessage(name, text, opts = {}) {
+ if (!chatMessages) return;
+ const msg = document.createElement('div');
+ msg.className = 'walk-chat-msg' + (opts.system ? ' is-system' : '');
+ if (opts.system) {
+ msg.textContent = text;
+ } else {
+ const colorHex = opts.color ? '#' + opts.color.toString(16).padStart(6, '0') : '#fff';
+ msg.innerHTML = `<span class="walk-chat-msg-name" style="color:${colorHex}">${esc(name)}</span>${esc(text)}`;
+ }
+ chatMessages.appendChild(msg);
+
+ while (chatMessages.children.length > MAX_VISIBLE) {
+ chatMessages.removeChild(chatMessages.firstChild);
+ }
+
+ setTimeout(() => {
+ msg.style.opacity = '0';
+ setTimeout(() => msg.remove(), 300);
+ }, FADE_MS);
+ }
+
+ if (chatForm) chatForm.addEventListener('submit', (e) => {
+ e.preventDefault();
+ const text = chatInput.value.trim();
+ if (!text) return;
+ chatInput.value = '';
+ const name = nameInput?.value?.trim() || 'you';
+ addChatMessage(name, text);
+ if (net?.room) {
+ net.room.send('chat', { text: text.slice(0, 200) });
+ }
+ });
+
+ window.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' && !e.shiftKey && document.activeElement !== chatInput
+ && document.activeElement?.tagName !== 'INPUT' && document.activeElement?.tagName !== 'TEXTAREA') {
+ e.preventDefault();
+ chatInput?.focus();
+ }
+ });
+
+ window._walkChat = { addChatMessage };
+}
diff --git a/vercel.json b/vercel.json
index b3f9d6b6d..0c44e7c99 100644
--- a/vercel.json
+++ b/vercel.json
@@ -73,6 +73,10 @@
"src": "/api/features\\.json",
"dest": "/api/features"
},
+ {
+ "src": "/api/platform/stats",
+ "dest": "/api/platform/stats"
+ },
{
"src": "/changelog",
"dest": "/changelog/index.html"
@@ -651,6 +655,10 @@
"src": "/dashboard/api/?",
"dest": "/dashboard-next/api.html"
},
+ {
+ "src": "/dashboard/analytics/?",
+ "dest": "/dashboard-next/analytics.html"
+ },
{
"src": "/dashboard/monetize/?",
"dest": "/dashboard-next/monetize.html"
@@ -850,6 +858,10 @@
"src": "/api/agents/([^/]+)/skills/set-price",
"dest": "/api/agent-skills?agentId=$1&action=set-price"
},
+ {
+ "src": "/api/marketplace/agents/([^/]+)/reviews",
+ "dest": "/api/marketplace/reviews?agent_id=$1"
+ },
{
"src": "/api/marketplace/agents/([^/]+)",
"dest": "/api/marketplace/[action]?action=agents&id=$1"
@@ -878,6 +890,14 @@
"src": "/api/marketplace/buy-asset/([^/]+)",
"dest": "/api/marketplace/buy-asset?reference=$1"
},
+ {
+ "src": "/skills",
+ "dest": "/skills.html"
+ },
+ {
+ "src": "/skills/",
+ "dest": "/skills.html"
+ },
{
"src": "/marketplace",
"dest": "/marketplace.html"
@@ -2148,6 +2168,14 @@
"src": "/create-review/",
"dest": "/create-review.html"
},
+ {
+ "src": "/start",
+ "dest": "/start.html"
+ },
+ {
+ "src": "/start/",
+ "dest": "/start.html"
+ },
{
"src": "/create",
"dest": "/create.html"
@@ -2278,6 +2306,50 @@
"src": "/rider/(.*)",
"dest": "/rider/$1"
},
+ {
+ "src": "/fact-checker",
+ "dest": "/pages/fact-checker.html"
+ },
+ {
+ "src": "/fact-checker/",
+ "dest": "/pages/fact-checker.html"
+ },
+ {
+ "src": "/unstoppable",
+ "dest": "/pages/unstoppable.html"
+ },
+ {
+ "src": "/unstoppable/",
+ "dest": "/pages/unstoppable.html"
+ },
+ {
+ "src": "/shopper",
+ "dest": "/pages/shopper.html"
+ },
+ {
+ "src": "/shopper/",
+ "dest": "/pages/shopper.html"
+ },
+ {
+ "src": "/paywall",
+ "dest": "/public/paywall.html"
+ },
+ {
+ "src": "/paywall/",
+ "dest": "/public/paywall.html"
+ },
+ {
+ "src": "/api/x402/fact-check",
+ "dest": "/api/x402/fact-check.js"
+ },
+ {
+ "src": "/api/agents/unstoppable-status",
+ "dest": "/api/agents/unstoppable-status.js"
+ },
+ {
+ "src": "/api/agents/endpoint-shopper-run",
+ "dest": "/api/agents/endpoint-shopper-run.js"
+ },
{
"src": "/(.*)",
"dest": "/$1"
@@ -2371,6 +2443,10 @@
{
"path": "/api/cron/siwx-gc",
"schedule": "23 * * * *"
+ },
+ {
+ "path": "/api/cron/unstoppable-tick",
+ "schedule": "*/5 * * * *"
}
]
}
\ No newline at end of file
diff --git a/vite.config.js b/vite.config.js
index c5b171b9d..8ec74463f 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -210,6 +210,7 @@ const appConfig = {
'walk-embed': resolve(__dirname, 'pages/walk-embed.html'),
pose: resolve(__dirname, 'pages/pose.html'),
club: resolve(__dirname, 'pages/club.html'),
+ skills: resolve(__dirname, 'pages/skills.html'),
'agenc-embodied': resolve(__dirname, 'pages/agenc/embodied.html'),
'agenc-room': resolve(__dirname, 'pages/agenc/room.html'),
studio: resolve(__dirname, 'public/studio/index.html'),