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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(chat): roll over to a live model instead of surfacing a dead one
nirholascfdd8a319b32
diff --git a/api/chat/config.js b/api/chat/config.jsindex 565678f0b..60f40ba67 100644--- a/api/chat/config.js+++ b/api/chat/config.js@@ -2,6 +2,7 @@ import { sql } from '../_lib/db.js';import { env } from '../_lib/env.js';import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';import { constantTimeEquals } from '../_lib/crypto.js';+import { isLiveFreeModel, pickDefaultFreeModel } from '../_lib/openrouter-free.js';import { z } from 'zod';const DEFAULT_SYSTEM_PROMPT = `You are a helpful AI assistant on three.ws — a platform for 3D AI agents, Solana, and pump.fun.@@ -24,11 +25,26 @@ const DEFAULTS = {logo_url: null,accent_color: '#6366f1',tagline: 'Chat with any AI model',- default_model: 'meta-llama/llama-3.3-70b-instruct:free',+ // Resolved from the live free-model list at request time — see+ // withLiveDefaultModel(). A hardcoded id here is exactly what broke chat:+ // OpenRouter retired the configured default and every visitor's first+ // message failed on it.+ default_model: null,agent_id: null,system_prompt: DEFAULT_SYSTEM_PROMPT,};+/**+ * Replace a configured default model that OpenRouter no longer serves with the+ * best live one, so the picker never opens on a dead id. The stored value is+ * left untouched: it becomes authoritative again the moment it is live.+ */+async function withLiveDefaultModel(config) {+ if (config.default_model && (await isLiveFreeModel(config.default_model))) return config;+ const live = await pickDefaultFreeModel({ exclude: [config.default_model].filter(Boolean) });+ return live ? { ...config, default_model: live } : config;+}+const bodySchema = z.object({name: z.string().trim().min(1).max(100),logo_url: z.string().url().max(500).nullable().optional(),@@ -46,11 +62,11 @@ export default wrap(async (req, res) => {// GET — fully publicif (req.method === 'GET') {const [row] = await sql`SELECT name, logo_url, accent_color, tagline, default_model, agent_id, system_prompt FROM chat_brand_config WHERE key = 'global'`;- return json(res, 200, { data: row ?? DEFAULTS });+ return json(res, 200, { data: await withLiveDefaultModel(row ?? DEFAULTS) });}// POST — admin key required (DB row takes precedence over env var, enabling keyless redeploy)- const [configRow] = await sql`SELECT admin_key FROM chat_brand_config WHERE key = 'global'`;+ const [configRow] = await sql`SELECT admin_key, default_model FROM chat_brand_config WHERE key = 'global'`;const adminKey = configRow?.admin_key || env.CHAT_ADMIN_KEY;if (!adminKey) return error(res, 503, 'not_configured', 'Admin key is not configured');@@ -68,6 +84,11 @@ export default wrap(async (req, res) => {return error(res, err.status ?? 400, 'bad_request', err.message);}+ // default_model is NOT NULL in the schema, so an omitted one resolves to the+ // best model live right now rather than to a hardcoded id that will retire.+ const defaultModel =+ body.default_model ?? (await pickDefaultFreeModel()) ?? configRow?.default_model ?? '';+const [row] = await sql`UPDATE chat_brand_configSET@@ -75,7 +96,7 @@ export default wrap(async (req, res) => {logo_url = ${body.logo_url ?? null},accent_color = ${body.accent_color},tagline = ${body.tagline ?? DEFAULTS.tagline},- default_model = ${body.default_model ?? DEFAULTS.default_model},+ default_model = ${defaultModel},agent_id = ${body.agent_id ?? null},system_prompt = ${body.system_prompt ?? DEFAULT_SYSTEM_PROMPT},updated_at = now()diff --git a/api/chat/models.js b/api/chat/models.jsindex 1d8996d2e..09fb3f12a 100644--- a/api/chat/models.js+++ b/api/chat/models.js@@ -1,47 +1,16 @@-import { env } from '../_lib/env.js';import { cors, json, method, wrap } from '../_lib/http.js';+import { listFreeModels } from '../_lib/openrouter-free.js';-// Cache the fetched model list for 5 minutes to avoid hammering OpenRouter.-let cachedModels = null;-let cacheExpiresAt = 0;-+// The live free-model list (fetch, cache, ranking) lives in _lib/openrouter-free.js+// so this endpoint and the completion proxy agree on what is actually serving —+// a picker offering a model the proxy would reject is how /chat broke before.export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS' })) return;if (!method(req, res, ['GET'])) return;- if (!env.OPENROUTER_API_KEY)- return json(res, 200, { data: [] });-- const now = Date.now();- if (cachedModels && now < cacheExpiresAt) {- return json(res, 200, { data: cachedModels });- }-- const upstream = await fetch('https://openrouter.ai/api/v1/models', {- headers: {- Authorization: `Bearer ${env.OPENROUTER_API_KEY}`,- 'HTTP-Referer': 'https://three.ws',- 'X-Title': 'three.ws chat',- },- });-- if (!upstream.ok)- return json(res, 200, { data: [] });-- // OpenRouter occasionally returns a non-JSON error page (HTML/empty) with a 200;- // fall back to the same empty list the !ok branch uses rather than 500-ing.- let allModels;- try {- ({ data: allModels } = await upstream.json());- } catch {- return json(res, 200, { data: [] });- }-- // Only expose free-tier models so completions work via the proxy without a user key.- const freeModels = (allModels ?? []).filter((m) => m.id.endsWith(':free'));-- cachedModels = freeModels;- cacheExpiresAt = now + 5 * 60 * 1000;-- return json(res, 200, { data: freeModels });+ // Ranked best-first, so a client can take data[0] as the default without+ // knowing anything about which ids exist today.+ const models = await listFreeModels();+ res.setHeader('cache-control', 'public, max-age=60');+ return json(res, 200, { data: models });});diff --git a/api/chat/proxy.js b/api/chat/proxy.jsindex 4aa4175ea..92a1cb6c7 100644--- a/api/chat/proxy.js+++ b/api/chat/proxy.js@@ -2,9 +2,24 @@ import { env } from '../_lib/env.js';import { cors, error, json, method, wrap, readJson, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { moderateAnonInput, refusalReply, lastUserMessage } from '../_lib/moderation.js';+import { isFreeModelId, isLiveFreeModel, pickDefaultFreeModel } from '../_lib/openrouter-free.js';const UPGRADE_URL = `${env.APP_ORIGIN}/pricing`;+// How many live models to try before giving up. OpenRouter retires `:free`+// endpoints without notice, and a saved conversation can name one for months+// afterwards; rolling over to a live model keeps that chat working instead of+// surfacing the upstream's raw "This model is unavailable for free" text.+const MAX_MODEL_ATTEMPTS = 3;++/** Upstream said the named model is gone / not free — not that the request was bad. */+function isModelUnavailable(status, body) {+ if (status !== 400 && status !== 404) return false;+ return /unavailable for free|no endpoints found|not a valid model|no allowed providers|is not available/i.test(+ body,+ );+}+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS' })) return;if (!method(req, res, ['POST'])) return;@@ -31,9 +46,18 @@ export default wrap(async (req, res) => {const model = body?.model;// Only allow free-tier OpenRouter models to prevent abuse.- if (!model || !model.endsWith(':free'))+ if (!isFreeModelId(model))return error(res, 400, 'invalid_model', 'Only free-tier models (ending in :free) are allowed via the built-in proxy');+ // A model that OpenRouter no longer serves is swapped for a live one BEFORE+ // the call, so a stale saved conversation costs no round-trip. When the live+ // list is unreachable the model is taken at face value and the post-call+ // rollover below is the safety net.+ let activeModel = model;+ if (!(await isLiveFreeModel(model))) {+ activeModel = (await pickDefaultFreeModel({ exclude: [model] })) ?? model;+ }+// Anonymous pre-moderation (FAIL-OPEN). This proxy is unauthenticated, so// screen the visitor's latest message with the free NIM safety lane before// spending an upstream call. A confirmed-unsafe message gets an in-band@@ -75,20 +99,53 @@ export default wrap(async (req, res) => {// final: every key would fail the same way.const keys = [...new Set([env.OPENROUTER_API_KEY, ...env.OPENROUTER_FALLBACK_KEYS].filter(Boolean))];let upstream;- for (const [i, key] of keys.entries()) {- upstream = await fetch('https://openrouter.ai/api/v1/chat/completions', {- method: 'POST',- headers: {- Authorization: `Bearer ${key}`,- 'Content-Type': 'application/json',- 'HTTP-Referer': 'https://three.ws',- 'X-Title': 'three.ws chat',- },- body: JSON.stringify(body),- });- if (![401, 402, 403, 429].includes(upstream.status) || i === keys.length - 1) break;- // Release the abandoned response so its connection returns to the pool.- await upstream.body?.cancel()?.catch?.(() => {});+ const tried = [];+ for (let attempt = 0; attempt < MAX_MODEL_ATTEMPTS; attempt += 1) {+ tried.push(activeModel);+ for (const [i, key] of keys.entries()) {+ upstream = await fetch('https://openrouter.ai/api/v1/chat/completions', {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${key}`,+ 'Content-Type': 'application/json',+ 'HTTP-Referer': 'https://three.ws',+ 'X-Title': 'three.ws chat',+ },+ body: JSON.stringify({ ...body, model: activeModel }),+ });+ if (![401, 402, 403, 429].includes(upstream.status) || i === keys.length - 1) break;+ // Release the abandoned response so its connection returns to the pool.+ await upstream.body?.cancel()?.catch?.(() => {});+ }++ // A retired model answers identically on every key, so rolling the model+ // is the only recovery. Reading the body here is safe: nothing has been+ // streamed to the client yet.+ if (upstream.status !== 400 && upstream.status !== 404) break;+ const failedBody = await upstream.text();+ if (!isModelUnavailable(upstream.status, failedBody)) {+ // A genuine bad request — hand the upstream's own explanation back.+ res.statusCode = upstream.status;+ res.setHeader('content-type', upstream.headers.get('content-type') ?? 'application/json');+ res.setHeader('cache-control', 'no-store');+ res.end(failedBody);+ return;+ }+ // Either way the current response is spent: roll to the next live model,+ // or fall through to the friendly 503 below. Never re-read this body.+ const next = await pickDefaultFreeModel({ exclude: tried });+ upstream = null;+ if (!next) break;+ activeModel = next;+ }++ if (!upstream) {+ return error(+ res,+ 503,+ 'no_free_model',+ 'Every free model is unavailable right now. Please try again in a moment.',+ );}if (upstream.status === 402) {