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: wire garment forge into the platform API and harden the worker runtime
nirholas1406afb5e965
diff --git a/api/garment-forge.js b/api/garment-forge.jsnew file mode 100644index 000000000..87f7e6b78--- /dev/null+++ b/api/garment-forge.js@@ -0,0 +1,146 @@+/**+ * /api/garment-forge: text prompt → published wardrobe garment.+ *+ * POST /api/garment-forge {+ * prompt: string, // "a white oxford cotton dress shirt, long sleeves"+ * slot: string // top | bottom | footwear | outerwear | hair |+ * } // headwear | glasses | accessory+ * → 202 { job_id, status, eta_seconds }+ *+ * GET /api/garment-forge?job=<id>+ * → { job_id, status, stage, glb_url?, manifest_url?, thumb_url?,+ * coverage?, occludes?, garment_id?, error? }+ *+ * Thin authenticated proxy over the workers/garment-forge Cloud Run service+ * (see its README for the pipeline: Vertex reference image → GPU mesh fleet →+ * compose on the canonical body → model-rig → strip/validate → publish). A+ * finished job is ALREADY live in the public wardrobe catalog+ * (src/garment-catalog.js) when this endpoint reports done — the closet's next+ * catalog refresh shows it with no extra step.+ *+ * Uses the same free-lane rate limits as the other generation endpoints; the+ * worker's bearer secret never leaves the server.+ */++import { cors, json, method, readJson, wrap, rateLimited } from './_lib/http.js';+import { limits, clientIp } from './_lib/rate-limit.js';++const GARMENT_SLOTS = [+ 'top', 'bottom', 'footwear', 'outerwear', 'hair', 'headwear', 'glasses', 'accessory',+];+const JOB_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;+// The full pipeline (image → mesh on the GPU fleet → rig → publish) runs+// about 7 minutes at the high tier; surfaced so clients can pace their polls.+const ETA_SECONDS = 450;++function config() {+ const base = (process.env.GCP_GARMENT_FORGE_URL || '').replace(/\/$/, '');+ const key = process.env.GCP_RECONSTRUCTION_KEY || '';+ return base && key ? { base, key } : null;+}++function unconfigured(res) {+ return json(res, 503, {+ error: 'unconfigured',+ message:+ 'Garment generation is not configured. Set GCP_GARMENT_FORGE_URL and ' ++ 'GCP_RECONSTRUCTION_KEY to the URL and bearer secret of the deployed ' ++ 'workers/garment-forge Cloud Run service.',+ });+}++async function startJob(req, res, cfg) {+ const rl = await limits.mcp3dGenerate(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const body = await readJson(req, 4_000).catch(() => null);+ const prompt = typeof body?.prompt === 'string' ? body.prompt.trim() : '';+ const slot = typeof body?.slot === 'string' ? body.slot.trim() : '';+ if (prompt.length < 3 || prompt.length > 500) {+ return json(res, 400, {+ error: 'invalid_prompt',+ message: 'Describe the garment in 3–500 characters (e.g. "a white oxford dress shirt").',+ });+ }+ if (!GARMENT_SLOTS.includes(slot)) {+ return json(res, 400, {+ error: 'invalid_slot',+ message: `slot must be one of: ${GARMENT_SLOTS.join(', ')}.`,+ });+ }++ const upstream = await fetch(`${cfg.base}/generate`, {+ method: 'POST',+ headers: {+ authorization: `Bearer ${cfg.key}`,+ 'content-type': 'application/json',+ },+ body: JSON.stringify({ prompt, slot }),+ }).catch(() => null);+ if (!upstream || !upstream.ok) {+ return json(res, 502, {+ error: 'garment_forge_unavailable',+ message: `Garment generation could not start (worker ${upstream ? upstream.status : 'unreachable'}).`,+ });+ }+ const job = await upstream.json();+ return json(res, 202, {+ job_id: job.job_id,+ status: job.status || 'queued',+ eta_seconds: ETA_SECONDS,+ });+}++async function pollJob(req, res, cfg, 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 rateLimited(res, rl);++ const upstream = await fetch(`${cfg.base}/jobs/${jobId}`, {+ headers: { authorization: `Bearer ${cfg.key}` },+ }).catch(() => null);+ if (!upstream) {+ return json(res, 502, { error: 'garment_forge_unavailable', message: 'Worker unreachable.' });+ }+ if (upstream.status === 404) {+ return json(res, 404, { error: 'job_not_found', message: 'No such garment job.' });+ }+ if (!upstream.ok) {+ return json(res, 502, {+ error: 'garment_forge_unavailable',+ message: `Worker returned ${upstream.status}.`,+ });+ }+ const job = await upstream.json();+ // Pass through only the documented public fields — the worker record also+ // carries internal bookkeeping the client has no use for.+ return json(res, 200, {+ job_id: job.job_id,+ status: job.status,+ stage: job.stage || null,+ glb_url: job.glb_url || null,+ manifest_url: job.manifest_url || null,+ thumb_url: job.thumb_url || null,+ coverage: typeof job.coverage === 'number' ? job.coverage : null,+ occludes: Array.isArray(job.occludes) ? job.occludes : null,+ garment_id: job.garment_id || null,+ error: job.error || null,+ });+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ const cfg = config();+ if (!cfg) return unconfigured(res);++ if (req.method === 'POST') return startJob(req, res, cfg);++ 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, cfg, jobId);+});diff --git a/docs/avatar-wardrobe.md b/docs/avatar-wardrobe.mdindex e63b5df4b..4803a2779 100644--- a/docs/avatar-wardrobe.md+++ b/docs/avatar-wardrobe.md@@ -73,6 +73,28 @@ slot, unknown body region, malformed hash, or a licence outside the approvedcommercial set (CC0, CC-BY, MIT, Apache-2.0, BSD) drops the entry with aconsole warning. A broken manifest becomes a missing tile, not a broken avatar.+## Generating new garments++The catalog is fed by the Garment Forge+([`workers/garment-forge/`](../workers/garment-forge/README.md)): a text+prompt becomes a rigged, validated, published catalog piece in about seven+minutes. The platform endpoint is a thin proxy over that worker:++```+POST /api/garment-forge { "prompt": "a red varsity jacket", "slot": "outerwear" }+ → 202 { job_id, status, eta_seconds }+GET /api/garment-forge?job=<id>+ → { status, stage, glb_url, manifest_url, coverage, occludes }+```++`stage` walks `image → mesh → compose → rig → extract → validate → publish`.+When the job reports `done`, the piece is already live in the catalog above;+a closet refresh (`loadCatalog({ force: true })`) shows it immediately. Every+published piece passed the same ≥60% bind-coverage gate the closet enforces,+measured against the canonical body before publish, so a generated garment+can never be a tile the closet then refuses to wear. Offline proof harness:+`node scripts/verify-garment.mjs <manifest url> [avatar.glb]`.+## Persistence shape```jsondiff --git a/workers/garment-forge/README.md b/workers/garment-forge/README.mdindex 9f457fb66..478341967 100644--- a/workers/garment-forge/README.md+++ b/workers/garment-forge/README.md@@ -113,6 +113,12 @@ watch -n 10 "curl -s $URL/jobs/$JOB -H 'authorization: Bearer $KEY' | python3 -mA finished job reports the published `manifest_url`, `glb_url`, and themeasured `coverage`.+The platform exposes this worker publicly (rate-limited, key held server-side)+at `POST /api/garment-forge` + `GET /api/garment-forge?job=<id>` via+[api/garment-forge.js](../../api/garment-forge.js) and the+`GCP_GARMENT_FORGE_URL` env var on `three-ws-api`; see the "Generating new+garments" section of [docs/avatar-wardrobe.md](../../docs/avatar-wardrobe.md).+## Deploy```bashdiff --git a/workers/garment-forge/cloudbuild.yaml b/workers/garment-forge/cloudbuild.yamlindex fc99e5662..0bc2879b8 100644--- a/workers/garment-forge/cloudbuild.yaml+++ b/workers/garment-forge/cloudbuild.yaml@@ -59,7 +59,13 @@ steps:- --port=8080- --cpu=4- --memory=8Gi- - --min-instances=0+ # Jobs run as post-202 background work, so the CPU must stay allocated+ # between requests (throttled CPU starves a job the moment pollers go+ # quiet) and one instance stays warm so a scale-to-zero reclaim cannot+ # kill a pipeline mid-flight. The stale-job watchdog in main.py is the+ # backstop for the remaining reclaim windows (deploys, crashes).+ - --no-cpu-throttling+ - --min-instances=1- --max-instances=2- --timeout=600- --allow-unauthenticateddiff --git a/workers/garment-forge/main.py b/workers/garment-forge/main.pyindex 24b89dc2e..7ef7addf0 100644--- a/workers/garment-forge/main.py+++ b/workers/garment-forge/main.py@@ -78,6 +78,12 @@ RIG_URL = os.environ["RIG_URL"].rstrip("/")REFBODY_PATH = os.environ.get("REFBODY_PATH", "/app/assets/refbody.glb")GARMENT_YAW_DEG = float(os.environ.get("GARMENT_YAW_DEG", "0"))MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "2"))+# A job whose record has not advanced in this long is dead: the instance that+# owned it was reclaimed mid-pipeline. Every live stage persists a transition+# well inside this window (the worst full run, with both hunyuan rungs failing+# over to trellis, stays under ~35 minutes), so a poll that finds an older+# running/queued record reports failure instead of "running" forever.+JOB_STALE_S = float(os.environ.get("JOB_STALE_S", "2700"))_bucket: Optional[storage.Bucket] = None # jobs + rig staging_publish_bucket: Optional[storage.Bucket] = None # public garment catalog@@ -252,12 +258,35 @@ async def generate(return {"job_id": job_id, "status": "queued"}+async def _fail_if_stale(job: dict) -> dict:+ """Watchdog: an in-flight record that stopped advancing belongs to a+ reclaimed instance. Convert it to a terminal failure (and persist that)+ so no client polls a zombie forever."""+ if job.get("status") not in ("queued", "running"):+ return job+ try:+ updated = datetime.fromisoformat(job.get("updated_at", ""))+ except ValueError:+ return job+ age = (datetime.now(timezone.utc) - updated).total_seconds()+ if age <= JOB_STALE_S:+ return job+ log.error("[%s] stale for %.0fs at stage %s; marking failed",+ job.get("job_id"), age, job.get("stage"))+ return await _update_job(+ job["job_id"], status="failed",+ error=f"job stalled at stage '{job.get('stage')}' "+ f"(no progress for {int(age)}s); the owning instance was likely "+ "reclaimed. Retry the generation.",+ )++@app.get("/jobs/{job_id}")async def get_job(job_id: str, authorization: str = Header(...)) -> dict:_require_api_key(authorization)job = _jobs.get(job_id)if job is not None:- return job+ return await _fail_if_stale(job)loop = asyncio.get_event_loop()try:data = await loop.run_in_executor(None, _job_blob(job_id).download_as_bytes)@@ -268,7 +297,7 @@ async def get_job(job_id: str, authorization: str = Header(...)) -> dict:detail=safe_error(exc, context="job lookup")) from excjob = json.loads(data)_jobs[job_id] = job- return job+ return await _fail_if_stale(job)@app.get("/health")