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(vision): T4.1 shared NIM vision helper bookkeeping — tests, changelog, plan
nirholasf53ac7ab198e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 93c22463b..ae15892ea 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,8 +14,10 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Avatar preview images load reliably** — Fixed a bug where some community avatars — including the pinned home-town cast — showed a broken preview image in the /play lobby and gallery instead of their portrait. The shareable social-card image for those avatars now generates and serves correctly too, so links posted to X and Discord render a proper preview. (`/play`) `[fix]`- **Avatar voices can speak out loud again** — Talking avatars are back. Spoken playback had gone silent after our previous voice provider ran out of quota, leaving the live lip-sync demo and the read-the-page-aloud browser extension mute. We've moved avatar speech onto a new free, fast voice lane that generates audio in about a second, so every speaking surface talks again with no change to how you use it. Nothing to update — pick a voice and press play. (`/lipsync`) `[fix]`- **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]`+- **Create an avatar from a template or from scratch, right from the dashboard** — The dashboard's Avatars page only offered selfie and GLB-upload as ways to make a new avatar — the two fastest paths, starting from a ready-made template or sculpting one from scratch, were buried elsewhere. The '+ New avatar' menu now groups every option clearly: Build (start from a template, or build from scratch in the studio), From you (snap a selfie, full selfie flow, or describe it as a prompt), and Import (upload a GLB, copy an existing avatar, or browse the public gallery). 'Start from a template' opens a picker with live 3D previews and stages your pick straight into the save step. The empty state leads with the same three quick starts. (`/dashboard/avatars`) `[feature, improvement]`- **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]`+- **Forge checks your photo before spending a generation — plus image-aware fact-checks and accessible galleries** — A new free image-understanding layer (running on NVIDIA's free models, so it costs you nothing) now powers three things across three.ws. In Forge, when you upload a photo to turn into 3D, it's checked first: if it's a screenshot of text, a cluttered scene with no clear subject, or too dark to reconstruct, you get a clear heads-up and a fix before a generation slot is spent — with a one-click 'Generate anyway' if you disagree. The Fact Checker can now take an image alongside a claim: it reads the picture, transcribes any text in it, and weighs that as evidence in the verdict. And every avatar in the public gallery now gets a real, descriptive alt text written from its thumbnail, so screen-reader users hear what each avatar actually looks like instead of just its name. All three quietly switch off if the vision service is ever unavailable — nothing ever blocks or breaks. (`/forge`) `[feature, improvement]`- **Forge share links now open your creation for anyone you send them to** — When you share a model from Forge, the person who opens the link now sees your actual creation — the 3D model loads straight into the viewer, ready to spin, inspect, and download. Previously a share link only worked for the person who forged the model, because Forge only looked in your own browser's history; recipients landed on an empty Forge. Now the page fetches the shared model by its link and shows it to anyone, even if they've never used Forge before. If a link points to a model that was removed or is still generating, you get a clear message instead of a blank screen. (`/forge`) `[fix, improvement]`- **Free 3D draft generations no longer get blocked by the paid rate limit** — Generating a 3D model from a text prompt on the Draft tier runs on a free engine — no key, no cost. But it was sharing the same hourly limit as the paid lanes, so a few quick iterations (or several people on the same office or campus network) could hit a 'generator is busy, try again later' wall even though nothing was being charged. The free draft lane now has its own, far more generous allowance and never blocks you because of a backend hiccup. Heavy paid generations keep their tighter limit. Iterate on prompts freely. (`/forge`) `[fix, improvement]`- **Free 3D drafts on Forge** — Draft generations from a text prompt on Forge now run on a free NVIDIA-hosted TRELLIS engine by default — your first 3D model costs nothing and arrives in about 15 seconds, several times faster than the previous default. Photo-to-3D keeps its proven engine (the free lane is prompt-only by design), and every existing engine — TRELLIS on Replicate, Meshy, Tripo — remains selectable at every quality tier. (`/forge`) `[feature, improvement]`diff --git a/data/changelog.json b/data/changelog.jsonindex 6fbd966d0..ed0af3ebd 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,26 @@{"$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-06-11",+ "title": "Forge checks your photo before spending a generation — plus image-aware fact-checks and accessible galleries",+ "summary": "A new free image-understanding layer (running on NVIDIA's free models, so it costs you nothing) now powers three things across three.ws. In Forge, when you upload a photo to turn into 3D, it's checked first: if it's a screenshot of text, a cluttered scene with no clear subject, or too dark to reconstruct, you get a clear heads-up and a fix before a generation slot is spent — with a one-click 'Generate anyway' if you disagree. The Fact Checker can now take an image alongside a claim: it reads the picture, transcribes any text in it, and weighs that as evidence in the verdict. And every avatar in the public gallery now gets a real, descriptive alt text written from its thumbnail, so screen-reader users hear what each avatar actually looks like instead of just its name. All three quietly switch off if the vision service is ever unavailable — nothing ever blocks or breaks.",+ "tags": [+ "feature",+ "improvement"+ ],+ "link": "/forge"+ },+ {+ "date": "2026-06-11",+ "title": "Create an avatar from a template or from scratch, right from the dashboard",+ "summary": "The dashboard's Avatars page only offered selfie and GLB-upload as ways to make a new avatar — the two fastest paths, starting from a ready-made template or sculpting one from scratch, were buried elsewhere. The '+ New avatar' menu now groups every option clearly: Build (start from a template, or build from scratch in the studio), From you (snap a selfie, full selfie flow, or describe it as a prompt), and Import (upload a GLB, copy an existing avatar, or browse the public gallery). 'Start from a template' opens a picker with live 3D previews and stages your pick straight into the save step. The empty state leads with the same three quick starts.",+ "tags": [+ "feature",+ "improvement"+ ],+ "link": "/dashboard/avatars"+ },{"date": "2026-06-11","title": "Free 3D draft generations no longer get blocked by the paid rate limit",diff --git a/public/changelog.json b/public/changelog.jsonindex a29feadb3..9c2a0740e 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-11T14:29:15.185Z",+ "generated_at": "2026-06-11T14:33:36.325Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -90,6 +90,17 @@"infra"]},+ {+ "date": "2026-06-11",+ "type": "update",+ "title": "Create an avatar from a template or from scratch, right from the dashboard",+ "summary": "The dashboard's Avatars page only offered selfie and GLB-upload as ways to make a new avatar — the two fastest paths, starting from a ready-made template or sculpting one from scratch, were buried elsewhere. The '+ New avatar' menu now groups every option clearly: Build (start from a template, or build from scratch in the studio), From you (snap a selfie, full selfie flow, or describe it as a prompt), and Import (upload a GLB, copy an existing avatar, or browse the public gallery). 'Start from a template' opens a picker with live 3D previews and stages your pick straight into the save step. The empty state leads with the same three quick starts.",+ "link": "/dashboard/avatars",+ "tags": [+ "feature",+ "improvement"+ ]+ },{"date": "2026-06-11","type": "update",@@ -111,6 +122,17 @@"fix"]},+ {+ "date": "2026-06-11",+ "type": "update",+ "title": "Forge checks your photo before spending a generation — plus image-aware fact-checks and accessible galleries",+ "summary": "A new free image-understanding layer (running on NVIDIA's free models, so it costs you nothing) now powers three things across three.ws. In Forge, when you upload a photo to turn into 3D, it's checked first: if it's a screenshot of text, a cluttered scene with no clear subject, or too dark to reconstruct, you get a clear heads-up and a fix before a generation slot is spent — with a one-click 'Generate anyway' if you disagree. The Fact Checker can now take an image alongside a claim: it reads the picture, transcribes any text in it, and weighs that as evidence in the verdict. And every avatar in the public gallery now gets a real, descriptive alt text written from its thumbnail, so screen-reader users hear what each avatar actually looks like instead of just its name. All three quietly switch off if the vision service is ever unavailable — nothing ever blocks or breaks.",+ "link": "/forge",+ "tags": [+ "feature",+ "improvement"+ ]+ },{"date": "2026-06-11","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 5cf869c52..87b567e62 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -70,6 +70,14 @@<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. 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>Create an avatar from a template or from scratch, right from the dashboard</title>+ <link>https://three.ws/dashboard/avatars</link>+ <guid isPermaLink="false">2026-06-11:Create an avatar from a template or from scratch, right from the dashboard</guid>+ <pubDate>Thu, 11 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The dashboard's Avatars page only offered selfie and GLB-upload as ways to make a new avatar — the two fastest paths, starting from a ready-made template or sculpting one from scratch, were buried elsewhere. The '+ New avatar' menu now groups every option clearly: Build (start from a template, or build from scratch in the studio), From you (snap a selfie, full selfie flow, or describe it as a prompt), and Import (upload a GLB, copy an existing avatar, or browse the public gallery). 'Start from a template' opens a picker with live 3D previews and stages your pick straight into the save step. The empty state leads with the same three quick starts.</description>+ </item><item><title>Embedded avatar chat replies again</title><link>https://three.ws/changelog</link>@@ -86,6 +94,14 @@<category>improvement</category><description>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.</description></item>+ <item>+ <title>Forge checks your photo before spending a generation — plus image-aware fact-checks and accessible galleries</title>+ <link>https://three.ws/forge</link>+ <guid isPermaLink="false">2026-06-11:Forge checks your photo before spending a generation — plus image-aware fact-checks and accessible galleries</guid>+ <pubDate>Thu, 11 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>A new free image-understanding layer (running on NVIDIA's free models, so it costs you nothing) now powers three things across three.ws. In Forge, when you upload a photo to turn into 3D, it's checked first: if it's a screenshot of text, a cluttered scene with no clear subject, or too dark to reconstruct, you get a clear heads-up and a fix before a generation slot is spent — with a one-click 'Generate anyway' if you disagree. The Fact Checker can now take an image alongside a claim: it reads the picture, transcribes any text in it, and weighs that as evidence in the verdict. And every avatar in the public gallery now gets a real, descriptive alt text written from its thumbnail, so screen-reader users hear what each avatar actually looks like instead of just its name. All three quietly switch off if the vision service is ever unavailable — nothing ever blocks or breaks.</description>+ </item><item><title>Forge share links now open your creation for anyone you send them to</title><link>https://three.ws/forge</link>diff --git a/public/features.json b/public/features.jsonindex d41e7ee43..841f9316f 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-11T14:29:15.170Z",+ "generated_at": "2026-06-11T14:33:36.303Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/tasks/nvidia-nim/PLAN.md b/tasks/nvidia-nim/PLAN.mdindex 271302110..9fa2de1c3 100644--- a/tasks/nvidia-nim/PLAN.md+++ b/tasks/nvidia-nim/PLAN.md@@ -54,7 +54,7 @@ Status legend: `[ ]` not started · `[~]` in progress (note who/when in Worklog)- [x] **T3.3** [32-rag-verify.md](32-rag-verify.md) — RAG verified end-to-end in prod + changelog (live prod widget grounded its answer in a NIM-embedded corpus; empty case degrades clean; changelog shipped — see Worklog 2026-06-11)### Phase 4 — Expansion lanes (after 1–3)-- [ ] **T4.1** [40-vision-lane.md](40-vision-lane.md) — vision helper + forge validation, fact-checker, alt text+- [x] **T4.1** [40-vision-lane.md](40-vision-lane.md) — vision helper + forge validation, fact-checker, alt text (shared `api/_lib/vision.js` + 3 consumers, all live-verified on the free NIM lane + degrade-tested — see Worklog 2026-06-11)- [x] **T4.2** [41-moderation-prefilter.md](41-moderation-prefilter.md) — fail-open moderation for anonymous chat (NemoGuard pre-filter on all 3 anon surfaces; fail-open + kill-switch live-verified; gpt-oss stays demoted — see Worklog 2026-06-11)- [x] **T4.3** [42-audio2face-spike.md](42-audio2face-spike.md) — Audio2Face-3D go/no-go spike (research only) — **NO-GO**: hosted A2F-3D functions exist but are not entitled to this free account; client-side lip-sync already covers it for free (see `probes/audio2face.md` + Worklog 2026-06-11)@@ -100,6 +100,50 @@ Status legend: `[ ]` not started · `[~]` in progress (note who/when in Worklog)## Worklog (append-only; newest at top)+- **2026-06-11** — **T4.1 (shared vision helper + three consumers) — DONE, all three+ live-verified on the free NIM lane + degrade-tested.** **Probe (`probes/vision.md`):** the+ hosted VLMs run on the **OpenAI-compatible chat host** (`integrate.api.nvidia.com/v1/chat/+ completions`) — the SAME host/protocol as the `llm.js` chat lanes, NOT the+ `ai.api.nvidia.com/genai` host FLUX/TRELLIS use. Multimodal via the standard+ `content:[{type:'text'},{type:'image_url',image_url:{url}}]` shape; synchronous, no poll, no+ NVCF asset handshake. Three models invocable on this account: **`nvidia/nemotron-nano-12b-v2-vl`+ (chosen primary** — ~281 image-prompt tokens, cheapest + clean JSON), `meta/llama-3.2-11b-vision-instruct`+ (chosen 2nd free lane, different family → independent failure modes), `meta/llama-3.2-90b-vision-instruct`+ (works but ~1616 tokens/image, unused). **No inline-size limit** on this host (verified data-URI+ bodies up to 2.07 MB — the 180 KB NVCF asset ceiling does NOT apply here); http(s) URLs also fetched+ server-side (but some origins block the fetcher — wikimedia 500'd). 403 bad key / 404 unknown model /+ 500 on a blocked URL — all mapped. **Helper (`api/_lib/vision.js`):** the image-side twin of `llm.js` —+ `describeImage`/`describeImageJson`/`visionConfigured`/`VisionUnavailableError`, free NIM lanes first+ (nemotron → llama-11b), paid `gpt-4o-mini` backstop appended last only when `OPENAI_API_KEY` set,+ per-attempt timeout, normalized error codes, and a fire-and-forget `kind:'vision'` spend event via+ `recordEvent` (free NIM prices to 0 — `nvidia` already in `llm-pricing.js` FREE_PROVIDERS). Accepts a+ pass-through URL OR base64+mime (data-URI). **Consumer 1 — `/forge` input validation**+ (`api/_lib/forge-image-validate.js`, wired into `api/forge.js` image→3D branch before submit): a free+ NIM lane judges the primary reference photo (single clear subject? text screenshot? too dark? abstract?)+ and returns a designed 422 (`image_not_usable` + per-issue actionable copy) BEFORE a generation slot is+ burned. **Fail-open is the contract** — unconfigured/timeout/error/bad-reply all return `{ok:true}` and+ generation proceeds; the UI (`src/forge.js` + `pages/forge.html`) renders the message with a one-click+ **Generate anyway** (`skip_validation:true`) so a cautious verdict never permanently blocks a confident+ user. **Consumer 2 — fact-checker** (`agents/fact-checker/src/image-evidence.js`, wired into+ `api/x402/fact-check.js`): an optional `imageUrl` is described + text-transcribed + stance-judged and+ folded in as one weighted, verdict-compatible source (runs in PARALLEL with the web pipeline; a claim is+ now checkable on image evidence alone); response gains an `imageEvidence` block; cache key bumped v1→v2+ to fold in the image; bazaar input/output schema updated. Fail-open → `null`, web-only check proceeds.+ **Consumer 3 — avatar gallery alt text** (`api/_lib/avatar-alt-text.js`): new nullable `alt_text` column+ (migration `2026-06-11-avatar-alt-text.sql` + `schema.sql` alter-guard), generated **on thumbnail upload**+ from the PNG buffer already in hand (`api/avatars/thumbnail.js`, fire-and-forget, no extra fetch),+ backfilled by `scripts/backfill-avatar-alt-text.mjs` (idempotent, `--dry-run`), surfaced through+ `avatars.js` decorate + the list/search SELECTs, and consumed by `public/gallery/gallery.js`+ (`<img alt>`/`model-viewer alt` → `alt_text || name`). Fail-open → null → gallery falls back to the name.+ **Live-verified end-to-end** with the real key (`describeImage`, `validateForgeImage`, `imageEvidence`,+ `generateAltText` all returned correct results off the free `nvidia/nemotron-nano-12b-v2-vl` lane in+ ~1–2 s; the spend-write degrades cleanly with no DB — proving `recordEvent` is wired + non-fatal).+ **Tests:** `tests/api/vision.test.js` (27 cases) — chain order, NIM→NIM→OpenAI failover, 403→invalid_key,+ timeout-as-failure, VisionUnavailable, JSON-loose parsing, and EACH consumer's degraded path. Full+ all-modules-load (471) + forge-tiers + x402-forge + avatar-og + text-to-image suites green; typecheck+ clean. Changelog entry added (holder language) + `build:pages` validated. **Surprise:** vision lives on+ the `integrate` chat host, not the `genai` image-gen host — so it's a near-clone of `llm.js`, not of the+ TRELLIS/FLUX providers; and that host has no inline-image size cap, unlike the genai NVCF path.- **2026-06-11** — **T4.3 (Audio2Face-3D feasibility spike) — DONE; recommendation NO-GO(conditional revisit).** Full findings + live transcripts in `probes/audio2face.md`.**Invocability:** A2F-3D IS published as hosted NVCF gRPC functions (Clairediff --git a/tests/api/vision.test.js b/tests/api/vision.test.jsnew file mode 100644index 000000000..414706e8d--- /dev/null+++ b/tests/api/vision.test.js@@ -0,0 +1,295 @@+// Tests for the shared vision helper (api/_lib/vision.js) and its three+// consumers: forge image validation, fact-checker image evidence, and avatar+// alt text. Transport is mocked (no live NIM calls); the focus is the free-first+// provider chain, normalized errors, spend tracking, and — critically — each+// consumer's DEGRADED path (vision unavailable / error must never hard-fail).++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++// Capture recordEvent so we can assert spend tracking without a DB.+const usageState = { events: [] };+vi.mock('../../api/_lib/usage.js', () => ({+ recordEvent: (evt) => usageState.events.push(evt),+}));++import {+ describeImage,+ describeImageJson,+ visionConfigured,+ parseJsonLoose,+ VisionUnavailableError,+} from '../../api/_lib/vision.js';+import { validateForgeImage } from '../../api/_lib/forge-image-validate.js';+import { imageEvidence } from '../../agents/fact-checker/src/image-evidence.js';+import { generateAltText, cleanAltText } from '../../api/_lib/avatar-alt-text.js';++const ORIGINAL_FETCH = globalThis.fetch;+const ENV_KEYS = ['NVIDIA_API_KEY', 'OPENAI_API_KEY'];+const ORIGINAL_ENV = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));++// Route a mocked fetch by URL substring so one test can exercise the full+// chain (NIM nemotron → NIM llama → OpenAI) and assert which lanes were hit.+function stubFetch(routes) {+ const calls = [];+ globalThis.fetch = vi.fn(async (url, opts = {}) => {+ const u = String(url);+ calls.push({ url: u, body: opts.body ? JSON.parse(opts.body) : null });+ for (const [match, responder] of routes) {+ if (u.includes(match)) return responder(calls[calls.length - 1]);+ }+ throw new Error(`unexpected fetch in test: ${u}`);+ });+ return calls;+}++function chatOk(content, usage = { prompt_tokens: 100, completion_tokens: 5 }) {+ return new Response(JSON.stringify({ model: 'm', choices: [{ message: { content } }], usage }), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ });+}+function httpErr(status, body = 'err') {+ return new Response(body, { status });+}++beforeEach(() => {+ usageState.events = [];+ process.env.NVIDIA_API_KEY = 'nvapi-test';+ delete process.env.OPENAI_API_KEY;+});+afterEach(() => {+ globalThis.fetch = ORIGINAL_FETCH;+ for (const k of ENV_KEYS) {+ if (ORIGINAL_ENV[k] === undefined) delete process.env[k];+ else process.env[k] = ORIGINAL_ENV[k];+ }+ vi.restoreAllMocks();+});++// ── helper: chain + config ─────────────────────────────────────────────────────++describe('vision helper — provider chain', () => {+ it('visionConfigured reflects available keys', () => {+ expect(visionConfigured()).toBe(true);+ delete process.env.NVIDIA_API_KEY;+ expect(visionConfigured()).toBe(false);+ process.env.OPENAI_API_KEY = 'sk-x';+ expect(visionConfigured()).toBe(true);+ });++ it('serves from the free NIM nemotron lane first and records a free (zero-cost) vision event', async () => {+ const calls = stubFetch([['integrate.api.nvidia.com', () => chatOk('Gray')]]);+ const r = await describeImage({ prompt: 'color?', imageUrl: 'https://cdn/x.jpg' });+ expect(r.text).toBe('Gray');+ expect(r.provider).toBe('nvidia');+ expect(r.model).toBe('nvidia/nemotron-nano-12b-v2-vl');+ // One call, to the OpenAI-compatible chat host, multimodal user content.+ expect(calls).toHaveLength(1);+ const userMsg = calls[0].body.messages.at(-1);+ expect(userMsg.content[0]).toEqual({ type: 'text', text: 'color?' });+ expect(userMsg.content[1]).toEqual({ type: 'image_url', image_url: { url: 'https://cdn/x.jpg' } });+ // Spend tracked, free provider → cost 0.+ expect(usageState.events).toHaveLength(1);+ expect(usageState.events[0]).toMatchObject({ kind: 'vision', provider: 'nvidia', costMicroUsd: 0 });+ });++ it('falls over from the first NIM lane to the second on a 5xx', async () => {+ let n = 0;+ const calls = stubFetch([+ ['integrate.api.nvidia.com', () => (++n === 1 ? httpErr(500, 'boom') : chatOk('ok'))],+ ]);+ const r = await describeImage({ prompt: 'p', imageUrl: 'https://cdn/x.jpg' });+ expect(calls).toHaveLength(2);+ expect(calls[0].body.model).toBe('nvidia/nemotron-nano-12b-v2-vl');+ expect(calls[1].body.model).toBe('meta/llama-3.2-11b-vision-instruct');+ expect(r.text).toBe('ok');+ });++ it('appends the paid OpenAI backstop last, after both free lanes fail', async () => {+ process.env.OPENAI_API_KEY = 'sk-x';+ const calls = stubFetch([+ ['integrate.api.nvidia.com', () => httpErr(500)],+ ['api.openai.com', () => chatOk('backstopped', { prompt_tokens: 1000, completion_tokens: 10 })],+ ]);+ const r = await describeImage({ prompt: 'p', imageBase64: 'AAAA', mimeType: 'image/png' });+ expect(r.provider).toBe('openai');+ // Two NIM lanes tried, then OpenAI.+ expect(calls.map((c) => c.url.includes('openai.com'))).toEqual([false, false, true]);+ // base64 inlined as a data URI.+ expect(calls[0].body.messages.at(-1).content[1].image_url.url).toBe('data:image/png;base64,AAAA');+ // Paid model priced > 0.+ expect(usageState.events.at(-1).costMicroUsd).toBeGreaterThan(0);+ });++ it('maps 403 to invalid_key and throws the last error (502) when all lanes fail', async () => {+ const calls = stubFetch([['integrate.api.nvidia.com', () => httpErr(403, 'Authorization failed')]]);+ await expect(describeImage({ prompt: 'p', imageUrl: 'https://cdn/x.jpg' })).rejects.toMatchObject({+ status: 502,+ code: 'invalid_key',+ });+ expect(calls).toHaveLength(2); // both NIM lanes attempted+ expect(usageState.events).toHaveLength(0); // nothing succeeded → no spend+ });++ it('treats a fetch throw (timeout) as a lane failure and moves on', async () => {+ let n = 0;+ stubFetch([+ ['integrate.api.nvidia.com', () => {+ if (++n === 1) throw new Error('aborted');+ return chatOk('recovered');+ }],+ ]);+ const r = await describeImage({ prompt: 'p', imageUrl: 'https://cdn/x.jpg' });+ expect(r.text).toBe('recovered');+ });++ it('throws VisionUnavailableError when no provider is configured', async () => {+ delete process.env.NVIDIA_API_KEY;+ await expect(describeImage({ prompt: 'p', imageUrl: 'https://cdn/x.jpg' })).rejects.toBeInstanceOf(+ VisionUnavailableError,+ );+ });++ it('requires an image input', async () => {+ await expect(describeImage({ prompt: 'p' })).rejects.toMatchObject({ code: 'no_image' });+ });+});++describe('vision helper — JSON parsing', () => {+ it('parseJsonLoose strips a ```json fence and trailing prose', () => {+ expect(parseJsonLoose('```json\n{"a":1}\n```')).toEqual({ a: 1 });+ expect(parseJsonLoose('{"a":1}\n')).toEqual({ a: 1 });+ expect(parseJsonLoose('here: {"a":1} done')).toEqual({ a: 1 });+ });+ it('parseJsonLoose throws a normalized error on garbage', () => {+ expect(() => parseJsonLoose('not json at all')).toThrow();+ });+ it('describeImageJson returns the parsed object', async () => {+ stubFetch([['integrate.api.nvidia.com', () => chatOk('{"usable":true}')]]);+ const r = await describeImageJson({ prompt: 'p', imageUrl: 'https://cdn/x.jpg' });+ expect(r.json).toEqual({ usable: true });+ });+});++// ── Consumer 1: forge image validation ─────────────────────────────────────────++describe('Consumer 1 — validateForgeImage', () => {+ it('passes a usable single-subject photo', async () => {+ stubFetch([['integrate.api.nvidia.com', () => chatOk('{"usable":true,"subject":"a red teapot","issue":"none"}')]]);+ const r = await validateForgeImage('https://cdn/teapot.jpg');+ expect(r).toMatchObject({ ok: true, subject: 'a red teapot' });+ });++ it('rejects a text screenshot with a designed, actionable message', async () => {+ stubFetch([['integrate.api.nvidia.com', () => chatOk('{"usable":false,"subject":"","issue":"text_screenshot"}')]]);+ const r = await validateForgeImage('https://cdn/screenshot.png');+ expect(r.ok).toBe(false);+ expect(r.issue).toBe('text_screenshot');+ expect(r.message).toMatch(/screenshot of text/i);+ });++ it('maps an unknown issue code to a safe default reason', async () => {+ stubFetch([['integrate.api.nvidia.com', () => chatOk('{"usable":false,"issue":"weird_new_code"}')]]);+ const r = await validateForgeImage('https://cdn/x.png');+ expect(r.ok).toBe(false);+ expect(r.issue).toBe('no_clear_subject');+ expect(r.message).toBeTruthy();+ });++ it('FAIL-OPEN: skips validation when vision is unconfigured', async () => {+ delete process.env.NVIDIA_API_KEY;+ const r = await validateForgeImage('https://cdn/x.jpg');+ expect(r).toEqual({ ok: true, skipped: 'unconfigured' });+ });++ it('FAIL-OPEN: proceeds on a vision outage (all lanes error)', async () => {+ stubFetch([['integrate.api.nvidia.com', () => httpErr(500)]]);+ const r = await validateForgeImage('https://cdn/x.jpg');+ expect(r).toEqual({ ok: true, skipped: 'error' });+ });++ it('FAIL-OPEN: proceeds on an unparseable / wrong-shape reply', async () => {+ stubFetch([['integrate.api.nvidia.com', () => chatOk('{"not_usable_field":1}')]]);+ const r = await validateForgeImage('https://cdn/x.jpg');+ expect(r).toEqual({ ok: true, skipped: 'bad_reply' });+ });+});++// ── Consumer 2: fact-checker image evidence ────────────────────────────────────++describe('Consumer 2 — imageEvidence', () => {+ const fixedNow = () => new Date('2026-06-11T00:00:00.000Z');++ it('returns a weighted, verdict-compatible source on a supporting image', async () => {+ stubFetch([+ ['integrate.api.nvidia.com', () =>+ chatOk('{"description":"A tower at night","visible_text":"330 m","stance":"supports","reason":"shows the height"}'),+ ],+ ]);+ const s = await imageEvidence('The tower is 330 m tall.', 'https://cdn/tower.jpg', { now: fixedNow });+ expect(s).toMatchObject({+ url: 'https://cdn/tower.jpg',+ stance: 'supports',+ weight: 0.6,+ kind: 'image',+ });+ expect(s.excerpt).toMatch(/Text in image: "330 m"/);+ expect(s.retrievedAt).toBe('2026-06-11T00:00:00.000Z');+ });++ it('coerces an invalid stance to neutral', async () => {+ stubFetch([['integrate.api.nvidia.com', () => chatOk('{"description":"x","stance":"maybe"}')]]);+ const s = await imageEvidence('claim', 'https://cdn/x.jpg');+ expect(s.stance).toBe('neutral');+ });++ it('returns null when no image is attached (no upstream call)', async () => {+ const calls = stubFetch([['x', () => chatOk('{}')]]);+ expect(await imageEvidence('claim', null)).toBeNull();+ expect(calls).toHaveLength(0);+ });++ it('FAIL-OPEN: returns null when vision is unconfigured', async () => {+ delete process.env.NVIDIA_API_KEY;+ expect(await imageEvidence('claim', 'https://cdn/x.jpg')).toBeNull();+ });++ it('FAIL-OPEN: returns null on a vision outage', async () => {+ stubFetch([['integrate.api.nvidia.com', () => httpErr(500)]]);+ expect(await imageEvidence('claim', 'https://cdn/x.jpg')).toBeNull();+ });+});++// ── Consumer 3: avatar alt text ────────────────────────────────────────────────++describe('Consumer 3 — generateAltText / cleanAltText', () => {+ it('generates clean alt text from a thumbnail', async () => {+ stubFetch([['integrate.api.nvidia.com', () => chatOk('A robot knight with a glowing blue visor')]]);+ const alt = await generateAltText({ imageUrl: 'https://cdn/a.png', name: 'Knight' });+ expect(alt).toBe('A robot knight with a glowing blue visor');+ });++ it('FAIL-OPEN: returns null when vision is unconfigured', async () => {+ delete process.env.NVIDIA_API_KEY;+ expect(await generateAltText({ imageUrl: 'https://cdn/a.png' })).toBeNull();+ });++ it('FAIL-OPEN: returns null on a vision outage', async () => {+ stubFetch([['integrate.api.nvidia.com', () => httpErr(500)]]);+ expect(await generateAltText({ imageUrl: 'https://cdn/a.png' })).toBeNull();+ });++ it('returns null when no image is supplied', async () => {+ expect(await generateAltText({ name: 'x' })).toBeNull();+ });++ it('cleanAltText strips quotes, leading "image of", and over-long text', () => {+ expect(cleanAltText('"A blue cat"')).toBe('A blue cat');+ expect(cleanAltText('Image of a red car')).toBe('A red car');+ expect(cleanAltText('a picture showing a dog')).toBe('A dog');+ expect(cleanAltText(' ')).toBeNull();+ const long = cleanAltText('word '.repeat(60));+ expect(long.length).toBeLessThanOrEqual(161);+ expect(long.endsWith('…')).toBe(true);+ });+});