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(observability): first-party client error reporting + chat model routing updates

nirholase482dc9c9c75
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c001cd8d4..d9f635f54 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,7 +7,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-06-11
- **Avatar pages back online after image-engine outage** — Fetching an individual avatar was failing with a server error, which also broke the walking avatar on the home page. The image-processing engine the avatar dress-up baker relies on failed to load in production and took the whole endpoint down with it. Avatar lookups now load independently of the baker, and the missing image libraries ship with the deployment, so avatar pages and the home hero are back. `[fix, infra]`
-- **Built-in AI stays up when a provider account runs dry** — The platform's built-in AI (chat, tutor, fact-checker, persona tools) now rotates across multiple OpenRouter accounts: when one account runs out of credits or hits a rate limit, the next takes over automatically, before any of the response has streamed. Paid x402 endpoints that previously returned errors during a provider outage now degrade to a backup account instead of failing. `[improvement, infra]`
+- **Built-in AI stays up when a provider runs dry** — The platform's built-in AI (chat, tutor, fact-checker, persona tools, agent talk) now runs on a deeper safety net. Three independent free lanes — Groq, OpenRouter (with automatic rotation across multiple accounts when one runs out of credits or hits a rate limit), and NVIDIA-hosted models — always serve first, and if every one of them fails, the request quietly falls through to a paid backstop instead of showing you an error. Paid x402 endpoints that previously returned errors during a provider outage now degrade the same way. `[improvement, infra]`
- **Faster, quieter agents directory and site-wide page polish** — The on-chain agents directory now loads from our server-side index instead of contacting every agent's metadata host from your browser — pages render faster and no longer spray network errors. Also: the pump.fun cockpit's sidebar pages are now shareable deep links, mobile nav and footer links meet touch-target guidelines, anonymous visitors no longer trigger failed sign-in requests on Walk and Create, and assorted dead links were removed. (`/agents`) `[improvement, fix]`
- **Live $THREE market data, longer trade streams, and tutor session fixes** — $THREE market stats (price, holders, liquidity) are flowing again from our primary data source — a missing request header had been silently failing it to backups for days. Live trade streams no longer cut out after 30 seconds; they now run their full duration. The Pay-As-You-Learn Tutor no longer errors when resuming a session — running tabs persist correctly across questions — and Fact Checker results are cached properly so repeat checks of the same claim return instantly. `[fix, improvement]`
- **Scheduled jobs restored after dependency outage** — Every background job — pump.fun monitoring, coin payouts, club payouts, scheduled X posts, DCA runs, subscription billing, and the rest — had been failing since a recent dependency upgrade left a required Solana staking library out of the deployment. The missing library now ships with every deploy, and the image-processing engine behind avatar baking was rolled back to its proven version so it loads reliably in production. All scheduled jobs run again. `[fix, infra]`
diff --git a/api/_lib/agent-delegate.js b/api/_lib/agent-delegate.js
index 09f8212ee..30b899974 100644
--- a/api/_lib/agent-delegate.js
+++ b/api/_lib/agent-delegate.js
@@ -41,10 +41,9 @@ export async function runAgentDelegation({ toAgentId, message }) {
system: systemPrompt,
user: message,
maxTokens: 1024,
+ // Free providers serve first; if every one fails, the paid backstop
+ // uses the agent's chosen Claude model on the platform key.
anthropicModel: model,
- // Lead with the agent's chosen Claude model on the platform key, then
- // degrade to the free providers if it's unset or Anthropic is down.
- serverAnthropic: true,
track: { agentId: toAgentId, tool: 'agent.delegate' },
});
return { response: result.text, agentId: toAgentId, model: result.model };
diff --git a/api/_lib/chat-models.js b/api/_lib/chat-models.js
index 2dc745dbe..7cf7f1046 100644
--- a/api/_lib/chat-models.js
+++ b/api/_lib/chat-models.js
@@ -3,12 +3,15 @@
//
// Two design rules drive this file:
//
-// 1. RELIABILITY-FIRST ORDERING. The fallback ladder leads with the model
-// that actually answers on the first attempt under current operating
-// conditions, not the cheapest model. Leading with rate-limited free
-// models meant the common path was "try 3-4 things that 429/404, then
-// finally succeed" — paying full fan-out latency and burning quota on
-// every turn. Free models are kept as *lower-priority* fallbacks.
+// 1. FREE PROVIDERS FIRST, ALWAYS. The platform holds three free-tier keys —
+// Groq (fastest, first-attempt-reliable), OpenRouter (:free models), and
+// NVIDIA NIM (one nvapi key, 100+ hosted models) — and the ladder leads
+// with them in that order. Paid providers (Anthropic, OpenAI) are
+// LAST-RESORT backstops only: the prod paid keys are routinely invalid
+// (Anthropic 401) or out of quota (OpenAI), so any ordering that leads
+// with them burns a doomed attempt on every request. With three
+// independent free lanes, a request should never surface a provider
+// error to the user.
//
// 2. CAPABILITY-AWARE ROUTING. Every model is annotated with what it can do
// ({ tools, moderationGated }). The router consults MODEL_CATALOG and
@@ -21,12 +24,10 @@
// - mistralai/mistral-7b-instruct:free → OpenRouter 404 "No endpoints found"
// - meta-llama/llama-3.2-3b-instruct:free → no tool-capable endpoint
//
-// Operational note (ops must act): the OpenAI account is over quota
-// ("You exceeded your current quota, please check your plan and billing"), so
-// `openai` is intentionally ranked LAST — it is effectively a dead final tier
-// until billing is topped up. Until then it only burns one wasted attempt at
-// the very end of an already-exhausted chain. Top up OPENAI billing or remove
-// the key to drop it from the ladder entirely.
+// Operational note (ops must act): the OpenAI account is over quota and the
+// prod Anthropic key 401s. Both are intentionally ranked at the very END of
+// the ladder — dead final tiers that only burn an attempt after every free
+// lane is exhausted. Fix the keys or remove them to drop them entirely.
/**
* Capability metadata per chat model id — the routing brain. Only models
@@ -65,6 +66,10 @@ export const MODEL_CATALOG = {
// never auto-selected for the primary path or auto-built fallback chains.
'openai/gpt-oss-120b:free': { provider: 'openrouter', tools: true, moderationGated: true },
+ // ── NVIDIA NIM free tier — one nvapi key, OpenAI-compatible ───────────────
+ 'meta/llama-3.3-70b-instruct': { provider: 'nvidia', tools: true },
+ 'nvidia/llama-3.3-nemotron-super-49b-v1.5': { provider: 'nvidia', tools: true },
+
// ── OpenAI (paid) — see operational note above; ranked last ───────────────
'gpt-4o-mini': { provider: 'openai', tools: true },
};
@@ -108,27 +113,29 @@ export const PROVIDER_MODEL_DEFAULTS = {
anthropic: 'claude-sonnet-4-6',
openrouter: DEFAULT_FREE_MODEL,
groq: 'llama-3.3-70b-versatile',
+ nvidia: 'meta/llama-3.3-70b-instruct',
openai: 'gpt-4o-mini',
};
/**
- * Provider order to try when none is explicitly requested ("auto"), ranked by
- * first-attempt reliability under current operating conditions:
- * 1. anthropic — paid, highly reliable, keyed in prod (host we-pay / BYOK).
- * Leads the ladder so the common path resolves on attempt 0
- * instead of burning the free tiers' rate limits first. Only
- * present when a key is configured; skipped otherwise, which
- * transparently falls back to the free-tier ordering below.
- * 2. groq — fast free tier that answers on the first attempt. Per-minute
- * caps only; the primary for anonymous/free traffic.
- * 3. openrouter — free fallback (reliable Llama 3.3 70B; see DEFAULT_FREE_MODEL).
- * 4. openai — LAST. Account is over quota (see operational note); only
- * reached after everything else is exhausted.
+ * Provider order to try when none is explicitly requested ("auto"). Free
+ * providers always lead; paid keys are last-resort backstops (see design rule
+ * 1 above — the prod paid keys are routinely dead, and three independent free
+ * lanes must absorb everything):
+ * 1. groq — fastest free tier, answers on the first attempt. Per-minute
+ * caps only; the primary for all traffic.
+ * 2. openrouter — free :free models (reliable Llama 3.3 70B; see
+ * DEFAULT_FREE_MODEL), multi-key rotation in llm.js.
+ * 3. nvidia — NVIDIA NIM free tier; an independent third lane on a
+ * different account/infra than the first two.
+ * 4. anthropic — paid backstop; only reached when every free lane failed
+ * (and currently 401s in prod — see operational note).
+ * 5. openai — paid backstop; account over quota (see operational note).
* Providers without a configured key are skipped, so the effective ladder is
* short in the common case. A provider in a health cooldown (see
* api/_lib/provider-health.js) is also skipped for the cooldown window.
*/
-export const DEFAULT_PROVIDER_ORDER = ['anthropic', 'groq', 'openrouter', 'openai'];
+export const DEFAULT_PROVIDER_ORDER = ['groq', 'openrouter', 'nvidia', 'anthropic', 'openai'];
/**
* OpenRouter sibling models for per-model rate-limit failover. OpenRouter's
@@ -142,7 +149,7 @@ export const OPENROUTER_SIBLINGS = [
];
/** Providers an anonymous (unauthenticated) caller may use — free tiers only. */
-export const ANON_PROVIDER_LIST = ['groq', 'openrouter'];
+export const ANON_PROVIDER_LIST = ['groq', 'openrouter', 'nvidia'];
/**
* Bounds on the fallback chain so a single request can't churn through every
@@ -156,6 +163,6 @@ export const ANON_PROVIDER_LIST = ['groq', 'openrouter'];
* the fetch at this bound (or the remaining budget,
* whichever is smaller) and fail over to the next route.
*/
-export const MAX_FALLBACK_ATTEMPTS = 3;
+export const MAX_FALLBACK_ATTEMPTS = 4;
export const TOTAL_BUDGET_MS = 25_000;
export const PER_CALL_TIMEOUT_MS = 15_000;
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index f73417049..71fa1e391 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -307,6 +307,11 @@ export const limits = {
snsResolve: (ip) => getLimiter('sns:resolve:ip', { limit: 60, window: '1 m' }).limit(ip),
// Generic public read endpoints (explore, showcase, public agent fetch). 60/min per IP.
publicIp: (ip) => getLimiter('public:ip', { limit: 60, window: '1 m' }).limit(ip),
+ // Client-side error report ingestion (api/client-errors). The browser
+ // reporter batches and caps itself at 25 events/page, so legitimate traffic
+ // is a handful of requests per pageview even on a broken page; 30/min per
+ // IP absorbs that while keeping log-flooding abuse bounded.
+ clientErrorsIp: (ip) => getLimiter('client-errors:ip', { limit: 30, window: '1 m' }).limit(ip),
// Publishing a /play build to a coin's featured surface (R20). Each write stores
// a screenshot in Redis, so cap the burst per IP to keep that bounded; reads use
// the generic publicIp bucket.
diff --git a/api/agent-trade/demo.js b/api/agent-trade/demo.js
index b88ad070e..f5759088f 100644
--- a/api/agent-trade/demo.js
+++ b/api/agent-trade/demo.js
@@ -26,6 +26,7 @@ import {
LAMPORTS_PER_SOL,
} from '../_lib/avatar-wallet.js';
import { watsonxConfig, watsonxChatComplete } from '../_lib/watsonx.js';
+import { llmComplete } from '../_lib/llm.js';
import { cors, method, json, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
@@ -63,49 +64,41 @@ function tradeEnv() {
}
async function generateAnalysis(topic) {
+ // Granite leads when configured, but a watsonx outage degrades to the
+ // platform LLM chain below instead of killing the demo tick.
const wx = watsonxConfig();
if (wx.configured) {
- const messages = [
- {
- role: 'user',
- content: `Provide a concise 2–3 sentence crypto market insight on: ${topic}. Be specific, data-driven, and actionable.`,
- },
- ];
- const { text } = await watsonxChatComplete(wx, {
- messages,
- maxTokens: 200,
- temperature: 0.7,
- });
- return {
- content: text?.trim() || '',
- model: wx.chatModel || 'ibm/granite-3-8b-instruct',
- provider: 'IBM Granite',
- };
+ try {
+ const messages = [
+ {
+ role: 'user',
+ content: `Provide a concise 2–3 sentence crypto market insight on: ${topic}. Be specific, data-driven, and actionable.`,
+ },
+ ];
+ const { text } = await watsonxChatComplete(wx, {
+ messages,
+ maxTokens: 200,
+ temperature: 0.7,
+ });
+ return {
+ content: text?.trim() || '',
+ model: wx.chatModel || 'ibm/granite-3-8b-instruct',
+ provider: 'IBM Granite',
+ };
+ } catch (err) {
+ console.warn(`[agent-trade:demo] watsonx failed (${err?.message}); falling back to platform LLM chain`);
+ }
}
- const key = process.env.ANTHROPIC_API_KEY;
- if (!key) throw new Error('No AI backend — set WATSONX_API_KEY or ANTHROPIC_API_KEY');
- const resp = await fetch('https://api.anthropic.com/v1/messages', {
- method: 'POST',
- headers: {
- 'x-api-key': key,
- 'anthropic-version': '2023-06-01',
- 'content-type': 'application/json',
- },
- body: JSON.stringify({
- model: 'claude-haiku-4-5-20251001',
- max_tokens: 200,
- system: 'You are a concise crypto market analyst. Respond in 2–3 sharp sentences.',
- messages: [{ role: 'user', content: `Market insight on: ${topic}` }],
- }),
+ // Platform LLM policy (api/_lib/llm.js): free providers first, paid keys as
+ // the automatic last resort — a dead Anthropic key must not kill the demo.
+ const { text, model, provider } = await llmComplete({
+ system: 'You are a concise crypto market analyst. Respond in 2–3 sharp sentences.',
+ user: `Market insight on: ${topic}`,
+ maxTokens: 200,
+ track: { tool: 'agent-trade.demo' },
});
- if (!resp.ok) throw new Error(`Anthropic API error ${resp.status}`);
- const j = await resp.json();
- return {
- content: j.content?.[0]?.text?.trim() || '',
- model: 'claude-haiku-4-5-20251001',
- provider: 'Claude Haiku',
- };
+ return { content: text, model, provider };
}
function sleep(ms) {
diff --git a/api/agent-trade/skill.js b/api/agent-trade/skill.js
index bc7d3e09d..0d31a94e6 100644
--- a/api/agent-trade/skill.js
+++ b/api/agent-trade/skill.js
@@ -11,6 +11,7 @@
import { loadAvatarKeypair, getConnection, LAMPORTS_PER_SOL } from '../_lib/avatar-wallet.js';
import { watsonxConfig, watsonxChatComplete } from '../_lib/watsonx.js';
+import { llmComplete } from '../_lib/llm.js';
import { cors, method, json, error, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { cacheGet, cacheSet, cacheDel } from '../_lib/cache.js';
@@ -119,53 +120,42 @@ async function verifyPayment(connection, sig, { sellerAddress, priceLamports, bu
}
async function generateAnalysis(topic) {
+ // The buyer has already paid on-chain by the time this runs — a watsonx
+ // outage must not turn their purchase into an error, so a Granite failure
+ // degrades to the platform LLM chain below instead of propagating.
const wx = watsonxConfig();
if (wx.configured) {
- const messages = [
- {
- role: 'user',
- content: `Provide a concise 2–3 sentence crypto market insight on: ${topic}. Be specific, data-driven, and actionable.`,
- },
- ];
- const { text } = await watsonxChatComplete(wx, {
- messages,
- maxTokens: 200,
- temperature: 0.7,
- });
- return {
- content: text?.trim() || '',
- model: wx.chatModel || 'ibm/granite-3-8b-instruct',
- provider: 'IBM Granite',
- };
+ try {
+ const messages = [
+ {
+ role: 'user',
+ content: `Provide a concise 2–3 sentence crypto market insight on: ${topic}. Be specific, data-driven, and actionable.`,
+ },
+ ];
+ const { text } = await watsonxChatComplete(wx, {
+ messages,
+ maxTokens: 200,
+ temperature: 0.7,
+ });
+ return {
+ content: text?.trim() || '',
+ model: wx.chatModel || 'ibm/granite-3-8b-instruct',
+ provider: 'IBM Granite',
+ };
+ } catch (err) {
+ console.warn(`[agent-trade:skill] watsonx failed (${err?.message}); falling back to platform LLM chain`);
+ }
}
- const key = process.env.ANTHROPIC_API_KEY;
- if (!key) {
- throw new Error('No AI backend configured — set WATSONX_API_KEY or ANTHROPIC_API_KEY');
- }
- const resp = await fetch('https://api.anthropic.com/v1/messages', {
- method: 'POST',
- headers: {
- 'x-api-key': key,
- 'anthropic-version': '2023-06-01',
- 'content-type': 'application/json',
- },
- body: JSON.stringify({
- model: 'claude-haiku-4-5-20251001',
- max_tokens: 200,
- system: 'You are a concise crypto market analyst. Respond in 2–3 sharp sentences.',
- messages: [{ role: 'user', content: `Market insight on: ${topic}` }],
- }),
+ // Platform LLM policy (api/_lib/llm.js): free providers first, paid keys as
+ // the automatic last resort — a dead Anthropic key must not fail a paid call.
+ const { text, model, provider } = await llmComplete({
+ system: 'You are a concise crypto market analyst. Respond in 2–3 sharp sentences.',
+ user: `Market insight on: ${topic}`,
+ maxTokens: 200,
+ track: { tool: 'agent-trade.skill' },
});
- if (!resp.ok) {
- throw new Error(`Anthropic API returned ${resp.status}`);
- }
- const j = await resp.json();
- return {
- content: j.content?.[0]?.text?.trim() || '',
- model: 'claude-haiku-4-5-20251001',
- provider: 'Claude Haiku',
- };
+ return { content: text, model, provider };
}
export default wrap(async (req, res) => {
diff --git a/api/agents/talk.js b/api/agents/talk.js
index 9039089e2..1b183deb8 100644
--- a/api/agents/talk.js
+++ b/api/agents/talk.js
@@ -104,10 +104,9 @@ export default wrap(async (req, res) => {
system: systemPrompt,
user: message,
maxTokens: 1024,
+ // Free providers serve first; if every one fails, the paid backstop
+ // uses the agent's chosen Claude model on the platform key.
anthropicModel: model,
- // Lead with Claude on the platform key; falls back to the free
- // providers automatically if it's unset or Anthropic errors.
- serverAnthropic: true,
track: { agentId: agent.id, tool: 'agent.talk' },
});
} catch (err) {
diff --git a/api/avatars/_actions.js b/api/avatars/_actions.js
index a60c40ce0..079877b99 100644
--- a/api/avatars/_actions.js
+++ b/api/avatars/_actions.js
@@ -638,22 +638,20 @@ 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.
+// Classify an avatar thumbnail with a vision-capable model. Platform LLM
+// policy (api/_lib/llm.js): free providers lead — OpenRouter's free vision
+// Llama, then the same model family on NVIDIA NIM — and paid Anthropic is the
+// last-resort backstop. Every configured provider is TRIED in order (not
+// pick-first-and-die): a 429 on the free tier degrades to the next lane
+// instead of failing the auto-tag. 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', {
+ const openaiVision = (name, key, url, model, extraHeaders = {}) => async () => {
+ const r = await fetch(url, {
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',
- },
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}`, ...extraHeaders },
body: JSON.stringify({
- model: 'meta-llama/llama-3.2-11b-vision-instruct',
+ model,
max_tokens: 256,
messages: [
{
@@ -666,37 +664,69 @@ async function classifyAvatarImage({ thumbUrl, prompt, env }) {
],
}),
});
- if (!r.ok) throw Object.assign(new Error(`openrouter vision ${r.status}`), { code: 'vision_api_error' });
+ if (!r.ok) throw Object.assign(new Error(`${name} vision ${r.status}`), { code: 'vision_api_error' });
const d = await r.json();
return d.choices?.[0]?.message?.content || '';
+ };
+
+ const attempts = [];
+ if (env.OPENROUTER_API_KEY) {
+ attempts.push(openaiVision(
+ 'openrouter',
+ env.OPENROUTER_API_KEY,
+ 'https://openrouter.ai/api/v1/chat/completions',
+ 'meta-llama/llama-3.2-11b-vision-instruct',
+ { 'HTTP-Referer': 'https://three.ws', 'X-Title': 'three.ws avatar auto-tag' },
+ ));
+ }
+ if (env.NVIDIA_API_KEY) {
+ attempts.push(openaiVision(
+ 'nvidia',
+ env.NVIDIA_API_KEY,
+ 'https://integrate.api.nvidia.com/v1/chat/completions',
+ 'meta/llama-3.2-11b-vision-instruct',
+ ));
}
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 },
- ],
- },
- ],
- }),
+ attempts.push(async () => {
+ 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 || '';
});
- 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' });
+ if (!attempts.length) {
+ throw Object.assign(new Error('no vision provider configured'), { code: 'not_configured' });
+ }
+ let lastErr;
+ for (const attempt of attempts) {
+ try {
+ return await attempt();
+ } catch (err) {
+ lastErr = err;
+ }
+ }
+ throw lastErr;
}
const handleAutoTag = wrap(async (req, res) => {
diff --git a/api/brain/chat.js b/api/brain/chat.js
index fb32951c2..6bf7b61c7 100644
--- a/api/brain/chat.js
+++ b/api/brain/chat.js
@@ -19,6 +19,7 @@ import { cors, method, readJson, error, wrap, rateLimited } from '../_lib/http.j
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { watsonxConfig, watsonxChatRequest } from '../_lib/watsonx.js';
+import { DEFAULT_FREE_MODEL } from '../_lib/chat-models.js';
// Providers an anonymous (signed-out) caller may use: only the genuinely free
// tiers — the OpenRouter-routed open-weight default and the free NVIDIA NIM
@@ -248,6 +249,14 @@ const PROVIDERS = {
},
};
+// Every configured OpenRouter key, primary first. Fallback keys are typically
+// unfunded free-tier accounts (see env.OPENROUTER_FALLBACK_KEYS) — they can't
+// serve paid mirrors, but they keep every :free route alive when the primary
+// account is out of credits or rate-limited.
+function openrouterKeys() {
+ return [...new Set([env.OPENROUTER_API_KEY, ...env.OPENROUTER_FALLBACK_KEYS].filter(Boolean))];
+}
+
// Resolve the primary route for a spec: native first-party model when its key is
// present, otherwise the OpenRouter-routed equivalent, otherwise nothing. `via`
// records which path won so buildFallback() knows whether OpenRouter is a
@@ -256,7 +265,7 @@ function buildPrimary(spec) {
if (spec.watsonx) return watsonxConfig().configured ? { kind: 'watsonx' } : null;
const native = spec.native?.();
if (native) return { kind: 'model', model: native, via: 'native' };
- if (spec.openrouterModel && env.OPENROUTER_API_KEY) {
+ if (spec.openrouterModel && openrouterKeys().length) {
return { kind: 'model', model: openrouter()(spec.openrouterModel), via: 'openrouter' };
}
return null;
@@ -265,12 +274,39 @@ function buildPrimary(spec) {
// A distinct fallback exists only when the primary ran on a native provider key
// AND an OpenRouter key is configured — then OpenRouter routes around a native
// outage (quota exhausted, out of credits, rate-limited). When the primary was
-// already OpenRouter there's nowhere better to retry.
+// already OpenRouter the free-tier safety net (freeFallbackChain) is the next stop.
function buildFallback(spec, primary) {
- if (primary?.via !== 'native' || !spec.openrouterModel || !env.OPENROUTER_API_KEY) return null;
+ if (primary?.via !== 'native' || !spec.openrouterModel || !openrouterKeys().length) return null;
return openrouter()(spec.openrouterModel);
}
+// The last line of defense: free providers the platform can always fall back to
+// when the requested model's primary AND mirror routes both fail before any
+// token streamed. Free-first platform policy (api/_lib/llm.js): the user gets
+// an answer from an open-weight model rather than an error event. Skips routes
+// that already failed as the primary (same key + model would fail identically).
+function freeFallbackChain(providerKey, spec, primary) {
+ const chain = [];
+ if (env.GROQ_API_KEY && providerKey !== 'groq-llama') {
+ chain.push({
+ label: 'groq/llama-3.3-70b-versatile',
+ model: createOpenAI({ apiKey: env.GROQ_API_KEY, baseURL: 'https://api.groq.com/openai/v1' }).chat('llama-3.3-70b-versatile'),
+ });
+ }
+ openrouterKeys().forEach((key, i) => {
+ // The primary already burned this exact key+model pair — don't repeat it.
+ if (i === 0 && primary?.via === 'openrouter' && spec.openrouterModel === DEFAULT_FREE_MODEL) return;
+ chain.push({
+ label: `openrouter${i > 0 ? `#${i + 1}` : ''}/${DEFAULT_FREE_MODEL}`,
+ model: openrouter(key)(DEFAULT_FREE_MODEL),
+ });
+ });
+ if (env.NVIDIA_API_KEY && !providerKey.startsWith('nvidia-')) {
+ chain.push({ label: 'nvidia/llama-3.3-70b-instruct', model: nvidia('meta/llama-3.3-70b-instruct') });
+ }
+ return chain;
+}
+
// NVIDIA NIM (build.nvidia.com) is OpenAI-*compatible* (Chat Completions, not the
// Responses API), so — like Groq, ModelScope and OpenRouter — we force the
// `.chat()` surface. One free `nvapi-...` key unlocks every hosted model.
@@ -281,9 +317,9 @@ function nvidia(modelId) {
}).chat(modelId);
}
-function openrouter() {
+function openrouter(key = openrouterKeys()[0]) {
const provider = createOpenAI({
- apiKey: env.OPENROUTER_API_KEY,
+ apiKey: key,
baseURL: 'https://openrouter.ai/api/v1',
headers: { 'HTTP-Referer': 'https://three.ws', 'X-Title': 'three.ws brain' },
});
@@ -548,42 +584,54 @@ export default wrap(async function handler(req, res) {
res.end();
};
+ // Ordered attempt list: the requested route first, its OpenRouter mirror
+ // second, then the free-tier safety net (Groq → OpenRouter :free across every
+ // key → NVIDIA NIM). Any attempt that fails BEFORE the first token — auth
+ // failure on a dead server key, quota exhaustion, rate limit, hang, 5xx —
+ // hands off to the next route, so a single bad provider never surfaces as an
+ // error event while any free provider can still answer. Once partial output
+ // has streamed we are committed to that attempt.
try {
- // watsonx.ai isn't an AI SDK model — stream it through the shared client,
- // emitting the same first/chunk/done event protocol the page expects.
- if (primary.kind === 'watsonx') {
- await streamWatsonx(res, { messages, system, maxTokens, t0 });
- return;
- }
-
- try {
- await streamOnce(maxTokens, primary.model);
- } catch (err) {
- const canRetry = firstTokenMs === null && !res.writableEnded;
- const affordable = affordableBudget(err);
- if (affordable && canRetry) {
+ const attempts = primary.kind === 'watsonx'
+ ? [{ label: 'watsonx', watsonx: true }]
+ : [{ label: 'primary', model: primary.model }];
+ if (fallbackModel) attempts.push({ label: 'openrouter-mirror', model: fallbackModel });
+ for (const f of freeFallbackChain(providerKey, spec, primary)) attempts.push(f);
+
+ let lastErr = null;
+ for (const [i, attempt] of attempts.entries()) {
+ if (firstTokenMs !== null || res.writableEnded) return;
+ // Leave the attempt at least a second of wall-clock to connect.
+ if (i > 0 && Date.now() >= deadline - 1_000) break;
+ if (i > 0) {
+ console.warn(`[brain:${providerKey}] ${attempts[i - 1].label} failed (${conciseReason(lastErr)}); falling back to ${attempt.label}`);
+ // Advisory for the client (current page ignores unknown events).
+ res.write(`event: fallback\ndata: ${JSON.stringify({ route: attempt.label })}\n\n`);
+ }
+ try {
+ // watsonx.ai isn't an AI SDK model — stream it through the shared
+ // client, emitting the same first/chunk/done event protocol. It only
+ // throws before writing tokens, so falling through is safe.
+ if (attempt.watsonx) await streamWatsonx(res, { messages, system, maxTokens, t0 });
+ else await streamOnce(maxTokens, attempt.model);
+ return;
+ } catch (err) {
+ lastErr = err;
// OpenRouter free tier: "requires more credits, or fewer max_tokens.
- // You requested up to 1024 tokens, but can only afford 788." Retry once
- // at the affordable ceiling instead of hard-failing.
- await streamOnce(affordable, primary.model);
- } else if (fallbackModel && canRetry && isProviderOutage(err)) {
- // Native provider is down (over quota, out of credits, rate-limited).
- // Route the same request through OpenRouter so the user still gets a reply.
- console.warn(`[brain:${providerKey}] native provider failed (${conciseReason(err)}); falling back to OpenRouter`);
- try {
- await streamOnce(maxTokens, fallbackModel);
- } catch (err2) {
- const affordable2 = affordableBudget(err2);
- if (affordable2 && firstTokenMs === null && !res.writableEnded) {
- await streamOnce(affordable2, fallbackModel);
- } else {
- throw err2;
+ // You requested up to 1024 tokens, but can only afford 788." Retry this
+ // route once at the affordable ceiling before moving on.
+ const affordable = attempt.model ? affordableBudget(err) : null;
+ if (affordable && firstTokenMs === null && !res.writableEnded) {
+ try {
+ await streamOnce(affordable, attempt.model);
+ return;
+ } catch (err2) {
+ lastErr = err2;
}
}
- } else {
- throw err;
}
}
+ throw lastErr || new Error('no provider route available');
} catch (err) {
const elapsedMs = Date.now() - t0;
// The SDK no longer logs for us (onError is captured), so emit one concise
@@ -612,21 +660,6 @@ function affordableBudget(err) {
return m ? Math.max(64, Math.floor(Number(m[1]) * 0.9)) : null;
}
-// A provider-side outage we can route around (vs a caller/content error that
-// every provider would reject identically): rate-limit, quota exhaustion, out of
-// credits, or an upstream 5xx.
-function isProviderOutage(err) {
- const status = Number(err?.statusCode || err?.cause?.statusCode || 0);
- if (status === 429 || status === 402 || status >= 500) return true;
- // An aborted attempt — our per-attempt timeout budget firing on a hung
- // provider — is route-around-able: hand off to the OpenRouter fallback rather
- // than surfacing a dead-air error to the user.
- const name = err?.name || err?.cause?.name || '';
- if (name === 'AbortError' || name === 'TimeoutError') return true;
- const msg = `${err?.message || ''} ${err?.cause?.message || ''}`;
- return /quota|insufficient_quota|rate.?limit|too many requests|billing|exceeded your current|requires more credits|overloaded|temporarily unavailable|maxRetriesExceeded|abort|timed out|timeout/i.test(msg);
-}
-
// One-line, length-capped error summary for server logs.
function conciseReason(err) {
const msg = (err?.message || String(err)).replace(/\s+/g, ' ').trim();
diff --git a/api/chat.js b/api/chat.js
index 193b26443..736ce2e48 100644
--- a/api/chat.js
+++ b/api/chat.js
@@ -3,13 +3,15 @@
// Body: { message, context, history, agentId?, provider?, model? }
// Response: SSE stream { type: 'chunk' | 'done' | 'error' }.
//
-// Provider routing (in order):
+// Provider routing (in order — free providers ALWAYS lead; see
+// api/_lib/chat-models.js DEFAULT_PROVIDER_ORDER):
// 1. Body.provider when present and the matching key is configured.
// 2. GROQ_API_KEY → Groq (free platform key — default).
// 3. OPENROUTER_API_KEY → OpenRouter free tier.
-// 4. OPENAI_API_KEY → OpenAI.
-// 5. ANTHROPIC_API_KEY → Anthropic (BYOK only — never set as a server key).
-// 6. WATSONX_API_KEY (+ project) → IBM Granite on watsonx.ai (server key only;
+// 4. NVIDIA_API_KEY → NVIDIA NIM free tier (third independent free lane).
+// 5. ANTHROPIC_API_KEY → Anthropic (paid backstop — BYOK or host key).
+// 6. OPENAI_API_KEY → OpenAI (paid backstop).
+// 7. WATSONX_API_KEY (+ project) → IBM Granite on watsonx.ai (server key only;
// explicit `provider: "watsonx"` from the client, never the silent default).
// Anthropic, the OpenAI-compatible providers (OpenRouter / Groq / OpenAI), and
// watsonx.ai use different request shapes, auth, tool-call wire formats, and SSE
@@ -85,6 +87,14 @@ const PROVIDERS = {
url: 'https://api.groq.com/openai/v1/chat/completions',
style: 'openai',
},
+ // NVIDIA NIM (build.nvidia.com) — free OpenAI-compatible inference; one
+ // nvapi key unlocks every hosted model. The third independent free lane.
+ nvidia: {
+ envKey: 'NVIDIA_API_KEY',
+ defaultModel: PROVIDER_MODEL_DEFAULTS.nvidia,
+ url: 'https://integrate.api.nvidia.com/v1/chat/completions',
+ style: 'openai',
+ },
openai: {
envKey: 'OPENAI_API_KEY',
defaultModel: DEFAULT_OPENAI_MODEL,
@@ -136,7 +146,7 @@ const chatBody = z.object({
system_prompt: z.string().trim().min(1).max(2000).optional(),
agentId: z.string().uuid().optional(),
provider: z
- .enum(['anthropic', 'openrouter', 'groq', 'openai', 'watsonx', 'orchestrate'])
+ .enum(['anthropic', 'openrouter', 'groq', 'nvidia', 'openai', 'watsonx', 'orchestrate'])
.optional(),
model: z.string().min(1).max(120).optional(),
history: z
@@ -335,18 +345,18 @@ export default wrap(async (req, res) => {
}
const hasOpenRouter = !!process.env.OPENROUTER_API_KEY;
const hasGroq = !!process.env.GROQ_API_KEY;
- if (!hasOpenRouter && !hasGroq) {
+ const hasNvidia = !!process.env.NVIDIA_API_KEY;
+ if (!hasOpenRouter && !hasGroq && !hasNvidia) {
return error(res, 401, 'unauthorized', 'sign in to chat with the agent');
}
if (body.provider && !ANON_PROVIDERS.has(body.provider)) {
return error(res, 401, 'unauthorized', 'sign in to use this model');
}
- // Honor an explicitly-requested free-tier provider (groq/openrouter).
+ // Honor an explicitly-requested free-tier provider (groq/openrouter/nvidia).
// Otherwise default to Groq — the fast, first-attempt-reliable free tier —
- // and fall back to OpenRouter's free Llama (DEFAULT_FREE_MODEL) if Groq
- // isn't configured.
+ // then OpenRouter's free Llama (DEFAULT_FREE_MODEL), then NVIDIA NIM.
if (!body.provider) {
- body.provider = hasGroq ? 'groq' : 'openrouter';
+ body.provider = hasGroq ? 'groq' : hasOpenRouter ? 'openrouter' : 'nvidia';
if (!body.model && body.provider === 'openrouter') body.model = DEFAULT_FREE_MODEL;
}
anonymous = true;
@@ -856,8 +866,11 @@ async function governActions(actions, userMessage) {
// ── Provider selection ───────────────────────────────────────────────────────
function pickProvider(requested, model, userKeys = {}, cooldown = new Set()) {
+ // Fall back in DEFAULT_PROVIDER_ORDER (free providers first), not the
+ // PROVIDERS object order — and never silently fall into watsonx/orchestrate,
+ // which are explicit-selection-only providers.
const order = requested
- ? [requested, ...Object.keys(PROVIDERS).filter((p) => p !== requested)]
+ ? [requested, ...DEFAULT_PROVIDER_ORDER.filter((p) => p !== requested)]
: DEFAULT_PROVIDER_ORDER;
// Two passes: first skip providers in a health cooldown, then — only if that
@@ -874,14 +887,15 @@ function pickProvider(requested, model, userKeys = {}, cooldown = new Set()) {
// Orchestrate needs both a key and its endpoint URL.
if (name === 'watsonx' && !watsonxConfig().configured) continue;
if (name === 'orchestrate' && !orchestrateConfig().configured) continue;
- // CHAT_MODEL is an Anthropic-style id; it must not leak into a watsonx or
- // Orchestrate request (which expect their own model/agent ids). Those
- // providers use the client-named value or their own default.
+ // CHAT_MODEL pins the default model, but only for the provider that
+ // actually serves that id (per MODEL_CATALOG) — with free providers
+ // leading the ladder, an Anthropic-style CHAT_MODEL leaking into a Groq
+ // or NVIDIA request would 400 every chat.
const chosenModel =
(requested === name && model) ||
(name === 'watsonx' || name === 'orchestrate'
? cfg.defaultModel
- : process.env.CHAT_MODEL || cfg.defaultModel);
+ : envPinnedModelFor(name) || cfg.defaultModel);
const route = makeRoute(name, cfg, apiKey, chosenModel);
// Flag whether this route bills the host's key (no user-supplied key for
// the provider) so the handler can enforce the global host-key ceiling.
@@ -893,6 +907,13 @@ function pickProvider(requested, model, userKeys = {}, cooldown = new Set()) {
return resolve(true) || resolve(false);
}
+// CHAT_MODEL pins a default model via env, but only the provider that serves
+// that id may use it — every other provider keeps its own default.
+function envPinnedModelFor(providerName) {
+ const m = process.env.CHAT_MODEL;
+ return m && MODEL_CATALOG[m]?.provider === providerName ? m : null;
+}
+
// Build an ordered failover list starting with the primary route. Cycles
// through (a) sibling models on the same provider so a per-model rate-limit
// doesn't kill the request, then (b) the next configured provider's default
@@ -911,6 +932,10 @@ function pickProvider(requested, model, userKeys = {}, cooldown = new Set()) {
const FALLBACK_SIBLINGS = {
openrouter: OPENROUTER_SIBLINGS,
groq: ['llama-3.3-70b-versatile'],
+ // Like Groq, NVIDIA NIM rate-limits per key (one account), so a second NIM
+ // model would re-hit the same throttle — keep a single slot and give the
+ // next fallback slot to a different provider.
+ nvidia: ['meta/llama-3.3-70b-instruct'],
anthropic: ['claude-sonnet-4-6', 'claude-haiku-4-5-20251001'],
openai: ['gpt-4o-mini'],
};
diff --git a/api/client-errors.js b/api/client-errors.js
new file mode 100644
index 000000000..ff7f867fa
--- /dev/null
+++ b/api/client-errors.js
@@ -0,0 +1,99 @@
+// Ingest endpoint for first-party client-side error reports sent by
+// public/error-reporter.js (loaded on every page). Each accepted event is
+// logged as one structured "[client-error]" line so browser errors from real
+// users are searchable in the Vercel function logs (and any attached log
+// drain), and JS errors are forwarded to Sentry when SENTRY_DSN is set.
+//
+// The client batches, dedupes, and hard-caps per page; this side re-validates
+// and re-truncates everything anyway — the payload is attacker-controllable
+// public input, so nothing from it is trusted or echoed back.
+
+import { cors, json, method, readJson, wrap, error, rateLimited } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { captureException } from './_lib/sentry.js';
+
+const MAX_EVENTS_PER_BATCH = 25;
+const EVENT_TYPES = new Set(['error', 'unhandledrejection', 'resource', 'manual']);
+const LIMITS = { message: 500, stack: 4000, url: 500, name: 100, tag: 20 };
+
+function str(value, max) {
+ if (typeof value !== 'string' || !value) return undefined;
+ return value.length > max ? `${value.slice(0, max)}…` : value;
+}
+
+function int(value) {
+ return Number.isFinite(value) ? Math.trunc(value) : undefined;
+}
+
+function sanitizeEvent(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ const type = EVENT_TYPES.has(raw.type) ? raw.type : null;
+ const message = str(raw.message, LIMITS.message);
+ if (!type || !message) return null;
+ return {
+ type,
+ name: str(raw.name, LIMITS.name),
+ message,
+ source: str(raw.source, LIMITS.url),
+ line: int(raw.line),
+ col: int(raw.col),
+ stack: str(raw.stack, LIMITS.stack),
+ tag: str(raw.tag, LIMITS.tag),
+ ts: int(raw.ts),
+ };
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: false })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const ip = clientIp(req);
+ const rl = await limits.clientErrorsIp(ip);
+ if (!rl.success) return rateLimited(res, rl);
+
+ let body;
+ try {
+ body = await readJson(req, 64_000);
+ } catch (err) {
+ return error(res, err.status || 400, 'validation_error', err.message || 'invalid body');
+ }
+
+ const rawEvents = Array.isArray(body?.events) ? body.events.slice(0, MAX_EVENTS_PER_BATCH) : [];
+ const events = rawEvents.map(sanitizeEvent).filter(Boolean);
+ if (!events.length) return error(res, 400, 'validation_error', 'events array required');
+
+ const context = {
+ page: str(body?.page, LIMITS.url),
+ referrer: str(body?.referrer, LIMITS.url),
+ viewport:
+ body?.viewport && typeof body.viewport === 'object'
+ ? { w: int(body.viewport.w), h: int(body.viewport.h) }
+ : undefined,
+ ua: str(req.headers['user-agent'], 300),
+ ip,
+ };
+
+ for (const event of events) {
+ // One line per event keeps Vercel log search precise:
+ // filter on "[client-error]" then on message/page substrings.
+ console.error('[client-error]', JSON.stringify({ ...event, ...context }));
+
+ // Resource 404s stay log-only — they group terribly as exceptions.
+ // Real JS errors carry their original browser stack into Sentry.
+ if (event.type !== 'resource') {
+ const synthetic = new Error(event.message);
+ synthetic.name = event.name || `client.${event.type}`;
+ if (event.stack) synthetic.stack = event.stack;
+ captureException(synthetic, {
+ origin: 'client',
+ page: context.page,
+ source: event.source,
+ line: event.line,
+ col: event.col,
+ ua: context.ua,
+ });
+ }
+ }
+
+ return json(res, 202, { received: events.length });
+});
diff --git a/api/cron/[name].js b/api/cron/[name].js
index 3d88e194b..baa8b3638 100644
--- a/api/cron/[name].js
+++ b/api/cron/[name].js
@@ -30,6 +30,7 @@ import { baseSepolia, base } from 'viem/chains';
import { sql } from '../_lib/db.js';
import { cors, error, json, method, wrap } from '../_lib/http.js';
import { env } from '../_lib/env.js';
+import { llmComplete } from '../_lib/llm.js';
import { CHAINS } from '../_lib/erc8004-chains.js';
import { DELEGATION_MANAGER_DEPLOYMENTS, DELEGATION_MANAGER_ABI } from '../../src/erc7710/abi.js';
import {
@@ -3245,77 +3246,17 @@ const DRAFT_SYSTEM = `You write tweets for AI agents on three.ws. Tweets must be
- Avoid em-dashes.
Output ONLY the tweet text, nothing else.`;
-async function anthropicDraft({ system, user, max }) {
- const r = 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: max,
- system,
- messages: [{ role: 'user', content: user }],
- }),
- });
- if (!r.ok) throw new Error(`anthropic ${r.status}: ${(await r.text()).slice(0, 200)}`);
- const data = await r.json();
- return data.content?.[0]?.text || '';
-}
-
-async function openaiCompatDraft({ url, key, model, system, user, max, extraHeaders = {} }) {
- const r = await fetch(url, {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- authorization: `Bearer ${key}`,
- ...extraHeaders,
- },
- body: JSON.stringify({
- model,
- max_tokens: max,
- messages: [
- { role: 'system', content: system },
- { role: 'user', content: user },
- ],
- }),
- });
- if (!r.ok) throw new Error(`${model} ${r.status}: ${(await r.text()).slice(0, 200)}`);
- const data = await r.json();
- return data.choices?.[0]?.message?.content || '';
-}
-
-// 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.
+// Draft short post text on the platform LLM chain (api/_lib/llm.js): free
+// providers first with full failover, paid keys as the automatic last resort.
+// The old pick-first-and-die routing meant one Groq 429 dropped the post.
async function llmDraft({ system, user, max = 200 }) {
- let text;
- if (env.GROQ_API_KEY) {
- text = await openaiCompatDraft({
- url: 'https://api.groq.com/openai/v1/chat/completions',
- key: env.GROQ_API_KEY,
- model: 'llama-3.3-70b-versatile',
- system,
- user,
- max,
- });
- } else if (env.OPENROUTER_API_KEY) {
- text = await openaiCompatDraft({
- url: 'https://openrouter.ai/api/v1/chat/completions',
- key: env.OPENROUTER_API_KEY,
- model: 'meta-llama/llama-3.3-70b-instruct',
- 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 GROQ_API_KEY or OPENROUTER_API_KEY)');
- }
- text = (text || '').trim();
+ const { text: raw } = await llmComplete({
+ system,
+ user,
+ maxTokens: max,
+ track: { tool: 'cron.x-trigger-draft' },
+ });
+ let text = (raw || '').trim();
if (text.startsWith('"') && text.endsWith('"')) text = text.slice(1, -1).trim();
if (text.length > 280) text = text.slice(0, 279) + '…';
return text;
diff --git a/api/marketplace/[action].js b/api/marketplace/[action].js
index eb0b01ab2..3edc90760 100644
--- a/api/marketplace/[action].js
+++ b/api/marketplace/[action].js
@@ -678,7 +678,8 @@ async function handleDetail(req, res, id) {
//
// History is capped at 8 turns; only the agent's published system_prompt is
// used (no viewer tools, no admin context). Provider is whichever is
-// configured via env, in fallback order: anthropic → openrouter → groq → openai.
+// configured via env, free providers first: groq → openrouter → nvidia →
+// anthropic → openai (see buildPreviewRoutes).
const PREVIEW_PROVIDERS = {
anthropic: {
@@ -704,6 +705,13 @@ const PREVIEW_PROVIDERS = {
defaultModel: 'llama-3.3-70b-versatile',
style: 'openai',
},
+ // NVIDIA NIM free tier — third independent free lane (see api/_lib/llm.js).
+ nvidia: {
+ envKey: 'NVIDIA_API_KEY',
+ url: 'https://integrate.api.nvidia.com/v1/chat/completions',
+ defaultModel: 'meta/llama-3.3-70b-instruct',
+ style: 'openai',
+ },
openai: {
envKey: 'OPENAI_API_KEY',
url: 'https://api.openai.com/v1/chat/completions',
@@ -864,15 +872,17 @@ async function handlePreview(req, res, id) {
}
// Build an ordered list of all configured preview routes. Priority mirrors the
-// chat ladder (api/_lib/chat-models.js → DEFAULT_PROVIDER_ORDER): Anthropic-first
-// so the common path resolves on attempt 0 instead of burning the rate-limited
-// free tiers, then the free fallbacks, with the over-quota OpenAI account last.
-// 1. anthropic — paid server key; keyed in prod, most reliable first attempt
-// 2. groq — free, fast, first-attempt reliable (per-minute caps only)
-// 3. openrouter — free Llama fallback
-// 4. openai — paid; last resort (account may be over quota)
+// chat ladder (api/_lib/chat-models.js → DEFAULT_PROVIDER_ORDER): free
+// providers ALWAYS lead, paid keys are last-resort backstops — the prod paid
+// keys are routinely invalid (Anthropic 401) or over quota (OpenAI), so
+// leading with them burned a doomed attempt on every preview.
+// 1. groq — free, fast, first-attempt reliable (per-minute caps only)
+// 2. openrouter — free Llama fallback
+// 3. nvidia — NVIDIA NIM free tier, independent third lane
+// 4. anthropic — paid backstop
+// 5. openai — paid backstop (account may be over quota)
function buildPreviewRoutes() {
- const order = ['anthropic', 'groq', 'openrouter', 'openai'];
+ const order = ['groq', 'openrouter', 'nvidia', 'anthropic', 'openai'];
const routes = [];
for (const name of order) {
const cfg = PREVIEW_PROVIDERS[name];
diff --git a/api/persona/extract.js b/api/persona/extract.js
index 9c8b7161d..1ae45aef1 100644
--- a/api/persona/extract.js
+++ b/api/persona/extract.js
@@ -106,7 +106,6 @@ const handler = wrap(async (req, res) => {
system: SYSTEM_PROMPT,
user: userMessage,
maxTokens: 800,
- serverAnthropic: true,
});
} catch (err) {
if (err instanceof LlmUnavailableError) {
diff --git a/api/persona/preview.js b/api/persona/preview.js
index 2cfedbe11..47f1b8d1f 100644
--- a/api/persona/preview.js
+++ b/api/persona/preview.js
@@ -74,12 +74,11 @@ const handler = wrap(async (req, res) => {
system,
user: body.user_message,
maxTokens: 220,
- serverAnthropic: true,
});
} catch (err) {
if (err instanceof LlmUnavailableError) {
return error(res, 503, 'config_missing',
- 'No LLM provider configured. Set ANTHROPIC_API_KEY, GROQ_API_KEY, or OPENROUTER_API_KEY.');
+ 'No LLM provider configured. Set GROQ_API_KEY, OPENROUTER_API_KEY, or NVIDIA_API_KEY (free), or ANTHROPIC_API_KEY / OPENAI_API_KEY.');
}
console.error('[persona/preview] all providers failed', err?.status, err?.message);
return error(res, err?.status || 502, 'upstream_error', 'Persona preview is briefly unavailable. Please try again.');
diff --git a/api/tx/explain.js b/api/tx/explain.js
index 423f80b69..fb21854fb 100644
--- a/api/tx/explain.js
+++ b/api/tx/explain.js
@@ -2,6 +2,7 @@ import { Interface } from 'ethers';
import { env } from '../_lib/env.js';
import { wrap, cors, error, json, readJson, method, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
+import { llmComplete, llmConfigured } from '../_lib/llm.js';
const ERC20_TRANSFER_TOPIC =
'0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef';
@@ -111,34 +112,19 @@ export default wrap(async (req, res) => {
};
}
- // Optional plain-English summary via OpenRouter
- const openRouterKey = env.OPENROUTER_API_KEY;
- if (openRouterKey) {
+ // Optional plain-English summary via the platform LLM chain (api/_lib/llm.js):
+ // free providers first with full failover, so one rate-limited key doesn't
+ // silently drop summaries platform-wide.
+ if (llmConfigured()) {
try {
- const summaryResp = await fetch('https://openrouter.ai/api/v1/chat/completions', {
- method: 'POST',
- headers: {
- Authorization: `Bearer ${openRouterKey}`,
- 'Content-Type': 'application/json',
- 'HTTP-Referer': 'https://three.ws',
- 'X-Title': 'three.ws tx explainer',
- },
- body: JSON.stringify({
- model: 'meta-llama/llama-3.1-8b-instruct:free',
- max_tokens: 200,
- messages: [
- {
- role: 'user',
- content: `Summarize this on-chain ${chain} transaction in one plain-English paragraph. Be concise. Data: ${JSON.stringify(txData)}`,
- },
- ],
- }),
+ const { text } = await llmComplete({
+ system: 'You summarize on-chain transactions in one concise plain-English paragraph.',
+ user: `Summarize this on-chain ${chain} transaction in one plain-English paragraph. Be concise. Data: ${JSON.stringify(txData)}`,
+ maxTokens: 200,
+ timeoutMs: 10_000,
+ track: { tool: 'tx.explain' },
});
- if (summaryResp.ok) {
- const summaryJson = await summaryResp.json();
- const text = summaryJson.choices?.[0]?.message?.content;
- if (text) txData.summary = text.trim();
- }
+ if (text) txData.summary = text;
} catch {
// summary is optional — silently skip
}
diff --git a/api/widgets/[id]/[action].js b/api/widgets/[id]/[action].js
index 31cedfd56..a135eec02 100644
--- a/api/widgets/[id]/[action].js
+++ b/api/widgets/[id]/[action].js
@@ -15,7 +15,7 @@ import { limits, clientIp } from '../../_lib/rate-limit.js';
import { captureException } from '../../_lib/sentry.js';
import { isDemoWidgetId, getDemoWidget } from '../_demo-fixtures.js';
import { decorate } from '../index.js';
-import { PROVIDER_MODEL_DEFAULTS, DEFAULT_PROVIDER_ORDER } from '../../_lib/chat-models.js';
+import { PROVIDER_MODEL_DEFAULTS, DEFAULT_PROVIDER_ORDER, MODEL_CATALOG, PER_CALL_TIMEOUT_MS } from '../../_lib/chat-models.js';
import { redactPii } from '../../_lib/pii.js';
import { embed, cosine, embeddingsConfigured } from '../../_lib/embeddings.js';
import { watsonxConfig, watsonxToken } from '../../_lib/watsonx.js';
@@ -52,9 +52,10 @@ const HARD_MAX_TOKENS = 4096;
const SAFE_SKILLS = new Set(['speak', 'wave', 'lookAt', 'playClip', 'remember']);
-// LLM provider routing — mirrors /api/chat.js. Anthropic is the historical
-// default; the OpenAI-compatible providers (OpenRouter / Groq / OpenAI) ship
-// here too so the talking-agent widget can pick any configured brain.
+// LLM provider routing — mirrors /api/chat.js. Free providers (Groq /
+// OpenRouter / NVIDIA NIM) lead via DEFAULT_PROVIDER_ORDER; paid Anthropic and
+// OpenAI are last-resort backstops. Every entry here MUST cover everything in
+// DEFAULT_PROVIDER_ORDER — pickProviderChain indexes this table by that list.
const PROVIDERS = {
anthropic: {
envKey: 'ANTHROPIC_API_KEY',
@@ -76,6 +77,13 @@ const PROVIDERS = {
url: 'https://api.groq.com/openai/v1/chat/completions',
style: 'openai',
},
+ // NVIDIA NIM free tier — third independent free lane (see api/_lib/llm.js).
+ nvidia: {
+ envKey: 'NVIDIA_API_KEY',
+ defaultModel: PROVIDER_MODEL_DEFAULTS.nvidia,
+ url: 'https://integrate.api.nvidia.com/v1/chat/completions',
+ style: 'openai',
+ },
openai: {
envKey: 'OPENAI_API_KEY',
defaultModel: 'gpt-4o-mini',
@@ -95,11 +103,11 @@ const PROVIDERS = {
// Brain settings that surface in widget config. `auto` picks the first
// configured provider; `custom`/`none` keep their legacy meanings.
-const BRAIN_PROVIDERS = new Set(['auto', 'anthropic', 'openrouter', 'groq', 'openai', 'watsonx']);
+const BRAIN_PROVIDERS = new Set(['auto', 'anthropic', 'openrouter', 'groq', 'nvidia', 'openai', 'watsonx']);
const chatBody = z.object({
message: z.string().trim().min(1).max(4000),
- provider: z.enum(['auto', 'anthropic', 'openrouter', 'groq', 'openai', 'watsonx']).optional(),
+ provider: z.enum(['auto', 'anthropic', 'openrouter', 'groq', 'nvidia', 'openai', 'watsonx']).optional(),
model: z.string().min(1).max(160).optional(),
history: z
.array(
@@ -239,24 +247,51 @@ async function handleChat(req, res) {
} else if (provider === 'custom') {
result = await callCustomProxy(cfg.proxyURL, body, cfg, allowedSkills);
} else {
- const route = pickProvider(provider, requestedModel);
- if (!route) {
+ const routes = pickProviderChain(provider, requestedModel);
+ if (!routes.length) {
result = {
reply: "I'm not configured to answer just yet — no chat provider key is set on this site.",
actions: [],
};
} else {
- usedProvider = route.name;
- usedModel = route.model;
- result = await callLLM({
- route,
- message: body.message,
- history: body.history,
- systemPrompt: buildSystemPrompt(cfg, widget, knowledgeBlock),
- temperature: Number(cfg.temperature) || 0.7,
- maxTurns: Math.min(20, Math.max(1, Number(cfg.maxTurns) || 20)),
- allowedSkills,
- });
+ // Walk the whole configured chain (free providers first — see
+ // DEFAULT_PROVIDER_ORDER): a dead key, exhausted quota, rate limit,
+ // or hung upstream on one provider hands off to the next instead of
+ // surfacing a canned failure while another lane could still answer.
+ let lastErr = null;
+ result = null;
+ for (const route of routes) {
+ try {
+ result = await callLLM({
+ route,
+ message: body.message,
+ history: body.history,
+ systemPrompt: buildSystemPrompt(cfg, widget, knowledgeBlock),
+ temperature: Number(cfg.temperature) || 0.7,
+ maxTurns: Math.min(20, Math.max(1, Number(cfg.maxTurns) || 20)),
+ allowedSkills,
+ });
+ usedProvider = route.name;
+ usedModel = route.model;
+ break;
+ } catch (err) {
+ lastErr = err;
+ if (process.env.DEBUG === 'true') {
+ console.warn(`[widget-chat] ${route.name} failed (${err?.message}); trying next provider`);
+ }
+ }
+ }
+ if (!result) {
+ captureException(lastErr || new Error('all widget chat providers failed'), {
+ route: 'widget-chat',
+ stage: 'chain-exhausted',
+ widgetId,
+ });
+ result = {
+ reply: 'I had trouble thinking of a response. Try again in a moment.',
+ actions: [],
+ };
+ }
}
}
@@ -290,28 +325,45 @@ async function handleChat(req, res) {
// ── Brain dispatchers ──────────────────────────────────────────────────────
-function pickProvider(requested, requestedModel) {
+function pickProviderChain(requested, requestedModel) {
+ // Fall back in DEFAULT_PROVIDER_ORDER (free providers first), not the
+ // PROVIDERS object order, so an unconfigured explicit request degrades to
+ // the free chain — never to a paid key first. Mirrors api/chat.js. Returns
+ // EVERY configured route in order; the caller walks the list until one
+ // answers, so a single failing provider can never end the conversation.
const order =
requested && requested !== 'auto'
- ? [requested, ...Object.keys(PROVIDERS).filter((p) => p !== requested)]
+ ? [requested, ...DEFAULT_PROVIDER_ORDER.filter((p) => p !== requested)]
: DEFAULT_PROVIDER_ORDER;
+ const chain = [];
for (const name of order) {
const cfg = PROVIDERS[name];
+ if (!cfg) continue;
const apiKey = process.env[cfg.envKey];
if (!apiKey) continue;
// watsonx needs both a key and a project/space scope to serve a model.
if (name === 'watsonx' && !watsonxConfig().configured) continue;
- // CHAT_MODEL is an Anthropic-style id; never leak it into a watsonx request
- // (which expects its own ibm/* model id). watsonx uses the client-named
- // value or its own default.
+ // CHAT_MODEL pins the default model, but only for the provider that
+ // actually serves that id (per MODEL_CATALOG) — with free providers
+ // leading the ladder, an Anthropic-style CHAT_MODEL leaking into a Groq
+ // or NVIDIA request would 400 every chat. watsonx always keeps its own
+ // ibm/* default.
+ const envPinned =
+ process.env.CHAT_MODEL && MODEL_CATALOG[process.env.CHAT_MODEL]?.provider === name
+ ? process.env.CHAT_MODEL
+ : null;
+ // The caller's model choice applies only to the route it was chosen for
+ // (the requested provider, or the lead route under `auto`); fallback
+ // routes run their own default so a model id never leaks cross-provider.
+ const requestedApplies =
+ requestedModel && (requested === name || (requested === 'auto' && chain.length === 0));
const model =
- (requested === name && requestedModel) ||
- (requested === 'auto' && requestedModel) ||
- (name === 'watsonx' ? cfg.defaultModel : process.env.CHAT_MODEL || cfg.defaultModel);
- return { name, cfg, apiKey, model };
+ (requestedApplies && requestedModel) ||
+ (name === 'watsonx' ? cfg.defaultModel : envPinned || cfg.defaultModel);
+ chain.push({ name, cfg, apiKey, model });
}
- return null;
+ return chain;
}
async function callLLM({
@@ -401,6 +453,9 @@ async function callAnthropic({
'content-type': 'application/json',
},
body: JSON.stringify(payload),
+ // A hung upstream must not eat the whole function budget — abort and let
+ // the provider chain in handleChat move to the next route.
+ signal: AbortSignal.timeout(PER_CALL_TIMEOUT_MS),
});
if (!upstream.ok) {
const text = await upstream.text().catch(() => '');
@@ -409,13 +464,9 @@ async function callAnthropic({
status: upstream.status,
body: text.slice(0, 400),
});
- if (process.env.DEBUG === 'true') {
- console.warn('[widget-chat] anthropic', upstream.status, text.slice(0, 400));
- }
- return {
- reply: 'I had trouble thinking of a response. Try again in a moment.',
- actions: [],
- };
+ // Throw so the provider chain in handleChat falls over to the next route
+ // (dead key, quota, rate limit — another lane can still answer).
+ throw Object.assign(new Error(`anthropic upstream ${upstream.status}`), { status: upstream.status });
}
const data = await upstream.json();
return normalizeAnthropic(data, allowedSkills);
@@ -458,6 +509,9 @@ async function callOpenAICompatible({
...(route.cfg.extraHeaders || {}),
},
body: JSON.stringify(payload),
+ // A hung upstream must not eat the whole function budget — abort and let
+ // the provider chain in handleChat move to the next route.
+ signal: AbortSignal.timeout(PER_CALL_TIMEOUT_MS),
});
if (!upstream.ok) {
const text = await upstream.text().catch(() => '');
@@ -467,13 +521,8 @@ async function callOpenAICompatible({
status: upstream.status,
body: text.slice(0, 400),
});
- if (process.env.DEBUG === 'true') {
- console.warn(`[widget-chat] ${route.name}`, upstream.status, text.slice(0, 400));
- }
- return {
- reply: 'I had trouble thinking of a response. Try again in a moment.',
- actions: [],
- };
+ // Throw so the provider chain in handleChat falls over to the next route.
+ throw Object.assign(new Error(`${route.name} upstream ${upstream.status}`), { status: upstream.status });
}
const data = await upstream.json();
return normalizeOpenAI(data, allowedSkills);
@@ -515,6 +564,8 @@ async function callWatsonx({ route, messages, systemPrompt, temperature, maxToke
Accept: 'application/json',
},
body: JSON.stringify(payload),
+ // Abort a hung upstream so the provider chain can move on.
+ signal: AbortSignal.timeout(PER_CALL_TIMEOUT_MS),
});
}
@@ -531,8 +582,8 @@ async function callWatsonx({ route, messages, systemPrompt, temperature, maxToke
}
} catch (err) {
captureException(err, { route: 'widget-chat', provider: 'watsonx', stage: 'fetch' });
- if (process.env.DEBUG === 'true') console.warn('[widget-chat] watsonx fetch', err?.message);
- return { reply: 'I had trouble thinking of a response. Try again in a moment.', actions: [] };
+ // Rethrow so the provider chain in handleChat falls over to the next route.
+ throw err;
}
if (!upstream.ok) {
@@ -543,8 +594,8 @@ async function callWatsonx({ route, messages, systemPrompt, temperature, maxToke
status: upstream.status,
body: text.slice(0, 400),
});
- if (process.env.DEBUG === 'true') console.warn('[widget-chat] watsonx', upstream.status, text.slice(0, 400));
- return { reply: 'I had trouble thinking of a response. Try again in a moment.', actions: [] };
+ // Throw so the provider chain in handleChat falls over to the next route.
+ throw Object.assign(new Error(`watsonx upstream ${upstream.status}`), { status: upstream.status });
}
const data = await upstream.json();
return normalizeOpenAI(data, allowedSkills);
diff --git a/data/changelog.json b/data/changelog.json
index 3c6b6a3e3..277485026 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -3,8 +3,8 @@
"entries": [
{
"date": "2026-06-11",
- "title": "Built-in AI stays up when a provider account runs dry",
- "summary": "The platform's built-in AI (chat, tutor, fact-checker, persona tools) now rotates across multiple OpenRouter accounts: when one account runs out of credits or hits a rate limit, the next takes over automatically, before any of the response has streamed. Paid x402 endpoints that previously returned errors during a provider outage now degrade to a backup account instead of failing.",
+ "title": "Built-in AI stays up when a provider runs dry",
+ "summary": "The platform's built-in AI (chat, the Brain model workbench, embedded site widgets, tutor, fact-checker, persona tools, agent talk, the transaction explainer) now runs on a deeper safety net. Three independent free lanes — Groq, OpenRouter (with automatic rotation across multiple accounts when one runs out of credits or hits a rate limit), and NVIDIA-hosted models — always serve first, and if every one of them fails, the request quietly falls through to a paid backstop instead of showing you an error. Paid x402 endpoints that previously returned errors during a provider outage now degrade the same way.",
"tags": [
"improvement",
"infra"
diff --git a/public/changelog.json b/public/changelog.json
index ee0231f8c..5af87f40f 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-11T04:19:59.255Z",
+ "generated_at": "2026-06-11T04:22:01.997Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -20,8 +20,8 @@
{
"date": "2026-06-11",
"type": "update",
- "title": "Built-in AI stays up when a provider account runs dry",
- "summary": "The platform's built-in AI (chat, tutor, fact-checker, persona tools) now rotates across multiple OpenRouter accounts: when one account runs out of credits or hits a rate limit, the next takes over automatically, before any of the response has streamed. Paid x402 endpoints that previously returned errors during a provider outage now degrade to a backup account instead of failing.",
+ "title": "Built-in AI stays up when a provider runs dry",
+ "summary": "The platform's built-in AI (chat, tutor, fact-checker, persona tools, agent talk) now runs on a deeper safety net. Three independent free lanes — Groq, OpenRouter (with automatic rotation across multiple accounts when one runs out of credits or hits a rate limit), and NVIDIA-hosted models — always serve first, and if every one of them fails, the request quietly falls through to a paid backstop instead of showing you an error. Paid x402 endpoints that previously returned errors during a provider outage now degrade the same way.",
"link": null,
"tags": [
"improvement",
diff --git a/public/changelog.xml b/public/changelog.xml
index b005763f2..15bd1548b 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -15,12 +15,12 @@
<description>Fetching an individual avatar was failing with a server error, which also broke the walking avatar on the home page. The image-processing engine the avatar dress-up baker relies on failed to load in production and took the whole endpoint down with it. Avatar lookups now load independently of the baker, and the missing image libraries ship with the deployment, so avatar pages and the home hero are back.</description>
</item>
<item>
- <title>Built-in AI stays up when a provider account runs dry</title>
+ <title>Built-in AI stays up when a provider runs dry</title>
<link>https://three.ws/changelog</link>
- <guid isPermaLink="false">2026-06-11:Built-in AI stays up when a provider account runs dry</guid>
+ <guid isPermaLink="false">2026-06-11:Built-in AI stays up when a provider runs dry</guid>
<pubDate>Thu, 11 Jun 2026 12:00:00 GMT</pubDate>
<category>improvement</category>
- <description>The platform's built-in AI (chat, tutor, fact-checker, persona tools) now rotates across multiple OpenRouter accounts: when one account runs out of credits or hits a rate limit, the next takes over automatically, before any of the response has streamed. Paid x402 endpoints that previously returned errors during a provider outage now degrade to a backup account instead of failing.</description>
+ <description>The platform's built-in AI (chat, tutor, fact-checker, persona tools, agent talk) now runs on a deeper safety net. Three independent free lanes — Groq, OpenRouter (with automatic rotation across multiple accounts when one runs out of credits or hits a rate limit), and NVIDIA-hosted models — always serve first, and if every one of them fails, the request quietly falls through to a paid backstop instead of showing you an error. Paid x402 endpoints that previously returned errors during a provider outage now degrade the same way.</description>
</item>
<item>
<title>Faster, quieter agents directory and site-wide page polish</title>
diff --git a/public/error-reporter.js b/public/error-reporter.js
new file mode 100644
index 000000000..912fa6a5a
--- /dev/null
+++ b/public/error-reporter.js
@@ -0,0 +1,220 @@
+// First-party client-side error reporting. Captures uncaught exceptions,
+// unhandled promise rejections, and failed resource loads on every page, then
+// batches them to POST /api/client-errors where they land in the Vercel
+// function logs (searchable as "[client-error]") and Sentry when configured.
+//
+// A tiny inline bootstrap (injected by the `client-error-reporter` plugin in
+// vite.config.js) installs the window listeners synchronously at the top of
+// <head> and queues raw events into window.__threeErrQ; this file loads
+// deferred, drains that queue, and takes over the queue's push so nothing
+// fired during page load is lost.
+//
+// Fails silent by design: a reporting pipeline must never become a source of
+// errors itself, so every send is fire-and-forget and every handler is
+// exception-proof.
+(() => {
+ 'use strict';
+ if (window.__threeErrorReporter) return;
+ window.__threeErrorReporter = true;
+
+ const ENDPOINT = '/api/client-errors';
+ const MAX_EVENTS_PER_PAGE = 25; // hard cap so an error loop can't flood the API
+ const MAX_PER_SIGNATURE = 3; // identical errors beyond this only bump `count`
+ const MAX_BATCH = 10; // flush early once this many events are queued
+ const FLUSH_DELAY_MS = 3000;
+ const LIMITS = { message: 500, stack: 4000, url: 500, name: 100 };
+
+ // Browser-extension frames and well-known benign browser noise. The two
+ // ResizeObserver messages are spec-mandated, thrown by the browser itself,
+ // and not actionable — every error pipeline ignores them.
+ const IGNORED_SOURCES = /^(chrome|moz|safari|safari-web)-extension:/;
+ const IGNORED_MESSAGES = [
+ 'ResizeObserver loop limit exceeded',
+ 'ResizeObserver loop completed with undelivered notifications.',
+ ];
+
+ const truncate = (value, max) => {
+ if (typeof value !== 'string' || !value) return undefined;
+ return value.length > max ? `${value.slice(0, max)}…` : value;
+ };
+
+ const signatures = new Map(); // signature → report (so repeats bump count)
+ let totalAccepted = 0;
+ let queue = [];
+ let flushTimer = null;
+
+ function normalize(raw) {
+ if (!raw || typeof raw !== 'object') return null;
+ if (raw.type === 'unhandledrejection') {
+ const reason = raw.reason;
+ const isError = reason instanceof Error;
+ return {
+ type: 'unhandledrejection',
+ name: isError ? reason.name : undefined,
+ message: isError
+ ? reason.message
+ : typeof reason === 'string'
+ ? reason
+ : safeStringify(reason),
+ stack: isError ? reason.stack : undefined,
+ };
+ }
+ if (raw.type === 'error') {
+ // Resource load failures (script/img/css 404s) arrive as plain Events
+ // on the element, seen only because the bootstrap listens in the
+ // capture phase. Uncaught JS errors arrive as ErrorEvents on window.
+ const target = raw.target;
+ if (target && target !== window && target.nodeName) {
+ const url = target.src || target.href;
+ if (!url || typeof url !== 'string') return null;
+ return {
+ type: 'resource',
+ tag: target.nodeName.toLowerCase(),
+ message: `failed to load ${target.nodeName.toLowerCase()}`,
+ source: url,
+ };
+ }
+ if (typeof raw.message !== 'string') return null;
+ return {
+ type: 'error',
+ name: raw.error && raw.error.name,
+ message: raw.message,
+ source: raw.filename,
+ line: raw.lineno,
+ col: raw.colno,
+ stack: raw.error && raw.error.stack,
+ };
+ }
+ return null;
+ }
+
+ function safeStringify(value) {
+ try {
+ return JSON.stringify(value) ?? String(value);
+ } catch {
+ return String(value);
+ }
+ }
+
+ function shouldIgnore(report) {
+ if (!report.message && !report.source) return true;
+ if (report.source && IGNORED_SOURCES.test(report.source)) return true;
+ if (report.stack && /\b(chrome|moz|safari|safari-web)-extension:\/\//.test(report.stack)) {
+ return true;
+ }
+ if (report.message && IGNORED_MESSAGES.includes(report.message)) return true;
+ return false;
+ }
+
+ function enqueue(report) {
+ if (totalAccepted >= MAX_EVENTS_PER_PAGE || shouldIgnore(report)) return;
+ const signature = [report.type, report.message, report.source, report.line].join('|');
+ const seen = signatures.get(signature);
+ if (seen) {
+ seen.count += 1;
+ if (seen.count > MAX_PER_SIGNATURE) return; // counted, not re-sent
+ } else {
+ report.count = 1;
+ signatures.set(signature, report);
+ }
+ totalAccepted += 1;
+ queue.push({
+ type: report.type,
+ name: truncate(report.name, LIMITS.name),
+ message: truncate(report.message, LIMITS.message),
+ source: truncate(report.source, LIMITS.url),
+ line: Number.isFinite(report.line) ? report.line : undefined,
+ col: Number.isFinite(report.col) ? report.col : undefined,
+ stack: truncate(report.stack, LIMITS.stack),
+ tag: report.tag,
+ ts: Date.now(),
+ });
+ if (queue.length >= MAX_BATCH) {
+ flush();
+ } else if (!flushTimer) {
+ flushTimer = setTimeout(flush, FLUSH_DELAY_MS);
+ }
+ }
+
+ function flush() {
+ if (flushTimer) {
+ clearTimeout(flushTimer);
+ flushTimer = null;
+ }
+ if (!queue.length) return;
+ const payload = JSON.stringify({
+ page: truncate(location.href, LIMITS.url),
+ referrer: truncate(document.referrer, LIMITS.url) || undefined,
+ viewport: { w: window.innerWidth, h: window.innerHeight },
+ events: queue,
+ });
+ queue = [];
+ try {
+ // sendBeacon survives page unload and never blocks the main thread;
+ // keepalive fetch is the fallback for browsers that reject the Blob.
+ const blob = new Blob([payload], { type: 'application/json' });
+ if (navigator.sendBeacon && navigator.sendBeacon(ENDPOINT, blob)) return;
+ } catch {
+ /* fall through to fetch */
+ }
+ try {
+ fetch(ENDPOINT, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: payload,
+ keepalive: true,
+ }).catch(() => {});
+ } catch {
+ /* reporting must never throw */
+ }
+ }
+
+ function handleRaw(raw) {
+ try {
+ const report = normalize(raw);
+ if (report) enqueue(report);
+ } catch {
+ /* never let the reporter become the error */
+ }
+ }
+
+ // Drain events the inline bootstrap queued before this file loaded, then
+ // take over its queue so the bootstrap's listeners feed us directly.
+ const bootQueue = (window.__threeErrQ = window.__threeErrQ || []);
+ const backlog = bootQueue.splice(0);
+ bootQueue.push = (raw) => {
+ handleRaw(raw);
+ return 0;
+ };
+ backlog.forEach(handleRaw);
+
+ // Standalone usage (a page that includes this file without the Vite-injected
+ // bootstrap): install the listeners ourselves.
+ if (!window.__threeErrCap) {
+ window.__threeErrCap = 1;
+ window.addEventListener('error', handleRaw, true);
+ window.addEventListener('unhandledrejection', handleRaw);
+ }
+
+ // Manual reporting hook for app code: window.reportClientError(err, { ...context })
+ window.reportClientError = (err, context) => {
+ try {
+ const isError = err instanceof Error;
+ enqueue({
+ type: 'manual',
+ name: isError ? err.name : undefined,
+ message: isError ? err.message : typeof err === 'string' ? err : safeStringify(err),
+ stack: isError ? err.stack : undefined,
+ source: context && typeof context === 'object' ? safeStringify(context) : undefined,
+ });
+ } catch {
+ /* never throw */
+ }
+ };
+
+ // Ship whatever is still queued when the user leaves the page.
+ addEventListener('visibilitychange', () => {
+ if (document.visibilityState === 'hidden') flush();
+ });
+ addEventListener('pagehide', flush);
+})();
diff --git a/public/features.json b/public/features.json
index b0a85765d..e1c1598a9 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-11T04:19:59.243Z",
+ "generated_at": "2026-06-11T04:22:01.983Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/tests/api/all-modules-load.test.js b/tests/api/all-modules-load.test.js
index da1d52653..4b3f46998 100644
--- a/tests/api/all-modules-load.test.js
+++ b/tests/api/all-modules-load.test.js
@@ -57,10 +57,12 @@ const files = [...walk(API_DIR)]
.sort();
// Some handlers transitively load heavy ESM SDKs (@coinbase/x402, jsdom, the
-// neon serverless client, @anthropic-ai/sdk, etc.). On slow CI workers the
-// cold-import alone can exceed vitest's default 5s. We give each load 60s —
-// well under a real hang, but generous enough to absorb a Codespace cache
-// miss on the first time a given module graph is walked.
+// neon serverless client, @anthropic-ai/sdk, etc.). The cold import is 1-3s in
+// plain Node on an idle box, but under Vitest's ESM transform pipeline (5-9x
+// overhead) WITH the full suite's parallel forks competing for the same cores,
+// a single graph walk has been measured north of 75s (api/_mcp/dispatch.js).
+// 180s keeps this a correctness test — does the module evaluate? — instead of
+// a scheduler race, while still bounding a genuine load-time hang.
describe('every api/**/*.js handler loads', () => {
for (const rel of files) {
it(
@@ -72,7 +74,7 @@ describe('every api/**/*.js handler loads', () => {
// Most Vercel handlers export `default`; some export named handlers (e.g. cron jobs).
// We don't enforce shape — only that the module evaluates without throwing.
},
- 60_000,
+ 180_000,
);
}
});
diff --git a/tests/api/chat-proxy-ratelimit.test.js b/tests/api/chat-proxy-ratelimit.test.js
index d61c2cfad..003181285 100644
--- a/tests/api/chat-proxy-ratelimit.test.js
+++ b/tests/api/chat-proxy-ratelimit.test.js
@@ -12,7 +12,7 @@ const rateLimitState = {
};
vi.mock('../../api/_lib/env.js', () => ({
- env: { APP_ORIGIN: 'http://localhost:3000', OPENROUTER_API_KEY: 'sk-or-test' },
+ env: { APP_ORIGIN: 'http://localhost:3000', OPENROUTER_API_KEY: 'sk-or-test', OPENROUTER_FALLBACK_KEYS: [] },
}));
vi.mock('../../api/_lib/rate-limit.js', () => ({
diff --git a/tests/api/client-errors.test.js b/tests/api/client-errors.test.js
new file mode 100644
index 000000000..38a04385c
--- /dev/null
+++ b/tests/api/client-errors.test.js
@@ -0,0 +1,190 @@
+// Unit tests for /api/client-errors — the client-side error report ingest.
+// Verifies the real contract without network: validation and truncation of
+// attacker-controllable input, the per-event "[client-error]" log line that
+// Vercel log search depends on, Sentry forwarding for JS errors (but not
+// resource 404s), rate limiting, and method/CORS handling.
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+const state = { rateLimited: false };
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ clientErrorsIp: vi.fn(async () =>
+ state.rateLimited
+ ? { success: false, limit: 30, remaining: 0, reset: Date.now() + 60_000 }
+ : { success: true, limit: 30, remaining: 29, reset: Date.now() + 60_000 },
+ ),
+ },
+ clientIp: vi.fn(() => '203.0.113.7'),
+}));
+
+const captureException = vi.fn();
+vi.mock('../../api/_lib/sentry.js', () => ({
+ captureException: (...args) => captureException(...args),
+ captureMessage: vi.fn(),
+}));
+
+const { default: handler } = await import('../../api/client-errors.js');
+
+function makeReq({ method = 'POST', body = null, raw = null } = {}) {
+ const payload = raw ?? (body ? JSON.stringify(body) : '');
+ const req = Readable.from(payload ? [Buffer.from(payload)] : []);
+ req.method = method;
+ req.url = '/api/client-errors';
+ req.headers = {
+ host: 'localhost',
+ 'content-type': 'application/json',
+ 'user-agent': 'TestBrowser/1.0',
+ };
+ return req;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ end(chunk) {
+ if (chunk !== undefined) this.body += chunk;
+ this.writableEnded = true;
+ },
+ };
+}
+
+async function invoke(reqOpts) {
+ const res = makeRes();
+ await handler(makeReq(reqOpts), res);
+ let body = null;
+ try {
+ body = JSON.parse(res.body);
+ } catch {
+ /* non-JSON (e.g. empty 204) */
+ }
+ return { status: res.statusCode, body, res };
+}
+
+const errorEvent = (overrides = {}) => ({
+ type: 'error',
+ name: 'TypeError',
+ message: 'x is not a function',
+ source: 'https://three.ws/app.js',
+ line: 12,
+ col: 3,
+ stack: 'TypeError: x is not a function\n at boot (https://three.ws/app.js:12:3)',
+ ts: 1_750_000_000_000,
+ ...overrides,
+});
+
+let consoleError;
+beforeEach(() => {
+ state.rateLimited = false;
+ captureException.mockClear();
+ consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+});
+afterEach(() => {
+ consoleError.mockRestore();
+});
+
+describe('api/client-errors', () => {
+ it('rejects non-POST methods', async () => {
+ const { status, body } = await invoke({ method: 'GET' });
+ expect(status).toBe(405);
+ expect(body.error).toBe('method_not_allowed');
+ });
+
+ it('answers OPTIONS preflight with 204', async () => {
+ const { status } = await invoke({ method: 'OPTIONS' });
+ expect(status).toBe(204);
+ });
+
+ it('rejects an empty or missing events array', async () => {
+ for (const body of [{}, { events: [] }, { events: 'nope' }]) {
+ const { status, body: out } = await invoke({ body });
+ expect(status).toBe(400);
+ expect(out.error).toBe('validation_error');
+ }
+ });
+
+ it('rejects invalid JSON', async () => {
+ const { status, body } = await invoke({ raw: '{not json' });
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+
+ it('accepts a batch and logs one [client-error] line per event', async () => {
+ const { status, body } = await invoke({
+ body: {
+ page: 'https://three.ws/play',
+ viewport: { w: 1440, h: 900 },
+ events: [errorEvent(), errorEvent({ type: 'unhandledrejection', message: 'boom' })],
+ },
+ });
+ expect(status).toBe(202);
+ expect(body.received).toBe(2);
+ const lines = consoleError.mock.calls.filter(([tag]) => tag === '[client-error]');
+ expect(lines).toHaveLength(2);
+ const logged = JSON.parse(lines[0][1]);
+ expect(logged.message).toBe('x is not a function');
+ expect(logged.page).toBe('https://three.ws/play');
+ expect(logged.ua).toBe('TestBrowser/1.0');
+ expect(logged.ip).toBe('203.0.113.7');
+ });
+
+ it('forwards JS errors to Sentry with the client stack, but not resource events', async () => {
+ await invoke({
+ body: {
+ events: [
+ errorEvent(),
+ { type: 'resource', tag: 'img', message: 'failed to load img', source: 'https://three.ws/x.png' },
+ ],
+ },
+ });
+ expect(captureException).toHaveBeenCalledTimes(1);
+ const [err, ctx] = captureException.mock.calls[0];
+ expect(err.name).toBe('TypeError');
+ expect(err.stack).toContain('at boot (https://three.ws/app.js:12:3)');
+ expect(ctx.origin).toBe('client');
+ });
+
+ it('drops malformed events and truncates oversized fields', async () => {
+ const { status, body } = await invoke({
+ body: {
+ events: [
+ errorEvent({ message: 'a'.repeat(2000), stack: 'b'.repeat(10_000) }),
+ { type: 'bogus-type', message: 'x' },
+ { type: 'error' }, // no message
+ 'not-an-object',
+ ],
+ },
+ });
+ expect(status).toBe(202);
+ expect(body.received).toBe(1);
+ const logged = JSON.parse(
+ consoleError.mock.calls.find(([tag]) => tag === '[client-error]')[1],
+ );
+ expect(logged.message.length).toBe(501); // 500 + ellipsis
+ expect(logged.stack.length).toBe(4001);
+ });
+
+ it('caps a batch at 25 events', async () => {
+ const { status, body } = await invoke({
+ body: { events: Array.from({ length: 40 }, () => errorEvent()) },
+ });
+ expect(status).toBe(202);
+ expect(body.received).toBe(25);
+ });
+
+ it('returns 429 with Retry-After when the IP is rate limited', async () => {
+ state.rateLimited = true;
+ const { status, body, res } = await invoke({ body: { events: [errorEvent()] } });
+ expect(status).toBe(429);
+ expect(body.error).toBe('rate_limited');
+ expect(Number(res.headers['retry-after'])).toBeGreaterThan(0);
+ });
+});
diff --git a/tests/chat-models.test.js b/tests/chat-models.test.js
index b2b5937c7..bc31530ab 100644
--- a/tests/chat-models.test.js
+++ b/tests/chat-models.test.js
@@ -71,16 +71,19 @@ describe('usableModels (route selector)', () => {
});
});
-describe('reliability-first ordering', () => {
- it('ranks anthropic first (keyed paid tier) and openai last (over-quota tier)', () => {
- // Anthropic leads so the happy path resolves on attempt 0 when keyed,
- // instead of burning the rate-limited free tiers first. When Anthropic is
- // unkeyed it's skipped, so the effective lead becomes groq (the free tier).
- expect(DEFAULT_PROVIDER_ORDER[0]).toBe('anthropic');
- expect(DEFAULT_PROVIDER_ORDER[DEFAULT_PROVIDER_ORDER.length - 1]).toBe('openai');
- // Free tiers still rank ahead of the over-quota OpenAI account.
- expect(DEFAULT_PROVIDER_ORDER.indexOf('groq')).toBeLessThan(DEFAULT_PROVIDER_ORDER.indexOf('openai'));
- expect(DEFAULT_PROVIDER_ORDER.indexOf('openrouter')).toBeLessThan(DEFAULT_PROVIDER_ORDER.indexOf('openai'));
+describe('free-first ordering', () => {
+ it('every free provider ranks ahead of every paid provider', () => {
+ // Free providers (Groq → OpenRouter → NVIDIA NIM) always lead; the paid
+ // keys (Anthropic, OpenAI) are last-resort backstops only reached when
+ // all three free lanes have failed.
+ expect(DEFAULT_PROVIDER_ORDER).toEqual(['groq', 'openrouter', 'nvidia', 'anthropic', 'openai']);
+ const free = ['groq', 'openrouter', 'nvidia'];
+ const paid = ['anthropic', 'openai'];
+ for (const f of free) {
+ for (const p of paid) {
+ expect(DEFAULT_PROVIDER_ORDER.indexOf(f), `${f} before ${p}`).toBeLessThan(DEFAULT_PROVIDER_ORDER.indexOf(p));
+ }
+ }
});
it('does not lead the free tier with the moderation-gated model', () => {
@@ -106,7 +109,7 @@ describe('reliability-first ordering', () => {
});
it('anonymous callers are clamped to free providers only', () => {
- expect(ANON_PROVIDER_LIST).toEqual(['groq', 'openrouter']);
+ expect(ANON_PROVIDER_LIST).toEqual(['groq', 'openrouter', 'nvidia']);
expect(ANON_PROVIDER_LIST).not.toContain('openai');
expect(ANON_PROVIDER_LIST).not.toContain('anthropic');
});
diff --git a/vite.config.js b/vite.config.js
index 74db22463..5a5b2e619 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -1182,6 +1182,27 @@ const appConfig = {
},
},
},
+ {
+ // First-party client-side error reporting on every page (embeds
+ // included — errors inside third-party iframe placements are exactly
+ // the ones nobody's DevTools ever sees). The inline bootstrap installs
+ // window error/unhandledrejection listeners synchronously so failures
+ // during page load are captured, queuing raw events into
+ // window.__threeErrQ; the deferred /error-reporter.js (public/) drains
+ // the queue, dedupes/batches, and beacons to /api/client-errors.
+ name: 'client-error-reporter',
+ transformIndexHtml: {
+ order: 'pre',
+ handler() {
+ const BOOTSTRAP =
+ "window.__threeErrQ=window.__threeErrQ||[];window.__threeErrCap=1;addEventListener('error',function(e){window.__threeErrQ.push(e)},!0);addEventListener('unhandledrejection',function(e){window.__threeErrQ.push(e)});";
+ return [
+ { tag: 'script', children: BOOTSTRAP, injectTo: 'head' },
+ { tag: 'script', attrs: { defer: true, src: '/error-reporter.js' }, injectTo: 'head' },
+ ];
+ },
+ },
+ },
{
// Native View Transitions for internal nav. Chrome/Safari ship it,
// Firefox falls back to a normal location change (no UX regression).