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
fix(swarms): answer the live dashboard stream's CORS preflight and stop HEAD holding it open
nirholas46782c4c6af7
diff --git a/api/galaxy.js b/api/galaxy.jsindex c3e6db0d2..581f28c2a 100644--- a/api/galaxy.js+++ b/api/galaxy.js@@ -1,14 +1,14 @@/**- * Agent Galaxy — a semantic 3D star-map of every published agent on three.ws,+ * Agent Galaxy: a semantic 3D star-map of every published agent on three.ws,* positioned by IBM Granite embeddings (watsonx.ai) and grouped into Granite-named* constellations.*- * GET /api/galaxy — the full galaxy snapshot (cached server-side).- * ?refresh=1 — force a rebuild (re-embed changed agents,+ * GET /api/galaxy : the full galaxy snapshot (cached server-side).+ * ?refresh=1 : force a rebuild (re-embed changed agents,* re-cluster, re-name constellations).- * ?limit=<n> — cap agents (default 600, max 1200; busiest first).+ * ?limit=<n> : cap agents (default 600, max 1200; busiest first).*- * POST /api/galaxy — { "query": "trading bots" } semantic search.+ * POST /api/galaxy : { "query": "trading bots" } semantic search.* Embeds the query with Granite, ranks published* agents by cosine similarity against their stored* Granite vectors, returns the top matches.@@ -34,7 +34,7 @@ import {} from './_lib/galaxy.js';// A served snapshot is reused for this long before a GET rebuilds it. The embedding-// cache (agent_embeddings) makes rebuilds cheap — only new/edited agents re-embed —+// cache (agent_embeddings) makes rebuilds cheap (only new/edited agents re-embed),// so this mostly throttles the k Granite cluster-naming calls per rebuild.const SNAPSHOT_TTL_MS = 6 * 60 * 60 * 1000; // 6h@@ -167,7 +167,7 @@ async function persistSnapshot(payload) {WHERE id NOT IN (SELECT id FROM galaxy_snapshots ORDER BY created_at DESC LIMIT 5)`;} catch (err) {- // A persistence failure must not fail the request — the caller still gets a+ // A persistence failure must not fail the request: the caller still gets a// freshly computed payload; the next GET simply rebuilds instead of caching.console.error('[galaxy] persistSnapshot failed', err);}@@ -221,7 +221,7 @@ async function handleSearch(req, res, cfg) {async function loadPublishedAgents(limit) {// This is the same public feed for every viewer, and its `chat_count`// correlated subquery + `ORDER BY chat_count` forces a COUNT(*) over- // usage_events for EVERY published agent on each load — the dominant cost+ // usage_events for EVERY published agent on each load, the dominant cost// here. Cache the result for 60s so that expensive ranking runs at most once// a minute regardless of traffic.const rows = await cacheWrap(`galaxy:published:${limit}`, 60, async () => await sql`diff --git a/api/garment-forge.js b/api/garment-forge.jsindex e52e012fc..b785babe8 100644--- a/api/garment-forge.js+++ b/api/garment-forge.js@@ -15,7 +15,7 @@* (see its README for the pipeline: Vertex reference image → GPU mesh fleet →* compose on the canonical body → model-rig → strip/validate → publish). A* finished job is ALREADY live in the public wardrobe catalog- * (src/garment-catalog.js) when this endpoint reports done — the closet's next+ * (src/garment-catalog.js) when this endpoint reports done: the closet's next* catalog refresh shows it with no extra step.** Uses the same free-lane rate limits as the other generation endpoints; the@@ -114,7 +114,7 @@ async function pollJob(req, res, cfg, jobId) {});}const job = await upstream.json();- // Pass through only the documented public fields — the worker record also+ // Pass through only the documented public fields: the worker record also// carries internal bookkeeping the client has no use for.return json(res, 200, {job_id: job.job_id,diff --git a/api/glb.js b/api/glb.jsindex b019ef6ef..981fc5a48 100644--- a/api/glb.js+++ b/api/glb.js@@ -1,4 +1,4 @@-// GET /api/glb?src=<url> — same-origin GLB proxy with open CORS.+// GET /api/glb?src=<url>: same-origin GLB proxy with open CORS.//// Why: generated models live on the public R2 host, whose CORS policy is an// origin allowlist. Anything loading a GLB from the browser on an origindiff --git a/api/gpt-forge.js b/api/gpt-forge.jsindex d9c8d225c..d586f013a 100644--- a/api/gpt-forge.js+++ b/api/gpt-forge.js@@ -1,5 +1,5 @@/**- * GPT Forge — the ChatGPT-dedicated forge pipeline, an exact clone of+ * GPT Forge: the ChatGPT-dedicated forge pipeline, an exact clone of* api/forge.js serving the ChatGPT surfaces (the Apps SDK MCP connector at* api/mcp-studio and the custom-GPT Actions endpoint at api/3d/studio, both* via api/_mcp-studio/gpt-forge-client.js). It exists so the ChatGPT pipeline@@ -17,13 +17,13 @@* GET /api/gpt-forge?catalog → tier/backend/cost matrix** Two request axes select how a mesh is produced (see api/_lib/forge-tiers.js):- * • path — "image" (image-intermediate: text→image→mesh via FLUX + TRELLIS,+ * • path : "image" (image-intermediate: text→image→mesh via FLUX + TRELLIS,* the fast default; or Hunyuan3D self-host), "geometry" (geometry-* first: native text→mesh / image→mesh via Meshy or Tripo, no* synthesized intermediate view, higher geometric ceiling), or* "sketch" (a drawing + a prompt naming it → TripoSG-scribble,* self-host; untextured geometry).- * • tier — draft | standard | high — the target polygon budget + texture+ * • tier : draft | standard | high: the target polygon budget + texture* richness. The high tier yields a visibly denser mesh.* Every job result reports the path + tier + backend that produced it.*@@ -31,21 +31,21 @@* (request header `x-forge-provider-key`, or the signed-in user's stored key).* Without one, the geometry path returns a designed `needs_key` state.*- * Optional output controls (every field off by default — see- * api/_lib/forge-options.js — an old request that never sends any of these+ * Optional output controls (every field off by default, see+ * api/_lib/forge-options.js: an old request that never sends any of these* behaves exactly as before):- * • seed — integer, reproducible generation on lanes that expose one.- * • output_format — "glb" (default) | "glb-draco" | "glb-meshopt": a real+ * • seed : integer, reproducible generation on lanes that expose one.+ * • output_format : "glb" (default) | "glb-draco" | "glb-meshopt": a real* post-generation @gltf-transform compression pass (api/_lib/glb-compress.js).- * • texture_size / target_polycount — poly-aware backends only (Hunyuan3D,+ * • texture_size / target_polycount: poly-aware backends only (Hunyuan3D,* Meshy, Tripo, Rodin, TripoSG); ignored (never 422s) on TRELLIS.- * • director: true — runs the same IBM Granite "art director" prompt+ * • director: true runs the same IBM Granite "art director" prompt* rewrite the free MCP tools use before a text prompt synthesizes its* reference image. Off by default; fails soft to the raw prompt.- * • force_regenerate: true — skip the result cache read for this call (the+ * • force_regenerate: true: skip the result cache read for this call (the* cache still gets refreshed with the new result).* A finished generation's metadata carries `quality` (api/_lib/glb-quality.js- * — valid/flag/score/reasons) and, when compression was requested,+ *: valid/flag/score/reasons) and, when compression was requested,* `compression` (mode + before/after byte counts). A flagged degenerate/low* result is retried once automatically on the lanes that complete inline* within one request (free NVIDIA NIM, HuggingFace Spaces, BYOK-sync).@@ -55,7 +55,7 @@** This is the public, auth-free twin of the 3D Studio MCP server (api/mcp-3d.js).* No mock paths: if a selected backend isn't configured the endpoint returns a- * clean 503/501 and the page renders a designed state — it never fabricates a+ * clean 503/501 and the page renders a designed state, it never fabricates a* model.*/@@ -152,17 +152,17 @@ import { meshDirectorFor, meshSubjectClass, resolveLogoPrompt } from './_lib/for// Circuit-breaker key + window for the free NVIDIA NIM TRELLIS text→3D lane. The// hosted NVCF gateway can degrade so a submit neither completes nor hands back a-// pollable id before our timeout — a single slow window otherwise makes every+// pollable id before our timeout: a single slow window otherwise makes every// text prompt re-pay that full timeout before failing over to the reconstruct// lane. A short cooldown (recorded on a health failure, checked before the lane// runs) lets subsequent requests skip a degraded lane and go straight to a// working one; it expires on its own so a recovered lane is retried promptly.-// Best-effort via the shared cache — a miss just means "not cooling".+// Best-effort via the shared cache: a miss just means "not cooling".const NIM_TRELLIS_COOLDOWN_KEY = 'forge-nim-trellis';// Sideline the free NIM lane after a failure. The cooldown exists to avoid// re-paying the expensive submit-timeout HANG, so a socket timeout / unreachable// host (no HTTP status came back) earns the full window. A fast gateway 5xx (a-// 504/503 the gateway returned promptly — a cold-start/capacity blip the+// 504/503 the gateway returned promptly: a cold-start/capacity blip the// in-provider retry already rode) only earns a short window, so a single transient// 504 doesn't sideline the free lane for two minutes and dump every text prompt on// the paid lane. See nimCooldownSeconds().@@ -170,7 +170,7 @@ const NIM_FORGE_COOLDOWN_SECONDS = 120;const NIM_FORGE_GATEWAY_COOLDOWN_SECONDS = 30;// The platform-keyed paid reconstruct lane (Replicate TRELLIS) recorded as down.-// Set only on an out-of-credit/billing failure — which won't self-heal until ops+// Set only on an out-of-credit/billing failure: which won't self-heal until ops// tops the account up, so the window is long (reason 'auth'). The NIM-cooldown// router reads it to avoid skipping the free lane in favour of a dead paid lane.const REPLICATE_PAID_COOLDOWN_KEY = 'forge-replicate-paid';@@ -245,7 +245,7 @@ const VALID_ASPECT = new Set(['1:1', '4:3', '3:4', '16:9', '9:16']);const MAX_VIEWS = 6;// Guard for caller-supplied reference image / source GLB URLs. http(s) only,-// bounded length — we forward these to the reconstruction/rig provider, so we+// bounded length: we forward these to the reconstruction/rig provider, so we// never accept data: URLs or unbounded strings.const HTTP_URL_RE = /^https?:\/\/[^\s]+$/i;@@ -261,7 +261,7 @@ function clientKeyFrom(req) {return hashClient(Array.isArray(raw) ? raw[0] : raw);}-// /forge is auth-free and the overwhelming majority of calls are anonymous —+// /forge is auth-free and the overwhelming majority of calls are anonymous -// but when a caller DOES carry a session cookie (the browser /create/studio// flow while logged in), attach their user_id to the durable creation so it// surfaces on their public portfolio (/u/:username → "Models" tab). Resolved@@ -289,7 +289,7 @@ function parseTier(body) {return TIER_IDS.includes(t) ? t : DEFAULT_TIER;}-// "needs a BYOK key" — a designed, branchable state (mirrors rig_unconfigured)+// "needs a BYOK key": a designed, branchable state (mirrors rig_unconfigured)// rather than a generic error, so the page can prompt for the key inline.function needsKey(res, providerName) {const meta = BACKENDS[providerName];@@ -302,7 +302,7 @@ function needsKey(res, providerName) {// Normalize the caller's reference image input into an ordered, de-duplicated// list of view URLs. Accepts the multi-view `image_urls: string[]` form and the-// legacy single `image_url: string` (backward compatible — a single string+// legacy single `image_url: string` (backward compatible, a single string// still works exactly as before). Empty/blank/duplicate entries are dropped.function parseImageUrls(body) {let raw;@@ -330,8 +330,8 @@ function unconfigured(res) {});}-// Whether a thrown provider error means the upstream itself is unavailable —-// throttled, over-quota, unreachable, or 5xx — as opposed to a client/config+// Whether a thrown provider error means the upstream itself is unavailable -+// throttled, over-quota, unreachable, or 5xx: as opposed to a client/config// fault. Both never-dead-end fallbacks (image→3D to the self-hosted Hunyuan3D// worker, text→3D to the free NVIDIA NIM lane) degrade on exactly these so a// generation rides out a transient upstream outage instead of failing the user.@@ -347,7 +347,7 @@ function isUpstreamUnavailable(err) {// A leaked paid-account billing/credit message from the platform's OWN vendor// (e.g. Replicate "You have insufficient credit to run this model… purchase-// credit") is internal infra state — surfacing it to the user is both useless+// credit") is internal infra state: surfacing it to the user is both useless// (they can't fund our account) and a billing-state leak. Detect it so the// boundary can answer with an honest, generic "temporarily unavailable" instead.// BYOK callers are excluded at the call site: a credit message about THEIR OWN@@ -361,9 +361,9 @@ function isPaidCreditFailure(err) {// ── Realism modules (land concurrently; imported lazily + fail-open) ───────────// Two dedicated modules sharpen the realism path without ever becoming a hard// dependency of it:-// • forge-reference-image.js — seeds text→3D reconstruction with a Vertex-Gemini+// • forge-reference-image.js: seeds text→3D reconstruction with a Vertex-Gemini// photoreal reference image (falls back to the standing text→image provider).-// • forge-quality-gate.js — scores a finished generation (vision QA) and+// • forge-quality-gate.js : scores a finished generation (vision QA) and// supplies the retry hint that drives a bounded auto-retry.// Both are consumed through the lazy, fail-open shims below: an absent module (not// yet deployed) or a down Vertex backend degrades to the standing behaviour, so@@ -379,8 +379,8 @@ function readForgeEnv(name) {// Photoreal reconstruction reference. Prefers the dedicated Vertex-Gemini module;// falls back to the standing text→image provider (the FLUX/Imagen/NIM chain) when-// the module is absent or Vertex is unavailable. Returns { imageUrl, model } —-// exactly textToImage()'s shape — so the call site is a drop-in swap.+// the module is absent or Vertex is unavailable. Returns { imageUrl, model } -+// exactly textToImage()'s shape: so the call site is a drop-in swap.export async function seedReferenceImage({ prompt, aspect, seed, skipNim }) {if (readForgeEnv('FORGE_REFERENCE_IMAGE') !== 'off') {try {@@ -436,7 +436,7 @@ export function qualityGateAppliesTo(tierId, quality = undefined) {if (s === 'adaptive') return shouldEscalateToVisionQA(quality);return false; // 'high' scope, non-high tier}-// Bounded retry cap — default 1, clamped 0..2 so a quality retry can never turn one+// Bounded retry cap: default 1, clamped 0..2 so a quality retry can never turn one// generation into an unbounded credit/latency sink.export function qualityGateMaxRetries() {const raw = readForgeEnv('FORGE_QUALITY_GATE_MAX_RETRIES');@@ -478,7 +478,7 @@ export async function scoreQualityGate({ glbUrl, prompt, tier, backend, referencreturn { pass: true, skipped: true, qa_available: false };}-// True only for an explicit failing verdict — a skipped/absent gate never retries.+// True only for an explicit failing verdict: a skipped/absent gate never retries.export function qualityGateFailed(verdict) {return Boolean(verdict) && verdict.skipped !== true && verdict.pass === false;}@@ -564,14 +564,14 @@ async function qualityGateFinalize({ tierId, prompt, path, backend, referenceIma// degrades to when Replicate is unreachable / over-quota (HTTP 429/5xx).// Returns true once it has written a 200 response, or false when the lane is// itself unavailable (so the caller can fall through to the next lane). Prompt-// is required — NVCF is text-only; photo submissions never reach here.+// is required: NVCF is text-only; photo submissions never reach here.async function runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path, opts = null, cacheKey = null }) {let submitted;try {const nv = await loadNvidiaProvider();submitted = await nv.textTo3d({ prompt, tier, seed: opts?.seed ?? undefined });} catch (err) {- // A timed-out / unreachable / throttled / 5xx NIM lane is degraded — cool it+ // A timed-out / unreachable / throttled / 5xx NIM lane is degraded, cool it// down so the next request skips the submit-timeout gamble and fails over// fast. A 4xx (bad input / key) is not a lane-health fault, so it never cools.if (isUpstreamUnavailable(err)) {@@ -627,7 +627,7 @@ async function runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path, opt// One auto-retry on a flagged low-quality/degenerate output (CLAUDE.md: no// silent mediocrity). Only worth attempting when the free NIM lane already- // completed synchronously once — a second synchronous completion is the+ // completed synchronously once: a second synchronous completion is the// common case, so this stays a bounded, in-request retry rather than a// background job. Best-effort: any retry failure just keeps the first result.let retried = false;@@ -769,14 +769,14 @@ async function runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path, opt}// Free Hugging Face Spaces image→3D lane (Hunyuan3D / TRELLIS / TripoSR on free-// GPU Spaces — the same provider the avatar reconstruction pipeline runs). The+// GPU Spaces: the same provider the avatar reconstruction pipeline runs). The// platform photo→3D default is the Replicate TRELLIS lane; when that account is// over-quota or unreachable a photo upload would otherwise dead-end, because the// free NVIDIA NIM fallback is text-only. This lane gives image mode the same-// "never dead-end" guarantee text mode already has — gated on HF_TOKEN, so it is+// "never dead-end" guarantee text mode already has: gated on HF_TOKEN, so it is// a transparent no-op on deployments that don't set it. The provider blocks// until the GLB is ready (Space queue + inference, within the 300s budget), so-// this returns status:'done' synchronously like the NVIDIA sync branch — no+// this returns status:'done' synchronously like the NVIDIA sync branch, no// poll handle to route. Returns true once a 200 is written, false when the lane// is unavailable so the caller can surface its own error.// One-shot guard so the "HuggingFace lane not configured" notice is logged once@@ -807,7 +807,7 @@ async function runHfImageLane({const mod = await import('./_providers/huggingface.js');provider = mod.createRegenProvider();} catch (err) {- // HF_TOKEN absent or the Space chain is empty — the lane isn't available+ // HF_TOKEN absent or the Space chain is empty: the lane isn't available// on this deployment; fall through so the caller surfaces the real error.// A missing token is a STATIC deployment condition, not a per-request fault:// logging it on every forge call floods the function logs (it was the@@ -827,9 +827,9 @@ async function runHfImageLane({// The Space call BLOCKS this serverless worker for up to ~280s. Under an influx// that exhausts the Vercel worker pool and stalls /forge for everyone, so we cap// fleet-wide concurrent holds with a self-healing TTL lease. Over the cap the- // lane reports "not served" (false) and the caller degrades — to the paid+ // lane reports "not served" (false) and the caller degrades, to the paid// reconstruct fallback on the free-first path, or a designed "free lane busy"- // error on an explicit free pick — instead of piling onto an exhausted pool.+ // error on an explicit free pick: instead of piling onto an exhausted pool.const slot = await acquireBlockingSlot('hf', {max: SCALE_LIMITS.hfConcurrent,ttlMs: SCALE_LIMITS.hfSlotTtlMs,@@ -893,7 +893,7 @@ async function runHfImageLane({});// One auto-retry on a flagged low-quality/degenerate output. Only attempted- // when a concurrency slot is free right now — the HF lane is capacity-capped,+ // when a concurrency slot is free right now: the HF lane is capacity-capped,// so a busy fleet keeps the first (flagged) result rather than starving// other callers of their turn on the free Spaces.let retried = false;@@ -1033,18 +1033,18 @@ async function startJob(req, res) {const body = await readJson(req, 8_000).catch(() => null);// Two reconstruction modes share this path:- // • image→3D — a caller supplies one or more reference views (image_url or+ // • image→3D: a caller supplies one or more reference views (image_url or// image_urls[]); we reconstruct directly and skip the text-to-image stage.// With >1 view the provider fuses them (multi-view conditioning). An// optional prompt may still guide the model where it accepts one.- // • text→3D — no images; we synthesize the reference image from the prompt+ // • text→3D: no images; we synthesize the reference image from the prompt// with FLUX first, then reconstruct.let imageUrls = parseImageUrls(body);const isImageMode = imageUrls.length > 0;const prompt = typeof body?.prompt === 'string' ? body.prompt.trim() : '';// Optional, additive output controls (seed, output_format/compression,- // texture_size, target_polycount) — see _lib/forge-options.js. Every field is+ // texture_size, target_polycount): see _lib/forge-options.js. Every field is// off by default, so a request that never sends them behaves exactly as// before. An explicitly-present but invalid value is a 400 with an actionable// message; an absent field is never an error.@@ -1067,7 +1067,7 @@ async function startJob(req, res) {// Subject class (organic / hard-surface / null) steers the High realism tier's// self-host lane order: Hunyuan3D-2.1 leads on people / creatures / detailed// organics, self-host TRELLIS leads on hard-surface / mechanical subjects. Pure- // keyword heuristic on the prompt — zero latency, no LLM — and a no-op for every+ // keyword heuristic on the prompt: zero latency, no LLM, and a no-op for every// tier below High (see freeLaneCandidates). An image submission with no guidance// prompt classifies to null and keeps the default order.const subjectClass = classifyForgeSubject(prompt);@@ -1083,7 +1083,7 @@ async function startJob(req, res) {// can't stack a second submit-timeout window on the same request.let nimGatewayDegraded = false;- // Pay-per-use (Token Utility — consumption lever): set to { paymentId, refId,+ // Pay-per-use (Token Utility: consumption lever): set to { paymentId, refId,// settledAt, redeemed? } once a non-holder's settled $THREE payment is accepted// in lieu of holding. The payment is validated at the gate, claimed atomically// just before dispatch, and released if the generation fails before delivery.@@ -1100,7 +1100,7 @@ async function startJob(req, res) {// must never hand one payer's job to another).let requestHash = null;- // The geometry path is BYOK-only — no free model does native text→geometry.+ // The geometry path is BYOK-only: no free model does native text→geometry.// So when the caller didn't explicitly pick a backend and has no key for the// default geometry engine, transparently serve the free image lane (NVIDIA// NIM on draft, TRELLIS otherwise) instead of a dead "needs key" error. The@@ -1117,7 +1117,7 @@ async function startJob(req, res) {// Health-aware lane selection: when the caller didn't name a backend, consult a// cheap, cached liveness snapshot of the free lanes and skip any our probe (or a- // recent submit failure) marks down — so a cold or unreachable self-host worker+ // recent submit failure) marks down: so a cold or unreachable self-host worker// is routed AROUND before submit, not failed-over after. Only the platform free// lanes (image/sketch) are candidates; geometry is BYOK and unaffected. Pure// best-effort: any snapshot error leaves the env-resolved backendId in place, so@@ -1145,7 +1145,7 @@ async function startJob(req, res) {// Honest cold-start signal for a chosen self-host lane: true only when the// liveness probe reached the worker but it answered slowly (a scale-to-zero// container spinning up). Reuses the cached snapshot, so the common path pays no- // extra probe. Used to widen the ETA + flag `cold_start` in the response — never+ // extra probe. Used to widen the ETA + flag `cold_start` in the response, never// to fabricate progress; the client's real polling still drives actual status.const coldStartFor = async (id) => {if (!isSelfHostBackend(id) || !coldStartSecondsFor(id)) return false;@@ -1159,12 +1159,12 @@ async function startJob(req, res) {};// Content-addressed result cache (see _lib/forge-cache.js): a text→3D request- // on a platform-keyed lane (never BYOK — that spends the caller's own account,+ // on a platform-keyed lane (never BYOK: that spends the caller's own account,// so it must never be replayed to a stranger) can be served instantly from a// prior identical generation instead of re-running the GPU pipeline. Captured// once, before any lane-failover churn reassigns `backendId` below, so the// same cache key is used to both look up and (on completion) store this- // request's result — a failover to a different lane just means a miss, never+ // request's result: a failover to a different lane just means a miss, never// a wrong hit. `force_regenerate: true` skips the read (a fresh run is still// written back, keeping the cache warm). High tier is paid/gated per caller// and is never cached, matching the module's own privacy boundary.@@ -1195,13 +1195,13 @@ async function startJob(req, res) {}}- // $THREE hold-to-access gate (Token Utility v1) — the High tier (200k poly ++ // $THREE hold-to-access gate (Token Utility v1): the High tier (200k poly +// PBR, textured) is the platform's premium quality tier. It now runs on a// free-for-us engine (HuggingFace Hunyuan3D) like every other tier, so this is- // a pure monetization gate — we charge for higher quality, not to recover+ // a pure monetization gate: we charge for higher quality, not to recover// vendor spend: reserved for holders (Bronze+, $25 hold) or a presented tier// pass, otherwise a hold-or-pay 402. BYOK backends are exempt (the caller pays- // their own vendor key — key-gated, not hold-gated). Draft and Standard are+ // their own vendor key: key-gated, not hold-gated). Draft and Standard are// never gated, and internal cron seed jobs bypass it entirely.// requireFeatureAccess writes the 402 (three_hold_required) itself and returns// { ok:false }; on a holder it writes nothing and lets the job proceed.@@ -1288,7 +1288,7 @@ async function startJob(req, res) {// above. It stops the influx/abuse failure mode where many callers each stay// under their own cap but collectively drain spend. BYOK lanes spend the// caller's own key, so the platform-budget ceiling must never throttle them.- // When it trips the free NVIDIA / HuggingFace lanes stay open — paid capacity+ // When it trips the free NVIDIA / HuggingFace lanes stay open, paid capacity// degrades, it never dead-ends.if (!isFreeLane && !backendMeta?.byok) {const globalRl = await limits.mcp3dGenerateGlobal();@@ -1341,7 +1341,7 @@ async function startJob(req, res) {// Vision pre-check (Consumer 1 of the shared vision helper): catch a photo// that can't be reconstructed BEFORE it burns a generation slot. Validates- // the primary view only. Fail-open — a vision outage returns ok:true and we+ // the primary view only. Fail-open: a vision outage returns ok:true and we// proceed exactly as before (validateForgeImage owns that contract). The// user can override a verdict they disagree with via `skip_validation:true`// (e.g. a stylized reference our checker is too cautious about).@@ -1349,7 +1349,7 @@ async function startJob(req, res) {// checker is trained to reject, and exactly what TripoSG-scribble wants.if (body?.skip_validation !== true && path !== 'sketch') {// The forge client key is a hashed client-supplied header, NOT an OAuth- // client — it has no row in oauth_clients, so it must never land in the+ // client: it has no row in oauth_clients, so it must never land in the// FK-constrained usage_events.client_id (that fails the insert and the// whole spend event is silently dropped). Attribute it via meta instead.// Every view is checked in parallel, not just the primary: a bad@@ -1392,7 +1392,7 @@ async function startJob(req, res) {// Sketch→3D is single-view and prompt-conditioned: the drawing is the only// input image, and the prompt names what it depicts (TripoSG-scribble is a- // text+scribble model — without the prompt it has nothing to disambiguate+ // text+scribble model: without the prompt it has nothing to disambiguate// rough strokes against).if (path === 'sketch') {if (!isImageMode) {@@ -1416,7 +1416,7 @@ async function startJob(req, res) {}// path / tier / backendId were resolved above (the rate limiter is lane-aware).- // An explicitly selected text-only backend can't serve a photo submission —+ // An explicitly selected text-only backend can't serve a photo submission -// say so plainly rather than failing upstream with an opaque 422.if (isImageMode && BACKENDS[backendId]?.userImages === false) {return json(res, 422, {@@ -1429,7 +1429,7 @@ async function startJob(req, res) {}try {- // Pay-per-use: claim the settled $THREE payment now — immediately before any+ // Pay-per-use: claim the settled $THREE payment now, immediately before any// provider work, so every cheap failure above (rate limit, moderation, bad// input) left the payment reusable. The atomic claim (payment_id PRIMARY KEY)// is the single-use source of truth: a concurrent retry of the same payment@@ -1485,7 +1485,7 @@ async function startJob(req, res) {// ── Sketch path (TripoSG-scribble, self-host) ───────────────────────────// The drawing + prompt go straight to the TripoSG worker's scribble- // pipeline. Geometry only — no synthesized intermediate view, no textures;+ // pipeline. Geometry only: no synthesized intermediate view, no textures;// the result panel's Retexture/Stylize tools pick up from there.if (path === 'sketch') {let gcp;@@ -1522,7 +1522,7 @@ async function startJob(req, res) {'Sketch-to-3D is not configured on this deployment (GCP_TRIPOSG_URL is not set).',});}- // The sketch model is conditioned on the drawing — no other lane can+ // The sketch model is conditioned on the drawing: no other lane can// serve it, so there is nothing to fail over to. Cool the worker so the// next request skips it while it recovers, and return a designed,// retryable state instead of a raw provider error.@@ -1542,7 +1542,7 @@ async function startJob(req, res) {}// Wrap the GCP job envelope in a forge token so polling routes back to- // the GCP provider — same idiom as the Hunyuan3D lane.+ // the GCP provider: same idiom as the Hunyuan3D lane.const token = encodeJobToken({ provider: 'gcp', kind: null, taskId: job.extJobId });const creationId = await createCreation({clientKey: clientKeyFrom(req),@@ -1582,12 +1582,12 @@ async function startJob(req, res) {}// ── BYOK geometry-style providers (Meshy / Tripo / Rodin / Stability) ────- // A native 3D model emits mesh geometry directly — from the prompt- // (text→geometry) or a single photo (image→3D) — with no synthesized+ // A native 3D model emits mesh geometry directly: from the prompt+ // (text→geometry) or a single photo (image→3D): with no synthesized// intermediate view, so detail isn't capped by one image. These backends// have no platform key; the caller supplies their own. Dispatch is a// registry lookup on the backend's `byok` name (Replicate BYOK is handled- // on the image-intermediate path below — it speaks a different interface).+ // on the image-intermediate path below: it speaks a different interface).const byokProvider = BACKENDS[backendId].byok;const byokFactory = BYOK_PROVIDER_FACTORIES[byokProvider];if (byokFactory) {@@ -1626,7 +1626,7 @@ async function startJob(req, res) {const clientKey = clientKeyFrom(req);// Synchronous completion (Stable Fast 3D): the provider already persisted- // the GLB to R2 and handed back a durable url — no task to poll. Record a+ // the GLB to R2 and handed back a durable url: no task to poll. Record a// finished creation and return done so the client skips polling, exactly// like the NVIDIA NIM synchronous path.if (!submitted.taskId && submitted.resultGlbUrl) {@@ -1722,8 +1722,8 @@ async function startJob(req, res) {// TRELLIS on NIM emits the mesh natively from the prompt (no FLUX// intermediate view) and needs no BYOK key. It serves prompt submissions// on the image path as the free draft default; photo submissions never- // resolve here (hosted preview is text-only — see the provider header).- // The free NVIDIA NIM lane is a flaky synchronous upstream — NVCF can be+ // resolve here (hosted preview is text-only: see the provider header).+ // The free NVIDIA NIM lane is a flaky synchronous upstream, NVCF can be// unreachable, accept the job but drop the request id, or finish with no// artifact, and a missing module/key throws on load. Per the free-first// "AI must never fail" policy none of these may surface as a dead 502: a@@ -1734,12 +1734,12 @@ async function startJob(req, res) {if (backendId === 'nvidia') {nvidiaTried = true;// Skip the submit-timeout gamble when the lane is in a recent-failure- // cooldown — go straight to the reconstruct lane instead of re-hanging.+ // cooldown: go straight to the reconstruct lane instead of re-hanging.// BUT only when that reconstruct lane is a real destination: it free-firsts// to HuggingFace and then the paid Replicate account, so it's viable when HF// is configured OR the paid account isn't itself recorded out-of-credit. When// both are gone, skipping NIM would route straight into a dead paid lane and- // 503 the user — so we ignore the cooldown and give the free lane a real shot.+ // 503 the user: so we ignore the cooldown and give the free lane a real shot.const cooldowns = await providersInCooldown([NIM_TRELLIS_COOLDOWN_KEY,REPLICATE_PAID_COOLDOWN_KEY,@@ -1763,11 +1763,11 @@ async function startJob(req, res) {}// ── Image-intermediate path (TRELLIS default, or Hunyuan3D self-host) ────- // Hunyuan3D runs on its own Cloud Run worker (GCP_HUNYUAN3D_URL) — never+ // Hunyuan3D runs on its own Cloud Run worker (GCP_HUNYUAN3D_URL), never// the avatar pipeline controller, whose face pipeline fails every// non-face image with "no face detected".// Replicate BYOK runs the same reconstruction models on the caller's own- // Replicate account — resolve their token up front (distinct from the+ // Replicate account: resolve their token up front (distinct from the// platform-keyed TRELLIS default).let byokReplicateKey = null;if (backendId === 'replicate_byok') {@@ -1786,13 +1786,13 @@ async function startJob(req, res) {} else if (backendId === 'replicate_byok') {provider = createRegenProvider({ apiToken: byokReplicateKey });} else if (backendId === 'huggingface') {- // The free HF Spaces lane is driven by runHfImageLane() below — it+ // The free HF Spaces lane is driven by runHfImageLane() below, it// creates its own provider. We deliberately do NOT build a Replicate// client here: creating one would 503 on a deployment that has no// REPLICATE_API_TOKEN, breaking an explicitly-chosen free engine.} else if (backendId === 'trellis_selfhost') {// Driven by the dedicated self-host TRELLIS lane below, which builds- // its own GCP provider. Same reasoning as huggingface — never build a+ // its own GCP provider. Same reasoning as huggingface, never build a// Replicate client here, or a deployment without REPLICATE_API_TOKEN// would 503 on an explicitly-chosen free self-hosted engine.} else {@@ -1809,11 +1809,11 @@ async function startJob(req, res) {});}if (backendId === 'replicate_byok') return needsKey(res, backendId);- // The default TRELLIS (Replicate) provider couldn't be built — no+ // The default TRELLIS (Replicate) provider couldn't be built, no// REPLICATE_API_TOKEN. That alone is NOT "unconfigured" when the free// HuggingFace Spaces lane is live: a degraded-from-NVIDIA text prompt, or// a photo→3D request, must still reconstruct on the free lane rather than- // dead-ending at a 503. Leave `provider` undefined and fall through — the+ // dead-ending at a 503. Leave `provider` undefined and fall through, the// free-first HF block below serves it, and the `!provider` guard further// down raises a designed unavailable state only if every free lane is gone// too. Mirrors the self-host TRELLIS failover (provider = undefined) above.@@ -1855,7 +1855,7 @@ async function startJob(req, res) {// Resolve the reference views: supplied directly (image→3D) or a single// view synthesized from the prompt (text→3D). `referenceImageUrl` is the- // primary view — the durable preview + the synthesis target.+ // primary view: the durable preview + the synthesis target.let referenceImageUrl;let textToImageModel;let views;@@ -1867,10 +1867,10 @@ async function startJob(req, res) {// Granite art-director pass (on by default; pass director:false to skip):// rewrites the raw prompt into a richer, single-subject spec (form,// per-part PBR materials, photoreal-by-default cues, composition- // constraints) before it drives the FLUX/Vertex reference image — the+ // constraints) before it drives the FLUX/Vertex reference image, the// same director the free MCP tools use. Fail-soft: any failure (chat// lane down, timeout) silently keeps the raw prompt, so running it by- // default can only ever help, never break, a generation — and it rides+ // default can only ever help, never break, a generation, and it rides// the free-first LLM chain, so it costs no GCP/vendor spend. This is the// single biggest lever on "does this look like a real photograph"// available before the reference image is even generated.@@ -1922,8 +1922,8 @@ async function startJob(req, res) {}// Explicitly chosen free HuggingFace lane. Unlike the trellis free-first- // path below — which degrades to the paid Replicate lane when the free- // Spaces are down — an explicit pick of the FREE engine must never silently+ // path below: which degrades to the paid Replicate lane when the free+ // Spaces are down: an explicit pick of the FREE engine must never silently// fall through to a paid lane: that would spend credits the user// deliberately opted out of. So we run the free Spaces and, if every one is// busy/down, return a designed error the UI can act on (retry / switch engine).@@ -1958,7 +1958,7 @@ async function startJob(req, res) {params: {images: views,seed: opts.seed ?? undefined,- // Tier-scaled sampler/export budgets — this is where standard/high+ // Tier-scaled sampler/export budgets: this is where standard/high// actually buy more quality on our own GPU (steps, kept geometry,// texture resolution) instead of only a bigger advertised polycount.quality: selfhostQualityForTier(tier.id),@@ -2090,8 +2090,8 @@ async function startJob(req, res) {}// Free-first: exhaust the free reconstruct lane (HuggingFace Spaces) BEFORE- // the paid Replicate default, so a forge call never spends on — or dead-ends- // against — the paid account while a free lane can serve it. We already hold+ // the paid Replicate default, so a forge call never spends on, or dead-ends+ // against: the paid account while a free lane can serve it. We already hold// the reference views (uploaded, or FLUX-synthesized above), so the free lane// reconstructs from exactly what Replicate would have. Scoped to the default// trellis lane: an explicitly chosen Hunyuan3D / Replicate-BYOK backend is@@ -2139,7 +2139,7 @@ async function startJob(req, res) {try {// A self-host failover landed here with no paid provider configured (no// REPLICATE_API_TOKEN) and the free HF lane above didn't serve the request- // — there is no reconstruct lane left. Raise it as upstream-unavailable so+ //: there is no reconstruct lane left. Raise it as upstream-unavailable so// the catch below runs the remaining free fallbacks (Hunyuan3D → HF) and,// if those are gone too, surfaces a designed unavailable state.if (!provider) {@@ -2150,7 +2150,7 @@ async function startJob(req, res) {}// Per-provider submit throttle: shed platform Replicate bursts to the free// lane BEFORE they hit the account quota and turn into fleet-wide 429s. Only- // the platform-keyed default lane is capped — BYOK lanes spend the caller's+ // the platform-keyed default lane is capped: BYOK lanes spend the caller's// own quota. Over-cap is thrown as upstream-unavailable so the existing// fallback chain (self-host Hunyuan3D → free HuggingFace) absorbs it.if (@@ -2184,7 +2184,7 @@ async function startJob(req, res) {// referenceImageUrl from textToImage(), so the same reconstruct// fallbacks apply. Without this branch the outer catch re-checks// nvidiaTried=true and skips NIM, leaving the user with a 429.- // Scoped to the default trellis backend only — an explicitly chosen+ // Scoped to the default trellis backend only: an explicitly chosen// Hunyuan3D / BYOK backend that fails surfaces its own error. Provenance// always reports the lane that actually ran so any downgrade is visible.const upstreamGone =@@ -2195,7 +2195,7 @@ async function startJob(req, res) {const mode3d = isImageMode ? 'image→3D' : 'text→3D (via synthesized image)';- // Fallback #1 — self-hosted TRELLIS Cloud Run worker (workers/model-trellis),+ // Fallback #1: self-hosted TRELLIS Cloud Run worker (workers/model-trellis),// when wired and not cooled. FREE_FALLBACK_FOR_PATH prefers it first among// the free image lanes, so this paid-lane failover walks the same order:// our own GPU (zero vendor cost) before any external free allocation. It@@ -2237,7 +2237,7 @@ async function startJob(req, res) {}}- // Fallback #2 — self-hosted Hunyuan3D Cloud Run worker, when wired.+ // Fallback #2: self-hosted Hunyuan3D Cloud Run worker, when wired.const hunyuanUrl = process.env.GCP_HUNYUAN3D_URL;if (!job && hunyuanUrl && process.env.GCP_RECONSTRUCTION_KEY) {console.warn(@@ -2245,7 +2245,7 @@ async function startJob(req, res) {);backendId = 'hunyuan3d';provider = createGcpProvider();- // Hunyuan3D is poly-aware — supply the tier budget the TRELLIS params omit.+ // Hunyuan3D is poly-aware: supply the tier budget the TRELLIS params omit.reconstructParams.target_polycount = opts.targetPolycount ?? tier.polycount;reconstructParams.tier = tier.id;reconstructParams.path = path;@@ -2256,7 +2256,7 @@ async function startJob(req, res) {params: reconstructParams,});} else if (!job) {- // Fallback #3 — free Hugging Face Spaces image→3D (gated on HF_TOKEN).+ // Fallback #3: free Hugging Face Spaces image→3D (gated on HF_TOKEN).// It blocks and writes its own status:'done' response; if it does, the// request is complete. Otherwise fall through to surface the real error.// For text mode, views=[referenceImageUrl] (the FLUX-synthesized image).@@ -2287,7 +2287,7 @@ async function startJob(req, res) {}// How the job was actually conditioned. The provider reports back which- // backend handled it and how many views it fused — these can differ from+ // backend handled it and how many views it fused: these can differ from// what was requested when a single-view model is configured and we fall// back to the primary view. Surfaced so a downgrade is never silent.const viewsRequested = views.length;@@ -2372,7 +2372,7 @@ async function startJob(req, res) {}if (err?.code === 'insufficient_credits' && BACKENDS[backendId]?.byok) {// BYOK lane: the message names the CALLER'S own provider account, which- // they can act on — surface it. The platform's own paid lane falls through+ // they can act on: surface it. The platform's own paid lane falls through// to the sanitized "temporarily unavailable" state below.return json(res, 402, {error: 'insufficient_credits',@@ -2381,16 +2381,16 @@ async function startJob(req, res) {}// Last-resort free fallback: when the paid image-intermediate TRELLIS lane// (Replicate) is throttled, over-quota, unreachable, OR out of credit, a text- // prompt must never dead-end — degrade to the free NVIDIA NIM lane so the+ // prompt must never dead-end: degrade to the free NVIDIA NIM lane so the// default "type a prompt → get a model" flow always returns something. The// credit-exhaustion case matters most here: the failure is the paid FLUX// synthesis step (textToImage throws code:'billing'/402, which is NOT// upstream-unavailable), but the NIM TRELLIS lane is native text→mesh and- // needs no FLUX intermediate at all — so a dry Replicate account should hand+ // needs no FLUX intermediate at all: so a dry Replicate account should hand// the prompt to the healthy free lane rather than skip straight to the 503.// Honors the free-first "AI must never fail" policy; provenance reports// backend:nvidia so the downgrade is visible, not silent. Image uploads have- // no free reconstruct fallback here (NVCF is text-only — the HF lane already+ // no free reconstruct fallback here (NVCF is text-only, the HF lane already// absorbed them above), so they fall through to the designed states below.// `nvidiaTried` guards against re-running a lane that already failed this// request (the draft nvidia→trellis→nvidia loop).@@ -2401,7 +2401,7 @@ async function startJob(req, res) {prompt) {nvidiaTried = true;- // Don't degrade to NIM when it's already in a recent-failure cooldown — that+ // Don't degrade to NIM when it's already in a recent-failure cooldown, that// would just re-pay the submit timeout on a lane we know is down right now.const trellisCooling = (await providersInCooldown([NIM_TRELLIS_COOLDOWN_KEY])).has(NIM_TRELLIS_COOLDOWN_KEY,@@ -2418,13 +2418,13 @@ async function startJob(req, res) {}}- // Upstream throttling is a transient 429, not a server fault — return it as+ // Upstream throttling is a transient 429, not a server fault, return it as// such with a retry hint so the page can show a "busy, try again" state.if (err?.code === 'rate_limited' || err?.providerStatus === 429) {const retryAfter = typeof err?.retryAfter === 'number' ? err.retryAfter : 10;res.setHeader('retry-after', String(retryAfter));// A `queued` throttle is our own rate gate pacing the request to the- // upstream limit (not an upstream rejection) — tell the user it's in line so+ // upstream limit (not an upstream rejection): tell the user it's in line so// a retry reads as "your turn is coming up", not "the system is failing".const queued = Boolean(err?.queued);return json(res, 429, {@@ -2438,7 +2438,7 @@ async function startJob(req, res) {}// Free lanes are exhausted and the only remaining lane was the platform's// PAID vendor account, which is out of credit. The vendor's raw "buy credit"- // message is our internal billing state and is useless to the user — answer+ // message is our internal billing state and is useless to the user, answer// with an honest, generic unavailable state instead of leaking it. (BYOK lanes// kept their actionable account message via the insufficient_credits branch.)if (!BACKENDS[backendId]?.byok && isPaidCreditFailure(err)) {@@ -2446,7 +2446,7 @@ async function startJob(req, res) {console.warn(`[forge] paid reconstruct lane out of credit and no free lane available: ${err?.message || err}${creditDetail}`,);- // Record the paid lane as down (reason 'auth' — a billing fault that won't+ // Record the paid lane as down (reason 'auth': a billing fault that won't// self-heal until ops tops the account up). The NIM-cooldown router reads this// so the next text prompt keeps the free NIM lane in play instead of skipping// it to route into this now-known-dead paid lane.@@ -2467,8 +2467,8 @@ async function startJob(req, res) {message: err?.message || 'The generator could not start this job.',});} finally {- // A claimed pay-per-use payment that did NOT deliver a model — any non-2xx- // exit (validation 4xx, unconfigured 5xx, provider failure) — is released so+ // A claimed pay-per-use payment that did NOT deliver a model, any non-2xx+ // exit (validation 4xx, unconfigured 5xx, provider failure), is released so// the settled $THREE payment stays reusable on retry. A successful job (200)// keeps the claim, so one payment can never buy a second generation.if (paidHigh?.redeemed && res.statusCode >= 400) {@@ -2492,7 +2492,7 @@ async function startJob(req, res) {// Auto-rig an existing GLB mesh: skeleton + skin weights via the provider's// `rerig` mode (VAST-AI UniRig by default). Takes a GLB URL, returns a job id-// that polls through the same GET ?job=<id> path — provider.status() is+// that polls through the same GET ?job=<id> path: provider.status() is// mode-agnostic, so the rigged GLB surfaces exactly like a reconstruction.async function startRigJob(req, res) {const ip = clientIp(req);@@ -2510,8 +2510,8 @@ async function startRigJob(req, res) {});}- // Prefer the self-hosted GCP UniRig pipeline when it's configured — it supports- // rerig out of the box via its /rig endpoint — and fall back to Replicate when+ // Prefer the self-hosted GCP UniRig pipeline when it's configured, it supports+ // rerig out of the box via its /rig endpoint: and fall back to Replicate when// a REPLICATE_RERIG_MODEL is set. Mirrors the gcp-first resolution the MCP// studio path uses, so rigging works whenever ANY rerig-capable lane exists,// not only when the highest-precedence provider happens to be the rigger.@@ -2540,7 +2540,7 @@ async function startRigJob(req, res) {}}- // Rigging stays dormant until a rerig lane is configured — surface a clean+ // Rigging stays dormant until a rerig lane is configured, surface a clean// 501 rather than a generic provider error so callers can branch on it.if (!provider) {return json(res, 501, {@@ -2601,14 +2601,14 @@ async function startRigJob(req, res) {// 404s. Two production consequences (53 of 134 nvidia jobs in one 36h window// failed with "NVCF request not found or expired"):// 1. Concurrent polls for the same job (overlapping browser timers, a second-// tab, a retried request) race — one consumes the result, the other 404s+// tab, a retried request) race: one consumes the result, the other 404s// and flips the creation to failed even though the mesh exists.// 2. A result that expires out of NVCF's retention window (throttled// background tab, closed laptop) is genuinely gone.// Recovery below: single-flight the upstream poll per task id so only one// request ever touches NVCF at a time; on a 404, first re-check the store for-// a completion a racing poll already materialized, then — because the prompt-// is recorded on the creation row — resubmit the SAME generation once and+// a completion a racing poll already materialized, then, because the prompt+// is recorded on the creation row: resubmit the SAME generation once and// alias the old task id to the new one so the client's existing poll handle// keeps working. The alias lives in the shared cache; the creation row keeps// its original replicate_job_id, so findByJob/materializeCreation are untouched.@@ -2640,7 +2640,7 @@ async function pollNvidiaStatus({ nv, upstreamId, clientKey }) {if (result?.code !== 'nvcf_expired') return result;// The request id is dead. A racing poll may have already materialized the- // creation — that's a success, not a failure.+ // creation: that's a success, not a failure.const row = await findByJob({ replicateJobId: upstreamId, clientKey });if (row?.status === 'done' && row.glb_url) {return { status: 'done', resultGlbUrl: row.glb_url };@@ -2648,7 +2648,7 @@ async function pollNvidiaStatus({ nv, upstreamId, clientKey }) {// Genuinely lost (expired / consumed by an aborted socket). The never-dead-end// rule: regenerate server-side rather than surface a failure the user can only- // answer by re-clicking Generate. Once per job — the resub lock outlives the+ // answer by re-clicking Generate. Once per job: the resub lock outlives the// alias so a second expiry reports the failure honestly.if (!row?.prompt) return result;if (!(await acquireLock(`nvcf:resub:${upstreamId}`, NVCF_ALIAS_TTL_S))) {@@ -2676,11 +2676,11 @@ async function pollNvidiaStatus({ nv, upstreamId, clientKey }) {// ── Self-host (GCP worker) poll recovery ─────────────────────────────────────// A self-host /tasks/:id or /jobs/:id poll can 404 ("task not found on gcp// service") when the durable task record isn't visible to the instance this-// poll reached — the post-submit cross-instance window (worker at high+// poll reached: the post-submit cross-instance window (worker at high// concurrency, no session affinity) or a completion write racing us. That was// the platform's single largest failure class (410 of 425 trellis failures, all// path='image'), and the router used to treat the FIRST 404 as terminal. The-// GCP twin of pollNvidiaStatus: never dead-end on a recoverable signal —+// GCP twin of pollNvidiaStatus: never dead-end on a recoverable signal -// re-check the store, grace a young job, and only surface failure once a missing// task is genuinely orphaned, where the poll handler's lane failover takes over.async function pollGcpStatus({ gcp, upstreamId, clientKey, createdAt }) {@@ -2750,7 +2750,7 @@ async function pollJob(req, res, jobId) {// ChatGPT-pipeline divergence from api/forge.js: polls surface the// painted reference view (and the model that painted it) so the// ChatGPT surfaces can show the concept image while the mesh is- // still generating — the submit response already carries these,+ // still generating, the submit response already carries these,// but ChatGPT's Actions poll loop only ever sees poll responses.prompt: meta.prompt ?? null,preview_image_url: meta.preview_image_url ?? null,@@ -2804,7 +2804,7 @@ async function pollJob(req, res, jobId) {}result = await pollNvidiaStatus({ nv, upstreamId, clientKey });} else if (provider === 'gcp') {- // Serves every self-host lane (Hunyuan3D, TripoSG sketch) — the job+ // Serves every self-host lane (Hunyuan3D, TripoSG sketch), the job// envelope carries the worker URL it was submitted to.let gcp;try {@@ -2828,22 +2828,22 @@ async function pollJob(req, res, jobId) {result = await rep.status(liveHandle);}} catch {- // A transient poll error shouldn't fail the job — report running so the+ // A transient poll error shouldn't fail the job: report running so the// client's loop retries.return json(res, 200, { job_id: jobId, status: 'running', ...metaFields });}if (result.status === 'done' && result.resultGlbUrl) {// The compression choice a caller requested at submit time (see- // _lib/forge-job-options.js) — this poll is a LATER, separate invocation+ // _lib/forge-job-options.js): this poll is a LATER, separate invocation// with no access to that original request body, so it was bound to the// job handle then and is looked up now. Absent when nothing non-default- // was requested, or Redis is unavailable — both fail open to uncompressed.+ // was requested, or Redis is unavailable: both fail open to uncompressed.const boundOpts = await optionsForJob(jobId);// Copy the mesh into our own storage so the model is permanent (provider// delivery URLs expire) and serve the durable CDN url. Falls back to the// provider url where the store is unavailable. Always scored for quality- // (glb-quality.js) — free, deterministic, and the signal every lane's+ // (glb-quality.js): free, deterministic, and the signal every lane's// completion should carry regardless of which provider produced it.const durable = await materializeCreation({replicateJobId: upstreamId,@@ -2854,7 +2854,7 @@ async function pollJob(req, res, jobId) {compress: boundOpts?.compression || null,});// Populate the result cache this job was bound to at submit time (text→3D,- // non-high-tier, platform-keyed lanes only — see forgeResultCacheKey). A+ // non-high-tier, platform-keyed lanes only: see forgeResultCacheKey). A// job with no binding (image mode, high tier, BYOK, or no options// requested) is a no-op here.const boundCacheKey = await cacheKeyForJob(jobId);@@ -2902,7 +2902,7 @@ async function pollJob(req, res, jobId) {await markFailed({ replicateJobId: upstreamId, clientKey, error: result.error });// Cool the platform lane that actually failed so health-aware routing- // steers new submits away immediately — the poll-time twin of the+ // steers new submits away immediately: the poll-time twin of the// submit-side cooldown. BYOK lanes are excluded (never auto-selected).const failedBackend = meta?.backend || null;const platformLaneFailed = Boolean(failedBackend && BACKENDS[failedBackend] && !BACKENDS[failedBackend].byok);@@ -2910,7 +2910,7 @@ async function pollJob(req, res, jobId) {// Automatic redispatch (see _lib/forge-failover.js): recover the original// inputs from the creation row and continue the SAME job on the next- // configured lane — the client keeps polling this id and sees+ // configured lane: the client keeps polling this id and sees// status:"running" with a new backend instead of a dead end. Scoped to// platform image-path jobs with a stored reference view; sketch stays on// its purpose-built lane and BYOK vendors are never silently swapped.@@ -2947,7 +2947,7 @@ async function pollJob(req, res, jobId) {tier: meta.tier,path: meta.path,});- // Report "running" ONLY once the successor is durably chaseable —+ // Report "running" ONLY once the successor is durably chaseable -// otherwise the client would poll a dead handle forever.const bound = await bindJobSuccessor(jobId, {handle: submitted.handle,@@ -2973,7 +2973,7 @@ async function pollJob(req, res, jobId) {}}- // Terminal — but never a bare dead end: name the configured lanes that can+ // Terminal: but never a bare dead end: name the configured lanes that can// still serve a fresh retry of this request, so a client can offer a// one-click engine switch instead of a bare error. Sketch keeps its single// purpose-built lane (reconstruct models do badly on drawings).@@ -3029,11 +3029,11 @@ export default wrap(async (req, res) => {return startJob(req, res);}- // ?catalog — the tier + backend + cost/time matrix the composer renders.+ // ?catalog: the tier + backend + cost/time matrix the composer renders.// Public, no secrets; lets the UI communicate the time/cost trade-off and// which backends are live before the user commits. The payload only changes// on a redeploy (tiers/backends are static; `configured` reflects env- // presence), so it is heavily CDN-cacheable — one of the hottest GETs on the+ // presence), so it is heavily CDN-cacheable: one of the hottest GETs on the// site (every /forge load), now served almost entirely from the edge instead// of recomputing per request. stale-while-revalidate keeps it instant even as// the cache refreshes in the background.@@ -3043,7 +3043,7 @@ export default wrap(async (req, res) => {});}- // ?health — live-probes every platform backend's upstream (auth + quota+ // ?health: live-probes every platform backend's upstream (auth + quota// gates, zero vendor spend) so the UI and uptime checks see what a// generation would actually hit, not just which env vars exist. Cached// briefly per instance; rate-limited like status polling.@@ -3054,7 +3054,7 @@ export default wrap(async (req, res) => {// The probe already memoizes per instance (60s TTL); a short edge cache// collapses an influx of identical health polls into one shared response// every ~30s instead of one origin probe per client. stale-while-revalidate- // means a client never waits on a refresh — it sees the live status surface+ // means a client never waits on a refresh: it sees the live status surface// update within ~30s while the CDN absorbs the load.return json(res, 200, await probeForgeHealth(), {'cache-control': 'public, max-age=15, s-maxage=30, stale-while-revalidate=120',diff --git a/api/healthz.js b/api/healthz.jsindex 3af1345bf..579fe305a 100644--- a/api/healthz.js+++ b/api/healthz.js@@ -4,7 +4,7 @@// summary block compatible with the pump-dashboard's API status panel.//// Core health is always green (no hard DB dependency). Optional sub-probes-// (Resend, x402) are cached for 5 minutes and fail gracefully — a DB outage+// (Resend, x402) are cached for 5 minutes and fail gracefully: a DB outage// degrades the `x402` block but never the top-level `status: 'ok'`.import { cors, json, method, wrap } from './_lib/http.js';@@ -25,7 +25,7 @@ const HEARTBEAT_FRESH_MS = 6 * 60 * 1000;const MONITOR_CACHE_TTL_MS = 8 * 1000;// Subsystem health is a live read of in-process breaker state + one DB ping.// Cache it briefly so a burst of /healthz hits (dashboards poll it) doesn't fire-// a DB ping each — but keep the TTL short so a breaker tripping shows up fast.+// a DB ping each, but keep the TTL short so a breaker tripping shows up fast.const SUBSYSTEMS_CACHE_TTL_MS = 5 * 1000;let _resendCache = { value: null, expiresAt: 0 };let _x402Cache = { value: null, expiresAt: 0 };@@ -63,13 +63,13 @@ async function probeSubsystems() {}// Real bot/monitor status, sourced from Postgres:-// running — a bot_heartbeat row written by the pumpfun-monitor cron within+// running : a bot_heartbeat row written by the pumpfun-monitor cron within// the freshness window. When no row exists yet (or the DB is// unreachable, e.g. in unit tests) we fall back to the serverless// liveness signal: the function answering IS a liveness proof.-// mode — the worker's reported mode (the cron writes 'cron').-// claimsDetected — count of real graduation events the monitor has recorded.-// watches.total — users with at least one alert rule armed (server-side+// mode : the worker's reported mode (the cron writes 'cron').+// claimsDetected: count of real graduation events the monitor has recorded.+// watches.total : users with at least one alert rule armed (server-side// watchers that fire even with no tab open).async function probeMonitor() {const now = Date.now();@@ -93,7 +93,7 @@ async function probeMonitor() {value = {monitor: {// If a heartbeat row exists, trust its freshness. If none exists yet,- // the dedicated worker hasn't reported — report the serverless API's+ // the dedicated worker hasn't reported: report the serverless API's// own liveness rather than a false "stopped".running: beat ? fresh : true,mode: beat?.mode || 'serverless',@@ -159,7 +159,7 @@ async function probeX402() {const result = {};// Check if PAY_TO addresses are configured. A network counts as wired only- // when EVERY field its 402 accept needs is present — the same gate+ // when EVERY field its 402 accept needs is present: the same gate// buildRequirements() applies before advertising it. Solana additionally// requires a fee payer (no default): without it the accept is dropped, so a// Solana-only paid endpoint (e.g. /api/x402/club-cover) fails closed with a@@ -182,7 +182,7 @@ async function probeX402() {// The 402 challenge advertises a Solana fee payer PUBKEY (X402_FEE_PAYER_SOLANA),// but a sponsor-mode settle can only complete if the matching SECRET is loaded- // to co-sign — a config where the pubkey is set and the secret is not passes+ // to co-sign: a config where the pubkey is set and the secret is not passes// every check above yet 502s on every settle (observed: club-cover's last// on-chain settles failed with `sponsor_key_unconfigured`). Probe the co-sign// key so that false-green stops reading as healthy. No key material is exposed:@@ -229,7 +229,7 @@ async function probeX402() {result.facilitator = 'not_configured';}- // Provider Hub (zauthx402) x402 telemetry — report whether the SDK+ // Provider Hub (zauthx402) x402 telemetry: report whether the SDK// initialized so the integration is observable in prod. Booleans only:// no key material is surfaced on this public, unauthenticated endpoint.try {@@ -249,7 +249,7 @@ async function probeX402() {// Self-facilitator verify/settle outcomes (last 24h), grouped by reason// class. A paying buyer whose wallet mutates the prepared transaction gets a- // deterministic verify 402 with everything else on this endpoint green —+ // deterministic verify 402 with everything else on this endpoint green,// without this block that failure mode is invisible outside the raw// facilitator log. Only the reason prefix (before ':') is exposed: suffixes can// carry wallet addresses, the prefix is a fixed validator code.@@ -295,12 +295,12 @@ async function probeX402() {result.siwx = 'unavailable';}- // Ring spend status — surface whether the autonomous closed-loop spend path is+ // Ring spend status: surface whether the autonomous closed-loop spend path is// live as a dashboard field, so a fail-closed guard (or a deliberate pause) is// visible here instead of only as recurring cron error logs. checkRingInvariants// is a pure env read (no I/O); no key material is exposed, only flag names.// `paused` reflects the existing kill switch (X402_AUTONOMOUS_ENABLED=false),- // which the loop honors before the guard check — a deliberate pause reads as+ // which the loop honors before the guard check, so a deliberate pause reads as// paused here, not as a violation.try {const { checkRingInvariants } = await import('./_lib/x402/ring-allowlist.js');@@ -352,7 +352,7 @@ export default wrap(async (req, res) => {subsystems,// Productized speech package (api/v1/ai/tts, api/v1/ai/asr). Honest env-gate// status so a missing NVIDIA key shows here instead of only surfacing as a- // 503 on the endpoint. Sync env reads — no upstream probe, no key material.+ // 503 on the endpoint. Sync env reads, no upstream probe, no key material.speech: {tts: { configured: nvidiaTtsConfigured(), route: '/api/v1/ai/tts', requires: ['NVIDIA_API_KEY'] },asr: {diff --git a/api/home-stats.js b/api/home-stats.jsindex 18874aac6..ad58b9830 100644--- a/api/home-stats.js+++ b/api/home-stats.js@@ -6,7 +6,7 @@* Returns real counts pulled from Neon. Used by the SaaS prologue strip on* the home page to render live "trusted by" numbers. No auth, edge-cached for* 60s at the CDN. If the DB is unreachable the response is { available: false }- * and the home page hides the metrics strip — we never serve fabricated numbers.+ * and the home page hides the metrics strip: we never serve fabricated numbers.*/import { sql } from './_lib/db.js';diff --git a/api/ibm-mcp.js b/api/ibm-mcp.jsindex 42af0b727..2b54b21c1 100644--- a/api/ibm-mcp.js+++ b/api/ibm-mcp.js@@ -1,14 +1,14 @@-// IBM Granite x402 MCP server — Streamable HTTP transport (MCP 2025-06-18,-// JSON-RPC 2.0). POST /api/ibm-mcp — tool calls GET — SSE DELETE — terminate.+// IBM Granite x402 MCP server: Streamable HTTP transport (MCP 2025-06-18,+// JSON-RPC 2.0). POST /api/ibm-mcp: tool calls GET: SSE DELETE: terminate.//// The hosted (remote) transport for the @three-ws/ibm-x402-mcp tool suite: five// IBM Granite tools (chat, code, embed, analyze, forecast) gated by per-call// x402 payments, plus a free ibm_granite_getting_started tool served without any// payment or token so any client can discover the server first. End users pay-// USDC on Base or Solana per paid call — no IBM Cloud account required; the+// USDC on Base or Solana per paid call, no IBM Cloud account required; the// operator funds watsonx.ai via WATSONX_* env vars.// Authenticated three.ws principals (Bearer / OAuth) call without per-call-// payment — the operator-funded path for watsonx Orchestrate connections.+// payment: the operator-funded path for watsonx Orchestrate connections.// Registered with the MCP Registry as io.github.nirholas/ibm-x402-mcp-remote// (see server-ibm.json).import { cors, readJson, wrap } from './_lib/http.js';@@ -43,7 +43,7 @@ export default wrap(async (req, res) => {// tool actually being called. Malformed JSON throws (status 400) → wrap().const body = await readJson(req, 2_000_000);- // x402 price for the WHOLE request — the sum of every priced Granite+ // x402 price for the WHOLE request: the sum of every priced Granite// tools/call in the (possibly batched) body. Charging the per-request total// (not just a lone call) stops a multi-call batch from running several billed// inferences for one tool's price. A discovery-only batch yields null.@@ -53,8 +53,8 @@ export default wrap(async (req, res) => {});// A batch composed solely of the free public ibm_granite_getting_started tool- // is served without an x402 payment or OAuth token so any client — including- // non-x402 hosts like watsonx Orchestrate — can discover the server first.+ // is served without an x402 payment or OAuth token so any client, including+ // non-x402 hosts like watsonx Orchestrate, can discover the server first.// Discovery-only batches (initialize / tools/list / ping) from plain x402// agents and crawlers are also free; MCP protocol clients still get the// 401 that starts their OAuth flow.@@ -79,7 +79,7 @@ export default wrap(async (req, res) => {});const batch = Array.isArray(body) ? body : [body];- // Per-request batch cap — each message can trigger an IBM inference call, so+ // Per-request batch cap: each message can trigger an IBM inference call, so// an unbounded batch multiplies billable work against the user's budget.if (batch.length > 16) return sendJsonRpcError(res, null, -32600, 'batch too large (max 16)');@@ -87,7 +87,7 @@ export default wrap(async (req, res) => {// signed payment proof across dispatch+settle so a captured/retried X-PAYMENT// can't re-run the priced (billable IBM inference) tools before the first// settle lands. Released in the finally; the consumed on-chain nonce blocks any- // replay thereafter. Fails open — see reservePaymentProof.+ // replay thereafter. Fails open, see reservePaymentProof.let releaseProof = async () => {};if (x402Ctx) {const guard = await reservePaymentProof(@@ -110,7 +110,7 @@ export default wrap(async (req, res) => {if (r !== null) responses.push(r);}- // Settle the x402 payment AFTER the work succeeded — atomic from the caller's+ // Settle the x402 payment AFTER the work succeeded, atomic from the caller's// perspective: if settle fails, the payer's signed payload is not broadcast// and they get an error instead of having paid for nothing. Only settle when// at least one call produced a result; a wholesale failure (every call erroreddiff --git a/api/img.js b/api/img.jsindex 488f3726b..42b6a50c8 100644--- a/api/img.js+++ b/api/img.js@@ -5,25 +5,25 @@// IPFS gateways and metadata hosts these images live on (ipfs.io, arweave,// per-launch CDNs) frequently answer browser requests with no// `Access-Control-Allow-Origin` header, or get blocked by the browser's Opaque-// Response Blocking (ORB) — so the texture fails and the console fills with CORS+// Response Blocking (ORB), so the texture fails and the console fills with CORS// / ERR_BLOCKED_BY_ORB errors, one per token.//// Routing the image through this same-origin endpoint removes the cross-origin// problem entirely: the browser only ever talks to three.ws. Server-side we:// 1. Fetch the upstream image through the SSRF-hardened fetcher (scheme// allowlist, our-side DNS + private-IP blocklist, connection pinning,-// per-redirect re-validation, byte cap, timeout) — see api/_lib/ssrf.js.+// per-redirect re-validation, byte cap, timeout). See api/_lib/ssrf.js.// 2. If the source is an IPFS URL that fails, retry across alternate public// gateways so one slow gateway never blanks the art.// 3. If `?url=` turns out to address a token *metadata* document rather than an-// image (roughly half of pump.fun art is stored this way — feeds keep both+// image (roughly half of pump.fun art is stored this way: feeds keep both// kinds in a single `image_uri` column, indistinguishable without fetching),// follow its `.image` field exactly one hop to the real artwork. Callers that// already know they hold a metadata URI can say so explicitly with `?meta=`.// 4. On total failure, serve a deterministic, on-brand SVG placeholder inline// (200, permissive CORS) so the loader ALWAYS receives a valid image and-// never logs an error. The placeholder is generated here — same-origin, no-// external dependency that could itself be down — and is unique per seed:+// never logs an error. The placeholder is generated here, same-origin, no+// external dependency that could itself be down, and is unique per seed:// an abstract gradient "gem" that reads as token art rather than a generic// "broken image" tile.//@@ -39,19 +39,19 @@ const MAX_BYTES = 8 * 1024 * 1024; // 8 MB: generous for token art, bounded for// Per-gateway attempt cap. Each candidate fetch (DNS + connect + body) is bounded// by this via the SSRF fetcher's own AbortController. Because the candidates are// raced CONCURRENTLY (below), the whole resolution finishes in roughly one-// attempt's time — not the sum — so one stalled gateway never stacks toward the+// attempt's time, not the sum, so one stalled gateway never stacks toward the// function's 30s kill, which is what produced the mass-504 storm.const TIMEOUT_MS = 9_000;// Token launch metadata (pump.fun et al.) is a small JSON doc whose `image`// field is the real art. Resolving it server-side lets the browser load token// images same-origin without the per-host CORS failures that a client-side-// `fetch(metadataUri)` hits. Kept short — the JSON is tiny.+// `fetch(metadataUri)` hits. Kept short: the JSON is tiny.const META_TIMEOUT_MS = 5_000;-// Overall budget for ALL upstream work combined — metadata resolution AND every+// Overall budget for ALL upstream work combined: metadata resolution AND every// gateway attempt. The function's Vercel maxDuration is 30s; trying 4 IPFS// gateways at 10s each can reach 40s, and a slow metadata fetch (5s) layered on// top of a 24s gateway budget reaches 29s + teardown and gets the invocation-// killed BEFORE the placeholder redirect below ever runs — defeating the+// killed BEFORE the placeholder redirect below ever runs, defeating the// "always hand back a valid 200" contract. A single deadline anchored at handler// start, capped well under 30s, keeps meta + gateways + the placeholder response// inside the hard kill no matter how the time is split between the two phases.@@ -62,7 +62,7 @@ const RESPONSE_HEADROOM_MS = 1_000;// Public IPFS gateways. ipfs.io is the canonical resolver the rest of the platform// pins to (api/_lib/onchain.js) but is also the one most likely to ORB-block or-// stall, so we fan out across healthy mirrors and race them — the first to return a+// stall, so we fan out across healthy mirrors and race them: the first to return a// valid image wins. cloudflare-ipfs.com is intentionally absent: Cloudflare sunset// its public IPFS gateway, so every request to it is a guaranteed failure that only// wastes a connection.@@ -92,20 +92,20 @@ function candidates(rawUrl) {// Race every candidate gateway concurrently and resolve with the FIRST one that// returns a usable payload. Resolves to null when all candidates fail, OR when the-// shared `budgetMs` elapses — whichever comes first — so a stalled gateway can+// shared `budgetMs` elapses, whichever comes first, so a stalled gateway can// never pin the invocation toward the 30s wall. The losing fetches are each// independently time-boxed by `perAttemptMs` (the SSRF fetcher aborts them), so// they cannot outlive the request in any meaningful way. This concurrency is the// fix for the sequential ipfs.io stall storm: total wall time is now ~one attempt,// not the sum of all four.//-// A "usable payload" is an image, OR — when `acceptJson` is set — a JSON document.+// A "usable payload" is an image, OR, when `acceptJson` is set, a JSON document.// Roughly half the token art on pump.fun surfaces is addressed by its *metadata*// URI rather than its image URI: the CID resolves to a small JSON doc whose// `image` field holds the real art. Callers hand us that URI in `?url=` because// upstream feeds store both kinds in one `image_uri` column and the two are-// indistinguishable without fetching. Detecting the JSON here — instead of-// discarding it as "valid response but not an image" — lets one `?url=` call+// indistinguishable without fetching. Detecting the JSON here, instead of+// discarding it as "valid response but not an image", lets one `?url=` call// resolve either form. Returns { kind: 'image' | 'json', ... }.function raceCandidates(urls, perAttemptMs, budgetMs, acceptJson) {if (!urls.length || budgetMs < 250) return Promise.resolve(null);@@ -125,19 +125,19 @@ function raceCandidates(urls, perAttemptMs, budgetMs, acceptJson) {const ct = result?.contentType || '';if (ct.startsWith('image/')) return finish({ kind: 'image', ...result });if (acceptJson && ct.includes('json')) {- // Metadata doc. Parse here — we already hold the bytes, so following+ // Metadata doc. Parse here: we already hold the bytes, so following// it costs no extra gateway round-trip for the document itself.try {const data = JSON.parse(new TextDecoder().decode(result.bytes));return finish({ kind: 'json', data });} catch {- /* malformed — fall through and let the other candidates settle */+ /* malformed: fall through and let the other candidates settle */}}if (--pending === 0) finish(null); // valid response, but nothing we can use}).catch(() => {- // SSRF refusal, timeout, gateway 5xx — this candidate is out. Only+ // SSRF refusal, timeout, gateway 5xx: this candidate is out. Only// give up once every candidate has settled.if (--pending === 0) finish(null);});@@ -149,7 +149,7 @@ function raceCandidates(urls, perAttemptMs, budgetMs, acceptJson) {// the same image, so a given token's fallback is stable across loads and the// edge cache stays warm. Derives a two-tone palette + accent from a hash of the// seed and composes a soft gradient backdrop, a faceted "gem" glyph, and a-// monogram — on-brand for three.ws and clearly intentional, not a 404 tile.+// monogram, on-brand for three.ws and clearly intentional, not a 404 tile.function hashSeed(str) {let h = 2166136261 >>> 0; // FNV-1afor (let i = 0; i < str.length; i++) {@@ -210,8 +210,8 @@ function placeholderSvg(seed) {}// Pull the artwork URL out of a token metadata document. The metadata is-// creator-controlled, so we accept only a non-empty string and reject data: URLs-// — we never serve attacker-supplied inline content from our own origin. The URL+// creator-controlled, so we accept only a non-empty string and reject data: URLs.+// We never serve attacker-supplied inline content from our own origin. The URL// itself is still validated by the SSRF fetcher before anything is requested.// Returns null on anything unusable, so callers fall through to the placeholder.function imageFromMetaDoc(data) {@@ -256,7 +256,7 @@ export default wrap(async function handler(req, res) {return error(res, 400, 'missing_url', 'one of url, meta, or seed is required');}- // data: URIs are not proxyable targets — redirecting to attacker-supplied+ // data: URIs are not proxyable targets: redirecting to attacker-supplied// data: content is an open-redirect/content-injection vector. Reject.if (directUrl && /^data:/i.test(directUrl.trim())) {return error(@@ -267,14 +267,14 @@ export default wrap(async function handler(req, res) {);}- // One hard deadline for ALL upstream work — metadata resolution and every+ // One hard deadline for ALL upstream work: metadata resolution and every// gateway attempt draw from the same budget so their combined spend can never// exceed it and trip the function's 30s kill before we serve the placeholder.const deadline = Date.now() + TOTAL_BUDGET_MS - RESPONSE_HEADROOM_MS;// Resolve the artwork URL: an explicit ?url wins; otherwise read it from the// token metadata document server-side. A null result simply falls through to- // the placeholder below — the loader always receives a valid image. The meta+ // the placeholder below: the loader always receives a valid image. The meta// fetch is capped at whatever is left of the shared budget (never more than// META_TIMEOUT_MS) so a hung metadata host can't consume the gateway budget.let target = directUrl;@@ -285,7 +285,7 @@ export default wrap(async function handler(req, res) {// Race all candidate gateways concurrently inside whatever is left of the shared// budget. The first valid image wins; if every gateway fails (or the budget- // runs out) we fall through to the placeholder below — always within the 30s wall.+ // runs out) we fall through to the placeholder below, always within the 30s wall.//// A `?url=` that turns out to address a metadata document (not art) is followed// exactly one hop to the image it names. `acceptJson` is off on that second racediff --git a/api/swarms/[id].js b/api/swarms/[id].jsindex ae14e6412..1555ffd9c 100644--- a/api/swarms/[id].js+++ b/api/swarms/[id].js@@ -1,9 +1,10 @@-// /api/swarms/:id — full dashboard state for one swarm-// /api/swarms/:id/stream — SSE: live consensus votes, payouts, treasury ticks+// /api/swarms/:id full dashboard state for one swarm+// /api/swarms/:id/stream SSE: live consensus votes, payouts, treasury ticks//-// Routed here by vercel.json (`/api/swarms/([^/]+)(/.*)? → /api/swarms/[id]`); the-// handler parses the path to split state vs. stream. GET only — mutations live on-// POST /api/swarms.+// Routed here by two vercel.json rules, `/api/swarms/([^/]+)/stream` and+// `/api/swarms/([^/]+)`, both pointing at `/api/swarms/[id]`. The server keeps the+// ORIGINAL pathname on req.url behind a dest rewrite, so the handler re-reads the+// path to split state vs. stream. GET only; mutations live on POST /api/swarms.import { cors, method, json, error, wrap } from '../_lib/http.js';import { resolveAccount } from '../_lib/account-auth.js';@@ -19,16 +20,21 @@ export default wrap(async (req, res) => {const id = parts[2];const sub = parts[3] || null;- if (!isUuid(id)) return error(res, 404, 'not_found', 'swarm not found');-- if (sub === 'stream') {- if (!method(req, res, ['GET'])) return;- return streamSwarm(req, res, id);- }-+ // CORS before anything can answer, so the stream, the 404 for an unknown id and+ // the preflight all carry the same headers as the state read. The stream branch+ // used to skip cors() entirely: it returned a bare 200 text/event-stream with no+ // access-control-allow-origin, so a cross-origin EventSource could open the+ // connection and never read a byte of it, and its OPTIONS preflight 405'd.if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ // Capture the verb before method() rewrites HEAD to GET (see below).+ const isHead = req.method === 'HEAD';if (!method(req, res, ['GET'])) return;+ if (!isUuid(id)) return error(res, 404, 'not_found', 'swarm not found');+ if (sub !== null && sub !== 'stream') return error(res, 404, 'not_found', 'swarm not found');++ if (sub === 'stream') return streamSwarm(req, res, id, { headOnly: isHead });+const auth = await resolveAccount(req, res).catch(() => null);const state = await getSwarmState(id, { viewerUserId: auth?.userId || null });if (!state) return error(res, 404, 'not_found', 'swarm not found');@@ -39,7 +45,7 @@ const HEARTBEAT_MS = 15_000;const POLL_MS = 2_500;const MAX_DURATION_MS = 280_000; // end before the platform function timeout; client reconnects-async function streamSwarm(req, res, id) {+async function streamSwarm(req, res, id, { headOnly = false } = {}) {const swarm = await getSwarm(id);if (!swarm) return error(res, 404, 'not_found', 'swarm not found');@@ -48,6 +54,16 @@ async function streamSwarm(req, res, id) {res.setHeader('X-Accel-Buffering', 'no');res.setHeader('Connection', 'keep-alive');+ // A HEAD probe gets the headers and nothing else. method() normalizes HEAD to+ // GET so the dispatch above works, which meant a HEAD opened the full poll loop+ // and held the connection (and a Cloud Run concurrency slot) for the whole+ // MAX_DURATION_MS, for a request Node strips the body from anyway. Any uptime+ // monitor or crawler pointed at this URL pinned a slot for ~5 minutes each.+ if (headOnly) {+ res.statusCode = 200;+ return res.end();+ }+const send = (event, data) => {try { res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); } catch { /* socket closed */ }};diff --git a/docs/swarms.md b/docs/swarms.mdindex 81f678306..56f17afbc 100644--- a/docs/swarms.md+++ b/docs/swarms.md@@ -116,6 +116,12 @@ curl -s https://three.ws/api/swarms/<SWARM_ID> # full dashboard statecurl -sN https://three.ws/api/swarms/<SWARM_ID>/stream # SSE: votes, payouts, treasury ticks```+Both are public reads and both answer CORS preflights, so an `EventSource` on the+stream works from an allowed cross-origin page, not only from three.ws itself. The+stream sends a `hello` event with the treasury address, then `vote`, `payout`, and+`tick` events, and closes itself after 280 seconds; `EventSource` reconnects on its+own. A `HEAD` on either URL returns the headers without opening the poll loop.+### MutationsAll mutations are `POST /api/swarms` with an `action` field.@@ -140,7 +146,7 @@ curl -s -X POST https://three.ws/api/swarms \-d '{"action":"join","swarm_id":"<SWARM_UUID>","agent_id":"<AGENT_UUID>"}'```-**`contribute` and `exit` move real SOL.** Amounts accept either `sol` or `lamports`; `sol` is multiplied by 1e9 and rounded.+**`contribute` and `exit` move real SOL.** Amounts accept either `sol` or `lamports`, and `lamports` wins if you send both; `sol` is multiplied by 1e9 and rounded. Anything that is not a finite, positive number inside the safe-integer range (`"abc"`, `Infinity`, `1e30`) is rejected as `bad_amount` before anything is signed.```bash# Contribute 0.05 SOL. This is a real on-chain transfer.@@ -165,7 +171,7 @@ Every failure returns `{ error, error_description }` with a specific code rather| Status | Code | Meaning ||---|---|---|| 400 | `bad_agent`, `bad_swarm` | The id is missing or not a UUID |-| 400 | `bad_amount` | `contribute` without a positive `sol` or `lamports` |+| 400 | `bad_amount` | `contribute` without a positive `sol` or `lamports`, or with one that is not a finite number in range || 400 | `bad_action` | Unrecognized `action` || 400 | `bad_name` | `create` with an empty name or one over 80 characters || 400 | `too_small` | Contribution under the 0.005 SOL floor |@@ -175,6 +181,7 @@ Every failure returns `{ error, error_description }` with a specific code rather| 403 | `forbidden` | Acting for an agent you do not own, or a creator-only action (`pause`, `resume`) from a member || 403 | `invite_only` | `join` by anyone but the creator on a swarm with `join_open: false` || 403 | `below_threshold` | `kill` from a member holding under `kill_threshold_bps` |+| 415 | `bad_request` | A mutation sent without `Content-Type: application/json` || 429 | `rate_limited` | Over 30 mutations per minute for this user || 404 | `not_found` | No such swarm || 404 | `agent_not_found` | No such agent |diff --git a/prompts/swarm-100/api-rider-01.md b/prompts/swarm-100/api-rider-01.mddeleted file mode 100644index bdce0c804..000000000--- a/prompts/swarm-100/api-rider-01.md+++ /dev/null@@ -1,104 +0,0 @@-# API audit: api/rider batch 01 (4 files)--How to run: paste this file's repo path into a fresh Claude Code chat in this-repository and say "run this work order". This file is fully self-contained:-it depends on no other prompt file anywhere. If neighboring files in-prompts/swarm-100/ are gone, that work is done; if present, ignore them.-Every claim below rots; step 0 re-measures, and what you measure wins.--## Operating clause (binding)--- Read CLAUDE.md first. Its rules override everything, including this file.-- Finish 100% in this session. Never end the turn with a question, an option- list, or an unexecuted plan. A judgment call goes in one line of the final- report; it never becomes a question that halts work.-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real- funds or any irreversible on-chain write, git push or a production deploy,- committing content that references a crypto project other than $THREE, and- destroying unrecoverable data.-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no- commented-out code. Real APIs and real integrations only.-- The em-dash and en-dash characters are banned in everything you write.-- Concurrent agents share this worktree: stage explicit paths only (never a- bare add-everything), and commit finished work promptly.-- Before committing, run: npm run check:rules -- --paths <files you touched>.- It must exit 0.--## Step 0: re-derive the current state--1. Confirm each file below still exists; deleted ones are done, skip them.-2. For each, decide routability: grep its path in vercel.json and read how- server/index.mjs maps filesystem handlers. Routed files get an endpoint- audit; internal modules get a code and test audit.-3. Start a local server for endpoint checks: node server/index.mjs with .env- loaded, on a free PORT if 3000 is busy.--## Task: audit these api files, then fix everything found--Files in this batch:--- api/rider/check.js-- api/rider/firebase.js-- api/rider/info.js-- api/rider/webhook.js--For every routed handler:--1. Exercise it with curl against the local server: the success path returns- real data with the correct status; malformed input returns a 4xx JSON- error, never a stack trace or an HTML error page; auth is enforced where- the code intends it; CORS matches neighboring handlers.-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed- responses, no unfinished markers. Errors are handled at the boundary and- internal code trusts itself.-3. Do not spend funds or sign anything on-chain while probing. Payment and- trading handlers get their validation and error paths exercised, never a- live settlement.--For every internal (non-routed) module:--4. Something must import it; if nothing does, delete it as dead code (verify- with a repo-wide grep first).-5. Its main path and one failure path must be covered in tests/; add the- missing test if not.--## Definition of done--- [ ] Every listed file has recorded evidence: a curl transcript for routed- handlers, a passing test or a deletion for internal modules.-- [ ] Zero hard-rule violations remain in these files.-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>- exits 0.--## Never blocked--| Blocker | Resolution (act, do not ask) |-|---|---|-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |-| Playwright browser missing | npx playwright install chromium |-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |--## Close out (required)--1. Verify every Definition of done line with the actual command output in- front of you. Never claim a line you did not verify.-2. Commit with explicit paths and a subject that describes the diff (house- style: type(scope): what changed and why a reader cares).-3. Delete this prompt file in that same commit:-- git rm prompts/swarm-100/api-rider-01.md-- The shrinking directory is this campaign's only progress ledger; there is- no progress log to update.-4. Final report: what step 0 measured, what changed (file list), evidence per- Definition of done line, and any one-line judgment calls. No trailing- questions, no unexecuted plans.--If a line genuinely cannot pass inside this session (an external party must-respond, or an owner-gated action is the final step), finish everything else,-leave this file in place, and state exactly which line remains and who owns-it. Never delete this file on a partial.diff --git a/prompts/swarm-100/api-swarms-01.md b/prompts/swarm-100/api-swarms-01.mddeleted file mode 100644index 6129c5f4b..000000000--- a/prompts/swarm-100/api-swarms-01.md+++ /dev/null@@ -1,102 +0,0 @@-# API audit: api/swarms batch 01 (2 files)--How to run: paste this file's repo path into a fresh Claude Code chat in this-repository and say "run this work order". This file is fully self-contained:-it depends on no other prompt file anywhere. If neighboring files in-prompts/swarm-100/ are gone, that work is done; if present, ignore them.-Every claim below rots; step 0 re-measures, and what you measure wins.--## Operating clause (binding)--- Read CLAUDE.md first. Its rules override everything, including this file.-- Finish 100% in this session. Never end the turn with a question, an option- list, or an unexecuted plan. A judgment call goes in one line of the final- report; it never becomes a question that halts work.-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real- funds or any irreversible on-chain write, git push or a production deploy,- committing content that references a crypto project other than $THREE, and- destroying unrecoverable data.-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no- commented-out code. Real APIs and real integrations only.-- The em-dash and en-dash characters are banned in everything you write.-- Concurrent agents share this worktree: stage explicit paths only (never a- bare add-everything), and commit finished work promptly.-- Before committing, run: npm run check:rules -- --paths <files you touched>.- It must exit 0.--## Step 0: re-derive the current state--1. Confirm each file below still exists; deleted ones are done, skip them.-2. For each, decide routability: grep its path in vercel.json and read how- server/index.mjs maps filesystem handlers. Routed files get an endpoint- audit; internal modules get a code and test audit.-3. Start a local server for endpoint checks: node server/index.mjs with .env- loaded, on a free PORT if 3000 is busy.--## Task: audit these api files, then fix everything found--Files in this batch:--- api/swarms/[id].js-- api/swarms/index.js--For every routed handler:--1. Exercise it with curl against the local server: the success path returns- real data with the correct status; malformed input returns a 4xx JSON- error, never a stack trace or an HTML error page; auth is enforced where- the code intends it; CORS matches neighboring handlers.-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed- responses, no unfinished markers. Errors are handled at the boundary and- internal code trusts itself.-3. Do not spend funds or sign anything on-chain while probing. Payment and- trading handlers get their validation and error paths exercised, never a- live settlement.--For every internal (non-routed) module:--4. Something must import it; if nothing does, delete it as dead code (verify- with a repo-wide grep first).-5. Its main path and one failure path must be covered in tests/; add the- missing test if not.--## Definition of done--- [ ] Every listed file has recorded evidence: a curl transcript for routed- handlers, a passing test or a deletion for internal modules.-- [ ] Zero hard-rule violations remain in these files.-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>- exits 0.--## Never blocked--| Blocker | Resolution (act, do not ask) |-|---|---|-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |-| Playwright browser missing | npx playwright install chromium |-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |--## Close out (required)--1. Verify every Definition of done line with the actual command output in- front of you. Never claim a line you did not verify.-2. Commit with explicit paths and a subject that describes the diff (house- style: type(scope): what changed and why a reader cares).-3. Delete this prompt file in that same commit:-- git rm prompts/swarm-100/api-swarms-01.md-- The shrinking directory is this campaign's only progress ledger; there is- no progress log to update.-4. Final report: what step 0 measured, what changed (file list), evidence per- Definition of done line, and any one-line judgment calls. No trailing- questions, no unexecuted plans.--If a line genuinely cannot pass inside this session (an external party must-respond, or an owner-gated action is the final step), finish everything else,-leave this file in place, and state exactly which line remains and who owns-it. Never delete this file on a partial.diff --git a/tests/swarms.test.js b/tests/swarms.test.jsindex 70757fc9c..6d43392f8 100644--- a/tests/swarms.test.js+++ b/tests/swarms.test.js@@ -6,7 +6,7 @@*/import { describe, it, expect } from 'vitest';-import { computeConsensus, normalizeSwarmPolicy } from '../api/_lib/swarms.js';+import { computeConsensus, normalizeSwarmPolicy, parseContributionLamports, SwarmError } from '../api/_lib/swarms.js';describe('computeConsensus', () => {const members = [@@ -90,3 +90,60 @@ describe('normalizeSwarmPolicy', () => {expect(normalizeSwarmPolicy({ exit_policy: 'nonsense' }).exit_policy).toBe('settle_at_mark');});});++describe('parseContributionLamports', () => {+ // The amount a POST /api/swarms contribute moves on-chain. Anything this lets+ // through is signed for, and anything it throws must be a 400 the caller can+ // read, never a RangeError escaping as a 500.+ const reject = (body) => {+ let caught = null;+ try { parseContributionLamports(body); } catch (e) { caught = e; }+ expect(caught).toBeInstanceOf(SwarmError);+ expect(caught.status).toBe(400);+ expect(caught.code).toBe('bad_amount');+ return caught;+ };++ it('reads an explicit lamport count', () => {+ expect(parseContributionLamports({ lamports: 25_000_000 })).toBe(25_000_000n);+ expect(parseContributionLamports({ lamports: '25000000' })).toBe(25_000_000n);+ });++ it('converts SOL to lamports', () => {+ expect(parseContributionLamports({ sol: 0.025 })).toBe(25_000_000n);+ expect(parseContributionLamports({ sol: '1.5' })).toBe(1_500_000_000n);+ });++ it('prefers lamports when a body carries both', () => {+ expect(parseContributionLamports({ lamports: 7_000_000, sol: 99 })).toBe(7_000_000n);+ });++ it('rejects a non-numeric amount instead of throwing a RangeError', () => {+ // BigInt(NaN) throws RangeError, which used to escape wrap() as a 500+ // internal_error (plus a Sentry capture and an ops alert) on a caller typo.+ reject({ lamports: 'abc' });+ reject({ sol: 'abc' });+ reject({ lamports: {} });+ });++ it('rejects a non-finite amount', () => {+ reject({ sol: Infinity });+ reject({ lamports: -Infinity });+ });++ it('rejects an amount past the safe-integer range', () => {+ // 1e30 SOL is 1e39 lamports, and a double can no longer name that exact+ // integer, so the amount signed for would not be the amount requested.+ reject({ sol: 1e30 });+ reject({ lamports: Number.MAX_SAFE_INTEGER + 100 });+ });++ it('rejects zero, negative, and missing amounts', () => {+ reject({ lamports: 0 });+ reject({ sol: 0 });+ reject({ lamports: -5_000_000 });+ reject({});+ reject({ lamports: null, sol: null });+ reject(undefined);+ });+});