Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(api): introduce new text-to-3D endpoint and pipeline stages

nich65075a99d91e
diff --git a/api/_lib/pipeline-stage.js b/api/_lib/pipeline-stage.js
new file mode 100644
index 000000000..f430f58b5
--- /dev/null
+++ b/api/_lib/pipeline-stage.js
@@ -0,0 +1,306 @@
+// Shared execution rail for the paid 3D-pipeline x402 stages.
+//
+// The free pipeline routes (api/forge-remesh.js, forge-gameready.js,
+// forge-stylize.js, forge-rembg.js, and the rig lane) are asynchronous: POST
+// submits a job, the client polls a GET for the result. Their paid x402 twins
+// (api/x402/pipeline-*.js) are SYNCHRONOUS: one payment buys one finished
+// asset, so the handler submits the same GCP worker job, polls it to completion
+// inside the request window, validates the output bytes, persists a durable
+// first-party copy, and returns its URL. This module holds the machinery every
+// paid stage shares so each route file only declares its slug, price, schema,
+// and the worker mode + params it drives.
+//
+// The buyer-never-charged guarantee (00-CONTEXT rule 4): every failure path here
+// THROWS a StageError before the paidEndpoint rail settles. An unconfigured
+// worker, a bad input URL, a non-GLB payload, a worker failure, a poll timeout,
+// or a corrupt output all surface as a thrown status/code — settlement never
+// runs, so the buyer keeps their USDC and can retry. Nothing is caught-and-
+// continued into a settled response.
+
+import { createRegenProvider } from '../_providers/gcp.js';
+import { validatePublicUrl, resolvePublicHost, SsrfError } from './ssrf.js';
+import { putObject, publicUrl } from './r2.js';
+
+// Poll cadence + budget. The x402 payment authorization carries
+// maxTimeoutSeconds:60, so completion + settlement must land inside that window;
+// 45s of polling leaves headroom for the settle round-trip. Both are
+// env-overridable for slower deployments.
+const POLL_INTERVAL_MS = Number(process.env.X402_PIPELINE_POLL_INTERVAL_MS) || 2_000;
+const POLL_BUDGET_MS = Number(process.env.X402_PIPELINE_POLL_BUDGET_MS) || 45_000;
+const OUTPUT_FETCH_TIMEOUT_MS = 60_000;
+const MAX_OUTPUT_BYTES = 64 * 1024 * 1024; // matches forge-store MAX_GLB_BYTES
+
+export class StageError extends Error {
+ constructor(message, { status = 500, code = 'stage_error' } = {}) {
+ super(message);
+ this.name = 'StageError';
+ this.status = status;
+ this.code = code;
+ }
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+// Read + parse the JSON request body. The paidEndpoint rail does not consume the
+// stream (it only inspects headers), so the paid handler reads it here. A
+// malformed or oversized body throws before any worker call.
+export async function readJsonBody(req, maxBytes = 8_192) {
+ const chunks = [];
+ let total = 0;
+ for await (const c of req) {
+ total += c.length;
+ if (total > maxBytes) {
+ throw new StageError('request body too large', { status: 413, code: 'body_too_large' });
+ }
+ chunks.push(c);
+ }
+ const raw = Buffer.concat(chunks).toString('utf8').trim();
+ if (!raw) return {};
+ try {
+ return JSON.parse(raw);
+ } catch {
+ throw new StageError('request body must be valid JSON', {
+ status: 400,
+ code: 'invalid_json',
+ });
+ }
+}
+
+// ── Input validation ────────────────────────────────────────────────────────
+
+// Validate a caller-supplied asset URL. Scheme + SSRF checks reject a malformed
+// or private-network URL BEFORE any worker touches it. `validatePublicUrl`
+// throws synchronously on a bad scheme (no DNS), so a "not a URL" input is a
+// clean 400 without a network round-trip; the DNS resolution then rejects
+// private/loopback/metadata hosts.
+export async function validateAssetUrl(raw, field = 'glb_url') {
+ const value = typeof raw === 'string' ? raw.trim() : '';
+ if (!value) {
+ throw new StageError(`${field} is required`, { status: 400, code: 'missing_url' });
+ }
+ let url;
+ try {
+ url = validatePublicUrl(value);
+ } catch (err) {
+ const detail = err instanceof SsrfError ? err.message : 'must be a valid https URL';
+ throw new StageError(`${field} rejected: ${detail}`, { status: 400, code: 'invalid_url' });
+ }
+ try {
+ await resolvePublicHost(url.hostname);
+ } catch (err) {
+ const detail = err instanceof SsrfError ? err.message : 'host could not be resolved';
+ throw new StageError(`${field} rejected: ${detail}`, { status: 400, code: 'invalid_url' });
+ }
+ return url.href;
+}
+
+// glTF binary magic — the first four bytes of every .glb are the ASCII "glTF"
+// (0x67 0x6C 0x54 0x46). Pure predicate so tests can assert it on captured bytes
+// with no network.
+export function isGlbMagic(bytes) {
+ if (!bytes || bytes.length < 12) return false;
+ return bytes[0] === 0x67 && bytes[1] === 0x6c && bytes[2] === 0x54 && bytes[3] === 0x46;
+}
+
+// Recognized raster-image magic numbers (PNG, JPEG, WEBP, GIF) — the rembg stage
+// takes an image, not a mesh. Pure predicate for the same reason.
+export function isImageMagic(bytes) {
+ if (!bytes || bytes.length < 12) return false;
+ // PNG: 89 50 4E 47 0D 0A 1A 0A
+ if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) return true;
+ // JPEG: FF D8 FF
+ if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return true;
+ // GIF: "GIF8"
+ if (bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38) return true;
+ // WEBP: "RIFF"...."WEBP"
+ if (
+ bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 &&
+ bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50
+ )
+ return true;
+ return false;
+}
+
+function magicMatches(kind, bytes) {
+ return kind === 'image' ? isImageMagic(bytes) : isGlbMagic(bytes);
+}
+
+// Range-fetch the first bytes of the caller's asset and confirm it is the
+// expected kind (glb | image). A 415 here means the URL resolved to something
+// that isn't the asset the stage processes — thrown before settlement so the
+// buyer is not charged for feeding, say, an HTML page to the remesher.
+export async function sniffRemoteAsset(url, kind = 'glb') {
+ let resp;
+ try {
+ resp = await fetch(url, {
+ redirect: 'follow',
+ headers: { range: 'bytes=0-63', accept: '*/*' },
+ signal: AbortSignal.timeout(15_000),
+ });
+ } catch (err) {
+ throw new StageError(`could not fetch ${kind}: ${err.message}`, {
+ status: 502,
+ code: 'fetch_failed',
+ });
+ }
+ if (!resp.ok && resp.status !== 206) {
+ throw new StageError(`source URL returned ${resp.status}`, {
+ status: resp.status === 404 ? 404 : 502,
+ code: 'fetch_failed',
+ });
+ }
+ const head = new Uint8Array((await resp.arrayBuffer()).slice(0, 64));
+ if (!magicMatches(kind, head)) {
+ throw new StageError(
+ kind === 'image'
+ ? 'source URL is not a supported image (PNG, JPEG, WEBP, or GIF)'
+ : 'source URL is not a binary glTF (.glb) — its bytes lack the "glTF" magic header',
+ { status: 415, code: 'unsupported_media_type' },
+ );
+ }
+ return true;
+}
+
+// ── Worker execution ────────────────────────────────────────────────────────
+
+// Submit one worker job and poll it to completion inside the request window.
+// `provider` is injectable so the fixture-backed tests can drive captured worker
+// response shapes without a live Cloud Run service; production defaults to the
+// real GCP provider. Throws StageError on every non-success outcome so the
+// caller never settles a payment for work that didn't finish.
+export async function runStageJob({
+ mode,
+ sourceUrl,
+ params,
+ provider,
+ pollBudgetMs = POLL_BUDGET_MS,
+ pollIntervalMs = POLL_INTERVAL_MS,
+}) {
+ let regen = provider;
+ if (!regen) {
+ try {
+ regen = createRegenProvider();
+ } catch {
+ throw new StageError(
+ `${mode} worker is not configured on this deployment (set GCP_${mode.toUpperCase()}_URL and GCP_RECONSTRUCTION_KEY)`,
+ { status: 503, code: 'unconfigured' },
+ );
+ }
+ }
+ if (!regen.supportsMode(mode)) {
+ throw new StageError(
+ `${mode} worker is not configured on this deployment (set the worker URL and GCP_RECONSTRUCTION_KEY)`,
+ { status: 503, code: 'unconfigured' },
+ );
+ }
+
+ let job;
+ try {
+ job = await regen.submit({ mode, sourceUrl, params });
+ } catch (err) {
+ throw new StageError(err?.message || `${mode} job could not start`, {
+ status: err?.status || 502,
+ code: err?.code || 'submit_failed',
+ });
+ }
+ const extJobId = job?.extJobId || job?.jobId;
+ if (!extJobId) {
+ throw new StageError(`${mode} worker returned no job id`, {
+ status: 502,
+ code: 'submit_failed',
+ });
+ }
+
+ const deadline = Date.now() + pollBudgetMs;
+ // Poll immediately, then on the interval — fast workers (rembg ~5s) often
+ // finish before the first sleep.
+ // eslint-disable-next-line no-constant-condition
+ while (true) {
+ const result = await regen.status(extJobId);
+ if (result.status === 'done') {
+ return { ...result, extJobId, mode };
+ }
+ if (result.status === 'failed') {
+ throw new StageError(result.error || `${mode} job failed`, {
+ status: 502,
+ code: 'stage_failed',
+ });
+ }
+ if (Date.now() + pollIntervalMs >= deadline) {
+ throw new StageError(
+ `${mode} job did not finish within ${Math.round(pollBudgetMs / 1000)}s — retry; you were not charged`,
+ { status: 504, code: 'stage_timeout' },
+ );
+ }
+ await sleep(pollIntervalMs);
+ }
+}
+
+// ── Output persistence ──────────────────────────────────────────────────────
+
+// Fetch the finished worker artifact, confirm its magic bytes, and mirror it
+// into R2 so the buyer's download URL is first-party and durable. When R2 is
+// unconfigured the validated worker URL is returned as-is (a real, working
+// result — never a faked one). A missing, unreachable, or wrong-kind output
+// throws so the payment is not settled for a broken artifact.
+export async function persistStageOutput({ resultUrl, key, contentType, kind = 'glb' }) {
+ if (!resultUrl) {
+ throw new StageError('worker finished but returned no result URL', {
+ status: 502,
+ code: 'no_output',
+ });
+ }
+ let resp;
+ try {
+ resp = await fetch(resultUrl, { signal: AbortSignal.timeout(OUTPUT_FETCH_TIMEOUT_MS) });
+ } catch (err) {
+ throw new StageError(`could not retrieve worker output: ${err.message}`, {
+ status: 502,
+ code: 'output_fetch_failed',
+ });
+ }
+ if (!resp.ok) {
+ throw new StageError(`worker output URL returned ${resp.status}`, {
+ status: 502,
+ code: 'output_fetch_failed',
+ });
+ }
+ const buf = Buffer.from(await resp.arrayBuffer());
+ if (!buf.length) {
+ throw new StageError('worker output was empty', { status: 502, code: 'empty_output' });
+ }
+ if (buf.length > MAX_OUTPUT_BYTES) {
+ throw new StageError(`worker output is ${buf.length} bytes; max is ${MAX_OUTPUT_BYTES}`, {
+ status: 502,
+ code: 'output_too_large',
+ });
+ }
+ if (!magicMatches(kind, new Uint8Array(buf.subarray(0, 64)))) {
+ throw new StageError(
+ `worker output is not a valid ${kind === 'image' ? 'image' : 'GLB'}`,
+ { status: 502, code: 'invalid_output' },
+ );
+ }
+
+ // Mirror into R2 when configured; otherwise hand back the worker URL. Both are
+ // real, working results — persistence is a durability upgrade, never a gate.
+ try {
+ await putObject({
+ key,
+ body: buf,
+ contentType: contentType || (kind === 'image' ? 'image/png' : 'model/gltf-binary'),
+ metadata: { source: 'x402-pipeline' },
+ });
+ return { url: publicUrl(key), bytes: buf.length, persisted: true };
+ } catch {
+ return { url: resultUrl, bytes: buf.length, persisted: false };
+ }
+}
+
+// Stable, collision-resistant R2 namespace for a stage output, derived from the
+// source URL so re-runs overwrite rather than orphan without leaking the URL.
+export async function stageObjectKey({ stage, sourceUrl, ext }) {
+ const { createHash } = await import('node:crypto');
+ const h = createHash('sha256').update(String(sourceUrl)).digest('hex').slice(0, 16);
+ return `x402-pipeline/${stage}/${h}.${ext}`;
+}
diff --git a/api/_lib/pipeline-store.js b/api/_lib/pipeline-store.js
new file mode 100644
index 000000000..a2b500ff5
--- /dev/null
+++ b/api/_lib/pipeline-store.js
@@ -0,0 +1,136 @@
+// Pipeline job store — durable state for the /api/x402/pipeline asset factory.
+//
+// A pipeline job runs an ordered chain of stages (generate → rig → optimize …)
+// as ONE paid job. Because Vercel functions are stateless and there is no
+// background worker, the chain is a poll-driven state machine: each free poll of
+// GET /api/forge?job=<pipeline-token> advances the current stage and kicks the
+// next one when it finishes (see advancePipeline in ./pipeline.js). That means
+// the job record must survive between two separate serverless invocations, so it
+// lives in the shared cache (Upstash Redis when configured, in-process memory
+// otherwise — the same durability posture forge-scale/forge-cache already use).
+//
+// Fail-soft: without Redis the record is single-instance only. That's honest
+// degradation, not a bug — polling still works within one warm instance, and a
+// multi-instance deployment sets UPSTASH_REDIS_REST_URL to make it durable.
+
+import { randomUUID } from 'node:crypto';
+
+import { cacheGet, cacheGetFresh, cacheSet, acquireLock } from './cache.js';
+
+const KEY_PREFIX = 'pipeline:job:';
+const LOCK_PREFIX = 'pipeline:lock:';
+
+// A pipeline completes in minutes; keep the record for two hours so a slow chain
+// (cold self-host workers) and a client that polls lazily both resolve, then let
+// it self-prune.
+const JOB_TTL_S = 2 * 3600;
+// The advance critical section (poll current stage + submit next) is quick; the
+// lock only needs to outlive one advance so two concurrent polls can't double-
+// submit the same next stage. Auto-expires if a lambda dies mid-advance.
+const LOCK_TTL_S = 90;
+
+function keyFor(id) {
+ return `${KEY_PREFIX}${id}`;
+}
+
+// Terminal states never advance again.
+export function isTerminal(status) {
+ return status === 'done' || status === 'failed';
+}
+
+// Create a fresh pipeline job record. `stages` is the validated, ordered stage
+// id list; every stage starts `queued` with null timings/outputs so a poll can
+// see the whole plan from the first request. Returns the persisted record (with
+// its generated id) or null when the store write itself failed.
+export async function createPipelineJob({ stages, prompt, glbUrl, options, priceUsdc, priceAtomics, network }) {
+ const id = randomUUID();
+ const now = new Date().toISOString();
+ const record = {
+ id,
+ version: 1,
+ status: 'queued',
+ created_at: now,
+ updated_at: now,
+ prompt: prompt ?? null,
+ input_glb_url: glbUrl ?? null,
+ options: options && typeof options === 'object' ? options : {},
+ price_usdc: priceUsdc ?? null,
+ price_atomics: priceAtomics ?? null,
+ network: network ?? null,
+ // The most recent successful stage output — the caller's "current best" GLB,
+ // available even on a later stage's failure (honest partial value).
+ result_glb_url: null,
+ stages: stages.map((sid) => ({
+ id: sid,
+ status: 'queued',
+ started_at: null,
+ finished_at: null,
+ output_url: null,
+ error: null,
+ // Internal poll handle for the running stage (provider + upstream id);
+ // stripped from the public poll response.
+ handle: null,
+ })),
+ };
+ const ok = await savePipelineJob(record);
+ return ok ? record : null;
+}
+
+// Load a job record. Uses the fresh read (bypasses the short read-memo) so a
+// poll immediately after a sibling poll's write doesn't see a stale snapshot.
+export async function getPipelineJob(id) {
+ if (!id) return null;
+ const record = await cacheGetFresh(keyFor(id));
+ return record && typeof record === 'object' ? record : null;
+}
+
+// Non-fresh read for callers that don't need the very latest write (discovery,
+// idempotent reads). Kept distinct so the hot poll path is explicit about using
+// the fresh variant.
+export async function peekPipelineJob(id) {
+ if (!id) return null;
+ const record = await cacheGet(keyFor(id));
+ return record && typeof record === 'object' ? record : null;
+}
+
+export async function savePipelineJob(record) {
+ if (!record?.id) return false;
+ record.updated_at = new Date().toISOString();
+ try {
+ await cacheSet(keyFor(record.id), record, JOB_TTL_S);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+// Best-effort advance lock so two concurrent polls of the same job don't both
+// submit its next stage. Returns true when THIS caller holds the lock (or when
+// no Redis is configured — a single instance needs no cross-instance lock).
+export async function acquireAdvanceLock(id) {
+ return acquireLock(`${LOCK_PREFIX}${id}`, LOCK_TTL_S);
+}
+
+// Strip internal fields (per-stage poll handles) from a record before it goes
+// over the wire. The handle names the upstream provider + task id — internal
+// routing state, never shown to the buyer.
+export function publicView(record) {
+ if (!record) return null;
+ return {
+ job_id: record.id,
+ status: record.status,
+ created_at: record.created_at,
+ updated_at: record.updated_at,
+ prompt: record.prompt,
+ result_glb_url: record.result_glb_url,
+ price_usdc: record.price_usdc,
+ stages: record.stages.map((s) => ({
+ id: s.id,
+ status: s.status,
+ started_at: s.started_at,
+ finished_at: s.finished_at,
+ output_url: s.output_url,
+ error: s.error,
+ })),
+ };
+}
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 106d1bcfb..3fdbc6c4a 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -483,6 +483,12 @@ export const limits = {
// image/text→3D inference against the NIM, so cap per principal to keep that
// GPU egress bounded. Non-critical: a Redis blip must never block the demo.
forgeNim: (key) => getLimiter('forge:nim', { limit: 30, window: '1 h' }).limit(key),
+ // Free text→3D lane (api/v1/ai/text-to-3d) — each generation drives one real
+ // NVIDIA NIM TRELLIS GPU inference, so the free tier is a per-IP daily quota
+ // (10/day). Above it the endpoint returns 429 + a pointer to the paid
+ // /api/x402/forge tiers rather than paywalling silently. Non-critical: a Redis
+ // blip degrades to the per-instance memory limiter, never blocks generation.
+ aiTextTo3d: (ip) => getLimiter('ai:text-to-3d', { limit: 10, window: '24 h' }).limit(ip),
// Diorama composer (api/diorama action:compose) — one free-first LLM
// completion per call that decomposes a sentence into a placed object set.
// Paid upstream egress, so cap per IP and add a global hourly circuit breaker.
diff --git a/api/v1/_catalog.js b/api/v1/_catalog.js
index 04cd14e3c..e2b8db839 100644
--- a/api/v1/_catalog.js
+++ b/api/v1/_catalog.js
@@ -49,6 +49,17 @@ export const API_META = {
};
export const CATALOG = [
+ {
+ id: 'v1.ai.text_to_3d',
+ method: 'POST',
+ path: '/api/v1/ai/text-to-3d',
+ auth: 'public',
+ summary:
+ 'Free text→3D — the only text-to-mesh lane in the agent-payments ecosystem; textured GLB ' +
+ 'from a prompt, no key, no wallet. Draft tier runs on the NVIDIA NIM TRELLIS lane; free ' +
+ 'per-IP quota of 10/day, then 429 pointing at the paid /api/x402/forge tiers.',
+ params: { prompt: 'string — describe a single object or character (3–1000 chars, required)' },
+ },
{
id: 'v1.sentiment',
method: 'POST',
diff --git a/api/v1/ai/text-to-3d.js b/api/v1/ai/text-to-3d.js
new file mode 100644
index 000000000..5abd61bd1
--- /dev/null
+++ b/api/v1/ai/text-to-3d.js
@@ -0,0 +1,135 @@
+// POST /api/v1/ai/text-to-3d — the flagship FREE text→3D endpoint of the
+// three.ws AI package.
+//
+// three.ws runs the only text→mesh lane in the x402 / agent-payments ecosystem.
+// Its draft tier is genuinely free: a prompt goes to the NVIDIA NIM TRELLIS lane
+// (backend `nvidia`, path `image`, draft tier) via the SAME submit pipeline that
+// backs the `forge_free` MCP tool and /forge — no key, no wallet. This route
+// gives that lane a clean, versioned front door instead of leaving it buried
+// under forge job plumbing.
+//
+// Semantics mirror the draft lane exactly (zero duplicated generation logic):
+// • The NIM often finishes inside the submit window → { status:'done', glb_url,
+// viewer_url }.
+// • Otherwise the job is queued → { status:'pending', job:<token>, poll_url }
+// and the caller polls the EXISTING free endpoint GET /api/forge?job=<token>.
+//
+// Free with a per-IP daily quota (10/day — the GPU quota is real). Above the
+// quota we do NOT paywall silently: 429 with X-RateLimit-Reset AND a pointer to
+// the paid /api/x402/forge tiers, which have no daily cap. The free lane is the
+// funnel; the paid forge is the upsell.
+
+import { defineEndpoint, fail } from '../../_lib/gateway.js';
+import { json } from '../../_lib/http.js';
+import { limits } from '../../_lib/rate-limit.js';
+import { backendIsConfigured } from '../../_lib/forge-tiers.js';
+import { startForge, originFromReq, viewerUrl } from '../../_mcp-studio/forge-client.js';
+
+const DAILY_QUOTA = 10;
+const PROMPT_MIN = 3;
+const PROMPT_MAX = 1000;
+const PAID_FORGE_ENDPOINT = '/api/x402/forge';
+
+// Translate a /api/forge draft-lane payload into the versioned response contract.
+// Pure + exported so the lane boundary can be pinned in tests against real
+// captured shapes (inline-done vs queued) without touching the network.
+export function shapeResult(job, base) {
+ const glbUrl = typeof job?.glb_url === 'string' ? job.glb_url : '';
+ if (job?.status === 'done' && glbUrl) {
+ return {
+ status: 'done',
+ glb_url: glbUrl,
+ viewer_url: viewerUrl(base, glbUrl),
+ creation_id: job.creation_id ?? null,
+ backend: 'nvidia',
+ tier: 'draft',
+ };
+ }
+ // Queued: hand back the signed job token and the existing free poll URL. The
+ // viewer link isn't known until the GLB lands, so it's null until then.
+ const token = job?.job_id ?? null;
+ return {
+ status: 'pending',
+ job: token,
+ poll_url: token ? `/api/forge?job=${encodeURIComponent(token)}` : null,
+ viewer_url: null,
+ backend: 'nvidia',
+ tier: 'draft',
+ };
+}
+
+// Map a startForge lane failure to an honest boundary error. The buyer/user is
+// never left with a silent failure — every code has a designed status + message.
+function failFromLane(err) {
+ const code = err?.code;
+ if (code === 'not_configured') {
+ fail(503, 'not_configured', err.message || 'Free text→3D is not configured on this deployment — set NVIDIA_API_KEY.');
+ }
+ if (code === 'busy') {
+ fail(429, 'rate_limited', err.message || 'The free text→3D lane is momentarily busy — try again shortly.');
+ }
+ if (code === 'timeout') {
+ fail(504, 'lane_timeout', err.message || 'The text→3D lane took too long to accept the job — try again.');
+ }
+ fail(502, 'lane_error', err?.message || 'The text→3D lane failed to accept the job.');
+}
+
+export default defineEndpoint({
+ name: 'v1.ai.text_to_3d',
+ method: 'POST',
+ auth: 'public',
+ handler: async ({ req, res, body, ip }) => {
+ const prompt = typeof body?.prompt === 'string' ? body.prompt.trim() : '';
+ if (prompt.length < PROMPT_MIN) {
+ fail(400, 'validation_error', `"prompt" must be a non-empty string of at least ${PROMPT_MIN} characters`);
+ }
+ if (prompt.length > PROMPT_MAX) {
+ fail(400, 'validation_error', `"prompt" must be ${PROMPT_MAX} characters or fewer`);
+ }
+
+ // The free draft lane pins the NVIDIA NIM TRELLIS backend. If its key isn't
+ // present the lane can't serve — surface a clear 503 naming the exact var.
+ if (!backendIsConfigured('nvidia')) {
+ fail(
+ 503,
+ 'not_configured',
+ 'Free text→3D is not configured on this deployment — set NVIDIA_API_KEY to enable the NVIDIA NIM TRELLIS lane.',
+ );
+ }
+
+ // Per-IP daily GPU quota. Above it: 429 with reset + paid upsell, never a
+ // silent paywall. Consumed before submit so a burst can't outrun the meter.
+ const rl = await limits.aiTextTo3d(ip);
+ if (!rl.success) {
+ const resetSec = Math.max(1, Math.ceil(((rl.reset ?? Date.now()) - Date.now()) / 1000));
+ res.setHeader('X-RateLimit-Limit', String(rl.limit ?? DAILY_QUOTA));
+ res.setHeader('X-RateLimit-Remaining', '0');
+ res.setHeader('X-RateLimit-Reset', String(resetSec));
+ res.setHeader('Retry-After', String(resetSec));
+ return json(res, 429, {
+ error: 'quota_exceeded',
+ error_description: `Free text→3D is capped at ${DAILY_QUOTA} generations per day per IP. Your quota resets in ${resetSec}s.`,
+ retry_after: resetSec,
+ reset_seconds: resetSec,
+ quota: { limit: rl.limit ?? DAILY_QUOTA, window: '24h' },
+ // Not a paywall — a doorway. The paid forge tiers have no daily cap and
+ // add higher quality/volume for agents that outgrow the free lane.
+ upgrade: {
+ message: 'Need higher volume or quality? The paid forge tiers have no daily cap.',
+ endpoint: PAID_FORGE_ENDPOINT,
+ docs: '/docs/api-reference',
+ },
+ });
+ }
+
+ const base = originFromReq(req);
+ let job;
+ try {
+ job = await startForge(base, { prompt, backend: 'nvidia', path: 'image', tier: 'draft' });
+ } catch (err) {
+ failFromLane(err);
+ }
+
+ return shapeResult(job, base);
+ },
+});
diff --git a/api/x402/forge.js b/api/x402/forge.js
index f3748d236..a792cdca4 100644
--- a/api/x402/forge.js
+++ b/api/x402/forge.js
@@ -250,7 +250,7 @@ function buildRequirements(resourceUrl, priceAtomics) {
// FLUX→TRELLIS reconstruct lane so a paid call never dead-ends. Image→3D always
// reconstructs (NVIDIA's hosted preview is text-only). Throws on any submit
// failure so the caller can avoid settling payment.
-async function submitGeneration({ prompt, imageUrls, isImageMode, aspect, tier }) {
+export async function submitGeneration({ prompt, imageUrls, isImageMode, aspect, tier }) {
// Text prompts → the free NVIDIA NIM TRELLIS lane first (zero vendor cost).
if (!isImageMode) {
const viaNvidia = await submitTextViaNvidia({ prompt, tier });
diff --git a/api/x402/pipeline-remesh.js b/api/x402/pipeline-remesh.js
new file mode 100644
index 000000000..678cbfe7d
--- /dev/null
+++ b/api/x402/pipeline-remesh.js
@@ -0,0 +1,185 @@
+// POST /api/x402/pipeline-remesh { glb_url, remesh_mode?, operation?, target_faces?, texture_size? }
+//
+// 3D Asset Pipeline — Remesh stage. Pay $0.03 USDC and get back a cleaned,
+// retopologized GLB: triangle/quad/low-poly remeshing, mesh repair, or decimation
+// to a target face count, with the texture re-baked onto the new topology. This
+// is the stage that turns a raw generated or scanned mesh into something with
+// predictable topology and a bounded polygon budget. Input: a public GLB URL +
+// options. Output: a durable first-party GLB URL. One payment, one finished mesh.
+//
+// Runs the same workers/remesh Cloud Run service the free /api/forge-remesh
+// endpoint drives — this is its synchronous, pay-per-call twin: submit → poll to
+// completion → validate output bytes → persist → return the URL, all inside the
+// request. Any worker/env/validation failure throws BEFORE settlement, so a buyer
+// is never charged for a stage that didn't produce a valid GLB.
+
+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
+import { installAccessControl } from '../_lib/x402/access-control.js';
+import { priceFor } from '../_lib/x402-prices.js';
+import {
+ readJsonBody,
+ validateAssetUrl,
+ sniffRemoteAsset,
+ runStageJob,
+ persistStageOutput,
+ stageObjectKey,
+} from '../_lib/pipeline-stage.js';
+
+const ROUTE = '/api/x402/pipeline-remesh';
+const SLUG = 'pipeline-remesh';
+
+const VALID_MODES = new Set(['triangle', 'quad', 'lowpoly']);
+const VALID_OPERATIONS = new Set(['full', 'simplify', 'repair', 'convert']);
+const VALID_TEXTURE_SIZES = new Set([512, 1024, 2048]);
+
+const DESCRIPTION =
+ '3D Asset Pipeline — Remesh: pay $0.03 USDC to retopologize a GLB. Triangle, ' +
+ 'quad, or low-poly remeshing plus repair and decimation to a target face count, ' +
+ 'with the texture re-baked onto the new topology. POST a public glb_url and ' +
+ 'options; get back a durable first-party GLB URL. Nowhere else in the x402 ' +
+ 'ecosystem sells mesh remeshing. Pay autonomously in USDC on Solana mainnet.';
+
+export const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['glb_url'],
+ properties: {
+ glb_url: {
+ type: 'string',
+ format: 'uri',
+ description: 'Public HTTPS URL of the source binary glTF (.glb) mesh.',
+ },
+ remesh_mode: {
+ type: 'string',
+ enum: [...VALID_MODES],
+ default: 'triangle',
+ description: 'triangle = clean triangulation; quad = QuadriFlow quad retopology; lowpoly = aggressive decimation.',
+ },
+ operation: {
+ type: 'string',
+ enum: [...VALID_OPERATIONS],
+ default: 'full',
+ description: 'triangle-mode only: full remesh, simplify (decimate), repair (fix holes/non-manifold), or convert.',
+ },
+ target_faces: {
+ type: 'integer',
+ minimum: 1_000,
+ maximum: 500_000,
+ default: 50_000,
+ description: 'Target triangle count for the output mesh.',
+ },
+ texture_size: {
+ type: 'integer',
+ enum: [...VALID_TEXTURE_SIZES],
+ default: 1_024,
+ description: 'Resolution of the re-baked texture atlas.',
+ },
+ },
+};
+
+export const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['stage', 'input_url', 'output_url'],
+ properties: {
+ stage: { type: 'string', const: 'remesh' },
+ input_url: { type: 'string', format: 'uri' },
+ output_url: { type: 'string', format: 'uri', description: 'The retopologized GLB.' },
+ bytes: { type: ['integer', 'null'] },
+ persisted: { type: 'boolean', description: 'true when mirrored to first-party storage.' },
+ remesh_mode: { type: 'string' },
+ operation: { type: 'string' },
+ face_count: { type: ['integer', 'null'] },
+ quad_ratio: { type: ['number', 'null'] },
+ textured: { type: ['boolean', 'null'] },
+ },
+};
+
+export const BAZAAR = {
+ discoverable: true,
+ info: {
+ input: { type: 'http', method: 'POST', bodyType: 'json', body: { glb_url: 'https://three.ws/forge/sample.glb', remesh_mode: 'quad', target_faces: 20000 } },
+ output: {
+ type: 'json',
+ example: {
+ stage: 'remesh',
+ input_url: 'https://three.ws/forge/sample.glb',
+ output_url: 'https://cdn.three.ws/x402-pipeline/remesh/abc123.glb',
+ bytes: 812_044,
+ persisted: true,
+ remesh_mode: 'quad',
+ operation: 'full',
+ face_count: 20_000,
+ quad_ratio: 0.98,
+ textured: true,
+ },
+ },
+ },
+ schema: buildBazaarSchema({
+ method: 'POST',
+ bodyType: 'json',
+ bodySchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
+};
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'POST',
+ priceAtomics: priceFor(SLUG, '30000'), // $0.03 USDC
+ networks: ['solana', 'base'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ service: withService({
+ serviceName: 'three.ws Pipeline — Remesh',
+ tags: ['3d', 'remesh', 'retopology', 'glb', 'pipeline'],
+ }),
+ requiredScope: 'x402:bypass',
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+
+ async handler({ req }) {
+ const body = await readJsonBody(req);
+ const glbUrl = await validateAssetUrl(body?.glb_url, 'glb_url');
+ await sniffRemoteAsset(glbUrl, 'glb');
+
+ const remeshMode = VALID_MODES.has(body?.remesh_mode) ? body.remesh_mode : 'triangle';
+ const operation = VALID_OPERATIONS.has(body?.operation) ? body.operation : 'full';
+ const targetFaces = Math.max(1_000, Math.min(500_000, Math.round(Number(body?.target_faces) || 50_000)));
+ const textureSize = VALID_TEXTURE_SIZES.has(Number(body?.texture_size)) ? Number(body.texture_size) : 1_024;
+
+ const result = await runStageJob({
+ mode: 'remesh',
+ sourceUrl: glbUrl,
+ params: {
+ remesh_mode: remeshMode,
+ operation,
+ target_faces: targetFaces,
+ texture_size: textureSize,
+ output_format: 'glb',
+ },
+ });
+
+ const key = await stageObjectKey({ stage: 'remesh', sourceUrl: glbUrl, ext: 'glb' });
+ const out = await persistStageOutput({
+ resultUrl: result.resultGlbUrl,
+ key,
+ contentType: 'model/gltf-binary',
+ kind: 'glb',
+ });
+
+ return {
+ stage: 'remesh',
+ input_url: glbUrl,
+ output_url: out.url,
+ bytes: out.bytes,
+ persisted: out.persisted,
+ remesh_mode: remeshMode,
+ operation,
+ face_count: typeof result.faceCount === 'number' ? result.faceCount : null,
+ quad_ratio: typeof result.quadRatio === 'number' ? result.quadRatio : null,
+ textured: typeof result.textured === 'boolean' ? result.textured : null,
+ };
+ },
+});
diff --git a/api/x402/pipeline-rig.js b/api/x402/pipeline-rig.js
new file mode 100644
index 000000000..0182ed4f8
--- /dev/null
+++ b/api/x402/pipeline-rig.js
@@ -0,0 +1,143 @@
+// POST /api/x402/pipeline-rig { glb_url, rig_type? }
+//
+// 3D Asset Pipeline — Rig stage. Pay $0.05 USDC and get back an animation-ready
+// GLB: a humanoid skeleton is inferred and bound to a static mesh with skin
+// weights, so the model can walk, wave, and emote. This is the stage that turns a
+// generated or uploaded static character into a riggable asset — the capability
+// no other x402 resource offers. Input: a public GLB URL. Output: a durable
+// first-party rigged GLB URL. One payment, one rigged mesh.
+//
+// Drives the same avatar-pipeline-controller /rig endpoint (the `rerig` worker
+// mode) that the platform's auto-rig lane uses. Synchronous pay-per-call twin:
+// submit → poll to completion → validate output bytes → persist → return the URL.
+// Any worker/env/validation failure throws BEFORE settlement, so a buyer is never
+// charged for a rig that didn't produce a valid GLB.
+
+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
+import { installAccessControl } from '../_lib/x402/access-control.js';
+import { priceFor } from '../_lib/x402-prices.js';
+import {
+ readJsonBody,
+ validateAssetUrl,
+ sniffRemoteAsset,
+ runStageJob,
+ persistStageOutput,
+ stageObjectKey,
+} from '../_lib/pipeline-stage.js';
+
+const ROUTE = '/api/x402/pipeline-rig';
+const SLUG = 'pipeline-rig';
+
+const VALID_RIG_TYPES = new Set(['biped', 'quadruped']);
+
+const DESCRIPTION =
+ '3D Asset Pipeline — Rig: pay $0.05 USDC to make a static GLB animation-ready. ' +
+ 'A humanoid skeleton is inferred and bound to the mesh with skin weights so the ' +
+ 'model can walk, wave, and emote. POST a public glb_url; get back a durable ' +
+ 'first-party rigged GLB URL. No other x402 resource rigs a mesh. Pay ' +
+ 'autonomously in USDC on Solana mainnet — no API key, no account.';
+
+export const INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['glb_url'],
+ properties: {
+ glb_url: {
+ type: 'string',
+ format: 'uri',
+ description: 'Public HTTPS URL of the static binary glTF (.glb) mesh to rig.',
+ },
+ rig_type: {
+ type: 'string',
+ enum: [...VALID_RIG_TYPES],
+ default: 'biped',
+ description: 'Skeleton template to fit — biped (humanoid) or quadruped.',
+ },
+ },
+};
+
+export const OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['stage', 'input_url', 'output_url'],
+ properties: {
+ stage: { type: 'string', const: 'rig' },
+ input_url: { type: 'string', format: 'uri' },
+ output_url: { type: 'string', format: 'uri', description: 'The rigged, skinned GLB.' },
+ bytes: { type: ['integer', 'null'] },
+ persisted: { type: 'boolean' },
+ rig_type: { type: 'string' },
+ },
+};
+
+export const BAZAAR = {
+ discoverable: true,
+ info: {
+ input: { type: 'http', method: 'POST', bodyType: 'json', body: { glb_url: 'https://three.ws/forge/character.glb', rig_type: 'biped' } },
+ output: {
+ type: 'json',
+ example: {
+ stage: 'rig',
+ input_url: 'https://three.ws/forge/character.glb',
+ output_url: 'https://cdn.three.ws/x402-pipeline/rig/abc123.glb',
+ bytes: 1_940_112,
+ persisted: true,
+ rig_type: 'biped',
+ },
+ },
+ },
+ schema: buildBazaarSchema({
+ method: 'POST',
+ bodyType: 'json',
+ bodySchema: INPUT_SCHEMA,
+ outputSchema: OUTPUT_SCHEMA,
+ }),
+};
+
+export default paidEndpoint({
+ route: ROUTE,
+ method: 'POST',
+ priceAtomics: priceFor(SLUG, '50000'), // $0.05 USDC
+ networks: ['solana', 'base'],
+ description: DESCRIPTION,
+ bazaar: BAZAAR,
+ service: withService({
+ serviceName: 'three.ws Pipeline — Rig',
+ tags: ['3d', 'rigging', 'skeleton', 'glb', 'pipeline'],
+ }),
+ requiredScope: 'x402:bypass',
+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),
+
+ async handler({ req }) {
+ const body = await readJsonBody(req);
+ const glbUrl = await validateAssetUrl(body?.glb_url, 'glb_url');
+ await sniffRemoteAsset(glbUrl, 'glb');
+
+ const rigType = VALID_RIG_TYPES.has(body?.rig_type) ? body.rig_type : 'biped';
+
+ const result = await runStageJob({
+ mode: 'rerig',
+ sourceUrl: glbUrl,
+ params: { rig_type: rigType },
+ });
+
+ const key = await stageObjectKey({ stage: 'rig', sourceUrl: glbUrl, ext: 'glb' });
+ const out = await persistStageOutput({
+ resultUrl: result.resultGlbUrl,
+ key,
+ contentType: 'model/gltf-binary',
+ kind: 'glb',
+ });
+
+ return {
+ stage: 'rig',
+ input_url: glbUrl,
+ output_url: out.url,
+ bytes: out.bytes,
+ persisted: out.persisted,
+ rig_type: rigType,
+ };
+ },
+});
diff --git a/tests/api/v1-text-to-3d.test.js b/tests/api/v1-text-to-3d.test.js
new file mode 100644
index 000000000..45049447b
--- /dev/null
+++ b/tests/api/v1-text-to-3d.test.js
@@ -0,0 +1,215 @@
+// POST /api/v1/ai/text-to-3d — the free, versioned text→3D endpoint.
+//
+// This is the flagship free lane of the AI package: a prompt goes to the NVIDIA
+// NIM TRELLIS draft lane (via the SAME /api/forge submit the forge_free MCP tool
+// uses) and comes back as a textured GLB — inline when fast, otherwise a job
+// token + the existing free poll URL. The tests pin the contract that matters:
+// • validation (empty / too-short prompt → 400),
+// • missing NVIDIA env → 503 not_configured naming the var,
+// • per-IP daily quota → 429 with X-RateLimit-Reset + a paid-forge upsell,
+// • the lane response contract for the inline-done and pending paths, against
+// the REAL captured /api/forge draft-lane shapes.
+//
+// The rate limiter is mocked (switchable per test) and the network is stubbed via
+// global fetch, so the suite runs fully offline while exercising the real handler,
+// real originFromReq, and real viewerUrl.
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { Readable } from 'node:stream';
+
+// Switchable quota result — flip `quotaOk` per test. apiV1 always passes (it's the
+// gateway's burst guard, not the thing under test here).
+let quotaOk = true;
+let quotaResult = { success: true, limit: 10, remaining: 9, reset: Date.now() + 86_400_000 };
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ apiV1: async () => ({ success: true, limit: 120, remaining: 119, reset: Date.now() + 60_000 }),
+ aiTextTo3d: async () => (quotaOk ? { success: true, limit: 10, remaining: 9, reset: Date.now() + 86_400_000 } : quotaResult),
+ },
+ clientIp: () => '203.0.113.7',
+}));
+
+const ORIGINAL_FETCH = globalThis.fetch;
+const ENV_KEYS = ['NVIDIA_API_KEY', 'STUDIO_API_BASE', 'PUBLIC_APP_ORIGIN', 'APP_ORIGIN'];
+const saved = {};
+
+beforeEach(() => {
+ quotaOk = true;
+ for (const k of ENV_KEYS) {
+ saved[k] = process.env[k];
+ delete process.env[k];
+ }
+});
+afterEach(() => {
+ for (const k of ENV_KEYS) {
+ if (saved[k] === undefined) delete process.env[k];
+ else process.env[k] = saved[k];
+ }
+ globalThis.fetch = ORIGINAL_FETCH;
+ vi.restoreAllMocks();
+});
+
+function makeReq({ method = 'POST', url = '/api/v1/ai/text-to-3d', body = null, host = 'three.ws' } = {}) {
+ const raw = body == null ? '' : JSON.stringify(body);
+ const stream = Readable.from(raw ? [Buffer.from(raw)] : []);
+ stream.method = method;
+ stream.url = url;
+ stream.headers = { 'content-type': 'application/json', host };
+ return stream;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ writableEnded: false,
+ headersSent: false,
+ setHeader(k, v) {
+ this._h[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this._h[k.toLowerCase()];
+ },
+ end(body) {
+ this._body = body;
+ this.writableEnded = true;
+ },
+ };
+}
+
+async function dispatch(req, res) {
+ const mod = await import('../../api/v1/ai/text-to-3d.js');
+ await mod.default(req, res);
+ return { res, body: res._body ? JSON.parse(res._body) : null };
+}
+
+// A JSON Response stub matching the subset of WHATWG Response startForge reads.
+function jsonResponse(obj, { status = 200 } = {}) {
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ headers: { get: () => 'application/json' },
+ json: async () => obj,
+ text: async () => JSON.stringify(obj),
+ };
+}
+
+// ── Real captured /api/forge draft-lane shapes (NVIDIA NIM TRELLIS) ───────────
+// Inline finish — the sync branch (api/forge.js): job_id null, status done, GLB.
+const DONE_FIXTURE = {
+ job_id: null,
+ creation_id: 'a1b2c3d4-0000-4000-8000-000000000001',
+ status: 'done',
+ glb_url: 'https://cdn.three.ws/forge/anon/a1b2c3d4.glb',
+ durable: true,
+ backend: 'nvidia',
+ tier: 'draft',
+ path: 'image',
+};
+// Queued — the async branch: a signed f1.* job token, status queued, no GLB yet.
+const QUEUED_FIXTURE = {
+ job_id: 'f1.eyJwIjoibnZpZGlhIiwiayI6InRleHQiLCJ0IjoibmltLXRhc2stMTIzIn0.c2lnbmF0dXJl',
+ creation_id: 'a1b2c3d4-0000-4000-8000-000000000002',
+ status: 'queued',
+};
+
+describe('shapeResult — lane boundary contract', () => {
+ it('maps the inline-done shape to a done payload with a viewer URL', async () => {
+ const { shapeResult } = await import('../../api/v1/ai/text-to-3d.js');
+ const out = shapeResult(DONE_FIXTURE, 'https://three.ws');
+ expect(out).toEqual({
+ status: 'done',
+ glb_url: 'https://cdn.three.ws/forge/anon/a1b2c3d4.glb',
+ viewer_url: 'https://three.ws/viewer?src=' + encodeURIComponent(DONE_FIXTURE.glb_url),
+ creation_id: 'a1b2c3d4-0000-4000-8000-000000000001',
+ backend: 'nvidia',
+ tier: 'draft',
+ });
+ });
+
+ it('maps the queued shape to a pending payload with the free poll URL', async () => {
+ const { shapeResult } = await import('../../api/v1/ai/text-to-3d.js');
+ const out = shapeResult(QUEUED_FIXTURE, 'https://three.ws');
+ expect(out).toEqual({
+ status: 'pending',
+ job: QUEUED_FIXTURE.job_id,
+ poll_url: '/api/forge?job=' + encodeURIComponent(QUEUED_FIXTURE.job_id),
+ viewer_url: null,
+ backend: 'nvidia',
+ tier: 'draft',
+ });
+ });
+});
+
+describe('POST /api/v1/ai/text-to-3d — validation', () => {
+ it('rejects an empty prompt with 400', async () => {
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+ const { res, body } = await dispatch(makeReq({ body: { prompt: '' } }), makeRes());
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+
+ it('rejects a too-short prompt with 400', async () => {
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+ const { res, body } = await dispatch(makeReq({ body: { prompt: 'ab' } }), makeRes());
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+});
+
+describe('POST /api/v1/ai/text-to-3d — configuration', () => {
+ it('returns 503 not_configured naming NVIDIA_API_KEY when the lane is unconfigured', async () => {
+ const { res, body } = await dispatch(makeReq({ body: { prompt: 'a small ceramic robot figurine' } }), makeRes());
+ expect(res.statusCode).toBe(503);
+ expect(body.error).toBe('not_configured');
+ expect(body.error_description).toMatch(/NVIDIA_API_KEY/);
+ });
+});
+
+describe('POST /api/v1/ai/text-to-3d — quota', () => {
+ it('returns 429 with X-RateLimit-Reset and a paid-forge upsell above quota', async () => {
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+ quotaOk = false;
+ quotaResult = { success: false, limit: 10, remaining: 0, reset: Date.now() + 3_600_000 };
+ // The lane must never be reached once quota is exhausted.
+ globalThis.fetch = vi.fn(async () => {
+ throw new Error('lane should not be called when over quota');
+ });
+ const { res, body } = await dispatch(makeReq({ body: { prompt: 'a small ceramic robot figurine' } }), makeRes());
+ expect(res.statusCode).toBe(429);
+ expect(body.error).toBe('quota_exceeded');
+ expect(res.getHeader('x-ratelimit-reset')).toBeTruthy();
+ expect(Number(res.getHeader('x-ratelimit-reset'))).toBeGreaterThan(0);
+ expect(res.getHeader('retry-after')).toBeTruthy();
+ expect(body.upgrade.endpoint).toBe('/api/x402/forge');
+ expect(body.retry_after).toBeGreaterThan(0);
+ expect(globalThis.fetch).not.toHaveBeenCalled();
+ });
+});
+
+describe('POST /api/v1/ai/text-to-3d — response contract', () => {
+ it('returns { status: done, glb_url, viewer_url } when the lane finishes inline', async () => {
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+ globalThis.fetch = vi.fn(async () => jsonResponse(DONE_FIXTURE));
+ const { res, body } = await dispatch(makeReq({ body: { prompt: 'a small ceramic robot figurine' } }), makeRes());
+ expect(res.statusCode).toBe(200);
+ expect(body.data.status).toBe('done');
+ expect(body.data.glb_url).toBe(DONE_FIXTURE.glb_url);
+ expect(body.data.viewer_url).toBe('https://three.ws/viewer?src=' + encodeURIComponent(DONE_FIXTURE.glb_url));
+ // The lane was submitted with the pinned free NVIDIA draft params.
+ const [, opts] = globalThis.fetch.mock.calls[0];
+ const sent = JSON.parse(opts.body);
+ expect(sent).toMatchObject({ prompt: 'a small ceramic robot figurine', backend: 'nvidia', path: 'image', tier: 'draft' });
+ });
+
+ it('returns { status: pending, job, poll_url } when the lane queues the job', async () => {
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+ globalThis.fetch = vi.fn(async () => jsonResponse(QUEUED_FIXTURE));
+ const { res, body } = await dispatch(makeReq({ body: { prompt: 'a small ceramic robot figurine' } }), makeRes());
+ expect(res.statusCode).toBe(200);
+ expect(body.data.status).toBe('pending');
+ expect(body.data.job).toBe(QUEUED_FIXTURE.job_id);
+ expect(body.data.poll_url).toBe('/api/forge?job=' + encodeURIComponent(QUEUED_FIXTURE.job_id));
+ expect(body.data.viewer_url).toBeNull();
+ });
+});