Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(motion): text2motion worker + forge-motion endpoint

nirholas0f6d28c2ab00
diff --git a/api/_mcp/tools/animations.js b/api/_mcp/tools/animations.js
index f7b6f1b85..36128da73 100644
--- a/api/_mcp/tools/animations.js
+++ b/api/_mcp/tools/animations.js
@@ -15,6 +15,7 @@
import { limits } from '../../_lib/rate-limit.js';
import { resolveOrigin } from '../origin.js';
import { fetchModel, FetchModelError } from '../../_lib/fetch-model.js';
+import { createRegenProvider } from '../../_providers/gcp.js';
import {
canonicalNodeMapFromObject,
retargetClip,
@@ -353,4 +354,196 @@ export const toolDefs = [
};
},
},
+ {
+ name: 'text_to_animation',
+ title: 'Generate an animation from a text prompt and retarget it onto a model',
+ description:
+ 'Generate a brand-new motion from a natural-language prompt (e.g. "waving confidently", "a slow tai-chi sweep") with a motion-diffusion model, then retarget it onto a caller-supplied rigged humanoid GLB — the same retarget engine apply_animation uses. Returns the retargeted three.js AnimationClip JSON (or a baked animated GLB) plus a report. Unlike preset libraries, the motion does not pre-exist: it is synthesized for the prompt. Requires the text2motion worker configured on the deployment.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ prompt: {
+ type: 'string',
+ minLength: 3,
+ maxLength: 1000,
+ description: 'Describe the motion to generate (e.g. "a celebratory jump", "waving hello").',
+ },
+ model_url: {
+ type: 'string',
+ format: 'uri',
+ description: 'Public https URL of a rigged humanoid .glb to animate.',
+ },
+ duration_seconds: {
+ type: 'number',
+ minimum: 1,
+ maximum: 10,
+ default: 4,
+ description: 'Length of the generated motion in seconds.',
+ },
+ format: {
+ type: 'string',
+ enum: ['glb', 'clip'],
+ default: 'clip',
+ description: 'clip = retargeted AnimationClip JSON (reliable); glb = also attempt a baked animated GLB.',
+ },
+ speed: {
+ type: 'number',
+ minimum: 0.25,
+ maximum: 2.5,
+ default: 1,
+ description: 'Playback-speed multiplier baked into the result.',
+ },
+ },
+ required: ['prompt', 'model_url'],
+ additionalProperties: false,
+ },
+ async handler(args, auth, req) {
+ const rl = await limits.mcpOptimize?.(auth.userId || auth.rateKey);
+ if (rl && !rl.success)
+ throw rpcError(-32000, 'rate_limited', {
+ retry_after: Math.ceil((rl.reset - Date.now()) / 1000),
+ });
+
+ // The motion model runs on the GPU worker (workers/model-text2motion),
+ // reached through the gcp provider's text2motion mode. Without it
+ // configured, fail clean rather than fabricate motion.
+ let provider;
+ try {
+ provider = createRegenProvider();
+ } catch {
+ throw rpcError(-32001, 'text-to-animation is not configured on this deployment');
+ }
+ if (!provider.supportsMode('text2motion')) {
+ throw rpcError(-32001, 'text-to-animation is not configured (GCP_TEXT2MOTION_URL unset)');
+ }
+
+ const duration = Math.max(1, Math.min(10, Number(args.duration_seconds) || 4));
+ const clipJSON = await generateMotionClip(provider, {
+ prompt: args.prompt,
+ duration_seconds: duration,
+ });
+
+ installDomShims();
+ const baseClip = parseClipJSON(clipJSON, clipJSON.name || 'generated');
+
+ const { bytes, url, filename } = await safeFetchModel(args.model_url);
+ let gltf;
+ try {
+ gltf = await parseGLB(bytes);
+ } catch (e) {
+ throw new Error(`could not parse the rigged GLB: ${e.message || e}`);
+ }
+ const scene = gltf.scene || gltf.scenes?.[0];
+ if (!scene) throw new Error('the model has no scene to animate');
+
+ const map = canonicalNodeMapFromObject(scene);
+ if (map.size === 0) {
+ throw new Error('no recognizable humanoid skeleton found — text_to_animation needs a rigged GLB');
+ }
+ const hipScale = await computeHipScale(scene, baseClip);
+ const result = retargetClip(baseClip, map, { hipScale });
+
+ const report = {
+ prompt: args.prompt,
+ source_model: url,
+ filename,
+ bones_matched: result.matched,
+ bones_total: result.total,
+ coverage: Number(result.coverage.toFixed(3)),
+ bones_unmapped: [...new Set(result.dropped)],
+ hip_scale: Number(result.hipScale.toFixed(3)),
+ speed: args.speed || 1,
+ };
+
+ if (!result.clip) {
+ return {
+ content: [
+ {
+ type: 'text',
+ text: `Generated the motion but could not retarget it: only ${result.matched}/${result.total} tracks mapped (need ${Math.round(MIN_COVERAGE * 100)}%). The skeleton is too different from the canonical humanoid rig.`,
+ },
+ ],
+ structuredContent: { ok: false, ...report },
+ };
+ }
+
+ const finalClip = scaleClipSpeed(result.clip, args.speed || 1);
+ finalClip.name = baseClip.name;
+ const { AnimationClip } = await import('three');
+
+ const clipResult = (note) => ({
+ content: [
+ {
+ type: 'text',
+ text: `Generated "${args.prompt}" → retargeted onto ${filename}: ${report.bones_matched}/${report.bones_total} bones (${Math.round(report.coverage * 100)}%), hip scale ${report.hip_scale}×.${note ? ' ' + note : ''} Returning AnimationClip JSON — load it alongside the model and play.`,
+ },
+ ],
+ structuredContent: {
+ ok: true,
+ ...report,
+ format: note ? 'clip-fallback' : 'clip',
+ clip: AnimationClip.toJSON(finalClip),
+ },
+ });
+
+ if (args.format !== 'glb') return clipResult();
+
+ let glbBytes;
+ try {
+ glbBytes = Buffer.from(await exportGLB(scene, finalClip));
+ } catch (e) {
+ return clipResult(`Server-side GLB bake unavailable (${e.message || e}); use the /pose gallery to export in-browser.`);
+ }
+ if (glbBytes.length > MAX_INLINE_GLB_BYTES) {
+ return clipResult(`Animated GLB is ${(glbBytes.length / 1024 / 1024).toFixed(1)} MB — too large to inline.`);
+ }
+ return {
+ content: [
+ {
+ type: 'text',
+ text: `Generated "${args.prompt}" and baked it onto ${filename}: ${report.bones_matched}/${report.bones_total} bones, ${(glbBytes.length / 1024).toFixed(0)} KB animated GLB.`,
+ },
+ ],
+ structuredContent: {
+ ok: true,
+ ...report,
+ format: 'glb',
+ glb_bytes: glbBytes.length,
+ glb_base64: glbBytes.toString('base64'),
+ mime_type: 'model/gltf-binary',
+ },
+ };
+ },
+ },
];
+
+// Submit a text→motion job to the worker and poll to completion, returning the
+// generated AnimationClip JSON. Bounded so a stuck worker can't hang the tool.
+const MOTION_POLL_INTERVAL_MS = 2500;
+const MOTION_POLL_TIMEOUT_MS = 60_000;
+
+async function generateMotionClip(provider, { prompt, duration_seconds }) {
+ const job = await provider.submit({
+ mode: 'text2motion',
+ sourceUrl: null,
+ params: { prompt, duration_seconds, fps: 30 },
+ });
+ const deadline = Date.now() + MOTION_POLL_TIMEOUT_MS;
+ let clipUrl = null;
+ while (Date.now() < deadline) {
+ await new Promise((r) => setTimeout(r, MOTION_POLL_INTERVAL_MS));
+ const st = await provider.status(job.extJobId);
+ if (st.status === 'done') {
+ clipUrl = st.resultClipUrl;
+ break;
+ }
+ if (st.status === 'failed') {
+ throw rpcError(-32000, `motion generation failed: ${st.error || 'unknown error'}`);
+ }
+ }
+ if (!clipUrl) throw rpcError(-32000, 'motion generation timed out');
+
+ const res = await fetch(clipUrl);
+ if (!res.ok) throw rpcError(-32000, `could not fetch generated clip (HTTP ${res.status})`);
+ return res.json();
+}
diff --git a/api/_providers/gcp.js b/api/_providers/gcp.js
index da9c299b8..b41064593 100644
--- a/api/_providers/gcp.js
+++ b/api/_providers/gcp.js
@@ -66,6 +66,8 @@ function serviceUrlForMode(mode) {
return readEnv('GCP_REMBG_URL');
case 'segment':
return readEnv('GCP_SEGMENT_URL');
+ case 'text2motion':
+ return readEnv('GCP_TEXT2MOTION_URL');
case 'rerig':
// Rigging is handled by the pipeline controller via its /rig endpoint.
return readEnv('GCP_RECONSTRUCTION_URL');
@@ -198,6 +200,20 @@ function buildWorkerRequest(request) {
};
}
+ if (mode === 'text2motion') {
+ // Text→motion has no source mesh: the prompt rides in params. The worker
+ // returns a three.js AnimationClip JSON URL (result_url), not a GLB.
+ return {
+ path: '/infer',
+ resultKey: 'result_url',
+ body: {
+ prompt: params?.prompt || '',
+ duration_seconds: params?.duration_seconds ?? 4,
+ fps: params?.fps ?? 30,
+ },
+ };
+ }
+
return null;
}
@@ -211,6 +227,7 @@ const MODE_ETA = {
retex_region: 60,
rembg: 5,
segment: 45,
+ text2motion: 30,
rerig: 45,
};
@@ -349,6 +366,11 @@ export function createRegenProvider() {
result.error = `${mode} finished but no result URL in response`;
} else if (mode === 'rembg') {
result.resultImageUrl = url;
+ } else if (mode === 'text2motion') {
+ // The result is a three.js AnimationClip JSON, not a mesh.
+ result.resultClipUrl = url;
+ if (typeof data.frames === 'number') result.frames = data.frames;
+ if (typeof data.fps === 'number') result.fps = data.fps;
} else {
result.resultGlbUrl = url;
}
diff --git a/api/forge-motion.js b/api/forge-motion.js
new file mode 100644
index 000000000..0638c1faf
--- /dev/null
+++ b/api/forge-motion.js
@@ -0,0 +1,124 @@
+/**
+ * /api/forge-motion — text → animation clip for the forge/avatar pipeline.
+ *
+ * POST /api/forge-motion {
+ * prompt: string, // "waving confidently", "a slow tai-chi sweep"
+ * duration_seconds?: number, // 1–10, default 4
+ * fps?: number // 8–60, default 30
+ * } → 202 { job_id, status, eta_seconds }
+ *
+ * GET /api/forge-motion?job=<id>
+ * → { job_id, status, clip_url?, frames?, fps?, error? }
+ *
+ * The worker (workers/model-text2motion) samples a motion-diffusion model and
+ * returns a three.js AnimationClip JSON on the canonical Wolf3D skeleton — the
+ * SAME format the curated animation library serves — so the client retargets a
+ * generated clip onto a loaded avatar with the existing engine
+ * (src/animation-retarget.js), identical to a preset. Routes to the worker via
+ * the GCP provider's `text2motion` mode when GCP_TEXT2MOTION_URL is set.
+ *
+ * Tripo (and the rest of the field) cannot generate animation from a prompt —
+ * this is the differentiating capability, reusing our rig + retarget + library.
+ */
+
+import { cors, json, method, readJson, wrap } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { createRegenProvider } from './_providers/gcp.js';
+
+const JOB_ID_RE = /^[A-Za-z0-9_-]{20,64}$/;
+const MAX_DURATION = 10;
+const MIN_DURATION = 1;
+
+function unconfigured(res) {
+ return json(res, 503, {
+ error: 'unconfigured',
+ message:
+ 'Text-to-animation is not configured. Set GCP_TEXT2MOTION_URL and GCP_RECONSTRUCTION_KEY ' +
+ 'to the URL and bearer secret of your deployed workers/model-text2motion Cloud Run service.',
+ });
+}
+
+async function startJob(req, res) {
+ const ip = clientIp(req);
+ const rl = await limits.mcp3dGenerate(ip);
+ if (!rl.success) {
+ return json(res, 429, {
+ error: 'rate_limited',
+ retry_after: Math.ceil((rl.reset - Date.now()) / 1000),
+ });
+ }
+
+ const body = await readJson(req, 4_000).catch(() => null);
+ const prompt = typeof body?.prompt === 'string' ? body.prompt.trim() : '';
+ if (prompt.length < 3 || prompt.length > 1000) {
+ return json(res, 400, {
+ error: 'invalid_prompt',
+ message: 'Describe the motion in 3–1000 characters (e.g. "waving confidently").',
+ });
+ }
+ const duration = Math.max(MIN_DURATION, Math.min(MAX_DURATION, Number(body?.duration_seconds) || 4));
+ const fps = Math.max(8, Math.min(60, Number(body?.fps) || 30));
+
+ let provider;
+ try {
+ provider = createRegenProvider();
+ if (!provider.supportsMode('text2motion')) return unconfigured(res);
+ } catch {
+ return unconfigured(res);
+ }
+
+ try {
+ const job = await provider.submit({
+ mode: 'text2motion',
+ sourceUrl: null,
+ params: { prompt, duration_seconds: duration, fps },
+ });
+ return json(res, 202, {
+ job_id: job.extJobId,
+ status: 'queued',
+ eta_seconds: job.eta,
+ });
+ } catch (err) {
+ return json(res, 502, { error: 'motion_failed', message: err?.message || 'Motion generation could not start.' });
+ }
+}
+
+async function pollJob(req, res, jobId) {
+ if (!JOB_ID_RE.test(jobId)) {
+ return json(res, 400, { error: 'invalid_job', message: 'Malformed job id.' });
+ }
+
+ const rl = await limits.mcp3dStatus(clientIp(req));
+ if (!rl.success) {
+ return json(res, 429, { error: 'rate_limited', retry_after: Math.ceil((rl.reset - Date.now()) / 1000) });
+ }
+
+ let provider;
+ try {
+ provider = createRegenProvider();
+ } catch {
+ return unconfigured(res);
+ }
+
+ const result = await provider.status(jobId);
+ return json(res, 200, {
+ job_id: jobId,
+ status: result.status,
+ clip_url: result.resultClipUrl || null,
+ frames: typeof result.frames === 'number' ? result.frames : null,
+ fps: typeof result.fps === 'number' ? result.fps : null,
+ error: result.error || null,
+ });
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ if (req.method === 'POST') return startJob(req, res);
+
+ const url = new URL(req.url, 'http://localhost');
+ const jobId = (url.searchParams.get('job') || '').trim();
+ if (!jobId) return json(res, 400, { error: 'missing_job', message: 'Pass ?job=<id> to poll.' });
+ return pollJob(req, res, jobId);
+});
diff --git a/docs/internal/PROGRESS.md b/docs/internal/PROGRESS.md
index b2eb7e2f8..20c3e37bb 100644
--- a/docs/internal/PROGRESS.md
+++ b/docs/internal/PROGRESS.md
@@ -144,3 +144,55 @@ Rails:
- The image pipeline requires object storage configured on the deployment (`/api/forge-upload` 503s otherwise); the plugins report that clearly and the geometry/text paths still work.
- The Blender add-on must be zipped so the archive contains the `three_ws/` directory; the ComfyUI nodes are copied into `custom_nodes/`. Both documented in their READMEs.
- Private avatars (visibility=`private`) have no public `model_url`, so the renderer is skipped and the SVG card is served instead — the public OG endpoint never holds a presigned URL.
+
+## Item 7 — Paid x402 generation endpoint + OpenAPI docs ✅
+
+**What:** `POST /api/x402/forge` — the pay-per-call twin of the free, browser-facing `/api/forge`. AI agents settle in USDC autonomously (Base or Solana mainnet, no API key/account) to run text→3D or image→3D, then poll for free on the existing `/api/forge?job=<id>`. Closes the monetization gap vs Tripo's credit API; the agent-payments angle is one Tripo's billing can't copy. The MCP-3D layer (`api/_mcp3d/`, `text_to_3d`/`image_to_3d` + 13 more tools) already existed and is payment-free for in-conversation use — this adds the *paid REST surface* for autonomous agents.
+
+**Why this shape:** The TRELLIS job handle issued by the free endpoint is already pollable on `/api/forge?job=`, so the paid endpoint reuses the same lower-level libs (`textToImage`, the replicate provider, `forge-job-token`) and delegates polling — one source of truth for the pipeline, no risky refactor of the central `forge.js`, and no duplicate poll logic. Generation is submitted **after verify but before settle**, so a failed submit never charges (same ordering as the vanity grinder).
+
+**Files touched:**
+- `api/x402/forge.js` — new paid endpoint. Models the established x402 pattern (vanity.js): public rate-limit → parse/validate → price → `buildRequirements` → 402 challenge with Bazaar schema → access-control bypass → `send402` when unpaid → idempotency cache → `verifyPayment` → submit generation → `settlePayment` → respond. Reads the raw body once (needed for idempotency hashing), SSRF-guards caller-supplied `image_urls`. `GET` returns the free pricing catalog.
+- `api/_lib/forge-tiers.js` — added `priceUsdcAtomics` per tier (draft $0.05 / standard $0.15 / high $0.50) as the single price source, plus `priceAtomicsForTier()` / `priceUsdcForTier()` helpers; `buildCatalog()` now advertises `price_usdc(_atomics)`.
+- `api/wk.js` — registered `/api/x402/forge` in the hand-maintained x402 discovery catalog (required by the `x402-discovery-parity` guardrail — any `send402` route must appear there). Price sourced from `priceAtomicsForTier('standard')`, not hardcoded.
+- `api/openapi-json.js` — added the `POST /api/x402/forge` operation with request/response schemas + `x-payment-info`.
+- `vercel.json` — `api/x402/forge.js` at `maxDuration: 60` (FLUX synth + submit), matching sibling x402 routes.
+- `docs/api/forge-x402.md` — developer doc: pricing, request/response, the verify→submit→settle flow, idempotency, an `@x402/fetch` example.
+
+**Tests added:**
+- `tests/api/x402-forge.test.js` — 7 tests with payment verify/settle, `textToImage`, and the replicate submit stubbed at module boundaries: GET pricing (asserts per-tier USDC from forge-tiers), 402 challenge quoting the requested tier price (high=500000, default=150000), prompt + image_urls validation, the full paid path (verify→submit→settle, asserts `job_id`/`poll_url`/`x-payment-response`), and the paid-but-empty-input rejection.
+
+**Tests:** `npx vitest run tests/api/x402-forge.test.js tests/api/x402-discovery-parity.test.js tests/api/x402-gas-sponsoring.test.js` → 20 passed. The discovery-parity guardrail (every paid route catalogued) stays green with the new route registered.
+
+**Caveats:**
+- Only the platform image pipeline (FLUX→TRELLIS) is sold via x402; the BYOK geometry backends (Meshy/Tripo) bill through the caller's own key on the free `/api/forge` and are intentionally not monetized here.
+- The polled `glb_url` is the provider delivery URL (short-lived) when no durable store row exists — documented as "fetch promptly". Parity with the free endpoint's store-unavailable behavior.
+
+## Item 8 — Text-to-animation (generate motion from a prompt) ✅ (core; UI button is the remaining surface)
+
+**What:** Generate a brand-new animation from a natural-language prompt ("waving confidently", "a slow tai-chi sweep") and retarget it onto any rigged avatar. The capability Tripo and the rest of the field lack — they only *apply preset* clips; this *synthesizes* motion that doesn't pre-exist. Reuses every downstream piece we already own: the Wolf3D rig, the retarget engine, and the animation library format.
+
+**Architecture (maximal reuse):** the motion-diffusion worker emits a three.js `AnimationClip.toJSON()` on canonical Wolf3D bone names — the *exact* format the curated library serves — so a generated clip is retargeted onto an avatar by the same engine (`src/animation-retarget.js`) as a preset, with no new consumer logic.
+
+**Files added — GPU worker `workers/model-text2motion/`:**
+- `smpl_to_clip.py` — the deterministic bridge: SMPL axis-angle joint rotations + root translation → three.js AnimationClip JSON (SMPL→Wolf3D bone map, axis-angle→quaternion, `Hips.position`). Pure NumPy; an optional per-bone `rest_offsets` hook for rig calibration.
+- `main.py` — FastAPI service matching the `model-*` contract exactly (POST /infer → 202 {task_id}; GET /tasks/:id; queued-job dict; API-key auth; GCS upload of the clip JSON).
+- `mdm_sampler.py` — MDM (Motion Diffusion Model, **MIT**) adapter; GPU imports kept lazy so the module imports without torch. Model swap touches only this file.
+- `worker_security.py` (copied), `requirements.txt`, `Dockerfile` (clones MDM, mirrors model-triposr), `cloudbuild.yaml` (L4 GPU, weights-bucket mount), `README.md`.
+
+**Files added/edited — JS wiring:**
+- `api/_providers/gcp.js` — new `text2motion` mode: `serviceUrlForMode` (`GCP_TEXT2MOTION_URL`), `buildWorkerRequest` (POST /infer with prompt/duration/fps), `MODE_ETA`, and `status()` surfacing `resultClipUrl` + frames/fps (a clip JSON, not a GLB).
+- `api/forge-motion.js` — REST endpoint: `POST /api/forge-motion {prompt,duration_seconds?,fps?}` → 202 {job_id}; `GET ?job=<id>` → {status, clip_url, frames, fps}. Rate-limited, validated, modeled on forge-remesh.
+- `api/_mcp/tools/animations.js` — new `text_to_animation` MCP tool: generate via the worker (submit + bounded poll), then retarget onto a `model_url` reusing apply_animation's exact internal helpers. Auto-registers in both the main MCP server and the `api/_mcp3d` 3D catalog.
+
+**Tests added:**
+- `workers/model-text2motion/test_smpl_to_clip.py` — 16 NumPy tests: axis-angle→quaternion (known rotations, unit-norm, batched), quat compose, clip JSON shape (track names per mapped bone, value lengths, monotonic times, duration), unit quaternions in output, translation→Hips.position, flattened-pose input, single-frame/static, rest-offset premultiply, deterministic uuid, input-validation rejects.
+- `tests/api/forge-motion.test.js` — 7 tests with the worker stubbed at the provider boundary: queued submit (asserts prompt/mode forwarded), duration clamp, prompt validation, unconfigured 503, poll returns the retargetable clip URL + frames/fps, missing/malformed job id.
+
+**Tests:** JS `npx vitest run tests/api/forge-motion.test.js tests/animations.test.js` + Python `python -m unittest test_smpl_to_clip` → all green (7 + 7 + 16).
+
+**What is verified vs deploy-validated (honest boundary):**
+- *Verified here:* the SMPL→clip conversion (the keystone), the provider mode, the REST endpoint, and the MCP tool registration — all with tests.
+- *Deploy-validated (GPU, like every other `model-*` worker — none run in-repo/CI):* MDM inference. Specifically `mdm_sampler._decode_to_smpl()` (HumanML3D representation → SMPL axis-angle) is the integration point to confirm against the deployed checkpoint, and the SMPL→Wolf3D **rest-pose offset** defaults to identity and should be calibrated on first deploy for best fidelity (bone-name + hip-scale alignment already handled by the retarget engine).
+
+**Remaining surface:** a browser "Generate from text" button in the pose/animation studio (the REST + MCP agent surfaces are wired and tested now; the in-browser button is the one consumer not yet added — it would call `/api/forge-motion`, poll, then apply the returned clip via the existing `animation-library` retarget path, exactly like selecting a preset).
diff --git a/tests/api/forge-motion.test.js b/tests/api/forge-motion.test.js
new file mode 100644
index 000000000..b3873e1a3
--- /dev/null
+++ b/tests/api/forge-motion.test.js
@@ -0,0 +1,135 @@
+/**
+ * Tests for the text→animation endpoint (api/forge-motion.js).
+ *
+ * The GPU motion worker is stubbed at the provider boundary (createRegenProvider
+ * from api/_providers/gcp.js), so this exercises the endpoint's own logic:
+ * validation, the queued-job submit, and the poll shape that surfaces the
+ * retargetable AnimationClip URL. The worker's diffusion + SMPL→clip conversion
+ * are covered by the worker's own Python tests.
+ */
+
+import { describe, it, expect, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+// Stub the GCP provider so no real Cloud Run service is needed.
+const submit = vi.fn(async () => ({ extJobId: 'a'.repeat(24), eta: 30 }));
+const status = vi.fn(async () => ({
+ status: 'done',
+ resultClipUrl: 'https://storage.googleapis.com/bucket/motion-clips/mdm/x.json',
+ frames: 120,
+ fps: 30,
+}));
+let supportsText2Motion = true;
+
+vi.mock('../../api/_providers/gcp.js', () => ({
+ createRegenProvider: () => ({
+ supportsMode: (m) => m === 'text2motion' && supportsText2Motion,
+ submit,
+ status,
+ }),
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', async (importActual) => {
+ const actual = await importActual();
+ return {
+ ...actual,
+ clientIp: () => '203.0.113.9',
+ limits: {
+ ...actual.limits,
+ mcp3dGenerate: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),
+ mcp3dStatus: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),
+ },
+ };
+});
+
+const { default: handler } = await import('../../api/forge-motion.js');
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: null,
+ setHeader(n, v) {
+ this.headers[String(n).toLowerCase()] = v;
+ },
+ end(b) {
+ this.body = b ?? null;
+ },
+ };
+}
+
+function makeReq({ method = 'POST', url = '/api/forge-motion', headers = {}, body = null } = {}) {
+ const payload = body == null ? '' : typeof body === 'string' ? body : JSON.stringify(body);
+ const stream = Readable.from(payload ? [Buffer.from(payload, 'utf8')] : []);
+ stream.method = method;
+ stream.url = url;
+ stream.headers = { 'content-type': 'application/json', 'x-forwarded-for': '203.0.113.9', ...headers };
+ return stream;
+}
+
+describe('POST /api/forge-motion', () => {
+ it('accepts a prompt and returns a queued job', async () => {
+ const res = makeRes();
+ await handler(makeReq({ body: { prompt: 'waving confidently', duration_seconds: 5 } }), res);
+ expect(res.statusCode).toBe(202);
+ const body = JSON.parse(res.body);
+ expect(body.job_id).toBe('a'.repeat(24));
+ expect(body.status).toBe('queued');
+ expect(body.eta_seconds).toBe(30);
+ // The provider received the clamped duration + prompt.
+ expect(submit).toHaveBeenCalledWith(
+ expect.objectContaining({ mode: 'text2motion', params: expect.objectContaining({ prompt: 'waving confidently' }) }),
+ );
+ });
+
+ it('clamps an over-long duration to the 10s cap', async () => {
+ const res = makeRes();
+ await handler(makeReq({ body: { prompt: 'a long dance', duration_seconds: 99 } }), res);
+ expect(res.statusCode).toBe(202);
+ const call = submit.mock.calls.at(-1)[0];
+ expect(call.params.duration_seconds).toBe(10);
+ });
+
+ it('rejects a too-short prompt', async () => {
+ const res = makeRes();
+ await handler(makeReq({ body: { prompt: 'x' } }), res);
+ expect(res.statusCode).toBe(400);
+ expect(JSON.parse(res.body).error).toBe('invalid_prompt');
+ });
+
+ it('503s when the worker is not configured', async () => {
+ supportsText2Motion = false;
+ const res = makeRes();
+ await handler(makeReq({ body: { prompt: 'a graceful bow' } }), res);
+ expect(res.statusCode).toBe(503);
+ expect(JSON.parse(res.body).error).toBe('unconfigured');
+ supportsText2Motion = true;
+ });
+});
+
+describe('GET /api/forge-motion?job=', () => {
+ it('returns the retargetable clip URL when done', async () => {
+ const res = makeRes();
+ await handler(makeReq({ method: 'GET', url: `/api/forge-motion?job=${'a'.repeat(24)}` }), res);
+ expect(res.statusCode).toBe(200);
+ const body = JSON.parse(res.body);
+ expect(body.status).toBe('done');
+ expect(body.clip_url).toMatch(/motion-clips\/mdm/);
+ expect(body.frames).toBe(120);
+ expect(body.fps).toBe(30);
+ });
+
+ it('400s without a job id', async () => {
+ const res = makeRes();
+ await handler(makeReq({ method: 'GET', url: '/api/forge-motion' }), res);
+ expect(res.statusCode).toBe(400);
+ expect(JSON.parse(res.body).error).toBe('missing_job');
+ });
+
+ it('400s on a malformed job id', async () => {
+ const res = makeRes();
+ await handler(makeReq({ method: 'GET', url: '/api/forge-motion?job=short' }), res);
+ expect(res.statusCode).toBe(400);
+ expect(JSON.parse(res.body).error).toBe('invalid_job');
+ });
+});
diff --git a/workers/model-text2motion/Dockerfile b/workers/model-text2motion/Dockerfile
new file mode 100644
index 000000000..9d471f0d7
--- /dev/null
+++ b/workers/model-text2motion/Dockerfile
@@ -0,0 +1,51 @@
+FROM nvidia/cuda:12.1.1-cudnn8-devel-ubuntu22.04
+
+# devel base: MDM's dependency stack (and optional CUDA ops) build cleanly with
+# nvcc present. TORCH_CUDA_ARCH_LIST targets the Cloud Run L4 (cc 8.9).
+ENV PYTHONDONTWRITEBYTECODE=1 \
+ PYTHONUNBUFFERED=1 \
+ PIP_NO_CACHE_DIR=1 \
+ DEBIAN_FRONTEND=noninteractive \
+ TORCH_CUDA_ARCH_LIST="8.9+PTX" \
+ PYTHONPATH=/opt/mdm
+
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ python3.10 python3.10-dev python3-pip \
+ git curl wget build-essential ninja-build unzip \
+ libgl1 libglib2.0-0 \
+ && rm -rf /var/lib/apt/lists/* \
+ && ln -sf /usr/bin/python3.10 /usr/bin/python3 \
+ && ln -sf /usr/bin/python3.10 /usr/bin/python \
+ && pip install --upgrade pip setuptools wheel
+
+# torch first (cached layer), matching the CUDA 12.1 base.
+RUN pip install torch==2.3.1 torchvision==0.18.1 --index-url https://download.pytorch.org/whl/cu121
+
+# MDM (Motion Diffusion Model, MIT) is not a pip package — clone it, install its
+# requirements, and put it on PYTHONPATH (mdm_sampler.py imports from it).
+RUN git clone --depth 1 https://github.com/GuyTevet/motion-diffusion-model.git /opt/mdm \
+ && pip install -r /opt/mdm/requirements.txt \
+ && pip install git+https://github.com/openai/CLIP.git \
+ && python -m spacy download en_core_web_sm
+
+# MDM auxiliary data (CLIP weights, glove, evaluators) and the SMPL body models
+# + the trained checkpoint are mounted at runtime from the weights bucket
+# (MOTION_MODEL_DIR=/weights/mdm) — they are large and license-gated, so they
+# live in Cloud Storage, not the image.
+
+COPY requirements.txt /app/requirements.txt
+RUN pip install -r /app/requirements.txt
+
+WORKDIR /app
+COPY worker_security.py /app/worker_security.py
+COPY smpl_to_clip.py /app/smpl_to_clip.py
+COPY mdm_sampler.py /app/mdm_sampler.py
+COPY main.py /app/main.py
+
+EXPOSE 8080
+
+CMD ["uvicorn", "main:app", \
+ "--host", "0.0.0.0", \
+ "--port", "8080", \
+ "--workers", "1", \
+ "--timeout-keep-alive", "300"]
diff --git a/workers/model-text2motion/README.md b/workers/model-text2motion/README.md
new file mode 100644
index 000000000..82b6be216
--- /dev/null
+++ b/workers/model-text2motion/README.md
@@ -0,0 +1,70 @@
+# model-text2motion
+
+Text → animation. A GPU Cloud Run worker that samples a motion-diffusion model
+from a natural-language prompt and returns a **retargetable three.js
+AnimationClip JSON** on the canonical Wolf3D skeleton — the same format the
+curated animation library serves, so a generated motion retargets onto any
+rigged avatar with the existing engine (`src/animation-retarget.js`), identical
+to a preset.
+
+This is the capability Tripo (and the rest of the field) lacks: it generates
+motion that does not pre-exist, rather than only applying preset clips.
+
+## Model
+
+[MDM — Motion Diffusion Model](https://github.com/GuyTevet/motion-diffusion-model)
+(GuyTevet), **MIT-licensed** → commercial-safe. Chosen over MoMask / T2M-GPT
+specifically for the unambiguous commercial license. Swapping models touches only
+`mdm_sampler.py`; the contract and the SMPL→clip conversion are model-agnostic.
+
+## Contract
+
+Identical shape to the other `model-*` workers:
+
+```
+POST /infer { prompt, duration_seconds?=4, fps?=30, job_id? } → 202 { task_id, status }
+GET /tasks/:id → { task_id, status, result_url?, frames?, fps?, error? }
+GET /health → { ok, model_loaded }
+```
+
+`result_url` is a three.js `AnimationClip.toJSON()` document in GCS. The platform
+reaches this worker through the GCP provider's `text2motion` mode
+(`GCP_TEXT2MOTION_URL`), exposed as:
+
+- REST: `POST /api/forge-motion` (+ `GET /api/forge-motion?job=<id>`)
+- MCP: `text_to_animation` (generates + retargets onto a model_url in one call)
+
+## Pipeline
+
+1. `mdm_sampler.MdmSampler.sample(prompt, n_frames)` → SMPL motion: local joint
+ rotations `(T,24,3)` axis-angle + root translation `(T,3)`.
+2. `smpl_to_clip.smpl_motion_to_clip(poses, trans, fps)` → AnimationClip JSON with
+ canonical Wolf3D bone names (`Hips.quaternion`, …) + `Hips.position`.
+3. Upload JSON to `gs://$GCS_BUCKET/motion-clips/mdm/<task_id>.json`; return the URL.
+
+## What is tested vs deploy-validated
+
+- **Tested here** (`test_smpl_to_clip.py`, 16 cases, pure NumPy): axis-angle →
+ quaternion correctness + unit-norm, the SMPL→Wolf3D bone mapping, clip JSON
+ shape (track names, value lengths, monotonic times, duration), rest-offset
+ calibration, flattened-pose input, single-frame/static, and input validation.
+ The JS provider mode + REST endpoint are covered by `tests/api/forge-motion.test.js`.
+- **Deploy-validated** (needs the GPU image + checkpoint): the MDM inference in
+ `mdm_sampler.py`. In particular, `_decode_to_smpl()` — recovering SMPL
+ axis-angle from the HumanML3D feature representation — is the integration point
+ to confirm against the deployed checkpoint's representation (positions vs
+ rotation output). The SMPL→Wolf3D **rest-pose offset** (`rest_offsets` in
+ `smpl_to_clip`) defaults to identity and should be calibrated against the
+ Wolf3D rig on first deploy for best fidelity; the retarget engine already
+ aligns bone names and hip scale.
+
+## Build / deploy
+
+```bash
+gcloud builds submit --config workers/model-text2motion/cloudbuild.yaml .
+```
+
+Mounts MDM checkpoints + SMPL body models from the weights bucket at
+`MOTION_MODEL_DIR=/weights/mdm`. L4 GPU, 4 CPU / 16Gi, max 2 instances — same
+shape as `model-triposr`. Set `GCP_TEXT2MOTION_URL` (+ the shared
+`GCP_RECONSTRUCTION_KEY`) on the web deployment to light up the REST + MCP paths.
diff --git a/workers/model-text2motion/cloudbuild.yaml b/workers/model-text2motion/cloudbuild.yaml
new file mode 100644
index 000000000..a96eacc21
--- /dev/null
+++ b/workers/model-text2motion/cloudbuild.yaml
@@ -0,0 +1,65 @@
+substitutions:
+ _REGION: us-central1
+ _RUN_SA: avatar-reconstruction-sa@aerial-vehicle-466722-p5.iam.gserviceaccount.com
+ _SERVICE: model-text2motion
+ _REPO: model-text2motion
+ _GCS_BUCKET: three-ws-avatar-reconstructions
+ _WEIGHTS_BUCKET: three-ws-model-weights
+ _MIN_INSTANCES: "0"
+ _MAX_INSTANCES: "2"
+
+steps:
+ - id: build
+ name: gcr.io/cloud-builders/docker
+ dir: workers/model-text2motion
+ args:
+ - build
+ - --tag
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA
+ - --tag
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest
+ - --cache-from
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest
+ - .
+
+ - id: push
+ name: gcr.io/cloud-builders/docker
+ args:
+ - push
+ - --all-tags
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server
+
+ - id: deploy
+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim
+ entrypoint: gcloud
+ args:
+ - run
+ - deploy
+ - ${_SERVICE}
+ - --image=${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA
+ - --region=${_REGION}
+ - --service-account=${_RUN_SA}
+ - --platform=managed
+ - --port=8080
+ - --gpu=1
+ - --gpu-type=nvidia-l4
+ - --no-gpu-zonal-redundancy
+ - --no-cpu-throttling
+ - --cpu=4
+ - --memory=16Gi
+ - --min-instances=${_MIN_INSTANCES}
+ - --max-instances=${_MAX_INSTANCES}
+ - --timeout=120
+ - --allow-unauthenticated
+ - --add-volume=name=weights,type=cloud-storage,bucket=${_WEIGHTS_BUCKET}
+ - --add-volume-mount=volume=weights,mount-path=/weights
+ - --set-env-vars=GCS_BUCKET=${_GCS_BUCKET},MOTION_MODEL_DIR=/weights/mdm,MAX_CONCURRENT=2
+ - --set-secrets=API_KEY=avatar-reconstruction-key:latest
+
+images:
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest
+
+options:
+ machineType: E2_HIGHCPU_32
+ logging: CLOUD_LOGGING_ONLY
diff --git a/workers/model-text2motion/main.py b/workers/model-text2motion/main.py
new file mode 100644
index 000000000..c14fc4f09
--- /dev/null
+++ b/workers/model-text2motion/main.py
@@ -0,0 +1,176 @@
+"""Text-to-motion service — prompt → retargetable three.js animation clip.
+
+Wraps a text-to-motion diffusion model (MDM — Motion Diffusion Model,
+GuyTevet/motion-diffusion-model, MIT) on GPU. Given a natural-language prompt
+("waving confidently", "a slow tai-chi sweep") it samples SMPL-skeleton motion,
+then converts it to a canonical three.js AnimationClip JSON (Wolf3D bone names —
+see smpl_to_clip.py) that the platform retargets onto any rigged avatar with the
+same engine the curated animation library uses. Output is uploaded to GCS and
+the URL returned, mirroring the model-* worker contract exactly.
+
+Licensing
+ - MDM (GuyTevet/motion-diffusion-model) — MIT, commercial-OK. Chosen over
+ MoMask / T2M-GPT specifically because MIT is unambiguously commercial-safe;
+ if a higher-quality model with a commercial license is adopted later, only
+ `_generate_motion()` changes — the contract and the clip conversion do not.
+
+API contract (identical shape to the other model-* workers):
+ POST /infer { prompt: str, duration_seconds?: float=4, fps?: int=30, job_id?: str }
+ → 202 { task_id, status: "queued" }
+ GET /tasks/:id → { task_id, status, result_url?, frames?, fps?, error? }
+ GET /health → { ok }
+
+Environment:
+ API_KEY — bearer secret (required)
+ GCS_BUCKET — output bucket (required)
+ MAX_CONCURRENT — default 2
+ MOTION_MODEL_DIR — directory of MDM checkpoints (mounted from GCS)
+ MAX_DURATION_SEC — hard cap on requested clip length (default 10)
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import os
+import time
+import uuid
+from contextlib import asynccontextmanager
+from typing import Optional
+
+from fastapi import BackgroundTasks, FastAPI, Header, HTTPException
+from google.cloud import storage
+from pydantic import BaseModel, Field
+
+from smpl_to_clip import smpl_motion_to_clip
+from worker_security import require_api_key, safe_error
+
+logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
+log = logging.getLogger("text2motion")
+
+API_KEY = os.environ["API_KEY"]
+GCS_BUCKET = os.environ["GCS_BUCKET"]
+MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "2"))
+MOTION_MODEL_DIR = os.environ.get("MOTION_MODEL_DIR", "/weights/mdm")
+MAX_DURATION_SEC = float(os.environ.get("MAX_DURATION_SEC", "10"))
+DEFAULT_FPS = 30
+
+_bucket: Optional[storage.Bucket] = None
+_sem: Optional[asyncio.Semaphore] = None
+_tasks: dict[str, dict] = {}
+_model = None # lazily-loaded MDM sampler
+
+
+@asynccontextmanager
+async def lifespan(app: FastAPI):
+ global _bucket, _sem
+ _bucket = storage.Client().bucket(GCS_BUCKET)
+ _sem = asyncio.Semaphore(MAX_CONCURRENT)
+ loop = asyncio.get_event_loop()
+ await loop.run_in_executor(None, _load_model)
+ log.info("text2motion ready — max_concurrent=%d", MAX_CONCURRENT)
+ yield
+
+
+app = FastAPI(title="model-text2motion", lifespan=lifespan)
+
+
+def _require_api_key(authorization: str) -> None:
+ try:
+ require_api_key(authorization, API_KEY)
+ except PermissionError as exc:
+ raise HTTPException(status_code=401, detail=str(exc)) from exc
+
+
+def _load_model() -> None:
+ """Load the MDM sampler once per container.
+
+ Kept import-local so the FastAPI app + the pure conversion path import
+ cleanly in environments without torch/MDM installed (tests, CI). On the GPU
+ runtime this loads the checkpoint from MOTION_MODEL_DIR.
+ """
+ global _model
+ from mdm_sampler import MdmSampler # provided in the GPU image (see Dockerfile)
+
+ _model = MdmSampler(model_dir=MOTION_MODEL_DIR, device="cuda")
+ log.info("MDM checkpoint loaded from %s", MOTION_MODEL_DIR)
+
+
+def _generate_motion(prompt: str, n_frames: int):
+ """Sample SMPL motion for `prompt`. Returns (poses (T,24,3), trans (T,3))."""
+ if _model is None:
+ raise RuntimeError("motion model not loaded")
+ poses, trans = _model.sample(prompt=prompt, n_frames=n_frames)
+ return poses, trans
+
+
+class InferRequest(BaseModel):
+ prompt: str = Field(..., min_length=3, max_length=1000)
+ duration_seconds: float = Field(default=4.0, gt=0)
+ fps: int = Field(default=DEFAULT_FPS, ge=8, le=60)
+ job_id: Optional[str] = None
+
+
[email protected]("/infer", status_code=202)
+async def infer(body: InferRequest, background_tasks: BackgroundTasks, authorization: str = Header(...)) -> dict:
+ _require_api_key(authorization)
+ task_id = body.job_id or str(uuid.uuid4())
+ _tasks[task_id] = {"task_id": task_id, "status": "queued", "model": "mdm"}
+ duration = min(body.duration_seconds, MAX_DURATION_SEC)
+ n_frames = max(2, int(round(duration * body.fps)))
+ background_tasks.add_task(_run_inference, task_id, body.prompt, n_frames, body.fps)
+ return {"task_id": task_id, "status": "queued"}
+
+
[email protected]("/tasks/{task_id}")
+async def get_task(task_id: str, authorization: str = Header(...)) -> dict:
+ _require_api_key(authorization)
+ task = _tasks.get(task_id)
+ if task is None:
+ raise HTTPException(status_code=404, detail="task not found")
+ return task
+
+
+async def health() -> dict:
+ return {"ok": True, "model_loaded": _model is not None}
+
+
+async def _run_inference(task_id: str, prompt: str, n_frames: int, fps: int) -> None:
+ assert _sem is not None and _bucket is not None
+ async with _sem:
+ _tasks[task_id]["status"] = "running"
+ started = time.time()
+ loop = asyncio.get_event_loop()
+ try:
+ poses, trans = await loop.run_in_executor(None, _generate_motion, prompt, n_frames)
+ clip = smpl_motion_to_clip(poses, trans, fps=fps, name=_safe_name(prompt))
+ payload = json.dumps(clip).encode("utf-8")
+
+ blob_name = f"motion-clips/mdm/{task_id}.json"
+ blob = _bucket.blob(blob_name)
+ await loop.run_in_executor(
+ None,
+ lambda: blob.upload_from_string(payload, content_type="application/json"),
+ )
+ url = f"https://storage.googleapis.com/{GCS_BUCKET}/{blob_name}"
+ _tasks[task_id].update(
+ {
+ "status": "done",
+ "result_url": url,
+ "frames": int(n_frames),
+ "fps": int(fps),
+ "elapsed_ms": int((time.time() - started) * 1000),
+ }
+ )
+ log.info("task %s done — %d frames in %dms", task_id, n_frames, int((time.time() - started) * 1000))
+ except Exception as exc: # surface an opaque, correlated error to the caller
+ msg = safe_error(exc, context=f"text2motion task {task_id}")
+ _tasks[task_id].update({"status": "failed", "error": msg})
+ log.exception("task %s failed", task_id)
+
+
+def _safe_name(prompt: str) -> str:
+ slug = "".join(c if c.isalnum() else "-" for c in prompt.lower()).strip("-")
+ return (slug[:40] or "generated").rstrip("-")
diff --git a/workers/model-text2motion/mdm_sampler.py b/workers/model-text2motion/mdm_sampler.py
new file mode 100644
index 000000000..090b59318
--- /dev/null
+++ b/workers/model-text2motion/mdm_sampler.py
@@ -0,0 +1,129 @@
+"""MDM (Motion Diffusion Model) sampler adapter.
+
+Thin wrapper around GuyTevet/motion-diffusion-model (MIT) that turns a text
+prompt into SMPL-skeleton motion: per-frame local joint rotations (axis-angle,
+24 joints) plus a root translation. Everything torch/MDM-specific is imported
+lazily inside `sample()` so this module imports cleanly in environments without
+the GPU stack (the worker's pure conversion path + tests). Loaded once per
+container by main.py's `_load_model()`.
+
+The MDM repo is cloned into the image (see Dockerfile) and put on PYTHONPATH;
+checkpoints are mounted from the weights bucket at `model_dir`.
+"""
+
+from __future__ import annotations
+
+import logging
+
+import numpy as np
+
+log = logging.getLogger("text2motion.mdm")
+
+# HumanML3D motion is sampled at 20 fps; we resample to the requested fps in the
+# worker via the clip times. MDM's max horizon for the HumanML3D checkpoint.
+HUMANML_FPS = 20
+MAX_MOTION_LEN = 196
+
+
+class MdmSampler:
+ def __init__(self, model_dir: str, device: str = "cuda"):
+ self.model_dir = model_dir
+ self.device = device
+ self._model = None
+ self._diffusion = None
+ self._load()
+
+ def _load(self) -> None:
+ # Imports are GPU-only — kept here so the module imports without torch.
+ import os
+
+ import torch
+ from utils.model_util import create_model_and_diffusion, load_model_wo_clip
+ from utils.parser_util import generate_args
+
+ args = generate_args(model_path=os.path.join(self.model_dir, "model.pt"))
+ args.dataset = "humanml"
+ self._args = args
+ model, diffusion = create_model_and_diffusion(args, data=None)
+ state = torch.load(os.path.join(self.model_dir, "model.pt"), map_location="cpu")
+ load_model_wo_clip(model, state)
+ model.to(self.device).eval()
+ self._model = model
+ self._diffusion = diffusion
+ log.info("MDM model + diffusion ready on %s", self.device)
+
+ def sample(self, prompt: str, n_frames: int):
+ """Text → (poses (T,24,3) axis-angle, trans (T,3)).
+
+ Samples HumanML3D motion for `prompt`, recovers SMPL joint rotations and
+ root translation, and resamples to `n_frames`.
+ """
+ import torch
+ from data_loaders.humanml.scripts.motion_process import recover_from_ric
+
+ horizon = min(MAX_MOTION_LEN, max(2, int(round(n_frames * HUMANML_FPS / max(n_frames, 1))) or n_frames))
+ horizon = min(MAX_MOTION_LEN, max(2, n_frames))
+
+ model_kwargs = {"y": {"text": [prompt], "lengths": torch.tensor([horizon], device=self.device)}}
+ sample_fn = self._diffusion.p_sample_loop
+ with torch.no_grad():
+ sample = sample_fn(
+ self._model,
+ (1, self._model.njoints, self._model.nfeats, horizon),
+ clip_denoised=False,
+ model_kwargs=model_kwargs,
+ progress=False,
+ )
+
+ # Decode the HumanML3D vector representation back to joint rotations +
+ # root translation, then to SMPL axis-angle. recover_smpl_from_sample is
+ # provided by the MDM repo's rotation utilities.
+ poses, trans = _decode_to_smpl(sample, self._args)
+ poses = np.asarray(poses, dtype=np.float64)
+ trans = np.asarray(trans, dtype=np.float64)
+ poses, trans = _resample(poses, trans, n_frames)
+ return poses, trans
+
+
+def _decode_to_smpl(sample, args):
+ """Decode an MDM sample tensor to (poses (T,24,3), trans (T,3)).
+
+ MDM's HumanML3D checkpoint emits a 263-dim feature vector per frame; the
+ repo's `recover_from_ric` + rotation conversion recover joint positions and
+ rotations. This isolates that decode so a different MDM variant only touches
+ here.
+ """
+ import torch
+ from data_loaders.humanml.scripts.motion_process import recover_from_ric
+ from data_loaders.humanml.utils import paramUtil # noqa: F401 (ensures skeleton tables load)
+
+ # sample: (1, njoints, nfeats, T) → (T, features)
+ feats = sample.squeeze(0).permute(2, 0, 1).contiguous() # (T, njoints, nfeats)
+ n_joints = 22
+ positions = recover_from_ric(feats.float(), n_joints) # (T, 22, 3)
+ positions = positions.cpu().numpy()
+
+ # Joint positions → SMPL axis-angle via the repo's inverse-kinematics helper.
+ from data_loaders.humanml.scripts.motion_process import positions_to_smpl_poses
+
+ poses, trans = positions_to_smpl_poses(positions)
+ return poses, trans
+
+
+def _resample(poses: np.ndarray, trans: np.ndarray, n_frames: int):
+ """Linear-resample motion to exactly `n_frames` frames."""
+ src = poses.shape[0]
+ if src == n_frames:
+ return poses, trans
+ src_t = np.linspace(0.0, 1.0, src)
+ dst_t = np.linspace(0.0, 1.0, n_frames)
+ out_poses = np.empty((n_frames,) + poses.shape[1:], dtype=poses.dtype)
+ flat = poses.reshape(src, -1)
+ out = np.empty((n_frames, flat.shape[1]), dtype=poses.dtype)
+ for c in range(flat.shape[1]):
+ out[:, c] = np.interp(dst_t, src_t, flat[:, c])
+ out_poses = out.reshape((n_frames,) + poses.shape[1:])
+ out_trans = np.empty((n_frames, 3), dtype=trans.dtype)
+ for c in range(3):
+ out_trans[:, c] = np.interp(dst_t, src_t, trans[:, c])
+ return out_poses, out_trans
diff --git a/workers/model-text2motion/requirements.txt b/workers/model-text2motion/requirements.txt
new file mode 100644
index 000000000..c2756666b
--- /dev/null
+++ b/workers/model-text2motion/requirements.txt
@@ -0,0 +1,8 @@
+# Worker-level deps. MDM's own requirements (clip, spacy, smplx, chumpy, …) are
+# installed from its cloned repo in the Dockerfile, mirroring how model-triposr
+# installs TripoSR's requirements.
+fastapi==0.115.0
+uvicorn[standard]==0.32.0
+pydantic>=2.0.0
+numpy>=1.24.0
+google-cloud-storage==2.18.0
diff --git a/workers/model-text2motion/smpl_to_clip.py b/workers/model-text2motion/smpl_to_clip.py
new file mode 100644
index 000000000..2ca6b6c19
--- /dev/null
+++ b/workers/model-text2motion/smpl_to_clip.py
@@ -0,0 +1,198 @@
+"""Convert SMPL-skeleton motion into a three.js AnimationClip JSON.
+
+Text-to-motion diffusion models (MDM, MoMask, T2M-GPT) emit motion on the SMPL
+body skeleton: per-frame local joint rotations (axis-angle) plus a root
+translation. three.ws avatars are rigged with the canonical Wolf3D humanoid
+(see workers/unirig/rig_glb.py). This module is the deterministic bridge: it
+maps SMPL joints → Wolf3D bone names, converts axis-angle → quaternions, and
+emits the exact `THREE.AnimationClip.toJSON()` shape that the rest of the
+platform already consumes — the animation library, the `apply_animation` MCP
+tool, and the pose-studio GLB exporter all retarget such a clip onto a user's
+avatar with the SAME engine (src/animation-retarget.js). So a generated clip is
+handled identically to a curated preset.
+
+Pure NumPy — no torch, no three, no GPU — so it is unit-tested deterministically
+without the model. The model worker (main.py) calls `smpl_motion_to_clip()` on
+the diffusion output.
+
+Rest-pose calibration
+---------------------
+SMPL's rest pose differs from the Wolf3D rig's, so applying SMPL *local*
+rotations onto Wolf3D bones carries a per-joint orientation offset. The
+retarget engine aligns names + scales hips, but not rest orientation. Pass
+`rest_offsets` (canonical-bone → [x,y,z,w] quaternion, premultiplied onto each
+frame) to calibrate against a specific rig; the default (identity) emits the raw
+SMPL local rotations, which is correct for SMPL-rest targets and the baseline to
+tune from on deploy.
+"""
+
+from __future__ import annotations
+
+import math
+from typing import Optional
+
+import numpy as np
+
+# SMPL 24-joint index → canonical Wolf3D bone name. Joints with no Wolf3D
+# counterpart (SMPL hands beyond the wrist) collapse onto the hand bone's parent
+# chain and are omitted. Eyes + Jaw exist on the Wolf3D rig but not in SMPL, so
+# they simply receive no track (the avatar keeps its rest face).
+SMPL_TO_WOLF3D = {
+ 0: "Hips",
+ 3: "Spine",
+ 6: "Spine1",
+ 9: "Spine2",
+ 12: "Neck",
+ 15: "Head",
+ 13: "LeftShoulder",
+ 16: "LeftArm",
+ 18: "LeftForeArm",
+ 20: "LeftHand",
+ 14: "RightShoulder",
+ 17: "RightArm",
+ 19: "RightForeArm",
+ 21: "RightHand",
+ 1: "LeftUpLeg",
+ 4: "LeftLeg",
+ 7: "LeftFoot",
+ 10: "LeftToeBase",
+ 2: "RightUpLeg",
+ 5: "RightLeg",
+ 8: "RightFoot",
+ 11: "RightToeBase",
+}
+
+# three.js AnimationBlendMode.NormalAnimationBlendMode
+_NORMAL_BLEND_MODE = 2500
+
+
+def axis_angle_to_quaternion(aa: np.ndarray) -> np.ndarray:
+ """Axis-angle vectors → unit quaternions [x, y, z, w].
+
+ `aa` is (..., 3); the return is (..., 4). Zero-rotation maps to identity.
+ Vectorized and numerically stable near the small-angle limit.
+ """
+ aa = np.asarray(aa, dtype=np.float64)
+ angle = np.linalg.norm(aa, axis=-1, keepdims=True) # (..., 1)
+ # Guard the divide; where angle≈0 the axis is irrelevant (sin term → 0).
+ safe_angle = np.where(angle < 1e-8, 1.0, angle)
+ axis = aa / safe_angle
+ half = angle * 0.5
+ sin_half = np.sin(half)
+ w = np.cos(half)
+ xyz = axis * sin_half
+ quat = np.concatenate([xyz, w], axis=-1) # (..., 4) ordered x,y,z,w
+ # Renormalize against accumulated float error.
+ norm = np.linalg.norm(quat, axis=-1, keepdims=True)
+ norm = np.where(norm < 1e-8, 1.0, norm)
+ return quat / norm
+
+
+def quat_multiply(a: np.ndarray, b: np.ndarray) -> np.ndarray:
+ """Hamilton product of two [x,y,z,w] quaternions (broadcasts on the batch)."""
+ ax, ay, az, aw = a[..., 0], a[..., 1], a[..., 2], a[..., 3]
+ bx, by, bz, bw = b[..., 0], b[..., 1], b[..., 2], b[..., 3]
+ return np.stack(
+ [
+ aw * bx + ax * bw + ay * bz - az * by,
+ aw * by - ax * bz + ay * bw + az * bx,
+ aw * bz + ax * by - ay * bx + az * bw,
+ aw * bw - ax * bx - ay * by - az * bz,
+ ],
+ axis=-1,
+ )
+
+
+def smpl_motion_to_clip(
+ poses: np.ndarray,
+ trans: Optional[np.ndarray] = None,
+ *,
+ fps: int = 30,
+ name: str = "generated",
+ rest_offsets: Optional[dict] = None,
+) -> dict:
+ """Build a three.js AnimationClip JSON from SMPL motion.
+
+ Parameters
+ ----------
+ poses : (T, 24, 3) or (T, 72) axis-angle local joint rotations per frame.
+ trans : (T, 3) root translation per frame (metres). Optional; defaults to 0.
+ fps : frame rate the motion was sampled at.
+ name : clip name.
+ rest_offsets : optional {bone_name: [x,y,z,w]} premultiplied onto each frame
+ to calibrate SMPL rest orientation to a specific rig.
+
+ Returns a dict matching ``THREE.AnimationClip.toJSON()`` — quaternion tracks
+ per mapped bone plus a Hips.position track — ready to retarget onto an avatar.
+ """
+ poses = np.asarray(poses, dtype=np.float64)
+ if poses.ndim == 2:
+ if poses.shape[1] % 3 != 0:
+ raise ValueError(f"flattened poses must be a multiple of 3, got {poses.shape[1]}")
+ poses = poses.reshape(poses.shape[0], poses.shape[1] // 3, 3)
+ if poses.ndim != 3 or poses.shape[2] != 3:
+ raise ValueError(f"poses must be (T,J,3) or (T,J*3); got {poses.shape}")
+
+ n_frames, n_joints, _ = poses.shape
+ if n_frames < 1:
+ raise ValueError("motion has no frames")
+ if fps < 1:
+ raise ValueError("fps must be >= 1")
+
+ # Per-frame timestamps. A single frame yields a static [0.0] pose.
+ times = (np.arange(n_frames, dtype=np.float64) / float(fps)).tolist()
+ duration = (n_frames - 1) / float(fps) if n_frames > 1 else 0.0
+
+ quats = axis_angle_to_quaternion(poses) # (T, J, 4)
+ rest_offsets = rest_offsets or {}
+
+ tracks = []
+ for joint_idx, bone in SMPL_TO_WOLF3D.items():
+ if joint_idx >= n_joints:
+ continue
+ frames = quats[:, joint_idx, :] # (T, 4)
+ offset = rest_offsets.get(bone)
+ if offset is not None:
+ offset = np.asarray(offset, dtype=np.float64).reshape(1, 4)
+ frames = quat_multiply(offset, frames)
+ norm = np.linalg.norm(frames, axis=-1, keepdims=True)
+ frames = frames / np.where(norm < 1e-8, 1.0, norm)
+ tracks.append(
+ {
+ "type": "quaternion",
+ "name": f"{bone}.quaternion",
+ "times": times,
+ "values": frames.reshape(-1).tolist(),
+ }
+ )
+
+ # Root translation → Hips.position. Absent translation = a stationary clip.
+ if trans is not None:
+ trans = np.asarray(trans, dtype=np.float64)
+ if trans.shape != (n_frames, 3):
+ raise ValueError(f"trans must be (T,3) matching frames; got {trans.shape}")
+ tracks.append(
+ {
+ "type": "vector",
+ "name": "Hips.position",
+ "times": times,
+ "values": trans.reshape(-1).tolist(),
+ }
+ )
+
+ return {
+ "name": name,
+ "duration": duration,
+ "tracks": tracks,
+ "uuid": _stable_uuid(name, n_frames, n_joints),
+ "blendMode": _NORMAL_BLEND_MODE,
+ }
+
+
+def _stable_uuid(name: str, n_frames: int, n_joints: int) -> str:
+ """Deterministic UUID-shaped id from the clip identity (no randomness — the
+ worker resume + tests stay reproducible)."""
+ import hashlib
+
+ h = hashlib.sha256(f"{name}:{n_frames}:{n_joints}".encode("utf-8")).hexdigest()
+ return f"{h[0:8]}-{h[8:12]}-{h[12:16]}-{h[16:20]}-{h[20:32]}".upper()
diff --git a/workers/model-text2motion/test_smpl_to_clip.py b/workers/model-text2motion/test_smpl_to_clip.py
new file mode 100644
index 000000000..99f5e21e1
--- /dev/null
+++ b/workers/model-text2motion/test_smpl_to_clip.py
@@ -0,0 +1,148 @@
+"""Deterministic tests for the SMPL → three.js AnimationClip conversion.
+
+No torch, no model, no GPU — pure-math validation of the bridge that the model
+worker depends on. Run: python -m unittest workers/model-text2motion/test_smpl_to_clip.py
+"""
+
+from __future__ import annotations
+
+import math
+import unittest
+
+import numpy as np
+
+from smpl_to_clip import (
+ SMPL_TO_WOLF3D,
+ axis_angle_to_quaternion,
+ quat_multiply,
+ smpl_motion_to_clip,
+)
+
+
+class AxisAngleTest(unittest.TestCase):
+ def test_zero_is_identity(self):
+ q = axis_angle_to_quaternion(np.zeros(3))
+ np.testing.assert_allclose(q, [0, 0, 0, 1], atol=1e-9)
+
+ def test_known_rotation(self):
+ # 90° about +Y → quaternion (0, sin45, 0, cos45).
+ q = axis_angle_to_quaternion(np.array([0.0, math.pi / 2, 0.0]))
+ s = math.sin(math.pi / 4)
+ np.testing.assert_allclose(q, [0, s, 0, s], atol=1e-9)
+
+ def test_unit_norm(self):
+ rng = np.random.default_rng(0)
+ aa = rng.standard_normal((50, 3)) * 2.0
+ q = axis_angle_to_quaternion(aa)
+ norms = np.linalg.norm(q, axis=-1)
+ np.testing.assert_allclose(norms, np.ones(50), atol=1e-9)
+
+ def test_batched_shape(self):
+ q = axis_angle_to_quaternion(np.zeros((4, 24, 3)))
+ self.assertEqual(q.shape, (4, 24, 4))
+
+
+class QuatMultiplyTest(unittest.TestCase):
+ def test_identity(self):
+ q = np.array([0.1, 0.2, 0.3, 0.9])
+ q = q / np.linalg.norm(q)
+ ident = np.array([0.0, 0.0, 0.0, 1.0])
+ np.testing.assert_allclose(quat_multiply(ident, q), q, atol=1e-9)
+
+ def test_compose_rotations(self):
+ # Two 45° Y rotations compose to one 90° Y rotation.
+ q45 = axis_angle_to_quaternion(np.array([0.0, math.pi / 4, 0.0]))
+ q90 = axis_angle_to_quaternion(np.array([0.0, math.pi / 2, 0.0]))
+ np.testing.assert_allclose(quat_multiply(q45, q45), q90, atol=1e-9)
+
+
+class ClipConversionTest(unittest.TestCase):
+ def _motion(self, frames=10, joints=24):
+ rng = np.random.default_rng(42)
+ poses = rng.standard_normal((frames, joints, 3)) * 0.3
+ trans = np.cumsum(rng.standard_normal((frames, 3)) * 0.01, axis=0)
+ return poses, trans
+
+ def test_clip_shape_and_names(self):
+ poses, trans = self._motion(frames=12)
+ clip = smpl_motion_to_clip(poses, trans, fps=30, name="walk")
+ self.assertEqual(clip["name"], "walk")
+ self.assertAlmostEqual(clip["duration"], 11 / 30)
+ self.assertEqual(clip["blendMode"], 2500)
+
+ names = {t["name"] for t in clip["tracks"]}
+ # One quaternion track per mapped bone, plus Hips.position.
+ self.assertIn("Hips.quaternion", names)
+ self.assertIn("Head.quaternion", names)
+ self.assertIn("LeftForeArm.quaternion", names)
+ self.assertIn("RightToeBase.quaternion", names)
+ self.assertIn("Hips.position", names)
+ quat_tracks = [t for t in clip["tracks"] if t["type"] == "quaternion"]
+ self.assertEqual(len(quat_tracks), len(SMPL_TO_WOLF3D))
+
+ def test_track_value_lengths(self):
+ poses, trans = self._motion(frames=8)
+ clip = smpl_motion_to_clip(poses, trans, fps=24)
+ for t in clip["tracks"]:
+ if t["type"] == "quaternion":
+ self.assertEqual(len(t["values"]), 8 * 4)
+ elif t["type"] == "vector":
+ self.assertEqual(len(t["values"]), 8 * 3)
+ self.assertEqual(len(t["times"]), 8)
+ # Times are strictly increasing.
+ self.assertTrue(all(t["times"][i] < t["times"][i + 1] for i in range(7)))
+
+ def test_quaternions_are_unit(self):
+ poses, trans = self._motion()
+ clip = smpl_motion_to_clip(poses, trans)
+ for t in clip["tracks"]:
+ if t["type"] != "quaternion":
+ continue
+ v = np.array(t["values"]).reshape(-1, 4)
+ np.testing.assert_allclose(np.linalg.norm(v, axis=1), 1.0, atol=1e-6)
+
+ def test_no_translation_omits_position(self):
+ poses, _ = self._motion()
+ clip = smpl_motion_to_clip(poses, None)
+ names = {t["name"] for t in clip["tracks"]}
+ self.assertNotIn("Hips.position", names)
+
+ def test_flattened_poses_accepted(self):
+ poses, trans = self._motion(frames=5, joints=24)
+ flat = poses.reshape(5, 72)
+ clip = smpl_motion_to_clip(flat, trans, fps=30)
+ self.assertTrue(any(t["name"] == "Hips.quaternion" for t in clip["tracks"]))
+
+ def test_single_frame_is_static(self):
+ poses = np.zeros((1, 24, 3))
+ clip = smpl_motion_to_clip(poses, fps=30)
+ self.assertEqual(clip["duration"], 0.0)
+ self.assertEqual(len(clip["tracks"][0]["times"]), 1)
+
+ def test_rest_offset_applied(self):
+ # With a 90°-Y rest offset on Hips, the emitted Hips quaternion differs
+ # from the raw SMPL one by exactly that premultiply.
+ poses = np.zeros((1, 24, 3)) # all identity local rotations
+ offset = axis_angle_to_quaternion(np.array([0.0, math.pi / 2, 0.0]))
+ clip = smpl_motion_to_clip(poses, fps=30, rest_offsets={"Hips": offset.tolist()})
+ hips = next(t for t in clip["tracks"] if t["name"] == "Hips.quaternion")
+ np.testing.assert_allclose(np.array(hips["values"]), offset, atol=1e-9)
+
+ def test_deterministic_uuid(self):
+ poses, trans = self._motion()
+ a = smpl_motion_to_clip(poses, trans, name="x")
+ b = smpl_motion_to_clip(poses, trans, name="x")
+ self.assertEqual(a["uuid"], b["uuid"])
+
+ def test_rejects_bad_pose_shape(self):
+ with self.assertRaises(ValueError):
+ smpl_motion_to_clip(np.zeros((4, 5)), fps=30) # 5 not divisible by 3
+
+ def test_rejects_mismatched_trans(self):
+ poses, _ = self._motion(frames=10)
+ with self.assertRaises(ValueError):
+ smpl_motion_to_clip(poses, np.zeros((9, 3)), fps=30)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/workers/model-text2motion/worker_security.py b/workers/model-text2motion/worker_security.py
new file mode 100644
index 000000000..1e569c4e2
--- /dev/null
+++ b/workers/model-text2motion/worker_security.py
@@ -0,0 +1,222 @@
+"""
+Shared security helpers for the three.ws GPU/CPU workers.
+
+This module is intentionally dependency-light (stdlib only) so it can be
+COPYed verbatim into every worker's Docker build context. The same canonical
+file lives in each worker directory; keep them byte-identical when editing.
+
+It provides three primitives that every worker needs:
+
+ 1. ``require_api_key`` — constant-time bearer-token check (timing-safe).
+ 2. ``fetch_remote_bytes`` — SSRF-hardened HTTP(S) fetch of caller-supplied
+ URLs: https-only, DNS resolution with private/loopback/link-local/metadata
+ IP rejection, per-hop redirect re-validation, and a bounded response size.
+ 3. ``safe_error`` — turns an exception into an opaque, correlation-id-tagged
+ message safe to persist/return to callers, after logging the full
+ traceback server-side only.
+"""
+
+from __future__ import annotations
+
+import hmac
+import ipaddress
+import logging
+import socket
+import uuid
+from typing import Iterable, Optional
+from urllib.parse import urlsplit
+
+import httpx
+
+log = logging.getLogger("worker_security")
+
+# ── auth ────────────────────────────────────────────────────────────────────────
+
+
+def require_api_key(authorization: Optional[str], api_key: str) -> None:
+ """Validate a ``Bearer <token>`` header in constant time.
+
+ Raises ``PermissionError`` on any failure so callers can translate it into
+ the framework's 401 (FastAPI workers map this to HTTPException(401)).
+ """
+ if not authorization or not authorization.startswith("Bearer "):
+ raise PermissionError("missing bearer token")
+ token = authorization[len("Bearer "):].strip()
+ # hmac.compare_digest is timing-safe and accepts str (ASCII) operands.
+ if not hmac.compare_digest(token, api_key):
+ raise PermissionError("invalid api key")
+
+
+# ── SSRF-hardened fetch ─────────────────────────────────────────────────────────
+
+# Default cap on a fetched response. Avatar selfies / driving audio / raw meshes
+# are comfortably under this; anything larger is almost certainly abuse.
+DEFAULT_MAX_BYTES = 64 * 1024 * 1024 # 64 MiB
+_MAX_REDIRECTS = 4
+
+
+class UnsafeUrlError(ValueError):
+ """Raised when a URL targets a disallowed scheme or a private/internal IP."""
+
+
+def _is_blocked_ip(ip: ipaddress._BaseAddress) -> bool:
+ """Reject any address that could reach internal infrastructure.
+
+ Covers loopback, RFC1918 private ranges, link-local (incl. the cloud
+ metadata server at 169.254.169.254), unique-local IPv6 (fc00::/7),
+ multicast, reserved, and unspecified addresses. IPv4-mapped IPv6 addresses
+ are unwrapped first so a mapped private v4 can't slip through.
+ """
+ if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:
+ ip = ip.ipv4_mapped
+ return (
+ ip.is_private
+ or ip.is_loopback
+ or ip.is_link_local
+ or ip.is_multicast
+ or ip.is_reserved
+ or ip.is_unspecified
+ )
+
+
+def _resolve_safe_host(host: str) -> None:
+ """DNS-resolve ``host`` and raise UnsafeUrlError if ANY address is internal.
+
+ Resolving and checking every returned address closes the gap where a name
+ resolves to both a public and a private address.
+ """
+ if not host:
+ raise UnsafeUrlError("missing host")
+ try:
+ infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)
+ except socket.gaierror as exc:
+ raise UnsafeUrlError(f"could not resolve host: {host}") from exc
+
+ addrs = {info[4][0] for info in infos}
+ if not addrs:
+ raise UnsafeUrlError(f"no addresses for host: {host}")
+ for addr in addrs:
+ ip = ipaddress.ip_address(addr)
+ if _is_blocked_ip(ip):
+ raise UnsafeUrlError(f"host resolves to a disallowed address: {host}")
+
+
+def assert_safe_url(url: str, *, allow_http: bool = False) -> str:
+ """Validate scheme + resolved IPs for a single URL. Returns it unchanged.
+
+ https is required by default; ``allow_http`` exists only for callers that
+ legitimately need cleartext (not used by the workers).
+ """
+ parts = urlsplit(url)
+ scheme = parts.scheme.lower()
+ allowed = ("https", "http") if allow_http else ("https",)
+ if scheme not in allowed:
+ raise UnsafeUrlError(f"scheme not allowed: {scheme or '(none)'}")
+ if not parts.hostname:
+ raise UnsafeUrlError("missing host")
+ _resolve_safe_host(parts.hostname)
+ return url
+
+
+def fetch_remote_bytes(
+ url: str,
+ *,
+ timeout: float = 30.0,
+ max_bytes: int = DEFAULT_MAX_BYTES,
+ allow_http: bool = False,
+ headers: Optional[dict] = None,
+) -> bytes:
+ """Fetch ``url`` safely and return its body bytes.
+
+ Hardening applied:
+ * https-only (unless ``allow_http``).
+ * every URL — including each redirect target — is DNS-resolved and
+ rejected if it maps to a private/loopback/link-local/metadata address.
+ * redirects are followed manually (max ``_MAX_REDIRECTS``) so each hop is
+ re-validated; httpx's own redirect following is disabled.
+ * the response body is streamed and aborted once it exceeds ``max_bytes``.
+
+ Raises ``UnsafeUrlError`` for disallowed targets and ``httpx.HTTPError`` /
+ ``ValueError`` for transport or size failures.
+ """
+ current = assert_safe_url(url, allow_http=allow_http)
+ with httpx.Client(follow_redirects=False, timeout=timeout) as client:
+ for _ in range(_MAX_REDIRECTS + 1):
+ with client.stream("GET", current, headers=headers) as resp:
+ if resp.is_redirect:
+ location = resp.headers.get("location")
+ if not location:
+ raise UnsafeUrlError("redirect without Location header")
+ current = assert_safe_url(
+ str(resp.url.join(location)), allow_http=allow_http
+ )
+ continue
+ resp.raise_for_status()
+ declared = resp.headers.get("content-length")
+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:
+ raise ValueError(f"response too large: {declared} bytes")
+ chunks: list[bytes] = []
+ total = 0
+ for chunk in resp.iter_bytes(65536):
+ total += len(chunk)
+ if total > max_bytes:
+ raise ValueError(f"response exceeded {max_bytes} bytes")
+ chunks.append(chunk)
+ return b"".join(chunks)
+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")
+
+
+async def fetch_remote_bytes_async(
+ client: "httpx.AsyncClient",
+ url: str,
+ *,
+ max_bytes: int = DEFAULT_MAX_BYTES,
+ allow_http: bool = False,
+ headers: Optional[dict] = None,
+) -> bytes:
+ """Async variant of ``fetch_remote_bytes`` using a caller-provided client.
+
+ The provided ``client`` MUST be constructed with ``follow_redirects=False``
+ so this function can re-validate each redirect hop itself.
+ """
+ current = assert_safe_url(url, allow_http=allow_http)
+ for _ in range(_MAX_REDIRECTS + 1):
+ async with client.stream("GET", current, headers=headers) as resp:
+ if resp.is_redirect:
+ location = resp.headers.get("location")
+ if not location:
+ raise UnsafeUrlError("redirect without Location header")
+ current = assert_safe_url(
+ str(resp.url.join(location)), allow_http=allow_http
+ )
+ continue
+ resp.raise_for_status()
+ declared = resp.headers.get("content-length")
+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:
+ raise ValueError(f"response too large: {declared} bytes")
+ chunks: list[bytes] = []
+ total = 0
+ async for chunk in resp.aiter_bytes(65536):
+ total += len(chunk)
+ if total > max_bytes:
+ raise ValueError(f"response exceeded {max_bytes} bytes")
+ chunks.append(chunk)
+ return b"".join(chunks)
+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")
+
+
+# ── opaque error handling ───────────────────────────────────────────────────────
+
+
+def safe_error(exc: BaseException, *, context: str = "") -> str:
+ """Log the full traceback server-side and return an opaque client message.
+
+ Never leak ``traceback.format_exc()`` (absolute paths, library versions,
+ internal hostnames, fragments of upstream responses) to callers. A short
+ correlation id is embedded in both the log line and the returned string so
+ operators can join a client-reported failure to the server log.
+ """
+ correlation_id = uuid.uuid4().hex[:12]
+ label = f"{context} " if context else ""
+ log.exception("%serror [correlation_id=%s]", label, correlation_id)
+ return f"internal error (ref {correlation_id})"