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
fix(stylize): transcode meshopt-compressed GLBs before trimesh and ship the worker's OIN signing docs
nirholas91a14bd51403
diff --git a/workers/stylize/Dockerfile b/workers/stylize/Dockerfileindex 4ce0539a6..38d857a86 100644--- a/workers/stylize/Dockerfile+++ b/workers/stylize/Dockerfile@@ -1,9 +1,25 @@+# gltfpack (zeux/meshoptimizer, MIT) decodes EXT_meshopt_compression, which+# trimesh cannot read and which most three.ws avatars ship as. Pinned by release+# tag and checksum so the image never picks up a binary we did not audit.+FROM python:3.11-slim AS gltfpack+ARG GLTFPACK_VERSION=v1.2+ARG GLTFPACK_SHA256=ebc236f5f6c08c7e5c5750476a187d24805d44d8c680449c4b7369c333f817b1+RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl unzip \+ && curl -fsSL -o /tmp/gltfpack.zip \+ https://github.com/zeux/meshoptimizer/releases/download/${GLTFPACK_VERSION}/gltfpack-ubuntu.zip \+ && echo "${GLTFPACK_SHA256} /tmp/gltfpack.zip" | sha256sum -c - \+ && unzip -j /tmp/gltfpack.zip gltfpack -d /usr/local/bin \+ && chmod +x /usr/local/bin/gltfpack \+ && /usr/local/bin/gltfpack -v+FROM python:3.11-slimENV PYTHONDONTWRITEBYTECODE=1 \PYTHONUNBUFFERED=1 \PIP_NO_CACHE_DIR=1+COPY --from=gltfpack /usr/local/bin/gltfpack /usr/local/bin/gltfpack+RUN apt-get update && apt-get install -y --no-install-recommends \libgl1 libglib2.0-0 libgomp1 \libassimp-dev libassimp5 \@@ -26,8 +42,8 @@ COPY test_stylize.py /app/test_stylize.py# Build-time guard: the four filters, the color sampler, the export round-trip,# the memory caps, the SSRF gate, and the upload retry policy must pass their# unit suite or the image does not ship. This is also the only place open3d's-# decimation path (used by voronoi + lowpoly) is exercised; the local run falls-# back to trimesh.+# decimation path (used by voronoi + lowpoly) and the gltfpack meshopt decode are+# exercised; the local run falls back to trimesh and skips the meshopt case.RUN python /app/test_stylize.pyEXPOSE 8080diff --git a/workers/stylize/README.md b/workers/stylize/README.mdindex 83ff6c376..6fb6234de 100644--- a/workers/stylize/README.md+++ b/workers/stylize/README.md@@ -39,6 +39,14 @@ input can never exhaust memory — resolution backs off automatically.Input formats: `.glb`, `.gltf`, `.obj`, `.stl`, `.ply`, `.fbx`, `.off`, `.dae`(FBX/DAE via `pyassimp`). Output formats: `glb` (default), `obj`, `stl`, `ply`.+A glTF asset that declares `EXT_meshopt_compression` (what `gltfpack` emits, and+what most three.ws avatars ship as) is transcoded to plain glTF with+[`gltfpack`](https://github.com/zeux/meshoptimizer) before loading: trimesh has+no decoder for that extension and fails on the compressed asset's fallback+buffer, so every filter used to fail on those meshes. The binary is pinned by+release tag and checksum in the [`Dockerfile`](Dockerfile); point `GLTFPACK_BIN`+at your own copy to run that path locally.+## HTTP contractBearer-authenticated on `/process` and `/tasks/:id`; `/styles` and `/health`@@ -109,6 +117,18 @@ gallery. Public, no auth.{ "ok": true, "service": "stylize", "styles": ["voxel", "brick", "voronoi", "lowpoly"] }```+### OIN routes (only with `OIN_ENABLED=true`)++The same filters are also offered over the Open Inference Protocol+([`specs/OPEN_INFERENCE_PROTOCOL.md`](../../specs/OPEN_INFERENCE_PROTOCOL.md)),+so an outside node operator can run this worker and return signed receipts:+`GET /.well-known/oin` (signed advertisement of the `mesh.stylize` capability),+`POST /oin/jobs`, `GET /oin/jobs/:id`. The job envelope carries the mesh URL as+`input.data` and the style as `input.model`, with `params.resolution` and+`params.output_format` as the knobs; the response commits to the artifact's+`sha256` and byte length, signed with `OIN_SIGNING_KEY`. Jobs use the same+bearer secret as `/process`. With the flag unset none of these routes exist.+## Environment| Var | Required | Default | Meaning |@@ -116,16 +136,26 @@ gallery. Public, no auth.| `API_KEY` | yes | — | Bearer secret for `/process` + `/tasks`. In production it is the shared model-worker key (Secret Manager `avatar-reconstruction-key`, mounted by `cloudbuild.yaml`). || `GCS_BUCKET` | yes | — | Output bucket for stylized meshes (prod: `three-ws-avatar-reconstructions`). || `MAX_CONCURRENT` | no | `2` | In-process semaphore bounding concurrent jobs. |+| `GLTFPACK_BIN` | no | `gltfpack` | Path to the meshopt decoder. The image ships it on `PATH`. |+| `OIN_ENABLED` | no | unset | `true` mounts the OIN routes (see below). Anything else leaves the worker byte-for-byte its pre-OIN self. |+| `OIN_SIGNING_KEY` | with OIN | (none) | base64 Ed25519 seed. With `OIN_ENABLED=true` and no key the worker refuses to boot, so a node can never advertise a key it cannot sign with. |+| `OIN_NODE_ID` | no | `three-ws-stylize` | Node identity in the advertisement. |+| `OIN_RESULT_DIR` | no | unset | Write OIN artifacts to this directory instead of GCS. Set it and the worker skips the GCS client entirely, so a local run needs no cloud credentials. |+| `OIN_RESULT_BASE_URL` | with `OIN_RESULT_DIR` | (none) | Public base URL the directory is served from; the signed `output.url` is built from it. |## How it ships-Deployed as the Cloud Run service **`stylize-service`** in **`us-central1`**,-built by Cloud Build from [`cloudbuild.yaml`](cloudbuild.yaml) (CPU-only:-`--cpu=8 --memory=16Gi`, `--min-instances=1 --max-instances=3`, 300 s timeout,-run SA `avatar-reconstruction-sa`, build SA `three-ws-build@` as every build in-this project must pin). It is kept warm rather than scaled to zero: a job itself-finishes in under ten seconds, so a cold start on top of it would be the-dominant stall in an interactive edit.+Deployed as the Cloud Run service **`stylize-service`** in **`us-central1`**+(live base URL `https://stylize-service-lp642k3kpa-uc.a.run.app`), built by Cloud+Build from [`cloudbuild.yaml`](cloudbuild.yaml) (CPU-only: `--cpu=8+--memory=16Gi`, `--min-instances=1 --max-instances=3`, 300 s timeout,+`--no-cpu-throttling`, run SA `avatar-reconstruction-sa`, build SA+`three-ws-build@` as every build in this project must pin). It is kept warm+rather than scaled to zero: a job itself finishes in under ten seconds, so a cold+start on top of it would be the dominant stall in an interactive edit. CPU+throttling stays off because the work happens in a background task after the+`202`, where a throttled container would crawl while still holding one of the+two concurrency slots.Submit from the **repo root** and pass `SHORT_SHA` explicitly, since the configtags images with it and `gcloud builds submit` does not populate it:@@ -163,7 +193,18 @@ API_KEY=dev-secret GCS_BUCKET=your-dev-bucket \(Uploads need Application Default Credentials with write access to`GCS_BUCKET`.) The container image installs `libassimp` + `libgl` system libs-so FBX/DAE input and headless mesh IO work.+so FBX/DAE input and headless mesh IO work, plus the pinned `gltfpack` binary+for meshopt input.++To run it as a self-hosted OIN node with no cloud account at all, keep results+on disk and skip GCS entirely:++```bash+API_KEY=dev-secret GCS_BUCKET=unused \+OIN_ENABLED=true OIN_SIGNING_KEY="$(python3 -c 'import base64,os;print(base64.b64encode(os.urandom(32)).decode())')" \+OIN_RESULT_DIR=/tmp/oin-artifacts OIN_RESULT_BASE_URL=http://localhost:8080/artifacts \+ uvicorn main:app --host 0.0.0.0 --port 8080+```## Tests@@ -176,11 +217,14 @@ network, and no server: the catalog and its resolution bounds, requestvalidation, scene loading, color preservation and the untextured fallback, allfour filters (geometry, tint, and the shape property each one promises), thezero-extent refusal, the `MAX_VOXELS` / `MAX_LATTICE_EDGES` backoff, an export-round-trip in every output format, the SSRF gate, the `401` contract, and the-upload retry policy. It needs `trimesh`, `numpy`, `scipy`, `fastapi`,-`pydantic`, and `google-cloud-storage`; `open3d` is optional locally (`_decimate`-falls back to trimesh without it) and present in the image, so the Docker build-gate is what exercises the open3d decimation path.+round-trip in every output format, the SSRF gate, the `401` contract, the upload+retry policy, the meshopt decode, the OIN protocol primitives, and the OIN job+executor end to end against a real result sink. It needs `trimesh`, `numpy`,+`scipy`, `pillow`, `fastapi` (its `TestClient`, so `httpx` too), `pydantic`, and+`google-cloud-storage`. Two dependencies are optional locally and present in the+image, so the Docker build gate is what exercises their paths: `open3d`+(`_decimate` falls back to trimesh without it) and `gltfpack` (without it the+suite pins the readable failure instead of round-tripping a compressed asset).## Usage example@@ -215,9 +259,11 @@ curl -s -X POST https://three.ws/api/forge-stylize \| File | Role ||------|------|-| [`main.py`](main.py) | FastAPI app: filters, color sampler, task queue, GCS upload, routes. |+| [`main.py`](main.py) | FastAPI app: filters, color sampler, mesh loading, task queue, GCS upload, routes, OIN executor. || [`test_stylize.py`](test_stylize.py) | Core-path unit suite; also a Docker build gate. || [`worker_security.py`](worker_security.py) | Shared bearer-auth, SSRF-safe fetch, error sanitizer. |-| [`requirements.txt`](requirements.txt) | Pinned deps (`trimesh`, `open3d`, `scipy`, `pyassimp`, …). |-| [`Dockerfile`](Dockerfile) | `python:3.11-slim` + assimp/GL system libs; uvicorn on `:8080`. |+| [`oin.py`](oin.py) | OIN protocol layer: canonicalization, job digests, Ed25519 signing, the `/oin/*` routes. Vendored copy, kept byte-identical across workers. |+| [`oin_upload.py`](oin_upload.py) | OIN result sinks: GCS in production, a local directory for self-hosted runs. |+| [`requirements.txt`](requirements.txt) | Pinned deps (`trimesh`, `open3d`, `scipy`, `pyassimp`, `pynacl`, …). |+| [`Dockerfile`](Dockerfile) | `python:3.11-slim` + assimp/GL system libs + pinned `gltfpack`; uvicorn on `:8080`. || [`cloudbuild.yaml`](cloudbuild.yaml) | Cloud Build → Artifact Registry → Cloud Run deploy. |diff --git a/workers/stylize/main.py b/workers/stylize/main.pyindex 4444e46fe..30ddecfd4 100644--- a/workers/stylize/main.py+++ b/workers/stylize/main.py@@ -39,8 +39,10 @@ from __future__ import annotationsimport asyncioimport io+import jsonimport loggingimport os+import subprocessimport tempfileimport timeimport uuid@@ -85,6 +87,17 @@ SUPPORTED_INPUT_FORMATS = {".glb", ".gltf", ".obj", ".stl", ".ply", ".fbx", ".ofSUPPORTED_OUTPUT_FORMATS = {"glb", "obj", "stl", "ply"}MAX_MESH_BYTES = 128 * 1024 * 1024+# trimesh has no EXT_meshopt_compression decoder, and a meshopt GLB's buffer 1 is+# a fallback that only exists after decoding, so trimesh dies on the bufferView+# lookup with a bare IndexError. Meshopt is what gltfpack emits and what most of+# three.ws's own avatars ship as, so this was a hard failure on our own assets+# (verified 2026-08-13: /avatars/michelle.glb failed every style in production).+# gltfpack is the same project's CLI and decodes what it encoded: transcode the+# input to plain glTF before trimesh ever sees it.+MESHOPT_EXTENSION = "EXT_meshopt_compression"+GLTFPACK_BIN = os.environ.get("GLTFPACK_BIN", "gltfpack")+GLTFPACK_TIMEOUT_S = 120+# Hard safety caps so a hostile/huge input can never exhaust memory.MAX_VOXELS = 60_000 # occupied surface cells rebuilt as cubesMAX_LATTICE_EDGES = 6_000 # struts emitted for the voronoi shell@@ -197,10 +210,74 @@ def _fetch_mesh(url: str) -> tuple[bytes, str]:return data, suffix+def _gltf_document(data: bytes, suffix: str) -> Optional[dict]:+ """The glTF JSON of a .glb/.gltf payload, or None when it is neither."""+ if suffix == ".gltf":+ try:+ return json.loads(data)+ except ValueError:+ return None+ if suffix != ".glb" or len(data) < 20 or data[:4] != b"glTF":+ return None+ chunk_length = int.from_bytes(data[12:16], "little")+ if data[16:20] != b"JSON":+ return None+ try:+ return json.loads(data[20:20 + chunk_length])+ except ValueError:+ return None+++def _uses_meshopt(document: Optional[dict]) -> bool:+ """True when the asset needs a meshopt decode before any reader can use it.++ Checked against both extension lists: a file that only *uses* the extension+ still stores its geometry in the compressed views, and its fallback buffer+ is empty until something decodes into it.+ """+ if not document:+ return False+ declared = set(document.get("extensionsRequired") or []) | set(document.get("extensionsUsed") or [])+ return MESHOPT_EXTENSION in declared+++def _transcode_meshopt(data: bytes, suffix: str) -> bytes:+ """Rewrite a meshopt-compressed asset as a plain GLB with gltfpack.++ `-noq` keeps the source quantization instead of re-quantizing on the way+ out, so the stylized result is derived from the geometry the author shipped.+ """+ with tempfile.TemporaryDirectory() as tmpdir:+ src = Path(tmpdir) / f"input{suffix}"+ dst = Path(tmpdir) / "decoded.glb"+ src.write_bytes(data)+ try:+ proc = subprocess.run(+ [GLTFPACK_BIN, "-i", str(src), "-o", str(dst), "-noq"],+ capture_output=True,+ timeout=GLTFPACK_TIMEOUT_S,+ )+ except FileNotFoundError as exc:+ raise ValueError(+ f"input uses {MESHOPT_EXTENSION} and the gltfpack decoder is not installed"+ ) from exc+ except subprocess.TimeoutExpired as exc:+ raise ValueError(f"{MESHOPT_EXTENSION} decode timed out") from exc+ if proc.returncode != 0 or not dst.exists():+ detail = (proc.stderr or b"").decode("utf-8", "replace").strip().splitlines()+ raise ValueError(f"{MESHOPT_EXTENSION} decode failed: {detail[-1][:200] if detail else 'no output'}")+ return dst.read_bytes()++def _load_single_mesh(data: bytes, suffix: str):"""Load to a single concatenated Trimesh, keeping visual/color where present."""import trimesh+ if _uses_meshopt(_gltf_document(data, suffix)):+ log.info("input declares %s; decoding with gltfpack before load", MESHOPT_EXTENSION)+ data = _transcode_meshopt(data, suffix)+ suffix = ".glb"+loaded = trimesh.load(io.BytesIO(data), file_type=suffix.lstrip("."), force="mesh", process=False)if isinstance(loaded, trimesh.Scene):meshes = [g for g in loaded.geometry.values() if isinstance(g, trimesh.Trimesh)]diff --git a/workers/stylize/test_stylize.py b/workers/stylize/test_stylize.pyindex a7e191ff3..a4e0fae8c 100644--- a/workers/stylize/test_stylize.py+++ b/workers/stylize/test_stylize.py@@ -197,6 +197,80 @@ try:except ValueError:check("geometry with no faces is rejected", True)+# ── meshopt-compressed input ────────────────────────────────────────────────────+# EXT_meshopt_compression is what gltfpack emits and what most three.ws avatars+# ship as. trimesh has no decoder for it and dies on the fallback buffer with a+# bare IndexError, so every style failed on our own avatars until the loader+# started transcoding through gltfpack first.++import io # noqa: E402+import shutil # noqa: E402+import subprocess # noqa: E402+import tempfile # noqa: E402+from pathlib import Path # noqa: E402++plain_glb = trimesh.Scene({"a": source_mesh()}).export(file_type="glb")+check(+ "a plain glb is not sent through the decoder",+ not main._uses_meshopt(main._gltf_document(plain_glb, ".glb")),+)+check(+ "a non-gltf payload has no gltf document",+ main._gltf_document(b"ply\nformat ascii 1.0\n", ".ply") is None,+)+for declared in ("extensionsRequired", "extensionsUsed"):+ check(+ f"{declared}: {main.MESHOPT_EXTENSION} is detected",+ main._uses_meshopt({declared: [main.MESHOPT_EXTENSION]}),+ )++if shutil.which(main.GLTFPACK_BIN):+ # Round-trip through the real encoder: compress, then prove the loader gets+ # usable geometry back out of a file trimesh cannot read on its own.+ with tempfile.TemporaryDirectory() as packdir:+ raw = Path(packdir) / "raw.glb"+ packed = Path(packdir) / "packed.glb"+ raw.write_bytes(plain_glb)+ subprocess.run(+ [main.GLTFPACK_BIN, "-i", str(raw), "-o", str(packed), "-cc"],+ capture_output=True,+ check=True,+ timeout=main.GLTFPACK_TIMEOUT_S,+ )+ packed_bytes = packed.read_bytes()++ check(+ "a meshopt glb is detected as needing a decode",+ main._uses_meshopt(main._gltf_document(packed_bytes, ".glb")),+ )+ try:+ trimesh.load(io.BytesIO(packed_bytes), file_type="glb", force="mesh", process=False)+ raw_load_failed = False+ except Exception: # noqa: BLE001: the exact trimesh error is not the contract+ raw_load_failed = True+ check("trimesh alone cannot read a meshopt glb", raw_load_failed)++ decoded = main._load_single_mesh(packed_bytes, ".glb")+ check(+ "the loader returns real geometry for a meshopt glb",+ len(decoded.faces) > 0 and len(decoded.vertices) > 0,+ f"faces={len(decoded.faces)}",+ )+ styled_from_packed = main._stylize_lowpoly(decoded, 8)+ check("a meshopt glb stylizes end to end", len(styled_from_packed.faces) > 0)+else:+ # No gltfpack locally: pin the failure contract instead, so a caller is told+ # what the input needs rather than getting a bare loader crash.+ try:+ main._transcode_meshopt(plain_glb, ".glb")+ check("a missing gltfpack is reported as a readable error", False, "no ValueError raised")+ except ValueError as exc:+ check(+ "a missing gltfpack is reported as a readable error",+ main.MESHOPT_EXTENSION in str(exc),+ str(exc),+ )+# ── color preservation ──────────────────────────────────────────────────────────colored = source_mesh()@@ -487,9 +561,6 @@ check(# mesh and a real LocalResultSink, with only the network fetch replaced by the# bytes of a locally exported GLB, so nothing here is stubbed but the download.-import tempfile # noqa: E402-from pathlib import Path # noqa: E402-from oin_upload import LocalResultSink # noqa: E402