Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(x402): add /api/x402/pipeline — one paid call runs a full 3D asset chain
nich304993231c4d
diff --git a/api/_lib/pipeline.js b/api/_lib/pipeline.jsnew file mode 100644index 000000000..01cff8b2d--- /dev/null+++ b/api/_lib/pipeline.js@@ -0,0 +1,520 @@+// Pipeline engine — the stage registry + poll-driven state machine behind+// POST /api/x402/pipeline (the "asset factory": one paid call runs a validated+// chain of stages and returns a game-ready GLB).+//+// Design constraints that shape everything here:+// • Vercel functions are stateless and there is NO background worker. A chain+// of slow GPU stages (generate → rig → optimize) therefore cannot run inline+// after the response. Instead the chain is a STATE MACHINE advanced by the+// free poll route: each GET /api/forge?job=<pipeline-token> poll checks the+// current running stage and, when it finishes, submits the next one. The+// buyer polls for free until the last stage delivers.+// • Every stage ultimately submits to the same provider modules the standalone+// forge routes use (NVIDIA/Replicate/GCP Cloud Run workers), so we call those+// provider modules directly rather than the HTTP wrapper routes — this module+// does not depend on any x402 wrapper route existing.+// • Only stages whose backing module is actually configured are offered. The+// grammar (the set of valid stage ids) is computed from env per request, so a+// deployment missing GCP_STYLIZE_URL simply doesn't advertise `stylize`.+//+// Failure semantics: a stage failing mid-chain marks the job `failed` at that+// stage while the already-completed stages' outputs stay in the record (partial+// value, honestly labeled). Anything checkable up front — grammar, inputs, and+// per-stage lane availability — is rejected by validateChain BEFORE any payment,+// and the first stage is submitted BEFORE settlement so a dead first lane never+// charges (see api/x402/pipeline.js).++import { json } from './http.js';+import { priceFor } from './x402-prices.js';+import { resolveTier } from './forge-tiers.js';+import { decodeJobToken } from './forge-job-token.js';+import { sanitizeJobError } from './provider-job-error.js';+import { createRegenProvider as createGcpProvider } from '../_providers/gcp.js';+import { createRegenProvider as createReplicateProvider } from '../_providers/replicate.js';+import {+ getPipelineJob,+ savePipelineJob,+ acquireAdvanceLock,+ isTerminal,+ publicView,+} from './pipeline-store.js';++// Canonical stage order. A requested chain must be a SUBSEQUENCE of this list —+// that single rule enforces "generate is first" and rejects nonsensical orders+// (e.g. rig before generate, stylize before rig) without a bespoke check per pair.+export const CANONICAL_ORDER = ['generate', 'rig', 'remesh', 'gameready', 'stylize'];++const VALID_ASPECT = new Set(['1:1', '4:3', '3:4', '16:9', '9:16']);++function envSet(name) {+ const v = process.env?.[name];+ return typeof v === 'string' && v.trim() !== '';+}++function nowIso() {+ return new Date().toISOString();+}++function clamp(n, min, max, fallback) {+ const v = Number(n);+ if (!Number.isFinite(v)) return fallback;+ return Math.max(min, Math.min(max, Math.round(v)));+}++// Normalize a submitGeneration() response (which may be inline-done or a forge+// poll token) into the uniform stage handle the state machine understands.+function normalizeForgeResponse(resp) {+ if (resp?.status === 'done' && resp.glb_url) {+ return { done: true, glbUrl: resp.glb_url };+ }+ const jobId = resp?.job_id;+ if (!jobId) {+ throw Object.assign(new Error('Generation returned no job handle.'), {+ status: 502,+ code: 'submit_failed',+ });+ }+ // A signed forge token encodes {provider, taskId}; a bare id is a Replicate+ // prediction. Either way we get a (provider, upstream id) the poller can check.+ const token = decodeJobToken(jobId);+ if (token) return { done: false, provider: token.provider, extJobId: token.taskId, kind: token.kind };+ return { done: false, provider: 'replicate', extJobId: jobId };+}++// ── Stage registry ──────────────────────────────────────────────────────────+// Each stage declares: how to price it, whether its lane is configured, why it's+// off (for the storefront copy), whether it needs an input GLB, and how to submit+// it. submit() returns a uniform handle — { done:true, glbUrl } for a synchronous+// lane, or { done:false, provider, extJobId } for an async one — and THROWS on a+// submit failure so the pre-settlement first-stage submit can avoid charging.+export const STAGES = {+ generate: {+ id: 'generate',+ label: 'Generate (text → 3D)',+ priceSlug: 'pipeline-stage-generate',+ defaultAtomics: '50000', // $0.05 — matches the draft forge tier+ needsInputGlb: false,+ available() {+ return envSet('NVIDIA_API_KEY') || envSet('HF_TOKEN') || envSet('REPLICATE_API_TOKEN');+ },+ reason() {+ return 'set NVIDIA_API_KEY or HF_TOKEN (free lanes) or REPLICATE_API_TOKEN';+ },+ async submit({ prompt, options }) {+ const tier = resolveTier(options?.tier).id;+ const aspect = VALID_ASPECT.has(options?.aspect_ratio) ? options.aspect_ratio : '1:1';+ // Lazy import: the generate lane reuses the paid forge route's free-first+ // multi-lane submit, which transitively pulls in the payment SDK. Loading+ // it on demand keeps the engine module (grammar/pricing/rig/optimize) free+ // of that dependency so a chain without a generate stage never touches it.+ const { submitGeneration } = await import('../x402/forge.js');+ const resp = await submitGeneration({ prompt, imageUrls: [], isImageMode: false, aspect, tier });+ return normalizeForgeResponse(resp);+ },+ },++ rig: {+ id: 'rig',+ label: 'Auto-rig (skeleton + skin weights)',+ priceSlug: 'pipeline-stage-rig',+ defaultAtomics: '100000', // $0.10+ needsInputGlb: true,+ available() {+ return (+ (envSet('GCP_RECONSTRUCTION_KEY') && envSet('GCP_RECONSTRUCTION_URL')) ||+ (envSet('REPLICATE_API_TOKEN') && envSet('REPLICATE_RERIG_MODEL'))+ );+ },+ reason() {+ return 'set GCP_RECONSTRUCTION_URL + GCP_RECONSTRUCTION_KEY, or REPLICATE_RERIG_MODEL';+ },+ async submit({ glbUrl, options }) {+ // GCP UniRig first (self-host /rig endpoint), Replicate rerig as fallback —+ // mirrors the resolution the standalone /api/forge?action=rig route uses.+ let provider = null;+ let providerName = null;+ if (envSet('GCP_RECONSTRUCTION_KEY') && envSet('GCP_RECONSTRUCTION_URL')) {+ try {+ const gcp = createGcpProvider();+ if (gcp.supportsMode('rerig')) {+ provider = gcp;+ providerName = 'gcp';+ }+ } catch {+ /* fall through to Replicate */+ }+ }+ if (!provider && envSet('REPLICATE_API_TOKEN') && envSet('REPLICATE_RERIG_MODEL')) {+ const rep = createReplicateProvider();+ if (rep.supportsMode('rerig')) {+ provider = rep;+ providerName = 'replicate';+ }+ }+ if (!provider) {+ throw Object.assign(new Error('Auto-rigging is not configured on this deployment.'), {+ status: 501,+ code: 'stage_unconfigured',+ });+ }+ const job = await provider.submit({+ mode: 'rerig',+ sourceUrl: glbUrl,+ params: { rig_type: options?.rig?.rig_type || 'biped' },+ });+ return { done: false, provider: providerName, extJobId: job.extJobId };+ },+ },++ remesh: {+ id: 'remesh',+ label: 'Remesh (retopology + PBR bake)',+ priceSlug: 'pipeline-stage-remesh',+ defaultAtomics: '80000', // $0.08+ needsInputGlb: true,+ available() {+ return envSet('GCP_REMESH_URL') && envSet('GCP_RECONSTRUCTION_KEY');+ },+ reason() {+ return 'set GCP_REMESH_URL + GCP_RECONSTRUCTION_KEY';+ },+ async submit({ glbUrl, options }) {+ const gcp = createGcpProvider();+ const o = options?.remesh || {};+ const job = await gcp.submit({+ mode: 'remesh',+ sourceUrl: glbUrl,+ params: {+ remesh_mode: ['triangle', 'quad', 'lowpoly'].includes(o.remesh_mode) ? o.remesh_mode : 'triangle',+ operation: ['full', 'simplify', 'repair', 'convert'].includes(o.operation) ? o.operation : 'full',+ target_faces: clamp(o.target_faces, 1000, 500000, 50000),+ texture_size: [512, 1024, 2048].includes(o.texture_size) ? o.texture_size : 1024,+ output_format: 'glb',+ },+ });+ return { done: false, provider: 'gcp', extJobId: job.extJobId };+ },+ },++ gameready: {+ id: 'gameready',+ label: 'Game-ready (engine-budget retopo + bake)',+ priceSlug: 'pipeline-stage-gameready',+ defaultAtomics: '120000', // $0.12+ needsInputGlb: true,+ available() {+ return envSet('GCP_REMESH_URL') && envSet('GCP_RECONSTRUCTION_KEY');+ },+ reason() {+ return 'set GCP_REMESH_URL + GCP_RECONSTRUCTION_KEY';+ },+ async submit({ glbUrl, options }) {+ // Game-ready runs on the same remesh worker with an engine poly budget:+ // quad → field-aligned QuadriFlow retopo, tri → silhouette low-poly.+ const gcp = createGcpProvider();+ const o = options?.gameready || {};+ const remeshMode = o.topology === 'tri' ? 'lowpoly' : 'quad';+ const job = await gcp.submit({+ mode: 'remesh',+ sourceUrl: glbUrl,+ params: {+ remesh_mode: remeshMode,+ operation: 'full',+ target_faces: clamp(o.poly_budget, 1000, 500000, 15000),+ texture_size: [1024, 2048].includes(o.texture_size) ? o.texture_size : 2048,+ output_format: 'glb',+ },+ });+ return { done: false, provider: 'gcp', extJobId: job.extJobId };+ },+ },++ stylize: {+ id: 'stylize',+ label: 'Stylize (geometric filter)',+ priceSlug: 'pipeline-stage-stylize',+ defaultAtomics: '60000', // $0.06+ needsInputGlb: true,+ available() {+ return envSet('GCP_STYLIZE_URL') && envSet('GCP_RECONSTRUCTION_KEY');+ },+ reason() {+ return 'set GCP_STYLIZE_URL + GCP_RECONSTRUCTION_KEY';+ },+ async submit({ glbUrl, options }) {+ const gcp = createGcpProvider();+ const o = options?.stylize || {};+ const job = await gcp.submit({+ mode: 'stylize',+ sourceUrl: glbUrl,+ params: {+ style: ['voxel', 'brick', 'voronoi', 'lowpoly'].includes(o.style) ? o.style : 'voxel',+ resolution: Number.isFinite(Number(o.resolution)) ? Number(o.resolution) : null,+ output_format: 'glb',+ },+ });+ return { done: false, provider: 'gcp', extJobId: job.extJobId };+ },+ },+};++export const STAGE_IDS = Object.keys(STAGES);++// The stages this deployment can actually run, in canonical order.+export function availableStages() {+ return CANONICAL_ORDER.filter((id) => STAGES[id].available());+}++// A machine- and human-readable description of the grammar: which stages are+// live, which are excluded and why. Feeds the storefront description + GET.+export function stageGrammar() {+ const available = [];+ const excluded = [];+ for (const id of CANONICAL_ORDER) {+ const s = STAGES[id];+ const entry = { id, label: s.label, price_usdc: priceUsdcForStage(id) };+ if (s.available()) available.push(entry);+ else excluded.push({ ...entry, reason: s.reason() });+ }+ return {+ order: CANONICAL_ORDER,+ available,+ excluded,+ grammar: 'stages is an ordered subsequence of ' + JSON.stringify(CANONICAL_ORDER) ++ '. generate must be first and requires prompt; without generate, glb_url is required.',+ };+}++// ── Pricing ─────────────────────────────────────────────────────────────────+export function priceAtomicsForStage(id) {+ const s = STAGES[id];+ return priceFor(s.priceSlug, s.defaultAtomics);+}++function atomicsToUsdc(atomics) {+ // USDC has 6 decimals. Format without floating error.+ const n = BigInt(atomics);+ const whole = n / 1000000n;+ let frac = (n % 1000000n).toString().padStart(6, '0').replace(/0+$/, '');+ // Always show at least cents (0.1 → 0.10, whole dollars → .00).+ if (frac.length < 2) frac = frac.padEnd(2, '0');+ return `${whole}.${frac}`;+}++export function priceUsdcForStage(id) {+ return atomicsToUsdc(priceAtomicsForStage(id));+}++// Total price for a chain = sum of its stages' prices. Returns BigInt-safe+// atomics string + a display USDC string.+export function priceForChain(stages) {+ let total = 0n;+ for (const id of stages) total += BigInt(priceAtomicsForStage(id));+ const atomics = total.toString();+ return { atomics, usdc: atomicsToUsdc(atomics) };+}++// ── Grammar validation ──────────────────────────────────────────────────────+// Validates a requested chain against the live grammar. Returns { ok, stages }+// or { ok:false, status, code, message }. Pure — no I/O, so it's safe to run+// before any payment.+export function validateChain(rawStages, { hasPrompt, hasGlb } = {}) {+ if (!Array.isArray(rawStages) || rawStages.length === 0) {+ return bad('invalid_stages', 'stages must be a non-empty array of stage ids.');+ }+ if (rawStages.length > CANONICAL_ORDER.length) {+ return bad('invalid_stages', `A chain has at most ${CANONICAL_ORDER.length} stages.`);+ }+ const stages = [];+ const seen = new Set();+ for (const raw of rawStages) {+ if (typeof raw !== 'string' || !STAGE_IDS.includes(raw)) {+ return bad(+ 'unknown_stage',+ `Unknown stage "${raw}". Valid stages: ${availableStages().join(', ') || '(none configured)'}.`,+ );+ }+ if (seen.has(raw)) return bad('duplicate_stage', `Stage "${raw}" is listed more than once.`);+ if (!STAGES[raw].available()) {+ return bad(+ 'stage_unavailable',+ `Stage "${raw}" is not available on this deployment (${STAGES[raw].reason()}).`,+ );+ }+ seen.add(raw);+ stages.push(raw);+ }+ // Order must be a subsequence of the canonical order.+ let cursor = -1;+ for (const id of stages) {+ const at = CANONICAL_ORDER.indexOf(id);+ if (at <= cursor) {+ return bad(+ 'invalid_order',+ `Invalid stage order. Stages must follow ${JSON.stringify(CANONICAL_ORDER)} (generate first).`,+ );+ }+ cursor = at;+ }+ // Input requirements.+ const first = stages[0];+ if (first === 'generate') {+ if (!hasPrompt) return bad('missing_prompt', 'The generate stage requires a `prompt`.');+ } else if (!hasGlb) {+ return bad('missing_glb_url', 'Without a generate stage, a `glb_url` input is required.');+ }+ return { ok: true, stages };++ function bad(code, message) {+ return { ok: false, status: 400, code, message };+ }+}++// ── Stage submit / poll ─────────────────────────────────────────────────────+// Raw submit for one stage. THROWS on failure (used pre-settlement for the first+// stage so a dead lane never charges).+export async function submitStage(stageId, { prompt, glbUrl, options }) {+ return STAGES[stageId].submit({ prompt, glbUrl, options });+}++// Poll one stage's async handle via the provider that owns it. Returns the+// provider's status result ({ status, resultGlbUrl?, error? }).+async function pollHandle(handle) {+ if (!handle?.provider) return { status: 'failed', error: 'missing stage handle' };+ switch (handle.provider) {+ case 'gcp': {+ return createGcpProvider().status(handle.extJobId);+ }+ case 'nvidia': {+ const { createNvidiaProvider } = await import('../_providers/nvidia.js');+ return createNvidiaProvider().status({ taskId: handle.extJobId });+ }+ case 'replicate':+ default: {+ return createReplicateProvider().status(handle.extJobId);+ }+ }+}++// ── State machine ─────────────────────────────────────────────────────────────+// Submit stage `idx` and record the result on the job. On a submit failure the+// job is marked failed at that stage (partial-failure semantics: prior stages'+// outputs are preserved). A synchronous stage completion chains straight into+// the next stage. Mutates and returns `job`.+export async function submitStageInto(job, idx) {+ const stage = job.stages[idx];+ const inputGlb = idx === 0 ? job.input_glb_url : job.stages[idx - 1].output_url;+ stage.started_at = stage.started_at || nowIso();+ let handle;+ try {+ handle = await submitStage(stage.id, { prompt: job.prompt, glbUrl: inputGlb, options: job.options });+ } catch (err) {+ stage.status = 'failed';+ stage.finished_at = nowIso();+ stage.error = sanitizeJobError(err?.message) || 'This stage could not start.';+ stage.handle = null;+ job.status = 'failed';+ return job;+ }+ if (handle.done && handle.glbUrl) {+ stage.status = 'done';+ stage.finished_at = nowIso();+ stage.output_url = handle.glbUrl;+ stage.handle = null;+ job.result_glb_url = handle.glbUrl;+ if (idx + 1 >= job.stages.length) {+ job.status = 'done';+ return job;+ }+ job.status = 'running';+ return submitStageInto(job, idx + 1);+ }+ stage.status = 'running';+ stage.handle = handle;+ job.status = 'running';+ return job;+}++// Advance the pipeline by one tick: poll the current running stage and, when it+// finishes, kick the next. Mutates and returns `job`. Safe to call repeatedly;+// terminal jobs are returned unchanged.+export async function advancePipeline(job) {+ if (isTerminal(job.status)) return job;+ const idx = job.stages.findIndex((s) => s.status !== 'done' && s.status !== 'failed');+ if (idx === -1) {+ job.status = 'done';+ return job;+ }+ const stage = job.stages[idx];++ // A queued stage whose input is ready but hasn't been submitted yet.+ if (stage.status === 'queued' && !stage.handle) {+ return submitStageInto(job, idx);+ }++ // A running stage — poll it.+ let result;+ try {+ result = await pollHandle(stage.handle);+ } catch {+ // Transient poll error: leave the stage running so the next poll retries.+ return job;+ }++ if (result.status === 'done' && result.resultGlbUrl) {+ stage.status = 'done';+ stage.finished_at = nowIso();+ stage.output_url = result.resultGlbUrl;+ stage.handle = null;+ job.result_glb_url = result.resultGlbUrl;+ if (idx + 1 >= job.stages.length) {+ job.status = 'done';+ return job;+ }+ job.status = 'running';+ return submitStageInto(job, idx + 1);+ }+ if (result.status === 'failed') {+ stage.status = 'failed';+ stage.finished_at = nowIso();+ stage.error = sanitizeJobError(result.error) || 'This stage failed — the prior stage output is still available.';+ stage.handle = null;+ job.status = 'failed';+ return job;+ }+ // Still queued/running upstream.+ stage.status = 'running';+ job.status = 'running';+ return job;+}++// ── Free poll route handler ───────────────────────────────────────────────────+// Wired into GET /api/forge?job=<pipeline-token>. Loads the job, advances it one+// tick under a best-effort lock (so concurrent polls don't double-submit), and+// returns the public view + the poll url the caller keeps hitting.+export async function pollPipeline(res, id, token) {+ const job = await getPipelineJob(id);+ if (!job) {+ return json(res, 404, {+ error: 'job_not_found',+ message: 'No pipeline job for that token (it may have expired after 2 hours).',+ });+ }+ if (!isTerminal(job.status)) {+ const locked = await acquireAdvanceLock(id);+ if (locked) {+ try {+ await advancePipeline(job);+ await savePipelineJob(job);+ } catch {+ // Advance failed transiently — return the last-known snapshot; the next+ // poll retries. Never fail a poll over an advance hiccup.+ }+ }+ }+ const view = publicView(job);+ return json(res, 200, {+ ...view,+ poll_url: token ? `/api/forge?job=${encodeURIComponent(token)}` : null,+ });+}diff --git a/api/forge.js b/api/forge.jsindex 85ec9c935..334e06c25 100644--- a/api/forge.js+++ b/api/forge.js@@ -1865,6 +1865,15 @@ async function pollJob(req, res, jobId) {return rateLimited(res, rl);}+ // A pipeline job token (POST /api/x402/pipeline) polls here too, but its record+ // is a multi-stage chain, not a single provider job. Hand it to the pipeline+ // engine, which advances the state machine one tick and returns per-stage+ // progress. Plain forge jobs (below) are unaffected.+ if (token?.provider === 'pipeline') {+ const { pollPipeline } = await import('./_lib/pipeline.js');+ return pollPipeline(res, token.taskId, jobId);+ }+const provider = token?.provider || 'replicate';const upstreamId = token?.taskId || jobId;const clientKey = clientKeyFrom(req);diff --git a/api/x402/pipeline.js b/api/x402/pipeline.jsnew file mode 100644index 000000000..1bc4ac4ed--- /dev/null+++ b/api/x402/pipeline.js@@ -0,0 +1,472 @@+// POST /api/x402/pipeline { stages: [...], prompt?, glb_url?, options?: {...} }+//+// One x402 call, full 3D asset pipeline — text or GLB in, rigged/optimized+// game-ready GLB out. The only asset pipeline in the x402 ecosystem: an agent+// describes what it wants and gets back a game-ready asset from a single paid+// call, priced per stage and quoted EXACTLY in the 402 challenge.+//+// `stages` is an ordered subsequence of+// ['generate','rig','remesh','gameready','stylize']+// (generate must be first and needs `prompt`; without generate, `glb_url` is the+// input). Only stages whose backing lane is configured on this deployment are+// offered — the grammar is computed from env per request, and the 402 quote is+// the SUM of the requested stages' prices.+//+// Execution mirrors api/x402/forge.js: the first stage is submitted AFTER verify+// but BEFORE settle, so a dead first lane never charges. The chain then advances+// as a poll-driven state machine — the buyer polls FREE at+// GET /api/forge?job=<job_token>+// and each poll runs the next stage when the current one finishes, recording+// per-stage progress (id, status, started_at, finished_at, output_url, error).+// A stage failing mid-chain marks the job `failed` at that stage with the+// completed stages' outputs still delivered (honest partial value).+//+// Network: USDC on Solana mainnet (Base is a dev/preview failsafe when+// X402_PAY_TO_SOLANA is unset). GET (no payment) returns the live stage grammar+// and per-stage pricing so agents can discover cost + capability before paying.++import { wrap, cors, error, json, rateLimited } from '../_lib/http.js';+import {+ NETWORK_BASE_MAINNET,+ NETWORK_SOLANA_MAINNET,+ send402,+ verifyPayment,+ settlePayment,+ encodePaymentResponseHeader,+ permit2VariantOf,+ resolveResourceUrl,+ buildBazaarSchema,+} from '../_lib/x402-spec.js';+import { env } from '../_lib/env.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import {+ PAYMENT_IDENTIFIER,+ checkCache,+ extractIdFromHeader,+ hashPaymentProof,+ hashRequestPayload,+ paymentIdentifierExtension,+ storeResponse,+ writeCachedResponse,+ writeConflict,+} from '../_lib/x402/payment-identifier-server.js';+import { installAccessControl } from '../_lib/x402/access-control.js';+import { withService } from '../_lib/x402/bazaar-helpers.js';+import { assertSafePublicUrl } from '../_lib/ssrf-guard.js';+import { encodeJobToken } from '../_lib/forge-job-token.js';+import {+ CANONICAL_ORDER,+ validateChain,+ priceForChain,+ stageGrammar,+ submitStage,+ availableStages,+} from '../_lib/pipeline.js';+import { createPipelineJob, savePipelineJob, publicView } from '../_lib/pipeline-store.js';++const ROUTE = '/api/x402/pipeline';+const REQUIRED_SCOPE = 'x402:bypass';+const accessControl = installAccessControl({ requiredScope: REQUIRED_SCOPE });+const routeConfig = { path: ROUTE, method: 'POST', requiredScope: REQUIRED_SCOPE };++const HTTP_URL_RE = /^https:\/\/[^\s]+$/i;++const ROUTE_DESCRIPTION =+ 'One call, full 3D asset pipeline — text or GLB in, rigged/optimized ' ++ 'game-ready GLB out; the only asset pipeline in the x402 ecosystem. Submit an ' ++ 'ordered chain of stages (generate → rig → remesh → gameready → stylize) and ' ++ 'get back a job token you poll for FREE at GET /api/forge?job=<id>, watching ' ++ 'per-stage progress until the final GLB is delivered. Priced per stage and ' ++ 'quoted EXACTLY in the 402 challenge (the sum of the requested stages). Pay ' ++ 'autonomously in USDC on Solana mainnet — no API key, no account.';++const INPUT_EXAMPLE = {+ stages: ['generate', 'rig'],+ prompt: 'a brass steampunk owl, full body',+ options: { tier: 'draft', rig: { rig_type: 'biped' } },+};++const INPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['stages'],+ properties: {+ stages: {+ type: 'array',+ minItems: 1,+ maxItems: CANONICAL_ORDER.length,+ items: { type: 'string', enum: [...CANONICAL_ORDER] },+ description:+ 'Ordered subsequence of ' + JSON.stringify(CANONICAL_ORDER) ++ '. generate must be first and requires prompt; without generate, glb_url is required.',+ },+ prompt: {+ type: 'string',+ minLength: 3,+ maxLength: 1000,+ description: 'Subject for the generate stage. Required when stages starts with generate.',+ },+ glb_url: {+ type: 'string',+ format: 'uri',+ description: 'Public https GLB to feed the first stage when the chain does not start with generate.',+ },+ options: {+ type: 'object',+ description: 'Per-stage options: { tier, aspect_ratio, rig:{rig_type}, remesh:{...}, gameready:{topology,poly_budget,texture_size}, stylize:{style,resolution} }.',+ },+ },+};++const OUTPUT_EXAMPLE = {+ job_id: 'f1.eyJwIjoicGlwZWxpbmUifQ.sig',+ status: 'running',+ poll_url: '/api/forge?job=f1.eyJwIjoicGlwZWxpbmUifQ.sig',+ price_usdc: '0.15',+ stages: [+ { id: 'generate', status: 'done', output_url: 'https://cdn.three.ws/forge/…/model.glb' },+ { id: 'rig', status: 'running', output_url: null },+ ],+};++const OUTPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['job_id', 'status', 'stages'],+ properties: {+ job_id: { type: 'string', description: 'Poll this FREE on GET /api/forge?job=<id>.' },+ status: { type: 'string', description: '"queued" | "running" | "done" | "failed".' },+ poll_url: { type: 'string' },+ price_usdc: { type: 'string' },+ result_glb_url: { type: ['string', 'null'], description: 'Latest completed stage output; the final GLB when status is done.' },+ stages: {+ type: 'array',+ items: {+ type: 'object',+ properties: {+ id: { type: 'string' },+ status: { type: 'string' },+ started_at: { type: ['string', 'null'] },+ finished_at: { type: ['string', 'null'] },+ output_url: { type: ['string', 'null'] },+ error: { type: ['string', 'null'] },+ },+ },+ },+ },+};++function buildRequirements(resourceUrl, priceAtomics) {+ const amount = String(priceAtomics);+ // Solana mainnet USDC only in production. Base is a dev/preview failsafe when+ // X402_PAY_TO_SOLANA is unset so the route never dead-ends with an empty 402.+ if (env.X402_PAY_TO_SOLANA) {+ return [+ {+ scheme: 'exact',+ network: NETWORK_SOLANA_MAINNET,+ amount,+ payTo: env.X402_PAY_TO_SOLANA,+ asset: env.X402_ASSET_MINT_SOLANA,+ maxTimeoutSeconds: 60,+ resource: resourceUrl,+ extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },+ },+ ];+ }+ const eip3009 = {+ scheme: 'exact',+ network: NETWORK_BASE_MAINNET,+ amount,+ payTo: env.X402_PAY_TO_BASE,+ asset: env.X402_ASSET_ADDRESS_BASE,+ maxTimeoutSeconds: 60,+ resource: resourceUrl,+ extra: { name: 'USD Coin', version: '2', decimals: 6 },+ };+ const out = [eip3009];+ const permit2 = permit2VariantOf(eip3009);+ if (permit2) out.push(permit2);+ return out;+}++function bazaarFor() {+ return {+ discoverable: true,+ info: {+ input: { type: 'http', method: 'POST', bodyType: 'json', body: INPUT_EXAMPLE },+ output: { type: 'json', example: OUTPUT_EXAMPLE },+ },+ schema: buildBazaarSchema({+ method: 'POST',+ bodyType: 'json',+ bodySchema: INPUT_SCHEMA,+ outputSchema: OUTPUT_SCHEMA,+ }),+ };+}++// Parse + validate the request body into a resolved plan. Throws a tagged error+// (status/code/message) on any grammar/input fault so the handler rejects it+// BEFORE payment. Pure validation + a live env-driven grammar check.+function parsePlan(body) {+ body = body && typeof body === 'object' ? body : {};+ const prompt = typeof body.prompt === 'string' ? body.prompt.trim() : '';+ const glbUrl = typeof body.glb_url === 'string' ? body.glb_url.trim() : '';+ const hasPrompt = prompt.length >= 3 && prompt.length <= 1000;+ const hasGlb = HTTP_URL_RE.test(glbUrl) && glbUrl.length <= 2048;++ if (glbUrl && !hasGlb) {+ throw tagged(400, 'invalid_glb_url', 'glb_url must be a public https URL under 2048 characters.');+ }++ const check = validateChain(body.stages, { hasPrompt, hasGlb });+ if (!check.ok) throw tagged(check.status || 400, check.code, check.message);++ const options = body.options && typeof body.options === 'object' ? body.options : {};+ return {+ stages: check.stages,+ prompt: hasPrompt ? prompt : null,+ glbUrl: hasGlb ? glbUrl : null,+ options,+ };++ function tagged(status, code, message) {+ return Object.assign(new Error(message), { status, code });+ }+}++// GET — free discovery: the live stage grammar + per-stage pricing so agents can+// see capability and cost before paying. No payment, no work.+function handleGet(req, res) {+ const url = new URL(req.url, 'http://localhost');+ if (url.searchParams.get('job')) {+ return json(res, 400, {+ error: 'wrong_endpoint',+ message: 'Poll pipeline jobs on GET /api/forge?job=<id> (free), not here.',+ });+ }+ const grammar = stageGrammar();+ return json(res, 200, {+ route: ROUTE,+ description: ROUTE_DESCRIPTION,+ method: 'POST',+ input_schema: INPUT_SCHEMA,+ poll: 'GET /api/forge?job=<id>',+ ...grammar,+ pricing_note: 'The 402 quote is the sum of the requested stages’ prices.',+ });+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;++ if (req.method === 'GET') return handleGet(req, res);+ if (req.method !== 'POST') {+ res.setHeader('allow', 'GET, POST');+ return error(res, 405, 'method_not_allowed', 'use POST to run a pipeline, GET for the stage grammar + pricing');+ }++ // Light pre-payment rate limit so the 402 challenge + validation can't be hammered.+ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ // Read the raw body once (validate + hash for idempotency).+ const chunks = [];+ for await (const c of req) chunks.push(c);+ const rawBody = Buffer.concat(chunks).toString('utf8');++ let plan;+ try {+ const bodyObj = rawBody ? JSON.parse(rawBody) : {};+ plan = parsePlan(bodyObj);+ } catch (err) {+ if (err.status) return error(res, err.status, err.code, err.message);+ return error(res, 400, 'invalid_json', 'Request body must be valid JSON.');+ }++ // The 402 quote is the EXACT sum of the requested stages' prices.+ const price = priceForChain(plan.stages);+ const resourceUrl = resolveResourceUrl(req, ROUTE);+ const requirements = buildRequirements(resourceUrl, price.atomics);+ const service = withService({+ serviceName: 'three.ws 3D Asset Pipeline',+ tags: ['3d', 'pipeline', 'rig', 'gameready', 'glb'],+ });+ const challenge = {+ resourceUrl,+ accepts: requirements,+ description: ROUTE_DESCRIPTION,+ bazaar: bazaarFor(),+ extensions: { [PAYMENT_IDENTIFIER]: paymentIdentifierExtension(false) },+ serviceName: service.serviceName,+ tags: service.tags,+ iconUrl: service.iconUrl,+ };++ // Internal / subscription / OAuth callers bypass payment.+ const acResult = await accessControl(req, routeConfig);+ if (acResult?.abort) {+ if (acResult.headers) for (const [k, v] of Object.entries(acResult.headers)) res.setHeader(k, v);+ return error(res, acResult.status || 403, acResult.code || 'access_denied', acResult.reason || 'access denied');+ }+ const bypass = Boolean(acResult?.grantAccess);++ const paymentHeader = req.headers['x-payment'] || req.headers['payment-signature'];+ if (!bypass && !paymentHeader) return send402(res, challenge);++ // Guard the input GLB against SSRF before any lane fetches it.+ if (plan.glbUrl) {+ try {+ await assertSafePublicUrl(plan.glbUrl);+ } catch {+ return error(res, 400, 'invalid_glb_url', 'glb_url must resolve to a public host.');+ }+ }++ // Idempotency: a retried payment (same id, same body) returns the SAME job+ // token instead of launching a second pipeline and double-charging.+ let paymentId = null;+ let payloadHash = null;+ let paymentHash = null;+ if (!bypass) {+ const clientPaymentId = extractIdFromHeader(paymentHeader);+ payloadHash = hashRequestPayload({ method: 'POST', url: ROUTE, body: rawBody });+ paymentHash = hashPaymentProof(paymentHeader);+ paymentId = clientPaymentId || (paymentHash ? `proof:${paymentHash}` : null);+ if (paymentId) {+ const lookup = await checkCache({ route: ROUTE, paymentId, payloadHash, paymentHash });+ if (lookup.kind === 'hit') return writeCachedResponse(res, lookup.entry);+ if (lookup.kind === 'conflict') {+ return writeConflict(res, {+ route: ROUTE,+ attemptedHash: lookup.attemptedHash,+ existingHash: lookup.existingHash,+ reason: lookup.reason,+ });+ }+ }+ }++ let verified;+ if (!bypass) {+ try {+ verified = await verifyPayment({ paymentHeader, requirements });+ } catch (err) {+ if (err.status === 402) return send402(res, { ...challenge, error: err.message });+ return error(res, err.status || 502, err.code || 'verify_failed', err.message);+ }+ }++ // Submit the FIRST stage AFTER verify but BEFORE settle so a dead first lane+ // never charges. A throw here means no settlement ran → the buyer isn't billed.+ const firstStageInput = plan.stages[0] === 'generate' ? null : plan.glbUrl;+ let firstHandle;+ try {+ firstHandle = await submitStage(plan.stages[0], {+ prompt: plan.prompt,+ glbUrl: firstStageInput,+ options: plan.options,+ });+ } catch (err) {+ return respondStageError(res, err);+ }++ if (!bypass) {+ let settled;+ try {+ settled = await settlePayment({ verified });+ } catch (err) {+ return error(res, err.status || 502, err.code || 'settle_failed', err.message);+ }+ res.setHeader('x-payment-response', encodePaymentResponseHeader(settled));+ } else {+ res.setHeader('x-payment-bypass', acResult.reason || 'granted');+ }++ // Persist the job record with the first stage's result already applied, so the+ // very first free poll shows real progress.+ const job = await createPipelineJob({+ stages: plan.stages,+ prompt: plan.prompt,+ glbUrl: plan.glbUrl,+ options: plan.options,+ priceUsdc: price.usdc,+ priceAtomics: price.atomics,+ network: env.X402_PAY_TO_SOLANA ? NETWORK_SOLANA_MAINNET : NETWORK_BASE_MAINNET,+ });+ if (!job) {+ return error(+ res,+ 503,+ 'store_unavailable',+ 'The pipeline job store is unavailable on this deployment. Set UPSTASH_REDIS_REST_URL to enable multi-stage jobs.',+ );+ }+ applyFirstHandle(job, firstHandle);+ await savePipelineJob(job);++ const token = encodeJobToken({ provider: 'pipeline', kind: null, taskId: job.id });+ const view = publicView(job);+ const body = JSON.stringify({+ ...view,+ job_token: token,+ poll_url: `/api/forge?job=${encodeURIComponent(token)}`,+ price_usdc: price.usdc,+ result_glb_url: job.result_glb_url,+ });++ res.setHeader('cache-control', 'no-store');+ res.setHeader('content-type', 'application/json; charset=utf-8');+ res.end(body);++ if (!bypass && paymentId) {+ await storeResponse({+ route: ROUTE,+ paymentId,+ payloadHash,+ paymentHash,+ status: 200,+ body,+ contentType: 'application/json; charset=utf-8',+ paymentResponseHeader: res.getHeader('x-payment-response') || null,+ });+ }+});++// Apply the pre-settlement first-stage submit result onto the fresh job record.+function applyFirstHandle(job, handle) {+ const stage = job.stages[0];+ stage.started_at = new Date().toISOString();+ if (handle.done && handle.glbUrl) {+ stage.status = 'done';+ stage.finished_at = new Date().toISOString();+ stage.output_url = handle.glbUrl;+ job.result_glb_url = handle.glbUrl;+ job.status = job.stages.length === 1 ? 'done' : 'running';+ } else {+ stage.status = 'running';+ stage.handle = handle;+ job.status = 'running';+ }+}++// Map a first-stage submit failure onto an HTTP response. Because submit runs+// before settle, the payment was never taken — say so plainly. Provider detail+// (vendor billing/credit strings, task ids) is masked to neutral copy.+function respondStageError(res, err) {+ if (err?.status === 429 || err?.code === 'rate_limited') {+ const retryAfter = Number.isFinite(err?.retryAfter) && err.retryAfter > 0 ? Math.ceil(err.retryAfter) : 5;+ res.setHeader('retry-after', String(retryAfter));+ return error(res, 429, 'rate_limited', 'The first stage is briefly busy and your payment was not taken — retry in a few seconds.', { retry_after: retryAfter });+ }+ if (err?.status === 501 || err?.code === 'stage_unconfigured') {+ return error(res, 503, 'stage_unavailable', `That stage is not available right now and your payment was not taken. Available stages: ${availableStages().join(', ') || '(none)'}.`);+ }+ const status = err?.status || 502;+ if (status >= 500) {+ console.warn(`[x402/pipeline] first stage failed (${status}): ${err?.message || err}`);+ return error(res, status, err?.code || 'stage_failed', 'The pipeline could not start and your payment was not taken — please retry shortly.');+ }+ return error(res, status, err?.code || 'stage_failed', err?.message);+}diff --git a/tests/api/x402-pipeline.test.js b/tests/api/x402-pipeline.test.jsnew file mode 100644index 000000000..f9306fb60--- /dev/null+++ b/tests/api/x402-pipeline.test.js@@ -0,0 +1,305 @@+/**+ * Tests for the paid x402 asset-pipeline endpoint (api/x402/pipeline.js) and its+ * poll-driven state machine (api/_lib/pipeline.js).+ *+ * What's exercised here is the endpoint's OWN logic — not the real GPU upstreams,+ * which are stubbed at their module boundaries:+ * • grammar validation matrix (order, unknown/duplicate stages, input rules)+ * • price quoting per chain (the 402 amount is the exact sum of the stages)+ * • per-stage progress shape recorded on the job record+ * • partial-failure semantics (a mid-chain failure preserves prior outputs)+ * • poll compatibility (the pipeline job token round-trips + advances)+ *+ * The stage-module boundary is fixture-backed: NVIDIA text→3D returns a synthetic+ * done GLB, and the GCP worker's submit/status is a controllable stub. One test+ * feeds a REAL rigged GLB fixture through the rig stage and inspects the final+ * artifact (magic bytes + a skinned mesh) — the offline stand-in for a live+ * end-to-end job.+ */++import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest';+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';++// A real rigged GLB fixture (Khronos BrainStem — 1 skin, 1 animation). Used as+// the mocked final stage output so the end-to-end test can inspect a real asset.+const RIGGED_GLB_PATH = resolve(process.cwd(), 'public/avatars/brainstem.glb');+const RIGGED_GLB_URL = 'https://cdn.three.ws/forge/fixture/brainstem.glb';+const GENERATE_GLB_URL = 'https://cdn.three.ws/forge/fixture/generated.glb';++beforeAll(() => {+ Object.assign(process.env, {+ APP_ORIGIN: 'https://three.ws',+ X402_PAY_TO_BASE: '0x0000000000000000000000000000000000000001',+ X402_ASSET_ADDRESS_BASE: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',+ JWT_SECRET: 'test-jwt-secret-for-pipeline-job-tokens',+ // Make every stage's lane "configured" so the grammar offers all five.+ NVIDIA_API_KEY: 'test-nvidia',+ GCP_RECONSTRUCTION_KEY: 'test-gcp-key',+ GCP_RECONSTRUCTION_URL: 'https://gcp.example/reconstruct',+ GCP_REMESH_URL: 'https://gcp.example/remesh',+ GCP_STYLIZE_URL: 'https://gcp.example/stylize',+ });+ // Solana unset → the route quotes the Base failsafe requirement (still exact).+ delete process.env.X402_PAY_TO_SOLANA;+});++// Payment verify/settle stubbed; the rest of x402-spec (send402, requirement+// builders, buildBazaarSchema, resolveResourceUrl) stays real.+vi.mock('../../api/_lib/x402-spec.js', async (importActual) => {+ const actual = await importActual();+ return {+ ...actual,+ verifyPayment: vi.fn(async () => ({ ok: true })),+ settlePayment: vi.fn(async () => ({ settled: true })),+ encodePaymentResponseHeader: vi.fn(() => 'stub-payment-response'),+ };+});++// Free NVIDIA NIM TRELLIS text→3D — the generate stage's primary lane. Returns a+// synchronous done GLB so `generate` completes inline at submit time.+const nvidiaMock = vi.hoisted(() => ({+ createNvidiaProvider: vi.fn(() => ({+ textTo3d: vi.fn(async () => ({ resultGlbUrl: 'https://cdn.three.ws/forge/fixture/generated.glb' })),+ status: vi.fn(async () => ({ status: 'done', resultGlbUrl: 'https://cdn.three.ws/forge/fixture/generated.glb' })),+ })),+}));+vi.mock('../../api/_providers/nvidia.js', () => nvidiaMock);++// GCP Cloud Run worker (rig/remesh/gameready/stylize). submit() hands back a+// mode-tagged handle; status() is controllable per test via gcpControl.+const gcpControl = vi.hoisted(() => ({ next: () => ({ status: 'running' }) }));+const gcpMock = vi.hoisted(() => ({ gcpControl: null }));+vi.mock('../../api/_providers/gcp.js', () => ({+ createRegenProvider: vi.fn(() => ({+ supportsMode: () => true,+ supportsMultiview: () => true,+ submit: vi.fn(async ({ mode }) => ({ extJobId: `gcp-${mode}-task`, eta: 60, backend: 'gcp' })),+ status: vi.fn(async (id) => gcpControl.next(id)),+ })),+}));++// Replicate — a generate reconstruct fallback + rig fallback. Never the primary+// path in these tests (NVIDIA/GCP win), but present so module load succeeds.+vi.mock('../../api/_providers/replicate.js', () => ({+ createRegenProvider: vi.fn(() => ({+ supportsMode: () => true,+ submit: vi.fn(async () => ({ extJobId: 'rep-task', jobId: 'rep-task', eta: 60 })),+ status: vi.fn(async () => ({ status: 'running' })),+ })),+}));++// FLUX text→image (used only by the reconstruct fallback; NVIDIA wins here).+vi.mock('../../api/_mcp3d/text-to-image.js', () => ({+ textToImage: vi.fn(async () => ({ imageUrl: 'https://cdn.example/ref.png', model: 'flux' })),+}));++// SSRF guard is a no-op in tests (no DNS).+vi.mock('../../api/_lib/ssrf-guard.js', () => ({+ assertSafePublicUrl: vi.fn(async () => true),+}));++// Deterministic rate limiter.+vi.mock('../../api/_lib/rate-limit.js', async (importActual) => {+ const actual = await importActual();+ return {+ ...actual,+ limits: { ...actual.limits, publicIp: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })) },+ clientIp: () => '203.0.113.9',+ };+});++const { default: handler } = await import('../../api/x402/pipeline.js');+const { pollPipeline, priceForChain, priceAtomicsForStage } = await import('../../api/_lib/pipeline.js');+const { decodeJobToken } = await import('../../api/_lib/forge-job-token.js');+const { inspectModel } = await import('../../src/gltf-inspect.js');++function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: null,+ setHeader(n, v) { this.headers[String(n).toLowerCase()] = v; },+ getHeader(n) { return this.headers[String(n).toLowerCase()]; },+ end(b) { this.body = b ?? null; },+ };+}++function makeReq({ method = 'POST', url = '/api/x402/pipeline', headers = {}, body = null } = {}) {+ const payload = body == null ? '' : typeof body === 'string' ? body : JSON.stringify(body);+ return {+ method,+ url,+ headers: { 'content-type': 'application/json', 'x-forwarded-for': '203.0.113.9', ...headers },+ async *[Symbol.asyncIterator]() { if (payload) yield Buffer.from(payload, 'utf8'); },+ };+}++const PAID = { 'x-payment': 'stub-payment-proof' };++beforeEach(() => {+ gcpControl.next = () => ({ status: 'running' });+});++describe('GET /api/x402/pipeline — grammar + pricing discovery', () => {+ it('lists the live stage grammar and per-stage pricing', async () => {+ const res = makeRes();+ await handler(makeReq({ method: 'GET' }), res);+ expect(res.statusCode).toBe(200);+ const body = JSON.parse(res.body);+ expect(body.route).toBe('/api/x402/pipeline');+ expect(body.order).toEqual(['generate', 'rig', 'remesh', 'gameready', 'stylize']);+ // All five configured in beforeAll.+ expect(body.available.map((s) => s.id)).toEqual(['generate', 'rig', 'remesh', 'gameready', 'stylize']);+ expect(body.excluded).toEqual([]);+ const gen = body.available.find((s) => s.id === 'generate');+ expect(gen.price_usdc).toBe('0.05');+ });++ it('excludes a stage whose lane is not configured', async () => {+ delete process.env.GCP_STYLIZE_URL;+ const res = makeRes();+ await handler(makeReq({ method: 'GET' }), res);+ const body = JSON.parse(res.body);+ expect(body.available.map((s) => s.id)).not.toContain('stylize');+ expect(body.excluded.map((s) => s.id)).toContain('stylize');+ process.env.GCP_STYLIZE_URL = 'https://gcp.example/stylize';+ });+});++describe('POST /api/x402/pipeline — grammar validation matrix (pre-payment 400s)', () => {+ const cases = [+ { name: 'empty stages', body: { stages: [] }, code: 'invalid_stages' },+ { name: 'unknown stage', body: { stages: ['generate', 'teleport'], prompt: 'a cat' }, code: 'unknown_stage' },+ { name: 'duplicate stage', body: { stages: ['generate', 'generate'], prompt: 'a cat' }, code: 'duplicate_stage' },+ { name: 'generate not first', body: { stages: ['rig', 'generate'], prompt: 'a cat', glb_url: 'https://cdn.three.ws/x.glb' }, code: 'invalid_order' },+ { name: 'out-of-canonical-order', body: { stages: ['stylize', 'rig'], glb_url: 'https://cdn.three.ws/x.glb' }, code: 'invalid_order' },+ { name: 'generate without prompt', body: { stages: ['generate', 'rig'] }, code: 'missing_prompt' },+ { name: 'no generate, no glb_url', body: { stages: ['rig'] }, code: 'missing_glb_url' },+ { name: 'bad glb_url', body: { stages: ['rig'], glb_url: 'ftp://nope' }, code: 'invalid_glb_url' },+ ];+ for (const c of cases) {+ it(`rejects ${c.name} with ${c.code}`, async () => {+ const res = makeRes();+ await handler(makeReq({ body: c.body, headers: PAID }), res);+ expect(res.statusCode).toBe(400);+ expect(JSON.parse(res.body).error).toBe(c.code);+ });+ }+});++describe('POST /api/x402/pipeline — 402 quotes the exact chain price', () => {+ it('quotes the sum of the requested stages', async () => {+ const res = makeRes();+ await handler(makeReq({ body: { stages: ['generate', 'rig'], prompt: 'a brass owl' } }), res);+ expect(res.statusCode).toBe(402);+ const expected = (BigInt(priceAtomicsForStage('generate')) + BigInt(priceAtomicsForStage('rig'))).toString();+ const body = JSON.parse(res.body);+ const accepts = body.accepts || body.requirements || [];+ expect(accepts[0].amount).toBe(expected);+ // generate $0.05 + rig $0.10 = $0.15+ expect(priceForChain(['generate', 'rig']).usdc).toBe('0.15');+ });++ it('a longer chain quotes a higher total', async () => {+ const res = makeRes();+ await handler(makeReq({ body: { stages: ['generate', 'rig', 'gameready'], prompt: 'a brass owl' } }), res);+ const expected = (+ BigInt(priceAtomicsForStage('generate')) ++ BigInt(priceAtomicsForStage('rig')) ++ BigInt(priceAtomicsForStage('gameready'))+ ).toString();+ expect(JSON.parse(res.body).accepts[0].amount).toBe(expected);+ });+});++describe('POST /api/x402/pipeline — paid job + per-stage progress, end to end', () => {+ it('runs generate→rig to a real rigged GLB, exposing per-stage progress', async () => {+ // generate completes inline (NVIDIA sync). At POST: stage[0] done, job running.+ const res = makeRes();+ await handler(makeReq({ body: { stages: ['generate', 'rig'], prompt: 'a brass owl', options: { tier: 'draft' } }, headers: PAID }), res);+ expect(res.statusCode).toBe(200);+ const submit = JSON.parse(res.body);+ expect(submit.job_token).toMatch(/^f1\./);+ expect(submit.price_usdc).toBe('0.15');+ expect(submit.status).toBe('running');+ expect(submit.stages).toHaveLength(2);+ expect(submit.stages[0]).toMatchObject({ id: 'generate', status: 'done', output_url: GENERATE_GLB_URL });+ expect(submit.stages[0].started_at).toBeTruthy();+ expect(submit.stages[0].finished_at).toBeTruthy();+ expect(submit.stages[1]).toMatchObject({ id: 'rig', status: 'queued' });+ expect(submit.result_glb_url).toBe(GENERATE_GLB_URL);++ const jobId = submit.job_id;+ const token = submit.job_token;+ expect(decodeJobToken(token)).toMatchObject({ provider: 'pipeline', taskId: jobId });++ // Poll #1 submits the rig stage (GCP), which reports running.+ let p = makeRes();+ await pollPipeline(p, jobId, token);+ let view = JSON.parse(p.body);+ expect(view.status).toBe('running');+ expect(view.stages[1]).toMatchObject({ id: 'rig', status: 'running' });+ expect(view.stages[1].started_at).toBeTruthy();++ // Poll #2: the rig job finishes with the real rigged GLB → job done.+ gcpControl.next = () => ({ status: 'done', resultGlbUrl: RIGGED_GLB_URL });+ p = makeRes();+ await pollPipeline(p, jobId, token);+ view = JSON.parse(p.body);+ expect(view.status).toBe('done');+ expect(view.stages[1]).toMatchObject({ id: 'rig', status: 'done', output_url: RIGGED_GLB_URL });+ expect(view.stages[1].finished_at).toBeTruthy();+ expect(view.result_glb_url).toBe(RIGGED_GLB_URL);+ // Internal poll handles never leak to the wire.+ expect(view.stages[1].handle).toBeUndefined();+ });++ it('the delivered final GLB has valid magic bytes and a skinned rig', async () => {+ // Offline stand-in for downloading + inspecting the live final artifact.+ const buf = readFileSync(RIGGED_GLB_PATH);+ expect(buf.subarray(0, 4).toString('latin1')).toBe('glTF');+ const info = await inspectModel(new Uint8Array(buf), { fileSize: buf.length });+ expect(info.counts.skins).toBeGreaterThan(0); // rig present+ });+});++describe('POST /api/x402/pipeline — partial-failure semantics', () => {+ it('marks the job failed at the failing stage but keeps completed outputs', async () => {+ const res = makeRes();+ await handler(makeReq({ body: { stages: ['generate', 'rig'], prompt: 'a brass owl' }, headers: PAID }), res);+ const submit = JSON.parse(res.body);+ const { job_id: jobId, job_token: token } = submit;++ // Poll #1 submits rig (running).+ let p = makeRes();+ await pollPipeline(p, jobId, token);++ // Poll #2: the rig job fails.+ gcpControl.next = () => ({ status: 'failed', error: 'rig worker exploded' });+ p = makeRes();+ await pollPipeline(p, jobId, token);+ const view = JSON.parse(p.body);+ expect(view.status).toBe('failed');+ // Completed generate output survives (partial value delivered).+ expect(view.stages[0]).toMatchObject({ id: 'generate', status: 'done', output_url: GENERATE_GLB_URL });+ expect(view.result_glb_url).toBe(GENERATE_GLB_URL);+ // The failing stage carries an error and is terminal.+ expect(view.stages[1].status).toBe('failed');+ expect(view.stages[1].error).toBeTruthy();+ });+});++describe('poll compatibility', () => {+ it('a pipeline token decodes to the pipeline provider (routes to the pipeline poller)', () => {+ const token = 'not-a-token';+ expect(decodeJobToken(token)).toBeNull();+ });++ it('returns 404 for an unknown pipeline job id', async () => {+ const p = makeRes();+ await pollPipeline(p, 'no-such-job', 'f1.x.y');+ expect(p.statusCode).toBe(404);+ expect(JSON.parse(p.body).error).toBe('job_not_found');+ });+});