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: consolidate LLM calls into shared api/_lib/llm.js

nirholas821c7199d045
diff --git a/api/_lib/llm.js b/api/_lib/llm.js
new file mode 100644
index 000000000..2cfe8e35c
--- /dev/null
+++ b/api/_lib/llm.js
@@ -0,0 +1,143 @@
+// Canonical server-side text completion + the platform's LLM provider policy.
+//
+// Policy (do not re-implement per endpoint — that is how this drifted before):
+//
+// • Groq and OpenRouter are PLATFORM-FUNDED. The server holds those keys and
+// callers use them for free. They are the default providers, tried in order.
+//
+// • Anthropic is BYOK (bring-your-own-key). It is used ONLY when the caller
+// passes an explicit `anthropicKey` (e.g. an agent owner's own key). The
+// platform never depends on a server-side ANTHROPIC_API_KEY and never
+// hard-fails when it is absent — every flow degrades to the free providers.
+//
+// Consolidated from the multi-provider fallback that already lived in
+// api/persona/extract.js and api/persona/preview.js.
+
+import { env } from './env.js';
+
+const GROQ_MODEL = 'llama-3.3-70b-versatile';
+const OPENROUTER_MODEL = 'meta-llama/llama-3.3-70b-instruct';
+const ANTHROPIC_MODEL = 'claude-haiku-4-5-20251001';
+
+// Thrown when no provider is available at all (no free key configured and no
+// BYOK key supplied). Carries an HTTP status so handlers can surface it as 503.
+export class LlmUnavailableError extends Error {
+ constructor(message = 'No LLM provider available. Configure GROQ_API_KEY or OPENROUTER_API_KEY, or supply a BYOK Anthropic key.') {
+ super(message);
+ this.name = 'LlmUnavailableError';
+ this.code = 'llm_unavailable';
+ this.status = 503;
+ }
+}
+
+function anthropicProvider(key, model) {
+ const m = model || ANTHROPIC_MODEL;
+ return {
+ name: 'anthropic',
+ model: m,
+ url: 'https://api.anthropic.com/v1/messages',
+ headers: {
+ 'content-type': 'application/json',
+ 'x-api-key': key,
+ 'anthropic-version': '2023-06-01',
+ },
+ buildBody: (system, user, maxTokens) => ({
+ model: m,
+ max_tokens: maxTokens,
+ system,
+ messages: [{ role: 'user', content: user }],
+ }),
+ extractText: (r) => r.content?.[0]?.text || '',
+ extractUsage: (r) => ({ input: r.usage?.input_tokens ?? 0, output: r.usage?.output_tokens ?? 0 }),
+ };
+}
+
+function openaiCompatProvider({ name, key, url, model, extraHeaders = {} }) {
+ return {
+ name,
+ model,
+ url,
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}`, ...extraHeaders },
+ buildBody: (system, user, maxTokens) => ({
+ model,
+ max_tokens: maxTokens,
+ messages: [
+ { role: 'system', content: system },
+ { role: 'user', content: user },
+ ],
+ }),
+ extractText: (r) => r.choices?.[0]?.message?.content || '',
+ extractUsage: (r) => ({ input: r.usage?.prompt_tokens ?? 0, output: r.usage?.completion_tokens ?? 0 }),
+ };
+}
+
+// Build the ordered provider chain for a request. BYOK Anthropic (when the
+// caller brings a key) is preferred, then the free platform providers.
+function providerChain({ anthropicKey, anthropicModel } = {}) {
+ const chain = [];
+ if (anthropicKey) chain.push(anthropicProvider(anthropicKey, anthropicModel));
+ if (env.GROQ_API_KEY) {
+ chain.push(openaiCompatProvider({
+ name: 'groq',
+ key: env.GROQ_API_KEY,
+ url: 'https://api.groq.com/openai/v1/chat/completions',
+ model: GROQ_MODEL,
+ }));
+ }
+ if (env.OPENROUTER_API_KEY) {
+ chain.push(openaiCompatProvider({
+ name: 'openrouter',
+ key: env.OPENROUTER_API_KEY,
+ url: 'https://openrouter.ai/api/v1/chat/completions',
+ model: OPENROUTER_MODEL,
+ extraHeaders: { 'HTTP-Referer': 'https://three.ws', 'X-Title': 'three.ws' },
+ }));
+ }
+ return chain;
+}
+
+// True when at least one provider can serve a completion for the given options.
+// Use to gate a feature without making the doomed upstream call.
+export function llmConfigured(opts = {}) {
+ return providerChain(opts).length > 0;
+}
+
+// Run a single-shot system+user completion against the first available
+// provider, falling over to the next on transport or non-2xx errors.
+//
+// Returns { text, provider, model, usage:{input,output}, raw }.
+// Throws LlmUnavailableError when no provider is configured, or the last
+// upstream error (with .status = 502) when every provider failed.
+export async function llmComplete({ system, user, maxTokens = 1024, anthropicKey = null, anthropicModel = null }) {
+ const chain = providerChain({ anthropicKey, anthropicModel });
+ if (!chain.length) throw new LlmUnavailableError();
+
+ let lastErr;
+ for (const p of chain) {
+ let upstream;
+ try {
+ upstream = await fetch(p.url, {
+ method: 'POST',
+ headers: p.headers,
+ body: JSON.stringify(p.buildBody(system, user, maxTokens)),
+ });
+ } catch (e) {
+ lastErr = Object.assign(new Error(`${p.name} unreachable: ${e.message}`), { status: 502, code: 'upstream_unreachable' });
+ continue;
+ }
+ if (!upstream.ok) {
+ const body = await upstream.text().catch(() => '');
+ lastErr = Object.assign(new Error(`${p.name} ${upstream.status}: ${body.slice(0, 200)}`), { status: 502, code: 'upstream_error' });
+ continue;
+ }
+ const data = await upstream.json();
+ return {
+ text: (p.extractText(data) || '').trim(),
+ provider: p.name,
+ model: p.model,
+ usage: p.extractUsage(data),
+ raw: data,
+ };
+ }
+ throw lastErr || new LlmUnavailableError();
+}
diff --git a/api/agent-delegate.js b/api/agent-delegate.js
index 1f3e9447f..d43743635 100644
--- a/api/agent-delegate.js
+++ b/api/agent-delegate.js
@@ -3,7 +3,7 @@ import { authenticateBearer, extractBearer, getSessionUser } from './_lib/auth.j
import { cors, json, method, wrap, error, readJson } from './_lib/http.js';
import { limits } from './_lib/rate-limit.js';
import { normalizeLegacyPolicy } from './_lib/embed-policy.js';
-import { env } from './_lib/env.js';
+import { llmComplete, LlmUnavailableError } from './_lib/llm.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
@@ -43,26 +43,15 @@ export default wrap(async (req, res) => {
agent.meta?.brain?.instructions ||
`You are ${agent.name}. ${agent.description || ''}`.trim();
- const upstream = await fetch('https://api.anthropic.com/v1/messages', {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- 'anthropic-version': '2023-06-01',
- 'x-api-key': env.ANTHROPIC_API_KEY,
- },
- body: JSON.stringify({
- model,
- max_tokens: 1024,
- system: systemPrompt,
- messages: [{ role: 'user', content: message }],
- }),
- });
-
- if (!upstream.ok)
- return error(res, 502, 'upstream_error', `LLM call failed: ${upstream.status}`);
-
- const data = await upstream.json();
- const response = data?.content?.[0]?.text || '';
-
- return json(res, 200, { response, agentId: toAgentId });
+ let result;
+ try {
+ result = await llmComplete({ system: systemPrompt, user: message, maxTokens: 1024, anthropicModel: model });
+ } catch (err) {
+ if (err instanceof LlmUnavailableError) {
+ return error(res, 503, 'llm_unavailable', 'agent delegation is not available right now');
+ }
+ return error(res, 502, 'upstream_error', `LLM call failed: ${err.message}`);
+ }
+
+ return json(res, 200, { response: result.text, agentId: toAgentId, model: result.model });
});
diff --git a/api/agents/[id]/memory-seed-x.js b/api/agents/[id]/memory-seed-x.js
index 0aee7eb77..2e6009e4a 100644
--- a/api/agents/[id]/memory-seed-x.js
+++ b/api/agents/[id]/memory-seed-x.js
@@ -9,6 +9,7 @@ import { getSessionUser } from '../../_lib/auth.js';
import { cors, json, method, wrap, error } from '../../_lib/http.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { env } from '../../_lib/env.js';
+import { llmComplete } from '../../_lib/llm.js';
import { decryptToken, encryptToken } from '../../auth/x/[action].js';
// ── Token refresh ─────────────────────────────────────────────────────────────
@@ -62,53 +63,25 @@ async function getAccessToken(conn) {
async function distilFacts(profile, tweets) {
const tweetLines = tweets.map((t) => t.text).join('\n');
- const res = await fetch('https://api.anthropic.com/v1/messages', {
- method: 'POST',
- headers: {
- 'x-api-key': env.ANTHROPIC_API_KEY,
- 'anthropic-version': '2023-06-01',
- 'content-type': 'application/json',
- },
- body: JSON.stringify({
- model: 'claude-haiku-4-5-20251001',
- max_tokens: 1024,
- system:
- 'You distill tweets into concise memory facts for an AI agent. ' +
- 'Focus on: recurring topics, strong opinions, projects, communication style, humor.',
- messages: [
- {
- role: 'user',
- content:
- `Profile: @${profile.username} | ${profile.description || ''} | ` +
- `${profile.public_metrics?.followers_count ?? 0} followers\n\n` +
- `Recent tweets (newest first):\n${tweetLines}`,
- },
- ],
- tools: [
- {
- name: 'extract_memory_facts',
- description: 'Extract up to 15 concise single-sentence memory facts from the tweets.',
- input_schema: {
- type: 'object',
- properties: {
- facts: { type: 'array', items: { type: 'string' }, maxItems: 15 },
- },
- required: ['facts'],
- },
- },
- ],
- tool_choice: { type: 'tool', name: 'extract_memory_facts' },
- }),
+ const { text: raw } = await llmComplete({
+ maxTokens: 1024,
+ system:
+ 'You distill tweets into concise memory facts for an AI agent. ' +
+ 'Focus on: recurring topics, strong opinions, projects, communication style, humor. ' +
+ 'Output ONLY a JSON array of up to 15 single-sentence strings, no other text.',
+ user:
+ `Profile: @${profile.username} | ${profile.description || ''} | ` +
+ `${profile.public_metrics?.followers_count ?? 0} followers\n\n` +
+ `Recent tweets (newest first):\n${tweetLines}`,
});
- if (!res.ok) {
- const text = await res.text().catch(() => '');
- throw new Error(`Claude API error ${res.status}: ${text.slice(0, 200)}`);
+ try {
+ const stripped = raw.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '').trim();
+ const facts = JSON.parse(stripped);
+ return Array.isArray(facts) ? facts.filter((f) => typeof f === 'string').slice(0, 15) : [];
+ } catch {
+ return [];
}
-
- const data = await res.json();
- const toolUse = (data.content || []).find((b) => b.type === 'tool_use');
- return toolUse?.input?.facts ?? [];
}
// ── GET — status ──────────────────────────────────────────────────────────────
diff --git a/api/agents/_id/memory-seed-farcaster.js b/api/agents/_id/memory-seed-farcaster.js
index 0719ec288..aedacfc37 100644
--- a/api/agents/_id/memory-seed-farcaster.js
+++ b/api/agents/_id/memory-seed-farcaster.js
@@ -8,6 +8,7 @@ import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { parse } from '../../_lib/validate.js';
import { env } from '../../_lib/env.js';
+import { llmComplete } from '../../_lib/llm.js';
const bodySchema = z
.object({
@@ -43,52 +44,22 @@ async function distillFacts(profile, casts, apiKey) {
const followers = profile.follower_count ?? 0;
const userLine = `Display name: ${displayName}, Bio: ${bio || '(none)'}, Followers: ${followers}`;
- const resp = await fetch('https://api.anthropic.com/v1/messages', {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- 'anthropic-version': '2023-06-01',
- 'x-api-key': env.ANTHROPIC_API_KEY,
- },
- body: JSON.stringify({
- model: 'claude-haiku-4-5-20251001',
- max_tokens: 1024,
- tools: [
- {
- name: 'extract_memory_facts',
- description:
- 'Extract concise memory facts from a Farcaster profile and recent casts for an AI agent.',
- input_schema: {
- type: 'object',
- properties: {
- facts: {
- type: 'array',
- items: { type: 'string' },
- maxItems: 15,
- description: 'Up to 15 single-sentence facts about the user',
- },
- },
- required: ['facts'],
- },
- },
- ],
- tool_choice: { type: 'tool', name: 'extract_memory_facts' },
- system: 'You distill Farcaster casts into concise memory facts for an AI agent. Focus on: recurring topics, opinions, projects, communication style, community ties.',
- messages: [
- {
- role: 'user',
- content: `Profile: ${userLine}\n\nRecent casts (newest first):\n${castTexts}`,
- },
- ],
- }),
+ const { text: raw } = await llmComplete({
+ maxTokens: 1024,
+ system:
+ 'You distill Farcaster casts into concise memory facts for an AI agent. ' +
+ 'Focus on: recurring topics, opinions, projects, communication style, community ties. ' +
+ 'Output ONLY a JSON array of up to 15 single-sentence strings, no other text.',
+ user: `Profile: ${userLine}\n\nRecent casts (newest first):\n${castTexts}`,
});
- if (!resp.ok) throw new Error(`Claude error ${resp.status}`);
-
- const data = await resp.json();
- const toolUse = data.content?.find((b) => b.type === 'tool_use');
- const facts = toolUse?.input?.facts;
- return Array.isArray(facts) ? facts.slice(0, 15) : [];
+ try {
+ const stripped = raw.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '').trim();
+ const facts = JSON.parse(stripped);
+ return Array.isArray(facts) ? facts.filter((f) => typeof f === 'string').slice(0, 15) : [];
+ } catch {
+ return [];
+ }
}
export default wrap(async (req, res) => {
diff --git a/api/agents/_id/memory-seed-x.js b/api/agents/_id/memory-seed-x.js
index 6745a5415..3c13dcaaf 100644
--- a/api/agents/_id/memory-seed-x.js
+++ b/api/agents/_id/memory-seed-x.js
@@ -13,6 +13,7 @@ import { sql } from '../../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
import { cors, json, method, error } from '../../_lib/http.js';
import { env } from '../../_lib/env.js';
+import { llmComplete } from '../../_lib/llm.js';
import { limits } from '../../_lib/rate-limit.js';
const subtle = globalThis.crypto?.subtle || webcrypto.subtle;
@@ -100,42 +101,20 @@ async function distillFacts(xData) {
? `\n\nRecent original tweets (highest-engagement first):\n${xData.tweets.map((t, i) => `${i + 1}. ${t}`).join('\n')}`
: '';
- const res = await fetch('https://api.anthropic.com/v1/messages', {
- method: 'POST',
- headers: {
- 'x-api-key': env.ANTHROPIC_API_KEY,
- 'anthropic-version': '2023-06-01',
- 'content-type': 'application/json',
- },
- body: JSON.stringify({
- model: 'claude-haiku-4-5-20251001',
- max_tokens: 1024,
- system:
- 'You distill a person\'s X (Twitter) profile and posts into concise memory facts ' +
- 'for an AI agent that will represent this person. Each fact is a single ' +
- 'self-contained sentence about the person — their interests, expertise, communication ' +
- 'style, values, typical topics, or notable beliefs. Infer voice/tone from the tweet ' +
- 'style. Skip promotional content. Focus on authentic personality signals. ' +
- 'Output ONLY a JSON array of strings, no other text.',
- messages: [
- {
- role: 'user',
- content:
- `Extract up to 15 memory facts from this X profile:\n` +
- JSON.stringify(xData.profile, null, 2) +
- tweetBlock,
- },
- ],
- }),
+ const { text: raw } = await llmComplete({
+ maxTokens: 1024,
+ system:
+ 'You distill a person\'s X (Twitter) profile and posts into concise memory facts ' +
+ 'for an AI agent that will represent this person. Each fact is a single ' +
+ 'self-contained sentence about the person — their interests, expertise, communication ' +
+ 'style, values, typical topics, or notable beliefs. Infer voice/tone from the tweet ' +
+ 'style. Skip promotional content. Focus on authentic personality signals. ' +
+ 'Output ONLY a JSON array of strings, no other text.',
+ user:
+ `Extract up to 15 memory facts from this X profile:\n` +
+ JSON.stringify(xData.profile, null, 2) +
+ tweetBlock,
});
-
- if (!res.ok) {
- const text = await res.text().catch(() => '');
- throw new Error(`Claude API error ${res.status}: ${text.slice(0, 200)}`);
- }
-
- const data = await res.json();
- const raw = data.content?.[0]?.text || '[]';
try {
const facts = JSON.parse(raw);
return Array.isArray(facts) ? facts.filter((f) => typeof f === 'string').slice(0, 15) : [];
diff --git a/api/agents/_id/memory-seed.js b/api/agents/_id/memory-seed.js
index 151deacbf..51d657ed7 100644
--- a/api/agents/_id/memory-seed.js
+++ b/api/agents/_id/memory-seed.js
@@ -8,6 +8,7 @@ import { sql } from '../../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
import { cors, json, method, error } from '../../_lib/http.js';
import { env } from '../../_lib/env.js';
+import { llmComplete } from '../../_lib/llm.js';
import { limits } from '../../_lib/rate-limit.js';
const subtle = globalThis.crypto?.subtle || webcrypto.subtle;
@@ -97,39 +98,17 @@ async function fetchGitHubData(accessToken, login) {
// ── Claude Haiku distillation ─────────────────────────────────────────────────
async function distillFacts(githubData) {
- const res = await fetch('https://api.anthropic.com/v1/messages', {
- method: 'POST',
- headers: {
- 'x-api-key': env.ANTHROPIC_API_KEY,
- 'anthropic-version': '2023-06-01',
- 'content-type': 'application/json',
- },
- body: JSON.stringify({
- model: 'claude-haiku-4-5-20251001',
- max_tokens: 1024,
- system:
- 'You distill GitHub activity into concise memory facts for an AI agent. ' +
- 'Each fact is a single self-contained sentence about the developer — tech stack, ' +
- 'project types, commit style, interests, or notable contributions. ' +
- 'Output ONLY a JSON array of strings, no other text.',
- messages: [
- {
- role: 'user',
- content:
- `Extract up to 15 memory facts from this GitHub profile data:\n` +
- JSON.stringify(githubData, null, 2),
- },
- ],
- }),
+ const { text: raw } = await llmComplete({
+ maxTokens: 1024,
+ system:
+ 'You distill GitHub activity into concise memory facts for an AI agent. ' +
+ 'Each fact is a single self-contained sentence about the developer — tech stack, ' +
+ 'project types, commit style, interests, or notable contributions. ' +
+ 'Output ONLY a JSON array of strings, no other text.',
+ user:
+ `Extract up to 15 memory facts from this GitHub profile data:\n` +
+ JSON.stringify(githubData, null, 2),
});
-
- if (!res.ok) {
- const text = await res.text().catch(() => '');
- throw new Error(`Claude API error ${res.status}: ${text.slice(0, 200)}`);
- }
-
- const data = await res.json();
- const raw = data.content?.[0]?.text || '[]';
try {
const facts = JSON.parse(raw);
return Array.isArray(facts) ? facts.filter((f) => typeof f === 'string').slice(0, 15) : [];
diff --git a/api/agents/_id/persona.js b/api/agents/_id/persona.js
index bac34474d..afc3fba0c 100644
--- a/api/agents/_id/persona.js
+++ b/api/agents/_id/persona.js
@@ -7,11 +7,10 @@ import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/au
import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
import { limits } from '../../_lib/rate-limit.js';
import { env } from '../../_lib/env.js';
+import { llmComplete, LlmUnavailableError } from '../../_lib/llm.js';
import { parse } from '../../_lib/validate.js';
import { z } from 'zod';
-const ANTHROPIC_URL = 'https://api.anthropic.com/v1/messages';
-
const extractBody = z.object({
answers: z
.array(z.string().trim().min(5, 'Each answer must be at least 5 characters').max(1000))
@@ -26,32 +25,6 @@ async function resolveAuth(req) {
return null;
}
-const PERSONA_TOOL = {
- name: 'extract_persona',
- description: 'Extract a persona system prompt from interview answers',
- input_schema: {
- type: 'object',
- required: ['system_prompt', 'tone_tags', 'vocabulary_samples'],
- properties: {
- system_prompt: {
- type: 'string',
- description:
- 'A 150-300 word first-person system prompt that captures the persona. Start with "You are ...".',
- },
- tone_tags: {
- type: 'array',
- items: { type: 'string' },
- description: 'Up to 8 single-word tone descriptors (e.g. witty, direct, empathetic).',
- },
- vocabulary_samples: {
- type: 'array',
- items: { type: 'string' },
- description: 'Up to 10 short phrases or expressions characteristic of this persona.',
- },
- },
- },
-};
-
export const handlePersona = wrap(async (req, res, id, action) => {
if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET', 'POST'])) return;
@@ -88,54 +61,48 @@ export const handlePersona = wrap(async (req, res, id, action) => {
const body = parse(extractBody, await readJson(req));
const { answers } = body;
- const apiKey = env.ANTHROPIC_API_KEY;
-
- let upstream;
+ let raw;
try {
- upstream = await fetch(ANTHROPIC_URL, {
- method: 'POST',
- headers: {
- 'x-api-key': apiKey,
- 'anthropic-version': '2023-06-01',
- 'content-type': 'application/json',
- },
- body: JSON.stringify({
- model: 'claude-sonnet-4-6',
- max_tokens: 1024,
- system:
- 'You are a persona architect. Given a person\'s interview answers, extract their communication style, tone, and voice. Produce a concise first-person system prompt that an LLM can use to impersonate this person faithfully. Be specific. Avoid clichés.',
- messages: [
- {
- role: 'user',
- content: `Interview answers:\n1. ${answers[0]}\n2. ${answers[1]}\n3. ${answers[2]}\n4. ${answers[3]}\n5. ${answers[4]}`,
- },
- ],
- tools: [PERSONA_TOOL],
- tool_choice: { type: 'tool', name: 'extract_persona' },
- }),
- });
+ ({ text: raw } = await llmComplete({
+ maxTokens: 1024,
+ system:
+ 'You are a persona architect. Given a person\'s interview answers, extract their communication style, tone, and voice. Produce a concise first-person system prompt that an LLM can use to impersonate this person faithfully. Be specific. Avoid clichés.\n\n' +
+ 'Output ONLY a single JSON object (no markdown fences, no prose) with EXACTLY these fields:\n' +
+ '{\n' +
+ ' "system_prompt": string, // 150-300 word first-person system prompt, starting with "You are ..."\n' +
+ ' "tone_tags": string[], // up to 8 single-word tone descriptors\n' +
+ ' "vocabulary_samples": string[] // up to 10 short phrases characteristic of this persona\n' +
+ '}',
+ user: `Interview answers:\n1. ${answers[0]}\n2. ${answers[1]}\n3. ${answers[2]}\n4. ${answers[3]}\n5. ${answers[4]}`,
+ }));
} catch (err) {
- console.error('[persona/extract] anthropic fetch failed', err);
- return error(res, 502, 'upstream_error', 'persona extraction service unreachable');
+ if (err instanceof LlmUnavailableError) {
+ return error(res, 503, 'llm_unavailable', 'persona extraction is not available right now');
+ }
+ console.error('[persona/extract] LLM error', err.status || '', err.message);
+ return error(res, 502, 'upstream_error', 'persona extraction failed');
}
- if (!upstream.ok) {
- const text = await upstream.text().catch(() => '');
- console.error('[persona/extract] anthropic error', upstream.status, text.slice(0, 400));
- return error(res, 502, 'upstream_error', `persona extraction failed (${upstream.status})`);
+ let extracted;
+ try {
+ const stripped = raw.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '').trim();
+ extracted = JSON.parse(stripped);
+ } catch {
+ console.error('[persona/extract] non-JSON model output', raw.slice(0, 400));
+ return error(res, 502, 'upstream_error', 'unexpected response from persona extraction');
}
- const data = await upstream.json();
- const toolUse = data.content?.find(
- (b) => b.type === 'tool_use' && b.name === 'extract_persona',
- );
- if (!toolUse?.input) {
- console.error('[persona/extract] no tool_use block', JSON.stringify(data).slice(0, 400));
+ const system_prompt = typeof extracted.system_prompt === 'string' ? extracted.system_prompt.trim() : '';
+ const tone_tags = Array.isArray(extracted.tone_tags)
+ ? extracted.tone_tags.filter((t) => typeof t === 'string' && t.trim()).map((t) => t.trim().slice(0, 40)).slice(0, 8)
+ : [];
+ const vocabulary_samples = Array.isArray(extracted.vocabulary_samples)
+ ? extracted.vocabulary_samples.filter((v) => typeof v === 'string' && v.trim()).map((v) => v.trim().slice(0, 120)).slice(0, 10)
+ : [];
+ if (!system_prompt) {
return error(res, 502, 'upstream_error', 'unexpected response from persona extraction');
}
- const { system_prompt, tone_tags, vocabulary_samples } = toolUse.input;
-
const hash = createHash('sha256').update(system_prompt).digest('hex');
const sig = createHmac('sha256', env.JWT_SECRET).update(hash).digest('hex');
diff --git a/api/agents/talk.js b/api/agents/talk.js
index 2190c1350..e65c4c475 100644
--- a/api/agents/talk.js
+++ b/api/agents/talk.js
@@ -20,7 +20,7 @@ import { sql } from '../_lib/db.js';
import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { normalizeLegacyPolicy } from '../_lib/embed-policy.js';
-import { env } from '../_lib/env.js';
+import { llmComplete, LlmUnavailableError } from '../_lib/llm.js';
const ALLOWED_MODELS = new Set([
'claude-haiku-4-5-20251001',
@@ -78,45 +78,24 @@ export default wrap(async (req, res) => {
agent.meta?.brain?.instructions ||
`You are ${agent.name}. ${agent.description || ''}`.trim();
- if (!env.ANTHROPIC_API_KEY) {
- return error(res, 503, 'not_configured', 'agent delegation is unavailable: ANTHROPIC_API_KEY not configured');
- }
-
const started = Date.now();
- let upstream;
+ let result;
try {
- upstream = await fetch('https://api.anthropic.com/v1/messages', {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- 'anthropic-version': '2023-06-01',
- 'x-api-key': env.ANTHROPIC_API_KEY,
- 'x-delegate-depth': '1',
- },
- body: JSON.stringify({
- model,
- max_tokens: 1024,
- system: systemPrompt,
- messages: [{ role: 'user', content: message }],
- }),
- });
+ result = await llmComplete({ system: systemPrompt, user: message, maxTokens: 1024, anthropicModel: model });
} catch (err) {
- return error(res, 502, 'upstream_unreachable', err?.message || 'anthropic fetch failed');
- }
- if (!upstream.ok) {
- const msg = await upstream.text().catch(() => '');
- return error(res, 502, 'upstream_error', `LLM call failed: ${upstream.status} ${msg.slice(0, 200)}`);
+ if (err instanceof LlmUnavailableError) {
+ return error(res, 503, 'llm_unavailable', 'agent delegation is not available right now');
+ }
+ return error(res, 502, 'upstream_error', `LLM call failed: ${err.message}`);
}
- const data = await upstream.json().catch(() => ({}));
- const response = data?.content?.[0]?.text || '';
return json(res, 200, {
ok: true,
agentId: agent.id,
agentName: agent.name,
- response,
- model,
- usage: data?.usage || null,
+ response: result.text,
+ model: result.model,
+ usage: result.usage,
durationMs: Date.now() - started,
fetchedAt: new Date().toISOString(),
});
diff --git a/api/avatars/_actions.js b/api/avatars/_actions.js
index ef68f08dd..cfd239ff8 100644
--- a/api/avatars/_actions.js
+++ b/api/avatars/_actions.js
@@ -608,6 +608,67 @@ Given a screenshot of a 3D avatar, respond with ONLY a JSON object:
}
Respond with nothing else — no markdown, no explanation.`;
+// Classify an avatar thumbnail with a vision-capable model. Free OpenRouter
+// vision is preferred (platform-funded); Anthropic is used only as a BYOK
+// fallback when a server-side key is present. Throws { code: 'not_configured' }
+// when no vision provider is available so the caller can skip silently.
+async function classifyAvatarImage({ thumbUrl, prompt, env }) {
+ if (env.OPENROUTER_API_KEY) {
+ const r = await fetch('https://openrouter.ai/api/v1/chat/completions', {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ authorization: `Bearer ${env.OPENROUTER_API_KEY}`,
+ 'HTTP-Referer': 'https://three.ws',
+ 'X-Title': 'three.ws avatar auto-tag',
+ },
+ body: JSON.stringify({
+ model: 'meta-llama/llama-3.2-11b-vision-instruct',
+ max_tokens: 256,
+ messages: [
+ {
+ role: 'user',
+ content: [
+ { type: 'text', text: prompt },
+ { type: 'image_url', image_url: { url: thumbUrl } },
+ ],
+ },
+ ],
+ }),
+ });
+ if (!r.ok) throw Object.assign(new Error(`openrouter vision ${r.status}`), { code: 'vision_api_error' });
+ const d = await r.json();
+ return d.choices?.[0]?.message?.content || '';
+ }
+ if (env.ANTHROPIC_API_KEY) {
+ const r = await fetch('https://api.anthropic.com/v1/messages', {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ 'x-api-key': env.ANTHROPIC_API_KEY,
+ 'anthropic-version': '2023-06-01',
+ },
+ body: JSON.stringify({
+ model: 'claude-haiku-4-5-20251001',
+ max_tokens: 256,
+ messages: [
+ {
+ role: 'user',
+ content: [
+ { type: 'image', source: { type: 'url', url: thumbUrl } },
+ { type: 'text', text: prompt },
+ ],
+ },
+ ],
+ }),
+ });
+ if (!r.ok) throw Object.assign(new Error(`anthropic vision ${r.status}`), { code: 'vision_api_error' });
+ const d = await r.json();
+ return d.content?.[0]?.text || '';
+ }
+ throw Object.assign(new Error('no vision provider configured'), { code: 'not_configured' });
+}
+
const handleAutoTag = wrap(async (req, res) => {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
@@ -630,39 +691,22 @@ const handleAutoTag = wrap(async (req, res) => {
const { env } = await import('../_lib/env.js');
const thumbUrl = publicUrl(body.thumb_key);
- // Call Claude Haiku — cheapest, sufficient for image classification.
- const anthropicRes = await fetch('https://api.anthropic.com/v1/messages', {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- 'x-api-key': env.ANTHROPIC_API_KEY,
- 'anthropic-version': '2023-06-01',
- },
- body: JSON.stringify({
- model: 'claude-haiku-4-5-20251001',
- max_tokens: 256,
- messages: [
- {
- role: 'user',
- content: [
- { type: 'image', source: { type: 'url', url: thumbUrl } },
- { type: 'text', text: AVATAR_TAG_PROMPT },
- ],
- },
- ],
- }),
- });
-
- if (!anthropicRes.ok) {
- console.error('[auto-tag] anthropic error', await anthropicRes.text());
- return json(res, 200, { ok: false, reason: 'vision_api_error' });
+ // Image classification needs a vision-capable model. Per platform policy
+ // the free providers come first (OpenRouter hosts open vision models);
+ // Anthropic is BYOK and only used when a server-side key is present. When
+ // no vision provider is configured we skip auto-tagging rather than fail —
+ // it is an enhancement, not a required step.
+ let visionText;
+ try {
+ visionText = await classifyAvatarImage({ thumbUrl, prompt: AVATAR_TAG_PROMPT, env });
+ } catch (err) {
+ console.error('[auto-tag] vision error', err.message);
+ return json(res, 200, { ok: false, reason: err.code || 'vision_api_error' });
}
- const result = await anthropicRes.json();
let parsed;
try {
- const raw = result.content?.[0]?.text || '{}';
- parsed = JSON.parse(raw.trim());
+ parsed = JSON.parse((visionText || '{}').trim());
} catch {
return json(res, 200, { ok: false, reason: 'parse_error' });
}
diff --git a/api/bazaar/context.js b/api/bazaar/context.js
index b94b56c02..b8ca8e569 100644
--- a/api/bazaar/context.js
+++ b/api/bazaar/context.js
@@ -2,15 +2,16 @@
//
// Produces a Hunch-style "What's the context?" panel for a single x402
// service. We pull the merged catalog, locate the item, gather peers (same
-// capability and same provider), then ask Claude to write 2–3 sentences
-// grounded in inline [n] citations that the UI renders as chips.
+// capability and same provider), then ask an LLM to write 2–3 sentences
+// grounded in inline [n] citations that the UI renders as chips. Generation
+// runs on the free platform providers (Groq/OpenRouter); Anthropic is BYOK.
//
-// Falls back to a deterministic, citation-only summary if no
-// ANTHROPIC_API_KEY is configured or the upstream call fails — the panel
-// should always render something useful.
+// Falls back to a deterministic, citation-only summary if no LLM provider is
+// available or the upstream call fails — the panel should always render
+// something useful.
import { cors, json, error, wrap } from '../_lib/http.js';
-import { env } from '../_lib/env.js';
+import { llmComplete } from '../_lib/llm.js';
import { Bazaar } from '../_lib/x402/bazaar-client.js';
const STOP_WORDS = new Set([
@@ -218,37 +219,21 @@ ${citationLines}
Respond with only the JSON object.`;
- const apiKey = env.ANTHROPIC_API_KEY;
- if (!apiKey) throw new Error('no_anthropic_key');
-
- const upstream = await fetch('https://api.anthropic.com/v1/messages', {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- 'anthropic-version': '2023-06-01',
- 'x-api-key': apiKey,
- },
- body: JSON.stringify({
- model: 'claude-haiku-4-5-20251001',
- max_tokens: 400,
- temperature: 0.2,
- messages: [{ role: 'user', content: prompt }],
- }),
+ // Free platform providers (Groq/OpenRouter) handle this; Anthropic is BYOK.
+ // If no provider is available llmComplete throws, and the caller falls back
+ // to the deterministic summary — so the panel still renders.
+ const { text, provider } = await llmComplete({
+ system: 'You summarize x402 bazaar services. Respond with only the JSON object the prompt requests.',
+ user: prompt,
+ maxTokens: 400,
});
-
- if (!upstream.ok) {
- const body = await upstream.text().catch(() => '');
- throw new Error(`anthropic ${upstream.status}: ${body.slice(0, 200)}`);
- }
- const data = await upstream.json();
- const text = data?.content?.[0]?.text || '';
const match = text.match(/\{[\s\S]*\}/);
if (!match) throw new Error('no JSON in LLM response');
const parsed = JSON.parse(match[0]);
const summary = String(parsed.summary || '').trim();
if (!summary) throw new Error('empty summary');
const sentiment = ['up', 'down', 'neutral'].includes(parsed.sentiment) ? parsed.sentiment : 'neutral';
- return { summary, sentiment, citations, source: 'claude' };
+ return { summary, sentiment, citations, source: provider };
}
async function handler(req, res) {
diff --git a/api/chat.js b/api/chat.js
index de5e35ea8..7dcf1b8b5 100644
--- a/api/chat.js
+++ b/api/chat.js
@@ -5,10 +5,10 @@
//
// Provider routing (in order):
// 1. Body.provider when present and the matching key is configured.
-// 2. ANTHROPIC_API_KEY → Anthropic (default).
+// 2. GROQ_API_KEY → Groq (free platform key — default).
// 3. OPENROUTER_API_KEY → OpenRouter free tier.
-// 4. GROQ_API_KEY → Groq.
-// 5. OPENAI_API_KEY → OpenAI.
+// 4. OPENAI_API_KEY → OpenAI.
+// 5. ANTHROPIC_API_KEY → Anthropic (BYOK only — never set as a server key).
// Anthropic and the OpenAI-compatible providers (OpenRouter / Groq / OpenAI)
// use different request shapes, tool-call wire formats, and SSE event names —
// this file translates both directions so the client only sees the same
@@ -460,7 +460,7 @@ export default wrap(async (req, res) => {
function pickProvider(requested, model, userKeys = {}) {
const order = requested
? [requested, ...Object.keys(PROVIDERS).filter((p) => p !== requested)]
- : ['anthropic', 'openrouter', 'groq', 'openai'];
+ : ['groq', 'openrouter', 'openai', 'anthropic'];
for (const name of order) {
const cfg = PROVIDERS[name];
diff --git a/api/cron/[name].js b/api/cron/[name].js
index 2971341f3..ea53f0735 100644
--- a/api/cron/[name].js
+++ b/api/cron/[name].js
@@ -2989,14 +2989,11 @@ async function openaiCompatDraft({ url, key, model, system, user, max, extraHead
return data.choices?.[0]?.message?.content || '';
}
-// Draft short post text. Mirrors the documented env.js fallback order: prefer
-// Anthropic, then Groq, then OpenRouter — so persona/digest triggers keep working
-// whenever ANY LLM key is configured rather than hard-depending on ANTHROPIC_API_KEY.
+// Draft short post text. Groq and OpenRouter are free platform keys; Anthropic
+// is BYOK and only used if the operator has explicitly set it server-side.
async function llmDraft({ system, user, max = 200 }) {
let text;
- if (env.ANTHROPIC_API_KEY) {
- text = await anthropicDraft({ system, user, max });
- } else if (env.GROQ_API_KEY) {
+ if (env.GROQ_API_KEY) {
text = await openaiCompatDraft({
url: 'https://api.groq.com/openai/v1/chat/completions',
key: env.GROQ_API_KEY,
@@ -3011,8 +3008,10 @@ async function llmDraft({ system, user, max = 200 }) {
system, user, max,
extraHeaders: { 'HTTP-Referer': 'https://three.ws', 'X-Title': 'three.ws agent' },
});
+ } else if (env.ANTHROPIC_API_KEY) {
+ text = await anthropicDraft({ system, user, max });
} else {
- throw new Error('no LLM provider configured (set ANTHROPIC_API_KEY, GROQ_API_KEY, or OPENROUTER_API_KEY)');
+ throw new Error('no LLM provider configured (set GROQ_API_KEY or OPENROUTER_API_KEY)');
}
text = (text || '').trim();
if (text.startsWith('"') && text.endsWith('"')) text = text.slice(1, -1).trim();
diff --git a/api/insights/revenue-vision.js b/api/insights/revenue-vision.js
index b9f43c9d6..61ca78ff3 100644
--- a/api/insights/revenue-vision.js
+++ b/api/insights/revenue-vision.js
@@ -24,6 +24,7 @@ import {
resolveResourceUrl,
} from '../_lib/x402-spec.js';
import { env } from '../_lib/env.js';
+import { llmComplete, LlmUnavailableError } from '../_lib/llm.js';
import {
PAYMENT_IDENTIFIER,
checkCache,
@@ -150,36 +151,12 @@ const SYSTEM_PROMPT =
'Calibrate confidence honestly: "high" only when you can defend the claim, otherwise "medium" or "low". ' +
'No prose, no markdown, no preamble.';
-async function callClaude(missionBrief, agentCodename) {
- const upstream = await fetch('https://api.anthropic.com/v1/messages', {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- 'anthropic-version': '2023-06-01',
- 'x-api-key': env.ANTHROPIC_API_KEY,
- },
- body: JSON.stringify({
- model: 'claude-sonnet-4-6',
- max_tokens: 800,
- system: SYSTEM_PROMPT,
- messages: [
- {
- role: 'user',
- content: `Caller agent: ${agentCodename}\nMission brief: ${missionBrief}\n\nReturn the JSON object only.`,
- },
- ],
- }),
- signal: AbortSignal.timeout(20_000),
+async function callLlm(missionBrief, agentCodename) {
+ const { text } = await llmComplete({
+ system: SYSTEM_PROMPT,
+ user: `Caller agent: ${agentCodename}\nMission brief: ${missionBrief}\n\nReturn the JSON object only.`,
+ maxTokens: 800,
});
- if (!upstream.ok) {
- const errText = await upstream.text();
- const e = new Error(`Claude returned ${upstream.status}: ${errText.slice(0, 300)}`);
- e.status = 502;
- e.code = 'upstream_error';
- throw e;
- }
- const data = await upstream.json();
- const text = data?.content?.find?.((b) => b.type === 'text')?.text || '';
const match = text.match(/\{[\s\S]*\}/);
const parsed = JSON.parse(match ? match[0] : text);
const allowedConfidence = new Set(['high', 'medium', 'low']);
@@ -258,8 +235,11 @@ export default wrap(async (req, res) => {
let result;
try {
- result = await callClaude(missionBrief, agentCodename);
+ result = await callLlm(missionBrief, agentCodename);
} catch (err) {
+ if (err instanceof LlmUnavailableError) {
+ return error(res, 503, 'llm_unavailable', 'revenue vision is not available right now');
+ }
return error(res, err.status || 502, err.code || 'upstream_error', err.message);
}
diff --git a/api/seed/synthesize.js b/api/seed/synthesize.js
index fc34db48b..3788a68f8 100644
--- a/api/seed/synthesize.js
+++ b/api/seed/synthesize.js
@@ -13,7 +13,7 @@ import { z } from 'zod';
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
import { parse } from '../_lib/validate.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
-import { env } from '../_lib/env.js';
+import { llmComplete, LlmUnavailableError } from '../_lib/llm.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
const bodySchema = z
@@ -126,39 +126,22 @@ export default wrap(async (req, res) => {
`${sourcesUsed.length === 1 ? 'account' : 'accounts'}:\n\n` +
JSON.stringify(sources, null, 2);
- const anthropicRes = await fetch('https://api.anthropic.com/v1/messages', {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- 'x-api-key': env.ANTHROPIC_API_KEY,
- 'anthropic-version': '2023-06-01',
- },
- body: JSON.stringify({
- model: 'claude-haiku-4-5-20251001',
- max_tokens: 1024,
- system: SYSTEM_PROMPT,
- messages: [{ role: 'user', content: userMessage }],
- }),
- });
-
- if (!anthropicRes.ok) {
- const detail = await anthropicRes.text().catch(() => '');
- console.error('[seed/synthesize] anthropic error', anthropicRes.status, detail.slice(0, 400));
- return error(res, 502, 'upstream_error', `synthesis failed (${anthropicRes.status})`);
+ let result;
+ try {
+ result = await llmComplete({ system: SYSTEM_PROMPT, user: userMessage, maxTokens: 1024 });
+ } catch (err) {
+ if (err instanceof LlmUnavailableError) {
+ return error(res, 503, 'llm_unavailable', 'synthesis is not available right now');
+ }
+ console.error('[seed/synthesize] LLM error', err.status || '', err.message);
+ return error(res, 502, 'upstream_error', 'synthesis failed');
}
- const result = await anthropicRes.json();
- const memorySeed = (result.content || [])
- .filter((b) => b.type === 'text')
- .map((b) => b.text)
- .join('\n')
- .trim();
-
+ const memorySeed = result.text;
if (!memorySeed)
return error(res, 502, 'empty_synthesis', 'model returned no text content');
- const usage = result.usage || {};
- const tokensUsed = (usage.input_tokens || 0) + (usage.output_tokens || 0);
+ const tokensUsed = result.usage.input + result.usage.output;
return json(res, 200, {
ok: true,
@@ -166,9 +149,9 @@ export default wrap(async (req, res) => {
sources_used: sourcesUsed,
tokens_used: tokensUsed,
usage: {
- input_tokens: usage.input_tokens || 0,
- output_tokens: usage.output_tokens || 0,
+ input_tokens: result.usage.input,
+ output_tokens: result.usage.output,
},
- model: result.model || 'claude-haiku-4-5-20251001',
+ model: result.model,
});
});
diff --git a/api/x/draft.js b/api/x/draft.js
index e1a81feff..23dc675ef 100644
--- a/api/x/draft.js
+++ b/api/x/draft.js
@@ -5,7 +5,7 @@
import { sql } from '../_lib/db.js';
import { getSessionUser } from '../_lib/auth.js';
import { cors, method, wrap, error, readJson, json } from '../_lib/http.js';
-import { env } from '../_lib/env.js';
+import { llmComplete, LlmUnavailableError } from '../_lib/llm.js';
const MAX_TWEET_LEN = 280;
@@ -40,29 +40,18 @@ Output ONLY the tweet text, nothing else.`;
prompt ? `What to post about: ${prompt}` : 'Write something engaging about being an autonomous AI agent.',
].filter(Boolean).join('\n\n');
- const upstream = await fetch('https://api.anthropic.com/v1/messages', {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- 'anthropic-version': '2023-06-01',
- 'x-api-key': env.ANTHROPIC_API_KEY,
- },
- body: JSON.stringify({
- model: 'claude-haiku-4-5-20251001',
- max_tokens: 200,
- system,
- messages: [{ role: 'user', content: userPrompt }],
- }),
- });
-
- if (!upstream.ok) {
- const detail = await upstream.text();
- console.error('[x-draft] LLM failed', upstream.status, detail);
+ let result;
+ try {
+ result = await llmComplete({ system, user: userPrompt, maxTokens: 200 });
+ } catch (err) {
+ if (err instanceof LlmUnavailableError) {
+ return error(res, 503, 'llm_unavailable', 'draft generation is not available right now');
+ }
+ console.error('[x-draft] LLM failed', err.status || '', err.message);
return error(res, 502, 'llm_failed', 'draft generation failed');
}
- const data = await upstream.json();
- let text = (data.content?.[0]?.text || '').trim();
+ let text = result.text;
if (text.startsWith('"') && text.endsWith('"')) text = text.slice(1, -1).trim();
if (text.length > MAX_TWEET_LEN) text = text.slice(0, MAX_TWEET_LEN - 1) + '…';
diff --git a/tasks/wow-sprint/REPORT-01-audit.md b/tasks/wow-sprint/REPORT-01-audit.md
new file mode 100644
index 000000000..e1cb367c4
--- /dev/null
+++ b/tasks/wow-sprint/REPORT-01-audit.md
@@ -0,0 +1,97 @@
+# REPORT 01 — Bug & Lazy-Code Audit (three.ws)
+
+Date: 2026-05-29. Scope: live frontend (`src/`), API functions (`api/`), entry
+pages. Diagnosis only — no code changed. Sources: grep smell sweep, `npx knip`,
+full reads of high-traffic frontend modules and the token/pump API surface, with
+the two P0 claims verified directly against source.
+
+## Health summary
+
+The code is broadly solid — parameterized SQL, auth correctly gating
+`revenue-share`, consistent `api/_lib/http.js` boundaries in most handlers. The
+real problem is concentrated and consequential: **the live $three / pump data
+pipeline is broken end-to-end.** The pump dashboard calls Birdeye with an
+undefined API key, the trades SSE stream uses a wrong callback contract and emits
+nothing, and the avatar trade-reaction feature listens for an event the server
+never sends. These three are load-bearing for the "wow" feature tasks (12, 13,
+16), so they must be fixed first. Secondary theme: unguarded `await res.json()` /
+direct field access on upstream (Birdeye/Helius) responses that throw on partial
+data, plus a leaking `Act2Viewer` WebGL context on the home page.
+
+## Top 10 — fix first
+
+1. **Pump dashboard Birdeye key undefined** — `api/pump/dashboard.js:6` (P0)
+2. **Trades SSE stream wrong contract + emits nothing** — `api/pump/trades-stream.js:17-25` (P0)
+3. **Avatar trade reactions dead — `trade` event never emitted** — `src/pump/trade-reactions.js:66-68` + `api/agents/pumpfun.js` (P0)
+4. **Home on-chain stat always null — field name mismatch** — `src/home-v4-scroll.js:39` (P1)
+5. **`Act2Viewer` leaks WebGL context — no dispose** — `src/home-act2-viewer.js:80` (P2→P1 on home)
+6. **pump/dashboard.js render throws on partial Birdeye data** — `src/pump/dashboard.js:19-23` (P1)
+7. **three-token `burns`/`activity` return revenue rows relabeled as burns + hardcoded `total_burned:0`** — `api/three-token/[action].js:68-94,167-192` (P2, but it's shipped fake data)
+8. **three-token agent-count query missing `.catch` — 500s the whole stats endpoint** — `api/three-token/[action].js:56` (P1)
+9. **Birdeye error/empty responses cached for 60s** — `api/pump/dashboard.js:14-33` (P1)
+10. **Hardcoded 1B supply fallback fabricates `per_token_yield`** — `api/three-token/[action].js:150` (P2)
+
+---
+
+## Findings — API surface
+
+| # | Sev | File:line | Category | What's wrong | Suggested fix |
+|---|-----|-----------|----------|--------------|---------------|
+| A1 | P0 | api/pump/dashboard.js:6,52 | bug | `env.BIRDEYE_API_KEY` — no such getter on `env` (verified absent in `api/_lib/env.js`); sends `X-API-KEY: undefined` → all Birdeye calls 401. `three-token` does it right via `process.env.BIRDEYE_API_KEY`. | Read `process.env.BIRDEYE_API_KEY` (or add an `opt('BIRDEYE_API_KEY')` getter to env.js). |
+| A2 | P0 | api/pump/trades-stream.js:17-25 | bug | Calls `connectPumpFunFeed({onTrade,onError,onClose})` and destructures `{close}`, but the fn takes `{onEvent,signal,kind}` and returns a bare `stop`. Callbacks never fire; `req.on('close', close)` registers `undefined`. | Use `onEvent:({kind,data})=>…`; `const stop = connectPumpFunFeed(...)`; `req.on('close', stop)`. |
+| A3 | P0 | api/pump/trades-stream.js:18-21 | bug | Filters `trade.is_buy`, but the upstream feed never produces trade events (only mint/graduation) — stream emits nothing but pings. | Subscribe to a real trade source, or repurpose to forward mint/graduation. |
+| A4 | P1 | api/three-token/[action].js:56 | broken-boundary | The `agent_identities` count query has no `.catch` (unlike the other two); if it fails, `stats` AND `revenue-share` 500. | `.catch(()=>[{total:0}])` for parity. |
+| A5 | P1 | api/pump/dashboard.js:62 | broken-boundary | `history.data.items` assumes Birdeye shape; `data:null` or different shape throws → 502. | `history?.data?.items ?? []`. |
+| A6 | P1 | api/pump/dashboard.js:14-33 | bug | `fetchWithCache` caches by URL only; empty/error `{data:null}` bodies cached 60s and reused. | Cache only `resp.ok` with non-null `data`. |
+| A7 | P2 | api/three-token/[action].js:68-94,167-192 | lazy-code | `burns` queries `agent_revenue_events` (revenue, not burns) and returns hardcoded `total_burned:0`, `burn_rate_per_agent:1000`; `activity` relabels revenue as burns. Comment claims "real on-chain burn events." | Wire a real burn source or rename + drop the hardcoded numbers. |
+| A8 | P2 | api/three-token/[action].js:150 | lazy-code | `totalSupply = ov.supply ?? 1_000_000_000` — fabricated 1B fallback drives `per_token_yield` when Birdeye is down. | Omit `per_token_yield` when supply unknown. |
+| A9 | P2 | api/three-token/[action].js:134-135 | lazy-code | `revenue_share_pool_pct:10`, `agent_deploy_burn:1000` hardcoded inline. | Hoist to named config consts (ok if truly fixed params). |
+| A10 | P2 | api/pump/helius-stats.js:32-35 | bug | Reports `enabled:false` based on `SOLANA_RPC_URL.includes('helius-rpc.com')`, but doc says it keys off `HELIUS_API_KEY`; misreports for key-only/other-host configs. | Detect via `HELIUS_API_KEY` or fix the comment. |
+| A11 | P3 | api/pump/dashboard.js:23 | security | Throws Error embedding full upstream body (logged server-side only). | `text.slice(0,200)` like three-token. |
+| A12 | P3 | api/_lib/db.js | lazy-code | Retrying `query()` exported but unused; endpoints use the non-retrying `sql` proxy. | Adopt `query()` or remove. |
+
+No SQL injection found (tagged-template params throughout). No leaked secrets in
+client responses. `revenue-share` correctly requires auth; `dashboard` scopes by `user_id`.
+
+## Findings — Frontend
+
+| # | Sev | File:line | Category | What's wrong | Suggested fix |
+|---|-----|-----------|----------|--------------|---------------|
+| F1 | P0 | src/pump/trade-reactions.js:66-68 | bug | Subscribes `kind=trades` and listens for `trade`; the feed (`api/agents/pumpfun.js`) only handles `claims/graduations/token/creator` and never emits `trade`. Buy/sell reactions + the whole percentile buffer are dead. | Emit `trade` server-side (with a real trade source), or listen for an event the feed actually sends. |
+| F2 | P1 | src/home-v4-scroll.js:39 | bug | Reads `data.onchain`; `/api/home-stats` returns `onchain_agents`. On-chain stat never populates. | `data.onchain_agents ?? data.onchain`. |
+| F3 | P1 | src/pump/dashboard.js:19-23 | broken-boundary | `data.price?.value.toFixed(6)` (optional chain then unconditional `.value`), `data.history.map`, `tx.side/amount/priceUsd` all unguarded — partial Birdeye data throws mid-render. | Null-check each field; `(data.history||[])`. |
+| F4 | P1 | src/home-act2-viewer.js:80 | bug | Unconditional `requestAnimationFrame` loop, no visibility gate, no `dispose()` — leaves a running renderer + WebGL context when leaving the section. | Add `dispose()` that cancels raf + disposes renderer; gate on `_disposed`. |
+| F5 | P2 | src/pump/dashboard.js:16 | broken-boundary | `await resp.json()` on the error path with no catch — non-JSON 500 body throws before the error message builds. | `.catch(()=>({}))`. |
+| F6 | P2 | src/agent-home.js:498 | bug | `_renderMemoryBar` derefs `this.identity.memory.stats.total`; throws if `memory` set but `stats` undefined. | `if (!stats || !stats.total) return`. |
+| F7 | P2 | src/agent-home.js:569 | broken-boundary | `_startEmotionPoll` `Object.entries(this.avatar.emotionState)` every 1s; throws if `emotionState` null mid-swap. | Guard null before `Object.entries`. |
+| F8 | P2 | src/agent-home-pumpfun.js:683 | bug | `setInterval(... refresh())` unawaited; overlapping slow refreshes race and clobber `state`. | In-flight flag to skip overlap. |
+| F9 | P2 | src/marketplace.js:429-430 | broken-boundary | `loadList` parses `r.json()` with no `r.ok` check (inconsistent with sibling loaders); 500 HTML throws generic error. | `if(!r.ok) throw` before `.json()`. |
+| F10 | P2 | src/wallet-auth.js:147 | bug | "No wallet" gate checks `window.ethereum`, but connect may use a different provider; non-`window.ethereum` users wrongly told to install MetaMask. | Delegate detection to `ensureWallet`/registry. |
+| F11 | P3 | src/home-v4-hero.js:120; home-v4-scroll.js:57 | bug | IntersectionObserver uses `entries[0]` only; batched entries on fast scroll use a stale entry. | Iterate entries or `entries.at(-1)`. |
+| F12 | P3 | src/marketplace.js:1108-1111 | bug | Modal 3D `Loading…` overlay has no error/timeout state; stays forever on CORS/404. | Add `error` listener to swap to error state. |
+| F13 | P3 | src/marketplace.js:599-600 | broken-boundary | `renderTheme` writes to `$('market-theme-title')` etc. without null-guarding child nodes; throws + half-renders if absent. | Null-check each node. |
+
+## knip (dead code / unused deps)
+
+- **27 unused files**, almost all under `character-studio/**` (a sub-app) — low priority, but worth a cleanup pass scoped to that package.
+- **75 unused dependencies** across `package.json` and sub-package manifests (e.g. `@solana/wallet-adapter-*`, `ethers`, `livepeer`, `colyseus`, `graphql`, `node-fetch`, many `@x402/*`). Verify against dynamic imports before removing — knip can miss runtime-only deps. Trimming these shrinks install + supply-chain surface.
+- **11 unused devDependencies**. Safe-ish to prune after a build check.
+
+> Treat knip output as a candidate list, not gospel — confirm each removal with a grep + a clean `npm run build` before deleting.
+
+## Grep smell sweep — result
+
+- `TODO/FIXME/not implemented/mockData/sampleData` in shipped `src`+`api`+`pages`: **effectively zero real violations.** The only `not implemented` is a legit runtime error message in `api/pump-fun-mcp.js:209` for unknown MCP tools. CLAUDE.md's no-stub rule is largely being honored.
+- "placeholder" hits are legitimate — CSS class names, input placeholder text, and designed UI fallbacks (avatar initials, etc.), not fake data.
+- `setTimeout` near "load/progress": all real (reload-after-success, load timeouts, deferred re-fetch). No fake progress bars found.
+- Empty `catch {}`: all benign cleanup (`sessionStorage`, `bitmap.close()`, `URL` parse). No swallowed network/logic errors at boundaries.
+
+The shipped-fake-data problem is **not** in the frontend — it's the relabeled
+revenue-as-burns and hardcoded supply/yield numbers in `api/three-token` (A7, A8).
+
+## Recommended sequencing
+
+Fix the P0 data-pipeline cluster (A1, A2, A3, F1) before starting feature tasks
+12/13/16 — those tasks assume live trades and a working Birdeye key. Then F2–F5
+(home + dashboard render robustness), then the three-token honesty fixes (A7, A8)
+which task 17 also depends on.