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
feat(embed): implement free-first provider chain for embeddings with fallback to paid service
nirholas77e3731c3814
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 50d683c81..755648d1e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,7 +8,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Accurate uptime on the x402 Provider Hub** — The payment directory was counting every unpaid x402 discovery request (the protocol's standard 402 challenge) as a failed call, dragging three.ws endpoint success rates down even when every endpoint was healthy. Telemetry now reports only real payment attempts, so the published uptime reflects actual service health. `[fix, infra]`- **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 runs dry** — 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. `[improvement, infra]`+- **Built-in AI stays up when a provider runs dry** — 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. Agent memory search now runs on a free embeddings lane with the paid provider demoted to backup, and embedded agents configured for a paid model degrade to the free lanes instead of erroring when that provider's key is dead. `[improvement, infra]`- **Embedded avatar chat replies again** — Avatars embedded straight from their public profile — the one-line widget on the homepage and anywhere else the avatar URL is dropped in — went silent when you typed a message: the chat box accepted your text but the avatar never answered. The built-in AI now recognizes a plain public avatar and serves it the free we-pay model with the same per-avatar rate and usage limits, so embedded chat responds out of the box. `[fix]`- **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]`diff --git a/api/_lib/env.js b/api/_lib/env.jsindex 8ff37fa29..78396f993 100644--- a/api/_lib/env.js+++ b/api/_lib/env.js@@ -815,9 +815,11 @@ export const env = {return opt('ELEVENLABS_API_KEY');},- // VoyageAI API key — used by /api/agents/:id/embed for text embeddings (voyage-3-lite).+ // VoyageAI API key — paid lane for /api/agents/:id/embed (voyage-3-lite).+ // Optional: the endpoint leads with the free NVIDIA NIM embedder and only+ // falls back to Voyage when keyed, so absence must not crash the route.get VOYAGE_API_KEY() {- return req('VOYAGE_API_KEY');+ return opt('VOYAGE_API_KEY');},// X (Twitter) OAuth 2.0 PKCE — required for /api/auth/x/* and memory seeding.diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex 71fa1e391..040a61a20 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -252,10 +252,11 @@ export const limits = {upload: (userId) => getLimiter('upload', { limit: 60, window: '1 h' }).limit(userId),avatarPatch: (userId) => getLimiter('avatar:patch', { limit: 20, window: '1 h' }).limit(userId),prefsWrite: (userId) => getLimiter('prefs:write', { limit: 30, window: '1 h' }).limit(userId),- // Per-user budget for the paid Voyage embeddings endpoint (api/agents/:id/embed).- // Keyed by userId (not IP) so the shared platform API key/quota can't be drained- // by one account rotating IPs. recall() embeds one query at a time, so a generous- // per-minute ceiling still leaves headroom for interactive memory search.+ // Per-user budget for the embeddings endpoint (api/agents/:id/embed — free+ // NVIDIA NIM lane first, paid Voyage fallback). Keyed by userId (not IP) so+ // the shared platform keys/quotas can't be drained by one account rotating+ // IPs. recall() embeds one query at a time, so a generous per-minute+ // ceiling still leaves headroom for interactive memory search.embedUser: (userId) => getLimiter('embed:user', { limit: 120, window: '1 m' }).limit(userId),avatarRollback: (userId) =>getLimiter('avatar:rollback', { limit: 10, window: '1 h' }).limit(userId),diff --git a/api/agents/_id/embed.js b/api/agents/_id/embed.jsindex c00ea3bf9..5820915b8 100644--- a/api/agents/_id/embed.js+++ b/api/agents/_id/embed.js@@ -1,6 +1,13 @@// POST /api/agents/:id/embed-// Generates a text embedding via Voyage AI (voyage-3-lite, 1024-dim).-// Used by AgentMemory.recall() for semantic similarity search.+// Generates a 1024-dim text embedding. Used by AgentMemory.recall() for+// semantic similarity search.+//+// Provider policy mirrors api/_lib/llm.js: the FREE lane leads — NVIDIA NIM's+// baai/bge-m3 (1024-dim, one free nvapi key) — and paid Voyage (voyage-3-lite,+// also 1024-dim) is only a keyed fallback. The response carries the `model`+// that produced the vector: embeddings from different models live in different+// vector spaces, so callers that persist vectors should store the model id+// alongside them and only compare like with like.import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../../_lib/auth.js';import { cors, json, method, readJson, error, rateLimited } from '../../_lib/http.js';@@ -8,7 +15,30 @@ import { limits } from '../../_lib/rate-limit.js';import { sql } from '../../_lib/db.js';import { env } from '../../_lib/env.js';-const VOYAGE_URL = 'https://api.voyageai.com/v1/embeddings';+// Ordered free-first. Both produce 1024-dim vectors, matching this endpoint's+// documented contract.+function embedProviderChain() {+ const chain = [];+ if (env.NVIDIA_API_KEY) {+ chain.push({+ name: 'nvidia',+ model: 'baai/bge-m3',+ url: 'https://integrate.api.nvidia.com/v1/embeddings',+ key: env.NVIDIA_API_KEY,+ buildBody: (text) => ({ model: 'baai/bge-m3', input: [text] }),+ });+ }+ if (env.VOYAGE_API_KEY) {+ chain.push({+ name: 'voyage',+ model: 'voyage-3-lite',+ url: 'https://api.voyageai.com/v1/embeddings',+ key: env.VOYAGE_API_KEY,+ buildBody: (text) => ({ model: 'voyage-3-lite', input: [text], input_type: 'query' }),+ });+ }+ return chain;+}export async function handleEmbed(req, res, id) {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;@@ -18,15 +48,16 @@ export async function handleEmbed(req, res, id) {const bearer = session ? null : await authenticateBearer(extractBearer(req));if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');// Match the sibling per-agent sub-resources (nfts.js / pumpfun.js): a bearer- // token must carry an appropriate scope to drive the paid embeddings API.+ // token must carry an appropriate scope to drive the embeddings API.if (bearer && !hasScope(bearer.scope, 'mcp') && !hasScope(bearer.scope, 'profile')) {return error(res, 403, 'insufficient_scope', 'requires mcp or profile scope');}const userId = session?.id || bearer?.userId;- // This route is namespaced per-agent and burns the shared platform Voyage key,- // so it must enforce ownership of :id exactly like every other /api/agents/:id- // sub-resource — never embed against an agent the caller doesn't own.+ // This route is namespaced per-agent and burns shared platform embedding+ // keys, so it must enforce ownership of :id exactly like every other+ // /api/agents/:id sub-resource — never embed against an agent the caller+ // doesn't own.const [agent] = await sql`select id from agent_identitieswhere id = ${id} and user_id = ${userId} and deleted_at is null@@ -46,30 +77,46 @@ export async function handleEmbed(req, res, id) {return error(res, 400, 'validation_error', 'text exceeds 8192 character limit');}- const upstream = await fetch(VOYAGE_URL, {- method: 'POST',- headers: {- 'content-type': 'application/json',- authorization: `Bearer ${env.VOYAGE_API_KEY}`,- },- body: JSON.stringify({- model: 'voyage-3-lite',- input: [text.trim()],- input_type: 'query',- }),- });-- if (!upstream.ok) {- const msg = await upstream.text().catch(() => '');- console.error('[embed] voyage error', upstream.status, msg.slice(0, 200));- return error(res, 502, 'upstream_error', 'embedding service unavailable');+ const chain = embedProviderChain();+ if (!chain.length) {+ return error(res, 503, 'not_configured',+ 'No embedding provider configured. Set NVIDIA_API_KEY (free) or VOYAGE_API_KEY.');}- const data = await upstream.json();- const embedding = data?.data?.[0]?.embedding;- if (!Array.isArray(embedding)) {- return error(res, 502, 'upstream_error', 'unexpected embedding response shape');+ let lastStatus = 0;+ for (const p of chain) {+ let upstream;+ try {+ upstream = await fetch(p.url, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ authorization: `Bearer ${p.key}`,+ },+ body: JSON.stringify(p.buildBody(text.trim())),+ signal: AbortSignal.timeout(15_000),+ });+ } catch (err) {+ console.error(`[embed] ${p.name} unreachable`, err?.message);+ lastStatus = 502;+ continue;+ }+ if (!upstream.ok) {+ const msg = await upstream.text().catch(() => '');+ console.error(`[embed] ${p.name} error`, upstream.status, msg.slice(0, 200));+ lastStatus = upstream.status;+ continue;+ }+ const data = await upstream.json();+ const embedding = data?.data?.[0]?.embedding;+ if (!Array.isArray(embedding)) {+ console.error(`[embed] ${p.name} unexpected response shape`);+ lastStatus = 502;+ continue;+ }+ return json(res, 200, { embedding, model: p.model, provider: p.name });}- return json(res, 200, { embedding });+ return error(res, 502, 'upstream_error',+ `embedding service unavailable (last upstream status ${lastStatus})`);}diff --git a/api/llm/anthropic.js b/api/llm/anthropic.jsindex bb65c27d6..59378e648 100644--- a/api/llm/anthropic.js+++ b/api/llm/anthropic.js@@ -396,14 +396,9 @@ export default wrap(async (req, res) => {const apiKey = process.env[route.envKey];if (!apiKey) {- if (attempt === 0) {- return error(- res,- 503,- 'provider_unavailable',- `${route.envKey} not configured on host`,- );- }+ // An unconfigured provider is never terminal — even for the requested+ // model. Degrade through the chain (free lanes follow); the post-loop+ // guard 503s only when no lane was usable at all.continue;}@@ -435,22 +430,32 @@ export default wrap(async (req, res) => {body: upstreamBody,});- if (upstream.status === 429 || upstream.status >= 500) {+ if (!upstream.ok) {+ // Any upstream failure degrades to the next lane. Account-level+ // failures (401 dead key, 402 no credits, 403, 429) and outages (5xx)+ // look identical to the embedded agent, and every remaining lane is a+ // different account AND model — request-shape errors can't reach here+ // because the body was validated by bodySchema and is rebuilt per+ // provider. Terminal only when the whole chain is exhausted.+ const status = upstream.status;const errText = await upstream.text().catch(() => '');const provider = route.provider || 'anthropic';- log.warn('upstream_rate_limited', {+ log.warn('upstream_error', {agentId,model: usedModel,provider,- status: upstream.status,+ status,attempt,body: errText.slice(0, 400),});if (attempt + 1 < modelFallbacks.length) {console.warn(- `[llm/anthropic] ${provider}/${usedModel} returned ${upstream.status} — ` ++ `[llm/anthropic] ${provider}/${usedModel} returned ${status} — ` +`falling back to ${modelFallbacks[attempt + 1]}`,);+ // Don't let a failed response leak past the loop if every later+ // lane turns out to be unconfigured.+ upstream = null;continue;}// All fallbacks exhausted — surface error.@@ -459,23 +464,10 @@ export default wrap(async (req, res) => {model: usedModel,kind: route.kind,provider,- status: upstream.status,- body: errText.slice(0, 2000),- });- return json(res, 502, { error: 'upstream_error', status: upstream.status });- }-- if (upstream.status >= 400) {- const errText = await upstream.text().catch(() => '');- log.error('upstream_error', {- agentId,- model: usedModel,- kind: route.kind,- provider: route.provider || 'anthropic',- status: upstream.status,+ status,body: errText.slice(0, 2000),});- return json(res, 502, { error: 'upstream_error', status: upstream.status });+ return json(res, 502, { error: 'upstream_error', status });}// Success — log the model used if it differed from the requested one.diff --git a/data/changelog.json b/data/changelog.jsonindex 8af1612ed..a29a1d198 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -21,7 +21,7 @@{"date": "2026-06-11","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.",+ "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. Agent memory search now runs on a free embeddings lane with the paid provider demoted to backup, and embedded agents configured for a paid model degrade to the free lanes instead of erroring when that provider's key is dead.","tags": ["improvement","infra"diff --git a/public/changelog.json b/public/changelog.jsonindex 9778b581e..2e408e5cd 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-11T05:09:19.145Z",+ "generated_at": "2026-06-11T05:44:07.698Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -32,7 +32,7 @@"date": "2026-06-11","type": "update","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.",+ "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. Agent memory search now runs on a free embeddings lane with the paid provider demoted to backup, and embedded agents configured for a paid model degrade to the free lanes instead of erroring when that provider's key is dead.","link": null,"tags": ["improvement",diff --git a/public/changelog.xml b/public/changelog.xmlindex 0f3fe3ad7..d0dc49ee1 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -28,7 +28,7 @@<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, 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.</description>+ <description>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. Agent memory search now runs on a free embeddings lane with the paid provider demoted to backup, and embedded agents configured for a paid model degrade to the free lanes instead of erroring when that provider's key is dead.</description></item><item><title>Embedded avatar chat replies again</title>diff --git a/public/features.json b/public/features.jsonindex 9c4e9b8e4..07a7b962a 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-11T05:09:19.132Z",+ "generated_at": "2026-06-11T05:44:07.683Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/tests/api/agents-embed.test.js b/tests/api/agents-embed.test.jsnew file mode 100644index 000000000..415c23d7d--- /dev/null+++ b/tests/api/agents-embed.test.js@@ -0,0 +1,152 @@+// Tests for POST /api/agents/:id/embed — the AgentMemory.recall() embedder.+// Pins the platform provider policy on this surface: the free NVIDIA NIM lane+// (baai/bge-m3) leads, paid Voyage is only a keyed fallback, a missing key is+// a designed 503 (never a crash), and the response names the model that+// produced the vector so callers can keep vector spaces consistent.++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';++const sqlMock = vi.fn();+vi.mock('../../api/_lib/db.js', () => ({ sql: (...a) => sqlMock(...a) }));++const getSessionUserMock = vi.fn();+vi.mock('../../api/_lib/auth.js', () => ({+ getSessionUser: (...a) => getSessionUserMock(...a),+ authenticateBearer: vi.fn(async () => null),+ extractBearer: vi.fn(() => null),+ hasScope: vi.fn(() => true),+}));++vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { embedUser: vi.fn(async () => ({ success: true })) },+}));++const { handleEmbed } = await import('../../api/agents/_id/embed.js');++function clearKeys() {+ delete process.env.NVIDIA_API_KEY;+ delete process.env.VOYAGE_API_KEY;+}++function mkReq(body) {+ const req = {+ method: 'POST',+ url: '/api/agents/a1/embed',+ headers: { 'content-type': 'application/json' },+ on(event, cb) {+ if (event === 'data') {+ queueMicrotask(() => {+ cb(Buffer.from(JSON.stringify(body)));+ this._endCb?.();+ });+ } else if (event === 'end') {+ this._endCb = cb;+ }+ },+ destroy() {},+ };+ return req;+}++function mkRes() {+ return {+ statusCode: 200,+ headers: {},+ body: '',+ setHeader(k, v) {+ this.headers[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this.headers[k.toLowerCase()];+ },+ end(chunk) {+ if (chunk !== undefined) this.body += String(chunk);+ this.writableEnded = true;+ },+ };+}++const VECTOR = Array.from({ length: 4 }, (_, i) => i / 10);+const okEmbedding = () => ({+ ok: true,+ status: 200,+ json: async () => ({ data: [{ embedding: VECTOR }] }),+ text: async () => '',+});+const errResp = (status) => ({ ok: false, status, json: async () => ({}), text: async () => 'boom' });++beforeEach(() => {+ clearKeys();+ getSessionUserMock.mockResolvedValue({ id: 'u1' });+ sqlMock.mockResolvedValue([{ id: 'a1' }]); // caller owns the agent+});+afterEach(() => {+ vi.restoreAllMocks();+ clearKeys();+});++async function invoke(body = { text: 'hello memory' }) {+ const res = mkRes();+ await handleEmbed(mkReq(body), res, 'a1');+ return { res, json: res.body ? JSON.parse(res.body) : null };+}++describe('POST /api/agents/:id/embed — free-first provider chain', () => {+ it('serves from the free NVIDIA lane when both keys are set', async () => {+ process.env.NVIDIA_API_KEY = 'nvapi-x';+ process.env.VOYAGE_API_KEY = 'pa-paid';+ const calls = [];+ globalThis.fetch = vi.fn(async (url) => {+ calls.push(String(url));+ return okEmbedding();+ });+ const { res, json } = await invoke();+ expect(res.statusCode).toBe(200);+ expect(json.embedding).toEqual(VECTOR);+ expect(json.provider).toBe('nvidia');+ expect(json.model).toBe('baai/bge-m3');+ // Paid Voyage was never touched while the free lane could serve.+ expect(calls).toHaveLength(1);+ expect(calls[0]).toContain('integrate.api.nvidia.com');+ });++ it('falls back to Voyage when NVIDIA errors', async () => {+ process.env.NVIDIA_API_KEY = 'nvapi-x';+ process.env.VOYAGE_API_KEY = 'pa-paid';+ globalThis.fetch = vi.fn(async (url) =>+ String(url).includes('integrate.api.nvidia.com') ? errResp(429) : okEmbedding(),+ );+ const { res, json } = await invoke();+ expect(res.statusCode).toBe(200);+ expect(json.provider).toBe('voyage');+ expect(json.model).toBe('voyage-3-lite');+ });++ it('returns a designed 503 (not a crash) when no embedding key is configured', async () => {+ globalThis.fetch = vi.fn(async () => {+ throw new Error('must not be called');+ });+ const { res, json } = await invoke();+ expect(res.statusCode).toBe(503);+ expect(json.error).toBe('not_configured');+ expect(globalThis.fetch).not.toHaveBeenCalled();+ });++ it('returns 502 with the last upstream status when every provider fails', async () => {+ process.env.NVIDIA_API_KEY = 'nvapi-x';+ process.env.VOYAGE_API_KEY = 'pa-paid';+ globalThis.fetch = vi.fn(async () => errResp(500));+ const { res, json } = await invoke();+ expect(res.statusCode).toBe(502);+ expect(json.error).toBe('upstream_error');+ expect(globalThis.fetch).toHaveBeenCalledTimes(2); // both lanes tried+ });++ it('still validates input before touching any provider', async () => {+ process.env.NVIDIA_API_KEY = 'nvapi-x';+ globalThis.fetch = vi.fn();+ const { res } = await invoke({ text: '' });+ expect(res.statusCode).toBe(400);+ expect(globalThis.fetch).not.toHaveBeenCalled();+ });+});diff --git a/tests/api/llm-anthropic.test.js b/tests/api/llm-anthropic.test.jsindex 3a7ebd771..44f918914 100644--- a/tests/api/llm-anthropic.test.js+++ b/tests/api/llm-anthropic.test.js@@ -516,13 +516,58 @@ describe('/api/llm/anthropic — free-provider routing', () => {expect(call.init.headers.authorization).toBe('Bearer gsk-test');});- it('returns 503 when the upstream API key is not configured', async () => {+ it('degrades through the fallback chain when the requested model has no key', async () => {+ // The requested OpenRouter lane is unkeyed; the request must NOT 503 —+ // it walks the chain and serves from the next configured lane.delete process.env.OPENROUTER_API_KEY;- const { status, body } = await invoke({+ const { status } = await invoke({body: { ...VALID_BODY, model: 'meta-llama/llama-3.3-70b-instruct:free' },});- expect(status).toBe(503);- expect(body.error).toBe('provider_unavailable');+ expect(status).toBe(200);+ // Every attempted call skipped the unkeyed OpenRouter lane.+ expect(fetchState.calls.every((c) => !c.url.includes('openrouter.ai'))).toBe(true);+ });++ it('degrades to a free lane when the keyed upstream rejects with 401 (dead key)', async () => {+ // Account-level 4xx (dead/revoked key) must fall through to the next+ // lane, not surface as a terminal error.+ let first = true;+ fetchState.response = () => {+ if (first) {+ first = false;+ return upstreamErr(401, 'invalid x-api-key');+ }+ return upstreamOk({+ id: 'gen-2',+ choices: [+ { message: { role: 'assistant', content: 'rescued by free lane' }, finish_reason: 'stop' },+ ],+ usage: { prompt_tokens: 3, completion_tokens: 4 },+ });+ };+ const { status } = await invoke({+ body: { ...VALID_BODY, model: 'meta-llama/llama-3.3-70b-instruct:free' },+ });+ expect(status).toBe(200);+ expect(fetchState.calls.length).toBeGreaterThan(1);+ });++ it('returns 503 only when no lane in the chain is configured', async () => {+ delete process.env.OPENROUTER_API_KEY;+ delete process.env.GROQ_API_KEY;+ delete process.env.NVIDIA_API_KEY;+ const savedAnthropic = process.env.ANTHROPIC_API_KEY;+ delete process.env.ANTHROPIC_API_KEY;+ try {+ const { status, body } = await invoke({+ body: { ...VALID_BODY, model: 'meta-llama/llama-3.3-70b-instruct:free' },+ });+ expect(status).toBe(503);+ expect(body.error).toBe('provider_unavailable');+ expect(fetchState.calls).toHaveLength(0);+ } finally {+ process.env.ANTHROPIC_API_KEY = savedAnthropic;+ }});it('translates Anthropic body shape → OpenAI body shape', async () => {