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.

Fix: fleet-wide market breaker, NIM flux retry, viewer remount recovery

nirholasfef8ee2e7fbb
diff --git a/api/_lib/market/token-market.js b/api/_lib/market/token-market.js
index e1ce20a68..53fa57801 100644
--- a/api/_lib/market/token-market.js
+++ b/api/_lib/market/token-market.js
@@ -12,7 +12,7 @@
// they can and never crash on a single upstream blip. This is the market-data
// analogue of the RPC failover layer.
-import { cacheGet, cacheSet } from '../cache.js';
+import { cacheGet, cacheSet, cacheDel } from '../cache.js';
const BIRDEYE_BASE = 'https://public-api.birdeye.so';
const DEXSCREENER_BASE = 'https://api.dexscreener.com/latest/dex/tokens';
@@ -40,9 +40,19 @@ const WARN_COOLDOWN_MS = 60_000;
// compute units) or rate-limits us, stop hitting it for a while instead of
// burning a doomed upstream call + warning on every read. Quota exhaustion
// only clears on the provider's billing cycle, so it gets a long cooldown.
+//
+// The breaker is FLEET-WIDE, not per-instance. The in-memory map below is wiped
+// on every Vercel cold start, so a per-instance breaker lets each fresh lambda
+// re-discover the exhausted quota the hard way — one more doomed Birdeye call
+// (which still counts against the compute-unit budget) and one more warning, per
+// cold instance, for the whole 6-hour window. Mirroring the cooldown into the L2
+// (Upstash) cache lets a cold lambda inherit a sibling's verdict and skip the
+// dead source immediately, collapsing fleet-wide waste to ~1 call per window.
const _sourceCooldown = new Map(); // source name → epoch ms to skip until
const QUOTA_COOLDOWN_MS = 6 * 3_600_000;
const RATE_LIMIT_COOLDOWN_MS = 10 * 60_000;
+// Single L2 key holding { source: untilMs } for every source currently cooling.
+const COOLDOWN_KEY = 'mktcool:v1';
function cooldownFor(err) {
const msg = String(err?.message || '');
@@ -51,6 +61,40 @@ function cooldownFor(err) {
return 0;
}
+// Pull the shared cooldown map from L2 and merge any still-active entries into
+// the in-process map, so a cold lambda inherits the fleet's view of dead sources
+// before it tries (and re-burns) them. Best-effort: a cache miss/error just
+// leaves the in-memory map as-is and the read proceeds normally.
+async function hydrateCooldowns(now) {
+ try {
+ const shared = await cacheGet(COOLDOWN_KEY);
+ if (!shared || typeof shared !== 'object') return;
+ for (const [source, until] of Object.entries(shared)) {
+ if (Number(until) > now && Number(until) > (_sourceCooldown.get(source) || 0)) {
+ _sourceCooldown.set(source, Number(until));
+ }
+ }
+ } catch {
+ /* fall through — local breaker still applies */
+ }
+}
+
+// Publish the in-process cooldowns (only those still active) to L2 so siblings
+// inherit them. TTL tracks the longest remaining cooldown; once it expires the
+// key vanishes and sources are retried. Best-effort.
+function publishCooldowns(now) {
+ const active = {};
+ let maxRemainingMs = 0;
+ for (const [source, until] of _sourceCooldown) {
+ if (until > now) {
+ active[source] = until;
+ maxRemainingMs = Math.max(maxRemainingMs, until - now);
+ }
+ }
+ if (maxRemainingMs <= 0) return;
+ cacheSet(COOLDOWN_KEY, active, Math.ceil(maxRemainingMs / 1000)).catch(() => {});
+}
+
function warnThrottled(key, msg) {
const now = Date.now();
if (now - (_warnedAt.get(key) || 0) < WARN_COOLDOWN_MS) return;
@@ -191,6 +235,10 @@ export async function fetchTokenMarketData(mint, { fresh = false, ttlMs = DEFAUL
}
}
+ // Live fetch ahead — inherit the fleet's circuit-breaker state so a cold
+ // lambda skips a source another instance already found exhausted.
+ await hydrateCooldowns(now);
+
for (const src of SOURCES) {
if ((_sourceCooldown.get(src.name) || 0) > now) continue;
try {
@@ -206,6 +254,8 @@ export async function fetchTokenMarketData(mint, { fresh = false, ttlMs = DEFAUL
const cooldown = cooldownFor(err);
if (cooldown) {
_sourceCooldown.set(src.name, now + cooldown);
+ // Broadcast the verdict so sibling lambdas skip this dead source too.
+ publishCooldowns(now);
warnThrottled(`${src.name}:cooldown`, `[market] ${src.name} quota/rate-limited — skipping it for ${Math.round(cooldown / 60_000)}min: ${err?.message}`);
} else {
warnThrottled(`${mint}:${src.name}`, `[market] ${src.name} failed for ${mint.slice(0, 6)}…: ${err?.message}`);
@@ -228,9 +278,12 @@ export async function fetchTokenPriceUsd(mint, opts) {
return md?.price_usd ?? null;
}
-/** Test seam: clear the in-memory caches between cases. */
+/** Test seam: clear the in-memory caches (and the shared cooldown key) between cases. */
export function __resetMarketCache() {
_cache.clear();
_warnedAt.clear();
_sourceCooldown.clear();
+ // Drop the L2 cooldown key so breaker state doesn't leak across cases. On the
+ // in-memory (unconfigured-Upstash) path this runs synchronously.
+ cacheDel(COOLDOWN_KEY);
}
diff --git a/api/_mcp3d/text-to-image.js b/api/_mcp3d/text-to-image.js
index 66bacb40b..0939cdc13 100644
--- a/api/_mcp3d/text-to-image.js
+++ b/api/_mcp3d/text-to-image.js
@@ -29,6 +29,22 @@ const NIM_FLUX_URL = 'https://ai.api.nvidia.com/v1/genai/black-forest-labs/flux.
const NIM_FLUX_MODEL = 'black-forest-labs/flux.1-schnell';
const NIM_TIMEOUT_MS = 60_000;
+// NVCF fronts the free NIM lane with a gateway that answers a cold model or a
+// momentary capacity/routing blip with a transient 502/503/504 that returns
+// FAST (not the slow-job path — that comes back 200/202). The TRELLIS provider
+// already retries these once and it measurably keeps the free lane from
+// dead-ending straight to the (often equally throttled) paid backstop and
+// surfacing to the user as a hard 502; mirror that here. A genuine socket/DNS
+// blip (non-timeout network error) gets the same single retry. A real *timeout*
+// is deliberately NOT retried: the request already burned the full window, so a
+// second attempt would just double the wait before failover (the same reasoning
+// that makes the TRELLIS submit timeout terminal). Bounded to one extra attempt
+// so a genuinely-down gateway still hands off fast.
+const NIM_GATEWAY_RETRY_STATUSES = new Set([502, 503, 504]);
+const NIM_MAX_ATTEMPTS = 2;
+const NIM_RETRY_DELAY_MS = 1_200;
+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
// FLUX wants explicit pixel dimensions (multiples of 64). Map the caller's
// aspect ratio to a sensible ~1MP size; anything unmapped falls back to square.
const NIM_DIMENSIONS = {
@@ -109,54 +125,74 @@ async function nimFluxImage(prompt, aspectRatio) {
const key = readEnv('NVIDIA_API_KEY');
const [width, height] = NIM_DIMENSIONS[aspectRatio] || NIM_DIMENSIONS['1:1'];
- const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), NIM_TIMEOUT_MS);
- let res;
- try {
- res = await fetch(NIM_FLUX_URL, {
- method: 'POST',
- headers: {
- authorization: `Bearer ${key}`,
- accept: 'application/json',
- 'content-type': 'application/json',
- },
- // No cfg_scale: schnell is guidance-distilled and the endpoint enforces
- // cfg_scale <= 0 for it (sending 3.5 422s — verified live 2026-06-11).
- body: JSON.stringify({
- prompt,
- mode: 'base',
- width,
- height,
- seed: 0,
- steps: 4,
- }),
- signal: controller.signal,
- });
- } catch (err) {
- const aborted = err?.name === 'AbortError';
- throw Object.assign(
- new Error(aborted ? 'nim flux timed out' : `nim flux unreachable: ${err?.message}`),
- { code: aborted ? 'rate_limited' : 'provider_unreachable' },
- );
- } finally {
- clearTimeout(timer);
- }
+ let lastErr = null;
+ for (let attempt = 1; attempt <= NIM_MAX_ATTEMPTS; attempt++) {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), NIM_TIMEOUT_MS);
+ let res;
+ try {
+ res = await fetch(NIM_FLUX_URL, {
+ method: 'POST',
+ headers: {
+ authorization: `Bearer ${key}`,
+ accept: 'application/json',
+ 'content-type': 'application/json',
+ },
+ // No cfg_scale: schnell is guidance-distilled and the endpoint enforces
+ // cfg_scale <= 0 for it (sending 3.5 422s — verified live 2026-06-11).
+ body: JSON.stringify({
+ prompt,
+ mode: 'base',
+ width,
+ height,
+ seed: 0,
+ steps: 4,
+ }),
+ signal: controller.signal,
+ });
+ } catch (err) {
+ const aborted = err?.name === 'AbortError' || err?.name === 'TimeoutError';
+ lastErr = Object.assign(
+ new Error(aborted ? 'nim flux timed out' : `nim flux unreachable: ${err?.message}`),
+ { code: aborted ? 'rate_limited' : 'provider_unreachable' },
+ );
+ // A timeout already burned the full window — don't retry it (a second
+ // attempt just doubles the wait before failover). A non-timeout network
+ // blip gets one retry, mirroring the TRELLIS provider.
+ if (!aborted && attempt < NIM_MAX_ATTEMPTS) {
+ await sleep(NIM_RETRY_DELAY_MS);
+ continue;
+ }
+ throw lastErr;
+ } finally {
+ clearTimeout(timer);
+ }
- if (!res.ok) {
- const detail = await res.text().catch(() => '');
- const message = `nim flux returned ${res.status}${detail ? `: ${detail.slice(0, 200)}` : ''}`;
- // 429 (credit-metered free tier) is retryable; surface it so a caller can
- // route, but here it just means "fall through to the paid lanes".
- throw Object.assign(new Error(message), {
- providerStatus: res.status,
- ...(res.status === 429 ? { code: 'rate_limited' } : {}),
- });
- }
+ if (!res.ok) {
+ const detail = await res.text().catch(() => '');
+ const message = `nim flux returned ${res.status}${detail ? `: ${detail.slice(0, 200)}` : ''}`;
+ // A fast transient gateway 5xx (cold model / capacity blip) gets one
+ // retry before we surface it and cascade to the paid lanes.
+ if (NIM_GATEWAY_RETRY_STATUSES.has(res.status) && attempt < NIM_MAX_ATTEMPTS) {
+ lastErr = Object.assign(new Error(message), { providerStatus: res.status });
+ await sleep(NIM_RETRY_DELAY_MS);
+ continue;
+ }
+ // 429 (credit-metered free tier) is retryable upstream; surface it so a
+ // caller can route, but here it just means "fall through to the paid lanes".
+ throw Object.assign(new Error(message), {
+ providerStatus: res.status,
+ ...(res.status === 429 ? { code: 'rate_limited' } : {}),
+ });
+ }
- const data = await res.json().catch(() => ({}));
- const b64 = data?.artifacts?.[0]?.base64;
- if (!b64) throw new Error('nim flux finished but produced no image');
- return { imageUrl: await persistImageBase64(b64), model: NIM_FLUX_MODEL };
+ const data = await res.json().catch(() => ({}));
+ const b64 = data?.artifacts?.[0]?.base64;
+ if (!b64) throw new Error('nim flux finished but produced no image');
+ return { imageUrl: await persistImageBase64(b64), model: NIM_FLUX_MODEL };
+ }
+ // Exhausted retries on a transient status/blip without a terminal verdict.
+ throw lastErr || new Error('nim flux failed after retries');
}
// Words that signal the caller already set their own lighting / background style.
diff --git a/pages/ibm/hello.html b/pages/ibm/hello.html
index 483ce4fbe..2fe4821e2 100644
--- a/pages/ibm/hello.html
+++ b/pages/ibm/hello.html
@@ -1804,24 +1804,37 @@ agent-3d:defined ~ .agent-skel{display:none}
})();
var HEADERS = { 'x-forge-client': CID };
+ // Load model-viewer, resilient to a transient script failure, and resolve to
+ // whether the element is genuinely defined so the caller never mounts an inert
+ // tag. Absolute, not './vendor/…': this page is built to be embedded. On any
+ // host where a relative path doesn't resolve (a preview tool, a partner site,
+ // file://) the element would never upgrade and would sit as a blank box — which
+ // is exactly why the free generator looked broken while <agent-3d> (loaded from
+ // an absolute URL) worked. The canonical copy on three.ws is self-contained and
+ // served with `Access-Control-Allow-Origin: *`, so it upgrades from any origin.
+ var MV_SRC = 'https://three.ws/ibm/vendor/model-viewer.min.js';
var _mv = null;
function ensureModelViewer() {
if (_mv) return _mv;
_mv = new Promise(function (resolve) {
- if (window.customElements && customElements.get('model-viewer')) { resolve(); return; }
- var s = document.createElement('script');
- s.type = 'module';
- // Absolute, not './vendor/…': this page is built to be embedded. On any host
- // where the relative path doesn't resolve (a preview tool, a partner site,
- // file://) the element would never upgrade and sit as a blank box — exactly
- // why the free generator looked broken while <agent-3d> (loaded from an
- // absolute URL) worked. The canonical copy on three.ws is served with
- // `Access-Control-Allow-Origin: *`, so it loads cross-origin anywhere.
- s.src = 'https://three.ws/ibm/vendor/model-viewer.min.js';
- s.addEventListener('error', resolve);
- document.head.appendChild(s);
- if (window.customElements) customElements.whenDefined('model-viewer').then(resolve, resolve);
- else resolve();
+ function defined() { return !!(window.customElements && customElements.get('model-viewer')); }
+ if (defined()) { resolve(true); return; }
+ if (!window.customElements) { resolve(false); return; }
+ var settled = false;
+ function done(v) { if (settled) return; settled = true; resolve(v); }
+ customElements.whenDefined('model-viewer').then(function () { done(true); });
+ function inject(attempt) {
+ var s = document.createElement('script');
+ s.type = 'module';
+ s.src = attempt > 1 ? (MV_SRC + '?r=' + attempt) : MV_SRC;
+ s.addEventListener('error', function () {
+ if (attempt < 3) setTimeout(function () { inject(attempt + 1); }, 600 * attempt);
+ else done(defined());
+ });
+ document.head.appendChild(s);
+ }
+ inject(1);
+ setTimeout(function () { done(defined()); }, 15000); // never hang — report real state
});
return _mv;
}
@@ -1987,28 +2000,58 @@ agent-3d:defined ~ .agent-skel{display:none}
return 'three.ws Forge';
}
+ function viewerMarkup(glb) {
+ return '<div class="mv-wrap"><model-viewer src="' + esc(glb) + '" alt="3D model generated from your prompt" ' +
+ 'camera-controls auto-rotate rotation-per-second="18deg" interaction-prompt="none" ' +
+ 'shadow-intensity="0.7" shadow-softness="0.8" environment-image="neutral" exposure="1" ' +
+ 'camera-orbit="0deg 80deg auto" loading="eager"></model-viewer></div>';
+ }
+
async function renderModel(job, prompt) {
clearInterval(loadTimer);
- await ensureModelViewer();
+ var ready = await ensureModelViewer();
var glb = cdnGlb(job.glb_url);
var scene = 'https://three.ws/scene?model=' + encodeURIComponent(glb) +
'&name=' + encodeURIComponent(prompt.slice(0, 80));
- result.className = 'g3d-result is-done';
- result.innerHTML =
- '<div class="mv-wrap"><model-viewer src="' + esc(glb) + '" alt="3D model generated from your prompt" ' +
- 'camera-controls auto-rotate rotation-per-second="18deg" interaction-prompt="none" ' +
- 'shadow-intensity="0.7" shadow-softness="0.8" environment-image="neutral" exposure="1" ' +
- 'camera-orbit="0deg 80deg auto" loading="eager"></model-viewer></div>' +
+ var actions =
'<div class="g3d-actions">' +
'<a class="g3d-act primary" href="' + esc(glb) + '" download>Download GLB</a>' +
'<a class="g3d-act" href="' + esc(scene) + '" target="_blank" rel="noopener">Open in 3D scene ↗</a>' +
'<span class="g3d-engine">Generated free · ' + esc(engineLabel(job.backend)) + '</span>' +
'</div>';
- // If the viewer fails to load the GLB, don't leave a blank box — surface the
- // designed error so the visitor can retry rather than stare at an empty stage.
- var mv = result.querySelector('model-viewer');
- if (mv) mv.addEventListener('error', function () { setError(); }, { once: true });
+ result.className = 'g3d-result is-done';
+ result.innerHTML = viewerMarkup(glb) + actions;
statusEl.textContent = 'Your 3D model is ready. Orbit it, or download the GLB.';
+
+ // Make the orbit view a certainty, not a hope. Confirm the GLB actually paints
+ // (model-viewer's 'load'); if it errors or never paints, remount the viewer
+ // once — that clears a one-off decode/WebGL-context blip — before falling back
+ // to the designed retry. The visitor either orbits their model or gets a clear
+ // way to recover; never a silent black box.
+ if (!ready) { setError(); return; }
+ var attempted = 0;
+ function mountViewer() {
+ attempted++;
+ var wrap = result.querySelector('.mv-wrap');
+ var mv = wrap && wrap.querySelector('model-viewer');
+ if (!mv) { setError(); return; }
+ var settled = false;
+ var watchdog = setTimeout(function () {
+ // 'load' should fire within seconds of a reachable GLB; if neither load nor
+ // error arrives, treat it as a stall and remount/recover.
+ if (settled) return;
+ if (mv.loaded) { settled = true; return; } // painted, event just missed
+ onProblem();
+ }, 12000);
+ function onProblem() {
+ if (settled) return; settled = true; clearTimeout(watchdog);
+ if (attempted < 2) { result.innerHTML = viewerMarkup(glb) + actions; mountViewer(); }
+ else setError();
+ }
+ mv.addEventListener('load', function () { settled = true; clearTimeout(watchdog); }, { once: true });
+ mv.addEventListener('error', onProblem, { once: true });
+ }
+ mountViewer();
}
async function run() {
diff --git a/tests/api/text-to-image.test.js b/tests/api/text-to-image.test.js
index c06973bc1..9e35cf315 100644
--- a/tests/api/text-to-image.test.js
+++ b/tests/api/text-to-image.test.js
@@ -160,8 +160,10 @@ describe('textToImage — NIM FLUX free lane (first)', () => {
vertexState.generate = vi.fn(async () => {
throw Object.assign(new Error('vertex down'), { code: 'unconfigured' });
});
+ // 500 is a terminal upstream fault (not a retryable gateway 502/503/504), so
+ // NIM is attempted once and the chain cascades straight through.
const calls = stubFetch([
- ['ai.api.nvidia.com', () => new Response('boom', { status: 503 })],
+ ['ai.api.nvidia.com', () => new Response('boom', { status: 500 })],
['api.replicate.com', () => replicateSuccessResponse()],
]);
vi.spyOn(console, 'error').mockImplementation(() => {});
@@ -171,10 +173,63 @@ describe('textToImage — NIM FLUX free lane (first)', () => {
expect(result.imageUrl).toBe('https://replicate.delivery/out.png');
expect(vertexState.generate).toHaveBeenCalledOnce();
- expect(calls.some((c) => c.url.includes('ai.api.nvidia.com'))).toBe(true);
+ expect(calls.filter((c) => c.url.includes('ai.api.nvidia.com'))).toHaveLength(1);
expect(calls.some((c) => c.url.includes('api.replicate.com'))).toBe(true);
});
+ it('retries a transient NIM gateway 504 once, then succeeds inline', async () => {
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+ let nimHits = 0;
+ const calls = stubFetch([
+ [
+ 'ai.api.nvidia.com',
+ () => {
+ nimHits += 1;
+ // First hit: a fast gateway 504 (cold model / routing blip).
+ // Second hit: the warmed model returns the artifact.
+ return nimHits === 1 ? new Response('gateway timeout', { status: 504 }) : nimSuccessResponse();
+ },
+ ],
+ ]);
+
+ vi.useFakeTimers();
+ try {
+ const textToImage = await freshTextToImage();
+ const p = textToImage('a red teapot');
+ await vi.advanceTimersByTimeAsync(2_000); // let the retry backoff elapse
+ const result = await p;
+ expect(result.model).toBe('black-forest-labs/flux.1-schnell');
+ expect(calls.filter((c) => c.url.includes('ai.api.nvidia.com'))).toHaveLength(2);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('does NOT retry a NIM timeout — hands off immediately to avoid a double wait', async () => {
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+ process.env.REPLICATE_API_TOKEN = 'r8_test_token';
+ const calls = stubFetch([
+ [
+ 'ai.api.nvidia.com',
+ () => {
+ // Emulate the AbortController firing: a timeout, not a gateway status.
+ const err = new Error('aborted');
+ err.name = 'TimeoutError';
+ throw err;
+ },
+ ],
+ ['api.replicate.com', () => replicateSuccessResponse()],
+ ]);
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ const textToImage = await freshTextToImage();
+ const result = await textToImage('a red teapot');
+
+ expect(result.imageUrl).toBe('https://replicate.delivery/out.png');
+ // NIM attempted exactly once — a timeout already burned the full window.
+ expect(calls.filter((c) => c.url.includes('ai.api.nvidia.com'))).toHaveLength(1);
+ });
+
it('surfaces the NIM error when it is the only configured lane', async () => {
process.env.NVIDIA_API_KEY = 'nvapi-test';
stubFetch([['ai.api.nvidia.com', () => new Response('nope', { status: 401 })]]);
diff --git a/tests/api/token-market-circuit.test.js b/tests/api/token-market-circuit.test.js
index 382f5680d..bfde94719 100644
--- a/tests/api/token-market-circuit.test.js
+++ b/tests/api/token-market-circuit.test.js
@@ -22,6 +22,7 @@ vi.stubGlobal('fetch', (url) => {
});
import { fetchTokenMarketData, __resetMarketCache } from '../../api/_lib/market/token-market.js';
+import { cacheSet } from '../../api/_lib/cache.js';
const MINT = 'THREEsynthetic111111111111111111111111111111';
@@ -83,6 +84,18 @@ describe('token-market source circuit breaker', () => {
expect(fetchCalls.some((u) => u.includes('birdeye'))).toBe(true);
});
+ it('inherits a fleet-mate cooldown from L2 (cold instance skips a dead source)', async () => {
+ // Simulate a cold lambda: local breaker state is empty, but a sibling already
+ // published an active Birdeye cooldown to the shared cache. The cold instance
+ // must skip Birdeye without burning a doomed call against the exhausted quota.
+ await cacheSet('mktcool:v1', { fromBirdeye: Date.now() + 6 * 3_600_000 }, 6 * 3600);
+
+ fetchResponses = [{ body: DEX_OK }];
+ const result = await fetchTokenMarketData(MINT, { fresh: true });
+ expect(result.source).toBe('dexscreener');
+ expect(fetchCalls.some((u) => u.includes('birdeye'))).toBe(false);
+ });
+
it('trips the breaker on a 429 rate limit as well', async () => {
fetchResponses = [
{ ok: false, status: 429, body: 'rate limited' },