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.

llm: OpenRouter fallback chain; bonfida bare import; vitest fork cap tweak

nirholas13044aaace6a
diff --git a/api/llm/anthropic.js b/api/llm/anthropic.js
index 36f0515e4..d5cf3083a 100644
--- a/api/llm/anthropic.js
+++ b/api/llm/anthropic.js
@@ -235,59 +235,127 @@ export default wrap(async (req, res) => {
const rawBody = await readJson(req);
const body = parse(bodySchema, rawBody);
- const model = body.model || policy.brain?.model || 'meta-llama/llama-3.3-70b-instruct:free';
- const route = MODELS[model];
- if (!route) {
- return error(res, 400, 'validation_error', `model "${model}" not in allowlist`);
- }
-
- const apiKey = process.env[route.envKey];
- if (!apiKey) {
- return error(res, 503, 'provider_unavailable', `${route.envKey} not configured on host`);
- }
+ const requestedModel = body.model || policy.brain?.model || 'meta-llama/llama-3.3-70b-instruct:free';
+
+ // Ordered fallback chain for 429 / 5xx from OpenRouter free tier:
+ // 1. Requested model (e.g. llama-3.3-70b:free)
+ // 2. meta-llama/llama-3.1-8b-instruct:free (smaller free model)
+ // 3. claude-haiku-4-5-20251001 (paid Anthropic — last resort)
+ const modelFallbacks = [
+ requestedModel,
+ ...([
+ 'meta-llama/llama-3.1-8b-instruct:free',
+ 'claude-haiku-4-5-20251001',
+ ].filter((m) => m !== requestedModel)),
+ ];
const isStreaming = body.stream === true;
const t0 = Date.now();
- const upstreamUrl = route.kind === 'anthropic' ? UPSTREAM_URL.anthropic : UPSTREAM_URL[route.provider];
- const upstreamHeaders =
- route.kind === 'anthropic'
- ? {
- 'content-type': 'application/json',
- 'anthropic-version': '2023-06-01',
- 'x-api-key': apiKey,
- }
- : {
- 'content-type': 'application/json',
- authorization: `Bearer ${apiKey}`,
- ...(route.provider === 'openrouter'
- ? { 'HTTP-Referer': 'https://three.ws', 'X-Title': 'three.ws agent' }
- : {}),
- };
- const upstreamBody =
- route.kind === 'anthropic'
- ? JSON.stringify({ ...body, model })
- : JSON.stringify(anthropicBodyToOpenAI({ ...body, model }));
-
- const upstream = await fetch(upstreamUrl, {
- method: 'POST',
- headers: upstreamHeaders,
- body: upstreamBody,
- });
+ let upstream;
+ let usedModel = requestedModel;
+ let usedRoute = null;
- if (upstream.status >= 400) {
- const errText = await upstream.text();
- log.error('upstream_error', {
- agentId,
- model,
- kind: route.kind,
- provider: route.provider || 'anthropic',
- status: upstream.status,
- body: errText.slice(0, 2000),
+ for (let attempt = 0; attempt < modelFallbacks.length; attempt++) {
+ usedModel = modelFallbacks[attempt];
+ const route = MODELS[usedModel];
+ if (!route) {
+ if (attempt === 0) {
+ return error(res, 400, 'validation_error', `model "${usedModel}" not in allowlist`);
+ }
+ continue;
+ }
+
+ const apiKey = process.env[route.envKey];
+ if (!apiKey) {
+ if (attempt === 0) {
+ return error(res, 503, 'provider_unavailable', `${route.envKey} not configured on host`);
+ }
+ continue;
+ }
+
+ usedRoute = route;
+ const upstreamUrl = route.kind === 'anthropic' ? UPSTREAM_URL.anthropic : UPSTREAM_URL[route.provider];
+ const upstreamHeaders =
+ route.kind === 'anthropic'
+ ? {
+ 'content-type': 'application/json',
+ 'anthropic-version': '2023-06-01',
+ 'x-api-key': apiKey,
+ }
+ : {
+ 'content-type': 'application/json',
+ authorization: `Bearer ${apiKey}`,
+ ...(route.provider === 'openrouter'
+ ? { 'HTTP-Referer': 'https://three.ws', 'X-Title': 'three.ws agent' }
+ : {}),
+ };
+ const upstreamBody =
+ route.kind === 'anthropic'
+ ? JSON.stringify({ ...body, model: usedModel })
+ : JSON.stringify(anthropicBodyToOpenAI({ ...body, model: usedModel }));
+
+ upstream = await fetch(upstreamUrl, {
+ method: 'POST',
+ headers: upstreamHeaders,
+ body: upstreamBody,
});
- return json(res, 502, { error: 'upstream_error', status: upstream.status });
+
+ if (upstream.status === 429 || upstream.status >= 500) {
+ const errText = await upstream.text().catch(() => '');
+ const provider = route.provider || 'anthropic';
+ log.warn('upstream_rate_limited', {
+ agentId,
+ model: usedModel,
+ provider,
+ status: upstream.status,
+ attempt,
+ body: errText.slice(0, 400),
+ });
+ if (attempt + 1 < modelFallbacks.length) {
+ console.warn(
+ `[llm/anthropic] ${provider}/${usedModel} returned ${upstream.status} — ` +
+ `falling back to ${modelFallbacks[attempt + 1]}`,
+ );
+ continue;
+ }
+ // All fallbacks exhausted — surface error.
+ log.error('upstream_error', {
+ agentId,
+ 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,
+ body: errText.slice(0, 2000),
+ });
+ return json(res, 502, { error: 'upstream_error', status: upstream.status });
+ }
+
+ // Success — log the model used if it differed from the requested one.
+ if (usedModel !== requestedModel) {
+ console.info(
+ `[llm/anthropic] agentId=${agentId} used fallback model ${usedModel} ` +
+ `(requested: ${requestedModel})`,
+ );
+ }
+ break;
}
+ const route = usedRoute;
+
// ── Streaming path ────────────────────────────────────────────────────────
if (isStreaming) {
res.statusCode = 200;
@@ -328,7 +396,7 @@ export default wrap(async (req, res) => {
}
} else {
// OpenAI-shape upstream → translate to Anthropic SSE shape on the fly.
- const usage = await pipeOpenAIAsAnthropic(upstream, res, { model });
+ const usage = await pipeOpenAIAsAnthropic(upstream, res, { model: usedModel });
inputTokens = usage.inputTokens;
outputTokens = usage.outputTokens;
}
@@ -348,7 +416,7 @@ export default wrap(async (req, res) => {
bytes: 0,
latencyMs,
status: 'ok',
- meta: { model, input_tokens: inputTokens, output_tokens: outputTokens, upstream_status: upstream.status },
+ meta: { model: usedModel, requested_model: requestedModel, input_tokens: inputTokens, output_tokens: outputTokens, upstream_status: upstream.status },
});
return;
}
@@ -375,7 +443,7 @@ export default wrap(async (req, res) => {
} else if (upstreamJson) {
inputTokens = upstreamJson?.usage?.prompt_tokens ?? 0;
outputTokens = upstreamJson?.usage?.completion_tokens ?? 0;
- const translated = openAIResponseToAnthropic(upstreamJson, { model });
+ const translated = openAIResponseToAnthropic(upstreamJson, { model: usedModel });
outBody = JSON.stringify(translated);
outContentType = 'application/json';
}
@@ -395,7 +463,7 @@ export default wrap(async (req, res) => {
bytes: upstreamText.length,
latencyMs,
status: 'ok',
- meta: { model, input_tokens: inputTokens, output_tokens: outputTokens, upstream_status: upstream.status },
+ meta: { model: usedModel, requested_model: requestedModel, input_tokens: inputTokens, output_tokens: outputTokens, upstream_status: upstream.status },
});
res.statusCode = 200;
diff --git a/src/solana/sns.js b/src/solana/sns.js
index 8156ea101..ba936cebe 100644
--- a/src/solana/sns.js
+++ b/src/solana/sns.js
@@ -4,6 +4,11 @@ import { Connection, PublicKey } from '@solana/web3.js';
// function bundler on cold start when statically imported by serverless
// endpoints. Load it on demand inside each call so the dispatcher modules
// (e.g. /api/portfolio, /api/pump-fun-mcp) don't pay the cost up front.
+//
+// Note: we used to import the CJS entry directly (`.../dist/cjs/index.js`)
+// to skip ESM init, but Vite 7 enforces the package's `exports` map and
+// rejects that subpath. The bare package import works under both the dev
+// bundler and Vercel because the dynamic import keeps it lazy.
// Server-side: prefer SOLANA_RPC_URL (typically Helius). Browser-side: route
// through our same-origin proxy because public mainnet-beta 403s most origins.
@@ -28,7 +33,7 @@ function stripSol(name) {
*/
export async function resolveSnsName(name) {
try {
- const { resolve } = await import('@bonfida/spl-name-service/dist/cjs/index.js');
+ const { resolve } = await import('@bonfida/spl-name-service');
const pk = await resolve(makeConnection(), stripSol(name));
return pk.toBase58();
} catch {
@@ -43,7 +48,7 @@ export async function resolveSnsName(name) {
*/
export async function reverseLookupAddress(addr) {
try {
- const { getFavoriteDomain } = await import('@bonfida/spl-name-service/dist/cjs/index.js');
+ const { getFavoriteDomain } = await import('@bonfida/spl-name-service');
const owner = new PublicKey(addr);
const { reverse } = await getFavoriteDomain(makeConnection(), owner);
return reverse.endsWith('.sol') ? reverse : `${reverse}.sol`;
diff --git a/vitest.config.js b/vitest.config.js
index 67a42d368..b7556873e 100644
--- a/vitest.config.js
+++ b/vitest.config.js
@@ -12,8 +12,12 @@ import os from 'node:os';
// repeatedly miss their hookTimeout. We cap forks at min(4, cpus - 1) so worker
// startup never queues behind a busy peer. Locally on a beefy machine
// (CPUs > 4) this still parallelizes; small hosts get safe serialisation.
+// On CI / Codespaces the box is small (typically 2-4 cores, capped memory),
+// and heavy ESM cold-imports across files compete for the same V8 instance.
+// We cap forks at 2 for hosts with <=4 cores so cold loads aren't blocked by
+// peer workers. Beefier machines (>4 cores) parallelise up to (cpus - 1, max 6).
const _cpus = Math.max(1, (os.availableParallelism?.() ?? os.cpus().length) - 1);
-const MAX_FORKS = Math.max(1, Math.min(4, _cpus));
+const MAX_FORKS = _cpus <= 3 ? 2 : Math.min(6, _cpus);
export default defineConfig({
test: {