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(pyclient): extend the shared Python client and its Blender and ComfyUI copies, with tests and a drift check

nirholas12053652b46a
diff --git a/integrations/_pyclient/test_no_drift.py b/integrations/_pyclient/test_no_drift.py
index 04db0a236..11e72c937 100644
--- a/integrations/_pyclient/test_no_drift.py
+++ b/integrations/_pyclient/test_no_drift.py
@@ -2,8 +2,8 @@
``three_ws_client.py`` is the one source of truth for the Forge contract. Each
plugin ships a byte-identical copy so it stays self-contained and distributable
-(a Blender add-on zip / a ComfyUI custom_nodes clone). This test fails if any
-copy drifts from the canonical file — re-copy it and the contract stays in lockstep.
+(a Blender add-on zip, a ComfyUI custom_nodes clone, a Modly extension folder). This test fails if any
+copy drifts from the canonical file. Re-copy it and the contract stays in lockstep.
"""
from __future__ import annotations
@@ -17,6 +17,8 @@ _CANONICAL = os.path.join(_HERE, "three_ws_client.py")
_VENDORED = [
os.path.join(_ROOT, "blender", "three_ws", "three_ws_client.py"),
os.path.join(_ROOT, "comfyui", "three_ws_nodes", "three_ws_client.py"),
+ os.path.join(_ROOT, "modly", "three-ws", "three_ws_client.py"),
+ os.path.join(_ROOT, "modly", "three-ws-publish", "three_ws_client.py"),
]
@@ -31,7 +33,7 @@ class NoDriftTest(unittest.TestCase):
self.assertEqual(
canonical,
copy,
- f"{path} drifted from the canonical three_ws_client.py — "
+ f"{path} drifted from the canonical three_ws_client.py. "
f"re-copy it: cp {_CANONICAL} {path}",
)
diff --git a/integrations/_pyclient/test_three_ws_client.py b/integrations/_pyclient/test_three_ws_client.py
index 84e530e43..9038bc2ab 100644
--- a/integrations/_pyclient/test_three_ws_client.py
+++ b/integrations/_pyclient/test_three_ws_client.py
@@ -14,7 +14,13 @@ import unittest
import urllib.parse
from http.server import BaseHTTPRequestHandler, HTTPServer
-from three_ws_client import ThreeWSClient, ThreeWSError, content_type_for_path
+from three_ws_client import ThreeWSClient, ThreeWSError, content_type_for_path, is_glb, slugify
+
+
+def _glb(payload: bytes = b"JSON") -> bytes:
+ """A header-valid GLB: magic, version 2, and a length equal to the buffer."""
+ total = 12 + len(payload)
+ return b"glTF" + (2).to_bytes(4, "little") + total.to_bytes(4, "little") + payload
class _Handler(BaseHTTPRequestHandler):
@@ -188,5 +194,268 @@ class ForgeClientTest(unittest.TestCase):
self.assertEqual(ctx.exception.code, "timeout")
+class _AccountHandler(BaseHTTPRequestHandler):
+ """Stands in for the authenticated avatar upload + create endpoints."""
+
+ def log_message(self, *args):
+ pass
+
+ def _send(self, status, obj):
+ body = json.dumps(obj).encode("utf-8")
+ self.send_response(status)
+ self.send_header("content-type", "application/json")
+ self.send_header("content-length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_POST(self):
+ state = self.server.state
+ parsed = urllib.parse.urlparse(self.path)
+ length = int(self.headers.get("content-length", 0))
+ raw = self.rfile.read(length) if length else b""
+ state["auth"].append(self.headers.get("authorization"))
+ if self.headers.get("authorization") != "Bearer sk_live_test":
+ return self._send(401, {"error": "unauthorized", "message": "sign in or provide a valid bearer token"})
+ if parsed.path == "/api/avatars/upload":
+ state["upload_query"] = urllib.parse.parse_qs(parsed.query)
+ state["upload_content_type"] = self.headers.get("content-type")
+ state["uploaded"] = raw
+ return self._send(200, {
+ "storage_key": "u/1/my-robot/abc.glb",
+ "size_bytes": len(raw),
+ "content_type": "model/gltf-binary",
+ "checksum_sha256": "f" * 64,
+ })
+ if parsed.path == "/api/avatars":
+ state["create"] = json.loads(raw.decode("utf-8"))
+ return self._send(201, {"avatar": {"id": "av_1", "name": state["create"]["name"], "visibility": "unlisted"}})
+ return self._send(404, {"error": "not_found"})
+
+
+class PublishTest(unittest.TestCase):
+ def setUp(self):
+ self.server = HTTPServer(("127.0.0.1", 0), _AccountHandler)
+ self.server.state = {"auth": []}
+ self.base = f"http://127.0.0.1:{self.server.server_address[1]}"
+ self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
+ self.thread.start()
+ self.client = ThreeWSClient(self.base, client_handle="h")
+
+ def tearDown(self):
+ self.server.shutdown()
+ self.server.server_close()
+ self.thread.join(timeout=2)
+
+ def test_publish_uploads_then_creates(self):
+ glb = _glb()
+ avatar = self.client.publish_glb(
+ glb,
+ api_key="sk_live_test",
+ name="My Robot!",
+ visibility="unlisted",
+ tags=["modly", " ", "robot"],
+ source_meta={"generator": "modly", "model": "triposg/generate"},
+ )
+ st = self.server.state
+ self.assertEqual(avatar["id"], "av_1")
+ self.assertEqual(st["uploaded"], glb)
+ self.assertEqual(st["upload_content_type"], "model/gltf-binary")
+ self.assertEqual(st["upload_query"]["slug"], ["my-robot"])
+ self.assertEqual(st["create"]["storage_key"], "u/1/my-robot/abc.glb")
+ self.assertEqual(st["create"]["size_bytes"], len(glb))
+ self.assertEqual(st["create"]["tags"], ["modly", "robot"])
+ self.assertEqual(st["create"]["source_meta"]["generator"], "modly")
+ self.assertEqual(st["auth"], ["Bearer sk_live_test", "Bearer sk_live_test"])
+ self.assertEqual(self.client.avatar_page_url(avatar), f"{self.base}/avatars/av_1")
+
+ def test_publish_rejects_non_glb_before_any_request(self):
+ with self.assertRaises(ThreeWSError) as ctx:
+ self.client.publish_glb(b"not a glb at all", api_key="sk_live_test", name="x")
+ self.assertEqual(ctx.exception.code, "invalid_glb")
+ self.assertEqual(self.server.state["auth"], [])
+
+ def test_publish_requires_key(self):
+ with self.assertRaises(ThreeWSError) as ctx:
+ self.client.publish_glb(_glb(), api_key=" ", name="x")
+ self.assertEqual(ctx.exception.code, "missing_api_key")
+
+ def test_publish_surfaces_auth_failure(self):
+ with self.assertRaises(ThreeWSError) as ctx:
+ self.client.publish_glb(_glb(), api_key="sk_live_wrong", name="x")
+ self.assertEqual(ctx.exception.status, 401)
+ self.assertEqual(ctx.exception.code, "unauthorized")
+
+ def test_helpers(self):
+ self.assertTrue(is_glb(_glb()))
+ self.assertFalse(is_glb(_glb()[:-1]))
+ self.assertFalse(is_glb(b"glTF"))
+ self.assertEqual(slugify(" Hello, World / v2 "), "hello-world-v2")
+ self.assertEqual(slugify("!!!"), "model")
+ self.assertLessEqual(len(slugify("a" * 200)), 64)
+
+
+class _MeshOpsHandler(BaseHTTPRequestHandler):
+ """Stands in for the GLB presign, the rigger, and the remesh worker."""
+
+ def log_message(self, *args):
+ pass
+
+ def _send(self, status, obj):
+ body = json.dumps(obj).encode("utf-8")
+ self.send_response(status)
+ self.send_header("content-type", "application/json")
+ self.send_header("content-length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def _read_body(self):
+ length = int(self.headers.get("content-length", 0))
+ raw = self.rfile.read(length) if length else b""
+ try:
+ return json.loads(raw.decode("utf-8")) if raw else {}
+ except ValueError:
+ return {}
+
+ def do_POST(self):
+ state = self.server.state
+ parsed = urllib.parse.urlparse(self.path)
+ qs = urllib.parse.parse_qs(parsed.query)
+ body = self._read_body()
+ host = f"http://127.0.0.1:{self.server.server_address[1]}"
+ if parsed.path == "/api/scene-glb-upload":
+ state["presign_body"] = body
+ return self._send(200, {
+ "upload_url": f"{host}/_put/scene.glb",
+ "public_url": "https://cdn.example/scenes/scene.glb",
+ "headers": {"content-type": "model/gltf-binary"},
+ "method": "PUT",
+ "expires_in": 900,
+ })
+ if parsed.path == "/api/forge" and qs.get("action") == ["rig"]:
+ state["rig_body"] = body
+ if state.get("rig_unconfigured"):
+ return self._send(501, {"error": "rig_unconfigured", "message": "Rigging is not configured."})
+ return self._send(202, {"job_id": "rig_1", "status": "queued"})
+ if parsed.path == "/api/forge-remesh":
+ state["remesh_body"] = body
+ return self._send(202, {"job_id": "rm_1", "status": "queued"})
+ return self._send(404, {"error": "not_found"})
+
+ def do_GET(self):
+ state = self.server.state
+ parsed = urllib.parse.urlparse(self.path)
+ qs = urllib.parse.parse_qs(parsed.query)
+ if parsed.path == "/api/forge" and qs.get("job") == ["rig_1"]:
+ state["rig_polls"] = state.get("rig_polls", 0) + 1
+ if state["rig_polls"] < 2:
+ return self._send(200, {"status": "running"})
+ return self._send(200, {"status": "done", "glb_url": "https://cdn.example/rigged.glb"})
+ if parsed.path == "/api/forge-remesh" and qs.get("job") == ["rm_1"]:
+ state["remesh_polls"] = state.get("remesh_polls", 0) + 1
+ if state["remesh_polls"] == 1:
+ # The worker cold-starting answers 502 with no status: retry.
+ return self._send(502, {"error": "upstream_unavailable"})
+ if state.get("remesh_fail"):
+ return self._send(200, {"status": "failed", "error": "mesh is not manifold"})
+ return self._send(200, {
+ "status": "done",
+ "result_url": "https://cdn.example/remeshed.glb",
+ "face_count": 4000,
+ })
+ return self._send(404, {"error": "not_found"})
+
+ def do_PUT(self):
+ length = int(self.headers.get("content-length", 0))
+ self.server.state["put_bytes"] = self.rfile.read(length)
+ self.server.state["put_type"] = self.headers.get("content-type")
+ self.send_response(200)
+ self.send_header("content-length", "0")
+ self.end_headers()
+
+
+class MeshOpsTest(unittest.TestCase):
+ def setUp(self):
+ self.server = HTTPServer(("127.0.0.1", 0), _MeshOpsHandler)
+ self.server.state = {}
+ self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
+ self.thread.start()
+ self.client = ThreeWSClient(f"http://127.0.0.1:{self.server.server_address[1]}")
+ self.no_sleep = {"_sleep": lambda _s: None}
+
+ def tearDown(self):
+ self.server.shutdown()
+ self.server.server_close()
+ self.thread.join(timeout=2)
+
+ def test_upload_glb_presigns_then_puts(self):
+ glb = _glb(b"mesh-bytes")
+ url = self.client.upload_glb(glb)
+ self.assertEqual(url, "https://cdn.example/scenes/scene.glb")
+ self.assertEqual(self.server.state["presign_body"], {"content_type": "model/gltf-binary", "size_bytes": len(glb)})
+ self.assertEqual(self.server.state["put_bytes"], glb)
+ self.assertEqual(self.server.state["put_type"], "model/gltf-binary")
+
+ def test_upload_glb_rejects_non_glb_without_a_request(self):
+ with self.assertRaises(ThreeWSError) as ctx:
+ self.client.upload_glb(b"\x89PNG not a mesh")
+ self.assertEqual(ctx.exception.code, "invalid_glb")
+ self.assertNotIn("presign_body", self.server.state)
+
+ def test_rig_submits_and_polls_for_glb_url(self):
+ statuses = []
+ url = self.client.rig(
+ "https://cdn.example/static.glb",
+ on_progress=lambda st, _e: statuses.append(st),
+ **self.no_sleep,
+ )
+ self.assertEqual(url, "https://cdn.example/rigged.glb")
+ self.assertEqual(self.server.state["rig_body"], {"glb_url": "https://cdn.example/static.glb"})
+ self.assertEqual(statuses, ["running", "done"])
+
+ def test_rig_unconfigured_surfaces_the_server_message(self):
+ self.server.state["rig_unconfigured"] = True
+ with self.assertRaises(ThreeWSError) as ctx:
+ self.client.rig("https://cdn.example/static.glb", **self.no_sleep)
+ self.assertEqual(ctx.exception.code, "rig_unconfigured")
+ self.assertEqual(ctx.exception.status, 501)
+
+ def test_rig_requires_https_url(self):
+ with self.assertRaises(ThreeWSError) as ctx:
+ self.client.submit_rig("file:///tmp/a.glb")
+ self.assertEqual(ctx.exception.code, "invalid_glb_url")
+
+ def test_remesh_retries_a_502_poll_and_returns_result_url(self):
+ url = self.client.remesh(
+ "https://cdn.example/raw.glb",
+ remesh_mode="quad",
+ operation="full",
+ target_faces=4000,
+ texture_size=2048,
+ **self.no_sleep,
+ )
+ self.assertEqual(url, "https://cdn.example/remeshed.glb")
+ self.assertEqual(self.server.state["remesh_polls"], 2)
+ self.assertEqual(self.server.state["remesh_body"], {
+ "mesh_url": "https://cdn.example/raw.glb",
+ "remesh_mode": "quad",
+ "operation": "full",
+ "texture_size": 2048,
+ "output_format": "glb",
+ "target_faces": 4000,
+ })
+
+ def test_remesh_failure_raises(self):
+ self.server.state["remesh_fail"] = True
+ with self.assertRaises(ThreeWSError) as ctx:
+ self.client.remesh("https://cdn.example/raw.glb", **self.no_sleep)
+ self.assertIn("manifold", ctx.exception.message)
+
+ def test_remesh_validates_options_before_any_request(self):
+ for kwargs in ({"remesh_mode": "voxel"}, {"operation": "melt"}, {"texture_size": 300}):
+ with self.assertRaises(ThreeWSError):
+ self.client.submit_remesh("https://cdn.example/raw.glb", **kwargs)
+ self.assertNotIn("remesh_body", self.server.state)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/integrations/_pyclient/three_ws_client.py b/integrations/_pyclient/three_ws_client.py
index dc2ea9a66..98ad00cd9 100644
--- a/integrations/_pyclient/three_ws_client.py
+++ b/integrations/_pyclient/three_ws_client.py
@@ -1,4 +1,4 @@
-"""three.ws Forge client — shared by the Blender add-on and the ComfyUI nodes.
+"""three.ws Forge client, shared by the Blender add-on, the ComfyUI nodes and the Modly extension.
Single source of truth for the public Forge generation contract
(``api/forge.js`` + ``api/forge-upload.js``). Stdlib-only (``urllib``) so it
@@ -12,10 +12,19 @@ Public contract this wraps
* ``GET /api/forge?job=<id>`` → poll ``{status, glb_url?, error?, backend?, ...}``
* ``GET /api/forge?catalog`` → tier/backend/cost matrix
* ``POST /api/forge-upload`` ``{content_type, size_bytes, checksum_sha256?}`` → presigned PUT
+* ``POST /api/scene-glb-upload`` ``{content_type, size_bytes}`` → presigned PUT for a GLB
+* ``POST /api/forge?action=rig`` ``{glb_url}`` → auto-rig, polled on ``?job=``
+* ``POST /api/forge-remesh`` ``{mesh_url, remesh_mode?, operation?, ...}`` → retopology job
+* ``GET /api/forge-remesh?job=`` → poll ``{status, result_url?, face_count?, error?}``
+* ``POST /api/avatars/upload`` raw GLB body, bearer ``avatars:write`` → ``{storage_key, ...}``
+* ``POST /api/avatars/presign`` ``{size_bytes, content_type, checksum_sha256}`` → presigned PUT (large GLBs)
+* ``POST /api/avatars`` ``{name, storage_key, size_bytes, ...}`` → the saved avatar
Generation is auth-free (IP rate-limited, scoped to an anonymous client handle).
The geometry path (Meshy/Tripo) is BYOK: pass ``provider_key`` and it travels as
-the ``x-forge-provider-key`` header.
+the ``x-forge-provider-key`` header. Publishing a GLB into an account
+(``publish_glb``) is the one authenticated call: it takes an API key from
+three.ws/dashboard/api carrying the ``avatars:write`` scope.
This file is vendored byte-for-byte into each plugin package; the canonical copy
lives at ``integrations/_pyclient/three_ws_client.py`` and a drift test keeps the
@@ -26,6 +35,7 @@ from __future__ import annotations
import hashlib
import json
+import ssl
import time
import urllib.error
import urllib.parse
@@ -41,9 +51,33 @@ DEFAULT_POLL_TIMEOUT = 300.0 # overall ceiling for a generation
# Mirrors api/_lib/forge-tiers.js so the plugins can present choices without a
# network round-trip. ``get_catalog()`` fetches the live matrix when needed.
TIERS = ("draft", "standard", "high")
-PATHS = ("image", "geometry")
-BACKENDS = ("trellis", "meshy", "tripo", "hunyuan3d")
+PATHS = ("image", "geometry", "sketch")
+BACKENDS = (
+ "trellis2",
+ "hunyuan3d",
+ "nvidia",
+ "trellis_selfhost",
+ "huggingface",
+ "trellis",
+ "triposg",
+ "meshy",
+ "tripo",
+ "rodin",
+ "stability",
+ "replicate_byok",
+)
ASPECT_RATIOS = ("1:1", "4:3", "3:4", "16:9", "9:16")
+AVATAR_VISIBILITIES = ("private", "unlisted", "public")
+REMESH_MODES = ("triangle", "quad", "lowpoly")
+REMESH_OPERATIONS = ("full", "simplify", "repair", "convert")
+REMESH_TEXTURE_SIZES = (512, 1024, 2048)
+MAX_SCENE_GLB_BYTES = 200 * 1024 * 1024
+
+# The upload proxy (``/api/avatars/upload``) accepts bodies up to 50 MB and
+# canonicalizes humanoid bone names at ingest. Anything larger goes through the
+# presigned direct-to-storage path instead.
+MAX_PROXY_UPLOAD_BYTES = 50 * 1024 * 1024
+MAX_AVATAR_BYTES = 500 * 1024 * 1024
_CONTENT_TYPE_BY_EXT = {
"png": "image/png",
@@ -53,6 +87,26 @@ _CONTENT_TYPE_BY_EXT = {
}
+def _ssl_context() -> ssl.SSLContext:
+ """CA bundle for HTTPS. Embedded Pythons (Blender, Modly, python.org macOS
+ builds) often ship without system roots, so prefer certifi when present."""
+ try:
+ import certifi # type: ignore
+
+ return ssl.create_default_context(cafile=certifi.where())
+ except ImportError:
+ return ssl.create_default_context()
+
+
+_SSL = _ssl_context()
+
+
+def _urlopen(req: urllib.request.Request, timeout: float):
+ if req.full_url.startswith("https://"):
+ return urllib.request.urlopen(req, timeout=timeout, context=_SSL)
+ return urllib.request.urlopen(req, timeout=timeout)
+
+
class ThreeWSError(Exception):
"""A Forge request failed. ``message`` is safe to show a user."""
@@ -113,16 +167,27 @@ class ThreeWSClient:
headers.update(extra)
return headers
- def _request(self, method: str, path: str, *, body: Optional[dict] = None) -> dict:
+ def _request(
+ self,
+ method: str,
+ path: str,
+ *,
+ body: Optional[dict] = None,
+ raw: Optional[bytes] = None,
+ headers: Optional[dict] = None,
+ timeout: Optional[float] = None,
+ ) -> dict:
url = f"{self.base_url}{path}"
data = None
- headers = self._headers()
+ merged = self._headers(headers)
if body is not None:
data = json.dumps(body).encode("utf-8")
- headers["content-type"] = "application/json"
- req = urllib.request.Request(url, data=data, headers=headers, method=method)
+ merged["content-type"] = "application/json"
+ elif raw is not None:
+ data = raw
+ req = urllib.request.Request(url, data=data, headers=merged, method=method)
try:
- with urllib.request.urlopen(req, timeout=self.timeout) as resp:
+ with _urlopen(req, timeout or self.timeout) as resp:
payload = resp.read()
except urllib.error.HTTPError as exc:
payload = exc.read()
@@ -165,23 +230,41 @@ class ThreeWSClient:
"checksum_sha256": checksum,
},
)
+ return self._put_presigned(presign, image_bytes, content_type, "Image")
+
+ def upload_glb(self, glb_bytes: bytes) -> str:
+ """Presign + PUT a binary glTF, returning its public URL.
+
+ Rigging and remeshing take a public mesh URL, so a mesh that exists only
+ on the caller's disk goes up through ``/api/scene-glb-upload`` first.
+ """
+ if not is_glb(glb_bytes):
+ raise ThreeWSError("Mesh must be a binary glTF 2.0 (.glb) file.", code="invalid_glb")
+ if len(glb_bytes) > MAX_SCENE_GLB_BYTES:
+ raise ThreeWSError("Mesh is larger than the 200 MB upload limit.", code="too_large")
+ presign = self._request(
+ "POST",
+ "/api/scene-glb-upload",
+ body={"content_type": "model/gltf-binary", "size_bytes": len(glb_bytes)},
+ )
+ return self._put_presigned(presign, glb_bytes, "model/gltf-binary", "Mesh")
+
+ def _put_presigned(self, presign: dict, data: bytes, content_type: str, label: str) -> str:
upload_url = presign.get("upload_url")
public_url = presign.get("public_url")
if not upload_url or not public_url:
raise ThreeWSError("Upload presign returned no URL.", code="presign_failed")
put_headers = presign.get("headers") or {"content-type": content_type}
- put_req = urllib.request.Request(
- upload_url, data=image_bytes, headers=put_headers, method="PUT"
- )
+ put_req = urllib.request.Request(upload_url, data=data, headers=put_headers, method="PUT")
try:
- with urllib.request.urlopen(put_req, timeout=max(self.timeout, 60)) as resp:
+ with _urlopen(put_req, max(self.timeout, 60)) as resp:
resp.read()
except urllib.error.HTTPError as exc:
raise ThreeWSError(
- f"Image upload failed (HTTP {exc.code}).", code="upload_failed", status=exc.code
+ f"{label} upload failed (HTTP {exc.code}).", code="upload_failed", status=exc.code
) from exc
except urllib.error.URLError as exc:
- raise ThreeWSError(f"Image upload failed: {exc.reason}", code="upload_failed") from exc
+ raise ThreeWSError(f"{label} upload failed: {exc.reason}", code="upload_failed") from exc
return public_url
# -- submit --------------------------------------------------------------
@@ -268,33 +351,174 @@ class ThreeWSClient:
``on_progress(status, elapsed_seconds)`` is called each tick. Raises
ThreeWSError on failure or timeout. ``should_cancel`` lets a host abort.
"""
+ return self._poll_until(
+ f"/api/forge?job={urllib.parse.quote(job_id)}",
+ "glb_url",
+ "Generation",
+ on_progress=on_progress,
+ interval=interval,
+ timeout=timeout,
+ should_cancel=should_cancel,
+ _now=_now,
+ _sleep=_sleep,
+ )
+
+ def _poll_until(
+ self,
+ path: str,
+ result_key: str,
+ label: str,
+ *,
+ on_progress: Optional[Callable[[str, float], None]],
+ interval: float,
+ timeout: float,
+ should_cancel: Optional[Callable[[], bool]],
+ _now: Callable[[], float],
+ _sleep: Callable[[float], None],
+ ) -> str:
start = _now()
- path = f"/api/forge?job={urllib.parse.quote(job_id)}"
while True:
if should_cancel and should_cancel():
- raise ThreeWSError("Generation cancelled.", code="cancelled")
+ raise ThreeWSError(f"{label} cancelled.", code="cancelled")
elapsed = _now() - start
if elapsed > timeout:
- raise ThreeWSError(
- f"Generation timed out after {int(elapsed)}s.", code="timeout"
- )
- result = self._request("GET", path)
- status = result.get("status", "running")
+ raise ThreeWSError(f"{label} timed out after {int(elapsed)}s.", code="timeout")
+ try:
+ result = self._request("GET", path)
+ except ThreeWSError as exc:
+ # A 502/503/504 on a poll is a transient upstream hiccup (the
+ # remesh worker answers 502 while it cold-starts); keep polling.
+ if exc.status in (502, 503, 504):
+ _sleep(interval)
+ continue
+ raise
+ status = result.get("status") or "running"
if on_progress:
on_progress(status, elapsed)
- if status == "done" and result.get("glb_url"):
- return result["glb_url"]
+ if status == "done" and result.get(result_key):
+ return result[result_key]
if status == "failed":
- raise ThreeWSError(result.get("error") or "Generation failed.", code="failed")
+ raise ThreeWSError(result.get("error") or f"{label} failed.", code="failed")
_sleep(interval)
+ # -- rig -----------------------------------------------------------------
+
+ def submit_rig(self, glb_url: str) -> dict:
+ """Start auto-rigging a public GLB; returns ``{job_id, ...}``."""
+ if not _is_web_url(glb_url):
+ raise ThreeWSError("Rigging needs a public GLB URL.", code="invalid_glb_url")
+ result = self._request("POST", "/api/forge?action=rig", body={"glb_url": glb_url})
+ if result.get("error"):
+ raise ThreeWSError(result.get("message") or result["error"], code=result["error"])
+ if not result.get("job_id"):
+ raise ThreeWSError("The rigger returned no job id.", code="no_job")
+ return result
+
+ def rig(
+ self,
+ glb_url: str,
+ *,
+ on_progress: Optional[Callable[[str, float], None]] = None,
+ should_cancel: Optional[Callable[[], bool]] = None,
+ poll_timeout: float = 600.0,
+ _now: Callable[[], float] = time.monotonic,
+ _sleep: Callable[[float], None] = time.sleep,
+ ) -> str:
+ """Auto-rig a GLB with a humanoid skeleton; return the rigged GLB URL."""
+ job = self.submit_rig(glb_url)
+ return self._poll_until(
+ f"/api/forge?job={urllib.parse.quote(job['job_id'])}",
+ "glb_url",
+ "Rigging",
+ on_progress=on_progress,
+ interval=DEFAULT_POLL_INTERVAL,
+ timeout=poll_timeout,
+ should_cancel=should_cancel,
+ _now=_now,
+ _sleep=_sleep,
+ )
+
+ # -- remesh --------------------------------------------------------------
+
+ def submit_remesh(
+ self,
+ mesh_url: str,
+ *,
+ remesh_mode: str = "triangle",
+ operation: str = "full",
+ target_faces: Optional[int] = None,
+ texture_size: int = 1024,
+ ) -> dict:
+ """Start a remesh/retopology job on a public GLB; returns ``{job_id, ...}``."""
+ if not _is_web_url(mesh_url):
+ raise ThreeWSError("Remeshing needs a public mesh URL.", code="invalid_mesh_url")
+ if remesh_mode not in REMESH_MODES:
+ raise ThreeWSError(
+ f"remesh_mode must be one of: {', '.join(REMESH_MODES)}.", code="invalid_mode"
+ )
+ if operation not in REMESH_OPERATIONS:
+ raise ThreeWSError(
+ f"operation must be one of: {', '.join(REMESH_OPERATIONS)}.", code="invalid_operation"
+ )
+ if texture_size not in REMESH_TEXTURE_SIZES:
+ raise ThreeWSError("texture_size must be 512, 1024 or 2048.", code="invalid_texture_size")
+ body = {
+ "mesh_url": mesh_url,
+ "remesh_mode": remesh_mode,
+ "operation": operation,
+ "texture_size": texture_size,
+ "output_format": "glb",
+ }
+ if target_faces and int(target_faces) > 0:
+ body["target_faces"] = int(target_faces)
+ result = self._request("POST", "/api/forge-remesh", body=body)
+ if result.get("error"):
+ raise ThreeWSError(result.get("message") or result["error"], code=result["error"])
+ if not result.get("job_id"):
+ raise ThreeWSError("Mesh processing returned no job id.", code="no_job")
+ return result
+
+ def remesh(
+ self,
+ mesh_url: str,
+ *,
+ remesh_mode: str = "triangle",
+ operation: str = "full",
+ target_faces: Optional[int] = None,
+ texture_size: int = 1024,
+ on_progress: Optional[Callable[[str, float], None]] = None,
+ should_cancel: Optional[Callable[[], bool]] = None,
+ poll_timeout: float = 900.0,
+ _now: Callable[[], float] = time.monotonic,
+ _sleep: Callable[[float], None] = time.sleep,
+ ) -> str:
+ """Remesh a GLB on the remesh worker; return the processed GLB URL."""
+ job = self.submit_remesh(
+ mesh_url,
+ remesh_mode=remesh_mode,
+ operation=operation,
+ target_faces=target_faces,
+ texture_size=texture_size,
+ )
+ return self._poll_until(
+ f"/api/forge-remesh?job={urllib.parse.quote(job['job_id'])}",
+ "result_url",
+ "Mesh processing",
+ on_progress=on_progress,
+ interval=DEFAULT_POLL_INTERVAL,
+ timeout=poll_timeout,
+ should_cancel=should_cancel,
+ _now=_now,
+ _sleep=_sleep,
+ )
+
# -- download ------------------------------------------------------------
def download(self, url: str, dest_path: str) -> str:
"""Stream a GLB (or any URL) to ``dest_path``; return the path."""
req = urllib.request.Request(url, headers={"user-agent": "three-ws-plugin/1.0"})
try:
- with urllib.request.urlopen(req, timeout=max(self.timeout, 120)) as resp, open(
+ with _urlopen(req, max(self.timeout, 120)) as resp, open(
dest_path, "wb"
) as out:
while True:
@@ -306,6 +530,120 @@ class ThreeWSClient:
raise ThreeWSError(f"Download failed: {exc}", code="download_failed") from exc
return dest_path
+ # -- publish into an account --------------------------------------------
+
+ def publish_glb(
+ self,
+ glb_bytes: bytes,
+ *,
+ api_key: str,
+ name: str,
+ description: str = "",
+ visibility: str = "private",
+ tags=(),
+ source_meta: Optional[dict] = None,
+ ) -> dict:
+ """Save a GLB into the API key owner's three.ws account; return the avatar.
+
+ The returned dict is the ``avatar`` object from ``POST /api/avatars``
+ (``id``, ``name``, ``slug``, ``visibility``, ...). Its page lives at
+ ``avatar_page_url(avatar)``. Static meshes are auto-rigged server-side
+ when they are humanoid, exactly like a dashboard upload.
+ """
+ api_key = (api_key or "").strip()
+ if not api_key:
+ raise ThreeWSError(
+ "Publishing needs a three.ws API key with the avatars:write scope. "
+ "Create one at three.ws/dashboard/api.",
+ code="missing_api_key",
+ )
+ name = (name or "").strip()[:120] or "Untitled model"
+ if visibility not in AVATAR_VISIBILITIES:
+ raise ThreeWSError(
+ f"visibility must be one of: {', '.join(AVATAR_VISIBILITIES)}.",
+ code="invalid_visibility",
+ )
+ if not is_glb(glb_bytes):
+ raise ThreeWSError(
+ "That file is not a binary glTF 2.0 (.glb). Export the mesh as GLB first.",
+ code="invalid_glb",
+ )
+ if len(glb_bytes) > MAX_AVATAR_BYTES:
+ raise ThreeWSError("GLB is larger than the 500 MB account limit.", code="too_large")
+
+ auth = {"authorization": f"Bearer {api_key}"}
+ checksum = hashlib.sha256(glb_bytes).hexdigest()
+ slug = slugify(name)
+ if len(glb_bytes) <= MAX_PROXY_UPLOAD_BYTES:
+ query = urllib.parse.urlencode(
+ {"slug": slug, "content_type": "model/gltf-binary", "sha256": checksum}
+ )
+ stored = self._request(
+ "POST",
+ f"/api/avatars/upload?{query}",
+ raw=glb_bytes,
+ headers={**auth, "content-type": "model/gltf-binary"},
+ timeout=max(self.timeout, 120),
+ )
+ storage_key = stored.get("storage_key")
+ size_bytes = stored.get("size_bytes") or len(glb_bytes)
+ checksum = stored.get("checksum_sha256") or checksum
+ else:
+ presign = self._request(
+ "POST",
+ "/api/avatars/presign",
+ body={
+ "size_bytes": len(glb_bytes),
+ "content_type": "model/gltf-binary",
+ "checksum_sha256": checksum,
+ "slug": slug,
+ },
+ headers=auth,
+ )
+ storage_key = presign.get("storage_key")
+ upload_url = presign.get("upload_url")
+ if not storage_key or not upload_url:
+ raise ThreeWSError("Upload presign returned no URL.", code="presign_failed")
+ put_headers = presign.get("headers") or {"content-type": "model/gltf-binary"}
+ put_req = urllib.request.Request(
+ upload_url, data=glb_bytes, headers=put_headers, method="PUT"
+ )
+ try:
+ with _urlopen(put_req, max(self.timeout, 600)) as resp:
+ resp.read()
+ except urllib.error.HTTPError as exc:
+ raise ThreeWSError(
+ f"GLB upload failed (HTTP {exc.code}).", code="upload_failed", status=exc.code
+ ) from exc
+ except urllib.error.URLError as exc:
+ raise ThreeWSError(f"GLB upload failed: {exc.reason}", code="upload_failed") from exc
+ size_bytes = len(glb_bytes)
+ if not storage_key:
+ raise ThreeWSError("Upload returned no storage key.", code="upload_failed")
+
+ body = {
+ "name": name,
+ "storage_key": storage_key,
+ "size_bytes": size_bytes,
+ "content_type": "model/gltf-binary",
+ "checksum_sha256": checksum,
+ "visibility": visibility,
+ "tags": [t.strip()[:40] for t in tags if isinstance(t, str) and t.strip()][:20],
+ "source": "upload",
+ "source_meta": dict(source_meta or {}),
+ }
+ if description.strip():
+ body["description"] = description.strip()[:2000]
+ created = self._request("POST", "/api/avatars", body=body, headers=auth)
+ avatar = created.get("avatar")
+ if not isinstance(avatar, dict) or not avatar.get("id"):
+ raise ThreeWSError("three.ws did not return the saved model.", code="create_failed")
+ return avatar
+
+ def avatar_page_url(self, avatar: dict) -> str:
+ """Public page for an avatar returned by ``publish_glb``."""
+ return f"{self.base_url}/avatars/{urllib.parse.quote(str(avatar.get('id', '')))}"
+
# -- high-level convenience ---------------------------------------------
def generate_text_to_3d(
@@ -347,6 +685,34 @@ class ThreeWSClient:
)
+def is_glb(data: bytes) -> bool:
+ """True when ``data`` starts with a well-formed binary glTF 2.0 header."""
+ if not isinstance(data, (bytes, bytearray)) or len(data) < 12:
+ return False
+ magic = bytes(data[0:4])
+ version = int.from_bytes(data[4:8], "little")
+ length = int.from_bytes(data[8:12], "little")
+ return magic == b"glTF" and version == 2 and length == len(data)
+
+
+def slugify(text: str) -> str:
+ """Lowercase ``[a-z0-9_-]`` slug (max 64) that ``/api/avatars`` accepts."""
+ out = []
+ for ch in (text or "").lower():
+ if ch.isascii() and (ch.isalnum() or ch in "-_"):
+ out.append(ch)
+ elif out and out[-1] != "-":
+ out.append("-")
+ slug = "".join(out).strip("-_")[:64].strip("-_")
+ return slug or "model"
+
+
+def _is_web_url(url) -> bool:
+ """An http(s) URL. The server decides what is publicly reachable (it
+ SSRF-checks every mesh URL); this only stops local paths early."""
+ return isinstance(url, str) and url.startswith(("https://", "http://"))
+
+
def _safe_json(payload: bytes) -> dict:
try:
parsed = json.loads(payload.decode("utf-8"))
diff --git a/integrations/blender/three_ws/__init__.py b/integrations/blender/three_ws/__init__.py
index 80f8e0bbb..d86cb4a9f 100644
--- a/integrations/blender/three_ws/__init__.py
+++ b/integrations/blender/three_ws/__init__.py
@@ -105,6 +105,22 @@ def _prefs(context):
# -- scene properties ---------------------------------------------------------
+_BACKEND_LABELS = {
+ "trellis2": "TRELLIS.2 (free)",
+ "hunyuan3d": "Hunyuan3D (free)",
+ "nvidia": "TRELLIS on NVIDIA (free)",
+ "trellis_selfhost": "TRELLIS self-host (free)",
+ "huggingface": "Hugging Face Spaces (free)",
+ "trellis": "TRELLIS",
+ "triposg": "TripoSG (sketch)",
+ "meshy": "Meshy (your key)",
+ "tripo": "Tripo (your key)",
+ "rodin": "Rodin (your key)",
+ "stability": "Stable Fast 3D (your key)",
+ "replicate_byok": "Replicate (your key)",
+}
+
+
def _enum(items_tuple, labels=None):
labels = labels or {}
return [(v, labels.get(v, v.replace("_", " ").title()), "") for v in items_tuple]
@@ -142,7 +158,7 @@ class ThreeWSProps(PropertyGroup):
backend: EnumProperty(
name="Backend",
items=[("auto", "Auto", "Let three.ws pick the default for the pipeline")]
- + _enum(BACKENDS, {"trellis": "TRELLIS", "meshy": "Meshy", "tripo": "Tripo", "hunyuan3d": "Hunyuan3D"}),
+ + _enum(BACKENDS, _BACKEND_LABELS),
default="auto",
)
aspect_ratio: EnumProperty(
diff --git a/integrations/blender/three_ws/three_ws_client.py b/integrations/blender/three_ws/three_ws_client.py
index dc2ea9a66..98ad00cd9 100644
--- a/integrations/blender/three_ws/three_ws_client.py
+++ b/integrations/blender/three_ws/three_ws_client.py
@@ -1,4 +1,4 @@
-"""three.ws Forge client — shared by the Blender add-on and the ComfyUI nodes.
+"""three.ws Forge client, shared by the Blender add-on, the ComfyUI nodes and the Modly extension.
Single source of truth for the public Forge generation contract
(``api/forge.js`` + ``api/forge-upload.js``). Stdlib-only (``urllib``) so it
@@ -12,10 +12,19 @@ Public contract this wraps
* ``GET /api/forge?job=<id>`` → poll ``{status, glb_url?, error?, backend?, ...}``
* ``GET /api/forge?catalog`` → tier/backend/cost matrix
* ``POST /api/forge-upload`` ``{content_type, size_bytes, checksum_sha256?}`` → presigned PUT
+* ``POST /api/scene-glb-upload`` ``{content_type, size_bytes}`` → presigned PUT for a GLB
+* ``POST /api/forge?action=rig`` ``{glb_url}`` → auto-rig, polled on ``?job=``
+* ``POST /api/forge-remesh`` ``{mesh_url, remesh_mode?, operation?, ...}`` → retopology job
+* ``GET /api/forge-remesh?job=`` → poll ``{status, result_url?, face_count?, error?}``
+* ``POST /api/avatars/upload`` raw GLB body, bearer ``avatars:write`` → ``{storage_key, ...}``
+* ``POST /api/avatars/presign`` ``{size_bytes, content_type, checksum_sha256}`` → presigned PUT (large GLBs)
+* ``POST /api/avatars`` ``{name, storage_key, size_bytes, ...}`` → the saved avatar
Generation is auth-free (IP rate-limited, scoped to an anonymous client handle).
The geometry path (Meshy/Tripo) is BYOK: pass ``provider_key`` and it travels as
-the ``x-forge-provider-key`` header.
+the ``x-forge-provider-key`` header. Publishing a GLB into an account
+(``publish_glb``) is the one authenticated call: it takes an API key from
+three.ws/dashboard/api carrying the ``avatars:write`` scope.
This file is vendored byte-for-byte into each plugin package; the canonical copy
lives at ``integrations/_pyclient/three_ws_client.py`` and a drift test keeps the
@@ -26,6 +35,7 @@ from __future__ import annotations
import hashlib
import json
+import ssl
import time
import urllib.error
import urllib.parse
@@ -41,9 +51,33 @@ DEFAULT_POLL_TIMEOUT = 300.0 # overall ceiling for a generation
# Mirrors api/_lib/forge-tiers.js so the plugins can present choices without a
# network round-trip. ``get_catalog()`` fetches the live matrix when needed.
TIERS = ("draft", "standard", "high")
-PATHS = ("image", "geometry")
-BACKENDS = ("trellis", "meshy", "tripo", "hunyuan3d")
+PATHS = ("image", "geometry", "sketch")
+BACKENDS = (
+ "trellis2",
+ "hunyuan3d",
+ "nvidia",
+ "trellis_selfhost",
+ "huggingface",
+ "trellis",
+ "triposg",
+ "meshy",
+ "tripo",
+ "rodin",
+ "stability",
+ "replicate_byok",
+)
ASPECT_RATIOS = ("1:1", "4:3", "3:4", "16:9", "9:16")
+AVATAR_VISIBILITIES = ("private", "unlisted", "public")
+REMESH_MODES = ("triangle", "quad", "lowpoly")
+REMESH_OPERATIONS = ("full", "simplify", "repair", "convert")
+REMESH_TEXTURE_SIZES = (512, 1024, 2048)
+MAX_SCENE_GLB_BYTES = 200 * 1024 * 1024
+
+# The upload proxy (``/api/avatars/upload``) accepts bodies up to 50 MB and
+# canonicalizes humanoid bone names at ingest. Anything larger goes through the
+# presigned direct-to-storage path instead.
+MAX_PROXY_UPLOAD_BYTES = 50 * 1024 * 1024
+MAX_AVATAR_BYTES = 500 * 1024 * 1024
_CONTENT_TYPE_BY_EXT = {
"png": "image/png",
@@ -53,6 +87,26 @@ _CONTENT_TYPE_BY_EXT = {
}
+def _ssl_context() -> ssl.SSLContext:
+ """CA bundle for HTTPS. Embedded Pythons (Blender, Modly, python.org macOS
+ builds) often ship without system roots, so prefer certifi when present."""
+ try:
+ import certifi # type: ignore
+
+ return ssl.create_default_context(cafile=certifi.where())
+ except ImportError:
+ return ssl.create_default_context()
+
+
+_SSL = _ssl_context()
+
+
+def _urlopen(req: urllib.request.Request, timeout: float):
+ if req.full_url.startswith("https://"):
+ return urllib.request.urlopen(req, timeout=timeout, context=_SSL)
+ return urllib.request.urlopen(req, timeout=timeout)
+
+
class ThreeWSError(Exception):
"""A Forge request failed. ``message`` is safe to show a user."""
@@ -113,16 +167,27 @@ class ThreeWSClient:
headers.update(extra)
return headers
- def _request(self, method: str, path: str, *, body: Optional[dict] = None) -> dict:
+ def _request(
+ self,
+ method: str,
+ path: str,
+ *,
+ body: Optional[dict] = None,
+ raw: Optional[bytes] = None,
+ headers: Optional[dict] = None,
+ timeout: Optional[float] = None,
+ ) -> dict:
url = f"{self.base_url}{path}"
data = None
- headers = self._headers()
+ merged = self._headers(headers)
if body is not None:
data = json.dumps(body).encode("utf-8")
- headers["content-type"] = "application/json"
- req = urllib.request.Request(url, data=data, headers=headers, method=method)
+ merged["content-type"] = "application/json"
+ elif raw is not None:
+ data = raw
+ req = urllib.request.Request(url, data=data, headers=merged, method=method)
try:
- with urllib.request.urlopen(req, timeout=self.timeout) as resp:
+ with _urlopen(req, timeout or self.timeout) as resp:
payload = resp.read()
except urllib.error.HTTPError as exc:
payload = exc.read()
@@ -165,23 +230,41 @@ class ThreeWSClient:
"checksum_sha256": checksum,
},
)
+ return self._put_presigned(presign, image_bytes, content_type, "Image")
+
+ def upload_glb(self, glb_bytes: bytes) -> str:
+ """Presign + PUT a binary glTF, returning its public URL.
+
+ Rigging and remeshing take a public mesh URL, so a mesh that exists only
+ on the caller's disk goes up through ``/api/scene-glb-upload`` first.
+ """
+ if not is_glb(glb_bytes):
+ raise ThreeWSError("Mesh must be a binary glTF 2.0 (.glb) file.", code="invalid_glb")
+ if len(glb_bytes) > MAX_SCENE_GLB_BYTES:
+ raise ThreeWSError("Mesh is larger than the 200 MB upload limit.", code="too_large")
+ presign = self._request(
+ "POST",
+ "/api/scene-glb-upload",
+ body={"content_type": "model/gltf-binary", "size_bytes": len(glb_bytes)},
+ )
+ return self._put_presigned(presign, glb_bytes, "model/gltf-binary", "Mesh")
+
+ def _put_presigned(self, presign: dict, data: bytes, content_type: str, label: str) -> str:
upload_url = presign.get("upload_url")
public_url = presign.get("public_url")
if not upload_url or not public_url:
raise ThreeWSError("Upload presign returned no URL.", code="presign_failed")
put_headers = presign.get("headers") or {"content-type": content_type}
- put_req = urllib.request.Request(
- upload_url, data=image_bytes, headers=put_headers, method="PUT"
- )
+ put_req = urllib.request.Request(upload_url, data=data, headers=put_headers, method="PUT")
try:
- with urllib.request.urlopen(put_req, timeout=max(self.timeout, 60)) as resp:
+ with _urlopen(put_req, max(self.timeout, 60)) as resp:
resp.read()
except urllib.error.HTTPError as exc:
raise ThreeWSError(
- f"Image upload failed (HTTP {exc.code}).", code="upload_failed", status=exc.code
+ f"{label} upload failed (HTTP {exc.code}).", code="upload_failed", status=exc.code
) from exc
except urllib.error.URLError as exc:
- raise ThreeWSError(f"Image upload failed: {exc.reason}", code="upload_failed") from exc
+ raise ThreeWSError(f"{label} upload failed: {exc.reason}", code="upload_failed") from exc
return public_url
# -- submit --------------------------------------------------------------
@@ -268,33 +351,174 @@ class ThreeWSClient:
``on_progress(status, elapsed_seconds)`` is called each tick. Raises
ThreeWSError on failure or timeout. ``should_cancel`` lets a host abort.
"""
+ return self._poll_until(
+ f"/api/forge?job={urllib.parse.quote(job_id)}",
+ "glb_url",
+ "Generation",
+ on_progress=on_progress,
+ interval=interval,
+ timeout=timeout,
+ should_cancel=should_cancel,
+ _now=_now,
+ _sleep=_sleep,
+ )
+
+ def _poll_until(
+ self,
+ path: str,
+ result_key: str,
+ label: str,
+ *,
+ on_progress: Optional[Callable[[str, float], None]],
+ interval: float,
+ timeout: float,
+ should_cancel: Optional[Callable[[], bool]],
+ _now: Callable[[], float],
+ _sleep: Callable[[float], None],
+ ) -> str:
start = _now()
- path = f"/api/forge?job={urllib.parse.quote(job_id)}"
while True:
if should_cancel and should_cancel():
- raise ThreeWSError("Generation cancelled.", code="cancelled")
+ raise ThreeWSError(f"{label} cancelled.", code="cancelled")
elapsed = _now() - start
if elapsed > timeout:
- raise ThreeWSError(
- f"Generation timed out after {int(elapsed)}s.", code="timeout"
- )
- result = self._request("GET", path)
- status = result.get("status", "running")
+ raise ThreeWSError(f"{label} timed out after {int(elapsed)}s.", code="timeout")
+ try:
+ result = self._request("GET", path)
+ except ThreeWSError as exc:
+ # A 502/503/504 on a poll is a transient upstream hiccup (the
+ # remesh worker answers 502 while it cold-starts); keep polling.
+ if exc.status in (502, 503, 504):
+ _sleep(interval)
+ continue
+ raise
+ status = result.get("status") or "running"
if on_progress:
on_progress(status, elapsed)
- if status == "done" and result.get("glb_url"):
- return result["glb_url"]
+ if status == "done" and result.get(result_key):
+ return result[result_key]
if status == "failed":
- raise ThreeWSError(result.get("error") or "Generation failed.", code="failed")
+ raise ThreeWSError(result.get("error") or f"{label} failed.", code="failed")
_sleep(interval)
+ # -- rig -----------------------------------------------------------------
+
+ def submit_rig(self, glb_url: str) -> dict:
+ """Start auto-rigging a public GLB; returns ``{job_id, ...}``."""
+ if not _is_web_url(glb_url):
+ raise ThreeWSError("Rigging needs a public GLB URL.", code="invalid_glb_url")
+ result = self._request("POST", "/api/forge?action=rig", body={"glb_url": glb_url})
+ if result.get("error"):
+ raise ThreeWSError(result.get("message") or result["error"], code=result["error"])
+ if not result.get("job_id"):
+ raise ThreeWSError("The rigger returned no job id.", code="no_job")
+ return result
+
+ def rig(
+ self,
+ glb_url: str,
+ *,
+ on_progress: Optional[Callable[[str, float], None]] = None,
+ should_cancel: Optional[Callable[[], bool]] = None,
+ poll_timeout: float = 600.0,
+ _now: Callable[[], float] = time.monotonic,
+ _sleep: Callable[[float], None] = time.sleep,
+ ) -> str:
+ """Auto-rig a GLB with a humanoid skeleton; return the rigged GLB URL."""
+ job = self.submit_rig(glb_url)
+ return self._poll_until(
+ f"/api/forge?job={urllib.parse.quote(job['job_id'])}",
+ "glb_url",
+ "Rigging",
+ on_progress=on_progress,
+ interval=DEFAULT_POLL_INTERVAL,
+ timeout=poll_timeout,
+ should_cancel=should_cancel,
+ _now=_now,
+ _sleep=_sleep,
+ )
+
+ # -- remesh --------------------------------------------------------------
+
+ def submit_remesh(
+ self,
+ mesh_url: str,
+ *,
+ remesh_mode: str = "triangle",
+ operation: str = "full",
+ target_faces: Optional[int] = None,
+ texture_size: int = 1024,
+ ) -> dict:
+ """Start a remesh/retopology job on a public GLB; returns ``{job_id, ...}``."""
+ if not _is_web_url(mesh_url):
+ raise ThreeWSError("Remeshing needs a public mesh URL.", code="invalid_mesh_url")
+ if remesh_mode not in REMESH_MODES:
+ raise ThreeWSError(
+ f"remesh_mode must be one of: {', '.join(REMESH_MODES)}.", code="invalid_mode"
+ )
+ if operation not in REMESH_OPERATIONS:
+ raise ThreeWSError(
+ f"operation must be one of: {', '.join(REMESH_OPERATIONS)}.", code="invalid_operation"
+ )
+ if texture_size not in REMESH_TEXTURE_SIZES:
+ raise ThreeWSError("texture_size must be 512, 1024 or 2048.", code="invalid_texture_size")
+ body = {
+ "mesh_url": mesh_url,
+ "remesh_mode": remesh_mode,
+ "operation": operation,
+ "texture_size": texture_size,
+ "output_format": "glb",
+ }
+ if target_faces and int(target_faces) > 0:
+ body["target_faces"] = int(target_faces)
+ result = self._request("POST", "/api/forge-remesh", body=body)
+ if result.get("error"):
+ raise ThreeWSError(result.get("message") or result["error"], code=result["error"])
+ if not result.get("job_id"):
+ raise ThreeWSError("Mesh processing returned no job id.", code="no_job")
+ return result
+
+ def remesh(
+ self,
+ mesh_url: str,
+ *,
+ remesh_mode: str = "triangle",
+ operation: str = "full",
+ target_faces: Optional[int] = None,
+ texture_size: int = 1024,
+ on_progress: Optional[Callable[[str, float], None]] = None,
+ should_cancel: Optional[Callable[[], bool]] = None,
+ poll_timeout: float = 900.0,
+ _now: Callable[[], float] = time.monotonic,
+ _sleep: Callable[[float], None] = time.sleep,
+ ) -> str:
+ """Remesh a GLB on the remesh worker; return the processed GLB URL."""
+ job = self.submit_remesh(
+ mesh_url,
+ remesh_mode=remesh_mode,
+ operation=operation,
+ target_faces=target_faces,
+ texture_size=texture_size,
+ )
+ return self._poll_until(
+ f"/api/forge-remesh?job={urllib.parse.quote(job['job_id'])}",
+ "result_url",
+ "Mesh processing",
+ on_progress=on_progress,
+ interval=DEFAULT_POLL_INTERVAL,
+ timeout=poll_timeout,
+ should_cancel=should_cancel,
+ _now=_now,
+ _sleep=_sleep,
+ )
+
# -- download ------------------------------------------------------------
def download(self, url: str, dest_path: str) -> str:
"""Stream a GLB (or any URL) to ``dest_path``; return the path."""
req = urllib.request.Request(url, headers={"user-agent": "three-ws-plugin/1.0"})
try:
- with urllib.request.urlopen(req, timeout=max(self.timeout, 120)) as resp, open(
+ with _urlopen(req, max(self.timeout, 120)) as resp, open(
dest_path, "wb"
) as out:
while True:
@@ -306,6 +530,120 @@ class ThreeWSClient:
raise ThreeWSError(f"Download failed: {exc}", code="download_failed") from exc
return dest_path
+ # -- publish into an account --------------------------------------------
+
+ def publish_glb(
+ self,
+ glb_bytes: bytes,
+ *,
+ api_key: str,
+ name: str,
+ description: str = "",
+ visibility: str = "private",
+ tags=(),
+ source_meta: Optional[dict] = None,
+ ) -> dict:
+ """Save a GLB into the API key owner's three.ws account; return the avatar.
+
+ The returned dict is the ``avatar`` object from ``POST /api/avatars``
+ (``id``, ``name``, ``slug``, ``visibility``, ...). Its page lives at
+ ``avatar_page_url(avatar)``. Static meshes are auto-rigged server-side
+ when they are humanoid, exactly like a dashboard upload.
+ """
+ api_key = (api_key or "").strip()
+ if not api_key:
+ raise ThreeWSError(
+ "Publishing needs a three.ws API key with the avatars:write scope. "
+ "Create one at three.ws/dashboard/api.",
+ code="missing_api_key",
+ )
+ name = (name or "").strip()[:120] or "Untitled model"
+ if visibility not in AVATAR_VISIBILITIES:
+ raise ThreeWSError(
+ f"visibility must be one of: {', '.join(AVATAR_VISIBILITIES)}.",
+ code="invalid_visibility",
+ )
+ if not is_glb(glb_bytes):
+ raise ThreeWSError(
+ "That file is not a binary glTF 2.0 (.glb). Export the mesh as GLB first.",
+ code="invalid_glb",
+ )
+ if len(glb_bytes) > MAX_AVATAR_BYTES:
+ raise ThreeWSError("GLB is larger than the 500 MB account limit.", code="too_large")
+
+ auth = {"authorization": f"Bearer {api_key}"}
+ checksum = hashlib.sha256(glb_bytes).hexdigest()
+ slug = slugify(name)
+ if len(glb_bytes) <= MAX_PROXY_UPLOAD_BYTES:
+ query = urllib.parse.urlencode(
+ {"slug": slug, "content_type": "model/gltf-binary", "sha256": checksum}
+ )
+ stored = self._request(
+ "POST",
+ f"/api/avatars/upload?{query}",
+ raw=glb_bytes,
+ headers={**auth, "content-type": "model/gltf-binary"},
+ timeout=max(self.timeout, 120),
+ )
+ storage_key = stored.get("storage_key")
+ size_bytes = stored.get("size_bytes") or len(glb_bytes)
+ checksum = stored.get("checksum_sha256") or checksum
+ else:
+ presign = self._request(
+ "POST",
+ "/api/avatars/presign",
+ body={
+ "size_bytes": len(glb_bytes),
+ "content_type": "model/gltf-binary",
+ "checksum_sha256": checksum,
+ "slug": slug,
+ },
+ headers=auth,
+ )
+ storage_key = presign.get("storage_key")
+ upload_url = presign.get("upload_url")
+ if not storage_key or not upload_url:
+ raise ThreeWSError("Upload presign returned no URL.", code="presign_failed")
+ put_headers = presign.get("headers") or {"content-type": "model/gltf-binary"}
+ put_req = urllib.request.Request(
+ upload_url, data=glb_bytes, headers=put_headers, method="PUT"
+ )
+ try:
+ with _urlopen(put_req, max(self.timeout, 600)) as resp:
+ resp.read()
+ except urllib.error.HTTPError as exc:
+ raise ThreeWSError(
+ f"GLB upload failed (HTTP {exc.code}).", code="upload_failed", status=exc.code
+ ) from exc
+ except urllib.error.URLError as exc:
+ raise ThreeWSError(f"GLB upload failed: {exc.reason}", code="upload_failed") from exc
+ size_bytes = len(glb_bytes)
+ if not storage_key:
+ raise ThreeWSError("Upload returned no storage key.", code="upload_failed")
+
+ body = {
+ "name": name,
+ "storage_key": storage_key,
+ "size_bytes": size_bytes,
+ "content_type": "model/gltf-binary",
+ "checksum_sha256": checksum,
+ "visibility": visibility,
+ "tags": [t.strip()[:40] for t in tags if isinstance(t, str) and t.strip()][:20],
+ "source": "upload",
+ "source_meta": dict(source_meta or {}),
+ }
+ if description.strip():
+ body["description"] = description.strip()[:2000]
+ created = self._request("POST", "/api/avatars", body=body, headers=auth)
+ avatar = created.get("avatar")
+ if not isinstance(avatar, dict) or not avatar.get("id"):
+ raise ThreeWSError("three.ws did not return the saved model.", code="create_failed")
+ return avatar
+
+ def avatar_page_url(self, avatar: dict) -> str:
+ """Public page for an avatar returned by ``publish_glb``."""
+ return f"{self.base_url}/avatars/{urllib.parse.quote(str(avatar.get('id', '')))}"
+
# -- high-level convenience ---------------------------------------------
def generate_text_to_3d(
@@ -347,6 +685,34 @@ class ThreeWSClient:
)
+def is_glb(data: bytes) -> bool:
+ """True when ``data`` starts with a well-formed binary glTF 2.0 header."""
+ if not isinstance(data, (bytes, bytearray)) or len(data) < 12:
+ return False
+ magic = bytes(data[0:4])
+ version = int.from_bytes(data[4:8], "little")
+ length = int.from_bytes(data[8:12], "little")
+ return magic == b"glTF" and version == 2 and length == len(data)
+
+
+def slugify(text: str) -> str:
+ """Lowercase ``[a-z0-9_-]`` slug (max 64) that ``/api/avatars`` accepts."""
+ out = []
+ for ch in (text or "").lower():
+ if ch.isascii() and (ch.isalnum() or ch in "-_"):
+ out.append(ch)
+ elif out and out[-1] != "-":
+ out.append("-")
+ slug = "".join(out).strip("-_")[:64].strip("-_")
+ return slug or "model"
+
+
+def _is_web_url(url) -> bool:
+ """An http(s) URL. The server decides what is publicly reachable (it
+ SSRF-checks every mesh URL); this only stops local paths early."""
+ return isinstance(url, str) and url.startswith(("https://", "http://"))
+
+
def _safe_json(payload: bytes) -> dict:
try:
parsed = json.loads(payload.decode("utf-8"))
diff --git a/integrations/comfyui/three_ws_nodes/three_ws_client.py b/integrations/comfyui/three_ws_nodes/three_ws_client.py
index dc2ea9a66..98ad00cd9 100644
--- a/integrations/comfyui/three_ws_nodes/three_ws_client.py
+++ b/integrations/comfyui/three_ws_nodes/three_ws_client.py
@@ -1,4 +1,4 @@
-"""three.ws Forge client — shared by the Blender add-on and the ComfyUI nodes.
+"""three.ws Forge client, shared by the Blender add-on, the ComfyUI nodes and the Modly extension.
Single source of truth for the public Forge generation contract
(``api/forge.js`` + ``api/forge-upload.js``). Stdlib-only (``urllib``) so it
@@ -12,10 +12,19 @@ Public contract this wraps
* ``GET /api/forge?job=<id>`` → poll ``{status, glb_url?, error?, backend?, ...}``
* ``GET /api/forge?catalog`` → tier/backend/cost matrix
* ``POST /api/forge-upload`` ``{content_type, size_bytes, checksum_sha256?}`` → presigned PUT
+* ``POST /api/scene-glb-upload`` ``{content_type, size_bytes}`` → presigned PUT for a GLB
+* ``POST /api/forge?action=rig`` ``{glb_url}`` → auto-rig, polled on ``?job=``
+* ``POST /api/forge-remesh`` ``{mesh_url, remesh_mode?, operation?, ...}`` → retopology job
+* ``GET /api/forge-remesh?job=`` → poll ``{status, result_url?, face_count?, error?}``
+* ``POST /api/avatars/upload`` raw GLB body, bearer ``avatars:write`` → ``{storage_key, ...}``
+* ``POST /api/avatars/presign`` ``{size_bytes, content_type, checksum_sha256}`` → presigned PUT (large GLBs)
+* ``POST /api/avatars`` ``{name, storage_key, size_bytes, ...}`` → the saved avatar
Generation is auth-free (IP rate-limited, scoped to an anonymous client handle).
The geometry path (Meshy/Tripo) is BYOK: pass ``provider_key`` and it travels as
-the ``x-forge-provider-key`` header.
+the ``x-forge-provider-key`` header. Publishing a GLB into an account
+(``publish_glb``) is the one authenticated call: it takes an API key from
+three.ws/dashboard/api carrying the ``avatars:write`` scope.
This file is vendored byte-for-byte into each plugin package; the canonical copy
lives at ``integrations/_pyclient/three_ws_client.py`` and a drift test keeps the
@@ -26,6 +35,7 @@ from __future__ import annotations
import hashlib
import json
+import ssl
import time
import urllib.error
import urllib.parse
@@ -41,9 +51,33 @@ DEFAULT_POLL_TIMEOUT = 300.0 # overall ceiling for a generation
# Mirrors api/_lib/forge-tiers.js so the plugins can present choices without a
# network round-trip. ``get_catalog()`` fetches the live matrix when needed.
TIERS = ("draft", "standard", "high")
-PATHS = ("image", "geometry")
-BACKENDS = ("trellis", "meshy", "tripo", "hunyuan3d")
+PATHS = ("image", "geometry", "sketch")
+BACKENDS = (
+ "trellis2",
+ "hunyuan3d",
+ "nvidia",
+ "trellis_selfhost",
+ "huggingface",
+ "trellis",
+ "triposg",
+ "meshy",
+ "tripo",
+ "rodin",
+ "stability",
+ "replicate_byok",
+)
ASPECT_RATIOS = ("1:1", "4:3", "3:4", "16:9", "9:16")
+AVATAR_VISIBILITIES = ("private", "unlisted", "public")
+REMESH_MODES = ("triangle", "quad", "lowpoly")
+REMESH_OPERATIONS = ("full", "simplify", "repair", "convert")
+REMESH_TEXTURE_SIZES = (512, 1024, 2048)
+MAX_SCENE_GLB_BYTES = 200 * 1024 * 1024
+
+# The upload proxy (``/api/avatars/upload``) accepts bodies up to 50 MB and
+# canonicalizes humanoid bone names at ingest. Anything larger goes through the
+# presigned direct-to-storage path instead.
+MAX_PROXY_UPLOAD_BYTES = 50 * 1024 * 1024
+MAX_AVATAR_BYTES = 500 * 1024 * 1024
_CONTENT_TYPE_BY_EXT = {
"png": "image/png",
@@ -53,6 +87,26 @@ _CONTENT_TYPE_BY_EXT = {
}
+def _ssl_context() -> ssl.SSLContext:
+ """CA bundle for HTTPS. Embedded Pythons (Blender, Modly, python.org macOS
+ builds) often ship without system roots, so prefer certifi when present."""
+ try:
+ import certifi # type: ignore
+
+ return ssl.create_default_context(cafile=certifi.where())
+ except ImportError:
+ return ssl.create_default_context()
+
+
+_SSL = _ssl_context()
+
+
+def _urlopen(req: urllib.request.Request, timeout: float):
+ if req.full_url.startswith("https://"):
+ return urllib.request.urlopen(req, timeout=timeout, context=_SSL)
+ return urllib.request.urlopen(req, timeout=timeout)
+
+
class ThreeWSError(Exception):
"""A Forge request failed. ``message`` is safe to show a user."""
@@ -113,16 +167,27 @@ class ThreeWSClient:
headers.update(extra)
return headers
- def _request(self, method: str, path: str, *, body: Optional[dict] = None) -> dict:
+ def _request(
+ self,
+ method: str,
+ path: str,
+ *,
+ body: Optional[dict] = None,
+ raw: Optional[bytes] = None,
+ headers: Optional[dict] = None,
+ timeout: Optional[float] = None,
+ ) -> dict:
url = f"{self.base_url}{path}"
data = None
- headers = self._headers()
+ merged = self._headers(headers)
if body is not None:
data = json.dumps(body).encode("utf-8")
- headers["content-type"] = "application/json"
- req = urllib.request.Request(url, data=data, headers=headers, method=method)
+ merged["content-type"] = "application/json"
+ elif raw is not None:
+ data = raw
+ req = urllib.request.Request(url, data=data, headers=merged, method=method)
try:
- with urllib.request.urlopen(req, timeout=self.timeout) as resp:
+ with _urlopen(req, timeout or self.timeout) as resp:
payload = resp.read()
except urllib.error.HTTPError as exc:
payload = exc.read()
@@ -165,23 +230,41 @@ class ThreeWSClient:
"checksum_sha256": checksum,
},
)
+ return self._put_presigned(presign, image_bytes, content_type, "Image")
+
+ def upload_glb(self, glb_bytes: bytes) -> str:
+ """Presign + PUT a binary glTF, returning its public URL.
+
+ Rigging and remeshing take a public mesh URL, so a mesh that exists only
+ on the caller's disk goes up through ``/api/scene-glb-upload`` first.
+ """
+ if not is_glb(glb_bytes):
+ raise ThreeWSError("Mesh must be a binary glTF 2.0 (.glb) file.", code="invalid_glb")
+ if len(glb_bytes) > MAX_SCENE_GLB_BYTES:
+ raise ThreeWSError("Mesh is larger than the 200 MB upload limit.", code="too_large")
+ presign = self._request(
+ "POST",
+ "/api/scene-glb-upload",
+ body={"content_type": "model/gltf-binary", "size_bytes": len(glb_bytes)},
+ )
+ return self._put_presigned(presign, glb_bytes, "model/gltf-binary", "Mesh")
+
+ def _put_presigned(self, presign: dict, data: bytes, content_type: str, label: str) -> str:
upload_url = presign.get("upload_url")
public_url = presign.get("public_url")
if not upload_url or not public_url:
raise ThreeWSError("Upload presign returned no URL.", code="presign_failed")
put_headers = presign.get("headers") or {"content-type": content_type}
- put_req = urllib.request.Request(
- upload_url, data=image_bytes, headers=put_headers, method="PUT"
- )
+ put_req = urllib.request.Request(upload_url, data=data, headers=put_headers, method="PUT")
try:
- with urllib.request.urlopen(put_req, timeout=max(self.timeout, 60)) as resp:
+ with _urlopen(put_req, max(self.timeout, 60)) as resp:
resp.read()
except urllib.error.HTTPError as exc:
raise ThreeWSError(
- f"Image upload failed (HTTP {exc.code}).", code="upload_failed", status=exc.code
+ f"{label} upload failed (HTTP {exc.code}).", code="upload_failed", status=exc.code
) from exc
except urllib.error.URLError as exc:
- raise ThreeWSError(f"Image upload failed: {exc.reason}", code="upload_failed") from exc
+ raise ThreeWSError(f"{label} upload failed: {exc.reason}", code="upload_failed") from exc
return public_url
# -- submit --------------------------------------------------------------
@@ -268,33 +351,174 @@ class ThreeWSClient:
``on_progress(status, elapsed_seconds)`` is called each tick. Raises
ThreeWSError on failure or timeout. ``should_cancel`` lets a host abort.
"""
+ return self._poll_until(
+ f"/api/forge?job={urllib.parse.quote(job_id)}",
+ "glb_url",
+ "Generation",
+ on_progress=on_progress,
+ interval=interval,
+ timeout=timeout,
+ should_cancel=should_cancel,
+ _now=_now,
+ _sleep=_sleep,
+ )
+
+ def _poll_until(
+ self,
+ path: str,
+ result_key: str,
+ label: str,
+ *,
+ on_progress: Optional[Callable[[str, float], None]],
+ interval: float,
+ timeout: float,
+ should_cancel: Optional[Callable[[], bool]],
+ _now: Callable[[], float],
+ _sleep: Callable[[float], None],
+ ) -> str:
start = _now()
- path = f"/api/forge?job={urllib.parse.quote(job_id)}"
while True:
if should_cancel and should_cancel():
- raise ThreeWSError("Generation cancelled.", code="cancelled")
+ raise ThreeWSError(f"{label} cancelled.", code="cancelled")
elapsed = _now() - start
if elapsed > timeout:
- raise ThreeWSError(
- f"Generation timed out after {int(elapsed)}s.", code="timeout"
- )
- result = self._request("GET", path)
- status = result.get("status", "running")
+ raise ThreeWSError(f"{label} timed out after {int(elapsed)}s.", code="timeout")
+ try:
+ result = self._request("GET", path)
+ except ThreeWSError as exc:
+ # A 502/503/504 on a poll is a transient upstream hiccup (the
+ # remesh worker answers 502 while it cold-starts); keep polling.
+ if exc.status in (502, 503, 504):
+ _sleep(interval)
+ continue
+ raise
+ status = result.get("status") or "running"
if on_progress:
on_progress(status, elapsed)
- if status == "done" and result.get("glb_url"):
- return result["glb_url"]
+ if status == "done" and result.get(result_key):
+ return result[result_key]
if status == "failed":
- raise ThreeWSError(result.get("error") or "Generation failed.", code="failed")
+ raise ThreeWSError(result.get("error") or f"{label} failed.", code="failed")
_sleep(interval)
+ # -- rig -----------------------------------------------------------------
+
+ def submit_rig(self, glb_url: str) -> dict:
+ """Start auto-rigging a public GLB; returns ``{job_id, ...}``."""
+ if not _is_web_url(glb_url):
+ raise ThreeWSError("Rigging needs a public GLB URL.", code="invalid_glb_url")
+ result = self._request("POST", "/api/forge?action=rig", body={"glb_url": glb_url})
+ if result.get("error"):
+ raise ThreeWSError(result.get("message") or result["error"], code=result["error"])
+ if not result.get("job_id"):
+ raise ThreeWSError("The rigger returned no job id.", code="no_job")
+ return result
+
+ def rig(
+ self,
+ glb_url: str,
+ *,
+ on_progress: Optional[Callable[[str, float], None]] = None,
+ should_cancel: Optional[Callable[[], bool]] = None,
+ poll_timeout: float = 600.0,
+ _now: Callable[[], float] = time.monotonic,
+ _sleep: Callable[[float], None] = time.sleep,
+ ) -> str:
+ """Auto-rig a GLB with a humanoid skeleton; return the rigged GLB URL."""
+ job = self.submit_rig(glb_url)
+ return self._poll_until(
+ f"/api/forge?job={urllib.parse.quote(job['job_id'])}",
+ "glb_url",
+ "Rigging",
+ on_progress=on_progress,
+ interval=DEFAULT_POLL_INTERVAL,
+ timeout=poll_timeout,
+ should_cancel=should_cancel,
+ _now=_now,
+ _sleep=_sleep,
+ )
+
+ # -- remesh --------------------------------------------------------------
+
+ def submit_remesh(
+ self,
+ mesh_url: str,
+ *,
+ remesh_mode: str = "triangle",
+ operation: str = "full",
+ target_faces: Optional[int] = None,
+ texture_size: int = 1024,
+ ) -> dict:
+ """Start a remesh/retopology job on a public GLB; returns ``{job_id, ...}``."""
+ if not _is_web_url(mesh_url):
+ raise ThreeWSError("Remeshing needs a public mesh URL.", code="invalid_mesh_url")
+ if remesh_mode not in REMESH_MODES:
+ raise ThreeWSError(
+ f"remesh_mode must be one of: {', '.join(REMESH_MODES)}.", code="invalid_mode"
+ )
+ if operation not in REMESH_OPERATIONS:
+ raise ThreeWSError(
+ f"operation must be one of: {', '.join(REMESH_OPERATIONS)}.", code="invalid_operation"
+ )
+ if texture_size not in REMESH_TEXTURE_SIZES:
+ raise ThreeWSError("texture_size must be 512, 1024 or 2048.", code="invalid_texture_size")
+ body = {
+ "mesh_url": mesh_url,
+ "remesh_mode": remesh_mode,
+ "operation": operation,
+ "texture_size": texture_size,
+ "output_format": "glb",
+ }
+ if target_faces and int(target_faces) > 0:
+ body["target_faces"] = int(target_faces)
+ result = self._request("POST", "/api/forge-remesh", body=body)
+ if result.get("error"):
+ raise ThreeWSError(result.get("message") or result["error"], code=result["error"])
+ if not result.get("job_id"):
+ raise ThreeWSError("Mesh processing returned no job id.", code="no_job")
+ return result
+
+ def remesh(
+ self,
+ mesh_url: str,
+ *,
+ remesh_mode: str = "triangle",
+ operation: str = "full",
+ target_faces: Optional[int] = None,
+ texture_size: int = 1024,
+ on_progress: Optional[Callable[[str, float], None]] = None,
+ should_cancel: Optional[Callable[[], bool]] = None,
+ poll_timeout: float = 900.0,
+ _now: Callable[[], float] = time.monotonic,
+ _sleep: Callable[[float], None] = time.sleep,
+ ) -> str:
+ """Remesh a GLB on the remesh worker; return the processed GLB URL."""
+ job = self.submit_remesh(
+ mesh_url,
+ remesh_mode=remesh_mode,
+ operation=operation,
+ target_faces=target_faces,
+ texture_size=texture_size,
+ )
+ return self._poll_until(
+ f"/api/forge-remesh?job={urllib.parse.quote(job['job_id'])}",
+ "result_url",
+ "Mesh processing",
+ on_progress=on_progress,
+ interval=DEFAULT_POLL_INTERVAL,
+ timeout=poll_timeout,
+ should_cancel=should_cancel,
+ _now=_now,
+ _sleep=_sleep,
+ )
+
# -- download ------------------------------------------------------------
def download(self, url: str, dest_path: str) -> str:
"""Stream a GLB (or any URL) to ``dest_path``; return the path."""
req = urllib.request.Request(url, headers={"user-agent": "three-ws-plugin/1.0"})
try:
- with urllib.request.urlopen(req, timeout=max(self.timeout, 120)) as resp, open(
+ with _urlopen(req, max(self.timeout, 120)) as resp, open(
dest_path, "wb"
) as out:
while True:
@@ -306,6 +530,120 @@ class ThreeWSClient:
raise ThreeWSError(f"Download failed: {exc}", code="download_failed") from exc
return dest_path
+ # -- publish into an account --------------------------------------------
+
+ def publish_glb(
+ self,
+ glb_bytes: bytes,
+ *,
+ api_key: str,
+ name: str,
+ description: str = "",
+ visibility: str = "private",
+ tags=(),
+ source_meta: Optional[dict] = None,
+ ) -> dict:
+ """Save a GLB into the API key owner's three.ws account; return the avatar.
+
+ The returned dict is the ``avatar`` object from ``POST /api/avatars``
+ (``id``, ``name``, ``slug``, ``visibility``, ...). Its page lives at
+ ``avatar_page_url(avatar)``. Static meshes are auto-rigged server-side
+ when they are humanoid, exactly like a dashboard upload.
+ """
+ api_key = (api_key or "").strip()
+ if not api_key:
+ raise ThreeWSError(
+ "Publishing needs a three.ws API key with the avatars:write scope. "
+ "Create one at three.ws/dashboard/api.",
+ code="missing_api_key",
+ )
+ name = (name or "").strip()[:120] or "Untitled model"
+ if visibility not in AVATAR_VISIBILITIES:
+ raise ThreeWSError(
+ f"visibility must be one of: {', '.join(AVATAR_VISIBILITIES)}.",
+ code="invalid_visibility",
+ )
+ if not is_glb(glb_bytes):
+ raise ThreeWSError(
+ "That file is not a binary glTF 2.0 (.glb). Export the mesh as GLB first.",
+ code="invalid_glb",
+ )
+ if len(glb_bytes) > MAX_AVATAR_BYTES:
+ raise ThreeWSError("GLB is larger than the 500 MB account limit.", code="too_large")
+
+ auth = {"authorization": f"Bearer {api_key}"}
+ checksum = hashlib.sha256(glb_bytes).hexdigest()
+ slug = slugify(name)
+ if len(glb_bytes) <= MAX_PROXY_UPLOAD_BYTES:
+ query = urllib.parse.urlencode(
+ {"slug": slug, "content_type": "model/gltf-binary", "sha256": checksum}
+ )
+ stored = self._request(
+ "POST",
+ f"/api/avatars/upload?{query}",
+ raw=glb_bytes,
+ headers={**auth, "content-type": "model/gltf-binary"},
+ timeout=max(self.timeout, 120),
+ )
+ storage_key = stored.get("storage_key")
+ size_bytes = stored.get("size_bytes") or len(glb_bytes)
+ checksum = stored.get("checksum_sha256") or checksum
+ else:
+ presign = self._request(
+ "POST",
+ "/api/avatars/presign",
+ body={
+ "size_bytes": len(glb_bytes),
+ "content_type": "model/gltf-binary",
+ "checksum_sha256": checksum,
+ "slug": slug,
+ },
+ headers=auth,
+ )
+ storage_key = presign.get("storage_key")
+ upload_url = presign.get("upload_url")
+ if not storage_key or not upload_url:
+ raise ThreeWSError("Upload presign returned no URL.", code="presign_failed")
+ put_headers = presign.get("headers") or {"content-type": "model/gltf-binary"}
+ put_req = urllib.request.Request(
+ upload_url, data=glb_bytes, headers=put_headers, method="PUT"
+ )
+ try:
+ with _urlopen(put_req, max(self.timeout, 600)) as resp:
+ resp.read()
+ except urllib.error.HTTPError as exc:
+ raise ThreeWSError(
+ f"GLB upload failed (HTTP {exc.code}).", code="upload_failed", status=exc.code
+ ) from exc
+ except urllib.error.URLError as exc:
+ raise ThreeWSError(f"GLB upload failed: {exc.reason}", code="upload_failed") from exc
+ size_bytes = len(glb_bytes)
+ if not storage_key:
+ raise ThreeWSError("Upload returned no storage key.", code="upload_failed")
+
+ body = {
+ "name": name,
+ "storage_key": storage_key,
+ "size_bytes": size_bytes,
+ "content_type": "model/gltf-binary",
+ "checksum_sha256": checksum,
+ "visibility": visibility,
+ "tags": [t.strip()[:40] for t in tags if isinstance(t, str) and t.strip()][:20],
+ "source": "upload",
+ "source_meta": dict(source_meta or {}),
+ }
+ if description.strip():
+ body["description"] = description.strip()[:2000]
+ created = self._request("POST", "/api/avatars", body=body, headers=auth)
+ avatar = created.get("avatar")
+ if not isinstance(avatar, dict) or not avatar.get("id"):
+ raise ThreeWSError("three.ws did not return the saved model.", code="create_failed")
+ return avatar
+
+ def avatar_page_url(self, avatar: dict) -> str:
+ """Public page for an avatar returned by ``publish_glb``."""
+ return f"{self.base_url}/avatars/{urllib.parse.quote(str(avatar.get('id', '')))}"
+
# -- high-level convenience ---------------------------------------------
def generate_text_to_3d(
@@ -347,6 +685,34 @@ class ThreeWSClient:
)
+def is_glb(data: bytes) -> bool:
+ """True when ``data`` starts with a well-formed binary glTF 2.0 header."""
+ if not isinstance(data, (bytes, bytearray)) or len(data) < 12:
+ return False
+ magic = bytes(data[0:4])
+ version = int.from_bytes(data[4:8], "little")
+ length = int.from_bytes(data[8:12], "little")
+ return magic == b"glTF" and version == 2 and length == len(data)
+
+
+def slugify(text: str) -> str:
+ """Lowercase ``[a-z0-9_-]`` slug (max 64) that ``/api/avatars`` accepts."""
+ out = []
+ for ch in (text or "").lower():
+ if ch.isascii() and (ch.isalnum() or ch in "-_"):
+ out.append(ch)
+ elif out and out[-1] != "-":
+ out.append("-")
+ slug = "".join(out).strip("-_")[:64].strip("-_")
+ return slug or "model"
+
+
+def _is_web_url(url) -> bool:
+ """An http(s) URL. The server decides what is publicly reachable (it
+ SSRF-checks every mesh URL); this only stops local paths early."""
+ return isinstance(url, str) and url.startswith(("https://", "http://"))
+
+
def _safe_json(payload: bytes) -> dict:
try:
parsed = json.loads(payload.decode("utf-8"))