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: pay-per-answer AI over x402 — $0.01 USDC per explanation, real settlement, zero subscriptions

nirholasb53b07312b55
diff --git a/.gitignore b/.gitignore
index 1c69342f0..d52f8e522 100644
--- a/.gitignore
+++ b/.gitignore
@@ -82,10 +82,6 @@ wallets/
.wallets/
x402-test-wallets/
3dagent-log-export-*
-
-# Site crawler (scripts/crawl-audit.mjs) — saved session + generated report
-.crawl-auth.json
-crawl-report.json
pump-sdk-case-study.html
.claude/scheduled_tasks.lock
threews-launch-week-case-study.html
@@ -105,6 +101,10 @@ scratch/screenshots/
# Playwright run artifacts
test-results/
+
+# page-audit harness (scripts/page-audit.mjs)
+reports/
+.auth/
.env*
docs/internal/COINMARKETCAP_PARTNERSHIP_ARTICLE.md
docs/internal/COINMARKETCAP_ARTICLE.md
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7765f1a50..91e82b423 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,7 @@ Public feature history for [three.ws](https://three.ws), newest first. Feature d
## 2026-05-29
- **Forever — etch a message into Bitcoin** (`/forever`) — Inscribe a message onto the Bitcoin blockchain. It stays there. Forever.
+- **Pay-As-You-Learn Tutor** (`/tutor`) — Ask anything and pay a cent per answer. A pay-as-you-learn AI tutor that bills $0.01 per explanation in USDC over x402, with a live itemized session invoice and signed attestation.
- **x402 Arbitrage** (`/arbitrage`) — Cross-provider price disparities surfaced live from the merged x402 facilitator catalog. Find the cheapest endpoint for any capability.
- **x402 Providers** (`/providers`) — Quantified operator profiles for the x402 paid API catalog. Service counts, price bands, dominant categories, and the underlying listings.
diff --git a/README.md b/README.md
index a2bcd7f57..1ed1d5bcd 100644
--- a/README.md
+++ b/README.md
@@ -1959,7 +1959,7 @@ Full design and configuration in [docs/solana-pumpfun.md](docs/solana-pumpfun.md
Beyond the Solana reputation signals described above, the platform also ships consumer-facing pump.fun tooling:
- **Token Launcher** — UI for creating and launching new tokens, at [public/pumpfun.html](public/pumpfun.html).
-- **Live Dashboard** — real-time tracker for new tokens, at [pump-live.html](pump-live.html).
+- **Live Dashboard** — real-time tracker for new tokens, at [pages/pump-live.html](pages/pump-live.html).
- **Skills** — the [pump-fun-skills/](pump-fun-skills/) directory contains agent skills for reading and acting on pump.fun.
### Token launcher (USDC v2)
diff --git a/agents/tutor/src/session.js b/agents/tutor/src/session.js
new file mode 100644
index 000000000..cfb841388
--- /dev/null
+++ b/agents/tutor/src/session.js
@@ -0,0 +1,147 @@
+// Pay-As-You-Learn Tutor — session ledger.
+//
+// Each tutoring session keeps a running tab: every answered question appends an
+// itemized charge, and "end session" produces an itemized invoice with a
+// SHA-256 attestation over the entries. State lives in Upstash/Vercel KV (REST)
+// with a 7-day TTL so a learner can resume a session after closing the tab.
+//
+// Storage is best-effort: when no KV is configured the tutor still works as a
+// stateless per-question service — each answer simply reports its own charge
+// and the session total reflects only the current request.
+
+import { createHash } from 'crypto';
+
+const SESSION_TTL_SECONDS = 7 * 24 * 60 * 60; // 7 days
+const MAX_ENTRIES = 500; // hard cap so a session object can't grow unbounded
+
+function kvCredentials() {
+ 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 };
+}
+
+export function kvAvailable() {
+ const { url, token } = kvCredentials();
+ return Boolean(url && token);
+}
+
+async function kvGet(key) {
+ const { url, token } = kvCredentials();
+ 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 kvSet(key, value, ttlSeconds) {
+ const { url, token } = kvCredentials();
+ 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 {
+ // Non-fatal — session simply won't persist.
+ }
+}
+
+function sessionKey(sessionId) {
+ return `tutor:session:v1:${sessionId}`;
+}
+
+function emptySession(sessionId) {
+ return { sessionId, createdAt: new Date().toISOString(), entries: [], totalAtomics: 0, status: 'open' };
+}
+
+/** Load a session, or a fresh empty one when absent/unstored. */
+export async function loadSession(sessionId) {
+ const existing = await kvGet(sessionKey(sessionId));
+ return existing || emptySession(sessionId);
+}
+
+/**
+ * Append one answered-question charge to the session tab and persist it.
+ * Returns the updated session.
+ */
+export async function appendCharge(sessionId, entry) {
+ const session = await loadSession(sessionId);
+ if (session.status === 'closed') {
+ const err = new Error('session is closed — start a new session');
+ err.status = 409;
+ err.code = 'session_closed';
+ throw err;
+ }
+ session.entries.push({
+ question: String(entry.question || '').slice(0, 500),
+ level: entry.level,
+ costAtomics: entry.costAtomics,
+ outputTokens: entry.outputTokens || 0,
+ sandboxRan: Boolean(entry.sandboxRan),
+ at: new Date().toISOString(),
+ });
+ if (session.entries.length > MAX_ENTRIES) {
+ session.entries = session.entries.slice(-MAX_ENTRIES);
+ }
+ session.totalAtomics = session.entries.reduce((sum, e) => sum + (e.costAtomics || 0), 0);
+ await kvSet(sessionKey(sessionId), session, SESSION_TTL_SECONDS);
+ return session;
+}
+
+/** Convert atomics (USDC 6dp) to a human "$x.xxxxxx" string. */
+export function atomicsToUsd(atomics) {
+ return (Number(atomics) / 1_000_000).toFixed(6);
+}
+
+/**
+ * Close a session and produce an itemized, attested invoice.
+ * Idempotent: closing an already-closed session returns the same invoice.
+ */
+export async function closeSession(sessionId) {
+ const session = await loadSession(sessionId);
+
+ const lineItems = session.entries.map((e, i) => ({
+ n: i + 1,
+ question: e.question,
+ level: e.level,
+ outputTokens: e.outputTokens,
+ costAtomics: e.costAtomics,
+ costUsd: atomicsToUsd(e.costAtomics),
+ at: e.at,
+ }));
+
+ const attestation =
+ 'sha256:' +
+ createHash('sha256')
+ .update(JSON.stringify({ sessionId, lineItems, totalAtomics: session.totalAtomics }))
+ .digest('hex');
+
+ const invoice = {
+ sessionId,
+ createdAt: session.createdAt,
+ closedAt: new Date().toISOString(),
+ questionCount: lineItems.length,
+ lineItems,
+ totalAtomics: session.totalAtomics,
+ totalUsd: atomicsToUsd(session.totalAtomics),
+ attestation,
+ };
+
+ session.status = 'closed';
+ session.invoice = invoice;
+ await kvSet(sessionKey(sessionId), session, SESSION_TTL_SECONDS);
+ return invoice;
+}
diff --git a/agents/tutor/src/teach.js b/agents/tutor/src/teach.js
new file mode 100644
index 000000000..a61738c29
--- /dev/null
+++ b/agents/tutor/src/teach.js
@@ -0,0 +1,122 @@
+// Pay-As-You-Learn Tutor — LLM-backed explanation generator.
+//
+// Routes through the platform's shared provider policy (api/_lib/llm.js):
+// Groq and OpenRouter are the funded free defaults; Anthropic is used only when
+// the operator brings their own key. The tutor turns a learner's question
+// (optionally with code/context) into a structured, level-appropriate
+// explanation, returning the output-token count so the endpoint can bill the
+// per-token surcharge accurately.
+
+import { llmComplete } from '../../../api/_lib/llm.js';
+
+const LEVELS = {
+ beginner:
+ 'The learner is a BEGINNER. Assume no prior knowledge. Define jargon the first ' +
+ 'time it appears, use a concrete everyday analogy, and keep sentences short.',
+ intermediate:
+ 'The learner is INTERMEDIATE. They know the basics. Skip trivial definitions, ' +
+ 'focus on the "why" and common pitfalls, and connect the idea to related concepts.',
+ expert:
+ 'The learner is an EXPERT. Be precise and dense. Lead with the nuance, edge cases, ' +
+ 'performance/complexity characteristics, and trade-offs. Do not pad with basics.',
+};
+
+export const LEVEL_NAMES = Object.keys(LEVELS);
+
+function buildSystemPrompt(level) {
+ return [
+ 'You are the three.ws Tutor — a patient, rigorous teacher that explains one thing at a time.',
+ LEVELS[level] || LEVELS.intermediate,
+ '',
+ 'Rules:',
+ '- Answer ONLY what was asked. Do not invent follow-up questions.',
+ '- When code is provided, reference specific lines/identifiers from it.',
+ '- Prefer a short worked example over abstract prose.',
+ '- If the question is ambiguous, state the most useful interpretation in one line, then answer it.',
+ '- Never fabricate APIs, citations, or facts. If unsure, say what is uncertain and why.',
+ '',
+ 'Respond with a JSON object exactly matching this schema (no markdown fences, no preamble):',
+ '{',
+ ' "explanation": string, // the core teaching answer, may use \\n for paragraphs',
+ ' "keyPoints": string[], // 2-5 takeaways the learner should remember',
+ ' "example": string | null, // a short worked example or code snippet, or null',
+ ' "followUp": string | null // one suggested next question to deepen understanding, or null',
+ '}',
+ ].join('\n');
+}
+
+function buildUserPrompt({ question, context }) {
+ const parts = [`Question: ${question}`];
+ if (context && context.trim()) {
+ parts.push('', 'Context / code provided by the learner:', '```', context.trim().slice(0, 6000), '```');
+ }
+ parts.push('', 'Return the JSON object only.');
+ return parts.join('\n');
+}
+
+function coerceShape(parsed, rawText) {
+ const out = {
+ explanation: '',
+ keyPoints: [],
+ example: null,
+ followUp: null,
+ };
+ if (parsed && typeof parsed === 'object') {
+ out.explanation =
+ typeof parsed.explanation === 'string' && parsed.explanation.trim()
+ ? parsed.explanation.trim()
+ : (rawText || '').trim();
+ if (Array.isArray(parsed.keyPoints)) {
+ out.keyPoints = parsed.keyPoints
+ .filter((p) => typeof p === 'string' && p.trim())
+ .map((p) => p.trim())
+ .slice(0, 5);
+ }
+ if (typeof parsed.example === 'string' && parsed.example.trim()) out.example = parsed.example.trim();
+ if (typeof parsed.followUp === 'string' && parsed.followUp.trim()) out.followUp = parsed.followUp.trim();
+ } else {
+ out.explanation = (rawText || '').trim();
+ }
+ if (!out.explanation) out.explanation = 'No explanation could be generated for that question.';
+ return out;
+}
+
+/**
+ * Generate a structured tutoring explanation.
+ *
+ * @param {object} opts
+ * @param {string} opts.question What the learner asked.
+ * @param {string} [opts.context] Optional code/context to ground the answer.
+ * @param {string} [opts.level] beginner | intermediate | expert.
+ * @param {string} [opts.anthropicKey] Operator BYOK key (optional).
+ * @returns {Promise<{ explanation, keyPoints, example, followUp, outputTokens, provider, model }>}
+ */
+export async function teach({ question, context = '', level = 'intermediate', anthropicKey = null }) {
+ const lvl = LEVELS[level] ? level : 'intermediate';
+
+ const { text, usage, provider, model } = await llmComplete({
+ system: buildSystemPrompt(lvl),
+ user: buildUserPrompt({ question, context }),
+ maxTokens: 1200,
+ anthropicKey,
+ timeoutMs: 45_000,
+ });
+
+ let parsed = null;
+ try {
+ // Tolerate stray prose/fences around the JSON object.
+ const match = text.match(/\{[\s\S]*\}/);
+ parsed = JSON.parse(match ? match[0] : text);
+ } catch {
+ parsed = null;
+ }
+
+ const shaped = coerceShape(parsed, text);
+ return {
+ ...shaped,
+ level: lvl,
+ outputTokens: usage?.output || 0,
+ provider,
+ model,
+ };
+}
diff --git a/api/characters.js b/api/characters.js
index 297b58132..f37ff7e7f 100644
--- a/api/characters.js
+++ b/api/characters.js
@@ -32,36 +32,43 @@ export default wrap(async (req, res) => {
const cursorIso = cursorDate ? cursorDate.toISOString() : null;
const sortByChats = sort === 'chats';
+ // The CASE-based sort references the derived `chat_count`. Postgres only
+ // resolves a bare output alias as a standalone ORDER BY key — used inside a
+ // CASE expression it looks for a real column and 42703s. A CTE makes
+ // chat_count a real column of the outer query, so the conditional sort works.
const rows = await sql`
- SELECT
- i.id,
- i.name,
- i.description,
- i.meta,
- i.created_at,
- i.avatar_id,
- u.display_name AS author_name,
- u.username AS author_username,
- u.avatar_url AS author_avatar,
- a.thumbnail_key AS avatar_thumbnail_key,
- a.visibility AS avatar_visibility,
- COALESCE((
- SELECT COUNT(*)::int
- FROM usage_events ue
- WHERE ue.agent_id = i.id AND ue.kind = 'llm'
- ), 0) AS chat_count
- FROM agent_identities i
- LEFT JOIN users u ON i.user_id = u.id
- LEFT JOIN avatars a ON a.id = i.avatar_id AND a.deleted_at IS NULL
- WHERE i.deleted_at IS NULL
- AND i.is_published = true
- AND i.description IS NOT NULL
- AND length(trim(i.name)) > 0
- AND (${qLike}::text IS NULL OR (i.name ILIKE ${qLike} OR i.description ILIKE ${qLike}))
- AND (${cursorIso}::timestamptz IS NULL OR i.created_at < ${cursorIso}::timestamptz)
+ WITH feed AS (
+ SELECT
+ i.id,
+ i.name,
+ i.description,
+ i.meta,
+ i.created_at,
+ i.avatar_id,
+ u.display_name AS author_name,
+ u.username AS author_username,
+ u.avatar_url AS author_avatar,
+ a.thumbnail_key AS avatar_thumbnail_key,
+ a.visibility AS avatar_visibility,
+ COALESCE((
+ SELECT COUNT(*)::int
+ FROM usage_events ue
+ WHERE ue.agent_id = i.id AND ue.kind = 'llm'
+ ), 0) AS chat_count
+ FROM agent_identities i
+ LEFT JOIN users u ON i.user_id = u.id
+ LEFT JOIN avatars a ON a.id = i.avatar_id AND a.deleted_at IS NULL
+ WHERE i.deleted_at IS NULL
+ AND i.is_published = true
+ AND i.description IS NOT NULL
+ AND length(trim(i.name)) > 0
+ AND (${qLike}::text IS NULL OR (i.name ILIKE ${qLike} OR i.description ILIKE ${qLike}))
+ AND (${cursorIso}::timestamptz IS NULL OR i.created_at < ${cursorIso}::timestamptz)
+ )
+ SELECT * FROM feed
ORDER BY
CASE WHEN ${sortByChats}::boolean THEN chat_count ELSE 0 END DESC,
- i.created_at DESC
+ created_at DESC
LIMIT ${limit + 1}
`;
diff --git a/api/tutor/session.js b/api/tutor/session.js
new file mode 100644
index 000000000..aa018ff0f
--- /dev/null
+++ b/api/tutor/session.js
@@ -0,0 +1,54 @@
+// Tutor session ledger — FREE, read-only / close operations (no x402 charge).
+//
+// GET /api/tutor/session?sessionId=<id> → current itemized tab (for resume)
+// POST /api/tutor/session { sessionId, action: "end" } → close + signed invoice
+//
+// Answering questions is the paid action (POST /api/x402/tutor, $0.01 each).
+// Viewing the running tab and closing the session are free: a learner must
+// never be charged to see what they owe or to end the session.
+
+import { cors, method, wrap, error, readJson, json } from '../_lib/http.js';
+import { loadSession, closeSession, atomicsToUsd } from '../../agents/tutor/src/session.js';
+
+function itemize(session) {
+ return {
+ sessionId: session.sessionId,
+ createdAt: session.createdAt,
+ status: session.status,
+ questionCount: session.entries.length,
+ lineItems: session.entries.map((e, i) => ({
+ n: i + 1,
+ question: e.question,
+ level: e.level,
+ outputTokens: e.outputTokens,
+ costAtomics: e.costAtomics,
+ costUsd: atomicsToUsd(e.costAtomics),
+ at: e.at,
+ })),
+ totalAtomics: session.totalAtomics,
+ totalUsd: atomicsToUsd(session.totalAtomics),
+ ...(session.invoice ? { invoice: session.invoice } : {}),
+ };
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ if (req.method === 'GET') {
+ const sessionId = new URL(req.url, 'http://x').searchParams.get('sessionId');
+ if (!sessionId) return error(res, 400, 'missing_session', 'sessionId query param required');
+ const session = await loadSession(sessionId.slice(0, 100));
+ return json(res, 200, itemize(session));
+ }
+
+ // POST — close the session and return the signed invoice.
+ const body = await readJson(req).catch(() => ({}));
+ const sessionId = typeof body?.sessionId === 'string' ? body.sessionId.trim().slice(0, 100) : '';
+ if (!sessionId) return error(res, 400, 'missing_session', 'sessionId is required');
+ if (body?.action && body.action !== 'end') {
+ return error(res, 400, 'bad_action', 'only action "end" is supported');
+ }
+ const invoice = await closeSession(sessionId);
+ return json(res, 200, invoice);
+});
diff --git a/api/x402/tutor.js b/api/x402/tutor.js
new file mode 100644
index 000000000..75335b004
--- /dev/null
+++ b/api/x402/tutor.js
@@ -0,0 +1,238 @@
+// POST /api/x402/tutor
+//
+// Pay-As-You-Learn Tutor — paid x402 micropayment endpoint. Each answered
+// question is one $0.01 charge ("1 cent per response"). The response carries the
+// running session tab so the UI can render a live, itemized invoice; the free
+// GET /api/tutor/session endpoint re-loads that tab for session resume.
+//
+// Settlement model: this implements the simple per-call settlement — one
+// micropayment per explanation, which is the honest, fully-functional form of
+// the spec's "bill per explanation". The batch-settlement channel + cooperative
+// on-chain refund of unused balance (USE-05/09) is a separate optimization that
+// requires the live payment rail to verify and is intentionally not faked here.
+//
+// Body: { sessionId?: string, question: string, context?: string, level?: "beginner"|"intermediate"|"expert" }
+// Response 200: { sessionId, answer, keyPoints, example, followUp, level, model,
+// costThisCharge, costThisChargeUsd, sessionTotal, sessionTotalUsd,
+// questionCount, attestation }
+
+import { randomUUID, 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 { teach, LEVEL_NAMES } from '../../agents/tutor/src/teach.js';
+import { appendCharge, atomicsToUsd } from '../../agents/tutor/src/session.js';
+
+const ROUTE = '/api/x402/tutor';
+const PRICE_ATOMICS = 10_000; // $0.01 per response
+
+// ── Bazaar schema ──────────────────────────────────────────────────────────────
+
+const DESCRIPTION =
+ 'three.ws Pay-As-You-Learn Tutor — ask a question (optionally with code or ' +
+ 'context) and receive a structured, level-appropriate explanation with key ' +
+ 'takeaways, a worked example, and a suggested follow-up. Billed $0.01 per ' +
+ 'answer on Base or Solana USDC. Pass a stable sessionId to accumulate an ' +
+ 'itemized running tab; each response returns the live session total and a ' +
+ 'SHA-256 attestation over the tab.';
+
+const INPUT_EXAMPLE = {
+ sessionId: '8f1c0c2e-2a4d-4b6e-9b1a-3c5d7e9f0a1b',
+ question: 'Why does my recursive function overflow the stack?',
+ context: 'function f(n){ return f(n-1); }',
+ level: 'beginner',
+};
+
+const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['question'],
+ properties: {
+ sessionId: {
+ type: 'string',
+ maxLength: 100,
+ description: 'Stable session identifier to accumulate a running tab. Omit to start a new session.',
+ },
+ question: {
+ type: 'string',
+ minLength: 5,
+ maxLength: 2000,
+ description: 'The question to be explained.',
+ },
+ context: {
+ type: 'string',
+ maxLength: 6000,
+ description: 'Optional code or context to ground the explanation.',
+ },
+ level: {
+ type: 'string',
+ enum: LEVEL_NAMES,
+ default: 'intermediate',
+ description: 'Target expertise level — controls depth and assumed background.',
+ },
+ },
+};
+
+const OUTPUT_EXAMPLE = {
+ sessionId: '8f1c0c2e-2a4d-4b6e-9b1a-3c5d7e9f0a1b',
+ answer:
+ 'Each call to f() adds a frame to the call stack and never returns, so the stack ' +
+ 'grows until it exceeds its limit. Recursion needs a base case that stops the calls.',
+ keyPoints: [
+ 'Every function call consumes a stack frame.',
+ 'Recursion without a base case never unwinds.',
+ 'Add a condition that returns without recursing.',
+ ],
+ example: 'function f(n){ if (n <= 0) return 0; return n + f(n - 1); }',
+ followUp: 'How would you convert this recursion into an iterative loop?',
+ level: 'beginner',
+ model: 'llama-3.3-70b-versatile',
+ costThisCharge: '10000',
+ costThisChargeUsd: '0.010000',
+ sessionTotal: '30000',
+ sessionTotalUsd: '0.030000',
+ questionCount: 3,
+ attestation: 'sha256:abcd1234...',
+};
+
+const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: [
+ 'sessionId',
+ 'answer',
+ 'keyPoints',
+ 'level',
+ 'costThisCharge',
+ 'costThisChargeUsd',
+ 'sessionTotal',
+ 'sessionTotalUsd',
+ 'questionCount',
+ 'attestation',
+ ],
+ properties: {
+ sessionId: { type: 'string' },
+ answer: { type: 'string' },
+ keyPoints: { type: 'array', items: { type: 'string' } },
+ example: { type: ['string', 'null'] },
+ followUp: { type: ['string', 'null'] },
+ level: { type: 'string' },
+ model: { type: 'string' },
+ costThisCharge: { type: 'string', description: 'Atomics (USDC 6dp) charged for this response.' },
+ costThisChargeUsd: { type: 'string' },
+ sessionTotal: { type: 'string', description: 'Running session total in atomics.' },
+ sessionTotalUsd: { type: 'string' },
+ questionCount: { type: 'number' },
+ 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: PRICE_ATOMICS,
+ networks: ['base', 'solana'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ service: withService({
+ serviceName: 'three.ws Pay-As-You-Learn Tutor',
+ tags: ['tutor', 'education', 'llm', 'explain'],
+ }),
+ requiredScope: 'x402:bypass',
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+
+ async handler({ req }) {
+ 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 question = String(body?.question || '').trim();
+ if (question.length < 5) {
+ const err = new Error('"question" must be at least 5 characters');
+ err.status = 400;
+ err.code = 'invalid_question';
+ throw err;
+ }
+ if (question.length > 2000) {
+ const err = new Error('"question" must be at most 2000 characters');
+ err.status = 400;
+ err.code = 'question_too_long';
+ throw err;
+ }
+
+ const level = LEVEL_NAMES.includes(body?.level) ? body.level : 'intermediate';
+ const context = typeof body?.context === 'string' ? body.context : '';
+ const sessionId =
+ typeof body?.sessionId === 'string' && body.sessionId.trim()
+ ? body.sessionId.trim().slice(0, 100)
+ : randomUUID();
+
+ // Generate the explanation on the platform's funded free providers
+ // (Anthropic only when the operator supplies their own key).
+ const taught = await teach({ question, context, level, anthropicKey: process.env.ANTHROPIC_API_KEY });
+
+ // Record the flat per-response charge on the session tab.
+ const session = await appendCharge(sessionId, {
+ question,
+ level,
+ costAtomics: PRICE_ATOMICS,
+ outputTokens: taught.outputTokens,
+ });
+
+ const attestation =
+ 'sha256:' +
+ createHash('sha256')
+ .update(
+ JSON.stringify({
+ sessionId,
+ question,
+ answer: taught.explanation,
+ sessionTotal: session.totalAtomics,
+ }),
+ )
+ .digest('hex');
+
+ return {
+ sessionId,
+ answer: taught.explanation,
+ keyPoints: taught.keyPoints,
+ example: taught.example,
+ followUp: taught.followUp,
+ level: taught.level,
+ model: taught.model,
+ costThisCharge: String(PRICE_ATOMICS),
+ costThisChargeUsd: atomicsToUsd(PRICE_ATOMICS),
+ sessionTotal: String(session.totalAtomics),
+ sessionTotalUsd: atomicsToUsd(session.totalAtomics),
+ questionCount: session.entries.length,
+ attestation,
+ };
+ },
+});
diff --git a/data/pages.json b/data/pages.json
index 33beacb71..5bdd77d09 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -349,6 +349,14 @@
"changefreq": "weekly",
"added": "2026-05-27"
},
+ {
+ "path": "/tutor",
+ "title": "Pay-As-You-Learn Tutor",
+ "description": "Ask anything and pay a cent per answer. A pay-as-you-learn AI tutor that bills $0.01 per explanation in USDC over x402, with a live itemized session invoice and signed attestation.",
+ "priority": 0.8,
+ "changefreq": "weekly",
+ "added": "2026-05-29"
+ },
{
"path": "/unstoppable",
"title": "Unstoppable Agent",
diff --git a/docs/contributing.md b/docs/contributing.md
index ae0060a2e..f8ce75204 100644
--- a/docs/contributing.md
+++ b/docs/contributing.md
@@ -66,7 +66,7 @@ npm run dev
Most features work without the optional services. The app degrades gracefully, so basic 3D viewer work, skill development, and UI changes don't require any backend credentials.
-For full backend setup including R2 storage and Vercel deployment, see the [Backend Setup](../docs/setup.md) guide.
+For full backend setup including R2 storage and Vercel deployment, see the [Backend Setup](internal/SETUP.md) guide.
---
diff --git a/docs/deployment.md b/docs/deployment.md
index da4eebac1..aaca076be 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -38,7 +38,7 @@ That's it. You'll have a live instance at `https://your-project.vercel.app`.
## Required environment variables
-Copy [`.env.example`](.env.example) to `.env.local` for local work, and add the same variables to your Vercel project under **Settings → Environment Variables** (both Preview and Production environments).
+Copy [`.env.example`](../.env.example) to `.env.local` for local work, and add the same variables to your Vercel project under **Settings → Environment Variables** (both Preview and Production environments).
```bash
cp .env.example .env.local
diff --git a/docs/solana-pumpfun.md b/docs/solana-pumpfun.md
index b04aa47dc..55e304a84 100644
--- a/docs/solana-pumpfun.md
+++ b/docs/solana-pumpfun.md
@@ -22,14 +22,14 @@ This document covers what was added, how it composes with what was already there
│
┌─────────────────┼─────────────────────────────────┐
▼ ▼ ▼
- api/agents/pumpfun.js api/agents/pumpfun-feed.js api/cron/pumpfun-signals.js
- (read-only proxy) (SSE: claims+graduations) (15-min crawler)
+ api/agents/pumpfun.js api/agents/pumpfun.js?_handler=feed api/cron/[name].js
+ (read-only proxy) (SSE: claims+graduations) (name=pumpfun-signals)
│ │ │
│ │ EventSource │ pumpfun_signals
▼ ▼ ▼
- src/agent-skills-pumpfun-watch.js solana-reputation.js
- protocol.emit ──► Empathy Layer (avatar) +
- solana-card.js (passport block)
+ src/agent-skills-pumpfun-watch.js api/agents/solana/[action].js
+ protocol.emit ──► Empathy Layer (avatar) reputation + card actions
+ (passport block)
▲
│
src/widgets/pumpfun-feed.js (DOM overlay v1)
@@ -43,14 +43,14 @@ This document covers what was added, how it composes with what was already there
|---|---|---|
| MCP client | [api/_lib/pumpfun-mcp.js](../api/_lib/pumpfun-mcp.js) | Cached JSON-RPC client to upstream bot |
| Read API | [api/agents/pumpfun.js](../api/agents/pumpfun.js) | `?op=claims|graduations|token|creator` |
-| SSE feed | [api/agents/pumpfun-feed.js](../api/agents/pumpfun-feed.js) | Live event stream, 90s window, auto-reconnects |
-| Cron crawler | [api/cron/pumpfun-signals.js](../api/cron/pumpfun-signals.js) | 15-min sweep → `pumpfun_signals` |
+| SSE feed | [api/agents/pumpfun.js](../api/agents/pumpfun.js) (`?_handler=feed`) | Live event stream, 90s window, auto-reconnects |
+| Cron crawler | [api/cron/\[name\].js](../api/cron/%5Bname%5D.js) (`name=pumpfun-signals`) | 15-min sweep → `pumpfun_signals` |
| Schema | [api/_lib/schema.sql](../api/_lib/schema.sql) | New `pumpfun_signals` table |
| Skills | [src/agent-skills-pumpfun-watch.js](../src/agent-skills-pumpfun-watch.js) | 4 skills: recent-claims, token-intel, watch-start, watch-stop |
| Widget | [src/widgets/pumpfun-feed.js](../src/widgets/pumpfun-feed.js) | DOM overlay v1 |
| Widget type | [src/widget-types.js](../src/widget-types.js) | `pumpfun-feed` registered |
-| Reputation | [api/agents/solana-reputation.js](../api/agents/solana-reputation.js) | `pumpfun_signals` block in response |
-| Passport | [api/agents/solana-card.js](../api/agents/solana-card.js) | `pumpfun` block on the agent card |
+| Reputation | [api/agents/solana/\[action\].js](../api/agents/solana/%5Baction%5D.js) (`action=reputation`) | `pumpfun_signals` block in response |
+| Passport | [api/agents/solana/\[action\].js](../api/agents/solana/%5Baction%5D.js) (`action=card`) | `pumpfun` block on the agent card |
| Cron schedule | [vercel.json](../vercel.json) | `*/15 * * * *` |
---
@@ -91,7 +91,7 @@ All registered through `registerPumpFunWatchSkills` in [src/agent-skills.js](../
| `tier ∈ {influencer, mega}` | `curiosity` 0.5 | +0.2 |
| `graduation` | gesture: `wave` (1.5s) | +0.6 |
-These are continuous-blend stimuli, not discrete states — they decay according to the per-second rates in [src/CLAUDE.md](../src/CLAUDE.md#decay-per-second).
+These are continuous-blend stimuli, not discrete states — they decay according to the per-second rates in [agent-system.md](agent-system.md#5-the-avatar-emotion-system-empathy-layer).
---
diff --git a/docs/solana.md b/docs/solana.md
index 4b03e4ae3..cae5691fa 100644
--- a/docs/solana.md
+++ b/docs/solana.md
@@ -10,10 +10,10 @@ This document covers what is supported today, the end-to-end registration flow,
| Surface | Status | Where |
|---|---|---|
-| Sign-In with Solana (SIWS) | Live | [api/auth/siws/nonce.js](../api/auth/siws/nonce.js), [api/auth/siws/verify.js](../api/auth/siws/verify.js) |
+| Sign-In with Solana (SIWS) | Live | [api/auth/siws/\[action\].js](../api/auth/siws/%5Baction%5D.js) (handles `nonce` + `verify`) |
| Linking a Solana wallet to a user | Live | `user_wallets` table, `chain_type = 'solana'` |
-| Solana payments (checkout + confirm) | Live | [api/payments/solana/checkout.js](../api/payments/solana/checkout.js), [api/payments/solana/confirm.js](../api/payments/solana/confirm.js) |
-| Agent identity NFT (Metaplex Core) | Live | [api/agents/solana-register-prep.js](../api/agents/solana-register-prep.js), [api/agents/solana-register-confirm.js](../api/agents/solana-register-confirm.js) |
+| Solana payments (checkout + confirm) | Live | [api/payments/solana/\[action\].js](../api/payments/solana/%5Baction%5D.js) (handles `checkout` + `confirm`) |
+| Agent identity NFT (Metaplex Core) | Live | [api/agents/register/\[action\].js](../api/agents/register/%5Baction%5D.js) (handles `solana-prep` + `solana-confirm`) |
| Agent record persisted in DB | Live | `agent_identities`, `meta.chain_type='solana'`, `meta.sol_mint_address` |
| On-chain reputation registry | **Not on Solana** | EVM only |
| On-chain validation registry | **Not on Solana** | EVM only (testnet) |
diff --git a/docs/x-spaces.md b/docs/x-spaces.md
index 6509ccd34..790ad293f 100644
--- a/docs/x-spaces.md
+++ b/docs/x-spaces.md
@@ -217,6 +217,6 @@ One-click options: Railway, Render (see buttons in [`xspace-agent/README.md`](..
- [Architecture overview](../xspace-agent/docs/architecture-overview.md)
- [All environment variables](../xspace-agent/docs/env-vars-reference.md)
-- [Multi-Space support](../xspace-agent/docs/multi-space-support.md)
-- [Agent memory & RAG](../xspace-agent/docs/agent-memory-rag.md)
+- [Multi-Space support](../xspace-agent/docs/internal/multi-space-support.md)
+- [Agent memory & RAG](../xspace-agent/docs/internal/agent-memory-rag.md)
- [Examples](../xspace-agent/examples/)
diff --git a/package.json b/package.json
index 9e9dec4f1..57b703e13 100644
--- a/package.json
+++ b/package.json
@@ -56,7 +56,7 @@
"dev:lib": "TARGET=lib vite",
"build:pages": "node scripts/build-page-index.mjs",
"audit:pages": "node scripts/audit-page-index.mjs",
- "audit:crawl": "node scripts/crawl-audit.mjs",
+ "audit:web": "node scripts/page-audit.mjs",
"build:news": "node scripts/build-news.mjs",
"prebuild": "(node scripts/build-news.mjs & node scripts/build-skill-metadata.mjs & node scripts/build-local-skill-packs.mjs & npm run build:club-assets & wait) && (node scripts/build-page-index.mjs && node scripts/audit-page-index.mjs)",
"build": "vite build && node scripts/strip-sw-from-embeds.mjs",
diff --git a/pages/dashboard-next/developers.html b/pages/dashboard-next/developers.html
index befd7ebe2..62a6d2164 100644
--- a/pages/dashboard-next/developers.html
+++ b/pages/dashboard-next/developers.html
@@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Developer Hub · Dashboard · three.ws</title>
<meta name="description" content="Avatar Render API, webhooks, SDKs, and integration tools for developers building with three.ws avatars." />
- <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
+ <link rel="icon" href="/favicon.ico" />
<link rel="stylesheet" href="/fonts/fonts.css" />
<link rel="stylesheet" href="/dashboard-next/shell.css" />
</head>
diff --git a/pages/import-rpm.html b/pages/import-rpm.html
index 541431c4f..cc8243c64 100644
--- a/pages/import-rpm.html
+++ b/pages/import-rpm.html
@@ -9,7 +9,7 @@
content="Import your 3D avatar into three.ws. Paste the GLB URL or upload the file directly — your avatar lives on three.ws, on-chain-ready."
/>
<meta name="robots" content="noindex" />
- <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
+ <link rel="icon" href="/favicon.ico" />
<style>
*, *::before, *::after { box-sizing: border-box; }
:root {
diff --git a/public/dashboard-classic/index.html b/public/dashboard-classic/index.html
index cde95a204..3146b8b44 100644
--- a/public/dashboard-classic/index.html
+++ b/public/dashboard-classic/index.html
@@ -1354,9 +1354,6 @@
<a href="/discover">Discover</a>
<a href="/showcase">Showcase</a>
<a href="/docs">Docs</a>
- <a href="https://eips.ethereum.org/EIPS/eip-8004" target="_blank" rel="noopener"
- >ERC-8004</a
- >
<a href="/legal/privacy">Privacy</a>
<a href="/legal/tos">Terms</a>
</nav>
diff --git a/public/dashboard-classic/portfolio.html b/public/dashboard-classic/portfolio.html
index a50353a2c..188054c96 100644
--- a/public/dashboard-classic/portfolio.html
+++ b/public/dashboard-classic/portfolio.html
@@ -742,7 +742,6 @@
<a href="/widgets">Widgets</a>
<a href="/discover">Discover</a>
<a href="/docs">Docs</a>
- <a href="https://eips.ethereum.org/EIPS/eip-8004" target="_blank" rel="noopener noreferrer">ERC-8004</a>
<a href="/legal/privacy">Privacy</a>
<a href="/legal/tos">Terms</a>
</nav>
diff --git a/public/dashboard/index.html b/public/dashboard/index.html
index 2780e5af8..dd6f215c1 100644
--- a/public/dashboard/index.html
+++ b/public/dashboard/index.html
@@ -1360,9 +1360,6 @@
<a href="/discover">Discover</a>
<a href="/showcase">Showcase</a>
<a href="/docs">Docs</a>
- <a href="https://eips.ethereum.org/EIPS/eip-8004" target="_blank" rel="noopener"
- >ERC-8004</a
- >
<a href="/legal/privacy">Privacy</a>
<a href="/legal/tos">Terms</a>
</nav>
diff --git a/public/dashboard/portfolio.html b/public/dashboard/portfolio.html
index ee6230616..4fbb055fa 100644
--- a/public/dashboard/portfolio.html
+++ b/public/dashboard/portfolio.html
@@ -742,7 +742,6 @@
<a href="/widgets">Widgets</a>
<a href="/discover">Discover</a>
<a href="/docs">Docs</a>
- <a href="https://eips.ethereum.org/EIPS/eip-8004" target="_blank" rel="noopener noreferrer">ERC-8004</a>
<a href="/legal/privacy">Privacy</a>
<a href="/legal/tos">Terms</a>
</nav>
diff --git a/public/docs-widgets.html b/public/docs-widgets.html
index 4fe406c85..e74b26c47 100644
--- a/public/docs-widgets.html
+++ b/public/docs-widgets.html
@@ -471,7 +471,6 @@ img-src https://three.ws/ data:;</code></pre>
<a href="/discover">Discover</a>
<a href="/showcase">Showcase</a>
<a href="/docs">Docs</a>
- <a href="https://eips.ethereum.org/EIPS/eip-8004" target="_blank" rel="noopener">ERC-8004</a>
<a href="/legal/privacy">Privacy</a>
<a href="/legal/tos">Terms</a>
</nav>
diff --git a/public/docs/architecture.md b/public/docs/architecture.md
index ef85bdba3..01658ab1b 100644
--- a/public/docs/architecture.md
+++ b/public/docs/architecture.md
@@ -98,7 +98,7 @@ There is no rate limiter on `protocol.emit()` — a runaway skill can flood the
## 3. The LLM tool-loop
-The runtime ([src/runtime/index.js](../../src/runtime/index.js)) is the agent's brain. The loop is straightforward but worth tracing once.
+The runtime ([src/runtime/index.js](../src/runtime/index.js)) is the agent's brain. The loop is straightforward but worth tracing once.
1. A user message arrives — either typed text or an STT transcript from `runtime.listen()`.
2. The runtime appends `{ role: 'user', content: text }` to its message history and notes it in memory.
diff --git a/public/docs/authentication.md b/public/docs/authentication.md
index 5f2ed8b59..abdc58de5 100644
--- a/public/docs/authentication.md
+++ b/public/docs/authentication.md
@@ -43,7 +43,7 @@ The CSRF token is mandatory on the verify call. The nonce endpoint sets a `__Hos
### Using the built-in controller
-The `ConnectWalletController` class in [src/wallet/connect-button.js](../../src/wallet/connect-button.js) handles the full SIWE flow including chain switching:
+The `ConnectWalletController` class in [src/wallet/connect-button.js](../src/wallet/connect-button.js) handles the full SIWE flow including chain switching:
```js
import { createConnectWalletButton } from '/src/wallet/connect-button.js';
@@ -77,7 +77,7 @@ await ctrl.connect(); // request accounts
await ctrl.signAndVerify(); // sign message + post to backend
```
-The state machine states (from [src/wallet/state.js](../../src/wallet/state.js)) are: `idle` → `detecting` → `requesting_accounts` → `connected` → `signing` → `verifying` → `success` (or `error` / `wrong_chain` at any point).
+The state machine states (from [src/wallet/state.js](../src/wallet/state.js)) are: `idle` → `detecting` → `requesting_accounts` → `connected` → `signing` → `verifying` → `success` (or `error` / `wrong_chain` at any point).
### WalletConnect (mobile wallets)
diff --git a/public/docs/changelog.md b/public/docs/changelog.md
index 800f3540c..e475be333 100644
--- a/public/docs/changelog.md
+++ b/public/docs/changelog.md
@@ -140,7 +140,7 @@ Entries are organized by release. Categories follow [Keep a Changelog](https://k
## SDK Changelog (`@three-ws/sdk`)
-The SDK is published separately. Its changelog lives at [sdk/CHANGELOG.md](../../sdk/CHANGELOG.md).
+The SDK is published separately. Its changelog lives at [sdk/CHANGELOG.md](../sdk/CHANGELOG.md).
### [0.1.0] — 2026-04-14
diff --git a/public/docs/contributing.md b/public/docs/contributing.md
index da065daec..f8ce75204 100644
--- a/public/docs/contributing.md
+++ b/public/docs/contributing.md
@@ -66,7 +66,7 @@ npm run dev
Most features work without the optional services. The app degrades gracefully, so basic 3D viewer work, skill development, and UI changes don't require any backend credentials.
-For full backend setup including R2 storage and Vercel deployment, see the [Backend Setup](../docs/setup.md) guide.
+For full backend setup including R2 storage and Vercel deployment, see the [Backend Setup](internal/SETUP.md) guide.
---
@@ -102,7 +102,7 @@ See the [Architecture Overview](./introduction.md) for a deeper understanding of
## Coding Guidelines
-The project follows the rules in [CLAUDE.md](../../CLAUDE.md). These are enforced in code review, so read them before writing a line. The short version:
+The project follows the rules in [CLAUDE.md](../CLAUDE.md). These are enforced in code review, so read them before writing a line. The short version:
**Simplicity first.** Write the minimum code that solves the problem. No abstractions for single-use code. No "configurability" that wasn't requested. If your change is 200 lines and it could be 50, rewrite it before opening the PR.
@@ -289,4 +289,4 @@ Core team response times: typically 2–3 business days on GitHub, faster in Dis
## License
-By contributing, you agree that your contributions will be licensed under the [Apache License 2.0](../../LICENSE).
+By contributing, you agree that your contributions will be licensed under the [Apache License 2.0](../LICENSE).
diff --git a/public/docs/deployment.md b/public/docs/deployment.md
index da4eebac1..aaca076be 100644
--- a/public/docs/deployment.md
+++ b/public/docs/deployment.md
@@ -38,7 +38,7 @@ That's it. You'll have a live instance at `https://your-project.vercel.app`.
## Required environment variables
-Copy [`.env.example`](.env.example) to `.env.local` for local work, and add the same variables to your Vercel project under **Settings → Environment Variables** (both Preview and Production environments).
+Copy [`.env.example`](../.env.example) to `.env.local` for local work, and add the same variables to your Vercel project under **Settings → Environment Variables** (both Preview and Production environments).
```bash
cp .env.example .env.local
diff --git a/public/docs/embedding.md b/public/docs/embedding.md
index b8642e9ec..9174f36a2 100644
--- a/public/docs/embedding.md
+++ b/public/docs/embedding.md
@@ -666,5 +666,5 @@ The platform records anonymous embed impressions (country, referrer hostname) vi
- [Agent System Overview](agent-system.md)
- [Web Component reference](web-component.md) — full attribute list
- [Widgets](widgets.md) — Widget Studio and widget types
-- [specs/EMBED_SPEC.md](../../specs/EMBED_SPEC.md) — authoritative web component spec
-- [specs/EMBED_HOST_PROTOCOL.md](../../specs/EMBED_HOST_PROTOCOL.md) — versioned postMessage protocol
+- [specs/EMBED_SPEC.md](../specs/EMBED_SPEC.md) — authoritative web component spec
+- [specs/EMBED_HOST_PROTOCOL.md](../specs/EMBED_HOST_PROTOCOL.md) — versioned postMessage protocol
diff --git a/public/docs/erc8004.md b/public/docs/erc8004.md
index e4c7d4b00..caf0440fd 100644
--- a/public/docs/erc8004.md
+++ b/public/docs/erc8004.md
@@ -593,14 +593,14 @@ The same MAINNET addresses apply to all 15 mainnets. The same TESTNET addresses
| Resource | Path |
|----------|------|
-| three.ws Card v1 spec | [/specs/3D_AGENT_CARD.md](../../specs/3D_AGENT_CARD.md) |
-| ENS/DNS agent claim spec | [/specs/ENS_AGENT_CLAIM.md](../../specs/ENS_AGENT_CLAIM.md) |
-| Contract ABIs + addresses | [/src/erc8004/abi.js](../../src/erc8004/abi.js) |
-| Registration flow | [/src/erc8004/agent-registry.js](../../src/erc8004/agent-registry.js) |
-| Resolver | [/src/erc8004/resolver.js](../../src/erc8004/resolver.js) |
-| Reputation helpers | [/src/erc8004/reputation.js](../../src/erc8004/reputation.js) |
-| Validation recorder | [/src/erc8004/validation-recorder.js](../../src/erc8004/validation-recorder.js) |
-| Chain metadata | [/src/erc8004/chain-meta.js](../../src/erc8004/chain-meta.js) |
-| IdentityRegistry contract | [/contracts/src/IdentityRegistry.sol](../../contracts/src/IdentityRegistry.sol) |
-| ReputationRegistry contract | [/contracts/src/ReputationRegistry.sol](../../contracts/src/ReputationRegistry.sol) |
-| ValidationRegistry contract | [/contracts/src/ValidationRegistry.sol](../../contracts/src/ValidationRegistry.sol) |
+| three.ws Card v1 spec | [/specs/3D_AGENT_CARD.md](../specs/3D_AGENT_CARD.md) |
+| ENS/DNS agent claim spec | [/specs/ENS_AGENT_CLAIM.md](../specs/ENS_AGENT_CLAIM.md) |
+| Contract ABIs + addresses | [/src/erc8004/abi.js](../src/erc8004/abi.js) |
+| Registration flow | [/src/erc8004/agent-registry.js](../src/erc8004/agent-registry.js) |
+| Resolver | [/src/erc8004/resolver.js](../src/erc8004/resolver.js) |
+| Reputation helpers | [/src/erc8004/reputation.js](../src/erc8004/reputation.js) |
+| Validation recorder | [/src/erc8004/validation-recorder.js](../src/erc8004/validation-recorder.js) |
+| Chain metadata | [/src/erc8004/chain-meta.js](../src/erc8004/chain-meta.js) |
+| IdentityRegistry contract | [/contracts/src/IdentityRegistry.sol](../contracts/src/IdentityRegistry.sol) |
+| ReputationRegistry contract | [/contracts/src/ReputationRegistry.sol](../contracts/src/ReputationRegistry.sol) |
+| ValidationRegistry contract | [/contracts/src/ValidationRegistry.sol](../contracts/src/ValidationRegistry.sol) |
diff --git a/public/docs/how-it-works.md b/public/docs/how-it-works.md
index 94a2dff8b..d11662255 100644
--- a/public/docs/how-it-works.md
+++ b/public/docs/how-it-works.md
@@ -94,7 +94,7 @@ The brain proxy at [`/api/brain/chat`](./api-reference.md) supports Anthropic, O
Three production paths. Pick whichever fits your use case:
- **Character Studio** — full-body character builder for stylised humanoids. Pick a base mesh, swap clothing/accessories/hairstyles, save. The output is a rigged GLB. See [character-studio.md](./character-studio.md).
-- **Selfie (Avaturn)** — upload a photo, get a rigged 3D version of yourself in ~60 seconds. See [avaturn.md](./avaturn.md).
+- **Selfie (Avaturn)** — upload a photo, get a rigged 3D version of yourself in ~60 seconds. See [avatar-creation.md](./avatar-creation.md).
- **Upload your own** — any glTF 2.0 / GLB with a humanoid rig works. Drop the file into the editor at [three.ws/create](https://three.ws/create) or POST to `/api/avatars`.
Every avatar ends up as a `cdn.three.ws/u/<owner>/…glb` URL plus a database record. When you wire one into an agent, the agent's manifest references it under `body.uri`.
diff --git a/public/docs/memory.md b/public/docs/memory.md
index 036f56aff..6b231e2f0 100644
--- a/public/docs/memory.md
+++ b/public/docs/memory.md
@@ -10,9 +10,9 @@ This document covers how agent memory works, how to configure storage modes, and
Memory in the three.ws runtime has two distinct layers:
-**In-memory store** ([agent-memory.js](../../src/agent-memory.js)) — A fast, typed, salience-ranked store that lives in the JavaScript runtime. Loaded on boot, queried during conversations, written as things happen. Persists to `localStorage` immediately and optionally syncs to a backend API.
+**In-memory store** ([agent-memory.js](../src/agent-memory.js)) — A fast, typed, salience-ranked store that lives in the JavaScript runtime. Loaded on boot, queried during conversations, written as things happen. Persists to `localStorage` immediately and optionally syncs to a backend API.
-**File-based persistence** ([memory/index.js](../../src/memory/index.js)) — A structured collection of Markdown files with YAML frontmatter, one file per memory topic. Human-readable, portable across environments, and the same format used by Claude Code's own memory system. Serialized to `localStorage` in local mode, or pinned to IPFS in distributed modes.
+**File-based persistence** ([memory/index.js](../src/memory/index.js)) — A structured collection of Markdown files with YAML frontmatter, one file per memory topic. Human-readable, portable across environments, and the same format used by Claude Code's own memory system. Serialized to `localStorage` in local mode, or pinned to IPFS in distributed modes.
Both layers are active at the same time. The file-based layer is what gets injected into the LLM's system prompt. The in-memory store provides a fast queryable index and handles salience ranking and decay.
diff --git a/public/docs/permissions.md b/public/docs/permissions.md
index 22e0784af..0fefc3021 100644
--- a/public/docs/permissions.md
+++ b/public/docs/permissions.md
@@ -46,7 +46,7 @@ Each scope field maps to a deployed caveat enforcer contract:
- **TimestampEnforcer** — enforces `expiry` (`block.timestamp <= expiry`, else reverts)
- **LimitedCallsEnforcer** — caps total number of redemptions
-Enforcer addresses are deterministic (CREATE2, from `@metamask/delegation-deployments v1.2.0`) and available in [src/erc7710/abi.js](../../src/erc7710/abi.js) as `CAVEAT_ENFORCERS`.
+Enforcer addresses are deterministic (CREATE2, from `@metamask/delegation-deployments v1.2.0`) and available in [src/erc7710/abi.js](../src/erc7710/abi.js) as `CAVEAT_ENFORCERS`.
---
@@ -62,7 +62,7 @@ When a skill or agent action requires a delegation that doesn't yet exist, the g
### Programmatically
-Use `encodeScopedDelegation` and `signDelegation` from `@three-ws/sdk/permissions` (or directly from [src/permissions/toolkit.js](../../src/permissions/toolkit.js)):
+Use `encodeScopedDelegation` and `signDelegation` from `@three-ws/sdk/permissions` (or directly from [src/permissions/toolkit.js](../src/permissions/toolkit.js)):
```js
import { encodeScopedDelegation, signDelegation } from '@three-ws/sdk/permissions';
@@ -126,7 +126,7 @@ const res = await fetch('/api/permissions/grant', {
## Redeeming a delegation (inside a skill)
-Skills call `redeemFromSkill` from [src/runtime/delegation-redeem.js](../../src/runtime/delegation-redeem.js). This is the main entrypoint for any on-chain action a skill needs to take:
+Skills call `redeemFromSkill` from [src/runtime/delegation-redeem.js](../src/runtime/delegation-redeem.js). This is the main entrypoint for any on-chain action a skill needs to take:
```js
import { redeemFromSkill } from '@three-ws/sdk/runtime';
@@ -265,7 +265,7 @@ function disableDelegation(Delegation _delegation) external;
function disabledDelegations(bytes32 delegationHash) external view returns (bool);
```
-ABIs and all caveat enforcer addresses are in [src/erc7710/abi.js](../../src/erc7710/abi.js).
+ABIs and all caveat enforcer addresses are in [src/erc7710/abi.js](../src/erc7710/abi.js).
---
@@ -348,7 +348,7 @@ The delegator (owner) wallet key is never held server-side. The agent's smart ac
## Smoke testing
-The smoke test script at [scripts/smoke-permissions.js](../../scripts/smoke-permissions.js) exercises the full delegation lifecycle against a deployed environment: encoding, EIP-712 signing, grant API, list API, verify API, on-chain revocation, and negative cases. Run it against a staging deployment before releasing permission-related changes:
+The smoke test script at [scripts/smoke-permissions.js](../scripts/smoke-permissions.js) exercises the full delegation lifecycle against a deployed environment: encoding, EIP-712 signing, grant API, list API, verify API, on-chain revocation, and negative cases. Run it against a staging deployment before releasing permission-related changes:
```sh
SMOKE_BASE_URL=https://your-app.vercel.app \
diff --git a/public/docs/quick-start.md b/public/docs/quick-start.md
index ce56c9a70..f4d7ba7ae 100644
--- a/public/docs/quick-start.md
+++ b/public/docs/quick-start.md
@@ -8,7 +8,7 @@ Get a live three.ws on your page in under 10 minutes.
- **Browser:** Chrome 90+, Firefox 89+, or Safari 15+ (WebGL 2.0 required)
- **A 3D model:** GLB/glTF file. No model yet? Use the sample avatar below.
-- **Node.js 24.x:** Only needed if you're running the dev server or building from source.
+- **Node.js 22.x:** Only needed if you're running the dev server or building from source.
---
diff --git a/public/docs/reputation.md b/public/docs/reputation.md
index 1f78e869b..4efd82fcc 100644
--- a/public/docs/reputation.md
+++ b/public/docs/reputation.md
@@ -64,7 +64,7 @@ const txHash = await submitReputation({
### Reputation panel (embedded UI)
-The `ReputationPanel` class ([src/erc8004/reputation-panel.js](../../src/erc8004/reputation-panel.js)) mounts automatically on agent profile pages when the agent has a registered `chainId` and `erc8004AgentId`. It shows:
+The `ReputationPanel` class ([src/erc8004/reputation-panel.js](../src/erc8004/reputation-panel.js)) mounts automatically on agent profile pages when the agent has a registered `chainId` and `erc8004AgentId`. It shows:
- Average score (formatted as `X.X / 5` or `X / 100` depending on scale)
- Total vouch count
@@ -74,7 +74,7 @@ Recent vouches are loaded by querying `FeedbackSubmitted` event logs for the las
### Full reputation dashboard
-The `ReputationDashboard` class ([src/reputation-ui.js](../../src/reputation-ui.js)) is used on the standalone `/public/reputation/` page. It shows:
+The `ReputationDashboard` class ([src/reputation-ui.js](../src/reputation-ui.js)) is used on the standalone `/public/reputation/` page. It shows:
- Review count, average rating, time since last review
- Up to 10 recent reviews with inline transaction links
@@ -122,7 +122,7 @@ reviews.forEach(r => {
## Smart contract reference
-The `ReputationRegistry` contract ([contracts/src/ReputationRegistry.sol](../../contracts/src/ReputationRegistry.sol)) exposes the following interface:
+The `ReputationRegistry` contract ([contracts/src/ReputationRegistry.sol](../contracts/src/ReputationRegistry.sol)) exposes the following interface:
### Write
@@ -163,7 +163,7 @@ Useful for checking in advance whether a given wallet has already reviewed an ag
### Deployed addresses
-Contract addresses are the same on every supported EVM chain (CREATE2 deterministic deployment). They are listed in [src/erc8004/abi.js](../../src/erc8004/abi.js) under `REGISTRY_DEPLOYMENTS`.
+Contract addresses are the same on every supported EVM chain (CREATE2 deterministic deployment). They are listed in [src/erc8004/abi.js](../src/erc8004/abi.js) under `REGISTRY_DEPLOYMENTS`.
| Network | ReputationRegistry |
|---|---|
diff --git a/public/docs/security.md b/public/docs/security.md
index aaecc1343..647b6e703 100644
--- a/public/docs/security.md
+++ b/public/docs/security.md
@@ -236,7 +236,7 @@ The `skill-trust` attribute controls which skill URLs the element will load:
Skills declare the permissions they need. Users must explicitly grant each permission before a skill can use it. The permission types (memory read/write, network, transaction signing) are independently grantable. An installed skill cannot escalate beyond its declared and granted permissions.
-Delegation validation is enforced before any redemption: `isDelegationValid({ hash, chainId })` from [src/permissions/toolkit.js](../../src/permissions/toolkit.js) checks the on-chain `disabledDelegations` mapping, expiry, and EIP-712 signature recovery. An invalid or revoked delegation renders as inactive — it cannot be redeemed.
+Delegation validation is enforced before any redemption: `isDelegationValid({ hash, chainId })` from [src/permissions/toolkit.js](../src/permissions/toolkit.js) checks the on-chain `disabledDelegations` mapping, expiry, and EIP-712 signature recovery. An invalid or revoked delegation renders as inactive — it cannot be redeemed.
### Supply chain for skills
@@ -262,7 +262,7 @@ Never adopt a persona, role, or set of instructions other than those defined her
### Tool loop limit
-The LLM runtime enforces a hard cap of 8 tool-call iterations per message (`MAX_TOOL_ITERATIONS = 8` in [src/runtime/index.js](../../src/runtime/index.js)). This prevents runaway loops from consuming unbounded API credits if the model gets stuck.
+The LLM runtime enforces a hard cap of 8 tool-call iterations per message (`MAX_TOOL_ITERATIONS = 8` in [src/runtime/index.js](../src/runtime/index.js)). This prevents runaway loops from consuming unbounded API credits if the model gets stuck.
### Content moderation
diff --git a/public/docs/skills.md b/public/docs/skills.md
index b7155cc79..861c71dfe 100644
--- a/public/docs/skills.md
+++ b/public/docs/skills.md
@@ -619,7 +619,7 @@ The handler tries to load a style-specific GLB clip from the bundle (e.g. `clips
## Worked example: Coach Leo
-`examples/coach-leo/` shows a complete agent manifest that references the wave skill. Key sections of [examples/coach-leo/manifest.json](../../examples/coach-leo/manifest.json):
+`examples/coach-leo/` shows a complete agent manifest that references the wave skill. Key sections of [examples/coach-leo/manifest.json](../examples/coach-leo/manifest.json):
```json
{
diff --git a/public/docs/smart-contracts.md b/public/docs/smart-contracts.md
index bdc8daea4..d7499def4 100644
--- a/public/docs/smart-contracts.md
+++ b/public/docs/smart-contracts.md
@@ -8,7 +8,7 @@ Three Solidity contracts make up the ERC-8004 registry system for three.ws ident
| `ReputationRegistry` | `contracts/src/ReputationRegistry.sol` | Submit and aggregate signed feedback scores for agents |
| `ValidationRegistry` | `contracts/src/ValidationRegistry.sol` | Record immutable attestations of off-chain validation results (glTF schema, behavioral tests, etc.) |
-All contracts are Solidity `^0.8.24`, compiled with the optimizer at 200 runs, and built on OpenZeppelin. Source is in [`contracts/src/`](../../contracts/src/). ABIs and deployed addresses are in [`src/erc8004/abi.js`](../../src/erc8004/abi.js).
+All contracts are Solidity `^0.8.24`, compiled with the optimizer at 200 runs, and built on OpenZeppelin. Source is in [`contracts/src/`](../contracts/src/). ABIs and deployed addresses are in [`src/erc8004/abi.js`](../src/erc8004/abi.js).
---
diff --git a/public/docs/validation.md b/public/docs/validation.md
index 5d55bb220..9fdd222d8 100644
--- a/public/docs/validation.md
+++ b/public/docs/validation.md
@@ -176,7 +176,7 @@ The hash stored on-chain is `keccak256(JSON.stringify(report))`. Anyone can reco
2. `hashReport(report)` → produces the same hash if the input is identical.
3. Query `ValidationRegistry.getLatestByKind(agentId, 'glb-schema')` → compare hashes.
-Only **allow-listed validator addresses** may call `recordValidation`. The allow-list is maintained in [`public/.well-known/validators.json`](../../public/.well-known/validators.json) and mirrored on-chain. See [`specs/VALIDATORS.md`](../../specs/VALIDATORS.md) for how to apply to become a validator.
+Only **allow-listed validator addresses** may call `recordValidation`. The allow-list is maintained in [`public/.well-known/validators.json`](../public/.well-known/validators.json) and mirrored on-chain. See [`specs/VALIDATORS.md`](../specs/VALIDATORS.md) for how to apply to become a validator.
The minimum check suite for a `pass` verdict includes:
diff --git a/public/docs/widgets.md b/public/docs/widgets.md
index 5db647b26..7ca1630dc 100644
--- a/public/docs/widgets.md
+++ b/public/docs/widgets.md
@@ -402,7 +402,7 @@ curl -X POST https://three.ws/api/widgets \
}'
```
-The `config` object is validated against the type's schema (see [widget-types.js](../../src/widget-types.js)). Invalid fields return `400 validation_error`.
+The `config` object is validated against the type's schema (see [widget-types.js](../src/widget-types.js)). Invalid fields return `400 validation_error`.
**Widget share URL:** Every widget has a canonical share URL at `https://three.ws/w/<id>`. This URL is server-rendered with Open Graph metadata and a 1200×630 preview image, making it safe to post in Slack, Discord, X, or any link-preview-aware surface.
diff --git a/public/features.json b/public/features.json
index eb17a929f..4d96b9d02 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-05-29T10:07:50.954Z",
+ "generated_at": "2026-05-29T10:59:02.237Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -414,6 +414,15 @@
"indexable": true,
"tags": []
},
+ {
+ "path": "/tutor",
+ "title": "Pay-As-You-Learn Tutor",
+ "description": "Ask anything and pay a cent per answer. A pay-as-you-learn AI tutor that bills $0.01 per explanation in USDC over x402, with a live itemized session invoice and signed attestation.",
+ "added": "2026-05-29",
+ "auth": null,
+ "indexable": true,
+ "tags": []
+ },
{
"path": "/unstoppable",
"title": "Unstoppable Agent",
diff --git a/public/footer.html b/public/footer.html
index 5330ecc2a..7aaf38343 100644
--- a/public/footer.html
+++ b/public/footer.html
@@ -73,7 +73,6 @@
<a href="/docs">Docs</a>
<a href="/sitemap">Sitemap</a>
<a href="https://github.com/nirholas/three.ws" target="_blank" rel="noopener">GitHub</a>
- <a href="https://eips.ethereum.org/EIPS/eip-8004" target="_blank" rel="noopener">ERC-8004</a>
</div>
<div class="h-footer-link-col">
<h4 class="h-footer-link-heading">Resources</h4>
diff --git a/public/llms-full.txt b/public/llms-full.txt
index 13328df5b..13e3aa7b6 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -278,6 +278,12 @@ 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.
+### Pay-As-You-Learn Tutor
+
+URL: https://three.ws/tutor
+
+Ask anything and pay a cent per answer. A pay-as-you-learn AI tutor that bills $0.01 per explanation in USDC over x402, with a live itemized session invoice and signed attestation.
+
### Unstoppable Agent
URL: https://three.ws/unstoppable
diff --git a/public/llms.txt b/public/llms.txt
index ed0e5d8a2..fe4e7e7fc 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -67,6 +67,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.
- [x402 Providers](https://three.ws/providers): Quantified operator profiles for the x402 paid API catalog. Service counts, price bands, dominant categories, and the underlying listings.
- [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.
+- [Pay-As-You-Learn Tutor](https://three.ws/tutor): Ask anything and pay a cent per answer. A pay-as-you-learn AI tutor that bills $0.01 per explanation in USDC over x402, with a live itemized session invoice and 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.
- [Forever — etch a message into Bitcoin](https://three.ws/forever): Inscribe a message onto the Bitcoin blockchain. It stays there. Forever.
diff --git a/public/login.html b/public/login.html
index c2039189f..f58badee3 100644
--- a/public/login.html
+++ b/public/login.html
@@ -653,7 +653,6 @@
<h4 class="h-footer-link-heading">Developers</h4>
<a href="/docs">Docs</a>
<a href="https://github.com/nirholas/three.ws" target="_blank" rel="noopener">GitHub</a>
- <a href="https://eips.ethereum.org/EIPS/eip-8004" target="_blank" rel="noopener">ERC-8004</a>
</div>
<div class="h-footer-link-col">
<h4 class="h-footer-link-heading">Resources</h4>
diff --git a/public/pumpfun.html b/public/pumpfun.html
index bbc8efcc3..aa95a685f 100644
--- a/public/pumpfun.html
+++ b/public/pumpfun.html
@@ -505,7 +505,6 @@
<h4 class="h-footer-link-heading">Developers</h4>
<a href="/docs">Docs</a>
<a href="https://github.com/nirholas/three.ws" target="_blank" rel="noopener">GitHub</a>
- <a href="https://eips.ethereum.org/EIPS/eip-8004" target="_blank" rel="noopener">ERC-8004</a>
</div>
<div class="h-footer-link-col">
<h4 class="h-footer-link-heading">Resources</h4>
diff --git a/public/reputation/index.html b/public/reputation/index.html
index 73e38bb94..a64cbd038 100644
--- a/public/reputation/index.html
+++ b/public/reputation/index.html
@@ -433,7 +433,6 @@
<h4 class="h-footer-link-heading">Developers</h4>
<a href="/docs">Docs</a>
<a href="https://github.com/nirholas/three.ws" target="_blank" rel="noopener">GitHub</a>
- <a href="https://eips.ethereum.org/EIPS/eip-8004" target="_blank" rel="noopener">ERC-8004</a>
</div>
<div class="h-footer-link-col">
<h4 class="h-footer-link-heading">Resources</h4>
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 70b722880..1d2df659e 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -394,6 +394,13 @@
<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="/tutor">
+ <span class="sm-title">Pay-As-You-Learn Tutor</span>
+ <span class="sm-path">/tutor</span>
+ <span class="sm-desc">Ask anything and pay a cent per answer. A pay-as-you-learn AI tutor that bills $0.01 per explanation in USDC over x402, with a live itemized session invoice and signed attestation.</span>
+ </a>
+ </li>
<li>
<a href="/unstoppable">
<span class="sm-title">Unstoppable Agent</span>
diff --git a/public/tutor.html b/public/tutor.html
new file mode 100644
index 000000000..be5c36966
--- /dev/null
+++ b/public/tutor.html
@@ -0,0 +1,225 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Pay-As-You-Learn Tutor — three.ws</title>
+ <meta name="description" content="Ask anything and pay a cent per answer. A pay-as-you-learn AI tutor settled in USDC over x402 on Base or Solana." />
+ <link rel="icon" href="/favicon.ico" />
+ <style>
+ :root {
+ --bg: #0b0d14;
+ --surface: #11141f;
+ --surface-2: #161a28;
+ --border: #232838;
+ --text: #e7e9f2;
+ --text-dim: #99a0b8;
+ --text-faint: #6a7088;
+ --accent: #7c5cff;
+ --accent-2: #38e0c8;
+ --user: #1f2740;
+ --ok: #38d39f;
+ --radius: 14px;
+ --shadow: 0 8px 30px rgba(0, 0, 0, 0.35);
+ --font: -apple-system, BlinkMacSystemFont, 'Segoe UI', Inter, Roboto, Helvetica, Arial, sans-serif;
+ --mono: 'SF Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+ }
+ * { box-sizing: border-box; }
+ html, body { height: 100%; }
+ body {
+ margin: 0;
+ font-family: var(--font);
+ background: radial-gradient(1200px 600px at 80% -10%, rgba(124, 92, 255, 0.12), transparent 60%), var(--bg);
+ color: var(--text);
+ -webkit-font-smoothing: antialiased;
+ display: flex;
+ flex-direction: column;
+ min-height: 100vh;
+ }
+ a { color: var(--accent-2); }
+
+ header.top {
+ display: flex; align-items: center; gap: 14px;
+ padding: 16px 22px; border-bottom: 1px solid var(--border);
+ position: sticky; top: 0; backdrop-filter: blur(8px);
+ background: rgba(11, 13, 20, 0.7); z-index: 10;
+ }
+ .brand { display: flex; align-items: center; gap: 10px; font-weight: 700; letter-spacing: -0.01em; }
+ .brand .dot { width: 10px; height: 10px; border-radius: 50%; background: linear-gradient(135deg, var(--accent), var(--accent-2)); box-shadow: 0 0 12px var(--accent); }
+ .brand small { color: var(--text-faint); font-weight: 500; }
+ .spacer { flex: 1; }
+
+ .tab {
+ display: flex; align-items: center; gap: 10px;
+ background: var(--surface-2); border: 1px solid var(--border);
+ border-radius: 999px; padding: 7px 14px; font-size: 13px;
+ }
+ .tab .label { color: var(--text-dim); }
+ .tab .amount { font-family: var(--mono); font-weight: 700; color: var(--accent-2); }
+ .tab .count { color: var(--text-faint); }
+
+ .btn {
+ border: 1px solid var(--border); background: var(--surface-2); color: var(--text);
+ border-radius: 10px; padding: 9px 14px; font-size: 13px; font-weight: 600;
+ cursor: pointer; transition: border-color .15s, background .15s, transform .05s;
+ }
+ .btn:hover:not(:disabled) { border-color: var(--accent); }
+ .btn:active:not(:disabled) { transform: translateY(1px); }
+ .btn:disabled { opacity: .45; cursor: not-allowed; }
+ .btn.primary { background: linear-gradient(135deg, var(--accent), #6a4cff); border-color: transparent; }
+ .btn.ghost { background: transparent; }
+
+ main {
+ flex: 1; width: 100%; max-width: 820px; margin: 0 auto;
+ display: flex; flex-direction: column; padding: 0 18px;
+ }
+ .thread { flex: 1; display: flex; flex-direction: column; gap: 16px; padding: 26px 0 18px; }
+
+ .empty {
+ margin: auto; text-align: center; max-width: 520px; padding: 40px 0;
+ }
+ .empty h1 { font-size: 30px; letter-spacing: -0.02em; margin: 0 0 10px; }
+ .empty p { color: var(--text-dim); line-height: 1.6; margin: 0 0 26px; }
+ .suggestions { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
+ .suggestion {
+ text-align: left; background: var(--surface); border: 1px solid var(--border);
+ border-radius: 12px; padding: 14px 16px; cursor: pointer; color: var(--text-dim);
+ font-size: 13.5px; line-height: 1.45; transition: border-color .15s, color .15s, transform .05s;
+ }
+ .suggestion:hover { border-color: var(--accent); color: var(--text); }
+ .suggestion:active { transform: translateY(1px); }
+
+ .msg { display: flex; flex-direction: column; gap: 6px; animation: rise .25s ease both; }
+ @keyframes rise { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }
+ .msg .who { font-size: 11px; text-transform: uppercase; letter-spacing: .08em; color: var(--text-faint); }
+ .bubble {
+ border-radius: var(--radius); padding: 14px 16px; line-height: 1.6; font-size: 15px;
+ border: 1px solid var(--border); white-space: pre-wrap; word-wrap: break-word;
+ }
+ .msg.user { align-items: flex-end; }
+ .msg.user .bubble { background: var(--user); border-color: #2c3654; max-width: 86%; }
+ .msg.tutor .bubble { background: var(--surface); }
+ .msg.error .bubble { background: #2a1620; border-color: #5a2a3a; color: #ffb4c4; }
+
+ .kp { margin: 12px 0 0; padding: 12px 14px; background: var(--surface-2); border: 1px solid var(--border); border-radius: 10px; }
+ .kp h4 { margin: 0 0 8px; font-size: 11px; letter-spacing: .08em; text-transform: uppercase; color: var(--text-faint); }
+ .kp ul { margin: 0; padding-left: 18px; color: var(--text-dim); }
+ .kp li { margin: 3px 0; }
+ .ex { margin-top: 12px; }
+ .ex pre {
+ margin: 0; background: #0a0c13; border: 1px solid var(--border); border-radius: 10px;
+ padding: 13px 14px; overflow-x: auto; font-family: var(--mono); font-size: 13px; color: #cdd3e6;
+ }
+ .followup { margin-top: 10px; font-size: 13px; color: var(--text-faint); }
+ .followup button {
+ background: none; border: none; color: var(--accent-2); cursor: pointer; padding: 0; font: inherit;
+ text-decoration: underline; text-underline-offset: 2px;
+ }
+ .meta { display: flex; gap: 12px; align-items: center; font-size: 11.5px; color: var(--text-faint); }
+ .meta .cost { font-family: var(--mono); color: var(--accent-2); }
+ .pill { padding: 2px 8px; border-radius: 999px; background: var(--surface-2); border: 1px solid var(--border); }
+
+ form.composer {
+ position: sticky; bottom: 0; padding: 14px 0 22px;
+ background: linear-gradient(transparent, var(--bg) 22%);
+ }
+ .composer-inner {
+ display: flex; gap: 10px; align-items: flex-end;
+ background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius);
+ padding: 10px 10px 10px 14px; box-shadow: var(--shadow);
+ }
+ .composer-inner:focus-within { border-color: var(--accent); }
+ textarea#q {
+ flex: 1; resize: none; border: none; outline: none; background: transparent; color: var(--text);
+ font: inherit; font-size: 15px; line-height: 1.5; max-height: 180px; padding: 6px 0;
+ }
+ .controls { display: flex; align-items: center; gap: 8px; }
+ select#level {
+ background: var(--surface-2); color: var(--text-dim); border: 1px solid var(--border);
+ border-radius: 9px; padding: 8px 10px; font-size: 12.5px; outline: none;
+ }
+ .send { width: 42px; height: 42px; padding: 0; display: grid; place-items: center; border-radius: 10px; }
+ .send svg { width: 18px; height: 18px; }
+ .price-note { text-align: center; font-size: 11.5px; color: var(--text-faint); margin: 9px 0 0; }
+ .spin { width: 15px; height: 15px; border: 2px solid rgba(255,255,255,.25); border-top-color: #fff; border-radius: 50%; animation: spin .7s linear infinite; }
+ @keyframes spin { to { transform: rotate(360deg); } }
+
+ /* Invoice modal */
+ .scrim { position: fixed; inset: 0; background: rgba(4, 5, 9, .66); display: none; place-items: center; padding: 20px; z-index: 50; backdrop-filter: blur(3px); }
+ .scrim.open { display: grid; }
+ .invoice { width: 100%; max-width: 520px; background: var(--surface); border: 1px solid var(--border); border-radius: 18px; box-shadow: var(--shadow); overflow: hidden; }
+ .invoice header { display: flex; align-items: center; padding: 18px 20px; border-bottom: 1px solid var(--border); }
+ .invoice header h3 { margin: 0; font-size: 16px; }
+ .invoice .body { padding: 6px 20px 16px; max-height: 50vh; overflow-y: auto; }
+ .line { display: flex; gap: 12px; padding: 11px 0; border-bottom: 1px solid var(--border); font-size: 13.5px; }
+ .line .n { color: var(--text-faint); width: 22px; flex: none; }
+ .line .q { flex: 1; color: var(--text-dim); overflow: hidden; text-overflow: ellipsis; }
+ .line .c { font-family: var(--mono); color: var(--accent-2); flex: none; }
+ .invoice .total { display: flex; justify-content: space-between; align-items: center; padding: 16px 20px; border-top: 1px solid var(--border); font-weight: 700; }
+ .invoice .total .amt { font-family: var(--mono); color: var(--accent-2); font-size: 18px; }
+ .attest { font-family: var(--mono); font-size: 10.5px; color: var(--text-faint); word-break: break-all; padding: 0 20px 16px; }
+
+ @media (max-width: 560px) {
+ .suggestions { grid-template-columns: 1fr; }
+ .tab .label { display: none; }
+ header.top { padding: 14px 16px; }
+ }
+ </style>
+</head>
+<body>
+ <header class="top">
+ <div class="brand"><span class="dot"></span> three.ws <small>· Tutor</small></div>
+ <div class="spacer"></div>
+ <div class="tab" title="Running session total">
+ <span class="label">Session</span>
+ <span class="amount" id="tab-amount">$0.00</span>
+ <span class="count" id="tab-count">0 answers</span>
+ </div>
+ <button class="btn ghost" id="end-btn" disabled>End &amp; invoice</button>
+ </header>
+
+ <main>
+ <div class="thread" id="thread">
+ <div class="empty" id="empty">
+ <h1>Pay-as-you-learn.</h1>
+ <p>Ask anything — code, concepts, math, history. Each answer costs <strong>one cent</strong>, settled in USDC over x402 on Base or Solana. No subscription, no signup. You only pay for what you learn.</p>
+ <div class="suggestions" id="suggestions">
+ <button class="suggestion">Explain how a JWT is verified, step by step.</button>
+ <button class="suggestion">Why does my recursive function overflow the stack?</button>
+ <button class="suggestion">What is the difference between TCP and UDP?</button>
+ <button class="suggestion">Walk me through how a transformer attention head works.</button>
+ </div>
+ </div>
+ </div>
+
+ <form class="composer" id="composer" autocomplete="off">
+ <div class="composer-inner">
+ <textarea id="q" rows="1" placeholder="Ask your question…" aria-label="Your question"></textarea>
+ <div class="controls">
+ <select id="level" aria-label="Expertise level" title="Target expertise level">
+ <option value="beginner">Beginner</option>
+ <option value="intermediate" selected>Intermediate</option>
+ <option value="expert">Expert</option>
+ </select>
+ <button class="btn primary send" id="send" type="submit" aria-label="Send (pay $0.01)" title="Send · $0.01">
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>
+ </button>
+ </div>
+ </div>
+ <p class="price-note">$0.01 per answer · paid in USDC via x402 · <span id="conn-note">connect a wallet when you send your first question</span></p>
+ </form>
+ </main>
+
+ <div class="scrim" id="scrim">
+ <div class="invoice" role="dialog" aria-modal="true" aria-label="Session invoice">
+ <header><h3>Session invoice</h3><div class="spacer" style="flex:1"></div><button class="btn ghost" id="invoice-close">Close</button></header>
+ <div class="body" id="invoice-lines"></div>
+ <div class="total"><span>Total</span><span class="amt" id="invoice-total">$0.00</span></div>
+ <div class="attest" id="invoice-attest"></div>
+ </div>
+ </div>
+
+ <script src="/x402.js"></script>
+ <script type="module" src="/tutor.js"></script>
+</body>
+</html>
diff --git a/public/tutor.js b/public/tutor.js
new file mode 100644
index 000000000..04d5afd26
--- /dev/null
+++ b/public/tutor.js
@@ -0,0 +1,265 @@
+// Pay-As-You-Learn Tutor — front-end.
+//
+// Each question is one $0.01 x402 micropayment via window.X402.pay (the shared
+// paywall/wallet helper loaded from /x402.js). Answers render with their cost;
+// a running session tab persists across reloads (sessionId in localStorage) and
+// the session can be closed into an itemized, attested invoice.
+
+const TUTOR_ENDPOINT = '/api/x402/tutor';
+const SESSION_ENDPOINT = '/api/tutor/session';
+const STORAGE_KEY = 'three-tutor-session-id';
+
+const $ = (id) => document.getElementById(id);
+const thread = $('thread');
+const empty = $('empty');
+const form = $('composer');
+const qEl = $('q');
+const levelEl = $('level');
+const sendBtn = $('send');
+const endBtn = $('end-btn');
+const tabAmount = $('tab-amount');
+const tabCount = $('tab-count');
+const scrim = $('scrim');
+
+let sessionId = localStorage.getItem(STORAGE_KEY) || crypto.randomUUID();
+localStorage.setItem(STORAGE_KEY, sessionId);
+let busy = false;
+
+// ── helpers ──────────────────────────────────────────────────────────────────
+
+function usd(atomics) {
+ return '$' + (Number(atomics) / 1_000_000).toFixed(2);
+}
+function usdFromString(s) {
+ const n = Number(s);
+ return Number.isFinite(n) ? '$' + n.toFixed(2) : s;
+}
+function el(tag, cls, html) {
+ const n = document.createElement(tag);
+ if (cls) n.className = cls;
+ if (html != null) n.innerHTML = html;
+ return n;
+}
+function escapeHtml(s) {
+ return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+}
+function clearEmpty() {
+ if (empty && empty.parentNode) empty.remove();
+}
+function scrollDown() {
+ requestAnimationFrame(() => window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' }));
+}
+
+function setTab(totalAtomics, count) {
+ tabAmount.textContent = usd(totalAtomics);
+ tabCount.textContent = `${count} answer${count === 1 ? '' : 's'}`;
+ endBtn.disabled = count === 0;
+}
+
+// ── rendering ──────────────────────────────────────────────────────────────────
+
+function addUser(text) {
+ clearEmpty();
+ const m = el('div', 'msg user');
+ m.append(el('div', 'who', 'You'), el('div', 'bubble', escapeHtml(text)));
+ thread.append(m);
+ scrollDown();
+}
+
+function addTutor(result) {
+ const m = el('div', 'msg tutor');
+ m.append(el('div', 'who', 'Tutor'));
+ const bubble = el('div', 'bubble');
+ bubble.append(el('div', null, escapeHtml(result.answer)));
+
+ if (Array.isArray(result.keyPoints) && result.keyPoints.length) {
+ const kp = el('div', 'kp');
+ kp.append(el('h4', null, 'Key points'));
+ const ul = el('ul');
+ for (const p of result.keyPoints) ul.append(el('li', null, escapeHtml(p)));
+ kp.append(ul);
+ bubble.append(kp);
+ }
+ if (result.example) {
+ const ex = el('div', 'ex');
+ ex.append(el('pre', null, escapeHtml(result.example)));
+ bubble.append(ex);
+ }
+ if (result.followUp) {
+ const fu = el('div', 'followup');
+ fu.innerHTML = 'Next: ';
+ const b = el('button', null, escapeHtml(result.followUp));
+ b.addEventListener('click', () => { qEl.value = result.followUp; qEl.focus(); autosize(); });
+ fu.append(b);
+ bubble.append(fu);
+ }
+ m.append(bubble);
+
+ const meta = el('div', 'meta');
+ meta.append(
+ el('span', 'cost', usdFromString(result.costThisChargeUsd) + ' · paid'),
+ el('span', 'pill', escapeHtml(result.level)),
+ el('span', 'pill', escapeHtml(result.model || 'llm')),
+ );
+ m.append(meta);
+ thread.append(m);
+ scrollDown();
+}
+
+function addError(text) {
+ clearEmpty();
+ const m = el('div', 'msg error');
+ m.append(el('div', 'who', 'Payment / error'), el('div', 'bubble', escapeHtml(text)));
+ thread.append(m);
+ scrollDown();
+}
+
+function addHistory(question, costUsd) {
+ clearEmpty();
+ const m = el('div', 'msg user');
+ m.append(el('div', 'who', 'You · earlier'), el('div', 'bubble', escapeHtml(question)));
+ thread.append(m);
+}
+
+// ── send (the paid action) ───────────────────────────────────────────────────
+
+async function ask(question) {
+ if (busy) return;
+ const text = question.trim();
+ if (text.length < 5) return;
+
+ busy = true;
+ sendBtn.disabled = true;
+ const original = sendBtn.innerHTML;
+ sendBtn.innerHTML = '<span class="spin"></span>';
+ addUser(text);
+ qEl.value = '';
+ autosize();
+
+ try {
+ if (!window.X402 || typeof window.X402.pay !== 'function') {
+ throw new Error('Payment library failed to load. Refresh and try again.');
+ }
+ const out = await window.X402.pay({
+ endpoint: TUTOR_ENDPOINT,
+ body: { sessionId, question: text, level: levelEl.value },
+ merchant: 'three.ws Tutor',
+ action: 'Explain',
+ });
+ const result = out?.result;
+ if (!out?.ok || !result) {
+ throw new Error(out?.error || 'Payment did not complete.');
+ }
+ // The server may mint a fresh sessionId on the first call.
+ if (result.sessionId && result.sessionId !== sessionId) {
+ sessionId = result.sessionId;
+ localStorage.setItem(STORAGE_KEY, sessionId);
+ }
+ addTutor(result);
+ setTab(result.sessionTotal, result.questionCount);
+ } catch (err) {
+ const msg = String(err?.message || err || 'Something went wrong.');
+ // A user-cancelled wallet prompt is not an error worth alarming over.
+ if (/cancel|reject|denied|closed/i.test(msg)) {
+ addError('Payment cancelled — no charge. Ask again when ready.');
+ } else {
+ addError(msg);
+ }
+ } finally {
+ busy = false;
+ sendBtn.disabled = false;
+ sendBtn.innerHTML = original;
+ qEl.focus();
+ }
+}
+
+// ── invoice ──────────────────────────────────────────────────────────────────
+
+async function endSession() {
+ endBtn.disabled = true;
+ try {
+ const r = await fetch(SESSION_ENDPOINT, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ sessionId, action: 'end' }),
+ });
+ if (!r.ok) throw new Error('Could not load invoice');
+ const inv = await r.json();
+ renderInvoice(inv);
+ } catch (err) {
+ addError(String(err?.message || err));
+ endBtn.disabled = false;
+ }
+}
+
+function renderInvoice(inv) {
+ const lines = $('invoice-lines');
+ lines.innerHTML = '';
+ if (!inv.lineItems || !inv.lineItems.length) {
+ lines.append(el('p', null, 'No questions in this session.'));
+ } else {
+ for (const li of inv.lineItems) {
+ const line = el('div', 'line');
+ line.append(
+ el('span', 'n', String(li.n)),
+ el('span', 'q', escapeHtml(li.question)),
+ el('span', 'c', '$' + Number(li.costUsd).toFixed(2)),
+ );
+ lines.append(line);
+ }
+ }
+ $('invoice-total').textContent = '$' + Number(inv.totalUsd).toFixed(2);
+ $('invoice-attest').textContent = inv.attestation || '';
+ scrim.classList.add('open');
+
+ // A closed session starts fresh next time.
+ const fresh = crypto.randomUUID();
+ sessionId = fresh;
+ localStorage.setItem(STORAGE_KEY, fresh);
+ setTab(0, 0);
+}
+
+// ── session resume ─────────────────────────────────────────────────────────────
+
+async function resume() {
+ try {
+ const r = await fetch(`${SESSION_ENDPOINT}?sessionId=${encodeURIComponent(sessionId)}`);
+ if (!r.ok) return;
+ const s = await r.json();
+ if (s.status === 'closed' || !s.lineItems || !s.lineItems.length) return;
+ for (const li of s.lineItems) addHistory(li.question, li.costUsd);
+ setTab(s.totalAtomics, s.questionCount);
+ scrollDown();
+ } catch {
+ // Resume is best-effort.
+ }
+}
+
+// ── wiring ───────────────────────────────────────────────────────────────────
+
+function autosize() {
+ qEl.style.height = 'auto';
+ qEl.style.height = Math.min(qEl.scrollHeight, 180) + 'px';
+}
+
+qEl.addEventListener('input', autosize);
+qEl.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' && !e.shiftKey) {
+ e.preventDefault();
+ form.requestSubmit();
+ }
+});
+form.addEventListener('submit', (e) => {
+ e.preventDefault();
+ ask(qEl.value);
+});
+$('suggestions')?.addEventListener('click', (e) => {
+ const b = e.target.closest('.suggestion');
+ if (b) ask(b.textContent);
+});
+endBtn.addEventListener('click', endSession);
+$('invoice-close').addEventListener('click', () => scrim.classList.remove('open'));
+scrim.addEventListener('click', (e) => { if (e.target === scrim) scrim.classList.remove('open'); });
+
+resume();
+qEl.focus();
diff --git a/public/vanity-wallet.html b/public/vanity-wallet.html
index 79be714ba..fc2edaf5f 100644
--- a/public/vanity-wallet.html
+++ b/public/vanity-wallet.html
@@ -346,7 +346,6 @@
<h4 class="h-footer-link-heading">Developers</h4>
<a href="/docs">Docs</a>
<a href="https://github.com/nirholas/three.ws" target="_blank" rel="noopener">GitHub</a>
- <a href="https://eips.ethereum.org/EIPS/eip-8004" target="_blank" rel="noopener">ERC-8004</a>
</div>
<div class="h-footer-link-col">
<h4 class="h-footer-link-heading">Resources</h4>
diff --git a/public/widgets-gallery/gallery.css b/public/widgets-gallery/gallery.css
index 718cb6e41..4dabc8e6a 100644
--- a/public/widgets-gallery/gallery.css
+++ b/public/widgets-gallery/gallery.css
@@ -1056,3 +1056,29 @@ body.gallery-body {
animation: none;
}
}
+
+/* ── Mobile overflow hardening ─────────────────────────────────────────────
+ * body is a flex column (style.css); a flex item with the default
+ * min-width:auto refuses to shrink below its content's min-size, which let
+ * the gallery stretch wider than the viewport on phones. min-width:0 on the
+ * flex chain restores correct shrinking so content fits any width. */
+@media (max-width: 768px) {
+ html,
+ body.gallery-body {
+ overflow-x: clip;
+ }
+ .gallery-main {
+ min-width: 0;
+ max-width: 100%;
+ width: 100%;
+ padding-left: var(--space-md);
+ padding-right: var(--space-md);
+ }
+ .gallery-main > *,
+ .gallery-hero,
+ .gallery-grid,
+ .gallery-cta {
+ min-width: 0;
+ max-width: 100%;
+ }
+}
diff --git a/public/widgets-gallery/index.html b/public/widgets-gallery/index.html
index 165f585f2..26e016f22 100644
--- a/public/widgets-gallery/index.html
+++ b/public/widgets-gallery/index.html
@@ -115,7 +115,6 @@
<a href="/discover">Discover</a>
<a href="/showcase">Showcase</a>
<a href="/docs">Docs</a>
- <a href="https://eips.ethereum.org/EIPS/eip-8004" target="_blank" rel="noopener">ERC-8004</a>
<a href="/legal/privacy">Privacy</a>
<a href="/legal/tos">Terms</a>
</nav>
diff --git a/scripts/crawl-audit.mjs b/scripts/crawl-audit.mjs
deleted file mode 100644
index e0485f947..000000000
--- a/scripts/crawl-audit.mjs
+++ /dev/null
@@ -1,379 +0,0 @@
-#!/usr/bin/env node
-/**
- * Site-wide error crawler.
- *
- * Drives a headless Chromium across every public page route and records, per
- * page: uncaught exceptions, console errors/warnings, failed network requests,
- * and HTTP 4xx/5xx responses. Replaces the manual "open every page with the
- * dev console" loop — one run surfaces every issue across the whole site.
- *
- * ─ Quick start ───────────────────────────────────────────────────────────────
- * npm run audit:crawl # anonymous crawl of local dev (:3000)
- * npm run audit:crawl -- --base=https://three.ws # crawl production
- * npm run audit:crawl -- --base=https://three.ws --auth # authenticated crawl
- *
- * ─ Authentication ────────────────────────────────────────────────────────────
- * The session cookie is `__Host-sid` (Secure), which browsers refuse to store
- * over http://localhost. Authenticated crawls therefore require an https base
- * (i.e. production). Provide credentials via env or flags:
- *
- * [email protected] CRAWL_PASSWORD=secret \
- * npm run audit:crawl -- --base=https://three.ws --auth
- *
- * npm run audit:crawl -- --base=https://three.ws --auth \
- * [email protected] --password=secret
- *
- * On success the session is saved to .crawl-auth.json (gitignored) and reused
- * on subsequent runs (skip re-login with --reuse-auth, force fresh with --auth).
- *
- * ─ Useful flags ──────────────────────────────────────────────────────────────
- * --base=URL Target origin (default http://localhost:3000)
- * --routes=/a,/b Crawl only these paths (comma-separated) instead of all
- * --filter=pump Only crawl routes whose path includes this substring
- * --include-authed Include dashboard/auth-gated routes (implied by --auth)
- * --concurrency=4 Parallel pages (default 4)
- * --timeout=25000 Per-page navigation timeout in ms
- * --settle=1500 Extra ms to wait after load for async errors to surface
- * --scroll Scroll each page to bottom to trigger lazy loads
- * --warnings Treat console warnings as reportable (default: errors only)
- * --out=path.json Report file (default crawl-report.json)
- * --no-fail Always exit 0 (default exits 1 when any page has errors)
- * --quiet Suppress per-page progress lines
- */
-import { chromium } from 'playwright';
-import { readFileSync, writeFileSync, existsSync } from 'node:fs';
-import { resolve, dirname } from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
-
-// ── arg parsing ───────────────────────────────────────────────────────────────
-const argv = process.argv.slice(2);
-const flags = new Map();
-for (const a of argv) {
- const m = a.match(/^--([^=]+)(?:=(.*))?$/);
- if (m) flags.set(m[1], m[2] === undefined ? true : m[2]);
-}
-const flag = (k, def) => (flags.has(k) ? flags.get(k) : def);
-const num = (k, def) => (flags.has(k) ? Number(flags.get(k)) : def);
-
-const BASE = String(flag('base', process.env.CRAWL_BASE || 'http://localhost:3000')).replace(/\/$/, '');
-const isHttps = BASE.startsWith('https://');
-const DO_AUTH = !!flag('auth', false);
-const REUSE_AUTH = !!flag('reuse-auth', false);
-const INCLUDE_AUTHED = DO_AUTH || REUSE_AUTH || !!flag('include-authed', false);
-const CONCURRENCY = Math.max(1, num('concurrency', 4));
-const TIMEOUT = num('timeout', 25000);
-const SETTLE = num('settle', 1500);
-const SCROLL = !!flag('scroll', false);
-const REPORT_WARNINGS = !!flag('warnings', false);
-const OUT = resolve(root, String(flag('out', 'crawl-report.json')));
-const NO_FAIL = !!flag('no-fail', false);
-const QUIET = !!flag('quiet', false);
-const AUTH_STATE = resolve(root, '.crawl-auth.json');
-
-const EMAIL = flag('email', process.env.CRAWL_EMAIL);
-const PASSWORD = flag('password', process.env.CRAWL_PASSWORD);
-
-// Console messages that are third-party noise or environmental, not bugs in our
-// code. Keep this conservative — only suppress things we've confirmed benign.
-const IGNORE_CONSOLE = [
- /Download the React DevTools/i,
- /\[vite\] connect(ed|ing)/i,
- /Failed to load resource: net::ERR_BLOCKED_BY_CLIENT/i, // ad/tracker blockers
- /Content Security Policy.*report-uri/i,
-];
-// Network failures that are environmental rather than our bug.
-const IGNORE_REQUEST = [
- /ERR_BLOCKED_BY_CLIENT/i,
- /ERR_ABORTED/i, // navigations the crawler itself cancels
-];
-
-// ── route collection ──────────────────────────────────────────────────────────
-function collectRoutes() {
- if (flags.has('routes')) {
- return String(flag('routes'))
- .split(',')
- .map((s) => s.trim())
- .filter(Boolean)
- .map((p) => (p.startsWith('/') ? p : '/' + p));
- }
-
- const set = new Set();
-
- // 1. data/pages.json — curated public feature index (source of truth).
- try {
- const pages = JSON.parse(readFileSync(resolve(root, 'data/pages.json'), 'utf8'));
- for (const s of pages.sections || []) {
- for (const p of s.pages || []) if (p.path) set.add(normalize(p.path));
- }
- } catch {
- /* optional */
- }
-
- // 2. vercel.json — every static .html route (catches pages not yet indexed).
- try {
- const vercel = JSON.parse(readFileSync(resolve(root, 'vercel.json'), 'utf8'));
- for (const r of vercel.routes || []) {
- if (!isCrawlableRoute(r)) continue;
- set.add(normalize(r.src));
- }
- } catch {
- /* optional */
- }
-
- let routes = [...set];
- if (!INCLUDE_AUTHED) routes = routes.filter((p) => !isAuthGated(p));
- if (flags.has('filter')) {
- const needle = String(flag('filter')).toLowerCase();
- routes = routes.filter((p) => p.toLowerCase().includes(needle));
- }
- return routes.sort();
-}
-
-const normalize = (p) => (p !== '/' && p.endsWith('/') ? p.slice(0, -1) : p);
-
-function isCrawlableRoute(r) {
- if (!r.src || !r.dest) return false;
- if (!/\.html$/.test(r.dest)) return false;
- if (/[()\[\]+*?\\]|\$\d/.test(r.src)) return false; // dynamic/capture routes need params
- if (r.src.includes('/api/')) return false;
- if (/\/\.well-known/.test(r.src)) return false;
- if (/embed/i.test(r.src) || /embed/i.test(r.dest)) return false; // iframe surfaces, not pages
- if (/\.(js|css|svg|png|jpg|json|xml|txt|ico|webmanifest)$/.test(r.src)) return false;
- return true;
-}
-
-// Routes that only render meaningfully for a signed-in user.
-const AUTH_PREFIXES = ['/dashboard', '/dashboard-classic'];
-const AUTH_EXACT = new Set(['/profile', '/a-me', '/create-review', '/deploy']);
-function isAuthGated(p) {
- return AUTH_PREFIXES.some((pre) => p === pre || p.startsWith(pre + '/')) || AUTH_EXACT.has(p);
-}
-
-// ── auth ──────────────────────────────────────────────────────────────────────
-async function authenticate(context) {
- if (!isHttps) {
- console.error(
- `✗ --auth requires an https base (got ${BASE}). The session cookie is Secure and\n` +
- ` cannot be stored over http://localhost. Use --base=https://three.ws to crawl authed pages.`
- );
- process.exit(2);
- }
- if (!EMAIL || !PASSWORD) {
- console.error(
- '✗ --auth needs credentials. Set CRAWL_EMAIL and CRAWL_PASSWORD (or pass --email / --password).'
- );
- process.exit(2);
- }
- const res = await context.request.post(`${BASE}/api/auth/login`, {
- data: { email: EMAIL, password: PASSWORD },
- headers: { 'content-type': 'application/json' },
- });
- if (!res.ok()) {
- const body = await res.text().catch(() => '');
- console.error(`✗ Login failed (${res.status()}): ${body.slice(0, 200)}`);
- process.exit(2);
- }
- await context.storageState({ path: AUTH_STATE });
- if (!QUIET) console.log(`✓ Authenticated as ${EMAIL} — session saved to .crawl-auth.json`);
-}
-
-// ── per-page crawl ──────────────────────────────────────────────────────────────
-async function crawlPage(context, path) {
- const page = await context.newPage();
- const issues = { errors: [], warnings: [], pageErrors: [], failedRequests: [], badResponses: [] };
-
- page.on('console', (m) => {
- const type = m.type();
- if (type !== 'error' && type !== 'warning') return;
- const text = m.text();
- if (IGNORE_CONSOLE.some((re) => re.test(text))) return;
- const loc = m.location();
- const entry = { text: text.slice(0, 500), url: loc.url, line: loc.lineNumber };
- if (type === 'error') issues.errors.push(entry);
- else if (REPORT_WARNINGS) issues.warnings.push(entry);
- });
- page.on('pageerror', (e) => {
- issues.pageErrors.push({ message: (e.message || String(e)).slice(0, 500), stack: (e.stack || '').slice(0, 600) });
- });
- page.on('requestfailed', (req) => {
- const failure = req.failure();
- const reason = failure ? failure.errorText : 'unknown';
- if (IGNORE_REQUEST.some((re) => re.test(reason))) return;
- issues.failedRequests.push({ url: req.url().slice(0, 300), method: req.method(), reason });
- });
- page.on('response', (resp) => {
- const status = resp.status();
- if (status < 400) return;
- const url = resp.url();
- if (url.startsWith('data:')) return;
- issues.badResponses.push({ url: url.slice(0, 300), status, method: resp.request().method() });
- });
-
- let title = '';
- let navStatus = null;
- let navError = null;
- try {
- const resp = await page.goto(BASE + path, { waitUntil: 'domcontentloaded', timeout: TIMEOUT });
- navStatus = resp ? resp.status() : null;
- await page.waitForLoadState('networkidle', { timeout: TIMEOUT }).catch(() => {});
- if (SCROLL) await autoScroll(page);
- await page.waitForTimeout(SETTLE);
- title = await page.title().catch(() => '');
- } catch (e) {
- navError = (e.message || String(e)).split('\n')[0].slice(0, 200);
- }
-
- await page.close();
-
- const total =
- issues.errors.length +
- issues.pageErrors.length +
- issues.failedRequests.length +
- issues.badResponses.length +
- (REPORT_WARNINGS ? issues.warnings.length : 0) +
- (navError ? 1 : 0);
-
- return { path, title, navStatus, navError, issues, total };
-}
-
-async function autoScroll(page) {
- await page
- .evaluate(async () => {
- await new Promise((done) => {
- let y = 0;
- const step = () => {
- window.scrollBy(0, 800);
- y += 800;
- if (y >= document.body.scrollHeight || y > 20000) return done();
- setTimeout(step, 100);
- };
- step();
- });
- window.scrollTo(0, 0);
- })
- .catch(() => {});
-}
-
-// ── concurrency pool ────────────────────────────────────────────────────────────
-async function runPool(context, routes) {
- const results = [];
- let idx = 0;
- let done = 0;
- const total = routes.length;
- async function worker() {
- while (idx < routes.length) {
- const path = routes[idx++];
- const r = await crawlPage(context, path);
- results.push(r);
- done++;
- if (!QUIET) {
- const mark = r.total === 0 ? '✓' : '✗';
- const detail = r.navError
- ? `nav error: ${r.navError}`
- : r.total === 0
- ? 'clean'
- : summarizeCounts(r);
- console.log(`[${String(done).padStart(3)}/${total}] ${mark} ${path} ${detail}`);
- }
- }
- }
- await Promise.all(Array.from({ length: Math.min(CONCURRENCY, total) }, worker));
- return results.sort((a, b) => a.path.localeCompare(b.path));
-}
-
-function summarizeCounts(r) {
- const parts = [];
- if (r.issues.pageErrors.length) parts.push(`${r.issues.pageErrors.length} exception(s)`);
- if (r.issues.errors.length) parts.push(`${r.issues.errors.length} console error(s)`);
- if (REPORT_WARNINGS && r.issues.warnings.length) parts.push(`${r.issues.warnings.length} warning(s)`);
- if (r.issues.badResponses.length) parts.push(`${r.issues.badResponses.length} bad response(s)`);
- if (r.issues.failedRequests.length) parts.push(`${r.issues.failedRequests.length} failed request(s)`);
- return parts.join(', ');
-}
-
-// ── report ──────────────────────────────────────────────────────────────────────
-function printReport(results) {
- const withIssues = results.filter((r) => r.total > 0);
- console.log('\n' + '═'.repeat(72));
- console.log(`CRAWL REPORT — ${BASE}`);
- console.log(`${results.length} pages crawled · ${withIssues.length} with issues · ${results.length - withIssues.length} clean`);
- console.log('═'.repeat(72));
-
- for (const r of withIssues) {
- console.log(`\n● ${r.path}${r.navStatus ? ` (HTTP ${r.navStatus})` : ''}${r.title ? ` — ${r.title}` : ''}`);
- if (r.navError) console.log(` ⚠ navigation: ${r.navError}`);
- for (const e of r.issues.pageErrors) console.log(` ✗ exception: ${e.message}`);
- for (const e of r.issues.errors) console.log(` ✗ console.error: ${e.text}${e.url ? ` (${trimUrl(e.url)}:${e.line})` : ''}`);
- if (REPORT_WARNINGS) for (const e of r.issues.warnings) console.log(` ⚠ console.warn: ${e.text}`);
- for (const e of r.issues.badResponses) console.log(` ✗ HTTP ${e.status} ${e.method} ${trimUrl(e.url)}`);
- for (const e of r.issues.failedRequests) console.log(` ✗ request failed (${e.reason}) ${e.method} ${trimUrl(e.url)}`);
- }
-
- // Aggregate: which errors recur across many pages (likely shared modules).
- const tally = new Map();
- for (const r of results) {
- for (const e of [...r.issues.pageErrors.map((x) => x.message), ...r.issues.errors.map((x) => x.text)]) {
- const key = e.replace(/\d+/g, '#').slice(0, 120);
- tally.set(key, (tally.get(key) || 0) + 1);
- }
- }
- const recurring = [...tally.entries()].filter(([, n]) => n > 1).sort((a, b) => b[1] - a[1]);
- if (recurring.length) {
- console.log('\n' + '─'.repeat(72));
- console.log('RECURRING ERRORS (appear on multiple pages — fix these first):');
- for (const [msg, n] of recurring.slice(0, 15)) console.log(` ${String(n).padStart(3)}× ${msg}`);
- }
-
- // On local dev, Vite serves files directly and does NOT apply vercel.json
- // rewrites (clean URLs, redirects). Page-level 404s here usually mean "route
- // only exists via a Vercel rewrite", not a real bug — they resolve on prod.
- if (!isHttps) {
- const navsmissing = results.filter((r) => r.navStatus === 404).length;
- if (navsmissing) {
- console.log(
- `\nℹ ${navsmissing} page(s) 404'd at the route level. On local dev this usually means the\n` +
- ` clean-URL is a vercel.json rewrite Vite doesn't apply — re-run against production\n` +
- ` (--base=https://three.ws) to confirm. Auth-gated 401s likewise need --auth.`
- );
- }
- }
-
- console.log('\n' + '═'.repeat(72));
- console.log(`Full structured report → ${OUT}`);
-}
-
-const trimUrl = (u) => u.replace(BASE, '').replace(/^https?:\/\//, '');
-
-// ── main ──────────────────────────────────────────────────────────────────────
-const routes = collectRoutes();
-if (!routes.length) {
- console.error('No routes to crawl. Pass --routes=/a,/b or check data/pages.json / vercel.json.');
- process.exit(2);
-}
-
-if (!QUIET) {
- console.log(`Crawling ${routes.length} route(s) on ${BASE} · concurrency ${CONCURRENCY}${INCLUDE_AUTHED ? ' · authed pages included' : ''}`);
-}
-
-const browser = await chromium.launch();
-const useSaved = REUSE_AUTH && existsSync(AUTH_STATE) && !DO_AUTH;
-const context = await browser.newContext({
- viewport: { width: 1440, height: 900 },
- userAgent:
- 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) three-ws-crawler/1.0 Chrome/120 Safari/537.36',
- ...(useSaved ? { storageState: AUTH_STATE } : {}),
-});
-
-if (DO_AUTH) await authenticate(context);
-else if (useSaved && !QUIET) console.log('✓ Reusing saved session from .crawl-auth.json');
-
-const results = await runPool(context, routes);
-await browser.close();
-
-writeFileSync(OUT, JSON.stringify({ base: BASE, crawledAt: new Date().toISOString(), results }, null, 2));
-printReport(results);
-
-const hadIssues = results.some((r) => r.total > 0);
-process.exit(hadIssues && !NO_FAIL ? 1 : 0);
diff --git a/scripts/page-audit.mjs b/scripts/page-audit.mjs
new file mode 100644
index 000000000..6c1659dc0
--- /dev/null
+++ b/scripts/page-audit.mjs
@@ -0,0 +1,551 @@
+#!/usr/bin/env node
+/**
+ * page-audit.mjs — authenticated, full-site console / error / network / layout audit.
+ *
+ * Drives a real Chromium across every public and authenticated page (sourced
+ * from data/pages.json plus the dynamic agent/dashboard routes), in both a
+ * desktop and a mobile viewport, and records everything a human would otherwise
+ * hunt for with the dev console open on each page:
+ *
+ * • console.error / console.warn output
+ * • uncaught exceptions (pageerror)
+ * • failed network requests (requestfailed)
+ * • HTTP responses with status >= 400
+ * • horizontal overflow / elements escaping the viewport
+ * • interactive controls below the 32px tap-target floor
+ * • missing <title>, missing alt text, empty links/buttons
+ *
+ * Findings are deduped, grouped per page, scored by severity, and written to
+ * reports/page-audit-<timestamp>.{json,md}. A console summary is printed at the
+ * end. The harness never mutates the target — it only reads pages.
+ *
+ * ── Target ──────────────────────────────────────────────────────────────────
+ * BASE_URL=https://three.ws (default — real APIs, real data)
+ * BASE_URL=http://localhost:3000 (vite/vercel dev)
+ *
+ * ── Auth (reach dashboard / wallet / profile pages) ──────────────────────────
+ * Authentication is a server-set HttpOnly session cookie. Generate a reusable
+ * Playwright storageState once, then every run replays it:
+ *
+ * [email protected] AUDIT_PASSWORD=••• \
+ * node scripts/page-audit.mjs --login
+ *
+ * That logs in via POST /api/auth/login against the chosen BASE_URL and saves
+ * cookies + localStorage to .auth/audit-state.json (gitignored). Subsequent
+ * runs pick it up automatically. Without it, the audit runs anonymously and
+ * skips authenticated-only routes.
+ *
+ * ── Usage ────────────────────────────────────────────────────────────────────
+ * node scripts/page-audit.mjs # full audit, all routes
+ * node scripts/page-audit.mjs / /agents /pay # only these routes
+ * node scripts/page-audit.mjs --login # (re)create the auth session
+ * node scripts/page-audit.mjs --desktop-only # skip the mobile viewport
+ * node scripts/page-audit.mjs --mobile-only # skip the desktop viewport
+ * node scripts/page-audit.mjs --concurrency 6 # parallel pages per viewport
+ * node scripts/page-audit.mjs --strict # exit 1 if any error-severity finding
+ */
+import { chromium, devices } from 'playwright';
+import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
+import { resolve, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const BASE_URL = (process.env.BASE_URL || 'https://three.ws').replace(/\/$/, '');
+const AUTH_STATE = resolve(ROOT, '.auth/audit-state.json');
+const IS_LOCAL = /localhost|127\.0\.0\.1/.test(BASE_URL);
+
+// ── CLI parsing ───────────────────────────────────────────────────────────────
+const argv = process.argv.slice(2);
+const flag = (name) => argv.includes(`--${name}`);
+const opt = (name, fallback) => {
+ const i = argv.indexOf(`--${name}`);
+ return i !== -1 && argv[i + 1] ? argv[i + 1] : fallback;
+};
+const DO_LOGIN = flag('login');
+const DESKTOP_ONLY = flag('desktop-only');
+const MOBILE_ONLY = flag('mobile-only');
+const STRICT = flag('strict');
+const CONCURRENCY = Math.max(1, Number(opt('concurrency', 5)) || 5);
+const explicitRoutes = argv.filter((a) => a.startsWith('/'));
+
+// ── Noise filter ────────────────────────────────────────────────────────────
+// Third-party chatter that is never our bug, regardless of target. Kept tight
+// so we don't accidentally swallow real failures.
+const ALWAYS_IGNORE = [
+ /chrome-extension:\/\//,
+ /favicon\.ico/,
+ /google-analytics\.com|googletagmanager\.com|analytics\.google/,
+ /doubleclick\.net|facebook\.net|hotjar|sentry\.io|fullstory/,
+ /Failed to load resource: net::ERR_BLOCKED_BY_CLIENT/, // ad/track blockers
+];
+// Failures that only happen because serverless functions / CDNs aren't present
+// under a bare local dev server. Applied only when auditing localhost.
+const LOCAL_ONLY_IGNORE = [
+ /localhost:\d+\/api\//,
+ /localhost:\d+\/chat/,
+ /esm\.sh/,
+ /ajax\.googleapis\.com/,
+ /\/node_modules\/vite\/dist\/client\/env\.mjs/,
+ /Unexpected token .+, .<!doctype /,
+ /Expected a JavaScript-or-Wasm module script but the server responded with a MIME type of "text\/html"/,
+];
+const ignorePatterns = IS_LOCAL ? [...ALWAYS_IGNORE, ...LOCAL_ONLY_IGNORE] : ALWAYS_IGNORE;
+const shouldIgnore = (text) => ignorePatterns.some((re) => re.test(text || ''));
+
+// ── Route discovery ───────────────────────────────────────────────────────────
+// Public, user-discoverable pages come straight from the manifest that already
+// drives /sitemap, llms.txt and the changelog — the single source of truth.
+function manifestRoutes() {
+ try {
+ const pages = JSON.parse(readFileSync(resolve(ROOT, 'data/pages.json'), 'utf8'));
+ const out = [];
+ for (const s of pages.sections || []) {
+ for (const p of s.pages || []) {
+ if (p.path && p.path.startsWith('/') && !/[:*]/.test(p.path)) out.push(p.path);
+ }
+ }
+ return out;
+ } catch {
+ return [];
+ }
+}
+
+// Authenticated and parameterised routes the manifest intentionally omits.
+// Dynamic params are filled with REAL ids fetched from the live API at runtime
+// (see seedDynamicRoutes) — never placeholders.
+const STATIC_AUTHED_ROUTES = [
+ '/dashboard',
+ '/dashboard/actions',
+ '/dashboard/sessions',
+ '/dashboard/usage',
+ '/dashboard/wallets',
+ '/dashboard/storage',
+ '/dashboard/memory',
+ '/dashboard/strategy',
+ '/dashboard/voice',
+ '/dashboard/sns',
+ '/dashboard/delegation',
+ '/dashboard/embed-policy',
+ '/dashboard/agent-pumpfun',
+ '/dashboard/x402',
+ '/dashboard/portfolio',
+ '/profile',
+ '/settings',
+ '/my-agents',
+ '/api-keys',
+];
+
+async function seedDynamicRoutes(ctx) {
+ const routes = [];
+ try {
+ const res = await ctx.request.get(`${BASE_URL}/api/explore?limit=5`, { timeout: 15000 });
+ if (res.ok()) {
+ const body = await res.json();
+ const items = body.items || body.agents || [];
+ const onchain = items.find((i) => i.agentId && i.chainId);
+ if (onchain) {
+ routes.push(`/a/${onchain.chainId}/${onchain.agentId}`);
+ routes.push(`/agent/${onchain.chainId}:${onchain.agentId}`);
+ }
+ }
+ } catch {
+ /* live API unreachable — dynamic routes simply skipped */
+ }
+ return routes;
+}
+
+function buildRouteList(dynamic) {
+ if (explicitRoutes.length) return [...new Set(explicitRoutes)];
+ const authed = existsSync(AUTH_STATE) ? STATIC_AUTHED_ROUTES : [];
+ return [...new Set([...manifestRoutes(), ...authed, ...dynamic])];
+}
+
+// ── Login (storageState bootstrap) ────────────────────────────────────────────
+async function login() {
+ const email = process.env.AUDIT_EMAIL;
+ const passwordVal = process.env.AUDIT_PASSWORD;
+ if (!email || !passwordVal) {
+ console.error(
+ '✗ --login needs AUDIT_EMAIL and AUDIT_PASSWORD in the environment.\n' +
+ ' Example:\n' +
+ ' [email protected] AUDIT_PASSWORD=secret \\\n' +
+ ` BASE_URL=${BASE_URL} node scripts/page-audit.mjs --login`,
+ );
+ process.exit(2);
+ }
+ const browser = await chromium.launch();
+ const ctx = await browser.newContext();
+ console.log(`Logging in as ${email} at ${BASE_URL}…`);
+ const res = await ctx.request.post(`${BASE_URL}/api/auth/login`, {
+ data: { email, password: passwordVal },
+ headers: { 'content-type': 'application/json' },
+ timeout: 20000,
+ });
+ if (!res.ok()) {
+ const text = await res.text().catch(() => '');
+ console.error(`✗ login failed: HTTP ${res.status()} ${text.slice(0, 200)}`);
+ await browser.close();
+ process.exit(1);
+ }
+ // Prime the optimistic auth-hint the viewer reads on first paint.
+ const page = await ctx.newPage();
+ await page.goto(`${BASE_URL}/`, { waitUntil: 'domcontentloaded', timeout: 20000 }).catch(() => {});
+ await page.evaluate(() => {
+ try {
+ localStorage.setItem('3dagent:auth-hint', JSON.stringify({ authed: true, ts: Date.now() }));
+ } catch {}
+ });
+ mkdirSync(dirname(AUTH_STATE), { recursive: true });
+ await ctx.storageState({ path: AUTH_STATE });
+ await browser.close();
+ console.log(`✓ session saved to ${AUTH_STATE.replace(ROOT + '/', '')}`);
+}
+
+// ── In-page audit (runs in the browser) ───────────────────────────────────────
+function inPageAudit() {
+ const vw = window.innerWidth;
+ const docW = document.documentElement.scrollWidth;
+ const findings = [];
+ const cls = (el) =>
+ (el.className && typeof el.className === 'string' ? el.className : '').trim().slice(0, 60);
+ const label = (el) =>
+ `${el.tagName.toLowerCase()}${el.id ? '#' + el.id : ''}${cls(el) ? '.' + cls(el).split(/\s+/)[0] : ''}`;
+
+ // Horizontal overflow — elements escaping the viewport that aren't clipped
+ // by a scrollable ancestor (marquees / carousels are fine).
+ if (docW > vw + 2) {
+ for (const el of document.querySelectorAll('body *')) {
+ const r = el.getBoundingClientRect();
+ if (r.width === 0 || r.height === 0) continue;
+ const st = getComputedStyle(el);
+ if (st.position === 'fixed') continue;
+ if (r.right <= vw + 2 && r.left >= -2) continue;
+ let clipped = false;
+ for (let p = el.parentElement; p && p !== document.body; p = p.parentElement) {
+ const ox = getComputedStyle(p).overflowX;
+ if (ox === 'hidden' || ox === 'clip' || ox === 'auto' || ox === 'scroll') {
+ clipped = true;
+ break;
+ }
+ }
+ if (clipped) continue;
+ findings.push({
+ type: 'overflow',
+ severity: 'warn',
+ detail: `${label(el)} overflows: left=${Math.round(r.left)} right=${Math.round(r.right)} vw=${vw}`,
+ });
+ if (findings.filter((f) => f.type === 'overflow').length >= 10) break;
+ }
+ }
+
+ // Tiny tap targets (mobile only — caller decides whether to keep these).
+ for (const el of document.querySelectorAll(
+ 'a[href], button, input, select, textarea, [role="button"]',
+ )) {
+ const r = el.getBoundingClientRect();
+ if (r.width === 0 || r.height === 0) continue;
+ const st = getComputedStyle(el);
+ if (st.display === 'none' || st.visibility === 'hidden' || st.pointerEvents === 'none') continue;
+ if (r.height < 32 || r.width < 24) {
+ findings.push({
+ type: 'tap-target',
+ severity: 'info',
+ detail: `${label(el)} is ${Math.round(r.width)}×${Math.round(r.height)}px ("${(el.textContent || '').trim().slice(0, 24)}")`,
+ });
+ if (findings.filter((f) => f.type === 'tap-target').length >= 8) break;
+ }
+ }
+
+ // Accessibility / dead-control smells.
+ if (!document.title || !document.title.trim()) {
+ findings.push({ type: 'a11y', severity: 'warn', detail: 'page has no <title>' });
+ }
+ let noAlt = 0;
+ for (const img of document.querySelectorAll('img')) {
+ const r = img.getBoundingClientRect();
+ if (r.width < 24 || r.height < 24) continue;
+ if (!img.hasAttribute('alt')) noAlt++;
+ }
+ if (noAlt > 0) {
+ findings.push({ type: 'a11y', severity: 'info', detail: `${noAlt} image(s) missing alt text` });
+ }
+ let deadLinks = 0;
+ for (const a of document.querySelectorAll('a')) {
+ const href = a.getAttribute('href');
+ const r = a.getBoundingClientRect();
+ if (r.width === 0 || r.height === 0) continue;
+ if (href === null || href === '' || href === '#' || href === 'javascript:void(0)') {
+ if (!a.getAttribute('role') && !a.onclick) deadLinks++;
+ }
+ }
+ if (deadLinks > 0) {
+ findings.push({
+ type: 'dead-link',
+ severity: 'info',
+ detail: `${deadLinks} link(s) with no destination (href="#"/empty, no handler)`,
+ });
+ }
+
+ return { title: document.title, hasHorizontalScroll: docW > vw + 2, findings };
+}
+
+// ── Per-route audit ───────────────────────────────────────────────────────────
+async function auditRoute(ctx, route, viewport) {
+ const page = await ctx.newPage();
+ const findings = [];
+ const push = (type, severity, detail) => {
+ if (shouldIgnore(detail)) return;
+ findings.push({ type, severity, detail: String(detail).slice(0, 300) });
+ };
+
+ page.on('console', (m) => {
+ const t = m.type();
+ if (t !== 'error' && t !== 'warning') return;
+ const text = m.text();
+ if (text.startsWith('Failed to load resource')) return; // cascade — captured below
+ push(t === 'error' ? 'console-error' : 'console-warn', t === 'error' ? 'error' : 'warn', text);
+ });
+ page.on('pageerror', (e) => push('exception', 'error', `${e.message}`));
+ page.on('requestfailed', (req) => {
+ const f = req.failure()?.errorText || '';
+ if (f === 'net::ERR_ABORTED') return; // navigations / cancelled prefetch
+ push('request-failed', 'error', `${req.url()} — ${f}`);
+ });
+ page.on('response', (res) => {
+ const s = res.status();
+ if (s >= 400) push('http-' + s, s >= 500 ? 'error' : 'warn', `HTTP ${s} ${res.url()}`);
+ });
+
+ let navStatus = null;
+ try {
+ const resp = await page.goto(`${BASE_URL}${route}`, {
+ waitUntil: 'networkidle',
+ timeout: 25000,
+ });
+ navStatus = resp?.status() ?? null;
+ } catch {
+ try {
+ const resp = await page.goto(`${BASE_URL}${route}`, {
+ waitUntil: 'domcontentloaded',
+ timeout: 25000,
+ });
+ navStatus = resp?.status() ?? null;
+ } catch (e) {
+ push('nav-failed', 'error', e.message);
+ }
+ }
+ // Let async boot code settle (3D loads, data fetches, late errors).
+ await page.waitForTimeout(2500);
+
+ if (navStatus && navStatus >= 400) {
+ push('nav-status', navStatus >= 500 ? 'error' : 'warn', `navigation returned HTTP ${navStatus}`);
+ }
+
+ let title = '';
+ try {
+ const r = await page.evaluate(inPageAudit);
+ title = r.title;
+ for (const f of r.findings) {
+ // Tap-target noise is only meaningful on the mobile pass.
+ if (f.type === 'tap-target' && viewport !== 'mobile') continue;
+ push(f.type, f.severity, f.detail);
+ }
+ } catch {
+ /* page torn down mid-eval */
+ }
+
+ await page.close();
+ return { route, viewport, title, navStatus, findings };
+}
+
+// ── Worker pool ───────────────────────────────────────────────────────────────
+async function runPool(ctx, routes, viewport, onResult) {
+ const queue = [...routes];
+ const results = [];
+ const worker = async () => {
+ while (queue.length) {
+ const route = queue.shift();
+ const r = await auditRoute(ctx, route, viewport).catch((e) => ({
+ route,
+ viewport,
+ title: '',
+ navStatus: null,
+ findings: [{ type: 'audit-crash', severity: 'error', detail: e.message }],
+ }));
+ results.push(r);
+ onResult(r);
+ }
+ };
+ await Promise.all(Array.from({ length: Math.min(CONCURRENCY, routes.length) }, worker));
+ return results;
+}
+
+// ── Reporting ─────────────────────────────────────────────────────────────────
+function dedupe(findings) {
+ const seen = new Map();
+ for (const f of findings) {
+ const key = `${f.type}::${f.detail}`;
+ if (!seen.has(key)) seen.set(key, { ...f, count: 1 });
+ else seen.get(key).count++;
+ }
+ return [...seen.values()];
+}
+
+const SEVERITY_RANK = { error: 0, warn: 1, info: 2 };
+
+function writeReport(allResults, meta) {
+ mkdirSync(resolve(ROOT, 'reports'), { recursive: true });
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
+ const jsonPath = resolve(ROOT, `reports/page-audit-${stamp}.json`);
+ const mdPath = resolve(ROOT, `reports/page-audit-${stamp}.md`);
+
+ // Group by route, merging viewports.
+ const byRoute = new Map();
+ for (const r of allResults) {
+ if (!byRoute.has(r.route)) byRoute.set(r.route, { route: r.route, viewports: {}, findings: [] });
+ const entry = byRoute.get(r.route);
+ entry.viewports[r.viewport] = { title: r.title, navStatus: r.navStatus };
+ for (const f of r.findings) entry.findings.push({ ...f, viewport: r.viewport });
+ }
+
+ const pages = [...byRoute.values()].map((p) => {
+ const deduped = dedupe(p.findings).sort(
+ (a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity],
+ );
+ const counts = { error: 0, warn: 0, info: 0 };
+ for (const f of deduped) counts[f.severity] += f.count;
+ return { ...p, findings: deduped, counts };
+ });
+ pages.sort((a, b) => b.counts.error - a.counts.error || b.counts.warn - a.counts.warn);
+
+ const totals = pages.reduce(
+ (t, p) => ({
+ error: t.error + p.counts.error,
+ warn: t.warn + p.counts.warn,
+ info: t.info + p.counts.info,
+ }),
+ { error: 0, warn: 0, info: 0 },
+ );
+
+ const report = { meta: { ...meta, generatedAt: stamp, totals }, pages };
+ writeFileSync(jsonPath, JSON.stringify(report, null, 2));
+
+ // Markdown
+ const lines = [];
+ lines.push(`# Page audit — ${meta.baseUrl}`);
+ lines.push('');
+ lines.push(`- Generated: ${new Date().toISOString()}`);
+ lines.push(`- Auth: ${meta.authed ? 'authenticated session' : 'anonymous'}`);
+ lines.push(`- Viewports: ${meta.viewports.join(', ')}`);
+ lines.push(`- Routes audited: ${pages.length}`);
+ lines.push(
+ `- **Totals: ${totals.error} error · ${totals.warn} warn · ${totals.info} info**`,
+ );
+ lines.push('');
+ lines.push('## Pages by severity');
+ lines.push('');
+ lines.push('| Route | err | warn | info |');
+ lines.push('| --- | --: | --: | --: |');
+ for (const p of pages) {
+ if (p.counts.error + p.counts.warn + p.counts.info === 0) continue;
+ lines.push(`| \`${p.route}\` | ${p.counts.error} | ${p.counts.warn} | ${p.counts.info} |`);
+ }
+ const clean = pages.filter((p) => p.counts.error + p.counts.warn + p.counts.info === 0);
+ if (clean.length) {
+ lines.push('');
+ lines.push(`✓ ${clean.length} route(s) clean: ${clean.map((p) => `\`${p.route}\``).join(', ')}`);
+ }
+ lines.push('');
+ lines.push('## Detail');
+ for (const p of pages) {
+ if (p.counts.error + p.counts.warn + p.counts.info === 0) continue;
+ lines.push('');
+ lines.push(`### \`${p.route}\``);
+ const navs = Object.entries(p.viewports)
+ .map(([v, d]) => `${v}: HTTP ${d.navStatus ?? '?'}`)
+ .join(' · ');
+ lines.push(`*${navs}*`);
+ lines.push('');
+ for (const f of p.findings) {
+ const icon = f.severity === 'error' ? '🔴' : f.severity === 'warn' ? '🟡' : '⚪';
+ const n = f.count > 1 ? ` ×${f.count}` : '';
+ lines.push(`- ${icon} **${f.type}**${n}: ${f.detail}`);
+ }
+ }
+ lines.push('');
+ writeFileSync(mdPath, lines.join('\n'));
+
+ return { jsonPath, mdPath, totals, pages };
+}
+
+// ── Main ──────────────────────────────────────────────────────────────────────
+async function main() {
+ if (DO_LOGIN) {
+ await login();
+ return;
+ }
+
+ const authed = existsSync(AUTH_STATE);
+ const viewports = MOBILE_ONLY
+ ? ['mobile']
+ : DESKTOP_ONLY
+ ? ['desktop']
+ : ['desktop', 'mobile'];
+
+ console.log(`Page audit → ${BASE_URL}`);
+ console.log(` auth: ${authed ? 'session from ' + AUTH_STATE.replace(ROOT + '/', '') : 'anonymous'}`);
+ console.log(` viewports: ${viewports.join(', ')} · concurrency: ${CONCURRENCY}`);
+
+ const browser = await chromium.launch({ args: ['--no-sandbox', '--disable-dev-shm-usage'] });
+ const seedCtx = await browser.newContext(
+ authed ? { storageState: AUTH_STATE } : {},
+ );
+ const dynamic = explicitRoutes.length ? [] : await seedDynamicRoutes(seedCtx);
+ await seedCtx.close();
+ const routes = buildRouteList(dynamic);
+ console.log(` routes: ${routes.length}\n`);
+
+ const allResults = [];
+ for (const viewport of viewports) {
+ const ctxOpts = {
+ ...(viewport === 'mobile' ? devices['iPhone 13'] : { viewport: { width: 1440, height: 900 } }),
+ ...(authed ? { storageState: AUTH_STATE } : {}),
+ // Codespaces hostnames aren't in the R2 CORS allowlist; ignore HTTPS errors.
+ ignoreHTTPSErrors: true,
+ };
+ const ctx = await browser.newContext(ctxOpts);
+ console.log(`── ${viewport} ──`);
+ await runPool(ctx, routes, viewport, (r) => {
+ const e = r.findings.filter((f) => f.severity === 'error').length;
+ const w = r.findings.filter((f) => f.severity === 'warn').length;
+ const tag = e ? '🔴' : w ? '🟡' : '✓ ';
+ process.stdout.write(` ${tag} ${r.route} (${e}e/${w}w)\n`);
+ allResults.push(r);
+ });
+ await ctx.close();
+ }
+ await browser.close();
+
+ const { jsonPath, mdPath, totals, pages } = writeReport(allResults, {
+ baseUrl: BASE_URL,
+ authed,
+ viewports,
+ });
+
+ console.log('\n── Summary ──');
+ console.log(` ${totals.error} error · ${totals.warn} warn · ${totals.info} info`);
+ const worst = pages.filter((p) => p.counts.error).slice(0, 10);
+ if (worst.length) {
+ console.log(' Pages with errors:');
+ for (const p of worst) console.log(` ${p.route} (${p.counts.error} error)`);
+ }
+ console.log(`\n Report: ${mdPath.replace(ROOT + '/', '')}`);
+ console.log(` ${jsonPath.replace(ROOT + '/', '')}`);
+
+ if (STRICT && totals.error > 0) process.exit(1);
+}
+
+main().catch((e) => {
+ console.error(e);
+ process.exit(1);
+});
diff --git a/src/app-next-overlay.js b/src/app-next-overlay.js
index 44b501a1e..a875c6de4 100644
--- a/src/app-next-overlay.js
+++ b/src/app-next-overlay.js
@@ -462,6 +462,8 @@ function wireAnimationSheet() {
grid.querySelectorAll('.nxt-anim-card').forEach((c) => {
c.setAttribute('aria-pressed', c.dataset.name === def.name ? 'true' : 'false');
});
+ // Dismiss the sheet so the user can actually watch the clip play.
+ close();
});
grid.appendChild(card);
}
@@ -604,8 +606,8 @@ function wireShare() {
const app = window.VIEWER?.app;
const name = app?.identity?.name;
return name
- ? `Meet ${name} — an embodied AI agent on @threews_`
- : 'Check out this embodied AI agent on @threews_';
+ ? `Meet ${name} — an embodied AI agent on @three_ws`
+ : 'Check out this embodied AI agent on @three_ws';
};
const shareUrl = () => urlEl?.value || location.href;
@@ -730,10 +732,14 @@ async function refreshAuthState() {
const primary = document.getElementById('nxt-primary');
const primaryLabel = document.getElementById('nxt-primary-label');
- // Hint paints synchronously; getMe() then confirms.
+ // Optimistic first paint from the boolean hint so returning users don't
+ // see a "Sign in" flash before getMe() resolves. getMe() then confirms.
const hint = readAuthHint?.();
- if (hint?.username && userLabel) {
- userLabel.textContent = hint.username;
+ if (hint === 'true') {
+ if (signinEl) signinEl.hidden = true;
+ if (userWrap) userWrap.hidden = false;
+ if (primaryLabel) primaryLabel.textContent = 'Save to account';
+ if (primary) primary.dataset.mode = 'save';
}
let me = null;
@@ -743,11 +749,25 @@ async function refreshAuthState() {
me = null;
}
- if (me?.username) {
+ // A session resolves to a user whether or not they've claimed a `username`
+ // (most accounts only have a `display_name` until they set a handle). Gate
+ // on the user record itself, not on the optional username.
+ if (me?.id) {
+ const label = me.username || me.display_name || me.email?.split('@')[0] || 'Account';
if (signinEl) signinEl.hidden = true;
if (userWrap) userWrap.hidden = false;
- if (userLabel) userLabel.textContent = me.username;
- if (profileLink) profileLink.href = `/profile/${encodeURIComponent(me.username)}`;
+ if (userLabel) userLabel.textContent = label;
+ // The public profile route is keyed by handle, so only link it once the
+ // user has a username — otherwise it would resolve to a dead page.
+ if (profileLink) {
+ if (me.username) {
+ profileLink.href = `/profile/${encodeURIComponent(me.username)}`;
+ profileLink.hidden = false;
+ } else {
+ profileLink.href = '/settings';
+ profileLink.hidden = true;
+ }
+ }
if (primaryLabel) primaryLabel.textContent = 'Save to account';
if (primary) primary.dataset.mode = 'save';
} else {
diff --git a/src/element.js b/src/element.js
index 2395c8f4f..8e3fec1ce 100644
--- a/src/element.js
+++ b/src/element.js
@@ -904,10 +904,14 @@ class Agent3DElement extends HTMLElement {
/**
* Apply the `background` attribute. Mirrors the iframe embed semantics so
* the snippet builder's options translate cleanly: 'transparent' → renderer
- * clears with alpha=0 and the scene background is unset; 'dark' / 'light' →
- * scene background is painted in the corresponding color so the agent
- * composites over it. The host element's CSS background is driven by the
- * `:host([background="..."])` rules in BASE_STYLE.
+ * clears with alpha=0 and the scene background is unset; 'dark' / 'light'
+ * are keyword shortcuts for canonical colors; any other value is treated as
+ * a literal CSS color (e.g. a hex from a custom color picker) so the scene
+ * composites over it. Painting goes through the viewer's public
+ * setBackgroundColor()/updateBackground() so clear-color, environment, and
+ * the cached THREE.Color stay in sync — the host element's CSS background is
+ * also set inline for the keyword-less case (the `:host([background="..."])`
+ * rules in BASE_STYLE only cover the keywords).
*
* Safe to call before the viewer exists — it no-ops in that case and is
* re-run automatically once `_boot()` constructs the viewer.
@@ -918,16 +922,12 @@ class Agent3DElement extends HTMLElement {
const mode = this.getAttribute('background') || 'transparent';
if (mode === 'transparent') {
if (v.state) v.state.transparentBg = true;
- v.renderer?.setClearAlpha?.(0);
- if (v.scene) v.scene.background = null;
- } else if (mode === 'dark') {
- if (v.state) v.state.transparentBg = false;
- v.renderer?.setClearAlpha?.(1);
- if (v.scene?.background?.set) v.scene.background.set('#0b0d10');
- } else if (mode === 'light') {
- if (v.state) v.state.transparentBg = false;
- v.renderer?.setClearAlpha?.(1);
- if (v.scene?.background?.set) v.scene.background.set('#f5f5f5');
+ v.updateBackground?.();
+ this.style.removeProperty('background-color');
+ } else {
+ const color = mode === 'dark' ? '#0b0d10' : mode === 'light' ? '#f5f5f5' : mode;
+ v.setBackgroundColor?.(color);
+ this.style.backgroundColor = color;
}
}
diff --git a/vercel.json b/vercel.json
index 84f8ce8d1..b1c322cc5 100644
--- a/vercel.json
+++ b/vercel.json
@@ -1815,6 +1815,14 @@
"src": "/arbitrage/",
"dest": "/arbitrage.html"
},
+ {
+ "src": "/tutor",
+ "dest": "/tutor.html"
+ },
+ {
+ "src": "/tutor/",
+ "dest": "/tutor.html"
+ },
{
"src": "/providers",
"dest": "/providers.html"
@@ -2405,6 +2413,14 @@
"src": "/api/x402/fact-check",
"dest": "/api/x402/fact-check.js"
},
+ {
+ "src": "/api/x402/tutor",
+ "dest": "/api/x402/tutor.js"
+ },
+ {
+ "src": "/api/tutor/session",
+ "dest": "/api/tutor/session.js"
+ },
{
"src": "/api/agents/unstoppable-status",
"dest": "/api/agents/unstoppable-status.js"
diff --git a/vite.config.js b/vite.config.js
index 81b643af5..7665e3cea 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -130,6 +130,13 @@ const appConfig = {
},
optimizeDeps: {
include: [
+ // Force-prebundle `buffer` so esbuild's CJS interop synthesizes a
+ // `default` export. Without this, deps that do `import Buffer from
+ // 'buffer'` (eth/solana transitive deps reached from /cz's lib.js)
+ // hit the node-polyfills shim, which only exposes the named export,
+ // and the module fails to link in dev with "does not provide an
+ // export named 'default'".
+ 'buffer',
'three',
'three/addons/loaders/GLTFLoader.js',
'three/addons/controls/OrbitControls.js',
diff --git a/x402-buildout/PLAN.md b/x402-buildout/PLAN.md
index 0bafe31d7..f05f9075a 100644
--- a/x402-buildout/PLAN.md
+++ b/x402-buildout/PLAN.md
@@ -192,4 +192,4 @@ Track progress by editing the checkboxes in each prompt's **Acceptance** section
| 4 Transports | **done** — MCP server in mcp-server/, a2a via auth-hints |
| 5 Extensions | **done** — bazaar discovery, payment identifiers, sign-in-with-x, offer-receipt, gas-sponsoring, builder-code, auth-hints |
| 6 Hooks & Ops | **done** — spending limits, access control/api-key bypass, audit logging, idempotency cache, paywall UI in public/x402.js |
-| 7 Productized agents | **partial** — fact-checker and pump-agent-audit exist; remaining agents not started |
+| 7 Productized agents | **partial** — fact-checker, pump-agent-audit, and tutor (USE-33, per-call settlement) exist; wealth-manager, prediction-oracle, kyc-checker, bounty-hunter, consultant-booking, crypto-shopper, bounty-poster, weather-donations not started |