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(forge): make TRELLIS.2 the default image-to-3D lane and keep Tencent model lanes out of the EU, UK and South Korea
nirholas5e81159676d5
diff --git a/api/_lib/forge-cache.js b/api/_lib/forge-cache.jsindex 98d4016c2..b3f0a73ac 100644--- a/api/_lib/forge-cache.js+++ b/api/_lib/forge-cache.js@@ -78,6 +78,7 @@ export function forgeResultCacheKey({ path, tier, backend, prompt, options }) {opt.outputFormat || 'glb',opt.textureSize ?? null,opt.targetPolycount ?? null,+ ...(opt.resolution ? [opt.resolution] : []),]);return createHash('sha256').update(basis).digest('hex').slice(0, 40);}diff --git a/api/_lib/forge-failover.js b/api/_lib/forge-failover.jsindex 5e6d1b82a..18ff8efe1 100644--- a/api/_lib/forge-failover.js+++ b/api/_lib/forge-failover.js@@ -36,6 +36,7 @@ import { getRedis } from './redis.js';import { BACKENDS, backendIsConfigured, resolveTier } from './forge-tiers.js';import { laneHealthSnapshot } from './forge-lane-health.js';import { encodeJobToken } from './forge-job-token.js';+import { laneAllowedInTerritory } from './forge-territory.js';const PREFIX = 'fr:successor:';// Outlive the polling window of a slow cold-start generation, with margin.@@ -55,14 +56,14 @@ export const MAX_FAILOVER_HOPS = 3;// 2026-09-18..28 worker outage, which took Hunyuan3D and TRELLIS self-host// down together, ended roughly 400 photo jobs a day in a hard failure while// the TripoSG worker sat healthy.-const ASYNC_REDISPATCH_ORDER = ['trellis_selfhost', 'hunyuan3d', 'trellis', 'triposg'];+const ASYNC_REDISPATCH_ORDER = ['trellis2', 'trellis_selfhost', 'hunyuan3d', 'trellis', 'triposg'];// Lanes a CLIENT can retry with a fresh POST, per input mode. A fresh POST may// ride blocking lanes too, so HuggingFace joins here; NVIDIA only serves text.// TripoSG is absent: its public lane is sketch-only, so a fresh photo POST// naming it would be refused. It serves photos only as the poll-time rung.-const SUGGESTION_ORDER_IMAGE = ['trellis_selfhost', 'hunyuan3d', 'huggingface', 'trellis'];-const SUGGESTION_ORDER_TEXT = ['nvidia', 'trellis_selfhost', 'hunyuan3d', 'huggingface', 'trellis'];+const SUGGESTION_ORDER_IMAGE = ['trellis2', 'trellis_selfhost', 'hunyuan3d', 'huggingface', 'trellis'];+const SUGGESTION_ORDER_TEXT = ['nvidia', 'trellis2', 'trellis_selfhost', 'hunyuan3d', 'huggingface', 'trellis'];function client(override) {return override || getRedis();@@ -127,9 +128,13 @@ export async function resolveLiveJob(originalHandle, { redis } = {}) {* lanes already attempted for this job, lanes not configured on this* deployment, and lanes the health snapshot marks down/cooled.*/-export async function pickRedispatchLane({ attempted = [] } = {}) {+export async function pickRedispatchLane({ attempted = [], country = null } = {}) {const candidates = ASYNC_REDISPATCH_ORDER.filter(- (id) => !attempted.includes(id) && BACKENDS[id] && backendIsConfigured(id),+ (id) =>+ !attempted.includes(id) &&+ BACKENDS[id] &&+ backendIsConfigured(id) &&+ laneAllowedInTerritory(id, country),);if (!candidates.length) return null;try {@@ -149,9 +154,15 @@ export async function pickRedispatchLane({ attempted = [] } = {}) {* `hasImage` scopes to reconstruct-capable lanes (NVIDIA's hosted preview is* text-only and would 4xx a photo).*/-export function retryBackendSuggestions({ attempted = [], hasImage = false } = {}) {+export function retryBackendSuggestions({ attempted = [], hasImage = false, country = null } = {}) {const order = hasImage ? SUGGESTION_ORDER_IMAGE : SUGGESTION_ORDER_TEXT;- return order.filter((id) => !attempted.includes(id) && BACKENDS[id] && backendIsConfigured(id));+ return order.filter(+ (id) =>+ !attempted.includes(id) &&+ BACKENDS[id] &&+ backendIsConfigured(id) &&+ laneAllowedInTerritory(id, country),+ );}/**@@ -164,6 +175,16 @@ export async function submitFailoverJob({ backend, imageUrl, prompt, tierId, patif (!imageUrl) throw new Error('failover needs a stored reference image');const tier = resolveTier(tierId);+ if (backend === 'trellis2') {+ const { createRegenProvider } = await import('../_providers/gcp.js');+ const job = await createRegenProvider().submit({+ mode: 'trellis2',+ sourceUrl: imageUrl,+ params: { images: [imageUrl], tier: tier.id },+ });+ return { extJobId: job.extJobId, handle: encodeJobToken({ provider: 'gcp', kind: null, taskId: job.extJobId }) };+ }+if (backend === 'trellis_selfhost') {const { createRegenProvider } = await import('../_providers/gcp.js');const job = await createRegenProvider().submit({diff --git a/api/_lib/forge-health.js b/api/_lib/forge-health.jsindex efc75fc4d..9059e5500 100644--- a/api/_lib/forge-health.js+++ b/api/_lib/forge-health.js@@ -282,6 +282,9 @@ const PROBES = {// nothing flagging it. It publishes the same /health contract the other GCP// workers do, load_error included, so the shared probe reads it as down.trellis_selfhost: gcpWorkerProbe('trellis_selfhost', 'MODEL_TRELLIS_URL'),+ // TRELLIS.2 is the default image lane for every tier. Same /health contract as+ // the other workers, so a latched model-load failure reads as down here too.+ trellis2: gcpWorkerProbe('trellis2', 'MODEL_TRELLIS2_URL'),};// The editing lanes: everything the result panel offers AFTER a mesh existsdiff --git a/api/_lib/forge-options.js b/api/_lib/forge-options.jsindex a87e5817c..f3e8e5ad0 100644--- a/api/_lib/forge-options.js+++ b/api/_lib/forge-options.js@@ -8,6 +8,7 @@// • output_format — glb (default) or a compressed variant (draco / meshopt)// • texture_size — bake textures at a specific resolution// • target_polycount — explicit geometry budget on poly-aware backends+// • resolution : TRELLIS.2 voxel resolution (512, 1024 or 1536)// • derive_pbr : the ONE exception to "off by default": the material// completion pass (glb-pbr-derive.js) runs on every delivered mesh, because// an albedo-only material is a defect rather than a preference. Send@@ -18,6 +19,8 @@// message rather than silently doing something the caller didn't ask for. A value// that is simply absent is never an error — it just keeps the current default.+import { TRELLIS2_RESOLUTIONS } from './forge-tiers.js';+// glb is the universal default. The two compressed variants run a post-generation// pass (see glb-compress.js) that shrinks the delivered file without changing the// rendered result — Draco for geometry, meshopt (EXT_meshopt_compression) for@@ -45,6 +48,7 @@ function compressionFor(format) {* compression: 'none' | 'draco' | 'meshopt',* textureSize: number | null,* targetPolycount: number | null,+ * resolution: 512 | 1024 | 1536 | null, // TRELLIS.2 voxel resolution* derivePbr: boolean, // material completion pass, true unless opted out* hasOptions: boolean, // true iff any non-default option was supplied* errors: Array<{ field: string, message: string }>,@@ -113,6 +117,20 @@ export function normalizeForgeOptions(body) {}}+ // resolution: TRELLIS.2 voxel resolution. Absent keeps the tier's own mapping+ // (draft 512, standard and high 1024); any other value is rejected rather than+ // silently clamped to a different cost and quality than the caller asked for.+ let resolution = null;+ if (b.resolution !== undefined && b.resolution !== null && b.resolution !== '') {+ const n = Number(b.resolution);+ if (TRELLIS2_RESOLUTIONS.includes(n)) resolution = n;+ else+ errors.push({+ field: 'resolution',+ message: `resolution must be one of: ${TRELLIS2_RESOLUTIONS.join(', ')}.`,+ });+ }+// derive_pbr: opt-OUT. Anything other than an explicit boolean false leaves// the completion pass on; a non-boolean value is reported rather than// silently coerced, so `derive_pbr: "no"` never reads as true.@@ -126,7 +144,7 @@ export function normalizeForgeOptions(body) {}const hasOptions =- seed !== null || outputFormat !== 'glb' || textureSize !== null || targetPolycount !== null || !derivePbr;+ seed !== null || outputFormat !== 'glb' || textureSize !== null || targetPolycount !== null || resolution !== null || !derivePbr;return {seed,@@ -134,6 +152,7 @@ export function normalizeForgeOptions(body) {compression: compressionFor(outputFormat),textureSize,targetPolycount,+ resolution,derivePbr,hasOptions,errors,@@ -166,6 +185,7 @@ export function summarizeForgeOptions(opts) {output_format: opts.outputFormat,texture_size: opts.textureSize,target_polycount: opts.targetPolycount,+ resolution: opts.resolution ?? null,derive_pbr: opts.derivePbr !== false,};}diff --git a/api/_lib/forge-scale.js b/api/_lib/forge-scale.jsindex 72fac0998..35e60b472 100644--- a/api/_lib/forge-scale.js+++ b/api/_lib/forge-scale.js@@ -59,6 +59,7 @@ export function forgeRequestHash({ path, tier, backend, prompt, images, optionsopt.outputFormat || 'glb',opt.textureSize ?? null,opt.targetPolycount ?? null,+ ...(opt.resolution ? [opt.resolution] : []),]);return createHash('sha256').update(basis).digest('hex').slice(0, 32);}diff --git a/api/_lib/forge-territory.js b/api/_lib/forge-territory.jsnew file mode 100644index 000000000..15eaabb14--- /dev/null+++ b/api/_lib/forge-territory.js@@ -0,0 +1,57 @@+/**+ * Forge territory router+ * ----------------------+ * Some model licences exclude whole regions. The Hunyuan3D 2.1 community+ * licence (Territory clause) does not grant any rights in the European Union,+ * the United Kingdom or South Korea, for the model or for its output. three.ws+ * serves those regions, so a request that originates there must never be+ * routed to a lane that runs a Tencent model.+ *+ * The country is resolved server side from the edge geo header+ * (api/_lib/client-geo.js), never from a field the caller controls. An unknown+ * country fails closed: the request is treated as restricted, because the+ * alternative is shipping a licensed-out model to a region we could not rule+ * out.+ *+ * Lanes that run a Tencent model:+ * - hunyuan3d our own Hunyuan3D 2.1 worker.+ * - huggingface the free Spaces lane, whose chain is Hunyuan Spaces.+ */++import { clientCountry } from './client-geo.js';++export const TENCENT_LANES = Object.freeze(['hunyuan3d', 'huggingface']);++// ISO 3166-1 alpha-2. EU member states, the UK and South Korea.+export const RESTRICTED_COUNTRIES = Object.freeze([+ 'AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'HU', 'IE',+ 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE',+ 'GB', 'KR',+]);++const RESTRICTED = new Set(RESTRICTED_COUNTRIES);++/** True when the country is in a restricted territory or could not be resolved. */+export function isRestrictedTerritory(country) {+ if (typeof country !== 'string' || !/^[A-Za-z]{2}$/.test(country)) return true;+ return RESTRICTED.has(country.toUpperCase());+}++export function isTencentLane(laneId) {+ return TENCENT_LANES.includes(laneId);+}++/** Whether `laneId` may serve a request from `country`. */+export function laneAllowedInTerritory(laneId, country) {+ return !isTencentLane(laneId) || !isRestrictedTerritory(country);+}++/** Drop every lane the territory rule forbids, preserving order. */+export function filterLanesForTerritory(laneIds, country) {+ return laneIds.filter((id) => laneAllowedInTerritory(id, country));+}++/** Country of the requester, resolved from the edge header; null when unknown. */+export function requestTerritory(req) {+ return clientCountry(req);+}diff --git a/api/_lib/forge-tiers.js b/api/_lib/forge-tiers.jsindex 32919c2a6..d7c65b2e3 100644--- a/api/_lib/forge-tiers.js+++ b/api/_lib/forge-tiers.js@@ -24,6 +24,8 @@// (BYOK) key, and its per-(path,tier) cost/latency estimates so the UI can// communicate the trade-off before the user commits.+import { laneAllowedInTerritory } from './forge-territory.js';+export const PATHS = Object.freeze(['image', 'geometry', 'sketch']);export const DEFAULT_PATH = 'image';export const TIER_IDS = Object.freeze(['draft', 'standard', 'high']);@@ -247,6 +249,27 @@ export const BACKENDS = Object.freeze({free: true,blurb: 'Free self-hosted high-poly reconstruction on our own GPU worker — image-conditioned geometry, zero vendor cost.',}),+ trellis2: Object.freeze({+ id: 'trellis2',+ label: 'TRELLIS.2 (self-host)',+ vendor: 'Microsoft TRELLIS.2 · self-host',+ paths: Object.freeze(['image']),+ byok: false,+ provider: 'gcp',+ // Our own TRELLIS.2 worker (workers/model-trellis2 on Cloud Run, MIT, 4B+ // flow transformer). Native single-hop image to 3D with PBR materials and+ // alpha, at a 512, 1024 or 1536 voxel resolution the caller can choose.+ // MIT licensed and territory-free, which is why it replaced Hunyuan3D as+ // the default image lane (see api/_lib/forge-territory.js).+ requiresEnv: Object.freeze(['MODEL_TRELLIS2_URL', 'GCP_RECONSTRUCTION_KEY']),+ polyControl: false,+ userImages: true,+ baseEta: 75,+ coldStartSeconds: 90,+ credits: null,+ free: true,+ blurb: 'Free native image to 3D on our own TRELLIS.2 worker: PBR materials with transparency, up to 1536 resolution, no vendor cost, available in every region.',+ }),trellis_selfhost: Object.freeze({id: 'trellis_selfhost',label: 'TRELLIS (self-host)',@@ -377,10 +400,10 @@ export const DEFAULT_BACKEND_FOR_PATH = Object.freeze({// highest-leverage lever on "does this look like a real photograph" the// platform has, and it must apply by default, not only at the high tier.//-// • draft / standard → our self-host TRELLIS worker (image-intermediate,-// fast, free); falls to Hunyuan3D / HuggingFace / (last) NVIDIA NIM via-// FREE_FALLBACK_FOR_PATH when self-host isn't configured.-// • high → self-host Hunyuan3D — textured, higher-fidelity, free.+// • every tier → our self-host TRELLIS.2 worker (image-intermediate, PBR,+// free, MIT licensed, served in every region); falls to self-host TRELLIS+// v1, then Hunyuan3D / HuggingFace (never in the EU, UK or South Korea, see+// forge-territory.js) and (last) NVIDIA NIM via FREE_FALLBACK_FOR_PATH.//// NVIDIA's hosted TRELLIS preview (native text→mesh, no reference image) is// NEVER a named default here anymore — see BACKENDS.nvidia's `userImages:@@ -398,15 +421,13 @@ export const DEFAULT_BACKEND_FOR_PATH = Object.freeze({// to recover vendor cost. Paid backends (Replicate/Meshy/Tripo) stay explicitly// selectable at every tier.export const FREE_DEFAULT_FOR_TIERS = Object.freeze({- draft: Object.freeze({ image: 'trellis_selfhost' }),- standard: Object.freeze({ image: 'trellis_selfhost' }),- // High names our self-host Hunyuan3D worker — the highest-fidelity engine we- // can run on our own GPUs. Until GCP_HUNYUAN3D_URL is configured the candidate- // walk falls to the per-path chain (self-host TRELLIS first). The external- // HuggingFace Spaces lane (the previous name here) stays in the fallback chain- // but no longer leads: its Hunyuan Spaces sit GPU-quota-dead for most of the- // day, so naming it made the tier a coin-flip.- high: Object.freeze({ image: 'hunyuan3d' }),+ draft: Object.freeze({ image: 'trellis2' }),+ standard: Object.freeze({ image: 'trellis2' }),+ // TRELLIS.2 is the default at every tier: it is MIT licensed with no territory+ // exclusion, and the tier maps to its resolution (workers/model-trellis2+ // request_policy.py), so high buys 1536 rather than a different engine.+ // Hunyuan3D stays in the fallback chain for regions its licence covers.+ high: Object.freeze({ image: 'trellis2' }),});// Free lanes to fall back to per path when the tier's named free engine can't@@ -414,8 +435,9 @@ export const FREE_DEFAULT_FOR_TIERS = Object.freeze({// hosted preview is text-only), which routes to a free reconstruct lane instead// of a paid engine. First configured + capable lane wins, and our OWN GPU workers// come first so the platform leans on the credits we control before any external-// free lane: self-hosted TRELLIS (native single-hop image→3D), then self-hosted-// Hunyuan3D, then the free HuggingFace Spaces lane. The free NVIDIA NIM TRELLIS+// free lane: self-hosted TRELLIS.2, then self-hosted TRELLIS v1, then self-hosted+// Hunyuan3D, then the free HuggingFace Spaces lane. The two Tencent lanes are+// dropped for requests from the EU, the UK, South Korea or an unknown country. The free NVIDIA NIM TRELLIS// lane trails as the final health-gated fallthrough so a text prompt still// returns a model when every GPU worker (and HuggingFace) is cold or down — this// is the realism-tier safety net that guarantees the High/MAX path never dead-ends@@ -423,7 +445,7 @@ export const FREE_DEFAULT_FOR_TIERS = Object.freeze({// submission filters it out and stops at HuggingFace, exactly as before. Every// entry is env-gated, so the list degrades cleanly on partial deployments.export const FREE_FALLBACK_FOR_PATH = Object.freeze({- image: Object.freeze(['trellis_selfhost', 'hunyuan3d', 'huggingface', 'nvidia']),+ image: Object.freeze(['trellis2', 'trellis_selfhost', 'hunyuan3d', 'huggingface', 'nvidia']),});// Realism subject classes. The two self-host PBR lanes have different strengths:@@ -495,7 +517,7 @@ function freeLaneUsable(id, p, userImages) {// lane). De-duplicated; only configured + capable lanes survive.// This is the single ordering both the env-only default and the health-aware// resolver walk, so they can never drift apart.-export function freeLaneCandidates(p, tierId, userImages, subjectClass = null) {+export function freeLaneCandidates(p, tierId, userImages, subjectClass = null, country = null) {const ordered = [];const named = FREE_DEFAULT_FOR_TIERS[tierId]?.[p];if (named) ordered.push(named);@@ -530,7 +552,7 @@ export function freeLaneCandidates(p, tierId, userImages, subjectClass = null) {for (const id of prioritized) {if (seen.has(id)) continue;seen.add(id);- if (freeLaneUsable(id, p, userImages)) out.push(id);+ if (freeLaneUsable(id, p, userImages) && laneAllowedInTerritory(id, country)) out.push(id);}return out;}@@ -538,8 +560,8 @@ export function freeLaneCandidates(p, tierId, userImages, subjectClass = null) {// Resolve the default backend for a (path, tier) when the caller didn't name one.// Free-for-us policy: the first configured free lane in the candidate ordering,// and only the paid standing default when NO free lane is live on this deployment.-function defaultBackendFor(p, tierId, userImages, subjectClass = null) {- const candidates = freeLaneCandidates(p, tierId, userImages, subjectClass);+function defaultBackendFor(p, tierId, userImages, subjectClass = null, country = null) {+ const candidates = freeLaneCandidates(p, tierId, userImages, subjectClass, country);return candidates[0] || DEFAULT_BACKEND_FOR_PATH[p];}@@ -557,8 +579,8 @@ function defaultBackendFor(p, tierId, userImages, subjectClass = null) {// 3. Only when every free lane is confirmed down, the paid standing default.// With an empty/undefined health map this returns exactly what defaultBackendFor// would, so callers with no telemetry are unaffected.-export function defaultBackendForHealthAware(p, tierId, userImages, health, subjectClass = null) {- const candidates = freeLaneCandidates(p, tierId, userImages, subjectClass);+export function defaultBackendForHealthAware(p, tierId, userImages, health, subjectClass = null, country = null) {+ const candidates = freeLaneCandidates(p, tierId, userImages, subjectClass, country);if (!candidates.length) return DEFAULT_BACKEND_FOR_PATH[p];const statusOf = (id) => health?.[id];const preferred = candidates.find((id) => {@@ -577,13 +599,13 @@ export function defaultBackendForHealthAware(p, tierId, userImages, health, subj// the resolved default must be a backend that accepts them. An explicitly named// backend is always honored here — the forge handler rejects an unsupported// (backend, input) combination with a designed error at the boundary instead.-export function resolveBackendId({ path, tier, backend, userImages = false, subjectClass = null }) {+export function resolveBackendId({ path, tier, backend, userImages = false, subjectClass = null, country = null }) {const p = PATHS.includes(path) ? path : DEFAULT_PATH;if (backend && BACKENDS[backend] && BACKENDS[backend].paths.includes(p)) {return backend;}const tierId = tier?.id || tier || DEFAULT_TIER;- return defaultBackendFor(p, tierId, userImages, subjectClass);+ return defaultBackendFor(p, tierId, userImages, subjectClass, country);}// Health-aware twin of resolveBackendId: an explicitly named backend is always@@ -593,13 +615,13 @@ export function resolveBackendId({ path, tier, backend, userImages = false, subj// laneId → status map (see defaultBackendForHealthAware). Pure — the caller// gathers the (cached) snapshot and passes it in, so this stays trivially// testable and adds no I/O of its own.-export function resolveBackendIdWithHealth({ path, tier, backend, userImages = false, health, subjectClass = null }) {+export function resolveBackendIdWithHealth({ path, tier, backend, userImages = false, health, subjectClass = null, country = null }) {const p = PATHS.includes(path) ? path : DEFAULT_PATH;if (backend && BACKENDS[backend] && BACKENDS[backend].paths.includes(p)) {return backend;}const tierId = tier?.id || tier || DEFAULT_TIER;- return defaultBackendForHealthAware(p, tierId, userImages, health, subjectClass);+ return defaultBackendForHealthAware(p, tierId, userImages, health, subjectClass, country);}// Where a request goes after the free HuggingFace Spaces lane failed to serve it.@@ -619,9 +641,9 @@ export function resolveBackendIdWithHealth({ path, tier, backend, userImages = f// caller named that engine, so it is never silently swapped.//// Returns 'hunyuan3d' | 'nvidia' | null (null = surface the busy state).-export function laneAfterHfFailure({ explicit = false, userImages = false } = {}) {+export function laneAfterHfFailure({ explicit = false, userImages = false, country = null } = {}) {if (explicit) return null;- if (backendIsConfigured('hunyuan3d')) return 'hunyuan3d';+ if (backendIsConfigured('hunyuan3d') && laneAllowedInTerritory('hunyuan3d', country)) return 'hunyuan3d';if (!userImages && backendIsConfigured('nvidia')) return 'nvidia';return null;}@@ -690,6 +712,11 @@ export const SELFHOST_TRELLIS_QUALITY = Object.freeze({high: Object.freeze({ ss_steps: 50, slat_steps: 50, simplify: 0.65, texture_size: 4096 }),});+// TRELLIS.2 voxel resolutions a caller may request (workers/model-trellis2+// request_policy.py RESOLUTIONS). Omitted, the worker maps the tier to one:+// draft 512, standard and high 1024, max 1536.+export const TRELLIS2_RESOLUTIONS = Object.freeze([512, 1024, 1536]);+export function selfhostQualityForTier(tierId) {return SELFHOST_TRELLIS_QUALITY[tierId] || SELFHOST_TRELLIS_QUALITY[DEFAULT_TIER];}@@ -797,6 +824,8 @@ export function buildCatalog() {user_images: b.userImages !== false,configured: backendIsConfigured(b.id),blurb: b.blurb,+ // Voxel resolutions the lane accepts as the `resolution` request option.+ resolutions: b.id === 'trellis2' ? TRELLIS2_RESOLUTIONS : undefined,estimates: b.paths.reduce((acc, p) => {acc[p] = TIER_IDS.map((tierId) => ({tier: tierId,diff --git a/api/_lib/prompt-avatar.js b/api/_lib/prompt-avatar.jsindex 540f3c277..8c606a55e 100644--- a/api/_lib/prompt-avatar.js+++ b/api/_lib/prompt-avatar.js@@ -22,6 +22,7 @@// The face pipeline (gcp `reconstruct` mode) is never a candidate here.import { BACKENDS } from './forge-tiers.js';+import { laneAllowedInTerritory } from './forge-territory.js';// Composition cues appended to the user's own words. They say nothing about// style, so "an anime ninja" stays anime and "a photoreal chef" stays photoreal;@@ -56,7 +57,7 @@ export function promptAvatarImagePrompt(prompt) {// accepted and the job would then fail on the worker, which costs the user the// whole wait. A lane that is merely in a failure cooldown keeps its place, since// one failed job (often a bad input) is not an outage.-export function planPromptAvatarLanes({ platform = [], byok = [], health = {} } = {}) {+export function planPromptAvatarLanes({ platform = [], byok = [], health = {}, country = null } = {}) {const byName = new Map(platform.filter((p) => p?.instance).map((p) => [p.name, p.instance]));const plan = [];const gcp = byName.get('gcp');@@ -75,13 +76,21 @@ export function planPromptAvatarLanes({ platform = [], byok = [], health = {} }params: { tier: PROMPT_AVATAR_TIER, path: 'image' },});- if (gcp && supports(gcp, 'hunyuan')) plan.push(selfHost('hunyuan', 'hunyuan3d'));+ // TRELLIS.2 leads: MIT licensed, served in every region. Two Tencent lanes+ // exist, self-host Hunyuan3D and the HuggingFace Spaces chain running it, and+ // both are dropped for the EU, the UK, South Korea and an unknown country.+ if (gcp && supports(gcp, 'trellis2')) plan.push(selfHost('trellis2', 'trellis2'));+ if (gcp && supports(gcp, 'hunyuan') && laneAllowedInTerritory('hunyuan3d', country)) {+ plan.push(selfHost('hunyuan', 'hunyuan3d'));+ }if (gcp && supports(gcp, 'trellis')) plan.push(selfHost('trellis', 'trellis_selfhost'));// Replicate's reconstruct model is TRELLIS (generic image→3D), and the HF// Spaces chain is Hunyuan3D / TRELLIS / TripoSR: both keep the whole figure.for (const name of ['replicate', 'huggingface']) {const instance = byName.get(name);- if (instance) plan.push({ name, instance, mode: 'reconstruct', lane: name, params: {} });+ if (instance && laneAllowedInTerritory(name, country)) {+ plan.push({ name, instance, mode: 'reconstruct', lane: name, params: {} });+ }}for (const p of byok) {if (p?.instance) plan.push({ name: p.name, instance: p.instance, mode: 'reconstruct', lane: p.name, params: {} });diff --git a/api/_mcp3d/tools/studio.js b/api/_mcp3d/tools/studio.jsindex b0de575c4..18e336f97 100644--- a/api/_mcp3d/tools/studio.js+++ b/api/_mcp3d/tools/studio.js@@ -327,6 +327,7 @@ const ENGINES = Object.freeze({const INTERNAL_TO_ENGINE = Object.freeze({trellis: 'three-image',nvidia: 'three-image',+ trellis2: 'three-image',trellis_selfhost: 'three-image',huggingface: 'three-image',replicate_byok: 'three-image',diff --git a/api/_providers/gcp.js b/api/_providers/gcp.jsindex 8c86b2628..67d38913a 100644--- a/api/_providers/gcp.js+++ b/api/_providers/gcp.js@@ -12,6 +12,7 @@// Native single-image→3D via Microsoft TRELLIS. Standard task// shape: POST /infer → { task_id } GET /tasks/:id → result_gcs_url.//+// trellis2 → MODEL_TRELLIS2_URL (workers/model-trellis2)// hunyuan → GCP_HUNYUAN3D_URL (workers/model-hunyuan3d)// Image→3D via Tencent Hunyuan3D-2 (shape DiT + multiview// paint). Same standard task shape as the TRELLIS worker:@@ -96,6 +97,10 @@ function serviceUrlForMode(mode) {// the avatar pipeline's `reconstruct` (face-only, /reconstruct + /jobs/:id);// this worker speaks the standard /infer + /tasks/:id task shape.return readEnv('MODEL_TRELLIS_URL');+ case 'trellis2':+ // Self-hosted Microsoft TRELLIS.2 image→3D worker (workers/model-trellis2),+ // the default image lane. Same /infer + /tasks/:id task shape.+ return readEnv('MODEL_TRELLIS2_URL');case 'hunyuan':// Self-hosted Hunyuan3D-2 image→3D worker (workers/model-hunyuan3d).// Same standard /infer + /tasks/:id task shape as the TRELLIS worker.@@ -180,6 +185,24 @@ function buildWorkerRequest(request) {};}+ if (mode === 'trellis2') {+ // Self-hosted TRELLIS.2 image→3D (workers/model-trellis2). One reference+ // view in, a PBR GLB with alpha out. `resolution` (512, 1024 or 1536) is+ // the voxel resolution; absent, the worker maps `tier` to one.+ const photos = Array.isArray(params?.images) && params.images.length+ ? params.images+ : [sourceUrl].filter(Boolean);+ const body = { images: photos, body_type: params?.bodyType || 'neutral' };+ if (Number.isFinite(Number(params?.resolution))) body.resolution = Math.round(Number(params.resolution));+ if (params?.tier) body.tier = params.tier;+ if (Number.isFinite(Number(params?.seed))) body.seed = Math.floor(Number(params.seed));+ return {+ path: '/infer',+ resultKey: 'result_gcs_url',+ body,+ };+ }+if (mode === 'hunyuan') {// Self-hosted Hunyuan3D-2 image→3D (workers/model-hunyuan3d). Shape DiT// conditions on the primary reference view; the worker isolates the@@ -416,6 +439,7 @@ function buildWorkerRequest(request) {const MODE_ETA = {reconstruct: 120,trellis: 60,+ trellis2: 75,// 50-step shape diffusion + multiview paint on the L4: much heavier than// TRELLIS's single pass.hunyuan: 300,@@ -522,7 +546,7 @@ export function createRegenProvider({ reconstructUrl } = {}) {// primary view only (report 1 so a multi-view request is never// silently claimed as fused); other modes are single-source.const viewsUsed =- mode === 'hunyuan'+ mode === 'hunyuan' || mode === 'trellis2'? 1: (mode === 'reconstruct' || mode === 'trellis') && Array.isArray(workerReq.body.images)? workerReq.body.images.lengthdiff --git a/api/avatars/_actions.js b/api/avatars/_actions.jsindex 9d4440fb4..074a3149c 100644--- a/api/avatars/_actions.js+++ b/api/avatars/_actions.js@@ -22,6 +22,7 @@ import { finalizeReconstructStage, pollRiggingStage } from '../_lib/reconstruct-import { finalizeAutoRigStage } from '../_lib/auto-rig.js';import { isAllowedProviderResultUrl } from '../_lib/provider-result-url.js';import { generateReferenceImage } from '../_lib/forge-reference-image.js';+import { requestTerritory } from '../_lib/forge-territory.js';import { planPromptAvatarLanes, promptAvatarImagePrompt } from '../_lib/prompt-avatar.js';import { laneHealthSnapshot } from '../_lib/forge-lane-health.js';@@ -1135,6 +1136,7 @@ const handleReconstruct = wrap(async (req, res) => {platform: reconstructCandidates.filter((c) => !BYOK_REGEN_PROVIDERS.includes(c.name)),byok: reconstructCandidates.filter((c) => BYOK_REGEN_PROVIDERS.includes(c.name)),health: await promptLaneHealth(),+ country: requestTerritory(req),}): reconstructCandidates.map((c) => ({ ...c, mode: 'reconstruct', lane: c.name, params: {} }));@@ -1289,7 +1291,7 @@ const handleReconstruct = wrap(async (req, res) => {// and failing it minutes later. Best-effort: no telemetry keeps the plan order.async function promptLaneHealth() {try {- return (await laneHealthSnapshot(['hunyuan3d', 'trellis_selfhost'])).byId;+ return (await laneHealthSnapshot(['trellis2', 'hunyuan3d', 'trellis_selfhost'])).byId;} catch (err) {console.warn('[avatars] prompt lane health skipped:', err?.message);return {};diff --git a/api/cron/gpu-keepwarm.js b/api/cron/gpu-keepwarm.jsindex fae90710d..a1f2cb3b7 100644--- a/api/cron/gpu-keepwarm.js+++ b/api/cron/gpu-keepwarm.js@@ -47,6 +47,18 @@ export const KEEPWARM_LANES = [safeByDefault: false,reason: 'us-central1 L4 grant is 3 and trellis+rig floors hold 2; warming this would cap the trellis lane at its floor',},+ {+ id: 'trellis2',+ urlEnv: 'MODEL_TRELLIS2_URL',+ region: 'us-central1',+ accelerator: 'nvidia-l4',+ safeByDefault: false,+ // The default image lane for every tier. Not warmed by default for the same+ // reason as its siblings: the us-central1 L4 grant is shared, and a warm+ // floor here is a quota decision (docs/ops/gcp-credits-plan.md), made with+ // FORGE_KEEPWARM_LANES=trellis2 once the grant allows it.+ reason: 'us-central1 L4 grant is shared with trellis, rig and hunyuan3d; a warm floor here is a quota decision',+ },{id: 'hunyuan3d',urlEnv: 'GCP_HUNYUAN3D_URL',diff --git a/api/forge.js b/api/forge.jsindex 5e9942ab6..c1fb0115c 100644--- a/api/forge.js+++ b/api/forge.js@@ -152,6 +152,11 @@ import {submitFailoverJob,MAX_FAILOVER_HOPS,} from './_lib/forge-failover.js';+import {+ laneAllowedInTerritory,+ requestTerritory,+ isTencentLane,+} from './_lib/forge-territory.js';import { decideSelfhostMissing } from './_lib/forge-selfhost-recovery.js';import { directPrompt } from './_mcp-studio/forge-client.js';import { meshDirectorFor, meshSubjectClass, resolveLogoPrompt } from './_lib/forge-director-prompts.js';@@ -806,8 +811,8 @@ async function runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path, opt// hop to one visibly instead of looping its countdown on the same dead Spaces.// The lane always holds reference views by now (uploaded, or synthesized from// the prompt), so the suggestions are scoped to image-capable lanes.-function hfLaneBusy(res) {- const retryBackends = retryBackendSuggestions({ attempted: ['huggingface'], hasImage: true });+function hfLaneBusy(res, country = null) {+ const retryBackends = retryBackendSuggestions({ attempted: ['huggingface'], hasImage: true, country });res.setHeader('retry-after', '30');return json(res, 503, {error: 'provider_busy',@@ -857,6 +862,10 @@ async function runHfImageLane({opts = null,cacheKey = null,}) {+ // The Spaces chain runs Hunyuan3D, so the lane is closed to the EU, the UK,+ // South Korea and unknown countries. false means "could not serve" and every+ // caller already falls through to the next lane.+ if (!laneAllowedInTerritory('huggingface', requestTerritory(req))) return false;let provider;try {const mod = await import('./_providers/huggingface.js');@@ -1153,7 +1162,11 @@ async function startJobWithBody(req, res, body) {// tier below High (see freeLaneCandidates). An image submission with no guidance// prompt classifies to null and keeps the default order.const subjectClass = classifyForgeSubject(prompt);- let backendId = resolveBackendId({ path, tier, backend: body?.backend, userImages: isImageMode, subjectClass });+ // Requester country, resolved from the edge geo header (never a body field).+ // Lanes that run a Tencent model are not routed for the EU, the UK, South+ // Korea or an unknown country (api/_lib/forge-territory.js).+ const country = requestTerritory(req);+ let backendId = resolveBackendId({ path, tier, backend: body?.backend, userImages: isImageMode, subjectClass, country });// Tracks whether the free NVIDIA NIM lane has already been attempted this// request, so the paid-lane fallback below never retries a lane that just// failed (draft already tries nvidia first; standard/high reach it only as a@@ -1189,11 +1202,23 @@ async function startJobWithBody(req, res, body) {// platform works with zero setup; Meshy/Tripo/Rodin stay fully selectable the// moment a key is present or a backend is explicitly chosen.const backendExplicit = Boolean(body?.backend && BACKENDS[body.backend]);+ // An explicitly named lane is honoured everywhere except where its model+ // licence excludes the requester's territory. Say so, and name the lane that+ // serves the same request there, instead of silently swapping the engine.+ if (backendExplicit && !laneAllowedInTerritory(body.backend, country)) {+ return json(res, 403, {+ error: 'region_restricted',+ backend: body.backend,+ message:+ 'This engine is not available in your region because its model licence excludes it. Use the default engine, which is available everywhere.',+ retry_backends: retryBackendSuggestions({ hasImage: isImageMode, country }),+ });+ }if (path === 'geometry' && !backendExplicit) {const defaultByok = BACKENDS[backendId]?.byok;if (defaultByok && !(await resolveProviderKey(req, body, defaultByok))) {path = 'image';- backendId = resolveBackendId({ path, tier, userImages: isImageMode, subjectClass });+ backendId = resolveBackendId({ path, tier, userImages: isImageMode, subjectClass, country });}}@@ -1207,7 +1232,7 @@ async function startJobWithBody(req, res, body) {// reused below to decide an honest cold-start ETA without a second probe.if (!backendExplicit && (path === 'image' || path === 'sketch')) {try {- const candidates = freeLaneCandidates(path, tier.id, isImageMode, subjectClass);+ const candidates = freeLaneCandidates(path, tier.id, isImageMode, subjectClass, country);if (candidates.length) {const snap = await laneHealthSnapshot(candidates);const healthAware = resolveBackendIdWithHealth({@@ -1216,6 +1241,7 @@ async function startJobWithBody(req, res, body) {userImages: isImageMode,health: snap.statusMap,subjectClass,+ country,});if (BACKENDS[healthAware]) backendId = healthAware;}@@ -1860,7 +1886,7 @@ async function startJobWithBody(req, res, body) {// creates its own provider. We deliberately do NOT build a Replicate// client here: creating one would 503 on a deployment that has no// REPLICATE_API_TOKEN, breaking an explicitly-chosen free engine.- } else if (backendId === 'trellis_selfhost') {+ } else if (backendId === 'trellis2' || backendId === 'trellis_selfhost') {// Driven by the dedicated self-host TRELLIS lane below, which builds// its own GCP provider. Same reasoning as huggingface, never build a// Replicate client here, or a deployment without REPLICATE_API_TOKEN@@ -2022,7 +2048,7 @@ async function startJobWithBody(req, res, body) {'Our image storage is not accepting writes right now, so this engine cannot be given the reference view. Try again on the free built-in engine, or retry shortly.',backend: backendId,retryable: true,- retry_backends: retryBackendSuggestions({ attempted: [backendId], hasImage: false }).filter(+ retry_backends: retryBackendSuggestions({ attempted: [backendId], hasImage: false, country }).filter(backendAcceptsInlineViews,),});@@ -2087,74 +2113,94 @@ async function startJobWithBody(req, res, body) {// sketch lane: returns a poll token that routes back through the gcp provider's// status(). Reached on an explicit pick OR as the preferred free image lane// (FREE_FALLBACK_FOR_PATH) when MODEL_TRELLIS_URL is configured.- if (backendId === 'trellis_selfhost') {+ if (backendId === 'trellis2' || backendId === 'trellis_selfhost') {let gcp;try {gcp = createGcpProvider();} catch {return json(res, 501, {error: 'backend_unconfigured',- backend: 'trellis_selfhost',+ backend: backendId,message: 'Self-hosted TRELLIS is not configured on this deployment.',});}let job;let selfHostTrellisFailed = false;- try {- job = await gcp.submit({- mode: 'trellis',- sourceUrl: referenceImageUrl,- params: {- images: views,- seed: opts.seed ?? undefined,- // Tier-scaled sampler/export budgets: this is where standard/high- // actually buy more quality on our own GPU (steps, kept geometry,- // texture resolution) instead of only a bigger advertised polycount.- quality: selfhostQualityForTier(tier.id),- // Background pre-matting via the worker's sibling rembg service- // (RMBG-2/isnet). A busy background (the classroom behind the- // subject) separates poorly in TRELLIS's internal cutout and bleeds- // into the fused geometry; a clean alpha cutout of every view before- // fusion removes that.- //- // This used to be gated to real user photos, on the reasoning that a- // text→3D reference is "already synthesized on a plain background".- // Measured on 2026-09-08, that premise is false: plain is not- // transparent, and the reconstruction happily fuses the plain- // backdrop in as geometry. Six text personas rendered through this- // exact path produced a figure standing on a full-footprint slab of- // reconstructed backdrop in four of six cases, twice losing the- // figure entirely (bbox 0.966 x 0.01 x 1: a bare plane, no person).- // Evidence: prompts/quality-bar/_generated/10/pass-2026-09-08/.- // So text→3D gets the same cutout; draft stays fast (single view,- // no matte). Worker-side it is best-effort either way: a rembg miss- // falls back to the original image, never failing the generation.- matte: tier.id !== 'draft',- },- });- } catch (err) {- if (err?.code === 'mode_unconfigured') {- return json(res, 501, {- error: 'backend_unconfigured',- backend: 'trellis_selfhost',- message:- 'Self-hosted TRELLIS is not configured on this deployment (MODEL_TRELLIS_URL is not set).',+ // TRELLIS.2 leads; when it is unavailable the same request retries on the+ // TRELLIS v1 worker, which holds the same reference views.+ for (;;) {+ try {+ job = await gcp.submit(backendId === 'trellis2' ? {+ mode: 'trellis2',+ sourceUrl: referenceImageUrl,+ params: {+ images: views,+ seed: opts.seed ?? undefined,+ // Voxel resolution: an explicit request value, else the worker maps+ // the tier (draft 512, standard and high 1024).+ resolution: opts.resolution ?? undefined,+ tier: tier.id,+ },+ } : {+ mode: 'trellis',+ sourceUrl: referenceImageUrl,+ params: {+ images: views,+ seed: opts.seed ?? undefined,+ // Tier-scaled sampler/export budgets: this is where standard/high+ // actually buy more quality on our own GPU (steps, kept geometry,+ // texture resolution) instead of only a bigger advertised polycount.+ quality: selfhostQualityForTier(tier.id),+ // Background pre-matting via the worker's sibling rembg service+ // (RMBG-2/isnet). A busy background (the classroom behind the+ // subject) separates poorly in TRELLIS's internal cutout and bleeds+ // into the fused geometry; a clean alpha cutout of every view before+ // fusion removes that.+ //+ // This used to be gated to real user photos, on the reasoning that a+ // text→3D reference is "already synthesized on a plain background".+ // Measured on 2026-09-08, that premise is false: plain is not+ // transparent, and the reconstruction happily fuses the plain+ // backdrop in as geometry. Six text personas rendered through this+ // exact path produced a figure standing on a full-footprint slab of+ // reconstructed backdrop in four of six cases, twice losing the+ // figure entirely (bbox 0.966 x 0.01 x 1: a bare plane, no person).+ // Evidence: prompts/quality-bar/_generated/10/pass-2026-09-08/.+ // So text→3D gets the same cutout; draft stays fast (single view,+ // no matte). Worker-side it is best-effort either way: a rembg miss+ // falls back to the original image, never failing the generation.+ matte: tier.id !== 'draft',+ },});+ } catch (err) {+ if (err?.code === 'mode_unconfigured') {+ return json(res, 501, {+ error: 'backend_unconfigured',+ backend: backendId,+ message:+ 'Self-hosted TRELLIS is not configured on this deployment (the worker URL is not set).',+ });+ }+ // A genuine config/input fault surfaces as-is. An upstream blip (the+ // worker is cold, restarting, throttled, or briefly unreachable) must+ // not fail a request another lane can serve: cool this lane so the next+ // request skips it, then fail over below to our other self-host worker+ // (Hunyuan3D) or the standing reconstruct chain (which free-firsts to HF+ // and only then the paid lane). We already hold the reference views, so+ // the next lane reconstructs from exactly the same input.+ if (!isUpstreamUnavailable(err)) throw err;+ await markLaneUnhealthy(backendId);+ console.warn(+ `[forge] self-host TRELLIS lane unavailable (${err?.providerStatus || err?.code}); failing over to the next image lane`,+ );+ if (backendId === 'trellis2' && backendIsConfigured('trellis_selfhost')) {+ backendId = 'trellis_selfhost';+ continue;+ }+ selfHostTrellisFailed = true;}- // A genuine config/input fault surfaces as-is. An upstream blip (the- // worker is cold, restarting, throttled, or briefly unreachable) must- // not fail a request another lane can serve: cool this lane so the next- // request skips it, then fail over below to our other self-host worker- // (Hunyuan3D) or the standing reconstruct chain (which free-firsts to HF- // and only then the paid lane). We already hold the reference views, so- // the next lane reconstructs from exactly the same input.- if (!isUpstreamUnavailable(err)) throw err;- await markLaneUnhealthy('trellis_selfhost');- console.warn(- `[forge] self-host TRELLIS lane unavailable (${err?.providerStatus || err?.code}); failing over to the next image lane`,- );- selfHostTrellisFailed = true;+ break;}if (!selfHostTrellisFailed) {@@ -2210,7 +2256,11 @@ async function startJobWithBody(req, res, body) {// HuggingFace Spaces lane and only then the paid Replicate account. Falls// through (no return) into the lane blocks below; provenance reports the// lane that actually runs, so the failover is never silent.- if (process.env.GCP_HUNYUAN3D_URL && process.env.GCP_RECONSTRUCTION_KEY) {+ if (+ process.env.GCP_HUNYUAN3D_URL &&+ process.env.GCP_RECONSTRUCTION_KEY &&+ laneAllowedInTerritory('hunyuan3d', country)+ ) {backendId = 'hunyuan3d';provider = createGcpProvider();} else {@@ -2245,7 +2295,7 @@ async function startJobWithBody(req, res, body) {return;// Failover instead of a dead end: see laneAfterHfFailure for why an// auto-routed request lands here while our own GPU worker is healthy.- const nextLane = laneAfterHfFailure({ explicit: backendExplicit, userImages: isImageMode });+ const nextLane = laneAfterHfFailure({ explicit: backendExplicit, userImages: isImageMode, country });if (nextLane === 'hunyuan3d') {console.warn('[forge] free HuggingFace lane could not serve this request; failing over to self-hosted Hunyuan3D');backendId = 'hunyuan3d';@@ -2256,7 +2306,7 @@ async function startJobWithBody(req, res, body) {if (await runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path, opts, cacheKey })) return;}if (backendId === 'huggingface') {- return hfLaneBusy(res);+ return hfLaneBusy(res, country);}}@@ -2411,7 +2461,7 @@ async function startJobWithBody(req, res, body) {// Fallback #2: self-hosted Hunyuan3D Cloud Run worker, when wired.const hunyuanUrl = process.env.GCP_HUNYUAN3D_URL;- if (!job && hunyuanUrl && process.env.GCP_RECONSTRUCTION_KEY) {+ if (!job && hunyuanUrl && process.env.GCP_RECONSTRUCTION_KEY && laneAllowedInTerritory('hunyuan3d', country)) {console.warn(`[forge] platform TRELLIS lane unavailable (${submitErr?.providerStatus || submitErr?.code}); degrading ${mode3d} to self-hosted Hunyuan3D`,);@@ -2474,7 +2524,7 @@ async function startJobWithBody(req, res, body) {// token tag so polling re-resolves the caller's key (not the platform one).// Either way the upstream id is what the store keys on.const jobHandle =- backendId === 'hunyuan3d' || backendId === 'trellis_selfhost'+ backendId === 'hunyuan3d' || backendId === 'trellis2' || backendId === 'trellis_selfhost'? encodeJobToken({ provider: 'gcp', kind: null, taskId: job.extJobId }): backendId === 'replicate_byok'? encodeJobToken({ provider: 'replicate_byok', kind: null, taskId: job.extJobId })@@ -3136,7 +3186,7 @@ async function pollJob(req, res, jobId) {const redispatchable =platformLaneFailed && hop < MAX_FAILOVER_HOPS && meta?.preview_image_url && meta?.path !== 'sketch';if (redispatchable) {- const nextLane = await pickRedispatchLane({ attempted });+ const nextLane = await pickRedispatchLane({ attempted, country: requestTerritory(req) });if (nextLane) {try {const submitted = await submitFailoverJob({@@ -3208,7 +3258,7 @@ async function pollJob(req, res, jobId) {const suggestions =meta?.path === 'sketch'? []- : retryBackendSuggestions({ attempted, hasImage: Boolean(meta?.preview_image_url) });+ : retryBackendSuggestions({ attempted, hasImage: Boolean(meta?.preview_image_url), country: requestTerritory(req) });return json(res, 200, {job_id: jobId,status: 'failed',diff --git a/api/gpt-forge.js b/api/gpt-forge.jsindex 912a58e1f..a5abfe7e8 100644--- a/api/gpt-forge.js+++ b/api/gpt-forge.js@@ -163,6 +163,11 @@ import {submitFailoverJob,MAX_FAILOVER_HOPS,} from './_lib/forge-failover.js';+import {+ laneAllowedInTerritory,+ requestTerritory,+ isTencentLane,+} from './_lib/forge-territory.js';import { decideSelfhostMissing } from './_lib/forge-selfhost-recovery.js';import { directPrompt } from './_mcp-studio/gpt-forge-client.js';import { meshDirectorFor, meshSubjectClass, resolveLogoPrompt } from './_lib/forge-director-prompts.js';@@ -839,8 +844,8 @@ async function runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path, opt// hop to one visibly instead of looping its countdown on the same dead Spaces.// The lane always holds reference views by now (uploaded, or synthesized from// the prompt), so the suggestions are scoped to image-capable lanes.-function hfLaneBusy(res) {- const retryBackends = retryBackendSuggestions({ attempted: ['huggingface'], hasImage: true });+function hfLaneBusy(res, country = null) {+ const retryBackends = retryBackendSuggestions({ attempted: ['huggingface'], hasImage: true, country });res.setHeader('retry-after', '30');return json(res, 503, {error: 'provider_busy',@@ -886,6 +891,10 @@ async function runHfImageLane({opts = null,cacheKey = null,}) {+ // The Spaces chain runs Hunyuan3D, so the lane is closed to the EU, the UK,+ // South Korea and unknown countries. false means "could not serve" and every+ // caller already falls through to the next lane.+ if (!laneAllowedInTerritory('huggingface', requestTerritory(req))) return false;let provider;try {const mod = await import('./_providers/huggingface.js');@@ -1164,7 +1173,11 @@ async function startJob(req, res) {// tier below High (see freeLaneCandidates). An image submission with no guidance// prompt classifies to null and keeps the default order.const subjectClass = classifyForgeSubject(prompt);- let backendId = resolveBackendId({ path, tier, backend: body?.backend, userImages: isImageMode, subjectClass });+ // Requester country, resolved from the edge geo header (never a body field).+ // Lanes that run a Tencent model are not routed for the EU, the UK, South+ // Korea or an unknown country (api/_lib/forge-territory.js).+ const country = requestTerritory(req);+ let backendId = resolveBackendId({ path, tier, backend: body?.backend, userImages: isImageMode, subjectClass, country });// Tracks whether the free NVIDIA NIM lane has already been attempted this// request, so the paid-lane fallback below never retries a lane that just// failed (draft already tries nvidia first; standard/high reach it only as a@@ -1200,11 +1213,23 @@ async function startJob(req, res) {// platform works with zero setup; Meshy/Tripo/Rodin stay fully selectable the// moment a key is present or a backend is explicitly chosen.const backendExplicit = Boolean(body?.backend && BACKENDS[body.backend]);+ // An explicitly named lane is honoured everywhere except where its model+ // licence excludes the requester's territory. Say so, and name the lane that+ // serves the same request there, instead of silently swapping the engine.+ if (backendExplicit && !laneAllowedInTerritory(body.backend, country)) {+ return json(res, 403, {+ error: 'region_restricted',+ backend: body.backend,+ message:+ 'This engine is not available in your region because its model licence excludes it. Use the default engine, which is available everywhere.',+ retry_backends: retryBackendSuggestions({ hasImage: isImageMode, country }),+ });+ }if (path === 'geometry' && !backendExplicit) {const defaultByok = BACKENDS[backendId]?.byok;if (defaultByok && !(await resolveProviderKey(req, body, defaultByok))) {path = 'image';- backendId = resolveBackendId({ path, tier, userImages: isImageMode, subjectClass });+ backendId = resolveBackendId({ path, tier, userImages: isImageMode, subjectClass, country });}}@@ -1218,7 +1243,7 @@ async function startJob(req, res) {// reused below to decide an honest cold-start ETA without a second probe.if (!backendExplicit && (path === 'image' || path === 'sketch')) {try {- const candidates = freeLaneCandidates(path, tier.id, isImageMode, subjectClass);+ const candidates = freeLaneCandidates(path, tier.id, isImageMode, subjectClass, country);if (candidates.length) {const snap = await laneHealthSnapshot(candidates);const healthAware = resolveBackendIdWithHealth({@@ -1227,6 +1252,7 @@ async function startJob(req, res) {userImages: isImageMode,health: snap.statusMap,subjectClass,+ country,});if (BACKENDS[healthAware]) backendId = healthAware;}@@ -1873,7 +1899,7 @@ async function startJob(req, res) {// creates its own provider. We deliberately do NOT build a Replicate// client here: creating one would 503 on a deployment that has no// REPLICATE_API_TOKEN, breaking an explicitly-chosen free engine.- } else if (backendId === 'trellis_selfhost') {+ } else if (backendId === 'trellis2' || backendId === 'trellis_selfhost') {// Driven by the dedicated self-host TRELLIS lane below, which builds// its own GCP provider. Same reasoning as huggingface, never build a// Replicate client here, or a deployment without REPLICATE_API_TOKEN@@ -2020,71 +2046,91 @@ async function startJob(req, res) {// sketch lane: returns a poll token that routes back through the gcp provider's// status(). Reached on an explicit pick OR as the preferred free image lane// (FREE_FALLBACK_FOR_PATH) when MODEL_TRELLIS_URL is configured.- if (backendId === 'trellis_selfhost') {+ if (backendId === 'trellis2' || backendId === 'trellis_selfhost') {let gcp;try {gcp = createGcpProvider();} catch {return json(res, 501, {error: 'backend_unconfigured',- backend: 'trellis_selfhost',+ backend: backendId,message: 'Self-hosted TRELLIS is not configured on this deployment.',});}let job;let selfHostTrellisFailed = false;- try {- job = await gcp.submit({- mode: 'trellis',- sourceUrl: referenceImageUrl,- params: {- images: views,- seed: opts.seed ?? undefined,- // Tier-scaled sampler/export budgets: this is where standard/high- // actually buy more quality on our own GPU (steps, kept geometry,- // texture resolution) instead of only a bigger advertised polycount.- quality: selfhostQualityForTier(tier.id),- // Background pre-matting via the worker's sibling rembg service- // (RMBG-2/isnet). A busy background (the classroom behind the- // subject) separates poorly in TRELLIS's internal cutout and bleeds- // into the fused geometry; a clean alpha cutout of every view before- // fusion removes that.- //- // This used to be gated to real user photos, on the reasoning that a- // text→3D reference is "already synthesized on a plain background".- // Measured on 2026-09-08, that premise is false: plain is not- // transparent, and the reconstruction fuses the plain backdrop in as- // geometry (a figure standing on a full-footprint slab, and twice no- // figure at all). Same change and same evidence as api/forge.js; see- // prompts/quality-bar/_generated/10/pass-2026-09-08/. draft stays- // fast (single view, no matte), and a rembg miss still falls back to- // the original image rather than failing the generation.- matte: tier.id !== 'draft',- },- });- } catch (err) {- if (err?.code === 'mode_unconfigured') {- return json(res, 501, {- error: 'backend_unconfigured',- backend: 'trellis_selfhost',- message:- 'Self-hosted TRELLIS is not configured on this deployment (MODEL_TRELLIS_URL is not set).',+ // TRELLIS.2 leads; when it is unavailable the same request retries on the+ // TRELLIS v1 worker, which holds the same reference views.+ for (;;) {+ try {+ job = await gcp.submit(backendId === 'trellis2' ? {+ mode: 'trellis2',+ sourceUrl: referenceImageUrl,+ params: {+ images: views,+ seed: opts.seed ?? undefined,+ // Voxel resolution: an explicit request value, else the worker maps+ // the tier (draft 512, standard and high 1024).+ resolution: opts.resolution ?? undefined,+ tier: tier.id,+ },+ } : {+ mode: 'trellis',+ sourceUrl: referenceImageUrl,+ params: {+ images: views,+ seed: opts.seed ?? undefined,+ // Tier-scaled sampler/export budgets: this is where standard/high+ // actually buy more quality on our own GPU (steps, kept geometry,+ // texture resolution) instead of only a bigger advertised polycount.+ quality: selfhostQualityForTier(tier.id),+ // Background pre-matting via the worker's sibling rembg service+ // (RMBG-2/isnet). A busy background (the classroom behind the+ // subject) separates poorly in TRELLIS's internal cutout and bleeds+ // into the fused geometry; a clean alpha cutout of every view before+ // fusion removes that.+ //+ // This used to be gated to real user photos, on the reasoning that a+ // text→3D reference is "already synthesized on a plain background".+ // Measured on 2026-09-08, that premise is false: plain is not+ // transparent, and the reconstruction fuses the plain backdrop in as+ // geometry (a figure standing on a full-footprint slab, and twice no+ // figure at all). Same change and same evidence as api/forge.js; see+ // prompts/quality-bar/_generated/10/pass-2026-09-08/. draft stays+ // fast (single view, no matte), and a rembg miss still falls back to+ // the original image rather than failing the generation.+ matte: tier.id !== 'draft',+ },});+ } catch (err) {+ if (err?.code === 'mode_unconfigured') {+ return json(res, 501, {+ error: 'backend_unconfigured',+ backend: backendId,+ message:+ 'Self-hosted TRELLIS is not configured on this deployment (the worker URL is not set).',+ });+ }+ // A genuine config/input fault surfaces as-is. An upstream blip (the+ // worker is cold, restarting, throttled, or briefly unreachable) must+ // not fail a request another lane can serve: cool this lane so the next+ // request skips it, then fail over below to our other self-host worker+ // (Hunyuan3D) or the standing reconstruct chain (which free-firsts to HF+ // and only then the paid lane). We already hold the reference views, so+ // the next lane reconstructs from exactly the same input.+ if (!isUpstreamUnavailable(err)) throw err;+ await markLaneUnhealthy(backendId);+ console.warn(+ `[forge] self-host TRELLIS lane unavailable (${err?.providerStatus || err?.code}); failing over to the next image lane`,+ );+ if (backendId === 'trellis2' && backendIsConfigured('trellis_selfhost')) {+ backendId = 'trellis_selfhost';+ continue;+ }+ selfHostTrellisFailed = true;}- // A genuine config/input fault surfaces as-is. An upstream blip (the- // worker is cold, restarting, throttled, or briefly unreachable) must- // not fail a request another lane can serve: cool this lane so the next- // request skips it, then fail over below to our other self-host worker- // (Hunyuan3D) or the standing reconstruct chain (which free-firsts to HF- // and only then the paid lane). We already hold the reference views, so- // the next lane reconstructs from exactly the same input.- if (!isUpstreamUnavailable(err)) throw err;- await markLaneUnhealthy('trellis_selfhost');- console.warn(- `[forge] self-host TRELLIS lane unavailable (${err?.providerStatus || err?.code}); failing over to the next image lane`,- );- selfHostTrellisFailed = true;+ break;}if (!selfHostTrellisFailed) {@@ -2138,7 +2184,11 @@ async function startJob(req, res) {// HuggingFace Spaces lane and only then the paid Replicate account. Falls// through (no return) into the lane blocks below; provenance reports the// lane that actually runs, so the failover is never silent.- if (process.env.GCP_HUNYUAN3D_URL && process.env.GCP_RECONSTRUCTION_KEY) {+ if (+ process.env.GCP_HUNYUAN3D_URL &&+ process.env.GCP_RECONSTRUCTION_KEY &&+ laneAllowedInTerritory('hunyuan3d', country)+ ) {backendId = 'hunyuan3d';provider = createGcpProvider();} else {@@ -2172,7 +2222,7 @@ async function startJob(req, res) {return;// Failover instead of a dead end: see laneAfterHfFailure for why an// auto-routed request lands here while our own GPU worker is healthy.- const nextLane = laneAfterHfFailure({ explicit: backendExplicit, userImages: isImageMode });+ const nextLane = laneAfterHfFailure({ explicit: backendExplicit, userImages: isImageMode, country });if (nextLane === 'hunyuan3d') {console.warn('[forge] free HuggingFace lane could not serve this request; failing over to self-hosted Hunyuan3D');backendId = 'hunyuan3d';@@ -2183,7 +2233,7 @@ async function startJob(req, res) {if (await runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path, opts, cacheKey })) return;}if (backendId === 'huggingface') {- return hfLaneBusy(res);+ return hfLaneBusy(res, country);}}@@ -2337,7 +2387,7 @@ async function startJob(req, res) {// Fallback #2: self-hosted Hunyuan3D Cloud Run worker, when wired.const hunyuanUrl = process.env.GCP_HUNYUAN3D_URL;- if (!job && hunyuanUrl && process.env.GCP_RECONSTRUCTION_KEY) {+ if (!job && hunyuanUrl && process.env.GCP_RECONSTRUCTION_KEY && laneAllowedInTerritory('hunyuan3d', country)) {console.warn(`[forge] platform TRELLIS lane unavailable (${submitErr?.providerStatus || submitErr?.code}); degrading ${mode3d} to self-hosted Hunyuan3D`,);@@ -2399,7 +2449,7 @@ async function startJob(req, res) {// token tag so polling re-resolves the caller's key (not the platform one).// Either way the upstream id is what the store keys on.const jobHandle =- backendId === 'hunyuan3d' || backendId === 'trellis_selfhost'+ backendId === 'hunyuan3d' || backendId === 'trellis2' || backendId === 'trellis_selfhost'? encodeJobToken({ provider: 'gcp', kind: null, taskId: job.extJobId }): backendId === 'replicate_byok'? encodeJobToken({ provider: 'replicate_byok', kind: null, taskId: job.extJobId })@@ -3064,7 +3114,7 @@ async function pollJob(req, res, jobId) {const redispatchable =platformLaneFailed && hop < MAX_FAILOVER_HOPS && meta?.preview_image_url && meta?.path !== 'sketch';if (redispatchable) {- const nextLane = await pickRedispatchLane({ attempted });+ const nextLane = await pickRedispatchLane({ attempted, country: requestTerritory(req) });if (nextLane) {try {const submitted = await submitFailoverJob({@@ -3125,7 +3175,7 @@ async function pollJob(req, res, jobId) {const suggestions =meta?.path === 'sketch'? []- : retryBackendSuggestions({ attempted, hasImage: Boolean(meta?.preview_image_url) });+ : retryBackendSuggestions({ attempted, hasImage: Boolean(meta?.preview_image_url), country: requestTerritory(req) });return json(res, 200, {job_id: jobId,status: 'failed',diff --git a/src/forge-showcase.js b/src/forge-showcase.jsindex 0284c0433..0c3228304 100644--- a/src/forge-showcase.js+++ b/src/forge-showcase.js@@ -102,6 +102,7 @@ const ENGINE_LABELS = {nvidia: 'Free',huggingface: 'Hunyuan3D',trellis: 'Fast',+ trellis2: 'TRELLIS.2',trellis_selfhost: 'TRELLIS',meshy: 'Meshy',tripo: 'Tripo',diff --git a/src/forge-studio/forge-showcase.js b/src/forge-studio/forge-showcase.jsindex 860217b4a..68524a5ce 100644--- a/src/forge-studio/forge-showcase.js+++ b/src/forge-studio/forge-showcase.js@@ -91,6 +91,7 @@ const ENGINE_LABELS = {nvidia: 'Free',huggingface: 'Hunyuan3D',trellis: 'Fast',+ trellis2: 'TRELLIS.2',trellis_selfhost: 'TRELLIS',meshy: 'Meshy',tripo: 'Tripo',diff --git a/src/forge.js b/src/forge.jsindex bdff70789..f0af6741e 100644--- a/src/forge.js+++ b/src/forge.js@@ -260,6 +260,7 @@ const ENGINE_LABELS = {nvidia: 'NVIDIA',huggingface: 'Hunyuan3D',trellis: 'Fast',+ trellis2: 'TRELLIS.2',trellis_selfhost: 'TRELLIS',meshy: 'Meshy',tripo: 'Tripo',diff --git a/src/home-forge-controls.js b/src/home-forge-controls.jsindex 41e698bbe..ecdeb5d72 100644--- a/src/home-forge-controls.js+++ b/src/home-forge-controls.js@@ -34,6 +34,7 @@ const ENGINE_LABELS = {nvidia: 'NVIDIA',huggingface: 'Hunyuan3D',trellis: 'Fast',+ trellis2: 'TRELLIS.2',trellis_selfhost: 'TRELLIS',meshy: 'Meshy',tripo: 'Tripo',diff --git a/src/shared/forge-frames.js b/src/shared/forge-frames.jsindex a13c3e377..5a3e561da 100644--- a/src/shared/forge-frames.js+++ b/src/shared/forge-frames.js@@ -53,6 +53,7 @@ const LANE_LABELS = {nvidia: 'free NVIDIA NIM',huggingface: 'free Hunyuan3D',trellis: 'Fast',+ trellis2: 'TRELLIS.2',trellis_selfhost: 'TRELLIS',meshy: 'Meshy',tripo: 'Tripo',diff --git a/tests/api/forge-fallback.test.js b/tests/api/forge-fallback.test.jsindex f5b2ec6f6..ca1321b2b 100644--- a/tests/api/forge-fallback.test.js+++ b/tests/api/forge-fallback.test.js@@ -115,7 +115,7 @@ function makeReq(body) {return {method: 'POST',url: '/api/forge',- headers: { 'content-type': 'application/json', 'x-forge-client': 'tester' },+ headers: { 'content-type': 'application/json', 'x-forge-client': 'tester', 'x-vercel-ip-country': 'US' },on(event, cb) {if (event === 'data') cb(Buffer.from(JSON.stringify(body)));if (event === 'end') cb();diff --git a/tests/api/forge-free-first.test.js b/tests/api/forge-free-first.test.jsindex a38d0d1bf..eb4a5b96d 100644--- a/tests/api/forge-free-first.test.js+++ b/tests/api/forge-free-first.test.js@@ -118,7 +118,7 @@ function makeReq(body) {return {method: 'POST',url: '/api/forge',- headers: { 'content-type': 'application/json', 'x-forge-client': 'tester' },+ headers: { 'content-type': 'application/json', 'x-forge-client': 'tester', 'x-vercel-ip-country': 'US' },on(event, cb) {if (event === 'data') cb(Buffer.from(JSON.stringify(body)));if (event === 'end') cb();diff --git a/tests/api/forge-hf-failover.test.js b/tests/api/forge-hf-failover.test.jsindex dab575cb2..a3ba2d582 100644--- a/tests/api/forge-hf-failover.test.js+++ b/tests/api/forge-hf-failover.test.js@@ -29,27 +29,27 @@ describe('laneAfterHfFailure', () => {process.env.GCP_HUNYUAN3D_URL = 'https://hunyuan.example.run.app';process.env.GCP_RECONSTRUCTION_KEY = 'k';process.env.NVIDIA_API_KEY = 'nv';- expect(laneAfterHfFailure({})).toBe('hunyuan3d');- expect(laneAfterHfFailure({ userImages: true })).toBe('hunyuan3d');+ expect(laneAfterHfFailure({country: 'US' })).toBe('hunyuan3d');+ expect(laneAfterHfFailure({ userImages: true, country: 'US' })).toBe('hunyuan3d');});it('sends a text prompt to the free NVIDIA lane when no self-host worker is wired', () => {process.env.NVIDIA_API_KEY = 'nv';- expect(laneAfterHfFailure({ userImages: false })).toBe('nvidia');+ expect(laneAfterHfFailure({ userImages: false, country: 'US' })).toBe('nvidia');});it('never sends a photo to the text-only NVIDIA lane', () => {process.env.NVIDIA_API_KEY = 'nv';- expect(laneAfterHfFailure({ userImages: true })).toBeNull();+ expect(laneAfterHfFailure({ userImages: true, country: 'US' })).toBeNull();});it('keeps an explicitly chosen HuggingFace engine on its designed busy state', () => {process.env.GCP_HUNYUAN3D_URL = 'https://hunyuan.example.run.app';process.env.GCP_RECONSTRUCTION_KEY = 'k';- expect(laneAfterHfFailure({ explicit: true })).toBeNull();+ expect(laneAfterHfFailure({ explicit: true, country: 'US' })).toBeNull();});it('has nowhere to go when nothing else is configured', () => {- expect(laneAfterHfFailure({})).toBeNull();+ expect(laneAfterHfFailure({country: 'US' })).toBeNull();});});diff --git a/tests/api/forge-lane-routing.test.js b/tests/api/forge-lane-routing.test.jsindex 40aa0fee4..c44105975 100644--- a/tests/api/forge-lane-routing.test.js+++ b/tests/api/forge-lane-routing.test.js@@ -60,7 +60,7 @@ describe('freeLaneCandidates — ordered, configured, de-duplicated', () => {it('orders our own GPU workers ahead of the free external lane for photos', () => {configureAllLanes();// Photo: NVIDIA's text-only preview is excluded; self-host workers lead.- expect(freeLaneCandidates('image', 'draft', true)).toEqual([+ expect(freeLaneCandidates('image', 'draft', true, null, 'US')).toEqual(['trellis_selfhost','hunyuan3d','huggingface',@@ -72,7 +72,7 @@ describe('freeLaneCandidates — ordered, configured, de-duplicated', () => {// Text (userImages=false): the tier-named image-intermediate lane leads (the// reference-image pipeline), NVIDIA's native text→mesh preview is the last// free-lane resort since it skips the photoreal reference image entirely.- expect(freeLaneCandidates('image', 'draft', false)).toEqual([+ expect(freeLaneCandidates('image', 'draft', false, null, 'US')).toEqual(['trellis_selfhost','hunyuan3d','huggingface',@@ -84,8 +84,8 @@ describe('freeLaneCandidates — ordered, configured, de-duplicated', () => {// Only the self-host TRELLIS worker is wired.process.env.MODEL_TRELLIS_URL = 'https://trellis.example.run.app';process.env.GCP_RECONSTRUCTION_KEY = 'secret';- expect(freeLaneCandidates('image', 'standard', true)).toEqual(['trellis_selfhost']);- expect(freeLaneCandidates('image', 'standard', false)).toEqual(['trellis_selfhost']);+ expect(freeLaneCandidates('image', 'standard', true, null, 'US')).toEqual(['trellis_selfhost']);+ expect(freeLaneCandidates('image', 'standard', false, null, 'US')).toEqual(['trellis_selfhost']);});});@@ -106,7 +106,7 @@ describe('FORGE_SELFHOST_PRIMARY — hoist our own GPU fleet ahead of hosted freit('off (default) already leads with self-host TRELLIS — the photoreal reference default', () => {configureAllLanes();delete process.env.FORGE_SELFHOST_PRIMARY;- expect(freeLaneCandidates('image', 'draft', false)).toEqual([+ expect(freeLaneCandidates('image', 'draft', false, null, 'US')).toEqual(['trellis_selfhost','hunyuan3d','huggingface',@@ -120,7 +120,7 @@ describe('FORGE_SELFHOST_PRIMARY — hoist our own GPU fleet ahead of hosted fre// The named draft/standard default is now itself a self-host lane// (trellis_selfhost), so hoisting self-host ahead of hosted lanes is a// no-op here — the order matches the flag-off case exactly.- expect(freeLaneCandidates('image', 'draft', false)).toEqual([+ expect(freeLaneCandidates('image', 'draft', false, null, 'US')).toEqual(['trellis_selfhost','hunyuan3d','huggingface',@@ -131,7 +131,7 @@ describe('FORGE_SELFHOST_PRIMARY — hoist our own GPU fleet ahead of hosted freit('on: photo lane already self-host-first is unchanged', () => {configureAllLanes();process.env.FORGE_SELFHOST_PRIMARY = '1';- expect(freeLaneCandidates('image', 'draft', true)).toEqual([+ expect(freeLaneCandidates('image', 'draft', true, null, 'US')).toEqual(['trellis_selfhost','hunyuan3d','huggingface',@@ -143,13 +143,13 @@ describe('FORGE_SELFHOST_PRIMARY — hoist our own GPU fleet ahead of hosted freprocess.env.NVIDIA_API_KEY = 'nvapi-test';process.env.HF_TOKEN = 'hf_test';process.env.FORGE_SELFHOST_PRIMARY = '1';- expect(freeLaneCandidates('image', 'draft', false)).toEqual(['huggingface', 'nvidia']);+ expect(freeLaneCandidates('image', 'draft', false, null, 'US')).toEqual(['huggingface', 'nvidia']);});it('on: routes an unnamed text prompt to self-host TRELLIS via the resolver', () => {configureAllLanes();process.env.FORGE_SELFHOST_PRIMARY = '1';- expect(resolveBackendId({ path: 'image', tier: 'draft', userImages: false })).toBe('trellis_selfhost');+ expect(resolveBackendId({ path: 'image', tier: 'draft', userImages: false, country: 'US' })).toBe('trellis_selfhost');// Health-aware twin agrees when the fleet is healthy.expect(resolveBackendIdWithHealth({@@ -167,28 +167,28 @@ describe('resolveBackendIdWithHealth — prefer healthy self-host → other freeit('routes a photo to the healthy self-host TRELLIS worker', () => {const health = { trellis_selfhost: 'ok', hunyuan3d: 'ok', huggingface: 'ok' };- expect(resolveBackendIdWithHealth({ path: 'image', tier: 'standard', userImages: true, health })).toBe(+ expect(resolveBackendIdWithHealth({ path: 'image', tier: 'standard', userImages: true, health, country: 'US' })).toBe('trellis_selfhost',);});it('skips a down self-host lane and falls to the next healthy self-host worker', () => {const health = { trellis_selfhost: 'down', hunyuan3d: 'ok', huggingface: 'ok' };- expect(resolveBackendIdWithHealth({ path: 'image', tier: 'standard', userImages: true, health })).toBe(+ expect(resolveBackendIdWithHealth({ path: 'image', tier: 'standard', userImages: true, health, country: 'US' })).toBe('hunyuan3d',);});it('falls to the healthy free external lane when both self-host workers are down', () => {const health = { trellis_selfhost: 'down', hunyuan3d: 'down', huggingface: 'ok' };- expect(resolveBackendIdWithHealth({ path: 'image', tier: 'standard', userImages: true, health })).toBe(+ expect(resolveBackendIdWithHealth({ path: 'image', tier: 'standard', userImages: true, health, country: 'US' })).toBe('huggingface',);});it('falls to the paid standing default only when every free lane is confirmed down', () => {const health = { trellis_selfhost: 'down', hunyuan3d: 'down', huggingface: 'down' };- expect(resolveBackendIdWithHealth({ path: 'image', tier: 'standard', userImages: true, health })).toBe(+ expect(resolveBackendIdWithHealth({ path: 'image', tier: 'standard', userImages: true, health, country: 'US' })).toBe(DEFAULT_BACKEND_FOR_PATH.image,);expect(DEFAULT_BACKEND_FOR_PATH.image).toBe('trellis');@@ -197,12 +197,12 @@ describe('resolveBackendIdWithHealth — prefer healthy self-host → other freeit('treats unknown/degraded health as usable (never blocks on missing telemetry)', () => {// trellis_selfhost has no entry (unknown) → still picked, ahead of an ok HF.const health = { huggingface: 'ok' };- expect(resolveBackendIdWithHealth({ path: 'image', tier: 'standard', userImages: true, health })).toBe(+ expect(resolveBackendIdWithHealth({ path: 'image', tier: 'standard', userImages: true, health, country: 'US' })).toBe('trellis_selfhost',);// A degraded self-host lane is skipped only if a later candidate is ok.const health2 = { trellis_selfhost: 'degraded', hunyuan3d: 'ok' };- expect(resolveBackendIdWithHealth({ path: 'image', tier: 'standard', userImages: true, health: health2 })).toBe(+ expect(resolveBackendIdWithHealth({ path: 'image', tier: 'standard', userImages: true, health: health2, country: 'US' })).toBe('hunyuan3d',);});@@ -219,6 +219,7 @@ describe('resolveBackendIdWithHealth — prefer healthy self-host → other freetier: 'draft',userImages: false,health: { trellis_selfhost: 'down', hunyuan3d: 'ok' },+ country: 'US',}),).toBe('hunyuan3d');});@@ -226,16 +227,16 @@ describe('resolveBackendIdWithHealth — prefer healthy self-host → other freeit('honors an explicitly named backend regardless of health', () => {const health = { trellis_selfhost: 'ok' };expect(- resolveBackendIdWithHealth({ path: 'image', tier: 'standard', backend: 'meshy', userImages: true, health }),+ resolveBackendIdWithHealth({ path: 'image', tier: 'standard', backend: 'meshy', userImages: true, health, country: 'US' }),).toBe('meshy');});it('with no health map, matches the env-only resolver exactly', () => {- expect(resolveBackendIdWithHealth({ path: 'image', tier: 'standard', userImages: true })).toBe(- resolveBackendId({ path: 'image', tier: 'standard', userImages: true }),+ expect(resolveBackendIdWithHealth({ path: 'image', tier: 'standard', userImages: true, country: 'US' })).toBe(+ resolveBackendId({ path: 'image', tier: 'standard', userImages: true, country: 'US' }),);- expect(resolveBackendIdWithHealth({ path: 'image', tier: 'draft', userImages: false })).toBe(- resolveBackendId({ path: 'image', tier: 'draft', userImages: false }),+ expect(resolveBackendIdWithHealth({ path: 'image', tier: 'draft', userImages: false, country: 'US' })).toBe(+ resolveBackendId({ path: 'image', tier: 'draft', userImages: false, country: 'US' }),);});diff --git a/tests/api/forge-poll-failover.test.js b/tests/api/forge-poll-failover.test.jsindex 53173b1c3..f5c19cc56 100644--- a/tests/api/forge-poll-failover.test.js+++ b/tests/api/forge-poll-failover.test.js@@ -122,7 +122,7 @@ function makeReq(jobId) {return {method: 'GET',url: `/api/forge?job=${encodeURIComponent(jobId)}`,- headers: { 'x-forge-client': 'tester' },+ headers: { 'x-forge-client': 'tester', 'x-vercel-ip-country': 'US' },on(event, cb) {if (event === 'end') cb();},diff --git a/tests/api/forge-realism-routing.test.js b/tests/api/forge-realism-routing.test.jsindex 6dd522073..9a4194d50 100644--- a/tests/api/forge-realism-routing.test.js+++ b/tests/api/forge-realism-routing.test.js@@ -74,11 +74,11 @@ describe('classifyForgeSubject', () => {});describe('High realism tier - self-host lanes lead, NIM is the last free fallthrough', () => {- it('text prompt: Hunyuan3D first, self-host TRELLIS next, HF then free NIM last', () => {+ it('text prompt: self-host TRELLIS leads, Hunyuan3D next (outside restricted territories), HF then free NIM last', () => {configureAllLanes();- expect(freeLaneCandidates('image', 'high', false)).toEqual([- 'hunyuan3d',+ expect(freeLaneCandidates('image', 'high', false, null, 'US')).toEqual(['trellis_selfhost',+ 'hunyuan3d','huggingface','nvidia',]);@@ -86,7 +86,7 @@ describe('High realism tier - self-host lanes lead, NIM is the last free fallthrit('hard-surface subject hoists self-host TRELLIS ahead of Hunyuan3D', () => {configureAllLanes();- expect(freeLaneCandidates('image', 'high', false, 'hardsurface')).toEqual([+ expect(freeLaneCandidates('image', 'high', false, 'hardsurface', 'US')).toEqual(['trellis_selfhost','hunyuan3d','huggingface',@@ -94,11 +94,11 @@ describe('High realism tier - self-host lanes lead, NIM is the last free fallthr]);});- it('organic subject keeps the default Hunyuan3D-first order', () => {+ it('organic subject keeps the default order (TRELLIS first, Hunyuan3D second)', () => {configureAllLanes();- expect(freeLaneCandidates('image', 'high', false, 'organic')).toEqual([- 'hunyuan3d',+ expect(freeLaneCandidates('image', 'high', false, 'organic', 'US')).toEqual(['trellis_selfhost',+ 'hunyuan3d','huggingface','nvidia',]);@@ -106,12 +106,12 @@ describe('High realism tier - self-host lanes lead, NIM is the last free fallthrit('photo submission at high excludes the text-only NIM lane', () => {configureAllLanes();- expect(freeLaneCandidates('image', 'high', true)).toEqual([- 'hunyuan3d',+ expect(freeLaneCandidates('image', 'high', true, null, 'US')).toEqual(['trellis_selfhost',+ 'hunyuan3d','huggingface',]);- expect(freeLaneCandidates('image', 'high', true, 'hardsurface')).toEqual([+ expect(freeLaneCandidates('image', 'high', true, 'hardsurface', 'US')).toEqual(['trellis_selfhost','hunyuan3d','huggingface',@@ -120,9 +120,9 @@ describe('High realism tier - self-host lanes lead, NIM is the last free fallthrit('resolveBackendId picks a self-host lane at high tier', () => {configureAllLanes();- expect(resolveBackendId({ path: 'image', tier: 'high', userImages: false })).toBe('hunyuan3d');+ expect(resolveBackendId({ path: 'image', tier: 'high', userImages: false, country: 'US' })).toBe('trellis_selfhost');expect(- resolveBackendId({ path: 'image', tier: 'high', userImages: false, subjectClass: 'hardsurface' }),+ resolveBackendId({ path: 'image', tier: 'high', userImages: false, subjectClass: 'hardsurface', country: 'US' }),).toBe('trellis_selfhost');});});@@ -132,7 +132,7 @@ describe('High realism tier - health-gated fallthrough to the free NIM lane', ()configureAllLanes();const health = { hunyuan3d: 'down', trellis_selfhost: 'down', huggingface: 'down' };expect(- resolveBackendIdWithHealth({ path: 'image', tier: 'high', userImages: false, health }),+ resolveBackendIdWithHealth({ path: 'image', tier: 'high', userImages: false, health, country: 'US' }),).toBe('nvidia');});@@ -140,7 +140,7 @@ describe('High realism tier - health-gated fallthrough to the free NIM lane', ()configureAllLanes();const health = { hunyuan3d: 'down' };expect(- resolveBackendIdWithHealth({ path: 'image', tier: 'high', userImages: false, health }),+ resolveBackendIdWithHealth({ path: 'image', tier: 'high', userImages: false, health, country: 'US' }),).toBe('trellis_selfhost');});});@@ -178,7 +178,7 @@ describe('Free/default tier now leads with the photoreal reference-image pipelin// a text prompt never dead-ends on a deployment with no self-host/HF lane.it('draft text prompt leads with self-host TRELLIS; native NVIDIA NIM is the last resort', () => {configureAllLanes();- expect(freeLaneCandidates('image', 'draft', false)).toEqual([+ expect(freeLaneCandidates('image', 'draft', false, null, 'US')).toEqual(['trellis_selfhost','hunyuan3d','huggingface',@@ -188,9 +188,9 @@ describe('Free/default tier now leads with the photoreal reference-image pipelinit('standard tier ordering is subject-invariant (reorder is high-only)', () => {configureAllLanes();- const plain = freeLaneCandidates('image', 'standard', false);- expect(freeLaneCandidates('image', 'standard', false, 'hardsurface')).toEqual(plain);- expect(freeLaneCandidates('image', 'standard', false, 'organic')).toEqual(plain);+ const plain = freeLaneCandidates('image', 'standard', false, null, 'US');+ expect(freeLaneCandidates('image', 'standard', false, 'hardsurface', 'US')).toEqual(plain);+ expect(freeLaneCandidates('image', 'standard', false, 'organic', 'US')).toEqual(plain);expect(plain[0]).toBe('trellis_selfhost');});});diff --git a/tests/api/forge-tiers.test.js b/tests/api/forge-tiers.test.jsindex a0d346f94..495baa6f7 100644--- a/tests/api/forge-tiers.test.js+++ b/tests/api/forge-tiers.test.js@@ -54,36 +54,36 @@ describe('forge-tiers — NVIDIA NIM backend registration', () => {it('falls to the paid TRELLIS last resort only when no free image lane is configured', () => {delete process.env.NVIDIA_API_KEY;delete process.env.HF_TOKEN;- expect(resolveBackendId({ path: 'image', tier: 'draft' })).toBe('trellis');- expect(resolveBackendId({ path: 'image', tier: 'standard' })).toBe('trellis');- expect(resolveBackendId({ path: 'image', tier: 'high' })).toBe('trellis');+ expect(resolveBackendId({ path: 'image', tier: 'draft', country: 'US' })).toBe('trellis');+ expect(resolveBackendId({ path: 'image', tier: 'standard', country: 'US' })).toBe('trellis');+ expect(resolveBackendId({ path: 'image', tier: 'high', country: 'US' })).toBe('trellis');});it('routes draft and standard tiers to the free NIM lane when configured', () => {process.env.NVIDIA_API_KEY = 'nvapi-test';- expect(resolveBackendId({ path: 'image', tier: 'draft' })).toBe('nvidia');- expect(resolveBackendId({ path: 'image', tier: 'standard' })).toBe('nvidia');+ expect(resolveBackendId({ path: 'image', tier: 'draft', country: 'US' })).toBe('nvidia');+ expect(resolveBackendId({ path: 'image', tier: 'standard', country: 'US' })).toBe('nvidia');});it('routes the high tier to the free textured engine, geometry stays BYOK Meshy', () => {process.env.NVIDIA_API_KEY = 'nvapi-test';process.env.HF_TOKEN = 'hf_test';// High is free-for-us too — the higher-quality HuggingFace engine, not paid Replicate.- expect(resolveBackendId({ path: 'image', tier: 'high' })).toBe('huggingface');- expect(resolveBackendId({ path: 'geometry', tier: 'draft' })).toBe('meshy');- expect(resolveBackendId({ path: 'geometry', tier: 'standard' })).toBe('meshy');+ expect(resolveBackendId({ path: 'image', tier: 'high', country: 'US' })).toBe('huggingface');+ expect(resolveBackendId({ path: 'geometry', tier: 'draft', country: 'US' })).toBe('meshy');+ expect(resolveBackendId({ path: 'geometry', tier: 'standard', country: 'US' })).toBe('meshy');});});it('stays selectable at any tier when explicitly named', () => {delete process.env.NVIDIA_API_KEY;- expect(resolveBackendId({ path: 'image', tier: 'standard', backend: 'nvidia' })).toBe('nvidia');- expect(resolveBackendId({ path: 'image', tier: 'high', backend: 'nvidia' })).toBe('nvidia');+ expect(resolveBackendId({ path: 'image', tier: 'standard', backend: 'nvidia', country: 'US' })).toBe('nvidia');+ expect(resolveBackendId({ path: 'image', tier: 'high', backend: 'nvidia', country: 'US' })).toBe('nvidia');});it('keeps other backends selectable on the draft tier even when NIM is the default', () => {process.env.NVIDIA_API_KEY = 'nvapi-test';- expect(resolveBackendId({ path: 'image', tier: 'draft', backend: 'trellis' })).toBe('trellis');+ expect(resolveBackendId({ path: 'image', tier: 'draft', backend: 'trellis', country: 'US' })).toBe('trellis');});it('surfaces the backend in the public catalog with honest estimates', () => {@@ -98,14 +98,13 @@ describe('forge-tiers — NVIDIA NIM backend registration', () => {const draftEst = nv.estimates.image.find((e) => e.tier === 'draft');expect(draftEst.eta_seconds).toBeGreaterThan(0);expect(draftEst.credits).toBeNull();- // The tier-aware default map advertises a free engine for every tier. With- // only NVIDIA + HuggingFace configured (no self-host worker) in this test,- // HuggingFace — an image-intermediate, reference-capable lane — outranks- // NVIDIA's native text-only preview at every tier, matching the- // photoreal-reference-by-default policy.- expect(cat.default_backend_for_tier.draft.image).toBe('huggingface');- expect(cat.default_backend_for_tier.standard.image).toBe('huggingface');- expect(cat.default_backend_for_tier.high.image).toBe('huggingface');+ // The catalog is CDN-cached and country-agnostic, so it advertises the+ // fail-closed default: a Tencent-model lane (HuggingFace Spaces) is never+ // listed as a tier default because the requester's territory is unknown.+ // With only NVIDIA + HuggingFace configured, NVIDIA is the one lane left.+ expect(cat.default_backend_for_tier.draft.image).toBe('nvidia');+ expect(cat.default_backend_for_tier.standard.image).toBe('nvidia');+ expect(cat.default_backend_for_tier.high.image).toBe('nvidia');});// NVIDIA's hosted TRELLIS preview is text-only (rejects every user-image@@ -114,18 +113,18 @@ describe('forge-tiers — NVIDIA NIM backend registration', () => {it('routes photo submissions to the standing image backend, not the text-only free lane', () => {process.env.NVIDIA_API_KEY = 'nvapi-test';// Photo uploads at draft and standard must route to trellis (NVIDIA is text-only).- expect(resolveBackendId({ path: 'image', tier: 'draft', userImages: true })).toBe('trellis');- expect(resolveBackendId({ path: 'image', tier: 'standard', userImages: true })).toBe('trellis');+ expect(resolveBackendId({ path: 'image', tier: 'draft', userImages: true, country: 'US' })).toBe('trellis');+ expect(resolveBackendId({ path: 'image', tier: 'standard', userImages: true, country: 'US' })).toBe('trellis');// Prompt-only drafts and standard requests still get the free lane.- expect(resolveBackendId({ path: 'image', tier: 'draft', userImages: false })).toBe('nvidia');- expect(resolveBackendId({ path: 'image', tier: 'draft' })).toBe('nvidia');- expect(resolveBackendId({ path: 'image', tier: 'standard', userImages: false })).toBe('nvidia');- expect(resolveBackendId({ path: 'image', tier: 'standard' })).toBe('nvidia');+ expect(resolveBackendId({ path: 'image', tier: 'draft', userImages: false, country: 'US' })).toBe('nvidia');+ expect(resolveBackendId({ path: 'image', tier: 'draft', country: 'US' })).toBe('nvidia');+ expect(resolveBackendId({ path: 'image', tier: 'standard', userImages: false, country: 'US' })).toBe('nvidia');+ expect(resolveBackendId({ path: 'image', tier: 'standard', country: 'US' })).toBe('nvidia');});it('honors an explicit nvidia selection in resolution (the handler owns the rejection)', () => {process.env.NVIDIA_API_KEY = 'nvapi-test';- expect(resolveBackendId({ path: 'image', tier: 'draft', backend: 'nvidia', userImages: true })).toBe('nvidia');+ expect(resolveBackendId({ path: 'image', tier: 'draft', backend: 'nvidia', userImages: true, country: 'US' })).toBe('nvidia');});it('declares the text-only capability in the public catalog', () => {@@ -189,7 +188,7 @@ describe('forge-tiers — HuggingFace free image lane', () => {it('stays selectable when explicitly named on the image path with photos', () => {expect(- resolveBackendId({ path: 'image', tier: 'standard', backend: 'huggingface', userImages: true }),+ resolveBackendId({ path: 'image', tier: 'standard', backend: 'huggingface', userImages: true, country: 'US' }),).toBe('huggingface');});@@ -200,17 +199,17 @@ describe('forge-tiers — HuggingFace free image lane', () => {it('becomes the auto default for photo submissions and the high tier when configured', () => {process.env.HF_TOKEN = 'hf_test';delete process.env.NVIDIA_API_KEY;- expect(resolveBackendId({ path: 'image', tier: 'draft', userImages: true })).toBe('huggingface');- expect(resolveBackendId({ path: 'image', tier: 'standard', userImages: true })).toBe('huggingface');- expect(resolveBackendId({ path: 'image', tier: 'high' })).toBe('huggingface');- expect(resolveBackendId({ path: 'image', tier: 'high', userImages: true })).toBe('huggingface');+ expect(resolveBackendId({ path: 'image', tier: 'draft', userImages: true, country: 'US' })).toBe('huggingface');+ expect(resolveBackendId({ path: 'image', tier: 'standard', userImages: true, country: 'US' })).toBe('huggingface');+ expect(resolveBackendId({ path: 'image', tier: 'high', country: 'US' })).toBe('huggingface');+ expect(resolveBackendId({ path: 'image', tier: 'high', userImages: true, country: 'US' })).toBe('huggingface');});it('falls back to the paid lane only when no free engine is configured', () => {delete process.env.HF_TOKEN;delete process.env.NVIDIA_API_KEY;- expect(resolveBackendId({ path: 'image', tier: 'standard' })).toBe('trellis');- expect(resolveBackendId({ path: 'image', tier: 'high' })).toBe('trellis');+ expect(resolveBackendId({ path: 'image', tier: 'standard', country: 'US' })).toBe('trellis');+ expect(resolveBackendId({ path: 'image', tier: 'high', country: 'US' })).toBe('trellis');});});diff --git a/tests/api/forge-trellis-selfhost.test.js b/tests/api/forge-trellis-selfhost.test.jsindex 536890019..7be4bb3a3 100644--- a/tests/api/forge-trellis-selfhost.test.js+++ b/tests/api/forge-trellis-selfhost.test.js@@ -86,8 +86,8 @@ describe('forge-tiers — self-hosted TRELLIS routing precedence', () => {process.env.HF_TOKEN = 'hf_test'; // HF also live — TRELLIS must still win the photo defaultprocess.env.NVIDIA_API_KEY = 'nvapi-test';// Draft/standard photo uploads route to our self-hosted TRELLIS, ahead of HF.- expect(resolveBackendId({ path: 'image', tier: 'draft', userImages: true })).toBe('trellis_selfhost');- expect(resolveBackendId({ path: 'image', tier: 'standard', userImages: true })).toBe('trellis_selfhost');+ expect(resolveBackendId({ path: 'image', tier: 'draft', userImages: true, country: 'US' })).toBe('trellis_selfhost');+ expect(resolveBackendId({ path: 'image', tier: 'standard', userImages: true, country: 'US' })).toBe('trellis_selfhost');});it('leads text prompts with the self-host photoreal reference pipeline too; high stays on self-host TRELLIS', () => {@@ -99,24 +99,24 @@ describe('forge-tiers — self-hosted TRELLIS routing precedence', () => {// image-intermediate lane too — NVIDIA's native single-hop text→mesh// preview skips the photoreal reference image, so it is no longer a// named tier default anywhere (see forge-tiers.js FREE_DEFAULT_FOR_TIERS).- expect(resolveBackendId({ path: 'image', tier: 'draft', userImages: false })).toBe('trellis_selfhost');- expect(resolveBackendId({ path: 'image', tier: 'standard', userImages: false })).toBe('trellis_selfhost');+ expect(resolveBackendId({ path: 'image', tier: 'draft', userImages: false, country: 'US' })).toBe('trellis_selfhost');+ expect(resolveBackendId({ path: 'image', tier: 'standard', userImages: false, country: 'US' })).toBe('trellis_selfhost');// High names our self-host Hunyuan3D engine; unconfigured here, so the// candidate walk falls to the self-host TRELLIS lane.- expect(resolveBackendId({ path: 'image', tier: 'high' })).toBe('trellis_selfhost');+ expect(resolveBackendId({ path: 'image', tier: 'high', country: 'US' })).toBe('trellis_selfhost');});it('degrades cleanly to HuggingFace when the worker URL is absent', () => {// No MODEL_TRELLIS_URL → trellis_selfhost unconfigured → HF serves photos.process.env.HF_TOKEN = 'hf_test';process.env.NVIDIA_API_KEY = 'nvapi-test';- expect(resolveBackendId({ path: 'image', tier: 'draft', userImages: true })).toBe('huggingface');+ expect(resolveBackendId({ path: 'image', tier: 'draft', userImages: true, country: 'US' })).toBe('huggingface');});it('stays explicitly selectable (the handler owns any rejection)', () => {// Even unconfigured, an explicit pick is honored at resolution time.expect(- resolveBackendId({ path: 'image', tier: 'standard', backend: 'trellis_selfhost', userImages: true }),+ resolveBackendId({ path: 'image', tier: 'standard', backend: 'trellis_selfhost', userImages: true, country: 'US' }),).toBe('trellis_selfhost');});});@@ -229,11 +229,12 @@ describe('forge-tiers — self-host TRELLIS per-tier quality budgets', () => {expect(selfhostQualityForTier(undefined)).toBe(SELFHOST_TRELLIS_QUALITY.standard);});- it('names hunyuan3d for the high tier and keeps huggingface only as fallback', async () => {+ it('names trellis2 for the high tier and keeps hunyuan3d and huggingface only as fallback', async () => {const { FREE_DEFAULT_FOR_TIERS, FREE_FALLBACK_FOR_PATH } = await import('../../api/_lib/forge-tiers.js');- expect(FREE_DEFAULT_FOR_TIERS.high.image).toBe('hunyuan3d');+ expect(FREE_DEFAULT_FOR_TIERS.high.image).toBe('trellis2');+ expect(FREE_FALLBACK_FOR_PATH.image).toContain('hunyuan3d');expect(FREE_FALLBACK_FOR_PATH.image).toContain('huggingface');});});diff --git a/tests/api/gcp-revert.test.js b/tests/api/gcp-revert.test.jsindex e65168481..113c51768 100644--- a/tests/api/gcp-revert.test.js+++ b/tests/api/gcp-revert.test.js@@ -53,7 +53,7 @@ describe('forge image→3D: GCP self-host lane reverts to a free lane by unsettiexpect(backendIsConfigured('trellis_selfhost')).toBe(true);// A photo submission can't use the text-only NVIDIA lane, so the self-host// worker leads the free candidate ordering.- const id = resolveBackendId({ path: 'image', tier: 'standard', userImages: true });+ const id = resolveBackendId({ path: 'image', tier: 'standard', userImages: true, country: 'US' });expect(id).toBe('trellis_selfhost');});@@ -63,12 +63,12 @@ describe('forge image→3D: GCP self-host lane reverts to a free lane by unsettidelete process.env.GCP_RECONSTRUCTION_KEY;process.env.HF_TOKEN = 'hf_x'; // the pre-program free image→3D laneexpect(backendIsConfigured('trellis_selfhost')).toBe(false);- const id = resolveBackendId({ path: 'image', tier: 'standard', userImages: true });+ const id = resolveBackendId({ path: 'image', tier: 'standard', userImages: true, country: 'US' });expect(id).toBe('huggingface');// And with no free lane at all, it degrades to the paid standing default —// never dead-ends.delete process.env.HF_TOKEN;- expect(resolveBackendId({ path: 'image', tier: 'standard', userImages: true })).toBe('trellis');+ expect(resolveBackendId({ path: 'image', tier: 'standard', userImages: true, country: 'US' })).toBe('trellis');});it('the Hunyuan3D and sketch/remesh gates flip the same way', () => {@@ -90,10 +90,10 @@ describe('forge image→3D: GCP self-host lane reverts to a free lane by unsettiprocess.env.GCP_HUNYUAN3D_URL = 'https://h.run.app';process.env.GCP_RECONSTRUCTION_KEY = 'secret';process.env.HF_TOKEN = 'hf_x';- expect(freeLaneCandidates('image', 'standard', true)).toEqual(['trellis_selfhost', 'hunyuan3d', 'huggingface']);+ expect(freeLaneCandidates('image', 'standard', true, null, 'US')).toEqual(['trellis_selfhost', 'hunyuan3d', 'huggingface']);// Revert: only the external free lane survives.for (const v of ['MODEL_TRELLIS_URL', 'GCP_HUNYUAN3D_URL', 'GCP_RECONSTRUCTION_KEY']) delete process.env[v];- expect(freeLaneCandidates('image', 'standard', true)).toEqual(['huggingface']);+ expect(freeLaneCandidates('image', 'standard', true, null, 'US')).toEqual(['huggingface']);});});diff --git a/tests/api/prompt-avatar-routing.test.js b/tests/api/prompt-avatar-routing.test.jsindex 8efdc40e8..d24b1d592 100644--- a/tests/api/prompt-avatar-routing.test.js+++ b/tests/api/prompt-avatar-routing.test.js@@ -100,7 +100,11 @@ async function reconstruct(body) {const req = {method: 'POST',url: '/api/avatars/reconstruct',- headers: { 'content-type': 'application/json', origin: 'https://three.ws' },+ headers: {+ 'content-type': 'application/json',+ origin: 'https://three.ws',+ 'x-client-geo-location': 'US,California',+ },body,};const res = makeRes();@@ -112,7 +116,7 @@ const stub = (name) => ({ name, instance: { supportsMode: () => true, submit: videscribe('planPromptAvatarLanes', () => {it('leads with self-hosted Hunyuan3D and never offers the face pipeline', () => {- const plan = planPromptAvatarLanes({ platform: [{ name: 'gcp', instance: gcpInstance }] });+ const plan = planPromptAvatarLanes({ platform: [{ name: 'gcp', instance: gcpInstance }], country: 'US' });expect(plan.map((p) => p.mode)).toEqual(['hunyuan', 'trellis']);expect(plan.every((p) => p.name === 'gcp')).toBe(true);expect(plan[0].params).toMatchObject({ tier: 'high', path: 'image' });@@ -122,6 +126,7 @@ describe('planPromptAvatarLanes', () => {const plan = planPromptAvatarLanes({platform: [stub('huggingface'), { name: 'gcp', instance: gcpInstance }, stub('replicate')],byok: [stub('meshy')],+ country: 'US',});expect(plan.map((p) => p.lane)).toEqual(['hunyuan3d', 'trellis_selfhost', 'replicate', 'huggingface', 'meshy']);expect(plan.filter((p) => p.name !== 'gcp').every((p) => p.mode === 'reconstruct')).toBe(true);@@ -129,7 +134,7 @@ describe('planPromptAvatarLanes', () => {it('omits a self-host engine the gcp adapter has no worker for', () => {const gcpNoTrellis = { supportsMode: (m) => m === 'hunyuan' };- const plan = planPromptAvatarLanes({ platform: [{ name: 'gcp', instance: gcpNoTrellis }] });+ const plan = planPromptAvatarLanes({ platform: [{ name: 'gcp', instance: gcpNoTrellis }], country: 'US' });expect(plan.map((p) => p.lane)).toEqual(['hunyuan3d']);});@@ -137,6 +142,7 @@ describe('planPromptAvatarLanes', () => {const plan = planPromptAvatarLanes({platform: [{ name: 'gcp', instance: gcpInstance }, stub('huggingface')],health: { hunyuan3d: { status: 'down', warm: false } },+ country: 'US',});expect(plan.map((p) => p.lane)).toEqual(['trellis_selfhost', 'huggingface', 'hunyuan3d']);});@@ -145,10 +151,29 @@ describe('planPromptAvatarLanes', () => {const plan = planPromptAvatarLanes({platform: [{ name: 'gcp', instance: gcpInstance }, stub('huggingface')],health: { hunyuan3d: { status: 'down', warm: false, cooled: true } },+ country: 'US',});expect(plan[0].lane).toBe('hunyuan3d');});+ it('leads with TRELLIS.2 and never offers a Tencent lane in the EU, the UK, South Korea or an unknown country', () => {+ const withTrellis2 = {+ supportsMode: (m) => ['reconstruct', 'trellis2', 'hunyuan', 'trellis'].includes(m),+ };+ for (const country of ['DE', 'GB', 'KR', null]) {+ const plan = planPromptAvatarLanes({+ platform: [stub('huggingface'), { name: 'gcp', instance: withTrellis2 }, stub('replicate')],+ country,+ });+ expect(plan.map((p) => p.lane)).toEqual(['trellis2', 'trellis_selfhost', 'replicate']);+ }+ const open = planPromptAvatarLanes({+ platform: [stub('huggingface'), { name: 'gcp', instance: withTrellis2 }],+ country: 'US',+ });+ expect(open.map((p) => p.lane)).toEqual(['trellis2', 'hunyuan3d', 'trellis_selfhost', 'huggingface']);+ });+it('returns nothing when no image→3D engine is configured', () => {expect(planPromptAvatarLanes({})).toEqual([]);});diff --git a/tests/forge-failover.test.js b/tests/forge-failover.test.jsindex c0610fff1..8d0db0080 100644--- a/tests/forge-failover.test.js+++ b/tests/forge-failover.test.js@@ -161,33 +161,33 @@ describe('retryBackendSuggestions', () => {process.env.HF_TOKEN = 'hf';process.env.REPLICATE_API_TOKEN = 'r8';- const all = retryBackendSuggestions({ hasImage: true });+ const all = retryBackendSuggestions({ hasImage: true, country: 'US' });expect(all).toEqual(['trellis_selfhost', 'huggingface', 'trellis']);- const minusFailed = retryBackendSuggestions({ hasImage: true, attempted: ['trellis_selfhost'] });+ const minusFailed = retryBackendSuggestions({ hasImage: true, attempted: ['trellis_selfhost'], country: 'US' });expect(minusFailed).toEqual(['huggingface', 'trellis']);});it('offers the text-only NVIDIA lane for text jobs but never for photo input', () => {process.env.NVIDIA_API_KEY = 'nv';- expect(retryBackendSuggestions({ hasImage: false })).toEqual(['nvidia']);- expect(retryBackendSuggestions({ hasImage: true })).toEqual([]);+ expect(retryBackendSuggestions({ hasImage: false, country: 'US' })).toEqual(['nvidia']);+ expect(retryBackendSuggestions({ hasImage: true, country: 'US' })).toEqual([]);});it('returns [] when nothing is configured — the caller omits the retry affordance', () => {- expect(retryBackendSuggestions({ hasImage: true })).toEqual([]);+ expect(retryBackendSuggestions({ hasImage: true, country: 'US' })).toEqual([]);});});describe('pickRedispatchLane', () => {it('returns null with no configured async lane', async () => {- expect(await pickRedispatchLane({ attempted: [] })).toBeNull();+ expect(await pickRedispatchLane({ attempted: [], country: 'US' })).toBeNull();});it('skips attempted lanes even when configured', async () => {process.env.MODEL_TRELLIS_URL = 'https://model-trellis.example';process.env.GCP_RECONSTRUCTION_KEY = 'k';- expect(await pickRedispatchLane({ attempted: ['trellis_selfhost'] })).toBeNull();+ expect(await pickRedispatchLane({ attempted: ['trellis_selfhost'], country: 'US' })).toBeNull();});it('skips lanes the health snapshot marks down', async () => {@@ -195,12 +195,12 @@ describe('pickRedispatchLane', () => {process.env.GCP_HUNYUAN3D_URL = 'https://hunyuan.example';process.env.GCP_RECONSTRUCTION_KEY = 'k';laneHealth.mockResolvedValue({ byId: { trellis_selfhost: { status: 'down' } } });- expect(await pickRedispatchLane({ attempted: [] })).toBe('hunyuan3d');+ expect(await pickRedispatchLane({ attempted: [], country: 'US' })).toBe('hunyuan3d');laneHealth.mockResolvedValue({byId: { trellis_selfhost: { status: 'down' }, hunyuan3d: { status: 'down' } },});- expect(await pickRedispatchLane({ attempted: [] })).toBeNull();+ expect(await pickRedispatchLane({ attempted: [], country: 'US' })).toBeNull();});it('falls through to the geometry-only TripoSG lane once every textured lane is down', async () => {@@ -213,8 +213,8 @@ describe('pickRedispatchLane', () => {laneHealth.mockResolvedValue({byId: { trellis_selfhost: { status: 'down' }, hunyuan3d: { status: 'down' } },});- expect(await pickRedispatchLane({ attempted: [] })).toBe('triposg');- expect(await pickRedispatchLane({ attempted: ['hunyuan3d', 'trellis_selfhost'] })).toBe('triposg');+ expect(await pickRedispatchLane({ attempted: [], country: 'US' })).toBe('triposg');+ expect(await pickRedispatchLane({ attempted: ['hunyuan3d', 'trellis_selfhost'], country: 'US' })).toBe('triposg');});it('never prefers the untextured TripoSG lane over a live textured one', async () => {@@ -222,18 +222,18 @@ describe('pickRedispatchLane', () => {process.env.GCP_TRIPOSG_URL = 'https://triposg.example';process.env.REPLICATE_API_TOKEN = 'r8_test';process.env.GCP_RECONSTRUCTION_KEY = 'k';- expect(await pickRedispatchLane({ attempted: [] })).toBe('hunyuan3d');+ expect(await pickRedispatchLane({ attempted: [], country: 'US' })).toBe('hunyuan3d');// Paid textured TRELLIS still outranks it when configured.- expect(await pickRedispatchLane({ attempted: ['hunyuan3d'] })).toBe('trellis');- expect(await pickRedispatchLane({ attempted: ['hunyuan3d', 'trellis'] })).toBe('triposg');- expect(await pickRedispatchLane({ attempted: ['hunyuan3d', 'trellis', 'triposg'] })).toBeNull();+ expect(await pickRedispatchLane({ attempted: ['hunyuan3d'], country: 'US' })).toBe('trellis');+ expect(await pickRedispatchLane({ attempted: ['hunyuan3d', 'trellis'], country: 'US' })).toBe('triposg');+ expect(await pickRedispatchLane({ attempted: ['hunyuan3d', 'trellis', 'triposg'], country: 'US' })).toBeNull();});it('keeps TripoSG out of the fresh-retry suggestions (its public lane is sketch-only)', () => {process.env.GCP_TRIPOSG_URL = 'https://triposg.example';process.env.GCP_RECONSTRUCTION_KEY = 'k';- expect(retryBackendSuggestions({ hasImage: true })).not.toContain('triposg');- expect(retryBackendSuggestions({ hasImage: false })).not.toContain('triposg');+ expect(retryBackendSuggestions({ hasImage: true, country: 'US' })).not.toContain('triposg');+ expect(retryBackendSuggestions({ hasImage: false, country: 'US' })).not.toContain('triposg');});it('falls back to the first configured candidate when the health snapshot throws', async () => {@@ -243,10 +243,10 @@ describe('pickRedispatchLane', () => {process.env.GCP_HUNYUAN3D_URL = 'https://hunyuan.example';process.env.GCP_RECONSTRUCTION_KEY = 'k';laneHealth.mockRejectedValue(new Error('telemetry down'));- expect(await pickRedispatchLane({ attempted: [] })).toBe('trellis_selfhost');+ expect(await pickRedispatchLane({ attempted: [], country: 'US' })).toBe('trellis_selfhost');// The fallback respects the attempted filter: candidates[0] is the first// UNATTEMPTED configured lane, not the first lane in the static order.- expect(await pickRedispatchLane({ attempted: ['trellis_selfhost'] })).toBe('hunyuan3d');+ expect(await pickRedispatchLane({ attempted: ['trellis_selfhost'], country: 'US' })).toBe('hunyuan3d');});});diff --git a/tests/forge-options.test.js b/tests/forge-options.test.jsindex 6c38522d1..ff6aa9b0d 100644--- a/tests/forge-options.test.js+++ b/tests/forge-options.test.js@@ -114,6 +114,7 @@ describe('summarizeForgeOptions', () => {output_format: 'glb-draco',texture_size: 1024,target_polycount: null,+ resolution: null,// Material completion is on unless the caller opts out, and the echo// says so, so a client can tell why its delivered file carries maps.derive_pbr: true,diff --git a/tests/forge-territory.test.js b/tests/forge-territory.test.jsnew file mode 100644index 000000000..24efef2c3--- /dev/null+++ b/tests/forge-territory.test.js@@ -0,0 +1,150 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import {+ RESTRICTED_COUNTRIES,+ TENCENT_LANES,+ filterLanesForTerritory,+ isRestrictedTerritory,+ laneAllowedInTerritory,+ requestTerritory,+} from '../api/_lib/forge-territory.js';+import {+ BACKENDS,+ freeLaneCandidates,+ laneAfterHfFailure,+ resolveBackendId,+ resolveBackendIdWithHealth,+} from '../api/_lib/forge-tiers.js';+import { pickRedispatchLane, retryBackendSuggestions } from '../api/_lib/forge-failover.js';+import { normalizeForgeOptions } from '../api/_lib/forge-options.js';++const ENV_KEYS = [+ 'MODEL_TRELLIS2_URL',+ 'MODEL_TRELLIS_URL',+ 'GCP_HUNYUAN3D_URL',+ 'GCP_RECONSTRUCTION_KEY',+ 'HF_TOKEN',+ 'NVIDIA_API_KEY',+];+let saved;++beforeEach(() => {+ saved = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));+ process.env.MODEL_TRELLIS2_URL = 'https://trellis2.test';+ process.env.MODEL_TRELLIS_URL = 'https://trellis.test';+ process.env.GCP_HUNYUAN3D_URL = 'https://hunyuan.test';+ process.env.GCP_RECONSTRUCTION_KEY = 'k';+ process.env.HF_TOKEN = 'hf';+});++afterEach(() => {+ for (const k of ENV_KEYS) {+ if (saved[k] === undefined) delete process.env[k];+ else process.env[k] = saved[k];+ }+});++const EU_UK_KR = ['DE', 'FR', 'IT', 'ES', 'NL', 'SE', 'IE', 'PL', 'GB', 'KR'];++describe('territory classification', () => {+ it('restricts every EU member state, the UK and South Korea', () => {+ expect(RESTRICTED_COUNTRIES).toHaveLength(29);+ for (const c of EU_UK_KR) expect(isRestrictedTerritory(c)).toBe(true);+ expect(isRestrictedTerritory('gb')).toBe(true);+ });++ it('fails closed on an unknown or malformed country', () => {+ for (const c of [null, undefined, '', 'XX1', 42]) expect(isRestrictedTerritory(c)).toBe(true);+ });++ it('does not restrict other countries', () => {+ for (const c of ['US', 'CA', 'JP', 'BR', 'IN', 'AU', 'CH', 'NO']) {+ expect(isRestrictedTerritory(c)).toBe(false);+ }+ });++ it('reads the country from the edge header only', () => {+ expect(requestTerritory({ headers: { 'x-client-geo-location': 'DE,Berlin' } })).toBe('DE');+ expect(requestTerritory({ headers: {} })).toBeNull();+ });+});++describe('lane filter', () => {+ it('closes both Tencent lanes to restricted territories and opens them elsewhere', () => {+ for (const lane of TENCENT_LANES) {+ for (const c of [...EU_UK_KR, null]) expect(laneAllowedInTerritory(lane, c)).toBe(false);+ expect(laneAllowedInTerritory(lane, 'US')).toBe(true);+ }+ expect(laneAllowedInTerritory('trellis2', 'DE')).toBe(true);+ expect(filterLanesForTerritory(['trellis2', 'hunyuan3d', 'huggingface'], 'KR')).toEqual(['trellis2']);+ });+});++describe('Forge routing never selects a Tencent lane for EU, UK or KR', () => {+ for (const country of [...EU_UK_KR, null]) {+ for (const tier of ['draft', 'standard', 'high']) {+ it(`${country ?? 'unknown'} / ${tier}: candidates and default exclude Tencent lanes`, () => {+ const candidates = freeLaneCandidates('image', tier, true, null, country);+ for (const lane of TENCENT_LANES) expect(candidates).not.toContain(lane);+ expect(resolveBackendId({ path: 'image', tier, userImages: true, country })).toBe('trellis2');+ });+ }++ it(`${country ?? 'unknown'}: still excludes Tencent lanes when TRELLIS.2 and TRELLIS v1 are down`, () => {+ const health = { trellis2: 'down', trellis_selfhost: 'down' };+ const chosen = resolveBackendIdWithHealth({+ path: 'image',+ tier: 'high',+ userImages: true,+ health,+ country,+ });+ expect(TENCENT_LANES).not.toContain(chosen);+ });++ it(`${country ?? 'unknown'}: HuggingFace failover does not hop to Hunyuan3D`, () => {+ expect(laneAfterHfFailure({ userImages: true, country })).not.toBe('hunyuan3d');+ });++ it(`${country ?? 'unknown'}: poll-time redispatch and retry suggestions skip Tencent lanes`, async () => {+ const attempted = ['trellis2', 'trellis_selfhost'];+ const next = await pickRedispatchLane({ attempted, country });+ expect(TENCENT_LANES).not.toContain(next);+ const suggestions = retryBackendSuggestions({ attempted: [], hasImage: true, country });+ for (const lane of TENCENT_LANES) expect(suggestions).not.toContain(lane);+ });+ }++ it('keeps Hunyuan3D reachable for an allowed country as a fallback behind TRELLIS.2', () => {+ const candidates = freeLaneCandidates('image', 'high', true, null, 'US');+ expect(candidates[0]).toBe('trellis2');+ expect(candidates).toContain('trellis_selfhost');+ expect(candidates).toContain('hunyuan3d');+ expect(candidates).toContain('huggingface');+ expect(laneAfterHfFailure({ userImages: true, country: 'US' })).toBe('hunyuan3d');+ });++ it('serves from the next configured lane when TRELLIS.2 is unconfigured', () => {+ delete process.env.MODEL_TRELLIS2_URL;+ expect(resolveBackendId({ path: 'image', tier: 'standard', userImages: true, country: 'DE' })).toBe(+ 'trellis_selfhost',+ );+ });+});++describe('TRELLIS.2 lane registration', () => {+ it('is a free, self-host, image-accepting lane', () => {+ const b = BACKENDS.trellis2;+ expect(b).toMatchObject({ free: true, provider: 'gcp', userImages: true });+ expect(b.paths).toContain('image');+ expect(b.requiresEnv).toContain('MODEL_TRELLIS2_URL');+ });++ it('accepts only the supported resolutions as a request option', () => {+ for (const r of [512, 1024, 1536, '1024']) {+ expect(normalizeForgeOptions({ resolution: r }).errors).toEqual([]);+ }+ expect(normalizeForgeOptions({ resolution: 2048 }).errors[0].field).toBe('resolution');+ expect(normalizeForgeOptions({}).resolution).toBeNull();+ expect(normalizeForgeOptions({ resolution: 1536 }).hasOptions).toBe(true);+ });+});diff --git a/workers/model-hunyuan3d/NOTICE b/workers/model-hunyuan3d/NOTICEnew file mode 100644index 000000000..4c2071407--- /dev/null+++ b/workers/model-hunyuan3d/NOTICE@@ -0,0 +1,5 @@+Tencent Hunyuan 3D 2.1 is licensed under the Tencent Hunyuan 3D 2.1 Community License Agreement, Copyright (c) 2025 Tencent. All Rights Reserved. The trademark rights of "Tencent Hunyuan" are owned by Tencent or its affiliate.++Territory: the license applies to the worldwide territory excluding the European Union, the United Kingdom and South Korea (Section 1.l), and forbids using the model or its output outside that territory (Section 5.c). three.ws therefore never routes a request from those regions to a Tencent model lane. The enforcement lives in api/_lib/forge-territory.js and is described in workers/model-hunyuan3d/README.md.++The full agreement and the upstream third-party notices ship in the weights bucket next to the checkpoints: gs://three-ws-model-weights/hunyuan3d-2.1/LICENSE and gs://three-ws-model-weights/hunyuan3d-2.1/Notice.txt.diff --git a/workers/model-hunyuan3d/README.md b/workers/model-hunyuan3d/README.mdindex e8fb986a3..ef7842cca 100644--- a/workers/model-hunyuan3d/README.md+++ b/workers/model-hunyuan3d/README.md@@ -75,6 +75,30 @@ and DINOv2 reference encoder carry their own upstream licenses (BSD-3 and Apache2.0 respectively). No weights or model code are redistributed by the platform;only generated GLBs are returned to callers.+### Territory rule (EU, UK and South Korea are excluded)++The agreement covers the worldwide territory **excluding the European Union,+the United Kingdom and South Korea** (Section 1.l), and Section 5.c forbids using+the model, or its output, outside that territory. The platform enforces this on+the server, not in the client:++- The requester's country comes from the edge geo header (`clientCountry` in+ `api/_lib/client-geo.js`), never from a request body field.+- `api/_lib/forge-territory.js` holds the restricted set (the 27 EU member+ states, GB and KR) and `laneAllowedInTerritory`. An unknown or malformed+ country is treated as restricted (fail closed).+- Both Tencent-model lanes are gated: `hunyuan3d` (this worker) and+ `huggingface` (a Spaces chain that runs Hunyuan3D-2 and 2.1). Auto routing,+ poll-time failover, the failover suggestions and the prompt-to-avatar plan+ all filter through it, and an explicit `backend=hunyuan3d` or+ `backend=huggingface` request from a restricted country answers `403+ region_restricted` with the lanes that remain open.+- TRELLIS.2 (MIT, `workers/model-trellis2/`) is the default image-to-3D lane+ everywhere, and the only one of the two families that serves the restricted+ regions.++The Notice file the agreement requires is in [`NOTICE`](NOTICE).+## Endpoints`POST /infer`, `POST /reconstruct`, `GET /tasks/{id}`, `GET /jobs/{id}` require