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): migrate the Tripo provider to its v3 API

nirholas858e7649193b
diff --git a/api/_providers/tripo.js b/api/_providers/tripo.js
index 39b2f0b90..db18472cf 100644
--- a/api/_providers/tripo.js
+++ b/api/_providers/tripo.js
@@ -1,21 +1,27 @@
-// Tripo provider — alternative native geometry-first backend.
+// Tripo provider: alternative native geometry-first backend, on Tripo's v3 API.
//
-// geometry path → POST /v2/openapi/task { type: "text_to_model" }
-// Native text→model: clean (often quad) geometry directly from the
+// geometry path → POST /generation/text-to-model
+// Native text->model: clean (often quad) geometry directly from the
// prompt. `face_limit` carries the tier's poly budget.
//
-// image path → POST /v2/openapi/task { type: "image_to_model" }
+// image path → POST /generation/image-to-model
// Single-image reconstruction with PBR textures.
//
-// Tripo wraps every response in { code, data } and polls a single task
-// endpoint regardless of type, so this client is simpler than Meshy's.
+// v3 gives every capability its own endpoint (no more shared `type` field) and
+// unifies every file/task source under a single `input` string: a public
+// http(s) URL, a `task_id` from a prior task, or a `file_token` from /files.
+// Every task type polls the same GET /tasks/{id}, returning
+// {status, output, credits_consumed, created_at, completed_at}; rig-check is
+// the one task whose `output` is `{riggable, rig_type}` instead of a model url.
//
-// BYOK only: the caller passes the user's Tripo key (tsk_…). The model version
-// defaults to v3.1 and is overridable via TRIPO_MODEL_VERSION.
+// BYOK or house key: the caller passes either the user's Tripo key (tsk_...)
+// or, when TRIPO_API_KEY is set, the platform's own key (forge-tiers.js /
+// forge-provider-key.js resolve which one). The model version defaults to
+// v3.1 and is overridable via TRIPO_MODEL_VERSION.
import { fetchUpstream } from '../_lib/upstream-fetch.js';
-const TRIPO_BASE = 'https://api.tripo3d.ai/v2/openapi';
+const TRIPO_BASE = 'https://openapi.tripo3d.com/v3';
const DEFAULT_MODEL_VERSION = 'v3.1-20260211';
// Tripo's face_limit is unbounded upward in practice, but keep the same sane
@@ -46,22 +52,12 @@ function mapStatus(s) {
return 'done';
case 'failed':
case 'cancelled':
- case 'banned':
- case 'expired':
- case 'unknown':
return 'failed';
default:
return 'queued';
}
}
-// .jpg / .jpeg / .png — Tripo's image_to_model `file` needs an explicit type.
-function imageTypeFor(url) {
- const m = /\.(jpe?g|png|webp)(\?|$)/i.exec(url || '');
- const ext = m ? m[1].toLowerCase() : 'jpg';
- return ext === 'jpeg' ? 'jpg' : ext;
-}
-
// Parse a data:image/...;base64,... URI into its raw bytes, mime, and the file
// extension Tripo expects. Returns null for anything that isn't a base64 image
// data URI (e.g. a plain http(s) URL), so callers can branch on it.
@@ -80,6 +76,48 @@ function parseImageDataUri(s) {
return { bytes, mime, ext };
}
+// Every v3 error response (any status) is the unified envelope
+// { code, message, suggestion, request_id }. HTTP status is advisory;
+// disambiguate credits-vs-permission on 403 using the error code, since Tripo
+// overloads 403 for both "no permission" and "insufficient credits".
+function classify(res, data) {
+ if (res.status === 401) {
+ throw Object.assign(new Error(data?.message || 'Tripo rejected the API key.'), {
+ code: 'invalid_key',
+ status: 401,
+ providerStatus: res.status,
+ });
+ }
+ if (data?.code === 2010) {
+ throw Object.assign(new Error(data?.message || 'Tripo account is out of credits.'), {
+ code: 'insufficient_credits',
+ status: 402,
+ providerStatus: res.status,
+ });
+ }
+ if (res.status === 403) {
+ throw Object.assign(new Error(data?.message || 'Tripo rejected the API key.'), {
+ code: 'invalid_key',
+ status: 401,
+ providerStatus: res.status,
+ });
+ }
+ if (res.status === 429 || data?.code === 2000) {
+ throw Object.assign(new Error(data?.message || 'Tripo is rate limiting this key.'), {
+ code: 'rate_limited',
+ status: 429,
+ providerStatus: res.status,
+ });
+ }
+ if (!res.ok || data?.code !== 0) {
+ throw Object.assign(
+ new Error(data?.message || `tripo returned ${res.status} (code ${data?.code})`),
+ { code: 'provider_error', status: 502, providerStatus: res.status },
+ );
+ }
+ return data;
+}
+
export function createTripoProvider(apiKey) {
if (!apiKey) {
throw Object.assign(new Error('Tripo API key is required'), { code: 'missing_key' });
@@ -89,10 +127,10 @@ export function createTripoProvider(apiKey) {
'content-type': 'application/json',
};
- async function createTask(body) {
+ async function postJson(path, body) {
let res;
try {
- res = await fetchUpstream(`${TRIPO_BASE}/task`, {
+ res = await fetchUpstream(`${TRIPO_BASE}${path}`, {
method: 'POST',
headers,
body: JSON.stringify(body),
@@ -104,33 +142,11 @@ export function createTripoProvider(apiKey) {
});
}
const data = await res.json().catch(() => ({}));
- if (res.status === 401 || res.status === 403) {
- throw Object.assign(new Error('Tripo rejected the API key.'), {
- code: 'invalid_key',
- status: 401,
- providerStatus: res.status,
- });
- }
- if (res.status === 402 || data?.code === 2000) {
- throw Object.assign(new Error('Tripo account is out of credits.'), {
- code: 'insufficient_credits',
- status: 402,
- });
- }
- if (res.status === 429) {
- throw Object.assign(new Error('Tripo is rate limiting this key.'), {
- code: 'rate_limited',
- status: 429,
- providerStatus: 429,
- });
- }
- // Tripo signals success with code 0; anything else is an error envelope.
- if (!res.ok || data?.code !== 0) {
- throw Object.assign(
- new Error(data?.message || `tripo returned ${res.status} (code ${data?.code})`),
- { code: 'provider_error', status: 502, providerStatus: res.status },
- );
- }
+ return classify(res, data);
+ }
+
+ async function createTask(path, body) {
+ const data = await postJson(path, body);
const taskId = data?.data?.task_id;
if (!taskId) {
throw Object.assign(new Error('tripo accepted the task but returned no task_id'), {
@@ -141,19 +157,19 @@ export function createTripoProvider(apiKey) {
return String(taskId);
}
- // Tripo's image_to_model `file` accepts a public http(s) `url` or an uploaded
- // `file_token` — never an inline data: URI. Selfies arrive as base64 data
- // URIs, so push the raw bytes through Tripo's multipart /upload endpoint and
- // hand the task the returned token. Mirrors createTask's error classification
- // so a bad key / no credits / throttle surfaces the same actionable code.
- async function uploadImage({ bytes, mime, ext }) {
+ // Pushes raw bytes (a selfie data URI, a re-exported mesh, ...) through
+ // Tripo's multipart /files endpoint and hands back a file_token usable as
+ // `input` on any other v3 endpoint. Mirrors createTask's error
+ // classification so a bad key / no credits / throttle surfaces the same
+ // actionable code.
+ async function uploadFile({ bytes, mime, ext }) {
const form = new FormData();
- form.append('file', new Blob([bytes], { type: mime }), `selfie.${ext}`);
+ form.append('file', new Blob([bytes], { type: mime }), `upload.${ext}`);
let res;
try {
- // Let fetch set the multipart content-type (with boundary) itself — only
+ // Let fetch set the multipart content-type (with boundary) itself, only
// forward the bearer, never the JSON content-type from `headers`.
- res = await fetchUpstream(`${TRIPO_BASE}/upload`, {
+ res = await fetchUpstream(`${TRIPO_BASE}/files`, {
method: 'POST',
headers: { authorization: headers.authorization },
body: form,
@@ -165,36 +181,10 @@ export function createTripoProvider(apiKey) {
});
}
const data = await res.json().catch(() => ({}));
- if (res.status === 401 || res.status === 403) {
- throw Object.assign(new Error('Tripo rejected the API key.'), {
- code: 'invalid_key',
- status: 401,
- providerStatus: res.status,
- });
- }
- if (res.status === 402 || data?.code === 2000) {
- throw Object.assign(new Error('Tripo account is out of credits.'), {
- code: 'insufficient_credits',
- status: 402,
- });
- }
- if (res.status === 429) {
- throw Object.assign(new Error('Tripo is rate limiting this key.'), {
- code: 'rate_limited',
- status: 429,
- providerStatus: 429,
- });
- }
- if (!res.ok || data?.code !== 0) {
- throw Object.assign(
- new Error(data?.message || `tripo upload returned ${res.status} (code ${data?.code})`),
- { code: 'provider_error', status: 502, providerStatus: res.status },
- );
- }
- // Upload returns the handle as image_token; older responses use file_token.
- const token = data?.data?.image_token || data?.data?.file_token;
+ classify(res, data);
+ const token = data?.data?.file_token;
if (!token) {
- throw Object.assign(new Error('tripo upload returned no image token'), {
+ throw Object.assign(new Error('tripo upload returned no file_token'), {
code: 'provider_error',
status: 502,
});
@@ -202,14 +192,60 @@ export function createTripoProvider(apiKey) {
return String(token);
}
+ // Resolves an imageUrl/modelUrl into the string the v3 `input` field wants:
+ // a data URI is uploaded first and replaced with its file_token; a real
+ // http(s) URL (or an existing task_id/file_token) passes straight through.
+ async function resolveInput(source) {
+ const parsed = parseImageDataUri(source);
+ if (!parsed) return source;
+ return uploadFile(parsed);
+ }
+
+ // Every task type's status payload is {status, output, credits_consumed,
+ // error_message} except rig-check, whose output is {riggable, rig_type}
+ // instead of a model url. Surface both shapes on the same result object.
+ async function status({ taskId }) {
+ let res;
+ try {
+ res = await fetchUpstream(`${TRIPO_BASE}/tasks/${encodeURIComponent(taskId)}`, { headers }, { name: 'tripo', timeoutMs: 15_000, attempts: 2, okWhen: () => true });
+ } catch (err) {
+ return { status: 'running', error: `tripo poll failed: ${err?.message}` };
+ }
+ const data = await res.json().catch(() => ({}));
+ if (res.status === 404) return { status: 'failed', error: 'tripo task not found' };
+ if (!res.ok || data?.code !== 0) {
+ return { status: 'running', error: `tripo returned ${res.status}` };
+ }
+
+ const d = data.data || {};
+ const taskStatus = mapStatus(d.status);
+ const result = { status: taskStatus, progress: Number(d.progress) || 0 };
+
+ if (taskStatus === 'done') {
+ const out = d.output || {};
+ if (out.model_url) {
+ result.resultGlbUrl = out.model_url;
+ } else if (typeof out.riggable === 'boolean') {
+ result.riggable = out.riggable;
+ result.rigType = out.rig_type || null;
+ } else {
+ result.error = 'tripo finished but produced no model url';
+ }
+ if (typeof d.credits_consumed === 'number') result.creditsConsumed = d.credits_consumed;
+ }
+ if (taskStatus === 'failed') {
+ result.error = d.error_message || `tripo task ${d.status || 'failed'}`;
+ }
+ return result;
+ }
+
return {
// targetFaces overrides the tier's poly budget when the caller sent an
// explicit target_polycount/target_faces (forge-options.js).
async textToGeometry({ prompt, tier, targetPolycount: targetFaces }) {
- const taskId = await createTask({
- type: 'text_to_model',
+ const taskId = await createTask('/generation/text-to-model', {
prompt: String(prompt).slice(0, 1024),
- model_version: modelVersion(),
+ model: modelVersion(),
face_limit: clampFaces(targetFaces ?? tier.polycount),
texture: false,
pbr: false,
@@ -218,16 +254,10 @@ export function createTripoProvider(apiKey) {
},
async imageTo3d({ imageUrl, tier, targetPolycount: targetFaces }) {
- // Data URI (selfie) → upload first and reference the token; a real
- // http(s) URL passes straight through as `file.url`.
- const parsed = parseImageDataUri(imageUrl);
- const file = parsed
- ? { type: parsed.ext, file_token: await uploadImage(parsed) }
- : { type: imageTypeFor(imageUrl), url: imageUrl };
- const taskId = await createTask({
- type: 'image_to_model',
- file,
- model_version: modelVersion(),
+ const input = await resolveInput(imageUrl);
+ const taskId = await createTask('/generation/image-to-model', {
+ input,
+ model: modelVersion(),
face_limit: clampFaces(targetFaces ?? tier.polycount),
texture: true,
pbr: Boolean(tier.pbr),
@@ -236,33 +266,53 @@ export function createTripoProvider(apiKey) {
},
// One status endpoint for every task type.
- async status({ taskId }) {
- let res;
- try {
- res = await fetchUpstream(`${TRIPO_BASE}/task/${encodeURIComponent(taskId)}`, { headers }, { name: 'tripo', timeoutMs: 15_000, attempts: 2, okWhen: () => true });
- } catch (err) {
- return { status: 'running', error: `tripo poll failed: ${err?.message}` };
- }
- const data = await res.json().catch(() => ({}));
- if (res.status === 404) return { status: 'failed', error: 'tripo task not found' };
- if (!res.ok || data?.code !== 0) {
- return { status: 'running', error: `tripo returned ${res.status}` };
- }
+ status,
- const d = data.data || {};
- const status = mapStatus(d.status);
- const result = { status, progress: Number(d.progress) || 0 };
+ // Riggability pre-check: recommended before rig() so the UI can show
+ // "not riggable" without spending a rig credit.
+ async rigCheck({ input }) {
+ const taskId = await createTask('/animations/rig-check', { input: await resolveInput(input) });
+ return { kind: 'task', taskId };
+ },
- if (status === 'done') {
- const out = d.output || d.result || {};
- const glb = out.pbr_model || out.model || out.base_model;
- if (glb) result.resultGlbUrl = glb;
- else result.error = 'tripo finished but produced no model url';
- }
- if (status === 'failed') {
- result.error = `tripo task ${d.status || 'failed'}`;
- }
- return result;
+ // spec:'mixamo' asks Tripo for Mixamo-named bones, which plugs directly
+ // into this repo's existing glb-canonicalize.js Mixamo mapping, no new
+ // bone-naming code needed on our side.
+ async rig({ input, rigType, model, spec = 'mixamo', outFormat = 'glb' }) {
+ const body = { input: await resolveInput(input), spec, out_format: outFormat };
+ if (rigType) body.rig_type = rigType;
+ if (model) body.model = model;
+ const taskId = await createTask('/animations/rig', body);
+ return { kind: 'task', taskId };
+ },
+
+ async retarget({ input, animation, animations, outFormat = 'glb', bakeAnimation = true }) {
+ const body = { input, out_format: outFormat, bake_animation: bakeAnimation };
+ if (Array.isArray(animations) && animations.length) body.animations = animations;
+ else body.animation = animation || 'preset:walk';
+ const taskId = await createTask('/animations/retarget', body);
+ return { kind: 'task', taskId };
},
+
+ // Retopology for the "game-ready" preset. v3.0 can also unwrap UVs
+ // (smart_uv) in the same task; v2.0 (default) does smart highpoly-to-
+ // lowpoly retopology; v1.0 is basic decimation.
+ async decimate({ input, faceLimit, quad = false, smartUv = false, model = 'v2.0' }) {
+ const body = { input: await resolveInput(input), model, quad: Boolean(quad) };
+ if (faceLimit) body.face_limit = clampFaces(faceLimit);
+ if (smartUv) body.smart_uv = true;
+ const taskId = await createTask('/mesh/decimate', body);
+ return { kind: 'task', taskId };
+ },
+
+ // Semantic/geometry segmentation feeding the parts editor.
+ async segment({ input, model = 'v1.0-20250506' }) {
+ const taskId = await createTask('/mesh/segment', { input: await resolveInput(input), model });
+ return { kind: 'task', taskId };
+ },
+
+ // Exposed so callers that already have raw bytes (not an imageUrl/task_id)
+ // can get a file_token without duplicating the upload logic.
+ uploadFile,
};
}
diff --git a/tests/tripo-provider.test.js b/tests/tripo-provider.test.js
index afb3b4f2e..b14d27db1 100644
--- a/tests/tripo-provider.test.js
+++ b/tests/tripo-provider.test.js
@@ -1,9 +1,11 @@
-// Tripo image_to_model input handling. Tripo's `file` object accepts a public
-// http(s) `url` or an uploaded `file_token` — never an inline data: URI. The
-// selfie → avatar pipeline hands the adapter base64 data URIs, so the provider
-// must upload them via /upload and reference the returned token; passing the
-// data URI straight into `file.url` is what produced the 502 "Avatar engine is
-// having trouble" error. These tests pin that behaviour.
+// Tripo v3 provider. v3 unifies every file/task source under a single `input`
+// string field (no more `{type, file_token}` wrapper object) and splits the
+// old single `/task` endpoint into one dedicated endpoint per capability.
+// The selfie -> avatar pipeline hands the adapter base64 data URIs, which have
+// no public URL, so the provider must upload them via /files and reference
+// the returned file_token as `input`; passing the data URI straight through is
+// what produced the 502 "Avatar engine is having trouble" error on v2. These
+// tests pin v3's request/response shapes end to end.
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { createTripoProvider } from '../api/_providers/tripo.js';
@@ -26,11 +28,41 @@ afterEach(() => {
vi.clearAllMocks();
});
-describe('createTripoProvider.imageTo3d — input routing', () => {
- it('uploads a data URI then submits the task with the returned file_token', async () => {
+describe('createTripoProvider: v3 request shapes', () => {
+ it('text-to-model hits the dedicated v3 endpoint with prompt/model/face_limit', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { code: 0, data: { task_id: 'task-default' } }));
+
+ const provider = createTripoProvider(KEY);
+ const out = await provider.textToGeometry({ prompt: 'a brass telescope', tier: { polycount: 30000 } });
+
+ expect(out).toEqual({ kind: 'task', taskId: 'task-default' });
+ const [url, opts] = fetchMock.mock.calls[0];
+ expect(url).toBe('https://openapi.tripo3d.com/v3/generation/text-to-model');
+ expect(opts.headers.authorization).toBe(`Bearer ${KEY}`);
+ const body = JSON.parse(opts.body);
+ expect(body).toEqual({
+ prompt: 'a brass telescope',
+ model: 'v3.1-20260211',
+ face_limit: 30000,
+ texture: false,
+ pbr: false,
+ });
+ });
+
+ it('honors an explicit targetPolycount override over the tier default face_limit', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { code: 0, data: { task_id: 'task-override' } }));
+
+ const provider = createTripoProvider(KEY);
+ await provider.textToGeometry({ prompt: 'a brass telescope', tier: { polycount: 30000 }, targetPolycount: 90_000 });
+
+ const body = JSON.parse(fetchMock.mock.calls[0][1].body);
+ expect(body.face_limit).toBe(90_000);
+ });
+
+ it('image-to-model uploads a data URI then submits input as the returned file_token', async () => {
fetchMock
- .mockResolvedValueOnce(jsonResponse(200, { code: 0, data: { image_token: 'img-123' } })) // /upload
- .mockResolvedValueOnce(jsonResponse(200, { code: 0, data: { task_id: 'task-789' } })); // /task
+ .mockResolvedValueOnce(jsonResponse(200, { code: 0, data: { file_token: 'file-123' } })) // /files
+ .mockResolvedValueOnce(jsonResponse(200, { code: 0, data: { task_id: 'task-789' } })); // /generation/image-to-model
const provider = createTripoProvider(KEY);
const out = await provider.imageTo3d({ imageUrl: DATA_URI, tier: { polycount: 30000, pbr: true } });
@@ -38,107 +70,209 @@ describe('createTripoProvider.imageTo3d — input routing', () => {
expect(out).toEqual({ kind: 'task', taskId: 'task-789' });
expect(fetchMock).toHaveBeenCalledTimes(2);
- // First call: multipart upload, bearer only (no JSON content-type so fetch
- // can set the multipart boundary), FormData body.
+ // First call: multipart upload to /files, bearer only (no JSON content-type
+ // so fetch can set the multipart boundary), FormData body.
const [uploadUrl, uploadOpts] = fetchMock.mock.calls[0];
- expect(uploadUrl).toBe('https://api.tripo3d.ai/v2/openapi/upload');
+ expect(uploadUrl).toBe('https://openapi.tripo3d.com/v3/files');
expect(uploadOpts.method).toBe('POST');
expect(uploadOpts.headers).toEqual({ authorization: `Bearer ${KEY}` });
expect(uploadOpts.body).toBeInstanceOf(FormData);
- // Second call: the task references the uploaded token, never a data: URI.
- const taskBody = JSON.parse(fetchMock.mock.calls[1][1].body);
- expect(taskBody.type).toBe('image_to_model');
- expect(taskBody.file).toEqual({ type: 'jpg', file_token: 'img-123' });
+ // Second call: input is the plain file_token string, never a data: URI or
+ // the old v2 {type, file_token} wrapper.
+ const [taskUrl, taskOpts] = fetchMock.mock.calls[1];
+ expect(taskUrl).toBe('https://openapi.tripo3d.com/v3/generation/image-to-model');
+ const taskBody = JSON.parse(taskOpts.body);
+ expect(taskBody.input).toBe('file-123');
expect(JSON.stringify(taskBody)).not.toContain('data:image');
});
- it('accepts an older upload response that returns file_token', async () => {
- fetchMock
- .mockResolvedValueOnce(jsonResponse(200, { code: 0, data: { file_token: 'tok-legacy' } }))
- .mockResolvedValueOnce(jsonResponse(200, { code: 0, data: { task_id: 't2' } }));
+ it('passes a real http(s) URL straight through as input without an upload call', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { code: 0, data: { task_id: 'task-url' } }));
const provider = createTripoProvider(KEY);
- await provider.imageTo3d({ imageUrl: DATA_URI, tier: { polycount: 30000, pbr: false } });
+ const out = await provider.imageTo3d({
+ imageUrl: 'https://cdn.example.com/selfie.png',
+ tier: { polycount: 30000, pbr: true },
+ });
- const taskBody = JSON.parse(fetchMock.mock.calls[1][1].body);
- expect(taskBody.file.file_token).toBe('tok-legacy');
+ expect(out.taskId).toBe('task-url');
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const body = JSON.parse(fetchMock.mock.calls[0][1].body);
+ expect(body.input).toBe('https://cdn.example.com/selfie.png');
+ expect(body.pbr).toBe(true);
});
- it('passes a real http(s) URL straight through without an upload call', async () => {
- fetchMock.mockResolvedValueOnce(jsonResponse(200, { code: 0, data: { task_id: 'task-url' } }));
+ it('honors targetPolycount on the image-to-model path too', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { code: 0, data: { task_id: 'task-img-override' } }));
const provider = createTripoProvider(KEY);
- const out = await provider.imageTo3d({
+ await provider.imageTo3d({
imageUrl: 'https://cdn.example.com/selfie.png',
tier: { polycount: 30000, pbr: true },
+ targetPolycount: 60_000,
});
- expect(out.taskId).toBe('task-url');
- expect(fetchMock).toHaveBeenCalledTimes(1);
- const taskBody = JSON.parse(fetchMock.mock.calls[0][1].body);
- expect(taskBody.file).toEqual({ type: 'png', url: 'https://cdn.example.com/selfie.png' });
+ const body = JSON.parse(fetchMock.mock.calls[0][1].body);
+ expect(body.face_limit).toBe(60_000);
});
- it('honors an explicit targetPolycount override over the tier default face_limit', async () => {
- fetchMock.mockResolvedValueOnce(jsonResponse(200, { code: 0, data: { task_id: 'task-override' } }));
+ it('TRIPO_MODEL_VERSION overrides the default model on both generation paths', async () => {
+ const prior = process.env.TRIPO_MODEL_VERSION;
+ process.env.TRIPO_MODEL_VERSION = 'v3.0-20250812';
+ try {
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { code: 0, data: { task_id: 'task-pinned' } }));
+ const provider = createTripoProvider(KEY);
+ await provider.textToGeometry({ prompt: 'a cat', tier: { polycount: 10000 } });
+ const body = JSON.parse(fetchMock.mock.calls[0][1].body);
+ expect(body.model).toBe('v3.0-20250812');
+ } finally {
+ if (prior === undefined) delete process.env.TRIPO_MODEL_VERSION;
+ else process.env.TRIPO_MODEL_VERSION = prior;
+ }
+ });
+
+ it('status() polls GET /tasks/{id} and maps a successful model task', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, {
+ code: 0,
+ data: {
+ task_id: 'task-abc123',
+ type: 'text_to_model',
+ status: 'success',
+ progress: 100,
+ output: { model_url: 'https://cdn.tripo3d.ai/output/model_pbr.glb' },
+ credits_consumed: 100,
+ },
+ }));
const provider = createTripoProvider(KEY);
- await provider.textToGeometry({ prompt: 'a brass telescope', tier: { polycount: 30000 }, targetPolycount: 90_000 });
+ const result = await provider.status({ taskId: 'task-abc123' });
- const taskBody = JSON.parse(fetchMock.mock.calls[0][1].body);
- expect(taskBody.face_limit).toBe(90_000);
+ expect(fetchMock.mock.calls[0][0]).toBe('https://openapi.tripo3d.com/v3/tasks/task-abc123');
+ expect(result).toEqual({
+ status: 'done',
+ progress: 100,
+ resultGlbUrl: 'https://cdn.tripo3d.ai/output/model_pbr.glb',
+ creditsConsumed: 100,
+ });
});
- it('falls back to the tier polycount when no override is supplied', async () => {
- fetchMock.mockResolvedValueOnce(jsonResponse(200, { code: 0, data: { task_id: 'task-default' } }));
+ it('status() surfaces a running task without a result url', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, {
+ code: 0,
+ data: { task_id: 't1', status: 'running', progress: 42 },
+ }));
+ const provider = createTripoProvider(KEY);
+ const result = await provider.status({ taskId: 't1' });
+ expect(result).toEqual({ status: 'running', progress: 42 });
+ });
+ it('status() surfaces a failed task with the error message', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, {
+ code: 0,
+ data: { task_id: 't1', status: 'failed', progress: 0, error_message: 'Generation failed' },
+ }));
const provider = createTripoProvider(KEY);
- await provider.textToGeometry({ prompt: 'a brass telescope', tier: { polycount: 30000 } });
+ const result = await provider.status({ taskId: 't1' });
+ expect(result).toEqual({ status: 'failed', progress: 0, error: 'Generation failed' });
+ });
- const taskBody = JSON.parse(fetchMock.mock.calls[0][1].body);
- expect(taskBody.face_limit).toBe(30000);
+ it('status() maps rig-check output {riggable, rig_type} distinctly from a model url', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, {
+ code: 0,
+ data: { task_id: 't2', status: 'success', progress: 100, output: { riggable: true, rig_type: 'biped' }, credits_consumed: 0 },
+ }));
+ const provider = createTripoProvider(KEY);
+ const result = await provider.status({ taskId: 't2' });
+ expect(result).toEqual({ status: 'done', progress: 100, riggable: true, rigType: 'biped', creditsConsumed: 0 });
});
- it('honors targetPolycount on the image_to_model path too', async () => {
- fetchMock.mockResolvedValueOnce(jsonResponse(200, { code: 0, data: { task_id: 'task-img-override' } }));
+ it('rigCheck() posts to /animations/rig-check with input', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { code: 0, data: { task_id: 'task-rc' } }));
+ const provider = createTripoProvider(KEY);
+ const out = await provider.rigCheck({ input: 'task_abc123' });
+ expect(out).toEqual({ kind: 'task', taskId: 'task-rc' });
+ expect(fetchMock.mock.calls[0][0]).toBe('https://openapi.tripo3d.com/v3/animations/rig-check');
+ expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ input: 'task_abc123' });
+ });
+ it('rig() defaults spec to mixamo so output plugs into glb-canonicalize.js', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { code: 0, data: { task_id: 'task-rig' } }));
const provider = createTripoProvider(KEY);
- await provider.imageTo3d({
- imageUrl: 'https://cdn.example.com/selfie.png',
- tier: { polycount: 30000, pbr: true },
- targetPolycount: 60_000,
- });
+ await provider.rig({ input: 'task_abc123', rigType: 'biped' });
+ const body = JSON.parse(fetchMock.mock.calls[0][1].body);
+ expect(fetchMock.mock.calls[0][0]).toBe('https://openapi.tripo3d.com/v3/animations/rig');
+ expect(body).toEqual({ input: 'task_abc123', spec: 'mixamo', out_format: 'glb', rig_type: 'biped' });
+ });
- const taskBody = JSON.parse(fetchMock.mock.calls[0][1].body);
- expect(taskBody.face_limit).toBe(60_000);
+ it('retarget() sends a single animation by default and an array when given animations', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { code: 0, data: { task_id: 'task-rt' } }));
+ const provider = createTripoProvider(KEY);
+ await provider.retarget({ input: 'task_rigged', animations: ['preset:idle', 'preset:walk'] });
+ const body = JSON.parse(fetchMock.mock.calls[0][1].body);
+ expect(fetchMock.mock.calls[0][0]).toBe('https://openapi.tripo3d.com/v3/animations/retarget');
+ expect(body).toEqual({ input: 'task_rigged', out_format: 'glb', bake_animation: true, animations: ['preset:idle', 'preset:walk'] });
});
- it('maps an upload auth failure to invalid_key (401) and never submits a task', async () => {
- fetchMock.mockResolvedValueOnce(jsonResponse(401, { code: 1001, message: 'bad key' }));
+ it('decimate() builds the game-ready quad request against /mesh/decimate', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { code: 0, data: { task_id: 'task-dec' } }));
+ const provider = createTripoProvider(KEY);
+ await provider.decimate({ input: 'task_abc123', faceLimit: 15000, quad: true, model: 'v3.0' });
+ const body = JSON.parse(fetchMock.mock.calls[0][1].body);
+ expect(fetchMock.mock.calls[0][0]).toBe('https://openapi.tripo3d.com/v3/mesh/decimate');
+ expect(body).toEqual({ input: 'task_abc123', model: 'v3.0', quad: true, face_limit: 15000 });
+ });
+ it('segment() posts to /mesh/segment with the default v1 model', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { code: 0, data: { task_id: 'task-seg' } }));
+ const provider = createTripoProvider(KEY);
+ await provider.segment({ input: 'task_abc123' });
+ const body = JSON.parse(fetchMock.mock.calls[0][1].body);
+ expect(fetchMock.mock.calls[0][0]).toBe('https://openapi.tripo3d.com/v3/mesh/segment');
+ expect(body).toEqual({ input: 'task_abc123', model: 'v1.0-20250506' });
+ });
+
+ it('maps a 401 to invalid_key and never submits a task', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse(401, { code: 1000, message: 'Invalid API Key', suggestion: 'check your key', request_id: 'req_1' }));
const provider = createTripoProvider(KEY);
await expect(
- provider.imageTo3d({ imageUrl: DATA_URI, tier: { polycount: 30000, pbr: true } }),
+ provider.textToGeometry({ prompt: 'a cat', tier: { polycount: 10000 } }),
).rejects.toMatchObject({ code: 'invalid_key', status: 401 });
- expect(fetchMock).toHaveBeenCalledTimes(1);
});
- it('maps an out-of-credits upload to insufficient_credits (402)', async () => {
- fetchMock.mockResolvedValueOnce(jsonResponse(402, { code: 2000, message: 'no credits' }));
-
+ it('maps a 403 with error code 2010 to insufficient_credits', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse(403, { code: 2010, message: 'Insufficient credits', suggestion: 'top up', request_id: 'req_2' }));
const provider = createTripoProvider(KEY);
await expect(
- provider.imageTo3d({ imageUrl: DATA_URI, tier: { polycount: 30000, pbr: true } }),
+ provider.textToGeometry({ prompt: 'a cat', tier: { polycount: 10000 } }),
).rejects.toMatchObject({ code: 'insufficient_credits', status: 402 });
});
- it('treats an upload with no token as a provider_error (502)', async () => {
- fetchMock.mockResolvedValueOnce(jsonResponse(200, { code: 0, data: {} }));
+ it('maps a 403 without the credits error code to invalid_key (permission denied)', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse(403, { code: 1001, message: 'Unauthorized', suggestion: 'check headers', request_id: 'req_3' }));
+ const provider = createTripoProvider(KEY);
+ await expect(
+ provider.textToGeometry({ prompt: 'a cat', tier: { polycount: 10000 } }),
+ ).rejects.toMatchObject({ code: 'invalid_key', status: 401 });
+ });
+
+ it('maps a 429 to rate_limited', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse(429, { code: 2000, message: 'Rate limit exceeded', suggestion: 'slow down', request_id: 'req_4' }));
+ const provider = createTripoProvider(KEY);
+ await expect(
+ provider.textToGeometry({ prompt: 'a cat', tier: { polycount: 10000 } }),
+ ).rejects.toMatchObject({ code: 'rate_limited', status: 429 });
+ });
+ it('treats a 200 with no task_id as a provider_error (502)', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { code: 0, data: {} }));
const provider = createTripoProvider(KEY);
await expect(
- provider.imageTo3d({ imageUrl: DATA_URI, tier: { polycount: 30000, pbr: true } }),
+ provider.textToGeometry({ prompt: 'a cat', tier: { polycount: 10000 } }),
).rejects.toMatchObject({ code: 'provider_error', status: 502 });
});
+
+ it('throws missing_key when constructed without an API key', () => {
+ expect(() => createTripoProvider('')).toThrow(expect.objectContaining({ code: 'missing_key' }));
+ });
});