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(forge): three more independent concept-image rungs so no single provider outage can stop text-to-3D
nirholas2771f41523ab
diff --git a/.env.example b/.env.exampleindex 9d9f6a234..98991fdf6 100644--- a/.env.example+++ b/.env.example@@ -107,6 +107,13 @@ NVIDIA_API_KEY=# keeps its own ceiling; this bounds the ladder as a whole so a stalled leading# lane cannot hold a submit open past the caller's socket. Default 60000.# TEXT_TO_IMAGE_BUDGET_MS=60000+#+# The concept-image ladder, free-first: Vertex Imagen (when GOOGLE_CLOUD_PROJECT+# is set and billing is live) -> NVIDIA NIM FLUX.1-dev (NVIDIA_API_KEY) -> HF+# routed providers fal-ai then nscale (HF_TOKEN also unlocks two image rungs,+# billed through the HF account) -> Pollinations (keyless, always present) ->+# Replicate (REPLICATE_API_TOKEN, paid backstop). No single provider outage+# can leave text-to-3D without an image.# SambaNova Cloud (free tier, no card): Llama 3.3 70B on its own free quotadiff --git a/.gitignore b/.gitignoreindex e53ee45d4..a675517f7 100644--- a/.gitignore+++ b/.gitignore@@ -502,3 +502,6 @@ marketing/*/kit/*.html# NotebookLM corpus bundles (regenerate with scripts/build-notebook-corpus.mjs), never commitexports/notebook-corpus/+docs/marketing/articleee.md+docs/marketing/posts.md+docs/marketing/posts2.mddiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5732266d5..c05dcca0c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,8 +6,10 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-08-27+- **three.ws for Seeker** (`/seeker`): The home screen of the three.ws app on Solana Seeker: one-tap Seed Vault sign-in, selfie to avatar, your agents, the marketplace, and Seeker Genesis Token verification.- **Seeker app: stay signed in across restarts, and a submission path that matches today's dApp Store**: On Solana Seeker, the three.ws app now remembers your Seed Vault session when Android restarts the app in the background, so reopening it no longer asks you to approve again; a revoked session is dropped cleanly instead of failing every signature. The My Agents home-screen shortcut opens your own agents instead of the public index. Behind the scenes the store submission tooling was rebuilt for the Publisher Portal that Solana Mobile now uses, and the listing copy was rewritten to describe only what the app really does. (`/my-agents`) `[improvement, fix, infra]`- **Text-to-3D is generating again, and it answers in seconds**: For most of a day, describing something in the forge produced a long wait and then a busy message, on the site, in the ChatGPT app, and for agents buying through OKX. Two things had gone wrong at once: the image provider that paints the concept picture had stopped responding, and the free assistant that sharpens your description was asking for models that no longer exist. Both are fixed. The painter now runs on a model that answers in about five seconds, the assistant uses current models, and a text-to-3D request is accepted in three to eight seconds instead of never. Image-to-3D was never affected. (`/forge`) `[fix]`+- **Text-to-3D now has five independent image sources behind it**: Every text-to-3D generation starts by painting a concept image, and until today that step leaned on two providers. When one of them was cut off and the other stalled, text prompts failed for hours. The painter now tries five independent sources in order: Google's image model, NVIDIA's FLUX.1-dev, two more FLUX providers routed through Hugging Face, and a keyless public service as the final fallback, all under one shared time budget so a slow provider hands off instead of holding your request. A finished model's status is also remembered, so checking on a done job answers instantly instead of re-scoring it every time. (`/forge`) `[fix, infra]`## 2026-08-25diff --git a/api/_lib/ai-image-lanes.js b/api/_lib/ai-image-lanes.jsindex c7b8639f0..a348430b7 100644--- a/api/_lib/ai-image-lanes.js+++ b/api/_lib/ai-image-lanes.js@@ -206,9 +206,39 @@ async function probeReplicate() {* network call. `healthy` is true when at least one lane is reachable, so the* probe distinguishes "not wired yet" from "wired but every lane is down".*/+async function probeHf() {+ if (!readEnv('HF_TOKEN')) return { configured: false, status: 'unconfigured' };+ try {+ const res = await fetch('https://huggingface.co/api/whoami-v2', {+ headers: { authorization: `Bearer ${readEnv('HF_TOKEN')}` },+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),+ });+ if (res.status === 200) return { configured: true, status: 'ok', providers: ['fal-ai', 'nscale'] };+ if (res.status === 401) return { configured: true, status: 'down', detail: 'invalid token' };+ return { configured: true, status: res.status < 500 ? 'ok' : 'down', httpStatus: res.status };+ } catch (err) {+ return { configured: true, status: 'down', detail: err?.message?.slice(0, 120) };+ }+}++async function probePollinations() {+ try {+ const res = await fetch('https://image.pollinations.ai/', { method: 'HEAD', signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });+ return { configured: true, status: res.status < 500 ? 'ok' : 'down', httpStatus: res.status };+ } catch (err) {+ return { configured: true, status: 'down', detail: err?.message?.slice(0, 120) };+ }+}+export async function imageLaneHealth() {- const [nim, vertex, replicate] = await Promise.all([probeNim(), probeVertex(), probeReplicate()]);- const lanes = { nim, vertex, replicate };+ const [nim, vertex, replicate, hf, pollinations] = await Promise.all([+ probeNim(),+ probeVertex(),+ probeReplicate(),+ probeHf(),+ probePollinations(),+ ]);+ const lanes = { nim, vertex, replicate, hf, pollinations };const anyConfigured = Object.values(lanes).some((l) => l.configured);const anyReachable = Object.values(lanes).some((l) => l.status === 'ok');return {diff --git a/api/_mcp3d/text-to-image.js b/api/_mcp3d/text-to-image.jsindex 27d809006..06a3e10de 100644--- a/api/_mcp3d/text-to-image.js+++ b/api/_mcp3d/text-to-image.js@@ -23,7 +23,7 @@import { markProviderCooldown, providersInCooldown } from '../_lib/provider-health.js';import { reserveProviderRateSlot, SCALE_LIMITS } from '../_lib/forge-scale.js';-import { persistImageBase64 } from '../_lib/image-persist.js';+import { persistImageBase64, persistImageBytes, looksLikeImageBytes } from '../_lib/image-persist.js';const REPLICATE_BASE = 'https://api.replicate.com/v1';const DEFAULT_TXT2IMG_MODEL = 'black-forest-labs/flux-schnell';@@ -223,6 +223,122 @@ function parseRetryAfter(headers, message) {return 10;}+// ── Hugging Face routed providers ──────────────────────────────────────────+// HF's own inference backend deprecated every text-to-image model (410 on+// FLUX and SDXL, verified 2026-08-27), but the same HF_TOKEN routes to the+// inference providers HF fronts, billed through the HF account the 3D lane+// already uses. Two independent providers, two rungs: a fal-ai outage does+// not take nscale with it. Both serve FLUX.1-schnell in 2-5 s.+const HF_ROUTER = 'https://router.huggingface.co';+const HF_IMAGE_TIMEOUT_MS = 45_000;+const HF_IMAGE_PROVIDERS = Object.freeze([+ {+ id: 'fal-ai',+ model: 'hf/fal-ai/flux-schnell',+ url: `${HF_ROUTER}/fal-ai/fal-ai/flux/schnell`,+ body: (prompt, width, height, seed) => ({+ prompt,+ image_size: { width, height },+ num_inference_steps: 4,+ num_images: 1,+ ...(Number.isInteger(seed) ? { seed } : {}),+ }),+ // fal answers with a hosted URL; the bytes are fetched and persisted so the+ // reference image lives on our storage like every other lane's.+ extract: async (data, signal) => {+ const url = data?.images?.[0]?.url;+ if (!url || !/^https:\/\//.test(url)) throw new Error('fal-ai returned no image url');+ const res = await fetch(url, { signal });+ if (!res.ok) throw new Error(`fal-ai image fetch returned ${res.status}`);+ return Buffer.from(await res.arrayBuffer());+ },+ },+ {+ id: 'nscale',+ model: 'hf/nscale/flux-schnell',+ url: `${HF_ROUTER}/nscale/v1/images/generations`,+ body: (prompt, width, height, seed) => ({+ model: 'black-forest-labs/FLUX.1-schnell',+ prompt,+ n: 1,+ size: `${width}x${height}`,+ response_format: 'b64_json',+ ...(Number.isInteger(seed) ? { seed } : {}),+ }),+ extract: async (data) => {+ const b64 = data?.data?.[0]?.b64_json;+ if (!b64) throw new Error('nscale returned no image');+ return Buffer.from(b64, 'base64');+ },+ },+]);++async function hfRoutedImage(provider, prompt, aspectRatio, seed, { timeoutMs = HF_IMAGE_TIMEOUT_MS } = {}) {+ const token = readEnv('HF_TOKEN');+ const [width, height] = NIM_DIMENSIONS[aspectRatio] || NIM_DIMENSIONS['1:1'];+ const signal = AbortSignal.timeout(Math.max(1_000, Math.min(HF_IMAGE_TIMEOUT_MS, timeoutMs)));+ let res;+ try {+ res = await fetch(provider.url, {+ method: 'POST',+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json', accept: 'application/json' },+ body: JSON.stringify(provider.body(prompt, width, height, seed)),+ signal,+ });+ } catch (err) {+ const aborted = err?.name === 'AbortError' || err?.name === 'TimeoutError';+ throw Object.assign(new Error(aborted ? `hf ${provider.id} timed out` : `hf ${provider.id} unreachable: ${err?.message}`), {+ code: aborted ? 'rate_limited' : 'provider_unreachable',+ });+ }+ if (!res.ok) {+ const detail = await res.text().catch(() => '');+ const err = new Error(`hf ${provider.id} returned ${res.status}: ${detail.slice(0, 160)}`);+ err.providerStatus = res.status;+ if (res.status === 429 || res.status === 402) err.code = 'rate_limited';+ throw err;+ }+ const bytes = await provider.extract(await res.json(), signal);+ if (!looksLikeImageBytes(bytes)) throw new Error(`hf ${provider.id} returned a non-image body`);+ return { imageUrl: await persistImageBytes(bytes), model: provider.model };+}++// ── Pollinations (keyless) ─────────────────────────────────────────────────+// The last free rung. No key, no account, a real FLUX image in ~2-3 s, lower+// fidelity than the keyed lanes, which is why it sits behind them. It exists+// so that a day when every keyed provider is down still produces a model+// instead of a 429; the text chain already relies on the same service.+const POLLINATIONS_TIMEOUT_MS = 40_000;+async function pollinationsImage(prompt, aspectRatio, seed, { timeoutMs = POLLINATIONS_TIMEOUT_MS } = {}) {+ const [width, height] = NIM_DIMENSIONS[aspectRatio] || NIM_DIMENSIONS['1:1'];+ const q = new URLSearchParams({+ width: String(width),+ height: String(height),+ nologo: 'true',+ model: 'flux',+ ...(Number.isInteger(seed) ? { seed: String(seed) } : {}),+ });+ const url = `https://image.pollinations.ai/prompt/${encodeURIComponent(prompt.slice(0, 1_000))}?${q}`;+ let res;+ try {+ res = await fetch(url, { signal: AbortSignal.timeout(Math.max(1_000, Math.min(POLLINATIONS_TIMEOUT_MS, timeoutMs))) });+ } catch (err) {+ const aborted = err?.name === 'AbortError' || err?.name === 'TimeoutError';+ throw Object.assign(new Error(aborted ? 'pollinations timed out' : `pollinations unreachable: ${err?.message}`), {+ code: aborted ? 'rate_limited' : 'provider_unreachable',+ });+ }+ if (!res.ok) {+ const err = new Error(`pollinations returned ${res.status}`);+ err.providerStatus = res.status;+ if (res.status === 429) err.code = 'rate_limited';+ throw err;+ }+ const bytes = Buffer.from(await res.arrayBuffer());+ if (!looksLikeImageBytes(bytes)) throw new Error('pollinations returned a non-image body');+ return { imageUrl: await persistImageBytes(bytes), model: 'pollinations/flux' };+}+// Image persistence moved to api/_lib/image-persist.js (shared by the NIM// lane, the Vertex reference-image lane, and the Livepeer federation// provider). See that module for why every synthesized image is persisted to@@ -429,7 +545,10 @@ export async function textToImage(prompt, { aspectRatio = '1:1', skipNim = false// otherwise a NIM failure after a Vertex failure would "fall through" to a// lane that was already tried and surface the wrong terminal error. Livepeer// and Replicate both sit after NIM either way, so both always count.- const hasFallback = (!vertexFirst && hasVertex) || hasLivepeer || !!token;+ const hasHf = !!readEnv('HF_TOKEN');+ // Pollinations needs no key, so a fallback always exists past NIM and the+ // keyed rungs: no single provider's failure is ever the terminal error.+ const hasFallback = (!vertexFirst && hasVertex) || hasHf || hasLivepeer || !!token || true;// One attempt at the Vertex lane, shared by both ladder positions. Returns// null to mean "hand off to the next lane" (unconfigured, or a failure with a@@ -498,6 +617,22 @@ export async function textToImage(prompt, { aspectRatio = '1:1', skipNim = falseif (served) return served;}+ // ── Hugging Face routed providers (fal-ai, then nscale) ──────────────────+ if (hasHf) {+ for (const provider of HF_IMAGE_PROVIDERS) {+ if (!canTry()) break;+ try {+ return logImageProvider(+ await hfRoutedImage(provider, prompt, aspectRatio, hasSeed ? seed : undefined, {+ timeoutMs: laneMs(HF_IMAGE_TIMEOUT_MS, true),+ }),+ );+ } catch (err) {+ console.warn(`hf ${provider.id} failed, falling back: ${err?.message}`);+ }+ }+ }+// ── Livepeer federation lane (Phase 4, behind LIVEPEER_FEDERATION_ENABLED) ──// One class of GPU job routed to the decentralized compute network. Sits// after the first-party free lanes (they cost nothing) and before the paid@@ -517,6 +652,22 @@ export async function textToImage(prompt, { aspectRatio = '1:1', skipNim = false}}+ // ── Pollinations, keyless ─────────────────────────────────────────────────+ if (canTry()) {+ try {+ return logImageProvider(+ await pollinationsImage(prompt, aspectRatio, hasSeed ? seed : undefined, {+ timeoutMs: laneMs(POLLINATIONS_TIMEOUT_MS, !!token),+ }),+ );+ } catch (err) {+ if (!token) throw err;+ console.warn(`pollinations failed, falling back: ${err?.message}`);+ }+ } else if (!token) {+ throw budgetExhausted(budget);+ }+// ── Replicate fallback ───────────────────────────────────────────────────if (!token) {throw Object.assign(diff --git a/data/changelog.json b/data/changelog.jsonindex 73a2e860c..769baf0db 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,16 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-08-27",+ "title": "Text-to-3D now has five independent image sources behind it",+ "summary": "Every text-to-3D generation starts by painting a concept image, and until today that step leaned on two providers. When one of them was cut off and the other stalled, text prompts failed for hours. The painter now tries five independent sources in order: Google's image model, NVIDIA's FLUX.1-dev, two more FLUX providers routed through Hugging Face, and a keyless public service as the final fallback, all under one shared time budget so a slow provider hands off instead of holding your request. A finished model's status is also remembered, so checking on a done job answers instantly instead of re-scoring it every time.",+ "tags": [+ "fix",+ "infra"+ ],+ "link": "/forge"+ },{"date": "2026-08-27","title": "Seeker app: stay signed in across restarts, and a submission path that matches today's dApp Store",diff --git a/public/changelog.json b/public/changelog.jsonindex 9d329f6bb..fe4eaacc6 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,21 @@{- "generated_at": "2026-08-27T04:58:40.313Z",+ "generated_at": "2026-08-27T05:37:58.249Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-08-27",+ "type": "launch",+ "title": "three.ws for Seeker",+ "summary": "The home screen of the three.ws app on Solana Seeker: one-tap Seed Vault sign-in, selfie to avatar, your agents, the marketplace, and Seeker Genesis Token verification.",+ "link": "/seeker",+ "tags": [+ "launch"+ ]+ },{"date": "2026-08-27","type": "update",@@ -28,6 +38,17 @@"fix"]},+ {+ "date": "2026-08-27",+ "type": "update",+ "title": "Text-to-3D now has five independent image sources behind it",+ "summary": "Every text-to-3D generation starts by painting a concept image, and until today that step leaned on two providers. When one of them was cut off and the other stalled, text prompts failed for hours. The painter now tries five independent sources in order: Google's image model, NVIDIA's FLUX.1-dev, two more FLUX providers routed through Hugging Face, and a keyless public service as the final fallback, all under one shared time budget so a slow provider hands off instead of holding your request. A finished model's status is also remembered, so checking on a done job answers instantly instead of re-scoring it every time.",+ "link": "/forge",+ "tags": [+ "fix",+ "infra"+ ]+ },{"date": "2026-08-25","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex 1b28a8548..fa668746f 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,14 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws: features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>three.ws for Seeker</title>+ <link>https://three.ws/seeker</link>+ <guid isPermaLink="false">2026-08-27:three.ws for Seeker</guid>+ <pubDate>Thu, 27 Aug 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>The home screen of the three.ws app on Solana Seeker: one-tap Seed Vault sign-in, selfie to avatar, your agents, the marketplace, and Seeker Genesis Token verification.</description>+ </item><item><title>Seeker app: stay signed in across restarts, and a submission path that matches today's dApp Store</title><link>https://three.ws/my-agents</link>@@ -22,6 +30,14 @@<category>fix</category><description>For most of a day, describing something in the forge produced a long wait and then a busy message, on the site, in the ChatGPT app, and for agents buying through OKX. Two things had gone wrong at once: the image provider that paints the concept picture had stopped responding, and the free assistant that sharpens your description was asking for models that no longer exist. Both are fixed. The painter now runs on a model that answers in about five seconds, the assistant uses current models, and a text-to-3D request is accepted in three to eight seconds instead of never. Image-to-3D was never affected.</description></item>+ <item>+ <title>Text-to-3D now has five independent image sources behind it</title>+ <link>https://three.ws/forge</link>+ <guid isPermaLink="false">2026-08-27:Text-to-3D now has five independent image sources behind it</guid>+ <pubDate>Thu, 27 Aug 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>Every text-to-3D generation starts by painting a concept image, and until today that step leaned on two providers. When one of them was cut off and the other stalled, text prompts failed for hours. The painter now tries five independent sources in order: Google's image model, NVIDIA's FLUX.1-dev, two more FLUX providers routed through Hugging Face, and a keyless public service as the final fallback, all under one shared time budget so a slow provider hands off instead of holding your request. A finished model's status is also remembered, so checking on a done job answers instantly instead of re-scoring it every time.</description>+ </item><item><title>Docs · Open-Source Footprint</title><link>https://three.ws/docs/open-source-footprint</link>diff --git a/public/features.json b/public/features.jsonindex 55b2e0a3e..2e778c821 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-08-27T04:44:26.020Z",+ "generated_at": "2026-08-27T05:37:58.227Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -1002,6 +1002,16 @@"tags": [],"showcase": false},+ {+ "path": "/seeker",+ "title": "three.ws for Seeker",+ "description": "The home screen of the three.ws app on Solana Seeker: one-tap Seed Vault sign-in, selfie to avatar, your agents, the marketplace, and Seeker Genesis Token verification.",+ "added": "2026-08-27",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/import/rpm","title": "Import an avatar URL",diff --git a/tests/text-to-image-fallbacks.test.js b/tests/text-to-image-fallbacks.test.jsnew file mode 100644index 000000000..27d3ad728--- /dev/null+++ b/tests/text-to-image-fallbacks.test.js@@ -0,0 +1,98 @@+/**+ * The concept-image ladder (api/_mcp3d/text-to-image.js) has five independent+ * rungs: Vertex, NIM FLUX.1-dev, HF-routed fal-ai, HF-routed nscale, and+ * keyless Pollinations. On 2026-08-27 the first two were both out (billing+ * hold, stalled gateway) and text-to-3D failed for hours; these pin that every+ * later rung is reached, in order, and that the keyless one is always there.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';++process.env.NVIDIA_API_KEY = 'nim-key';+process.env.HF_TOKEN = 'hf-token';+delete process.env.GOOGLE_CLOUD_PROJECT;+delete process.env.REPLICATE_API_TOKEN;+delete process.env.LIVEPEER_FEDERATION_ENABLED;+delete process.env.TEXT_TO_IMAGE_BUDGET_MS;++vi.mock('../api/_lib/provider-health.js', () => ({ providersInCooldown: async () => new Set(), markProviderCooldown: async () => {} }));+vi.mock('../api/_lib/forge-scale.js', () => ({ reserveProviderRateSlot: async () => ({ ok: true, waitMs: 0 }), SCALE_LIMITS: {} }));+vi.mock('../api/_providers/livepeer.js', () => ({ livepeerFederationEnabled: () => false, livepeerTextToImage: async () => { throw new Error('unused'); } }));+const persisted = vi.hoisted(() => ({ calls: 0 }));+vi.mock('../api/_lib/image-persist.js', async (importOriginal) => {+ const real = await importOriginal();+ return { ...real, persistImageBytes: async () => { persisted.calls++; return `https://cdn.test/img-${persisted.calls}.png`; }, persistImageBase64: async () => { persisted.calls++; return `https://cdn.test/img-${persisted.calls}.png`; } };+});++const { textToImage } = await import('../api/_mcp3d/text-to-image.js');++const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3]);+const JPG = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 1, 2, 3]);+const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });+const bytes = (b, type) => new Response(b, { status: 200, headers: { 'content-type': type } });++// Per-test behaviour by host.+const lane = {};+const hits = [];+globalThis.fetch = vi.fn(async (url, init) => {+ const u = String(url);+ hits.push(u);+ if (u.includes('ai.api.nvidia.com')) return lane.nim(init);+ if (u.includes('router.huggingface.co/fal-ai')) return lane.fal(init);+ if (u.includes('fal.media')) return bytes(JPG, 'image/jpeg');+ if (u.includes('router.huggingface.co/nscale')) return lane.nscale(init);+ if (u.includes('image.pollinations.ai')) return lane.pollinations(init);+ throw new Error(`unexpected fetch ${u}`);+});++beforeEach(() => {+ hits.length = 0;+ persisted.calls = 0;+ lane.nim = () => json(502, { error: 'gateway' });+ lane.fal = () => json(503, {});+ lane.nscale = () => json(503, {});+ lane.pollinations = () => bytes(JPG, 'image/jpeg');+});++describe('the ladder reaches every rung in order', () => {+ it('NIM serves first when it is up', async () => {+ lane.nim = () => json(200, { artifacts: [{ base64: Buffer.from(PNG).toString('base64'), finishReason: 'SUCCESS' }] });+ const out = await textToImage('a fox', { budgetMs: 20_000 });+ expect(out.model).toBe('black-forest-labs/flux.1-dev');+ expect(hits.some((u) => u.includes('huggingface'))).toBe(false);+ });++ it('falls to HF fal-ai when NIM fails, and fetches the hosted image it returns', async () => {+ lane.fal = () => json(200, { images: [{ url: 'https://v3b.fal.media/files/x.jpg' }] });+ const out = await textToImage('a fox', { budgetMs: 20_000 });+ expect(out.model).toBe('hf/fal-ai/flux-schnell');+ expect(out.imageUrl).toMatch(/^https:\/\/cdn\.test\//);+ expect(hits.some((u) => u.includes('nscale'))).toBe(false);+ });++ it('falls to HF nscale when fal-ai fails too', async () => {+ lane.nscale = () => json(200, { data: [{ b64_json: Buffer.from(PNG).toString('base64') }] });+ const out = await textToImage('a fox', { budgetMs: 20_000 });+ expect(out.model).toBe('hf/nscale/flux-schnell');+ });++ it('ends on keyless Pollinations when every keyed rung is down', async () => {+ const out = await textToImage('a fox', { budgetMs: 20_000 });+ expect(out.model).toBe('pollinations/flux');+ expect(hits.filter((u) => u.includes('huggingface'))).toHaveLength(2);+ });++ it('sends the NIM request flux.1-dev needs (steps >= 5, a cfg_scale)', async () => {+ let body;+ lane.nim = (init) => { body = JSON.parse(init.body); return json(200, { artifacts: [{ base64: Buffer.from(PNG).toString('base64') }] }); };+ await textToImage('a fox', { budgetMs: 20_000 });+ expect(body.steps).toBeGreaterThanOrEqual(5);+ expect(body.cfg_scale).toBeGreaterThan(0);+ expect(hits[0]).toContain('flux.1-dev');+ });++ it('refuses a non-image body from a rung instead of persisting garbage', async () => {+ lane.pollinations = () => bytes(new Uint8Array([0x3c, 0x68, 0x74, 0x6d, 0x6c]), 'text/html');+ await expect(textToImage('a fox', { budgetMs: 20_000 })).rejects.toThrow(/non-image/);+ expect(persisted.calls).toBe(0);+ });+});