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: integrate Vertex Gemini as a fallback provider for LLM requests
nirholas11da00522e05
diff --git a/api/_lib/avatar-render.js b/api/_lib/avatar-render.jsindex 23e4e485a..4482469e3 100644--- a/api/_lib/avatar-render.js+++ b/api/_lib/avatar-render.js@@ -5,6 +5,7 @@// duplicated chromium code anywhere else.import { createHash } from 'node:crypto';+import { readFileSync } from 'node:fs';// puppeteer-core + @sparticuz/chromium-min are loaded lazily inside getBrowser()// so Vercel's NFT does not statically trace the chromium binary tree on every// route in a function package — that trace was the 45-min build timeout.@@ -16,13 +17,81 @@ export const MIN_DIM = 64;export const MAX_DIM = 2048;export const DEFAULT_SIZE = 512;+// Bump whenever the in-page render pipeline changes visibly (pose application,+// camera framing, lighting). Part of the cache fingerprint, so every cached+// render from the previous pipeline is invalidated on deploy instead of+// serving stale/broken images forever.+const RENDER_PIPELINE_VERSION = 2;++// Camera framing per scene. `band` is the vertical slice of the model shown,+// as fractions of its bounding-box height measured from the feet: [0, 1] is+// the whole figure, band[1] > 1 buys guaranteed headroom above the crown so a+// head can never be clipped. `halfWidthFrac` is the minimum horizontal+// half-extent to keep in frame, as a fraction of model height (a head is+// ~0.13 H wide, shoulders ~0.3 H); `fitFullWidth` additionally fits the whole+// bounding-box width (full-body must never crop an outstretched arm).+// `margin` is the safety zoom-out applied after fitting. phi/theta are the+// default orbit angles (degrees; phi is polar from +Y, so ~80-86 is eye-ish+// level looking slightly down).export const SCENE_PRESETS = {- 'full-body': { phi: 80, theta: 0, radiusMult: 1.0, lookAtY: 0.0 },- 'upper-body': { phi: 82, theta: 5, radiusMult: 0.55, lookAtY: 0.15 },- 'portrait': { phi: 84, theta: 8, radiusMult: 0.38, lookAtY: 0.30 },- 'headshot': { phi: 86, theta: 5, radiusMult: 0.28, lookAtY: 0.38 },+ 'full-body': { phi: 80, theta: 0, band: [-0.02, 1.05], fitFullWidth: true, halfWidthFrac: 0.25, margin: 1.12 },+ 'upper-body': { phi: 82, theta: 5, band: [0.42, 1.05], fitFullWidth: false, halfWidthFrac: 0.22, margin: 1.08 },+ 'portrait': { phi: 84, theta: 8, band: [0.60, 1.06], fitFullWidth: false, halfWidthFrac: 0.14, margin: 1.08 },+ 'headshot': { phi: 86, theta: 5, band: [0.74, 1.07], fitFullWidth: false, halfWidthFrac: 0.09, margin: 1.08 },};+// Pure camera-framing math, shared verbatim between Node (unit tests) and the+// headless render page (injected via toString(), so keep it self-contained:+// plain objects and Math only, no three.js, no outer-scope references).+//+// Given the POSED model's world-space bounding box, a scene preset (above),+// the output aspect ratio (width / height) and the vertical FOV, it returns+// where to put the camera and what to look at so the preset's vertical band+// fits the vertical frustum AND the required horizontal extent fits the+// horizontal frustum. Fitting the band (whose top is above the crown) against+// the vertical FOV is what makes portrait-aspect outputs keep the head in+// frame; fitting the width keeps landscape/square framing correct too.+export function computeCameraFraming(box, preset, aspect, fovDeg, orbit) {+ const p = preset || {};+ const sizeX = Math.max(box.max.x - box.min.x, 1e-6);+ const sizeY = Math.max(box.max.y - box.min.y, 1e-6);+ const sizeZ = Math.max(box.max.z - box.min.z, 1e-6);+ const cx = (box.min.x + box.max.x) / 2;+ const cz = (box.min.z + box.max.z) / 2;++ const band = Array.isArray(p.band) && p.band.length === 2 ? p.band : [-0.02, 1.05];+ const bandBottom = box.min.y + sizeY * band[0];+ const bandTop = box.min.y + sizeY * band[1];+ const lookY = (bandBottom + bandTop) / 2;+ const halfH = Math.max((bandTop - bandBottom) / 2, 1e-6);++ const minHalfW = sizeY * (Number.isFinite(p.halfWidthFrac) ? p.halfWidthFrac : 0.3);+ const halfW = p.fitFullWidth ? Math.max(Math.max(sizeX, sizeZ) / 2, minHalfW) : minHalfW;++ const tanV = Math.tan(((Number(fovDeg) || 28) * Math.PI) / 360);+ const tanH = tanV * Math.max(Number(aspect) || 1, 1e-6);+ const margin = Number.isFinite(p.margin) ? p.margin : 1.08;+ // + sizeZ / 2 backs the camera off past the model's front surface so depth+ // (an outstretched punch, a knee toward camera) never breaches the frustum.+ const distance = Math.max(halfH / tanV, halfW / tanH) * margin + sizeZ / 2;++ const num = (v) => (v == null ? NaN : Number(v));+ const thetaDeg = Number.isFinite(num(orbit && orbit.theta)) ? num(orbit.theta) : (Number(p.theta) || 0);+ const phiDeg = Number.isFinite(num(orbit && orbit.phi)) ? num(orbit.phi) : (Number(p.phi) || 80);+ const theta = (thetaDeg * Math.PI) / 180;+ const phi = (phiDeg * Math.PI) / 180;++ return {+ position: {+ x: cx + distance * Math.sin(phi) * Math.sin(theta),+ y: lookY + distance * Math.cos(phi),+ z: cz + distance * Math.sin(phi) * Math.cos(theta),+ },+ target: { x: cx, y: lookY, z: cz },+ distance,+ };+}+export const FORMAT_TYPES = {png: 'image/png',jpeg: 'image/jpeg',@@ -124,6 +193,7 @@ function renderFingerprint(updatedAt, params) {pose: params.posePresetId,expression: params.expression,updated: updatedAt,+ pipeline: RENDER_PIPELINE_VERSION,});}@@ -204,12 +274,48 @@ async function getBrowser() {return _browserPromise;}-function sceneViewerHtml({ glbUrl, width, height, background, pose, cameraOrbit, expression, scenePreset }) {+// The pose studio's posing stack (src/pose-rig.js + src/glb-canonicalize.js ++// src/pose-mannequin.js) is pure three.js ESM, so the headless page runs the+// EXACT same code the client does: canonical bone-name mapping for every rig+// convention, and world-delta preset retargeting (poseFromMannequinPreset →+// GltfRig.applyPose) that lands presets on top of any bind stance. The+// sources are shipped to the page as data: URL modules in its import map,+// with pose-rig's relative imports rewritten to the bare specifiers the map+// defines. Never reintroduce a hand-rolled alias table here — it silently+// missed every Mixamo rig (GLTFLoader strips ':' from node names) and stomped+// absolute local Eulers over bind rotations on the rest.+const SRC_DIR = new URL('../../src/', import.meta.url);++function poseModuleDataUrl(file, rewrites = []) {+ let code = readFileSync(new URL(file, SRC_DIR), 'utf8');+ for (const [from, to] of rewrites) code = code.replaceAll(from, to);+ if (/from\s+['"]\.{1,2}\//.test(code)) {+ throw new Error(`avatar-render: ${file} still has relative imports after rewrite — update poseRuntimeModules()`);+ }+ return 'data:text/javascript;base64,' + Buffer.from(code, 'utf8').toString('base64');+}++let _poseRuntimeModules = null;+export function poseRuntimeModules() {+ if (_poseRuntimeModules) return _poseRuntimeModules;+ _poseRuntimeModules = {+ 'glb-canonicalize': poseModuleDataUrl('glb-canonicalize.js'),+ 'pose-mannequin': poseModuleDataUrl('pose-mannequin.js'),+ 'pose-rig': poseModuleDataUrl('pose-rig.js', [+ ["from './glb-canonicalize.js'", "from 'glb-canonicalize'"],+ ["from './pose-mannequin.js'", "from 'pose-mannequin'"],+ ]),+ };+ return _poseRuntimeModules;+}++export function sceneViewerHtml({ glbUrl, width, height, background, pose, cameraOrbit, expression, scenePreset }) {const bg = background === 'transparent' ? 'null' : JSON.stringify(background || '#0a0a0a');const poseJson = pose ? JSON.stringify(pose) : 'null';const orbitJson = JSON.stringify(cameraOrbit || { theta: 0, phi: 80, radius: null });const expressionJson = JSON.stringify(expression || null);const presetJson = JSON.stringify(scenePreset);+ const poseModules = poseRuntimeModules();return `<!doctype html><html><head><meta charset="utf-8" />@@ -218,7 +324,10 @@ function sceneViewerHtml({ glbUrl, width, height, background, pose, cameraOrbit,<canvas id="c" width="${width}" height="${height}" style="display:block;width:${width}px;height:${height}px"></canvas><script type="importmap">{ "imports": {"three": "https://unpkg.com/three@${THREE_VERSION}/build/three.module.js",- "three/addons/": "https://unpkg.com/three@${THREE_VERSION}/examples/jsm/"+ "three/addons/": "https://unpkg.com/three@${THREE_VERSION}/examples/jsm/",+ "glb-canonicalize": "${poseModules['glb-canonicalize']}",+ "pose-mannequin": "${poseModules['pose-mannequin']}",+ "pose-rig": "${poseModules['pose-rig']}"}}</script><script type="module">import * as THREE from 'three';@@ -227,6 +336,7 @@ import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';import { KTX2Loader } from 'three/addons/loaders/KTX2Loader.js';import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';+import { makeGltfRig, poseFromMannequinPreset } from 'pose-rig';window.__renderDone = false;window.__renderError = null;@@ -265,42 +375,18 @@ fill.position.set(-3, 1.2, 2.5); scene.add(fill);const rim = new THREE.DirectionalLight(0xecdcff, 0.7);rim.position.set(-0.5, 2.5, -4); scene.add(rim);-const aliases = {- shoulderl: ['leftshoulder','shoulder_l','l_shoulder','mixamorig:leftshoulder'],- shoulderr: ['rightshoulder','shoulder_r','r_shoulder','mixamorig:rightshoulder'],- elbowl: ['leftforearm','leftelbow','elbow_l','mixamorig:leftforearm','mixamorig:leftelbow'],- elbowr: ['rightforearm','rightelbow','elbow_r','mixamorig:rightforearm','mixamorig:rightelbow'],- wristl: ['lefthand','wrist_l','mixamorig:lefthand'],- wristr: ['righthand','wrist_r','mixamorig:righthand'],- hipl: ['leftupleg','hip_l','mixamorig:leftupleg'],- hipr: ['rightupleg','hip_r','mixamorig:rightupleg'],- kneel: ['leftleg','knee_l','mixamorig:leftleg'],- kneer: ['rightleg','knee_r','mixamorig:rightleg'],- anklel: ['leftfoot','ankle_l','mixamorig:leftfoot'],- ankler: ['rightfoot','ankle_r','mixamorig:rightfoot'],- head: ['head','mixamorig:head'],- neck: ['neck','mixamorig:neck'],- spine: ['spine','spine1','mixamorig:spine','mixamorig:spine1'],- hips: ['hips','mixamorig:hips'],-};-+// Preset poses are authored in the mannequin convention (src/pose-presets.js);+// poseFromMannequinPreset converts them to canonical world-frame deltas and+// GltfRig.applyPose replays those on the avatar's OWN rest pose with+// reference-stance alignment — the same path the /pose studio uses, so a+// preset lands identically here whether the rig binds in a T-pose or A-pose,+// and whatever naming convention its bones use. Rigs with no recognizable+// humanoid skeleton stay in bind pose (there is no safe mapping for those).function applyPose(root, poseMap) {if (!poseMap) return;- const byName = new Map();- root.traverse((o) => { if (o.name) byName.set(o.name.toLowerCase(), o); });- function findJoint(k) {- const key = k.toLowerCase();- const direct = byName.get(key);- if (direct) return direct;- const list = aliases[key] || [];- for (const a of list) { const j = byName.get(a); if (j) return j; }- return null;- }- for (const [key, rot] of Object.entries(poseMap)) {- const joint = findJoint(key);- if (!joint) continue;- joint.rotation.set(rot.x || 0, rot.y || 0, rot.z || 0);- }+ const rig = makeGltfRig(root);+ if (!rig) return;+ rig.applyPose(poseFromMannequinPreset(poseMap));}function applyExpression(root, expression) {@@ -314,30 +400,29 @@ function applyExpression(root, expression) {});}+${computeCameraFraming.toString()}+function frameCameraForScene(root, orbit, preset) {+ // The bounding box must reflect the POSED skin, not the bind-pose geometry:+ // three's Box3.setFromObject defers to SkinnedMesh.computeBoundingBox (CPU+ // skinning), which needs current bone matrices — update the graph and each+ // skeleton first. (Never reset rigs via THREE.Skeleton's pose method: it+ // reconstructs bind from inverse-bind matrices and collapses Mixamo rigs.)+ root.updateMatrixWorld(true);+ root.traverse((o) => { if (o.isSkinnedMesh && o.skeleton) o.skeleton.update(); });const box = new THREE.Box3().setFromObject(root);- const size = new THREE.Vector3(); box.getSize(size);- const center = new THREE.Vector3(); box.getCenter(center);-- root.position.sub(center);-- const halfH = size.y * 0.5;- const lookAtY = halfH * (preset.lookAtY || 0);-- root.position.y += size.y * 0.05;-- const maxDim = Math.max(size.x, size.y, size.z);- const fov = THREE.MathUtils.degToRad(camera.fov);- const defaultDist = (maxDim / 2) / Math.tan(fov / 2) * 1.45;- const radius = defaultDist * (preset.radiusMult || 1.0);- const theta = THREE.MathUtils.degToRad(Number(orbit.theta) || 0);- const phi = THREE.MathUtils.degToRad(Number(orbit.phi) || 80);- const x = radius * Math.sin(phi) * Math.sin(theta);- const y = radius * Math.cos(phi) + lookAtY;- const z = radius * Math.sin(phi) * Math.cos(theta);- camera.position.set(x, y, z);- camera.lookAt(0, lookAtY, 0);+ const framing = computeCameraFraming(+ { min: { x: box.min.x, y: box.min.y, z: box.min.z }, max: { x: box.max.x, y: box.max.y, z: box.max.z } },+ preset, ${width} / ${height}, camera.fov, orbit,+ );+ // Scale-aware clip planes: pipeline GLBs are ~1.7 units tall but Mixamo+ // cm-scale exports are ~170 — a fixed near/far would clip one or the other.+ camera.near = Math.max(framing.distance / 1000, 0.001);+ camera.far = framing.distance * 10;+ camera.updateProjectionMatrix();+ camera.position.set(framing.position.x, framing.position.y, framing.position.z);+ camera.lookAt(framing.target.x, framing.target.y, framing.target.z);}const orbit = ${orbitJson};diff --git a/api/_lib/coingecko.js b/api/_lib/coingecko.jsindex 8707409e8..d9827e660 100644--- a/api/_lib/coingecko.js+++ b/api/_lib/coingecko.js@@ -7,6 +7,8 @@// CDN caching on the endpoints absorbs most traffic — this cache only shields// the upstream from concurrent cold-instance misses.+import { cacheGet, cacheSet } from './cache.js';+export const COINGECKO_BASE = 'https://api.coingecko.com/api/v3';// key → { value, expiresAt, staleUntil }. Entries stay readable past expiresAt@@ -21,6 +23,24 @@ const MAX_ENTRIES = 512;// minutes of staleness far better than an outage.const STALE_MS = 30 * 60_000;+// The in-memory stale buffer dies with the instance, so a COLD instance facing+// a throttled upstream still 502s (the July 2026 api-sweep caught /api/coin/+// exchanges doing exactly that). Mirror every good payload into the shared+// cache (Upstash) as a durable last-good copy that any instance can fall back+// to. Long window on purpose: it is only ever read after the live fetch AND+// the memory stale buffer have both failed.+const DURABLE_STALE_S = 6 * 3600;+const durableKey = (path) => `gecko:last-good:${path}`;++async function durableStale(path) {+ try {+ const value = await cacheGet(durableKey(path));+ return value === undefined || value === null ? null : value;+ } catch {+ return null;+ }+}+function headers() {const h = { accept: 'application/json', 'user-agent': 'three.ws/1.0' };const key = (process.env.COINGECKO_API_KEY || '').trim();@@ -52,6 +72,12 @@ export async function geckoFetch(path, { ttlMs = 60_000, timeoutMs = 8000 } = {}console.warn(`[coingecko] ${path} fetch failed (${netErr?.name || 'error'}); serving stale`);return stale;}+ const durable = await durableStale(path);+ if (durable !== null) {+ console.warn(`[coingecko] ${path} fetch failed (${netErr?.name || 'error'}); serving durable last-good`);+ _cache.set(path, { value: durable, expiresAt: now, staleUntil: now + STALE_MS });+ return durable;+ }throw netErr;}if (!resp.ok) {@@ -62,6 +88,16 @@ export async function geckoFetch(path, { ttlMs = 60_000, timeoutMs = 8000 } = {}console.warn(`[coingecko] ${path} → ${resp.status}; serving stale`);return stale;}+ if (resp.status !== 404) {+ // Cold instance, throttled upstream, nothing in memory — the shared+ // last-good copy is the difference between minutes-stale data and a 502.+ const durable = await durableStale(path);+ if (durable !== null) {+ console.warn(`[coingecko] ${path} → ${resp.status}; serving durable last-good`);+ _cache.set(path, { value: durable, expiresAt: now, staleUntil: now + STALE_MS });+ return durable;+ }+ }const err = new Error(`CoinGecko ${resp.status} for ${path}`);err.status = resp.status;throw err;@@ -69,6 +105,8 @@ export async function geckoFetch(path, { ttlMs = 60_000, timeoutMs = 8000 } = {}const value = await resp.json();_cache.set(path, { value, expiresAt: now + ttlMs, staleUntil: now + ttlMs + STALE_MS });if (_cache.size > MAX_ENTRIES) _cache.delete(_cache.keys().next().value);+ // Fire-and-forget durable mirror — never let a cache fault fail a live fetch.+ Promise.resolve(cacheSet(durableKey(path), value, DURABLE_STALE_S)).catch(() => {});return value;}diff --git a/api/_lib/vertex-gemini.js b/api/_lib/vertex-gemini.jsnew file mode 100644index 000000000..ea549c218--- /dev/null+++ b/api/_lib/vertex-gemini.js@@ -0,0 +1,74 @@+// Vertex Gemini — the platform's credits-funded LLM reliability anchor.+//+// One shared definition of the rung that api/chat.js proved out (commit+// 2b3d00254, "chat anchor eviction"): Gemini on Vertex AI through its+// OpenAI-compatible endpoint, authenticated with the GCP service account (no+// API key) and billed to the platform's GCP credits. It needs no third-party+// quota and no Model Garden acceptance, which makes it the one rung a fallback+// chain can rely on when every free tier (Groq / OpenRouter / NVIDIA NIM)+// throttles at once and the paid backstops are dead (prod OPENAI_API_KEY 429s+// billing_not_active; the OpenRouter host key must never route to paid models).+//+// Semantics every consumer must preserve (mirroring api/chat.js exactly):+// • The anchor is appended at the TAIL of the chain — never auto-selected as+// a primary route, always present as the last-resort rung.+// • Presence of other provider keys (OPENAI_API_KEY etc.) must never evict+// it — no chain cap, cooldown, or anon filter may drop the anchor.+// • Anonymous/keyless callers keep it: it is GCP-credit funded, so it is not+// a paid-key drain vector (see ANON_PROVIDER_LIST in chat-models.js).+// • Availability is gated ONLY by GOOGLE_CLOUD_PROJECT (set on every Cloud+// Run deploy); the OAuth bearer token is minted per request and a token+// failure falls through the chain like any other provider error.+//+// Env knobs (same as the api/chat.js and api/_lib/llm.js rungs):+// GOOGLE_CLOUD_PROJECT — GCP project id (required; gates the rung)+// GOOGLE_CLOUD_LOCATION_GEMINI — region or "global" (default: "global")+// VERTEX_GEMINI_MODEL — model id (default: google/gemini-2.5-flash)++import { getGcpAccessToken } from './gcp-auth.js';++// True when the deployment can serve the anchor at all. Read per call (not at+// module load) so tests and late-injected env both behave.+export function vertexGeminiAvailable() {+ return Boolean(process.env.GOOGLE_CLOUD_PROJECT);+}++// The anchor's model id. Full Flash by default (platform credits, standing+// owner-approved spend) — env-tunable without a code change.+export function vertexGeminiModel() {+ return process.env.VERTEX_GEMINI_MODEL || 'google/gemini-2.5-flash';+}++function vertexGeminiTarget() {+ const project = process.env.GOOGLE_CLOUD_PROJECT;+ const location = process.env.GOOGLE_CLOUD_LOCATION_GEMINI || 'global';+ const host =+ location === 'global' ? 'aiplatform.googleapis.com' : `${location}-aiplatform.googleapis.com`;+ return { project, location, host };+}++// OpenAI-compatible base URL (no trailing /chat/completions) — for SDK clients+// that append the path themselves (e.g. @ai-sdk/openai's baseURL).+export function vertexGeminiOpenAIBase() {+ const { project, location, host } = vertexGeminiTarget();+ return `https://${host}/v1beta1/projects/${project}/locations/${location}/endpoints/openapi`;+}++// Full chat-completions URL — for hand-rolled fetch transports.+export function vertexGeminiChatUrl() {+ return `${vertexGeminiOpenAIBase()}/chat/completions`;+}++// Per-request headers: a fresh (cached) GCP OAuth bearer token. May throw when+// no GCP credentials are resolvable; callers treat that like any other provider+// failure and fall through their chain.+export async function vertexGeminiHeaders() {+ const token = await getGcpAccessToken();+ return { authorization: `Bearer ${token}`, 'content-type': 'application/json' };+}++// The raw bearer token, for clients that take an apiKey instead of headers+// (e.g. the AI SDK's createOpenAI). Same failure semantics as the headers.+export async function vertexGeminiAccessToken() {+ return getGcpAccessToken();+}diff --git a/api/_lib/vision.js b/api/_lib/vision.jsindex d4001788a..bbf8a0ffd 100644--- a/api/_lib/vision.js+++ b/api/_lib/vision.js@@ -31,6 +31,12 @@ import { recordEvent } from './usage.js';import { costMicroUsd } from './llm-pricing.js';import { validatePublicUrl, isPrivateAddress, SsrfError } from './ssrf.js';import { fetchSafePublicUrl } from './ssrf-guard.js';+import {+ vertexGeminiAvailable,+ vertexGeminiModel,+ vertexGeminiChatUrl,+ vertexGeminiHeaders,+} from './vertex-gemini.js';// Free NIM vision lanes, in order. nemotron-nano carries the smallest image// token footprint (~281 prompt tokens for a tiny image vs ~1600 for llama-90B);@@ -48,7 +54,7 @@ const OPENAI_VISION_MODEL = 'gpt-5.4-nano';// a handler that *chose* to surface it can return 503 — but consumers should// generally catch it and degrade silently instead.export class VisionUnavailableError extends Error {- constructor(message = 'No vision provider available. Configure NVIDIA_API_KEY (free) or OPENAI_API_KEY (paid backstop).') {+ constructor(message = 'No vision provider available. Configure NVIDIA_API_KEY (free), GOOGLE_CLOUD_PROJECT (Vertex Gemini credits anchor), or OPENAI_API_KEY (paid backstop).') {super(message);this.name = 'VisionUnavailableError';this.code = 'vision_unavailable';@@ -57,13 +63,17 @@ export class VisionUnavailableError extends Error {}// One OpenAI-compatible vision provider entry. The multimodal user message is-// the only shape difference from llm.js's text providers.-function openaiCompatVisionProvider({ name, key, url, model }) {+// the only shape difference from llm.js's text providers. `getHeaders` (async)+// replaces the static key header for keyless lanes whose auth is minted per+// request (the Vertex Gemini credits anchor).+function openaiCompatVisionProvider({ name, key, url, model, getHeaders = null }) {return {name,model,url,- headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },+ ...(getHeaders+ ? { getHeaders }+ : { headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` } }),buildBody: (system, parts, maxTokens) => {const messages = [];if (system) messages.push({ role: 'system', content: system });@@ -75,9 +85,11 @@ function openaiCompatVisionProvider({ name, key, url, model }) {};}-// Build the ordered vision provider chain: free NIM lanes first, paid OpenAI-// backstop appended last and only when its key is set.-function visionChain() {+// Build the ordered vision provider chain: free NIM lanes first, then the+// credits-funded Vertex Gemini anchor, paid OpenAI backstop appended last and+// only when its key is set. Exported for the anchor regression tests+// (tests/api/llm-vertex-anchor-surfaces).+export function visionChain() {const chain = [];if (env.NVIDIA_API_KEY) {for (const model of NVIDIA_VISION_MODELS) {@@ -89,6 +101,21 @@ function visionChain() {}));}}+ // Vertex Gemini credits anchor — multimodal (Gemini Flash reads image_url+ // parts, data URIs included, through the same OpenAI-compatible endpoint),+ // keyless (OAuth token minted per request), billed to GCP credits. Sits+ // after the free NIM lanes and ahead of the paid tail, exactly like the+ // text anchor in llm.js's providerChain: the prod OPENAI_API_KEY is+ // billing-dead, so this rung is what keeps vision answering when the NIM+ // queue throttles or hangs. Nothing may evict it (see api/_lib/vertex-gemini.js).+ if (vertexGeminiAvailable()) {+ chain.push(openaiCompatVisionProvider({+ name: 'vertex-gemini',+ url: vertexGeminiChatUrl(),+ model: vertexGeminiModel(),+ getHeaders: vertexGeminiHeaders,+ }));+ }if (env.OPENAI_API_KEY) {chain.push(openaiCompatVisionProvider({name: 'openai',@@ -285,9 +312,12 @@ export async function describeImage({const startedAt = Date.now();let upstream;try {+ // Keyless lanes (the Vertex Gemini credits anchor) mint their auth per+ // attempt via getHeaders — a token-exchange failure lands in the catch+ // below and fails over to the next lane like any transport error.upstream = await fetch(p.url, {method: 'POST',- headers: p.headers,+ headers: p.getHeaders ? await p.getHeaders() : p.headers,body: JSON.stringify(p.buildBody(system, parts, maxTokens)),signal: AbortSignal.timeout(attemptTimeout),});diff --git a/api/agents/copilot.js b/api/agents/copilot.jsindex 000537cea..02de8d989 100644--- a/api/agents/copilot.js+++ b/api/agents/copilot.js@@ -33,6 +33,12 @@ import { quoteTrade } from './solana-trade.js';import { assessTradeSafety } from '../_lib/trade-firewall.js';import { getSmartMoneyForMint } from '../_lib/smart-money.js';import { getTradeLimits } from '../_lib/agent-trade-guards.js';+import {+ vertexGeminiAvailable,+ vertexGeminiModel,+ vertexGeminiChatUrl,+ vertexGeminiHeaders,+} from '../_lib/vertex-gemini.js';const NETWORKS = new Set(['mainnet', 'devnet']);const netOf = (v) => (NETWORKS.has(v) ? v : 'mainnet');@@ -56,8 +62,12 @@ async function resolveAuth(req) {// OpenAI chat-completions wire format (tools + streamed tool_calls), so one// reader handles them all. Anthropic is intentionally omitted from the tool loop// — the free OpenAI-compatible lanes are the primary path and OpenAI is the paid-// tail; nothing here depends on a paid key existing.-function providerChain() {+// tail; nothing here depends on a paid key existing. The credits-funded Vertex+// Gemini anchor is ALWAYS the final rung when the GCP project is set (api/chat.js+// semantics): the prod OPENAI_API_KEY is billing-dead, so without the anchor a+// simultaneous free-lane throttle 5xx'd the copilot. Exported for the anchor+// regression tests.+export function providerChain() {const chain = [];if (env.GROQ_API_KEY) {chain.push({ name: 'groq', url: 'https://api.groq.com/openai/v1/chat/completions', key: env.GROQ_API_KEY, model: 'llama-3.3-70b-versatile' });@@ -78,6 +88,19 @@ function providerChain() {if (env.OPENAI_API_KEY) {chain.push({ name: 'openai', url: 'https://api.openai.com/v1/chat/completions', key: env.OPENAI_API_KEY, model: 'gpt-5.4-nano' });}+ // Vertex Gemini credits anchor — keyless (GCP OAuth token minted per request+ // via getHeaders; see api/_lib/vertex-gemini.js), OpenAI-compatible including+ // tools + streamed tool_calls, billed to platform credits. Appended at the+ // tail unconditionally when available so no present provider key can evict it.+ if (vertexGeminiAvailable()) {+ chain.push({+ name: 'vertex-gemini',+ url: vertexGeminiChatUrl(),+ key: null,+ model: vertexGeminiModel(),+ getHeaders: vertexGeminiHeaders,+ });+ }return chain;}@@ -93,9 +116,15 @@ async function streamRound(provider, { messages, tools, onContent }) {messages,};if (Array.isArray(tools) && tools.length) { body.tools = tools; body.tool_choice = 'auto'; }+ // Keyless lanes (the Vertex Gemini credits anchor) mint their auth per request+ // via getHeaders — a token-exchange failure throws here and fails over to the+ // next provider exactly like a transport error.+ const headers = provider.getHeaders+ ? { ...(await provider.getHeaders()), ...(provider.extraHeaders || {}) }+ : { 'content-type': 'application/json', authorization: `Bearer ${provider.key}`, ...(provider.extraHeaders || {}) };const resp = await fetch(provider.url, {method: 'POST',- headers: { 'content-type': 'application/json', authorization: `Bearer ${provider.key}`, ...(provider.extraHeaders || {}) },+ headers,body: JSON.stringify(body),signal: AbortSignal.timeout(45_000),});@@ -403,7 +432,7 @@ export default async function handler(req, res, id) {}const chain = providerChain();- if (!chain.length) return error(res, 503, 'llm_unavailable', 'No LLM provider configured. Set GROQ_API_KEY, OPENROUTER_API_KEY, or NVIDIA_API_KEY.');+ if (!chain.length) return error(res, 503, 'llm_unavailable', 'No LLM provider configured. Set GROQ_API_KEY, OPENROUTER_API_KEY, or NVIDIA_API_KEY (or GOOGLE_CLOUD_PROJECT for the Vertex credits anchor).');// SSE open.res.writeHead(200, {diff --git a/api/brain/chat.js b/api/brain/chat.jsindex 6836d9ec3..1fd823156 100644--- a/api/brain/chat.js+++ b/api/brain/chat.js@@ -26,6 +26,12 @@ import {vertexClaudeConfigured,vertexAnthropicMessages,} from '../_lib/vertex-claude.js';+import {+ vertexGeminiAvailable,+ vertexGeminiModel,+ vertexGeminiOpenAIBase,+ vertexGeminiAccessToken,+} from '../_lib/vertex-gemini.js';// Providers an anonymous (signed-out) caller may use: only the genuinely free// tiers — the OpenRouter-routed open-weight default and the free NVIDIA NIM@@ -464,7 +470,8 @@ function buildFallback(spec, primary) {// token streamed. Free-first platform policy (api/_lib/llm.js): the user gets// an answer from an open-weight model rather than an error event. Skips routes// that already failed as the primary (same key + model would fail identically).-function freeFallbackChain(providerKey, spec, primary) {+// Exported for the anchor regression tests (tests/api/llm-vertex-anchor-surfaces).+export function freeFallbackChain(providerKey, spec, primary) {const chain = [];if (env.GROQ_API_KEY && providerKey !== 'groq-llama') {chain.push({@@ -483,6 +490,16 @@ function freeFallbackChain(providerKey, spec, primary) {if (env.NVIDIA_API_KEY && !providerKey.startsWith('nvidia-')) {chain.push({ label: 'nvidia/llama-3.3-70b-instruct', model: nvidia('meta/llama-3.3-70b-instruct') });}+ // Credits-funded Vertex Gemini anchor, ALWAYS at the tail when the GCP+ // project is set (api/chat.js semantics — see api/_lib/vertex-gemini.js). No+ // key gates it and nothing may evict it: it is the rung that keeps /brain+ // streaming when groq/openrouter/nvidia all throttle at once and the paid+ // backstops are dead. The AI SDK model is built lazily in streamBrain's+ // attempt loop (vertexGemini flag) because its bearer token is minted per+ // request — a token failure falls through like any other provider error.+ if (vertexGeminiAvailable()) {+ chain.push({ label: `vertex-gemini/${vertexGeminiModel()}`, vertexGemini: true });+ }return chain;}@@ -858,7 +875,17 @@ export async function streamBrain(res, { plan, providerKey, messages, system, maif (attempt.watsonx) await streamWatsonx(res, { messages, system, maxTokens, t0 });else if (attempt.vertex)await streamVertex(res, { messages, system, maxTokens, t0, model: attempt.model });- else await streamOnce(maxTokens, attempt.model);+ else if (attempt.vertexGemini) {+ // Credits anchor: OpenAI-compatible Vertex endpoint, bearer token+ // minted per attempt (a token-exchange failure throws here and is+ // handled like any other lane failure). Reuses streamOnce so the+ // budget/abort/onError machinery is identical to every other lane.+ const anchorModel = createOpenAI({+ apiKey: await vertexGeminiAccessToken(),+ baseURL: vertexGeminiOpenAIBase(),+ }).chat(vertexGeminiModel());+ await streamOnce(maxTokens, anchorModel);+ } else await streamOnce(maxTokens, attempt.model);return;} catch (err) {lastErr = err;diff --git a/api/cron/db-retention.js b/api/cron/db-retention.jsindex a3ce84fcf..6674af010 100644--- a/api/cron/db-retention.js+++ b/api/cron/db-retention.js@@ -42,6 +42,15 @@// a day old, and deletes terminal jobs past 30 days.// C. VACUUM. Plain VACUUM on the tables it pruned so the freed pages become// reusable and Neon's storage GC can return them.+// D. COMPACTION. Plain VACUUM never shrinks the relation FILES, so on Neon+// pg_database_size stays high after a prune and the storage-pressure gate+// (isStoragePressured / requireWriteCapacity) can latch permanently: the+// July 2026 recurrence had 770 MB of dead file space across the pruned+// tables while every write-heavy cron sat skipped. When a tick starts+// under pressure, this step measures reclaimable space per managed table+// (pgstattuple_approx) and VACUUM FULLs the worst offenders, smallest+// first and bounded per tick, so the file space actually returns and the+// gate unlatches without a human.//// DELETE (not UPDATE) is used for the firehose because DELETE settles xmax in place// and does NOT extend a relation file — it therefore succeeds even AT the cap,@@ -85,6 +94,17 @@ const SERIES_BATCH = 5000; // rows per batch for time-keyed series prunesconst SERIES_MAX_PER_RUN = 50_000; // per-table ceiling per tickconst ORPHAN_BATCH = 5000; // orphaned satellite rows per table per tick+// Compaction bounds (section D). VACUUM FULL rewrites a table into a fresh file+// under an ACCESS EXCLUSIVE lock — cheap on Neon for these churn tables (a+// 500 MB table compacted in ~2 s in the July 2026 recovery) but never free, so+// only tables with real reclaimable space qualify and each tick rewrites at+// most a few. Smallest-first ordering matters near the hard cap: each rewrite+// needs headroom ≈ the table's LIVE size, so freeing the small ones first buys+// the room to rewrite the big ones.+const COMPACT_MIN_FREE_MB = 25; // ignore tables with less reclaimable space than this+const COMPACT_MIN_FREE_RATIO = 0.3; // ... or mostly-live files (rewrite buys little)+const COMPACT_MAX_TABLES = 3; // per tick; the cron re-runs on its schedule+// Time-keyed tables outside the mint-cascade family that still grow without// bound. Each is pruned by its own timestamp column on the shared valve// (window tightens to the floor under storage pressure). All names/columns are@@ -375,6 +395,100 @@ async function pruneRegenJobs() {return { stripped, deleted };}+// ── D. Bounded compaction under storage pressure ──────────────────────────────+// Every table this cron manages is a compaction candidate; nothing outside the+// retention set is ever rewritten (a VACUUM FULL on a hot product table would+// block its writers behind an exclusive lock).+const COMPACT_CANDIDATES = [+ 'pump_coin_intel',+ ...FIREHOSE_SATELLITES,+ ...TIME_SERIES_TABLES.map((t) => t.table),+ ...RUN_LOG_TABLES.map((t) => t.table),+ 'x402_audit_log',+ 'avatar_regen_jobs',+];++/**+ * Pure target selection so the bounds are unit-testable. Keeps tables whose+ * reclaimable space clears both the absolute and the ratio floor, orders them+ * smallest file first (each rewrite needs headroom ≈ live size, so free the+ * cheap space before attempting the big files near a hard cap), and caps how+ * many one tick may rewrite.+ *+ * @param {object} a+ * @param {Array<{table:string, tableMb:number, freeMb:number}>} a.candidates+ * @param {number} a.minFreeMb+ * @param {number} a.minFreeRatio+ * @param {number} a.maxTables+ */+export function pickCompactionTargets({ candidates, minFreeMb, minFreeRatio, maxTables }) {+ return candidates+ .filter(+ (c) =>+ c.tableMb > 0 &&+ c.freeMb >= minFreeMb &&+ c.freeMb / c.tableMb >= minFreeRatio,+ )+ .sort((a, b) => a.tableMb - b.tableMb)+ .slice(0, Math.max(0, maxTables));+}++// Measure reclaimable space per candidate and VACUUM FULL the picks. Wholly+// best-effort: pgstattuple missing, a lock we can't get, or a rewrite failing+// mid-tick degrades to "less compacted this tick", never a failed cron.+async function compactTables({ minFreeMb, maxTables }) {+ const result = { measured: 0, compacted: [], skipped: [] };+ try {+ // Idempotent; Neon ships pgstattuple as an installable extension.+ await sql`CREATE EXTENSION IF NOT EXISTS pgstattuple`;+ } catch (err) {+ result.skipped.push({ reason: 'pgstattuple_unavailable', detail: err?.message?.slice(0, 120) });+ return result;+ }++ const candidates = [];+ for (const t of COMPACT_CANDIDATES) {+ if (!(await tableExists(t))) continue;+ try {+ // t is a fixed constant from the retention config above — safe to splice.+ const [r] = await sql(`SELECT * FROM pgstattuple_approx('public.${t}'::regclass)`);+ candidates.push({+ table: t,+ tableMb: Number(r.table_len) / 1048576,+ freeMb: (Number(r.approx_free_space) + Number(r.dead_tuple_len)) / 1048576,+ });+ } catch {+ /* a table we cannot measure is a table we do not rewrite */+ }+ }+ result.measured = candidates.length;++ const targets = pickCompactionTargets({+ candidates,+ minFreeMb,+ minFreeRatio: COMPACT_MIN_FREE_RATIO,+ maxTables,+ });+ for (const target of targets) {+ const t0 = Date.now();+ try {+ await sql(`VACUUM FULL ${target.table}`);+ const [after] = await sql(+ `SELECT (pg_total_relation_size('${target.table}') / 1048576.0)::numeric(10,1) AS mb`,+ );+ result.compacted.push({+ table: target.table,+ before_mb: Math.round(target.tableMb),+ after_mb: Number(after.mb),+ took_ms: Date.now() - t0,+ });+ } catch (err) {+ result.skipped.push({ table: target.table, reason: err?.message?.slice(0, 120) });+ }+ }+ return result;+}+// ── C. Best-effort VACUUM of the tables we pruned ─────────────────────────────async function vacuumTables(names) {for (const t of names) {@@ -428,6 +542,17 @@ export default wrapCron(async (req, res) => {if (regen.deleted > 0 || regen.stripped > 0) touched.push('avatar_regen_jobs');await vacuumTables(touched);+ // D. Under pressure, actually shrink the files (plain VACUUM cannot) so the+ // storage gate unlatches. Off-switch and bounds are env-tunable.+ let compaction = { measured: 0, compacted: [], skipped: [] };+ const compactEnabled = process.env.DB_COMPACT_ENABLED !== '0';+ if (underPressure && compactEnabled) {+ compaction = await compactTables({+ minFreeMb: clampInt(process.env.DB_COMPACT_MIN_FREE_MB, 1, 10_000, COMPACT_MIN_FREE_MB),+ maxTables: clampInt(process.env.DB_COMPACT_MAX_TABLES, 0, 20, COMPACT_MAX_TABLES),+ });+ }+const sizeAfterMb = await dbSizeMb();const topTables = await topRelationsBySize();@@ -443,9 +568,12 @@ export default wrapCron(async (req, res) => {.slice(0, 5).map((t) => `${t.table} ${t.mb}MB`).join(', ');+ const compactLine = compaction.compacted.length+ ? ` Compacted: ${compaction.compacted.map((c) => `${c.table} ${c.before_mb}→${c.after_mb}MB`).join(', ')}.`+ : '';sendOpsAlert('db retention pressure valve engaged',- `db ${sizeBeforeMb}MB ≥ high-water ${highWaterMb}MB — tightened firehose retention to ${minDays}d; pruned ${firehose.mints} mints, ${seriesDeleted} series rows, ${runLogsDeleted} autopilot run-log rows, ${orphansDeleted} orphaned satellite rows. Largest tables: ${topLine || 'n/a'}. Raise the Neon storage plan (or DB_RETENTION_HIGH_WATER_MB / PUMP_INTEL_RETENTION_DAYS) for a longer window.`,+ `db ${sizeBeforeMb}MB ≥ high-water ${highWaterMb}MB — tightened firehose retention to ${minDays}d; pruned ${firehose.mints} mints, ${seriesDeleted} series rows, ${runLogsDeleted} autopilot run-log rows, ${orphansDeleted} orphaned satellite rows.${compactLine} Largest tables: ${topLine || 'n/a'}. Raise the Neon storage plan (or DB_RETENTION_HIGH_WATER_MB / PUMP_INTEL_RETENTION_DAYS) for a longer window.`,{ signature: 'db:retention-pressure' },);}@@ -467,6 +595,7 @@ export default wrapCron(async (req, res) => {audit,regen,vacuumed: touched,+ compaction,top_tables: topTables,took_ms: Date.now() - started,});diff --git a/api/cron/intel-learn.js b/api/cron/intel-learn.jsindex 76204bac8..282ab5fc1 100644--- a/api/cron/intel-learn.js+++ b/api/cron/intel-learn.js@@ -43,7 +43,15 @@ export default wrapCron(async (req, res) => {const { labeled } = await labelOutcomes({ network: NETWORK, limit: 100, minAgeMinutes: 60 });// Retrain once there's enough labeled history. Skips quietly below the floor.- const train = await trainWeights({ network: NETWORK, minSamples: 50 });+ // The sample ceiling keeps the training query's memory bounded (the signals+ // JSONB per row is heavy) — freshest labeled coins win, which also tracks+ // regime shifts in the launch meta.+ const maxSamples = Number.parseInt(process.env.INTEL_TRAIN_MAX_SAMPLES || '', 10);+ const train = await trainWeights({+ network: NETWORK,+ minSamples: 50,+ maxSamples: Number.isFinite(maxSamples) && maxSamples > 0 ? maxSamples : 20_000,+ });return json(res, 200, {ok: true,diff --git a/api/llm/anthropic.js b/api/llm/anthropic.jsindex 1c3a8b2e2..7f7181a28 100644--- a/api/llm/anthropic.js+++ b/api/llm/anthropic.js@@ -30,6 +30,12 @@ import {vertexRequestHeaders,toVertexBody,} from '../_lib/vertex-claude.js';+import {+ vertexGeminiAvailable,+ vertexGeminiModel,+ vertexGeminiChatUrl,+ vertexGeminiHeaders,+} from '../_lib/vertex-gemini.js';const log = logger('llm.anthropic');@@ -109,6 +115,44 @@ const UPSTREAM_URL = {grok: 'https://api.x.ai/v1/chat/completions',};+// Resolve a model id to its upstream route. Static allowlist first; the Vertex+// Gemini credits anchor resolves dynamically because its model id is env-tunable+// (VERTEX_GEMINI_MODEL) and its availability is gated by GOOGLE_CLOUD_PROJECT,+// not an API key. It shares the 'openai' branch — the Vertex OpenAI-compatible+// endpoint speaks the same wire format (tools included), so request translation+// and the Anthropic-shape response/SSE conversion below work verbatim.+// Exported for the anchor regression tests (tests/api/llm-vertex-anchor-surfaces).+export function resolveModelRoute(modelId) {+ if (MODELS[modelId]) return MODELS[modelId];+ if (vertexGeminiAvailable() && modelId === vertexGeminiModel()) {+ return { kind: 'openai', provider: 'vertex-gemini' };+ }+ return null;+}++// Ordered model fallback chain for a request. Free lanes degrade in-order; the+// credits-funded Vertex Gemini anchor is ALWAYS the final rung when the GCP+// project is set (api/chat.js semantics — see api/_lib/vertex-gemini.js): it is+// keyless, has no third-party quota, and no present provider key may evict it,+// so an embedded agent's brain cannot 5xx while GCP credits can still answer.+// The paid Anthropic rung stays ahead of it — when that key works it is the+// caller-visible model family — but a dead paid key degrades to the anchor+// instead of surfacing an error. Exported for the anchor regression tests.+export function modelFallbackChain(requestedModel) {+ const chain = [+ requestedModel,+ ...[+ 'meta-llama/llama-3.1-8b-instruct:free',+ 'meta/llama-4-maverick-17b-128e-instruct',+ 'claude-haiku-4-5-20251001',+ ].filter((m) => m !== requestedModel),+ ];+ if (vertexGeminiAvailable() && !chain.includes(vertexGeminiModel())) {+ chain.push(vertexGeminiModel());+ }+ return chain;+}+const FIRST_PARTY = ['three.ws', 'localhost'];const DEFAULT_MONTHLY_TOKEN_BUDGET = 1_000_000;@@ -366,20 +410,15 @@ export default wrap(async (req, res) => {// 1. Requested model (e.g. llama-3.3-70b:free)// 2. meta-llama/llama-3.1-8b-instruct:free (smaller free model)// 3. meta/llama-4-maverick-17b-128e-instruct (free NVIDIA NIM tier)- // 4. claude-haiku-4-5-20251001 (paid Anthropic — last resort)+ // 4. claude-haiku-4-5-20251001 (paid Anthropic)+ // 5. Vertex Gemini credits anchor (keyless last resort)// The NVIDIA free tier sits ahead of paid Anthropic so a rate-limited OpenRouter// free model exhausts every free option before any per-token cost is incurred.// A non-reasoning model is used here on purpose: a reasoning model can spend a// small max_tokens budget entirely on (dropped) reasoning_content and return an- // empty completion to the embedded agent.- const modelFallbacks = [- requestedModel,- ...[- 'meta-llama/llama-3.1-8b-instruct:free',- 'meta/llama-4-maverick-17b-128e-instruct',- 'claude-haiku-4-5-20251001',- ].filter((m) => m !== requestedModel),- ];+ // empty completion to the embedded agent. See modelFallbackChain for the+ // anchor's never-evicted guarantee.+ const modelFallbacks = modelFallbackChain(requestedModel);const isStreaming = body.stream === true;const t0 = Date.now();@@ -397,7 +436,7 @@ export default wrap(async (req, res) => {for (let attempt = 0; attempt < modelFallbacks.length; attempt++) {usedModel = modelFallbacks[attempt];- const route = MODELS[usedModel];+ const route = resolveModelRoute(usedModel);if (!route) {if (attempt === 0) {return error(res, 400, 'validation_error', `model "${usedModel}" not in allowlist`);@@ -436,6 +475,20 @@ export default wrap(async (req, res) => {}),});}+ } else if (route.provider === 'vertex-gemini') {+ // Credits anchor: keyless — the GCP OAuth bearer token is minted in+ // build() per attempt, and a token-exchange failure degrades through+ // the chain exactly like an unreachable upstream (upstream_prepare_failed).+ // Same OpenAI wire shape as the other non-Anthropic lanes, so the+ // request translation and Anthropic-shape response conversion are reused.+ transports.push({+ via: 'vertex-gemini',+ build: async () => ({+ url: vertexGeminiChatUrl(),+ headers: await vertexGeminiHeaders(),+ body: JSON.stringify(anthropicBodyToOpenAI({ ...body, model: usedModel })),+ }),+ });} else {const apiKey = process.env[route.envKey];if (apiKey) {diff --git a/api/vision.js b/api/vision.jsindex ad9983c5c..fc86f7ed3 100644--- a/api/vision.js+++ b/api/vision.js@@ -55,7 +55,7 @@ export default wrap(async function handler(req, res) {}if (!visionConfigured()) {- return error(res, 503, 'not_configured', 'Vision is not configured (set NVIDIA_API_KEY, or OPENAI_API_KEY for the paid backstop)');+ return error(res, 503, 'not_configured', 'Vision is not configured (set NVIDIA_API_KEY, GOOGLE_CLOUD_PROJECT for the Vertex Gemini credits anchor, or OPENAI_API_KEY for the paid backstop)');}// Metered like the other free NVIDIA lanes.diff --git a/api/widgets/[id]/[action].js b/api/widgets/[id]/[action].jsindex bde4bfc3d..c2f053c8f 100644--- a/api/widgets/[id]/[action].js+++ b/api/widgets/[id]/[action].js@@ -21,6 +21,12 @@ import { moderateAnonInput, refusalReply } from '../../_lib/moderation.js';import { embeddingsConfigured, scoreRowsBySpace } from '../../_lib/embeddings.js';import { rerankConfigured, rerankPassages } from '../../_lib/rerank.js';import { watsonxConfig, watsonxToken } from '../../_lib/watsonx.js';+import {+ vertexGeminiAvailable,+ vertexGeminiModel,+ vertexGeminiChatUrl,+ vertexGeminiHeaders,+} from '../../_lib/vertex-gemini.js';import { fetchSafePublicUrlPinned, SsrfBlockedError } from '../../_lib/ssrf-guard.js';import { listTranscripts, getTranscript } from './_transcripts.js';// _knowledge.js is loaded on demand (dynamic import in handleKnowledge) so the@@ -370,7 +376,8 @@ async function handleChat(req, res) {// ── Brain dispatchers ──────────────────────────────────────────────────────-function pickProviderChain(requested, requestedModel) {+// Exported for the anchor regression tests (tests/api/llm-vertex-anchor-surfaces).+export function pickProviderChain(requested, requestedModel) {// Fall back in DEFAULT_PROVIDER_ORDER (free providers first), not the// PROVIDERS object order, so an unconfigured explicit request degrades to// the free chain — never to a paid key first. Mirrors api/chat.js. Returns@@ -408,6 +415,25 @@ function pickProviderChain(requested, requestedModel) {(name === 'watsonx' ? cfg.defaultModel : envPinned || cfg.defaultModel);chain.push({ name, cfg, apiKey, model });}+ // Credits-funded Vertex Gemini anchor, ALWAYS the final rung when the GCP+ // project is set (api/chat.js semantics — see api/_lib/vertex-gemini.js).+ // Keyless: the OAuth bearer token is minted per request via resolveHeaders,+ // so no env key gates it and no present paid key can evict it. This is what+ // keeps embedded widget chat answering when groq/openrouter/nvidia throttle+ // together and the prod OPENAI_API_KEY is billing-dead. Never a primary:+ // it is appended after every configured route, reached only via failover.+ if (vertexGeminiAvailable()) {+ chain.push({+ name: 'vertex-gemini',+ cfg: {+ style: 'openai',+ url: vertexGeminiChatUrl(),+ resolveHeaders: vertexGeminiHeaders,+ },+ apiKey: 'vertex',+ model: vertexGeminiModel(),+ });+ }return chain;}@@ -546,13 +572,19 @@ async function callOpenAICompatible({payload.tool_choice = 'auto';}+ // Keyless routes (the Vertex Gemini credits anchor) mint their auth per+ // request via resolveHeaders — a token-exchange failure throws here and fails+ // over to the next route exactly like a transport error.+ const headers = route.cfg.resolveHeaders+ ? { ...(await route.cfg.resolveHeaders()), ...(route.cfg.extraHeaders || {}) }+ : {+ Authorization: `Bearer ${route.apiKey}`,+ 'Content-Type': 'application/json',+ ...(route.cfg.extraHeaders || {}),+ };const upstream = await fetch(route.cfg.url, {method: 'POST',- headers: {- Authorization: `Bearer ${route.apiKey}`,- 'Content-Type': 'application/json',- ...(route.cfg.extraHeaders || {}),- },+ headers,body: JSON.stringify(payload),// A hung upstream must not eat the whole function budget — abort and let// the provider chain in handleChat move to the next route.diff --git a/tests/api/avatar-render-framing.test.js b/tests/api/avatar-render-framing.test.jsnew file mode 100644index 000000000..afa2126ea--- /dev/null+++ b/tests/api/avatar-render-framing.test.js@@ -0,0 +1,178 @@+// /api/avatar/render regression locks for the two 2026-07-21 defects:+//+// 1. Pose parameter silently dropped. The old in-page applier used a+// hand-rolled alias table whose Mixamo entries kept the ':' that+// GLTFLoader strips from node names, so on mixamorig rigs zero joints+// matched and every render came out in bind pose. The fix ships the pose+// studio's real modules (pose-rig / glb-canonicalize / pose-mannequin)+// into the headless page as data: URL modules and applies presets via+// world-delta retargeting. These tests lock that wiring.+//+// 2. Portrait/headshot crops decapitated the model: the camera aimed at a+// fraction of the bounding-box CENTER with a radius multiplier, which put+// the top of the visible frustum below the crown. computeCameraFraming is+// the pure replacement (vertical band + width fit); these tests assert the+// head band always fits the frustum across scenes and aspect ratios.++import { describe, it, expect } from 'vitest';+import {+ SCENE_PRESETS,+ computeCameraFraming,+ resolveRenderParams,+ poseRuntimeModules,+ sceneViewerHtml,+} from '../../api/_lib/avatar-render.js';++// A typical rigged human: 1.7 units tall, arms at sides.+const HUMAN_BOX = { min: { x: -0.3, y: 0, z: -0.15 }, max: { x: 0.3, y: 1.7, z: 0.15 } };+// The same human bound in a T-pose: arm span roughly equals height.+const TPOSE_BOX = { min: { x: -0.85, y: 0, z: -0.15 }, max: { x: 0.85, y: 1.7, z: 0.15 } };+const FOV = 28;+const ASPECTS = [0.5, 0.75, 1, 16 / 9, 2];++function verticalHalfCoverage(distance, fovDeg) {+ return distance * Math.tan((fovDeg * Math.PI) / 360);+}+function horizontalHalfCoverage(distance, fovDeg, aspect) {+ return verticalHalfCoverage(distance, fovDeg) * aspect;+}++describe('SCENE_PRESETS bands', () => {+ it('every scene band tops out above the crown (headroom baked in)', () => {+ for (const [name, preset] of Object.entries(SCENE_PRESETS)) {+ expect(Array.isArray(preset.band), `${name} has a band`).toBe(true);+ expect(preset.band[1], `${name} band top`).toBeGreaterThanOrEqual(1.02);+ expect(preset.band[0], `${name} band order`).toBeLessThan(preset.band[1]);+ }+ });++ it('keeps the phi/theta the public endpoint catalog exposes', () => {+ for (const preset of Object.values(SCENE_PRESETS)) {+ expect(Number.isFinite(preset.phi)).toBe(true);+ expect(Number.isFinite(preset.theta)).toBe(true);+ }+ });+});++describe('computeCameraFraming', () => {+ it('keeps the head band inside the vertical frustum for every scene and aspect', () => {+ for (const [name, preset] of Object.entries(SCENE_PRESETS)) {+ for (const aspect of ASPECTS) {+ for (const box of [HUMAN_BOX, TPOSE_BOX]) {+ const f = computeCameraFraming(box, preset, aspect, FOV, { theta: preset.theta, phi: preset.phi });+ const sizeY = box.max.y - box.min.y;+ const bandTop = box.min.y + sizeY * preset.band[1];+ const covered = f.target.y + verticalHalfCoverage(f.distance, FOV);+ // The frustum top at the target plane must clear the band top,+ // which itself is above the crown — no decapitation possible.+ expect(covered, `${name} @ aspect ${aspect}`).toBeGreaterThanOrEqual(bandTop);+ expect(bandTop).toBeGreaterThanOrEqual(box.max.y);+ expect(f.distance).toBeGreaterThan(0);+ }+ }+ }+ });++ it('full-body fits the entire T-pose arm span horizontally at every aspect', () => {+ const preset = SCENE_PRESETS['full-body'];+ for (const aspect of ASPECTS) {+ const f = computeCameraFraming(TPOSE_BOX, preset, aspect, FOV, null);+ const halfSpan = (TPOSE_BOX.max.x - TPOSE_BOX.min.x) / 2;+ expect(horizontalHalfCoverage(f.distance, FOV, aspect), `aspect ${aspect}`).toBeGreaterThanOrEqual(halfSpan);+ }+ });++ it('crop scenes zoom tighter than full-body on a square render', () => {+ const order = ['full-body', 'upper-body', 'portrait', 'headshot'];+ const distances = order.map(+ (name) => computeCameraFraming(HUMAN_BOX, SCENE_PRESETS[name], 1, FOV, null).distance,+ );+ for (let i = 1; i < distances.length; i++) {+ expect(distances[i], `${order[i]} tighter than ${order[i - 1]}`).toBeLessThan(distances[i - 1]);+ }+ });++ it('aims the camera at the band center, elevated per phi', () => {+ const preset = SCENE_PRESETS['portrait'];+ const f = computeCameraFraming(HUMAN_BOX, preset, 1, FOV, null);+ const sizeY = HUMAN_BOX.max.y - HUMAN_BOX.min.y;+ const expectedLookY = HUMAN_BOX.min.y + (sizeY * (preset.band[0] + preset.band[1])) / 2;+ expect(f.target.y).toBeCloseTo(expectedLookY, 6);+ // phi < 90 puts the camera above the look-at point.+ expect(f.position.y).toBeGreaterThan(f.target.y);+ });++ it('orbit overrides beat preset angles, including a legitimate 0', () => {+ const preset = SCENE_PRESETS['portrait']; // theta 8+ const overridden = computeCameraFraming(HUMAN_BOX, preset, 1, FOV, { theta: 0, phi: 90 });+ // theta 0 + phi 90 → camera straight down +Z from the target, same height.+ expect(overridden.position.x).toBeCloseTo(overridden.target.x, 6);+ expect(overridden.position.y).toBeCloseTo(overridden.target.y, 6);+ expect(overridden.position.z).toBeGreaterThan(overridden.target.z);+ });++ it('survives a degenerate zero-size box without NaNs', () => {+ const point = { min: { x: 0, y: 0, z: 0 }, max: { x: 0, y: 0, z: 0 } };+ const f = computeCameraFraming(point, SCENE_PRESETS['full-body'], 1, FOV, null);+ for (const v of [f.distance, f.position.x, f.position.y, f.position.z, f.target.x, f.target.y, f.target.z]) {+ expect(Number.isFinite(v)).toBe(true);+ }+ });+});++describe('pose runtime modules (world-delta retarget in the headless page)', () => {+ it('ships pose-rig, glb-canonicalize, and pose-mannequin as data: URL ESM', () => {+ const mods = poseRuntimeModules();+ expect(Object.keys(mods).sort()).toEqual(['glb-canonicalize', 'pose-mannequin', 'pose-rig']);+ for (const url of Object.values(mods)) {+ expect(url.startsWith('data:text/javascript;base64,')).toBe(true);+ }+ });++ it('rewrites pose-rig relative imports to bare specifiers the import map resolves', () => {+ const mods = poseRuntimeModules();+ const decode = (url) => Buffer.from(url.split(',')[1], 'base64').toString('utf8');+ const poseRig = decode(mods['pose-rig']);+ expect(poseRig).toContain("from 'glb-canonicalize'");+ expect(poseRig).toContain("from 'pose-mannequin'");+ expect(poseRig).toContain('export function poseFromMannequinPreset');+ expect(poseRig).toContain('export function makeGltfRig');+ expect(/from\s+['"]\.{1,2}\//.test(poseRig)).toBe(false);+ const canon = decode(mods['glb-canonicalize']);+ expect(canon).toContain('export function canonicalizeBoneName');+ const mannequin = decode(mods['pose-mannequin']);+ expect(mannequin).toContain('export class Mannequin');+ });+});++describe('sceneViewerHtml wiring', () => {+ const params = resolveRenderParams({ scene: 'portrait', width: 384, height: 512, pose: 'wave' }).params;++ it('embeds the requested pose and the pose-rig retarget path', () => {+ const html = sceneViewerHtml({+ glbUrl: 'https://cdn.example/avatar.glb',+ width: params.width,+ height: params.height,+ background: 'transparent',+ pose: { shoulderR: { x: 0, y: 0, z: -2.45 } },+ cameraOrbit: { theta: params.scenePreset.theta, phi: params.scenePreset.phi, radius: null },+ expression: null,+ scenePreset: params.scenePreset,+ });+ expect(html).toContain("import { makeGltfRig, poseFromMannequinPreset } from 'pose-rig'");+ expect(html).toContain('"pose-rig": "data:text/javascript;base64,');+ expect(html).toContain('poseFromMannequinPreset(poseMap)');+ expect(html).toContain('"shoulderR"');+ expect(html).toContain('function computeCameraFraming');+ // The retired alias table must not resurface: it never matched Mixamo+ // rigs (GLTFLoader strips the ':' its entries relied on).+ expect(html).not.toContain('mixamorig:leftshoulder');+ // The rule from the pose-preset retarget fix: never skeleton.pose().+ expect(html).not.toContain('skeleton.pose(');+ });++ it('still validates pose ids at the param layer', () => {+ expect(resolveRenderParams({ pose: 'wave' }).params.posePresetId).toBe('wave');+ expect(resolveRenderParams({ pose: 'nope' }).error.code).toBe('unknown_pose');+ });+});diff --git a/tests/api/coingecko-stale.test.js b/tests/api/coingecko-stale.test.jsindex 75d0e1728..6067b80f3 100644--- a/tests/api/coingecko-stale.test.js+++ b/tests/api/coingecko-stale.test.js@@ -11,6 +11,7 @@import { describe, it, expect, afterEach, vi } from 'vitest';import { geckoFetch } from '../../api/_lib/coingecko.js';+import { cacheSet } from '../../api/_lib/cache.js';const realFetch = global.fetch;afterEach(() => {@@ -66,4 +67,29 @@ describe('geckoFetch — stale-on-error', () => {await geckoFetch(path, { ttlMs: 60_000 });expect(global.fetch).toHaveBeenCalledTimes(1);});++ // The memory stale buffer dies with the instance. The durable last-good copy+ // (shared cache, written on every good fetch) is what keeps a COLD instance+ // serving through an upstream storm instead of 502ing — the exact failure the+ // 2026-07-22 api-sweep caught on /api/coin/exchanges.+ it('falls back to the durable last-good copy when memory has nothing (throttled upstream)', async () => {+ const path = `/coins/durable-429-${Math.round(performance.now())}`;+ await cacheSet(`gecko:last-good:${path}`, { id: 'from-durable' }, 300);+ global.fetch = vi.fn().mockResolvedValue(fail(429));+ await expect(geckoFetch(path)).resolves.toEqual({ id: 'from-durable' });+ });++ it('falls back to the durable last-good copy on a cold network failure', async () => {+ const path = `/coins/durable-net-${Math.round(performance.now())}`;+ await cacheSet(`gecko:last-good:${path}`, { id: 'from-durable-net' }, 300);+ global.fetch = vi.fn().mockRejectedValue(Object.assign(new Error('boom'), { name: 'TimeoutError' }));+ await expect(geckoFetch(path)).resolves.toEqual({ id: 'from-durable-net' });+ });++ it('never masks a 404 with the durable copy', async () => {+ const path = `/coins/durable-404-${Math.round(performance.now())}`;+ await cacheSet(`gecko:last-good:${path}`, { id: 'ghost' }, 300);+ global.fetch = vi.fn().mockResolvedValue(fail(404));+ await expect(geckoFetch(path)).rejects.toMatchObject({ status: 404 });+ });});diff --git a/tests/db-retention-compaction.test.js b/tests/db-retention-compaction.test.jsnew file mode 100644index 000000000..0dcf25b1a--- /dev/null+++ b/tests/db-retention-compaction.test.js@@ -0,0 +1,51 @@+// pickCompactionTargets — the pure selection bounds behind db-retention's+// section D (VACUUM FULL under storage pressure). The floors and ordering are+// what keep the rewrite step safe: never touch mostly-live tables, never+// rewrite more than the per-tick cap, and always free the small files first so+// each rewrite has headroom near a hard cap.+import { describe, it, expect } from 'vitest';+import { pickCompactionTargets } from '../api/cron/db-retention.js';++const pick = (candidates, over = {}) =>+ pickCompactionTargets({+ candidates,+ minFreeMb: 25,+ minFreeRatio: 0.3,+ maxTables: 3,+ ...over,+ });++describe('pickCompactionTargets', () => {+ it('keeps only tables clearing both the absolute and ratio floors', () => {+ const targets = pick([+ { table: 'bloated', tableMb: 100, freeMb: 60 }, // 60% free — in+ { table: 'small_free', tableMb: 40, freeMb: 20 }, // 50% free but < 25 MB — out+ { table: 'big_live', tableMb: 500, freeMb: 60 }, // 60 MB free but only 12% — out+ { table: 'healthy', tableMb: 80, freeMb: 2 }, // out on both+ ]);+ expect(targets.map((t) => t.table)).toEqual(['bloated']);+ });++ it('orders smallest file first so rewrites free headroom progressively', () => {+ const targets = pick([+ { table: 'huge', tableMb: 500, freeMb: 300 },+ { table: 'mid', tableMb: 120, freeMb: 70 },+ { table: 'tiny', tableMb: 60, freeMb: 30 },+ ]);+ expect(targets.map((t) => t.table)).toEqual(['tiny', 'mid', 'huge']);+ });++ it('caps the number of rewrites per tick', () => {+ const candidates = Array.from({ length: 6 }, (_, i) => ({+ table: `t${i}`,+ tableMb: 100 + i,+ freeMb: 50,+ }));+ expect(pick(candidates)).toHaveLength(3);+ expect(pick(candidates, { maxTables: 0 })).toHaveLength(0);+ });++ it('ignores zero-size tables instead of dividing by zero', () => {+ expect(pick([{ table: 'empty', tableMb: 0, freeMb: 0 }])).toEqual([]);+ });+});diff --git a/workers/agent-sniper/intel/learn.js b/workers/agent-sniper/intel/learn.jsindex 6933e7643..8e89bb383 100644--- a/workers/agent-sniper/intel/learn.js+++ b/workers/agent-sniper/intel/learn.js@@ -308,7 +308,7 @@ export function correlation(pairs) {** @returns {Promise<{ trained: boolean, sample_size: number, weights?: object, conditional_win_rates?: object }>}*/-export async function trainWeights({ network = 'mainnet', minSamples = 50 } = {}) {+export async function trainWeights({ network = 'mainnet', minSamples = 50, maxSamples = 20_000 } = {}) {const sql = await getSql();if (!sql) return { trained: false, sample_size: 0 };@@ -317,6 +317,12 @@ export async function trainWeights({ network = 'mainnet', minSamples = 50 } = {}// traded carries its REAL realized win/loss (ro.realized_win). Realized PnL is// higher-fidelity ground truth than the chart-based ATH label, so the label// below prefers it when present.+ //+ // Bounded to the freshest maxSamples labeled coins: the unbounded form OOMed+ // the cron once the labeled set passed ~64k rows (each carries the full+ // signals JSONB), and launch-meta regimes shift (e.g. the 2026-07-21 BOOST+ // cutover), so the newest window is both the safe and the better training set.+ const cap = Math.max(1, Math.min(200_000, maxSamples | 0));const rows = await sql`selecti.signals, o.outcome, ro.realized_win,@@ -328,6 +334,8 @@ export async function trainWeights({ network = 'mainnet', minSamples = 50 } = {}join pump_coin_outcomes o on o.mint = i.mintleft join oracle_realized_outcomes ro on ro.mint = i.mint and ro.network = i.networkwhere i.network = ${network} and o.outcome <> 'unknown'+ order by i.first_seen_at desc+ limit ${cap}`;if (rows.length < minSamples) return { trained: false, sample_size: rows.length };