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-sdk): add the x402 pay-per-call lane and carry a BYOK key through every poll

nirholasf1c8246b1357
diff --git a/packages/forge/src/index.d.ts b/packages/forge/src/index.d.ts
index 23bd33033..4b318d4a9 100644
--- a/packages/forge/src/index.d.ts
+++ b/packages/forge/src/index.d.ts
@@ -31,10 +31,16 @@ export interface ForgeInput {
export interface ForgeOptions {
path?: ForgePath;
tier?: ForgeTier;
- /** Force a generation backend (`nvidia`, `huggingface`, `meshy`, `tripo`). */
+ /** Force a generation backend. See the live `catalog()` for the current ids. */
backend?: string;
- /** Billing lane for paid tiers. */
- payWith?: 'x402' | 'credits';
+ /**
+ * Billing lane. Default: the account/credits lane on `/api/forge`.
+ * `'x402'` routes to the pay-per-call twin `/api/x402/forge`, which rejects
+ * `path`, `backend`, and `providerKey` because it picks its own lane.
+ */
+ payWith?: 'credits' | 'x402';
+ /** BYOK provider key for this call. Overrides the client-level key. */
+ providerKey?: string;
/** Called on each poll tick with the latest job state. */
onProgress?: (job: ForgeResult) => void;
pollIntervalMs?: number;
@@ -43,6 +49,13 @@ export interface ForgeOptions {
signal?: AbortSignal;
}
+export interface JobOptions {
+ /** BYOK provider key. Required to poll a job that was submitted with one. */
+ providerKey?: string;
+ headers?: Record<string, string>;
+ signal?: AbortSignal;
+}
+
export interface ForgeResult {
jobId: string | null;
creationId: string | null;
@@ -78,10 +91,11 @@ export interface ForgeClient {
forge(promptOrInput: string | ForgeInput, opts?: ForgeOptions): Promise<ForgeResult>;
rig(glbUrl: string, opts?: ForgeOptions): Promise<ForgeResult>;
catalog(opts?: { signal?: AbortSignal }): Promise<Catalog>;
- getJob(jobId: string, opts?: { signal?: AbortSignal }): Promise<ForgeResult>;
+ getJob(jobId: string, opts?: JobOptions): Promise<ForgeResult>;
}
export declare function createForge(options?: ForgeClientOptions): ForgeClient;
export declare function forge(promptOrInput: string | ForgeInput, opts?: ForgeOptions): Promise<ForgeResult>;
export declare function rig(glbUrl: string, opts?: ForgeOptions): Promise<ForgeResult>;
export declare function catalog(opts?: { signal?: AbortSignal }): Promise<Catalog>;
+export declare function getJob(jobId: string, opts?: JobOptions): Promise<ForgeResult>;
diff --git a/packages/forge/src/index.js b/packages/forge/src/index.js
index f98f0e7bf..3947011a8 100644
--- a/packages/forge/src/index.js
+++ b/packages/forge/src/index.js
@@ -8,6 +8,12 @@ export { ThreeWsError, PaymentRequiredError, DEFAULT_BASE_URL } from './http.js'
const TIERS = ['draft', 'standard', 'high'];
const PATHS = ['image', 'geometry', 'sketch'];
+const PAY_LANES = ['credits', 'x402'];
+
+// The browser-facing lane (account credits / free draft) and its pay-per-call
+// twin. They are separate endpoints, not a flag on one endpoint.
+const FORGE_ROUTE = '/api/forge';
+const X402_ROUTE = '/api/x402/forge';
/**
* Create a Forge client bound to a base URL, fetch, and optional auth/provider key.
@@ -17,11 +23,14 @@ const PATHS = ['image', 'geometry', 'sketch'];
*/
export function createForge(options = {}) {
const request = createHttp(options);
- const providerKey = options.providerKey || null;
+ const clientProviderKey = options.providerKey || null;
- function providerHeaders(extra) {
+ // A BYOK key rides on every request that touches the job, submit AND poll:
+ // the API re-resolves it per poll and fails the job without it.
+ function providerHeaders(extra, perCallKey) {
const h = { ...(extra || {}) };
- if (providerKey) h['x-forge-provider-key'] = providerKey;
+ const key = perCallKey || clientProviderKey;
+ if (key) h['x-forge-provider-key'] = key;
return h;
}
@@ -30,6 +39,7 @@ export function createForge(options = {}) {
const input = typeof promptOrInput === 'string' ? { prompt: promptOrInput } : { ...(promptOrInput || {}) };
const path = normalizeEnum(opts.path, PATHS, 'path');
const tier = normalizeEnum(opts.tier, TIERS, 'tier');
+ const payWith = normalizeEnum(opts.payWith, PAY_LANES, 'payWith');
if (!input.prompt && !(input.images && input.images.length)) {
throw new ThreeWsError('forge() needs a `prompt` or at least one image.', { code: 'invalid_input' });
@@ -38,6 +48,8 @@ export function createForge(options = {}) {
throw new ThreeWsError('The sketch path needs a `prompt` naming what the drawing depicts.', { code: 'invalid_input' });
}
+ if (payWith === 'x402') return forgeOverX402({ input, tier, path, opts });
+
const body = {
prompt: input.prompt,
image_urls: input.images,
@@ -45,17 +57,52 @@ export function createForge(options = {}) {
path,
tier,
backend: opts.backend,
- pay_with: opts.payWith,
+ pay_with: payWith,
};
- const submitted = await request('/api/forge', {
+ const headers = providerHeaders(opts.headers, opts.providerKey);
+ const submitted = await request(FORGE_ROUTE, {
method: 'POST',
body: prune(body),
- headers: providerHeaders(opts.headers),
+ headers,
signal: opts.signal,
});
- return resolveJob(submitted, opts);
+ return resolveJob(submitted, opts, headers);
+ }
+
+ // The pay-per-call twin. One USDC payment buys one generation, with no
+ // account and no key, so the BYOK/backend/path knobs of the credits lane do
+ // not apply: the server picks the lane from the input. Without a payment-aware
+ // `fetch` the first call throws PaymentRequiredError carrying the challenge.
+ async function forgeOverX402({ input, tier, path, opts }) {
+ const unsupported = [
+ opts.backend ? 'backend' : null,
+ path ? 'path' : null,
+ opts.providerKey || clientProviderKey ? 'providerKey' : null,
+ ].filter(Boolean);
+ if (unsupported.length) {
+ throw new ThreeWsError(
+ `The x402 lane picks its own generation lane, so it does not accept: ${unsupported.join(', ')}. ` +
+ 'Drop them, or use the default credits lane.',
+ { code: 'invalid_input' },
+ );
+ }
+
+ const submitted = await request(X402_ROUTE, {
+ method: 'POST',
+ body: prune({
+ prompt: input.prompt,
+ image_urls: input.images,
+ aspect_ratio: input.aspectRatio,
+ tier,
+ }),
+ headers: { ...(opts.headers || {}) },
+ signal: opts.signal,
+ });
+ // The job token is polled for free on the shared endpoint, so resolution
+ // runs against /api/forge exactly as the credits lane does.
+ return resolveJob(submitted, opts, opts.headers || {});
}
/** Auto-rig an existing GLB into an animation-ready humanoid. */
@@ -63,28 +110,34 @@ export function createForge(options = {}) {
if (!glbUrl || typeof glbUrl !== 'string') {
throw new ThreeWsError('rig() needs a GLB url string.', { code: 'invalid_input' });
}
- const submitted = await request('/api/forge', {
+ const headers = providerHeaders(opts.headers, opts.providerKey);
+ const submitted = await request(FORGE_ROUTE, {
method: 'POST',
query: { action: 'rig' },
body: { glb_url: glbUrl },
- headers: providerHeaders(opts.headers),
+ headers,
signal: opts.signal,
});
- return resolveJob(submitted, opts);
+ return resolveJob(submitted, opts, headers);
}
/** Fetch the live tier / backend / cost matrix. */
async function catalog(opts = {}) {
- return request('/api/forge', { query: { catalog: '1' }, signal: opts.signal });
+ return request(FORGE_ROUTE, { query: { catalog: '1' }, signal: opts.signal });
}
/** Poll a single job once. */
async function getJob(jobId, opts = {}) {
- return shape(await request('/api/forge', { query: { job: jobId }, signal: opts.signal }), options.baseUrl);
+ const res = await request(FORGE_ROUTE, {
+ query: { job: jobId },
+ headers: providerHeaders(opts.headers, opts.providerKey),
+ signal: opts.signal,
+ });
+ return shape(res, options.baseUrl);
}
// Poll a submitted job to completion (sync backends return done immediately).
- async function resolveJob(submitted, opts) {
+ async function resolveJob(submitted, opts, headers) {
let job = shape(submitted, options.baseUrl);
opts.onProgress?.(job);
if (job.status === 'done' || !job.jobId) {
@@ -99,7 +152,8 @@ export function createForge(options = {}) {
throw new ThreeWsError(`Forge job ${job.jobId} did not finish within ${Math.round(timeoutMs / 1000)}s.`, { code: 'timeout' });
}
await delay(intervalMs, opts.signal);
- job = shape(await request('/api/forge', { query: { job: job.jobId }, signal: opts.signal }), options.baseUrl);
+ const polled = await request(FORGE_ROUTE, { query: { job: job.jobId }, headers, signal: opts.signal });
+ job = shape(polled, options.baseUrl);
opts.onProgress?.(job);
if (job.status === 'failed') throw failed(job);
}
@@ -127,6 +181,10 @@ export function rig(glbUrl, opts) {
export function catalog(opts) {
return defaultClient().catalog(opts);
}
+/** Read one job's current state without waiting for it to finish. */
+export function getJob(jobId, opts) {
+ return defaultClient().getJob(jobId, opts);
+}
function shape(res, baseUrl) {
if (!res || typeof res !== 'object') {
diff --git a/packages/forge/test/forge.test.js b/packages/forge/test/forge.test.js
index 6176bb4c7..82e37d526 100644
--- a/packages/forge/test/forge.test.js
+++ b/packages/forge/test/forge.test.js
@@ -75,6 +75,70 @@ test('the geometry path attaches the BYOK provider key header', async () => {
assert.equal(calls[0].init.headers['x-forge-provider-key'], 'meshy_test_key');
});
+test('a per-call providerKey overrides the client key and rides every poll', async () => {
+ const { fetch, calls } = stubFetch([
+ { body: { job_id: 'j9', status: 'queued' } },
+ { body: { job_id: 'j9', status: 'done', glb_url: 'https://three.ws/cdn/c.glb' } },
+ ]);
+ const client = createForge({ fetch, providerKey: 'client_key' });
+ const res = await client.forge('a sword', { path: 'geometry', providerKey: 'call_key', pollIntervalMs: 1 });
+
+ assert.equal(res.glbUrl, 'https://three.ws/cdn/c.glb');
+ assert.equal(calls[0].init.headers['x-forge-provider-key'], 'call_key');
+ // The API re-resolves the BYOK key on every poll and fails the job without it.
+ assert.equal(calls[1].init.headers['x-forge-provider-key'], 'call_key');
+});
+
+test('getJob() reads one job and carries the BYOK key', async () => {
+ const { fetch, calls } = stubFetch([{ body: { job_id: 'j5', status: 'running' } }]);
+ const client = createForge({ fetch });
+ const job = await client.getJob('j5', { providerKey: 'meshy_test_key' });
+ assert.equal(calls[0].url.searchParams.get('job'), 'j5');
+ assert.equal(calls[0].init.headers['x-forge-provider-key'], 'meshy_test_key');
+ assert.equal(job.status, 'running');
+ assert.equal(job.jobId, 'j5');
+});
+
+test('payWith:x402 posts to the paid twin and polls the free job endpoint', async () => {
+ const { fetch, calls } = stubFetch([
+ { body: { job_id: 'x402-token', status: 'queued', tier: 'draft', backend: 'nvidia' } },
+ { body: { job_id: 'x402-token', status: 'done', glb_url: 'https://three.ws/cdn/paid.glb' } },
+ ]);
+ const client = createForge({ fetch });
+ const res = await client.forge('a chrome robot', { payWith: 'x402', tier: 'draft', pollIntervalMs: 1 });
+
+ assert.equal(calls[0].url.pathname, '/api/x402/forge');
+ assert.equal(calls[0].init.method, 'POST');
+ const sent = JSON.parse(calls[0].init.body);
+ assert.deepEqual(sent, { prompt: 'a chrome robot', tier: 'draft' });
+ assert.equal(calls[1].url.pathname, '/api/forge');
+ assert.equal(calls[1].url.searchParams.get('job'), 'x402-token');
+ assert.equal(res.glbUrl, 'https://three.ws/cdn/paid.glb');
+});
+
+test('the x402 lane rejects the knobs it cannot honor, before any network call', async () => {
+ const { fetch, calls } = stubFetch([]);
+ const client = createForge({ fetch });
+ await assert.rejects(() => client.forge('x', { payWith: 'x402', backend: 'meshy' }), /does not accept: backend/);
+ await assert.rejects(() => client.forge('x', { payWith: 'x402', path: 'geometry' }), /does not accept: path/);
+ await assert.rejects(() => client.forge('x', { payWith: 'nope' }), /Invalid payWith/);
+ assert.equal(calls.length, 0);
+});
+
+test('an unpaid x402 call surfaces the challenge as PaymentRequiredError', async () => {
+ const accepts = [{ scheme: 'exact', network: 'solana:5eykt4Us…', maxAmountRequired: '50000' }];
+ const { fetch, calls } = stubFetch([
+ { status: 402, body: { x402Version: 2, error: 'X-PAYMENT header is required', accepts } },
+ ]);
+ const client = createForge({ fetch });
+ await assert.rejects(() => client.forge('a fox', { payWith: 'x402' }), (e) => {
+ assert.ok(e instanceof PaymentRequiredError);
+ assert.deepEqual(e.accepts, accepts);
+ return true;
+ });
+ assert.equal(calls[0].url.pathname, '/api/x402/forge');
+});
+
test('needs_key (501) surfaces as a typed ThreeWsError', async () => {
const { fetch } = stubFetch([{ status: 501, body: { error: 'needs_key', message: 'Add a Meshy key.' } }]);
const client = createForge({ fetch });