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): sell each 3D pipeline stage as its own priced x402 resource
nichce5bb4c04143
diff --git a/api/x402/pipeline-gameready.js b/api/x402/pipeline-gameready.jsnew file mode 100644index 000000000..4cc9f665c--- /dev/null+++ b/api/x402/pipeline-gameready.js@@ -0,0 +1,185 @@+// POST /api/x402/pipeline-gameready { glb_url, topology?, poly_budget?, texture_size? }+//+// 3D Asset Pipeline — Game-Ready stage. Pay $0.03 USDC and get back an+// engine-ready GLB: the mesh is retopologized to a fixed polygon budget (quad+// QuadriFlow or silhouette-preserving low-poly) and its PBR texture re-baked onto+// the new topology, so it drops straight into a real-time engine without blowing+// the frame budget. Input: a public GLB URL + a poly budget. Output: a durable+// first-party GLB URL. One payment, one game-ready mesh.+//+// Opinionated preset over the same workers/remesh Cloud Run service the free+// /api/forge-gameready endpoint drives (topology → retopo mode, poly_budget →+// target faces). Synchronous pay-per-call twin: submit → poll → validate → persist+// → return the URL. 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-gameready';+const SLUG = 'pipeline-gameready';++const VALID_TOPOLOGIES = new Set(['quad', 'tri']);+const VALID_TEXTURE_SIZES = new Set([1024, 2048]);+// quad → field-aligned QuadriFlow retopology; tri → silhouette-preserving+// quadric low-poly with UV re-unwrap + texture re-bake. Both are real worker+// pipelines (workers/remesh); neither is faked here.+const TOPOLOGY_TO_MODE = { quad: 'quad', tri: 'lowpoly' };+const POLY_MIN = 1_000;+const POLY_MAX = 500_000;++const DESCRIPTION =+ '3D Asset Pipeline — Game-Ready: pay $0.03 USDC to make a GLB engine-ready. ' ++ 'The mesh is retopologized to a fixed polygon budget (quad QuadriFlow or ' ++ 'silhouette-preserving low-poly) with PBR re-baked onto the new topology, so it ' ++ 'drops into a real-time engine within budget. POST a public glb_url + ' ++ 'poly_budget; get back a durable first-party GLB URL. 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.',+ },+ topology: {+ type: 'string',+ enum: [...VALID_TOPOLOGIES],+ default: 'quad',+ description: 'quad = QuadriFlow field-aligned retopo; tri = silhouette-preserving low-poly.',+ },+ poly_budget: {+ type: 'integer',+ minimum: POLY_MIN,+ maximum: POLY_MAX,+ default: 15_000,+ description: 'Target triangle budget for the engine-ready output.',+ },+ texture_size: {+ type: 'integer',+ enum: [...VALID_TEXTURE_SIZES],+ default: 1_024,+ description: 'Resolution of the re-baked PBR 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: 'gameready' },+ input_url: { type: 'string', format: 'uri' },+ output_url: { type: 'string', format: 'uri', description: 'The engine-ready GLB.' },+ bytes: { type: ['integer', 'null'] },+ persisted: { type: 'boolean' },+ topology: { type: 'string' },+ poly_budget: { type: 'integer' },+ 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/prop.glb', topology: 'quad', poly_budget: 12000 } },+ output: {+ type: 'json',+ example: {+ stage: 'gameready',+ input_url: 'https://three.ws/forge/prop.glb',+ output_url: 'https://cdn.three.ws/x402-pipeline/gameready/abc123.glb',+ bytes: 640_220,+ persisted: true,+ topology: 'quad',+ poly_budget: 12_000,+ face_count: 12_000,+ quad_ratio: 0.97,+ 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 - Game-Ready',+ tags: ['3d', 'gameready', '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 topology = VALID_TOPOLOGIES.has(body?.topology) ? body.topology : 'quad';+ const mode = TOPOLOGY_TO_MODE[topology];+ const polyBudget = Math.max(POLY_MIN, Math.min(POLY_MAX, Math.round(Number(body?.poly_budget) || 15_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: mode,+ operation: 'full',+ target_faces: polyBudget,+ texture_size: textureSize,+ output_format: 'glb',+ },+ });++ const key = await stageObjectKey({ stage: 'gameready', sourceUrl: glbUrl, ext: 'glb' });+ const out = await persistStageOutput({+ resultUrl: result.resultGlbUrl,+ key,+ contentType: 'model/gltf-binary',+ kind: 'glb',+ });++ return {+ stage: 'gameready',+ input_url: glbUrl,+ output_url: out.url,+ bytes: out.bytes,+ persisted: out.persisted,+ topology,+ poly_budget: polyBudget,+ 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-rembg.js b/api/x402/pipeline-rembg.jsnew file mode 100644index 000000000..9a365b458--- /dev/null+++ b/api/x402/pipeline-rembg.js@@ -0,0 +1,142 @@+// POST /api/x402/pipeline-rembg { image_url, model? }+//+// 3D Asset Pipeline — Background Removal stage. Pay $0.01 USDC and get back the+// input image with its background removed (transparent PNG) — the clean reference+// view that image→3D reconstruction needs to avoid baking a room into the mesh.+// Input: a public image URL. Output: a durable first-party PNG URL. One payment,+// one cut-out image.+//+// Runs the same workers/rembg Cloud Run service the free /api/forge-rembg+// endpoint drives — its synchronous, pay-per-call twin: submit → poll → validate+// → persist → return the URL. Any worker/env/validation failure throws BEFORE+// settlement, so a buyer is never charged for a stage that didn't produce a valid+// image.++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-rembg';+const SLUG = 'pipeline-rembg';++const VALID_MODELS = new Set(['rmbg2', 'u2net', 'isnet', 'u2net_human_seg', 'silueta']);++const DESCRIPTION =+ '3D Asset Pipeline — Background Removal: pay $0.01 USDC to strip the background ' ++ 'from an image, returning a transparent PNG. This is the clean reference view ' ++ 'image→3D reconstruction needs so it never bakes a room into the mesh. POST a ' ++ 'public image_url; get back a durable first-party PNG URL. Pay autonomously in ' ++ 'USDC on Solana mainnet.';++export const INPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['image_url'],+ properties: {+ image_url: {+ type: 'string',+ format: 'uri',+ description: 'Public HTTPS URL of the source image (PNG, JPEG, WEBP, or GIF).',+ },+ model: {+ type: 'string',+ enum: [...VALID_MODELS],+ default: 'rmbg2',+ description: 'Segmentation model — rmbg2 (default, general), u2net_human_seg (people), isnet, u2net, silueta.',+ },+ },+};++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: 'rembg' },+ input_url: { type: 'string', format: 'uri' },+ output_url: { type: 'string', format: 'uri', description: 'The cut-out transparent PNG.' },+ bytes: { type: ['integer', 'null'] },+ persisted: { type: 'boolean' },+ model: { type: 'string' },+ },+};++export const BAZAAR = {+ discoverable: true,+ info: {+ input: { type: 'http', method: 'POST', bodyType: 'json', body: { image_url: 'https://three.ws/uploads/photo.jpg', model: 'rmbg2' } },+ output: {+ type: 'json',+ example: {+ stage: 'rembg',+ input_url: 'https://three.ws/uploads/photo.jpg',+ output_url: 'https://cdn.three.ws/x402-pipeline/rembg/abc123.png',+ bytes: 284_112,+ persisted: true,+ model: 'rmbg2',+ },+ },+ },+ schema: buildBazaarSchema({+ method: 'POST',+ bodyType: 'json',+ bodySchema: INPUT_SCHEMA,+ outputSchema: OUTPUT_SCHEMA,+ }),+};++export default paidEndpoint({+ route: ROUTE,+ method: 'POST',+ priceAtomics: priceFor(SLUG, '10000'), // $0.01 USDC+ networks: ['solana', 'base'],+ description: DESCRIPTION,+ bazaar: BAZAAR,+ service: withService({+ serviceName: 'three.ws Pipeline - RemBG',+ tags: ['image', 'rembg', 'cutout', 'segmentation', 'pipeline'],+ }),+ requiredScope: 'x402:bypass',+ accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),++ async handler({ req }) {+ const body = await readJsonBody(req);+ const imageUrl = await validateAssetUrl(body?.image_url, 'image_url');+ await sniffRemoteAsset(imageUrl, 'image');++ const model = VALID_MODELS.has(body?.model) ? body.model : 'rmbg2';++ const result = await runStageJob({+ mode: 'rembg',+ sourceUrl: imageUrl,+ params: { model },+ });++ const key = await stageObjectKey({ stage: 'rembg', sourceUrl: imageUrl, ext: 'png' });+ const out = await persistStageOutput({+ resultUrl: result.resultImageUrl || result.resultGlbUrl,+ key,+ contentType: 'image/png',+ kind: 'image',+ });++ return {+ stage: 'rembg',+ input_url: imageUrl,+ output_url: out.url,+ bytes: out.bytes,+ persisted: out.persisted,+ model,+ };+ },+});diff --git a/api/x402/pipeline-remesh.js b/api/x402/pipeline-remesh.jsindex 678cbfe7d..1da8f5efa 100644--- a/api/x402/pipeline-remesh.js+++ b/api/x402/pipeline-remesh.js@@ -133,7 +133,7 @@ export default paidEndpoint({description: DESCRIPTION,bazaar: BAZAAR,service: withService({- serviceName: 'three.ws Pipeline — Remesh',+ serviceName: 'three.ws Pipeline - Remesh',tags: ['3d', 'remesh', 'retopology', 'glb', 'pipeline'],}),requiredScope: 'x402:bypass',diff --git a/api/x402/pipeline-rig.js b/api/x402/pipeline-rig.jsindex 0182ed4f8..3b1d48c88 100644--- a/api/x402/pipeline-rig.js+++ b/api/x402/pipeline-rig.js@@ -104,7 +104,7 @@ export default paidEndpoint({description: DESCRIPTION,bazaar: BAZAAR,service: withService({- serviceName: 'three.ws Pipeline — Rig',+ serviceName: 'three.ws Pipeline - Rig',tags: ['3d', 'rigging', 'skeleton', 'glb', 'pipeline'],}),requiredScope: 'x402:bypass',diff --git a/api/x402/pipeline-stylize.js b/api/x402/pipeline-stylize.jsnew file mode 100644index 000000000..e27a9c496--- /dev/null+++ b/api/x402/pipeline-stylize.js@@ -0,0 +1,164 @@+// POST /api/x402/pipeline-stylize { glb_url, style?, resolution? }+//+// 3D Asset Pipeline — Stylize stage. Pay $0.03 USDC and get back a geometrically+// restyled GLB: voxel, brick, Voronoi-shatter, or faceted low-poly filters that+// rebuild the mesh itself (not a shader), so the style survives export to any+// engine. Input: a public GLB URL + a style. Output: a durable first-party GLB+// URL. One payment, one stylized mesh.+//+// Runs the same workers/stylize Cloud Run service the free /api/forge-stylize+// endpoint drives — its synchronous, pay-per-call twin: submit → poll → validate+// → persist → return the URL. 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-stylize';+const SLUG = 'pipeline-stylize';++// Density bounds per filter — kept in lockstep with workers/stylize STYLE_CATALOG+// and api/forge-stylize.js.+const STYLE_BOUNDS = {+ voxel: { def: 32, min: 8, max: 96 },+ brick: { def: 24, min: 8, max: 64 },+ voronoi: { def: 48, min: 12, max: 120 },+ lowpoly: { def: 40, min: 8, max: 120 },+};++const DESCRIPTION =+ '3D Asset Pipeline — Stylize: pay $0.03 USDC to geometrically restyle a GLB. ' ++ 'Voxel, brick, Voronoi-shatter, or faceted low-poly filters that rebuild the ' ++ 'mesh itself (not a shader), so the look survives export to any engine. POST a ' ++ 'public glb_url + style; get back a durable first-party GLB URL. 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.',+ },+ style: {+ type: 'string',+ enum: Object.keys(STYLE_BOUNDS),+ default: 'voxel',+ description: 'Geometric filter to apply — voxel, brick, voronoi, or lowpoly.',+ },+ resolution: {+ type: 'integer',+ description: 'Style density (clamped to each filter\'s range). Higher = finer detail.',+ },+ },+};++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: 'stylize' },+ input_url: { type: 'string', format: 'uri' },+ output_url: { type: 'string', format: 'uri', description: 'The restyled GLB.' },+ bytes: { type: ['integer', 'null'] },+ persisted: { type: 'boolean' },+ style: { type: 'string' },+ resolution: { type: 'integer' },+ face_count: { type: ['integer', 'null'] },+ },+};++export const BAZAAR = {+ discoverable: true,+ info: {+ input: { type: 'http', method: 'POST', bodyType: 'json', body: { glb_url: 'https://three.ws/forge/statue.glb', style: 'voxel', resolution: 48 } },+ output: {+ type: 'json',+ example: {+ stage: 'stylize',+ input_url: 'https://three.ws/forge/statue.glb',+ output_url: 'https://cdn.three.ws/x402-pipeline/stylize/abc123.glb',+ bytes: 512_880,+ persisted: true,+ style: 'voxel',+ resolution: 48,+ face_count: 18_240,+ },+ },+ },+ 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 - Stylize',+ tags: ['3d', 'stylize', 'voxel', '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 style = STYLE_BOUNDS[body?.style] ? body.style : 'voxel';+ const bounds = STYLE_BOUNDS[style];+ const requested = Number(body?.resolution);+ const resolution = Number.isFinite(requested)+ ? Math.max(bounds.min, Math.min(bounds.max, Math.round(requested)))+ : bounds.def;++ const result = await runStageJob({+ mode: 'stylize',+ sourceUrl: glbUrl,+ params: { style, resolution, output_format: 'glb' },+ });++ const key = await stageObjectKey({ stage: 'stylize', sourceUrl: glbUrl, ext: 'glb' });+ const out = await persistStageOutput({+ resultUrl: result.resultGlbUrl,+ key,+ contentType: 'model/gltf-binary',+ kind: 'glb',+ });++ return {+ stage: 'stylize',+ input_url: glbUrl,+ output_url: out.url,+ bytes: out.bytes,+ persisted: out.persisted,+ style,+ resolution,+ face_count: typeof result.faceCount === 'number' ? result.faceCount : null,+ };+ },+});diff --git a/docs/3d-pipeline.md b/docs/3d-pipeline.mdnew file mode 100644index 000000000..b153989d1--- /dev/null+++ b/docs/3d-pipeline.md@@ -0,0 +1,172 @@+# The 3D Asset Pipeline (pay-per-stage over x402)++three.ws runs a full 3D asset pipeline — the same lanes the platform uses to turn+a prompt into a rigged, game-ready character. Every working stage is sold as its+own [x402](x402.md) resource: an AI agent pays a few cents in USDC, hands in a URL,+and gets back a finished asset URL. No API key, no account, no signup.++Nobody else in the x402 ecosystem offers this. The generation stage (text/image →+3D) is [`/api/x402/forge`](x402-endpoints.md); the stages below are what you do to+a mesh *after* it exists.++```+ generate → rig → remesh / gameready → stylize → deliver+ (forge) (skeleton) (topology + budget) (geometry) (GLB URL)+```++## Two ways to buy++1. **One stage at a time** — `POST /api/x402/pipeline-<stage>`. One payment buys+ one finished asset, returned inline as a durable first-party URL. This is the+ reference below.+2. **The whole chain in one call** — [`POST /api/x402/pipeline`](x402-endpoints.md).+ Submit an ordered chain (`generate → rig → remesh → gameready → stylize`); the+ 402 quote is the exact sum of the requested stages, and you poll the job free+ at `GET /api/forge?job=<id>` while it advances. Use this when you want the full+ pipeline without orchestrating each call yourself.++Both run on the same GCP Cloud Run workers (`workers/remesh`, `workers/stylize`,+`workers/rembg`, and the avatar-pipeline rig controller). A stage whose worker+isn't configured on a deployment returns `503 unconfigured` **before** settlement,+so a buyer is never charged for a stage that can't run.++## How a paid stage call works++Every `pipeline-*` route is a synchronous, pay-per-call endpoint:++1. You `POST` a JSON body with the source URL + options.+2. If you send no `X-PAYMENT` header, you get a `402` challenge quoting the price+ in USDC (Solana mainnet; Base when configured).+3. You settle and retry with `X-PAYMENT`. The server validates your input URL+ (SSRF-guarded, magic-byte sniffed), submits the worker job, polls it to+ completion, validates the output bytes, mirrors the result into first-party+ storage, and returns its URL.+4. **Any** failure — bad URL, wrong media type, worker error, timeout, corrupt+ output — throws *before* settlement. You keep your USDC and can retry.++Prices are env-overridable per the [pricing model](x402-endpoints.md#pricing-model)+(`X402_PRICE_<UPPER_SNAKE_SLUG>`).++## Stages++### Rig — `POST /api/x402/pipeline-rig` — $0.05++Infers a humanoid skeleton and binds it to a static mesh with skin weights, so the+model can walk, wave, and emote. **In:** a static GLB. **Out:** a rigged GLB.++```bash+# 1. Discover the price (unpaid request returns the 402 challenge)+curl -s -X POST https://three.ws/api/x402/pipeline-rig \+ -H 'content-type: application/json' \+ -d '{"glb_url":"https://three.ws/forge/character.glb","rig_type":"biped"}'++# 2. Pay with an x402 client (settles the 402 and retries automatically)+npx @x402/fetch POST https://three.ws/api/x402/pipeline-rig \+ --json '{"glb_url":"https://three.ws/forge/character.glb","rig_type":"biped"}'+# → { "stage":"rig", "output_url":"https://cdn.three.ws/x402-pipeline/rig/….glb", ... }+```++### Remesh — `POST /api/x402/pipeline-remesh` — $0.03++Retopologizes a mesh: triangle/quad/low-poly remeshing, repair, or decimation to a+target face count, with the texture re-baked onto the new topology. **In:** a GLB ++options. **Out:** a cleaned GLB with predictable topology.++```bash+npx @x402/fetch POST https://three.ws/api/x402/pipeline-remesh \+ --json '{"glb_url":"https://three.ws/forge/sample.glb","remesh_mode":"quad","target_faces":20000}'+# → { "stage":"remesh", "output_url":"…", "face_count":20000, "quad_ratio":0.98, "textured":true }+```++Options: `remesh_mode` (`triangle` | `quad` | `lowpoly`), `operation` (`full` |+`simplify` | `repair` | `convert`, triangle mode only), `target_faces`+(1,000–500,000), `texture_size` (512 | 1024 | 2048).++### Game-Ready — `POST /api/x402/pipeline-gameready` — $0.03++An opinionated engine-ready preset: retopologize to a fixed polygon budget (quad+QuadriFlow or silhouette-preserving low-poly) with PBR re-baked onto the new+topology, so the asset drops into a real-time engine within budget. **In:** a GLB ++`poly_budget`. **Out:** an engine-ready GLB.++```bash+npx @x402/fetch POST https://three.ws/api/x402/pipeline-gameready \+ --json '{"glb_url":"https://three.ws/forge/prop.glb","topology":"quad","poly_budget":12000}'+# → { "stage":"gameready", "output_url":"…", "poly_budget":12000, "quad_ratio":0.97 }+```++Options: `topology` (`quad` | `tri`), `poly_budget` (1,000–500,000), `texture_size`+(1024 | 2048).++### Stylize — `POST /api/x402/pipeline-stylize` — $0.03++Geometric restyle: voxel, brick, Voronoi-shatter, or faceted low-poly filters that+rebuild the mesh itself (not a shader), so the look survives export to any engine.+**In:** a GLB + `style`. **Out:** a restyled GLB.++```bash+npx @x402/fetch POST https://three.ws/api/x402/pipeline-stylize \+ --json '{"glb_url":"https://three.ws/forge/statue.glb","style":"voxel","resolution":48}'+# → { "stage":"stylize", "output_url":"…", "style":"voxel", "resolution":48 }+```++Options: `style` (`voxel` | `brick` | `voronoi` | `lowpoly`), `resolution`+(clamped per filter).++### Background Removal — `POST /api/x402/pipeline-rembg` — $0.01++Strips the background from an image, returning a transparent PNG — the clean+reference view image→3D reconstruction needs so it never bakes a room into the+mesh. **In:** an image (PNG/JPEG/WEBP/GIF). **Out:** a transparent PNG.++```bash+npx @x402/fetch POST https://three.ws/api/x402/pipeline-rembg \+ --json '{"image_url":"https://three.ws/uploads/photo.jpg","model":"rmbg2"}'+# → { "stage":"rembg", "output_url":"https://cdn.three.ws/x402-pipeline/rembg/….png" }+```++Options: `model` (`rmbg2` | `u2net` | `isnet` | `u2net_human_seg` | `silueta`).++## A full flow++Generate a mesh, then rig and optimize it — three paid calls, each output URL+feeding the next input:++```bash+# 1. Generate ($0.05 draft tier) → poll /api/forge?job=<id> for the GLB+FORGE=$(npx @x402/fetch POST https://three.ws/api/x402/forge \+ --json '{"prompt":"a brass steampunk owl, full body","tier":"draft"}')+GLB=$(echo "$FORGE" | jq -r '.glb_url')++# 2. Rig it ($0.05)+RIGGED=$(npx @x402/fetch POST https://three.ws/api/x402/pipeline-rig \+ --json "{\"glb_url\":\"$GLB\"}" | jq -r '.output_url')++# 3. Make it game-ready ($0.03)+npx @x402/fetch POST https://three.ws/api/x402/pipeline-gameready \+ --json "{\"glb_url\":\"$RIGGED\",\"poly_budget\":15000}"+```++## Operator configuration++Each stage advertises itself only when its worker is configured. Set, in the+platform environment:++| Stage | Env var | Worker |+| ----------- | ---------------------- | ----------------------------------- |+| rig | `GCP_RECONSTRUCTION_URL` | avatar-pipeline controller (`/rig`) |+| remesh | `GCP_REMESH_URL` | `workers/remesh` |+| gameready | `GCP_REMESH_URL` | `workers/remesh` |+| stylize | `GCP_STYLIZE_URL` | `workers/stylize` |+| rembg | `GCP_REMBG_URL` | `workers/rembg` |++All workers share the bearer secret `GCP_RECONSTRUCTION_KEY`. First-party output+persistence uses the R2 config (`S3_*`); when unset, the validated worker URL is+returned as-is. Poll budget is tunable via `X402_PIPELINE_POLL_BUDGET_MS`+(default 45,000).++## Related++- [x402 paid endpoints](x402-endpoints.md) — the full catalog + pricing model+- [x402 buyer client](x402-buyer.md) — how to settle payments as an agent+- [Avatar pipeline](avatar-pipeline.md) — the generation + rig lanes in depthdiff --git a/tests/api/x402-pipeline-stages.test.js b/tests/api/x402-pipeline-stages.test.jsnew file mode 100644index 000000000..a4b1781c0--- /dev/null+++ b/tests/api/x402-pipeline-stages.test.js@@ -0,0 +1,290 @@+/**+ * Tests for the paid 3D-pipeline x402 stages (api/x402/pipeline-*.js) and their+ * shared execution rail (api/_lib/pipeline-stage.js).+ *+ * The GCP Cloud Run workers these stages drive are external and env-gated, so the+ * worker itself is exercised by its own worker suites. What's tested here is the+ * wrapper contract that guarantees a buyer is never charged for a failed stage:+ * - input validation (bad URL → 400, non-GLB/non-image → 415),+ * - the discovery schema each route publishes is present and valid,+ * - price resolution flows through priceFor (env-overridable),+ * - the stage-lane boundary (submit → poll → validate → persist) against real+ * captured worker response shapes, injected via the runStageJob provider+ * seam so no live Cloud Run service is needed.+ */++import { describe, it, expect, vi, beforeAll, afterEach } from 'vitest';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, resolve } from 'node:path';+import Ajv2020 from 'ajv/dist/2020.js';+import addFormats from 'ajv-formats';++import {+ StageError,+ isGlbMagic,+ isImageMagic,+ validateAssetUrl,+ sniffRemoteAsset,+ runStageJob,+ persistStageOutput,+ stageObjectKey,+ readJsonBody,+} from '../../api/_lib/pipeline-stage.js';+import { priceFor } from '../../api/_lib/x402-prices.js';++const __dirname = dirname(fileURLToPath(import.meta.url));+// A real committed GLB — its first bytes are the authentic "glTF" magic header.+const REAL_GLB = readFileSync(resolve(__dirname, '../_fixtures/club-venue.glb'));+const REAL_GLB_HEAD = new Uint8Array(REAL_GLB.subarray(0, 64));+// A real PNG magic prefix (89 50 4E 47 0D 0A 1A 0A) padded to 64 bytes.+const REAL_PNG_HEAD = new Uint8Array(64);+REAL_PNG_HEAD.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], 0);+// An HTML page — the classic "wrong asset behind a URL" case.+const HTML_HEAD = new Uint8Array(Buffer.from('<!doctype html><html><head><title>nope', 'utf8'));++const ajv = new Ajv2020({ allErrors: true, strict: false });+addFormats(ajv);++// Each shipped stage: slug, default price atomics, and the worker mode it drives.+const STAGES = [+ { slug: 'pipeline-rig', price: '50000', mode: 'rerig', module: '../../api/x402/pipeline-rig.js' },+ { slug: 'pipeline-remesh', price: '30000', mode: 'remesh', module: '../../api/x402/pipeline-remesh.js' },+ { slug: 'pipeline-gameready', price: '30000', mode: 'remesh', module: '../../api/x402/pipeline-gameready.js' },+ { slug: 'pipeline-stylize', price: '30000', mode: 'stylize', module: '../../api/x402/pipeline-stylize.js' },+ { slug: 'pipeline-rembg', price: '10000', mode: 'rembg', module: '../../api/x402/pipeline-rembg.js' },+];++beforeAll(() => {+ // The 402 challenge + price plumbing read these at import; set before loading routes.+ Object.assign(process.env, {+ APP_ORIGIN: 'https://three.ws',+ X402_PAY_TO_SOLANA: 'THREEsynthetic1111111111111111111111111111',+ X402_ASSET_MINT_SOLANA: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',+ X402_FEE_PAYER_SOLANA: 'THREEfeepayer11111111111111111111111111111',+ });+});++afterEach(() => {+ vi.restoreAllMocks();+ delete process.env.X402_PRICE_PIPELINE_REMESH;+});++// ── Magic-byte predicates (real captured bytes) ─────────────────────────────+describe('asset magic-byte predicates', () => {+ it('recognizes a real GLB header and rejects non-GLB bytes', () => {+ expect(isGlbMagic(REAL_GLB_HEAD)).toBe(true);+ expect(isGlbMagic(HTML_HEAD)).toBe(false);+ expect(isGlbMagic(REAL_PNG_HEAD)).toBe(false);+ expect(isGlbMagic(new Uint8Array(4))).toBe(false); // too short+ });+ it('recognizes a real PNG header and rejects a GLB posing as an image', () => {+ expect(isImageMagic(REAL_PNG_HEAD)).toBe(true);+ expect(isImageMagic(REAL_GLB_HEAD)).toBe(false);+ });+});++// ── Input validation: bad URL → 400 ─────────────────────────────────────────+describe('validateAssetUrl rejects bad input with 400', () => {+ it('rejects an empty url', async () => {+ await expect(validateAssetUrl('', 'glb_url')).rejects.toMatchObject({ status: 400, code: 'missing_url' });+ });+ it('rejects a non-http scheme', async () => {+ await expect(validateAssetUrl('ftp://example.com/a.glb', 'glb_url')).rejects.toMatchObject({+ status: 400,+ code: 'invalid_url',+ });+ });+ it('rejects a non-URL string', async () => {+ await expect(validateAssetUrl('not a url', 'glb_url')).rejects.toMatchObject({ status: 400, code: 'invalid_url' });+ });+});++// ── Input validation: non-GLB/non-image → 415 ───────────────────────────────+describe('sniffRemoteAsset enforces the expected media type', () => {+ function stubFetch(head) {+ vi.spyOn(globalThis, 'fetch').mockResolvedValue({+ ok: true,+ status: 206,+ arrayBuffer: async () => head.buffer.slice(head.byteOffset, head.byteOffset + head.byteLength),+ });+ }+ it('passes a real GLB', async () => {+ stubFetch(REAL_GLB_HEAD);+ await expect(sniffRemoteAsset('https://three.ws/x.glb', 'glb')).resolves.toBe(true);+ });+ it('rejects an HTML page fed as a GLB with 415', async () => {+ stubFetch(HTML_HEAD);+ await expect(sniffRemoteAsset('https://three.ws/x.glb', 'glb')).rejects.toMatchObject({+ status: 415,+ code: 'unsupported_media_type',+ });+ });+ it('rejects a GLB fed as an image with 415', async () => {+ stubFetch(REAL_GLB_HEAD);+ await expect(sniffRemoteAsset('https://three.ws/x.png', 'image')).rejects.toMatchObject({+ status: 415,+ code: 'unsupported_media_type',+ });+ });+ it('maps an upstream 404 to a clean 404, not a charge', async () => {+ vi.spyOn(globalThis, 'fetch').mockResolvedValue({ ok: false, status: 404, arrayBuffer: async () => new ArrayBuffer(0) });+ await expect(sniffRemoteAsset('https://three.ws/missing.glb', 'glb')).rejects.toMatchObject({ status: 404 });+ });+});++// ── Stage-lane boundary against captured worker shapes ──────────────────────+describe('runStageJob poll-to-completion boundary (fixture-backed)', () => {+ // A real captured "done" shape from the gcp provider's status() for a remesh+ // job (see api/_providers/gcp.js status() → resultGlbUrl + telemetry).+ const DONE_REMESH = {+ status: 'done',+ resultGlbUrl: 'https://storage.googleapis.com/three-workers/remesh/out.glb',+ faceCount: 20000,+ quadRatio: 0.98,+ textured: true,+ mode: 'quad',+ };++ function fakeProvider({ statuses }) {+ let i = 0;+ return {+ supportsMode: () => true,+ submit: vi.fn(async () => ({ extJobId: 'ext-job-1', eta: 30 })),+ status: vi.fn(async () => statuses[Math.min(i++, statuses.length - 1)]),+ };+ }++ it('returns the finished result once the worker reports done', async () => {+ const provider = fakeProvider({ statuses: [{ status: 'running' }, DONE_REMESH] });+ const out = await runStageJob({+ mode: 'remesh',+ sourceUrl: 'https://three.ws/in.glb',+ params: { remesh_mode: 'quad' },+ provider,+ pollIntervalMs: 1,+ pollBudgetMs: 1000,+ });+ expect(out.resultGlbUrl).toBe(DONE_REMESH.resultGlbUrl);+ expect(out.faceCount).toBe(20000);+ expect(provider.submit).toHaveBeenCalledOnce();+ });++ it('throws (never settles) when the worker reports failed', async () => {+ const provider = fakeProvider({ statuses: [{ status: 'failed', error: 'mesh non-manifold' }] });+ await expect(+ runStageJob({ mode: 'remesh', sourceUrl: 'https://three.ws/in.glb', params: {}, provider, pollIntervalMs: 1 }),+ ).rejects.toMatchObject({ status: 502, code: 'stage_failed' });+ });++ it('throws a 504 timeout when the worker never finishes inside the budget', async () => {+ const provider = fakeProvider({ statuses: [{ status: 'running' }] });+ await expect(+ runStageJob({+ mode: 'remesh',+ sourceUrl: 'https://three.ws/in.glb',+ params: {},+ provider,+ pollIntervalMs: 5,+ pollBudgetMs: 8,+ }),+ ).rejects.toMatchObject({ status: 504, code: 'stage_timeout' });+ });++ it('throws 503 unconfigured when no worker URL is set (buyer not charged)', async () => {+ // No provider passed → real createRegenProvider() throws (GCP_RECONSTRUCTION_KEY unset).+ delete process.env.GCP_RECONSTRUCTION_KEY;+ await expect(+ runStageJob({ mode: 'remesh', sourceUrl: 'https://three.ws/in.glb', params: {} }),+ ).rejects.toMatchObject({ status: 503, code: 'unconfigured' });+ });+});++// ── Output persistence + validation ─────────────────────────────────────────+describe('persistStageOutput validates and falls back cleanly', () => {+ it('returns the worker URL (persisted:false) when R2 is unconfigured, validating magic bytes', async () => {+ vi.spyOn(globalThis, 'fetch').mockResolvedValue({+ ok: true,+ status: 200,+ arrayBuffer: async () => REAL_GLB.buffer.slice(REAL_GLB.byteOffset, REAL_GLB.byteOffset + REAL_GLB.byteLength),+ });+ const out = await persistStageOutput({+ resultUrl: 'https://worker/out.glb',+ key: 'x402-pipeline/remesh/abc.glb',+ kind: 'glb',+ });+ expect(out.url).toBe('https://worker/out.glb');+ expect(out.persisted).toBe(false);+ expect(out.bytes).toBe(REAL_GLB.length);+ });++ it('throws invalid_output when the worker returns non-GLB bytes', async () => {+ vi.spyOn(globalThis, 'fetch').mockResolvedValue({+ ok: true,+ status: 200,+ arrayBuffer: async () => HTML_HEAD.buffer.slice(HTML_HEAD.byteOffset, HTML_HEAD.byteOffset + HTML_HEAD.byteLength),+ });+ await expect(+ persistStageOutput({ resultUrl: 'https://worker/out.glb', key: 'k.glb', kind: 'glb' }),+ ).rejects.toMatchObject({ status: 502, code: 'invalid_output' });+ });++ it('throws no_output when the worker reports done with no URL', async () => {+ await expect(persistStageOutput({ resultUrl: null, key: 'k.glb', kind: 'glb' })).rejects.toMatchObject({+ code: 'no_output',+ });+ });+});++describe('stageObjectKey is stable + namespaced', () => {+ it('derives the same key for the same source and differs by stage', async () => {+ const a = await stageObjectKey({ stage: 'remesh', sourceUrl: 'https://three.ws/in.glb', ext: 'glb' });+ const b = await stageObjectKey({ stage: 'remesh', sourceUrl: 'https://three.ws/in.glb', ext: 'glb' });+ const c = await stageObjectKey({ stage: 'rig', sourceUrl: 'https://three.ws/in.glb', ext: 'glb' });+ expect(a).toBe(b);+ expect(a).not.toBe(c);+ expect(a.startsWith('x402-pipeline/remesh/')).toBe(true);+ });+});++// ── Price resolution via priceFor ───────────────────────────────────────────+describe('price resolution', () => {+ for (const { slug, price } of STAGES) {+ it(`${slug} defaults to ${price} atomics`, () => {+ expect(priceFor(slug, price)).toBe(price);+ });+ }+ it('honors an env override', () => {+ process.env.X402_PRICE_PIPELINE_REMESH = '99000';+ expect(priceFor('pipeline-remesh', '30000')).toBe('99000');+ });+});++// ── Discovery schema present + valid for every stage ────────────────────────+describe('discovery schema', () => {+ for (const stage of STAGES) {+ it(`${stage.slug} publishes a valid, priced, discoverable bazaar schema`, async () => {+ const mod = await import(stage.module);+ expect(typeof mod.default).toBe('function'); // paidEndpoint handler+ expect(mod.BAZAAR).toBeTruthy();+ expect(mod.BAZAAR.discoverable).toBe(true);+ expect(mod.BAZAAR.info).toBeTruthy();+ expect(mod.BAZAAR.schema).toBeTruthy();+ // Input + output JSON Schemas must compile.+ expect(() => ajv.compile(mod.INPUT_SCHEMA)).not.toThrow();+ const validateOut = ajv.compile(mod.OUTPUT_SCHEMA);+ // The advertised output.example must validate against the output schema —+ // exactly what x402scan / agentic.market render and rank on.+ expect(validateOut(mod.BAZAAR.info.output.example)).toBe(true);+ });+ }+});++describe('StageError shape', () => {+ it('carries status + code', () => {+ const e = new StageError('x', { status: 415, code: 'unsupported_media_type' });+ expect(e).toBeInstanceOf(Error);+ expect(e.status).toBe(415);+ expect(e.code).toBe('unsupported_media_type');+ });+});