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.

refactor: route agent + livepeer inference through shared LLM policy

nirholasf040d2978b7a
diff --git a/.gitignore b/.gitignore
index 55c8f888d..1c69342f0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -82,6 +82,10 @@ 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
diff --git a/agents/unstoppable/src/inference.js b/agents/unstoppable/src/inference.js
index 8b77136b9..36edb7e1b 100644
--- a/agents/unstoppable/src/inference.js
+++ b/agents/unstoppable/src/inference.js
@@ -1,9 +1,12 @@
-// Inference — calls Claude Haiku to "think" about what to do next.
+// Inference — asks the LLM to "think" about what to do next.
//
// The agent reasons over its current financial state and recent activity,
// then returns a JSON plan with thoughts and a list of actions to execute.
+// Runs on the platform's funded free providers (Groq/OpenRouter) by default;
+// Anthropic is used only when the operator supplies their own key.
+
+import { llmComplete, llmConfigured } from '../../../api/_lib/llm.js';
-const MODEL = 'claude-haiku-4-5-20251001';
const MAX_TOKENS = 512;
const TIMEOUT_MS = 20_000;
@@ -58,12 +61,11 @@ Prioritise earning over spending. Keep thoughts concise.`;
// Think about what to do next.
// Returns { thoughts: string, actions: Array<{type, description}>, tokensUsed: number }
export async function think({ treasury, recentActivity, earnings24h = 0, costs24h = 0, availableBudgetAtomics }) {
- const apiKey = process.env.ANTHROPIC_API_KEY;
- if (!apiKey) {
- console.warn('[inference] ANTHROPIC_API_KEY not set — returning idle plan');
+ if (!llmConfigured({ anthropicKey: process.env.ANTHROPIC_API_KEY })) {
+ console.warn('[inference] no LLM provider configured — returning idle plan');
return {
- thoughts: 'API key not configured. Idling until environment is ready.',
- actions: [{ type: 'idle', description: 'Waiting for API key configuration.' }],
+ thoughts: 'No LLM provider configured. Idling until environment is ready.',
+ actions: [{ type: 'idle', description: 'Waiting for LLM provider configuration.' }],
tokensUsed: 0,
};
}
@@ -78,56 +80,26 @@ export async function think({ treasury, recentActivity, earnings24h = 0, costs24
const userMessage = 'What should I do this tick? Respond with JSON only.';
- let response;
+ let result;
try {
- response = await fetch('https://api.anthropic.com/v1/messages', {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- 'x-api-key': apiKey,
- 'anthropic-version': '2023-06-01',
- },
- body: JSON.stringify({
- model: MODEL,
- max_tokens: MAX_TOKENS,
- system: systemPrompt,
- messages: [{ role: 'user', content: userMessage }],
- }),
- signal: AbortSignal.timeout(TIMEOUT_MS),
+ result = await llmComplete({
+ system: systemPrompt,
+ user: userMessage,
+ maxTokens: MAX_TOKENS,
+ anthropicKey: process.env.ANTHROPIC_API_KEY,
+ timeoutMs: TIMEOUT_MS,
});
} catch (err) {
- console.error('[inference] fetch failed:', err.message);
- return {
- thoughts: 'Network error reaching Anthropic. Conserving resources.',
- actions: [{ type: 'idle', description: 'Skipped think due to network error.' }],
- tokensUsed: 0,
- };
- }
-
- if (!response.ok) {
- const text = await response.text().catch(() => '');
- console.error('[inference] Anthropic API error:', response.status, text);
- return {
- thoughts: `Anthropic API returned ${response.status}. Conserving.`,
- actions: [{ type: 'idle', description: `API error ${response.status}.` }],
- tokensUsed: 0,
- };
- }
-
- let data;
- try {
- data = await response.json();
- } catch (err) {
- console.error('[inference] JSON parse failed:', err.message);
+ console.error('[inference] LLM call failed:', err.message);
return {
- thoughts: 'Could not parse LLM response. Idling.',
- actions: [{ type: 'idle', description: 'JSON parse error.' }],
+ thoughts: 'Error reaching LLM provider. Conserving resources.',
+ actions: [{ type: 'idle', description: 'Skipped think due to provider error.' }],
tokensUsed: 0,
};
}
- const tokensUsed = data.usage?.input_tokens + data.usage?.output_tokens || 0;
- const rawContent = data.content?.[0]?.text || '';
+ const tokensUsed = (result.usage?.input || 0) + (result.usage?.output || 0);
+ const rawContent = result.text || '';
let parsed;
try {
diff --git a/agents/unstoppable/src/reflection.js b/agents/unstoppable/src/reflection.js
index 817b48775..68d8f1212 100644
--- a/agents/unstoppable/src/reflection.js
+++ b/agents/unstoppable/src/reflection.js
@@ -2,12 +2,13 @@
//
// Once per calendar day the agent introspects on its activity, earnings,
// and costs, then writes a 2-3 sentence reflection + strategy note for
-// the next day. Reflection uses the same Anthropic API as inference.js.
+// the next day. Reflection uses the same shared LLM helper as inference.js —
+// funded free providers (Groq/OpenRouter) by default, Anthropic only as BYOK.
import { sql } from '../../../api/_lib/db.js';
import { getEarnings24h, getCosts24h, getRecentActivity } from './earnings.js';
+import { llmComplete, llmConfigured } from '../../../api/_lib/llm.js';
-const MODEL = 'claude-haiku-4-5-20251001';
const MAX_TOKENS = 512;
const TIMEOUT_MS = 20_000;
@@ -36,12 +37,11 @@ async function todayReflectionExists() {
// Calls the LLM to generate a reflection summary.
async function generateReflection({ earnings24h, costs24h, actionsCount, recentActivity }) {
- const apiKey = process.env.ANTHROPIC_API_KEY;
- if (!apiKey) {
+ if (!llmConfigured({ anthropicKey: process.env.ANTHROPIC_API_KEY })) {
const net = earnings24h - costs24h;
return {
summary: `Today the agent processed ${actionsCount} actions and earned $${formatAtomics(earnings24h)} USDC against $${formatAtomics(costs24h)} in costs, for a net of $${formatAtomics(net)} USDC.`,
- strategy_notes: 'No API key configured — using statistical summary only.',
+ strategy_notes: 'No LLM provider configured — using statistical summary only.',
};
}
@@ -69,50 +69,23 @@ Write a daily reflection as JSON with exactly two fields:
Respond with JSON only. No prose, no markdown fences.`;
- let response;
+ let result;
try {
- response = await fetch('https://api.anthropic.com/v1/messages', {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- 'x-api-key': apiKey,
- 'anthropic-version': '2023-06-01',
- },
- body: JSON.stringify({
- model: MODEL,
- max_tokens: MAX_TOKENS,
- messages: [{ role: 'user', content: prompt }],
- }),
- signal: AbortSignal.timeout(TIMEOUT_MS),
+ result = await llmComplete({
+ user: prompt,
+ maxTokens: MAX_TOKENS,
+ anthropicKey: process.env.ANTHROPIC_API_KEY,
+ timeoutMs: TIMEOUT_MS,
});
} catch (err) {
- console.error('[reflection] fetch failed:', err.message);
+ console.error('[reflection] LLM call failed:', err.message);
return {
- summary: `API unreachable during reflection. Today: ${actionsCount} actions, $${formatAtomics(earnings24h)} earned, $${formatAtomics(costs24h)} spent.`,
- strategy_notes: 'Network error prevented strategic analysis.',
+ summary: `LLM unreachable during reflection. Today: ${actionsCount} actions, $${formatAtomics(earnings24h)} earned, $${formatAtomics(costs24h)} spent.`,
+ strategy_notes: 'Provider error prevented strategic analysis.',
};
}
- if (!response.ok) {
- console.error('[reflection] Anthropic error:', response.status);
- return {
- summary: `Anthropic API error ${response.status}. ${actionsCount} actions today, net $${formatAtomics(earnings24h - costs24h)}.`,
- strategy_notes: 'API error prevented reflection generation.',
- };
- }
-
- let data;
- try {
- data = await response.json();
- } catch (err) {
- console.error('[reflection] parse error:', err.message);
- return {
- summary: `Parse error during reflection. ${actionsCount} actions, $${formatAtomics(earnings24h)} earned.`,
- strategy_notes: null,
- };
- }
-
- const rawContent = data.content?.[0]?.text || '';
+ const rawContent = result.text || '';
try {
const clean = rawContent.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '').trim();
const parsed = JSON.parse(clean);
diff --git a/api/_lib/db.js b/api/_lib/db.js
index 0c89e4143..65d2b9e5d 100644
--- a/api/_lib/db.js
+++ b/api/_lib/db.js
@@ -1,5 +1,5 @@
// Neon serverless Postgres. HTTP-based, works in edge + node runtimes.
-// Use `sql` as a tagged template for one-shot queries; use `tx()` for transactions.
+// Use `sql` as a tagged template for queries: sql`SELECT … WHERE id = ${id}`.
import { neon } from '@neondatabase/serverless';
import { env } from './env.js';
@@ -20,22 +20,3 @@ export const sql = new Proxy(function () {}, {
return getSql()[prop];
},
});
-
-// Simple retry for transient network errors — Neon drops idle HTTPS quickly.
-export async function query(strings, ...values) {
- let lastErr;
- for (let attempt = 0; attempt < 2; attempt++) {
- try {
- return await getSql()(strings, ...values);
- } catch (err) {
- lastErr = err;
- if (!isRetryable(err)) throw err;
- }
- }
- throw lastErr;
-}
-
-function isRetryable(err) {
- const msg = String(err?.message || '').toLowerCase();
- return msg.includes('fetch failed') || msg.includes('network') || msg.includes('timeout');
-}
diff --git a/api/_lib/pumpfun-ws-feed.js b/api/_lib/pumpfun-ws-feed.js
index 3da73580f..d5cab7637 100644
--- a/api/_lib/pumpfun-ws-feed.js
+++ b/api/_lib/pumpfun-ws-feed.js
@@ -105,7 +105,9 @@ export function connectPumpFunFeed({ onEvent, signal, kind = 'all', mints = [] }
if (kind === 'all' || kind === 'mint') {
ws.send(JSON.stringify({ method: 'subscribeNewToken' }));
}
- if (kind === 'all' || kind === 'graduation') {
+ // Trade subscribers also watch migrations so a tracked token's
+ // graduation surfaces alongside its trades (filtered to the mint below).
+ if (kind === 'all' || kind === 'graduation' || wantsTrades) {
ws.send(JSON.stringify({ method: 'subscribeMigration' }));
}
if (wantsTrades) {
@@ -130,7 +132,12 @@ export function connectPumpFunFeed({ onEvent, signal, kind = 'all', mints = [] }
pushBuffer('mint', data);
if (active) onEvent({ kind: 'mint', data });
});
- } else if ((msg.txType === 'migrate' || msg.txType === 'migration') && (kind === 'all' || kind === 'graduation')) {
+ } else if (msg.txType === 'migrate' || msg.txType === 'migration') {
+ const wantGrad = kind === 'all' || kind === 'graduation';
+ // In trades-only mode, only the tracked mint's graduation is relevant —
+ // filter before the (expensive) enrichment so we don't enrich the
+ // whole firehose for one watched token.
+ if (!wantGrad && !(wantsTrades && tradeMints.includes(msg.mint))) return;
if (!markSeen(msg.signature)) return;
enrichGrad(msg).then((data) => {
pushBuffer('graduation', data);
diff --git a/api/inference/livepeer.js b/api/inference/livepeer.js
index ef698f973..6db5ed829 100644
--- a/api/inference/livepeer.js
+++ b/api/inference/livepeer.js
@@ -23,12 +23,13 @@
// eslint-disable-next-line no-unused-vars -- pinned for version parity with the SDK call shape
import { Livepeer } from 'livepeer';
import { env } from '../_lib/env.js';
+import { llmComplete } from '../_lib/llm.js';
import { cors, method, readJson, error, json, wrap } from '../_lib/http.js';
export const maxDuration = 60;
const DEFAULT_LIVEPEER_MODEL = 'meta-llama/Meta-Llama-3.1-8B-Instruct';
-const CLAUDE_MODEL = 'claude-haiku-4-5-20251001';
+const PROVIDER_NETWORK = { anthropic: 'Anthropic', groq: 'Groq', openrouter: 'OpenRouter' };
// Models known to be available on the Livepeer public/studio gateway as of
// late 2025. Surfaced to the client via the GET handler so the demo's
@@ -56,63 +57,41 @@ function clampTemp(n, fallback = 0.7) {
return Math.min(Math.max(v, 0), 2);
}
-// ── Claude leg ────────────────────────────────────────────────────────────────
+// ── Platform LLM leg ────────────────────────────────────────────────────────
+//
+// The non-Livepeer side of the comparison runs on the platform's funded free
+// providers (Groq/OpenRouter) by default, and upgrades to Anthropic when the
+// operator supplies their own key — matching the platform-wide BYOK policy.
+// `network`/`model` always report whichever provider actually answered.
-async function callClaude({ prompt, max_tokens, temperature }) {
- // ANTHROPIC_API_KEY is optional (env.opt) — skip the doomed request and
- // report the missing-key state so the comparison still shows the Livepeer leg.
- const key = env.ANTHROPIC_API_KEY;
- if (!key) {
- return {
- ok: false,
- network: 'Anthropic',
- model: CLAUDE_MODEL,
- latency_ms: 0,
- error: 'missing_api_key',
- upstream_body: 'ANTHROPIC_API_KEY is not configured',
- };
- }
+async function callPlatformLlm({ prompt, max_tokens }) {
const t0 = Date.now();
- const upstream = await fetch('https://api.anthropic.com/v1/messages', {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- 'x-api-key': key,
- 'anthropic-version': '2023-06-01',
- },
- body: JSON.stringify({
- model: CLAUDE_MODEL,
- max_tokens,
- temperature,
- messages: [{ role: 'user', content: prompt }],
- }),
- });
- const latency_ms = Date.now() - t0;
-
- if (!upstream.ok) {
- const body = await upstream.text().catch(() => '');
+ let result;
+ try {
+ result = await llmComplete({
+ user: prompt,
+ maxTokens: max_tokens,
+ anthropicKey: env.ANTHROPIC_API_KEY,
+ timeoutMs: 45_000,
+ });
+ } catch (e) {
return {
ok: false,
- network: 'Anthropic',
- model: CLAUDE_MODEL,
- latency_ms,
- error: 'upstream_error',
- upstream_status: upstream.status,
- upstream_body: body.slice(0, 1000),
+ network: PROVIDER_NETWORK.anthropic,
+ model: null,
+ latency_ms: Date.now() - t0,
+ error: e.code === 'llm_unavailable' ? 'no_provider_configured' : 'upstream_error',
+ upstream_body: String(e?.message || e).slice(0, 1000),
};
}
-
- const data = await upstream.json();
- const reply = (data.content || []).map((c) => c?.text || '').join('').trim();
return {
ok: true,
- network: 'Anthropic',
- model: CLAUDE_MODEL,
- latency_ms,
- reply,
- prompt_tokens: data?.usage?.input_tokens ?? null,
- completion_tokens: data?.usage?.output_tokens ?? null,
- stop_reason: data?.stop_reason ?? null,
+ network: PROVIDER_NETWORK[result.provider] || result.provider,
+ model: result.model,
+ latency_ms: Date.now() - t0,
+ reply: (result.text || '').trim(),
+ prompt_tokens: result.usage?.input ?? null,
+ completion_tokens: result.usage?.output ?? null,
};
}
@@ -265,7 +244,7 @@ export default wrap(async function handler(req, res) {
const temperature = clampTemp(body.temperature, 0.7);
const [claudeRes, livepeerRes] = await Promise.allSettled([
- callClaude({ prompt, max_tokens, temperature }),
+ callPlatformLlm({ prompt, max_tokens }),
callLivepeer({ prompt, model, max_tokens, temperature }),
]);
@@ -273,8 +252,8 @@ export default wrap(async function handler(req, res) {
? claudeRes.value
: {
ok: false,
- network: 'Anthropic',
- model: CLAUDE_MODEL,
+ network: PROVIDER_NETWORK.anthropic,
+ model: null,
error: 'leg_failed',
error_message: String(claudeRes.reason?.message || claudeRes.reason || 'unknown'),
};
diff --git a/package.json b/package.json
index 7b37f890a..9e9dec4f1 100644
--- a/package.json
+++ b/package.json
@@ -56,6 +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",
"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/home.html b/pages/home.html
index 58fe61c95..98dea7b19 100644
--- a/pages/home.html
+++ b/pages/home.html
@@ -2329,6 +2329,30 @@
<a href="/login">Sign in</a>
<a class="btn primary" href="/dashboard" style="margin-top:4px;">Console →</a>
</nav>
+<script>
+ (function () {
+ var toggle = document.getElementById('nav-toggle');
+ var drawer = document.getElementById('nav-drawer');
+ if (!toggle || !drawer) return;
+ function isOpen() { return drawer.classList.contains('open'); }
+ function setOpen(open) {
+ toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
+ drawer.setAttribute('aria-hidden', open ? 'false' : 'true');
+ document.body.style.overflow = open ? 'hidden' : '';
+ drawer.classList.toggle('open', open);
+ }
+ toggle.addEventListener('click', function () { setOpen(!isOpen()); });
+ drawer.addEventListener('click', function (e) {
+ if (e.target.closest('a')) setOpen(false);
+ });
+ document.addEventListener('keydown', function (e) {
+ if (e.key === 'Escape' && isOpen()) { setOpen(false); toggle.focus(); }
+ });
+ window.addEventListener('resize', function () {
+ if (window.innerWidth > 880 && isOpen()) setOpen(false);
+ });
+ })();
+</script>
<!-- ── HERO ─────────────────────────────────────────────────────── -->
<section class="hero">
diff --git a/scripts/crawl-audit.mjs b/scripts/crawl-audit.mjs
new file mode 100644
index 000000000..3204b820c
--- /dev/null
+++ b/scripts/crawl-audit.mjs
@@ -0,0 +1,365 @@
+#!/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}`);
+ }
+
+ 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/tests/pumpfun-ws-trades.test.js b/tests/pumpfun-ws-trades.test.js
new file mode 100644
index 000000000..f12b2d46d
--- /dev/null
+++ b/tests/pumpfun-ws-trades.test.js
@@ -0,0 +1,90 @@
+// Tests for the PumpPortal trade-stream path added to connectPumpFunFeed.
+//
+// Drives a fake `ws` WebSocket so we can assert the real dispatch loop:
+// - kind:'trades' + mints subscribes via subscribeTokenTrade(keys)
+// - buy/sell messages emit normalized { kind:'trade' } events
+// - a tracked mint's migration still surfaces as a graduation
+// - no trade subscription is sent without mints
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+class FakeWS {
+ constructor(url) {
+ this.url = url;
+ this.sent = [];
+ this._h = {};
+ FakeWS.instances.push(this);
+ }
+ on(ev, cb) { (this._h[ev] ||= []).push(cb); return this; }
+ emit(ev, ...args) { (this._h[ev] || []).forEach((cb) => cb(...args)); }
+ send(data) { this.sent.push(JSON.parse(data)); }
+ close() { this.emit('close'); }
+}
+FakeWS.instances = [];
+
+vi.mock('ws', () => ({ default: FakeWS }));
+vi.mock('../api/_lib/db.js', () => ({ sql: vi.fn(async () => []) }));
+vi.mock('../api/_lib/env.js', () => ({
+ env: { DATABASE_URL: 'postgres://test', APP_ORIGIN: 'http://test' },
+}));
+
+// getSolPrice() hits CoinGecko — stub a stable price.
+globalThis.fetch = vi.fn(async () => ({ ok: true, json: async () => ({ solana: { usd: 150 } }) }));
+
+const { connectPumpFunFeed } = await import('../api/_lib/pumpfun-ws-feed.js');
+
+const flush = () => new Promise((r) => setTimeout(r, 10));
+
+describe('connectPumpFunFeed — trades', () => {
+ beforeEach(() => { FakeWS.instances.length = 0; });
+
+ it('subscribes to token trades for the given mints', () => {
+ const stop = connectPumpFunFeed({ kind: 'trades', mints: ['MINT1'], onEvent: () => {} });
+ const ws = FakeWS.instances[0];
+ ws.emit('open');
+ const sub = ws.sent.find((m) => m.method === 'subscribeTokenTrade');
+ expect(sub).toBeTruthy();
+ expect(sub.keys).toContain('MINT1');
+ stop();
+ });
+
+ it('emits a normalized trade event for buy/sell messages', async () => {
+ const events = [];
+ const stop = connectPumpFunFeed({ kind: 'trades', mints: ['MINT1'], onEvent: (e) => events.push(e) });
+ const ws = FakeWS.instances[0];
+ ws.emit('open');
+ ws.emit('message', JSON.stringify({
+ txType: 'buy', mint: 'MINT1', signature: 'sig-buy-1',
+ solAmount: 2.5, marketCapSol: 30, traderPublicKey: 'traderA', tokenAmount: 1000,
+ }));
+ await flush();
+ const trade = events.find((e) => e.kind === 'trade');
+ expect(trade).toBeTruthy();
+ expect(trade.data.is_buy).toBe(true);
+ expect(trade.data.solAmount).toBe(2.5);
+ expect(trade.data.sol_amount).toBe(2.5);
+ expect(trade.data.mint).toBe('MINT1');
+ expect(trade.data.sol_value_usd).toBeCloseTo(375); // 2.5 * 150
+ stop();
+ });
+
+ it('does not subscribe to trades when no mints are provided', () => {
+ const stop = connectPumpFunFeed({ kind: 'trades', mints: [], onEvent: () => {} });
+ const ws = FakeWS.instances[0];
+ ws.emit('open');
+ expect(ws.sent.find((m) => m.method === 'subscribeTokenTrade')).toBeUndefined();
+ stop();
+ });
+
+ it('ignores trades for non-tracked mints (no firehose leakage)', async () => {
+ const events = [];
+ const stop = connectPumpFunFeed({ kind: 'trades', mints: ['MINT1'], onEvent: (e) => events.push(e) });
+ const ws = FakeWS.instances[0];
+ ws.emit('open');
+ // A graduation for a different mint must not surface in trades-only mode.
+ ws.emit('message', JSON.stringify({ txType: 'migrate', mint: 'OTHER', signature: 'sig-grad-other' }));
+ await flush();
+ expect(events.find((e) => e.kind === 'graduation')).toBeUndefined();
+ stop();
+ });
+});