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(forge): x402 forge openapi + docs + tests

nirholas48751d8aafce
diff --git a/api/openapi-json.js b/api/openapi-json.js
index 4cfe4d659..347985c97 100644
--- a/api/openapi-json.js
+++ b/api/openapi-json.js
@@ -523,6 +523,71 @@ export default wrap(async (req, res) => {
},
},
},
+ '/api/x402/forge': {
+ post: {
+ operationId: 'x402_forge_generate',
+ summary: 'Paid: text→3D / image→3D generation (returns a job token)',
+ description:
+ 'Pay per quality tier in USDC ($0.05 draft / $0.15 standard / $0.50 high) to generate a 3D model. Submit a prompt for text→3D, or up to four public https reference views of one object for image→3D. Runs the FLUX→TRELLIS pipeline. The response returns a job token; poll it for FREE at GET /api/forge?job=<id> to retrieve the finished GLB URL. The 402 challenge quotes the exact price for the requested tier.',
+ requestBody: {
+ required: false,
+ content: {
+ 'application/json': {
+ schema: {
+ type: 'object',
+ properties: {
+ prompt: {
+ type: 'string',
+ minLength: 3,
+ maxLength: 1000,
+ description: 'Describe one subject for text→3D. Omit when supplying image_urls.',
+ },
+ image_urls: {
+ type: 'array',
+ items: { type: 'string', format: 'uri' },
+ minItems: 1,
+ maxItems: 4,
+ description: 'Up to four public https reference views of one object for image→3D.',
+ },
+ tier: { type: 'string', enum: ['draft', 'standard', 'high'], default: 'standard' },
+ aspect_ratio: { type: 'string', enum: ['1:1', '4:3', '3:4', '16:9', '9:16'], default: '1:1' },
+ },
+ },
+ },
+ },
+ },
+ responses: {
+ 200: {
+ description: 'Generation job accepted; poll poll_url for the GLB',
+ content: {
+ 'application/json': {
+ schema: {
+ type: 'object',
+ required: ['job_id', 'status', 'poll_url'],
+ properties: {
+ job_id: { type: 'string' },
+ status: { type: 'string' },
+ poll_url: { type: 'string', description: 'Free, provider-aware status endpoint.' },
+ mode: { type: 'string', enum: ['text_to_3d', 'image_to_3d'] },
+ tier: { type: 'string' },
+ backend: { type: 'string' },
+ eta_seconds: { type: 'integer' },
+ price_usdc: { type: 'string' },
+ },
+ },
+ },
+ },
+ },
+ 400: { description: 'Missing or invalid input' },
+ 402: { description: 'Payment Required (x402)' },
+ 503: { description: 'Generation backend not configured' },
+ },
+ 'x-payment-info': {
+ price: { mode: 'fixed', currency: 'USD', amount: '0.15' },
+ protocols: X402_PROTOCOLS,
+ },
+ },
+ },
'/api/insights/revenue-vision': {
get: {
operationId: 'insights_revenue_vision',
diff --git a/docs/api/forge-x402.md b/docs/api/forge-x402.md
new file mode 100644
index 000000000..94223295e
--- /dev/null
+++ b/docs/api/forge-x402.md
@@ -0,0 +1,111 @@
+# Forge — paid 3D generation API (x402)
+
+Pay-per-call text→3D and image→3D for AI agents. Settle in USDC autonomously —
+no API key, no account, no signup. This is the monetized twin of the free,
+browser-facing `/api/forge`.
+
+- **Endpoint:** `POST /api/x402/forge`
+- **Payment:** x402 over USDC on Base or Solana mainnet
+- **Polling:** free, on the existing `GET /api/forge?job=<id>`
+- **Discovery:** listed in `/.well-known/x402` and `/openapi.json`; the price is
+ in the 402 challenge and at `GET /api/x402/forge`.
+
+## Pricing
+
+Per quality tier, in USDC. Source of truth: `api/_lib/forge-tiers.js`
+(`priceUsdcAtomics`). The 402 challenge quotes the exact price for the requested
+tier.
+
+| Tier | Price | Polygon budget |
+|---|---|---|
+| `draft` | $0.05 | ~12k |
+| `standard` (default) | $0.15 | ~30k |
+| `high` | $0.50 | ~200k + PBR |
+
+`GET /api/x402/forge` returns the live pricing table (free, no payment).
+
+## Request
+
+`POST /api/x402/forge` with a JSON body:
+
+```jsonc
+{
+ "prompt": "a brass steampunk owl, full body", // text→3D (3–1000 chars)
+ // OR, for image→3D, omit prompt and supply public https reference views:
+ // "image_urls": ["https://.../front.png", "https://.../side.png"], // 1–4
+ "tier": "standard", // draft | standard | high
+ "aspect_ratio": "1:1" // 1:1 | 4:3 | 3:4 | 16:9 | 9:16 (text→3D only)
+}
+```
+
+Caller-supplied `image_urls` are SSRF-guarded before the reconstructor fetches
+them.
+
+## Flow
+
+1. **Unpaid request** → `402 Payment Required` with an `accepts[]` array quoting
+ the tier price on each supported network.
+2. **Pay** with any x402 client (e.g. `@x402/fetch`, CDP, PayAI) — the payment
+ proof rides in the `X-PAYMENT` header.
+3. **Paid request** → the server verifies payment, submits the generation job,
+ then settles. Generation is submitted **after verify but before settle**, so a
+ failed submit never charges you. Response:
+
+ ```json
+ {
+ "job_id": "abcd1234efgh5678ij",
+ "status": "queued",
+ "poll_url": "/api/forge?job=abcd1234efgh5678ij",
+ "mode": "text_to_3d",
+ "tier": "standard",
+ "backend": "trellis",
+ "eta_seconds": 60,
+ "price_usdc": "0.15"
+ }
+ ```
+
+4. **Poll for free** until the GLB is ready:
+
+ ```bash
+ curl 'https://three.ws/api/forge?job=abcd1234efgh5678ij'
+ # → { "status": "done", "glb_url": "https://.../model.glb", ... }
+ ```
+
+ Fetch the `glb_url` promptly — provider delivery URLs are short-lived.
+
+## Idempotency
+
+A retried payment (same payment id + same body) returns the **same** job token
+instead of submitting a second generation, so a network retry never
+double-charges.
+
+## Example (`@x402/fetch`)
+
+```js
+import { wrapFetchWithPayment } from '@x402/fetch';
+
+const fetchWithPay = wrapFetchWithPayment(fetch, wallet);
+const res = await fetchWithPay('https://three.ws/api/x402/forge', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ prompt: 'a brass steampunk owl', tier: 'standard' }),
+});
+const { poll_url } = await res.json();
+
+let glb;
+for (;;) {
+ const s = await (await fetch(`https://three.ws${poll_url}`)).json();
+ if (s.status === 'done') { glb = s.glb_url; break; }
+ if (s.status === 'failed') throw new Error(s.error);
+ await new Promise((r) => setTimeout(r, 2000));
+}
+```
+
+## Notes
+
+- The MCP-3D server (`/api/mcp-3d`) exposes the same generation as `text_to_3d` /
+ `image_to_3d` tools for in-conversation use; this REST endpoint is the
+ pay-per-call surface for autonomous agents.
+- Only the platform image pipeline (FLUX→TRELLIS) is sold here. The BYOK geometry
+ backends (Meshy/Tripo) bill through the caller's own provider key on the free
+ `/api/forge` and are not monetized via x402.
diff --git a/tests/api/x402-forge.test.js b/tests/api/x402-forge.test.js
new file mode 100644
index 000000000..20bd057dc
--- /dev/null
+++ b/tests/api/x402-forge.test.js
@@ -0,0 +1,160 @@
+/**
+ * Tests for the paid x402 generation endpoint (api/x402/forge.js).
+ *
+ * Payment verification/settlement, the FLUX text-to-image step, and the
+ * Replicate reconstruction submit are stubbed at their module boundaries — the
+ * real upstreams (payment facilitators, Replicate) are exercised by their own
+ * suites. What's tested here is the endpoint's own logic: pricing sourced from
+ * forge-tiers, the 402 challenge, input validation, and the verify → submit →
+ * settle ordering that guarantees a failed generation never charges.
+ */
+
+import { describe, it, expect, vi, beforeAll } from 'vitest';
+
+// Env the 402 challenge builder reads. Set before importing the handler.
+beforeAll(() => {
+ Object.assign(process.env, {
+ APP_ORIGIN: 'https://three.ws',
+ X402_PAY_TO_BASE: '0x0000000000000000000000000000000000000001',
+ X402_ASSET_ADDRESS_BASE: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
+ REPLICATE_API_TOKEN: 'test-token',
+ });
+});
+
+// Stub payment verify/settle (keep the rest of x402-spec real: send402,
+// buildRequirements helpers, buildBazaarSchema, resolveResourceUrl).
+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'),
+ };
+});
+
+// Stub the FLUX text-to-image step and the Replicate reconstruction submit.
+vi.mock('../../api/_mcp3d/text-to-image.js', () => ({
+ textToImage: vi.fn(async () => ({ imageUrl: 'https://cdn.example/ref.png', model: 'flux', predictionId: 'p1' })),
+}));
+vi.mock('../../api/_providers/replicate.js', () => ({
+ createRegenProvider: () => ({
+ submit: vi.fn(async () => ({ extJobId: 'abcd1234efgh5678ij', jobId: 'abcd1234efgh5678ij', eta: 60 })),
+ }),
+}));
+
+// Rate limiter: deterministic success, no Upstash dependency.
+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.7',
+ };
+});
+
+const { default: handler } = await import('../../api/x402/forge.js');
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: null,
+ setHeader(name, value) {
+ this.headers[String(name).toLowerCase()] = value;
+ },
+ end(body) {
+ this.body = body ?? null;
+ },
+ };
+}
+
+// A request the handler can consume: async-iterable body + headers/method/url.
+function makeReq({ method = 'POST', url = '/api/x402/forge', 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.7', ...headers },
+ async *[Symbol.asyncIterator]() {
+ if (payload) yield Buffer.from(payload, 'utf8');
+ },
+ };
+}
+
+describe('GET /api/x402/forge — pricing discovery', () => {
+ it('returns the per-tier USDC pricing sourced from forge-tiers', async () => {
+ const res = makeRes();
+ await handler(makeReq({ method: 'GET', url: '/api/x402/forge' }), res);
+ expect(res.statusCode).toBe(200);
+ const body = JSON.parse(res.body);
+ expect(body.route).toBe('/api/x402/forge');
+ const standard = body.pricing_usdc.find((p) => p.tier === 'standard');
+ expect(standard.price_usdc).toBe('0.15');
+ expect(body.pricing_usdc.find((p) => p.tier === 'draft').price_usdc).toBe('0.05');
+ expect(body.pricing_usdc.find((p) => p.tier === 'high').price_usdc).toBe('0.50');
+ });
+});
+
+describe('POST /api/x402/forge — 402 challenge', () => {
+ it('emits a 402 quoting the requested tier price when unpaid', async () => {
+ const res = makeRes();
+ await handler(makeReq({ body: { prompt: 'a brass owl', tier: 'high' } }), res);
+ expect(res.statusCode).toBe(402);
+ const body = JSON.parse(res.body);
+ // High tier = $0.50 = 500000 atomic. The Base accept must quote it.
+ const amounts = (body.accepts || []).map((a) => a.amount);
+ expect(amounts).toContain('500000');
+ });
+
+ it('quotes the standard price by default', async () => {
+ const res = makeRes();
+ await handler(makeReq({ body: { prompt: 'a brass owl' } }), res);
+ expect(res.statusCode).toBe(402);
+ const body = JSON.parse(res.body);
+ expect((body.accepts || []).map((a) => a.amount)).toContain('150000');
+ });
+});
+
+describe('POST /api/x402/forge — validation', () => {
+ it('rejects a too-short prompt with no payment required', async () => {
+ const res = makeRes();
+ await handler(makeReq({ body: { prompt: 'hi' } }), res);
+ expect(res.statusCode).toBe(400);
+ expect(JSON.parse(res.body).error).toBe('invalid_prompt');
+ });
+
+ it('rejects non-https image_urls', async () => {
+ const res = makeRes();
+ await handler(makeReq({ body: { image_urls: ['http://insecure/x.png'] } }), res);
+ expect(res.statusCode).toBe(400);
+ expect(JSON.parse(res.body).error).toBe('invalid_image_urls');
+ });
+});
+
+describe('POST /api/x402/forge — paid generation', () => {
+ it('submits a job and returns a free poll_url after payment', async () => {
+ const res = makeRes();
+ await handler(
+ makeReq({ headers: { 'x-payment': 'stub-payment-proof' }, body: { prompt: 'a brass steampunk owl', tier: 'standard' } }),
+ res,
+ );
+ expect(res.statusCode).toBe(200);
+ const body = JSON.parse(res.body);
+ expect(body.job_id).toBe('abcd1234efgh5678ij');
+ expect(body.poll_url).toBe('/api/forge?job=abcd1234efgh5678ij');
+ expect(body.mode).toBe('text_to_3d');
+ expect(body.tier).toBe('standard');
+ expect(body.backend).toBe('trellis');
+ expect(body.price_usdc).toBe('0.15');
+ // Settlement ran (the x-payment-response header is set).
+ expect(res.headers['x-payment-response']).toBe('stub-payment-response');
+ });
+
+ it('rejects a paid request that carries no actual input', async () => {
+ const res = makeRes();
+ await handler(makeReq({ headers: { 'x-payment': 'stub-payment-proof' }, body: {} }), res);
+ expect(res.statusCode).toBe(400);
+ expect(JSON.parse(res.body).error).toBe('missing_input');
+ });
+});
diff --git a/vercel.json b/vercel.json
index 987f3e233..ee47490ba 100644
--- a/vercel.json
+++ b/vercel.json
@@ -51,6 +51,10 @@
"includeFiles": "examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json",
"maxDuration": 60
},
+ "api/x402/forge.js": {
+ "includeFiles": "examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json",
+ "maxDuration": 60
+ },
"api/brain/chat.js": {
"includeFiles": "examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json",
"maxDuration": 120