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(integrations): Blender addon + ComfyUI nodes three.ws clients
nirholaseaf5a48eeecf
diff --git a/integrations/_pyclient/test_three_ws_client.py b/integrations/_pyclient/test_three_ws_client.pyindex 30682ca1b..84e530e43 100644--- a/integrations/_pyclient/test_three_ws_client.py+++ b/integrations/_pyclient/test_three_ws_client.py@@ -42,13 +42,15 @@ class _Handler(BaseHTTPRequestHandler):def do_GET(self):state = self.server.stateparsed = urllib.parse.urlparse(self.path)- qs = urllib.parse.parse_qs(parsed.query)+ qs = urllib.parse.parse_qs(parsed.query, keep_blank_values=True)if parsed.path == "/api/forge" and "catalog" in qs:return self._send(200, {"tiers": [{"id": "standard"}], "backends": []})if parsed.path == "/api/forge" and "job" in qs:state["poll_count"] += 1# Record the client handle so the test can assert scoping.state["last_client_handle"] = self.headers.get("x-forge-client")+ if state.get("fail_poll"):+ return self._send(200, {"job_id": qs["job"][0], "status": "failed", "error": "render exploded"})if state["poll_count"] >= state["done_after"]:return self._send(200, {"job_id": qs["job"][0], "status": "done", "glb_url": state["glb_url"]})return self._send(200, {"job_id": qs["job"][0], "status": "running"})@@ -116,6 +118,7 @@ class ForgeClientTest(unittest.TestCase):def tearDown(self):self.server.shutdown()+ self.server.server_close()self.thread.join(timeout=2)def test_catalog(self):@@ -151,11 +154,14 @@ class ForgeClientTest(unittest.TestCase):self.client.submit_text_to_3d("a model", backend="meshy")self.assertEqual(ctx.exception.code, "needs_key")- def test_failed_job_raises(self):- self.server.state["submit_error"] = {"job_id": "j", "status": "failed", "error": "boom"}- # submit returns ok (has job_id), poll surfaces the failure- job = self.client._submit({"prompt": "x"})- self.assertEqual(job["job_id"], "j")+ def test_failed_job_raises_at_poll(self):+ # Submit succeeds (job queued); the failure surfaces during polling.+ self.server.state["fail_poll"] = True+ job = self.client.submit_text_to_3d("a model that will fail")+ with self.assertRaises(ThreeWSError) as ctx:+ self.client.poll(job["job_id"], interval=0.01, timeout=5)+ self.assertEqual(ctx.exception.code, "failed")+ self.assertIn("render exploded", ctx.exception.message)def test_short_prompt_rejected(self):with self.assertRaises(ThreeWSError) as ctx:diff --git a/integrations/blender/three_ws/__init__.py b/integrations/blender/three_ws/__init__.pynew file mode 100644index 000000000..a179b8cfc--- /dev/null+++ b/integrations/blender/three_ws/__init__.py@@ -0,0 +1,387 @@+"""three.ws — Blender add-on.++Generate a 3D model from a text prompt or a reference image with three.ws Forge,+without leaving Blender. The model is reconstructed on three.ws (FLUX→TRELLIS by+default, or Meshy/Tripo geometry path with your own key), then imported into the+current scene.++Install: zip this folder → Edit ▸ Preferences ▸ Add-ons ▸ Install… → enable+"three.ws". Open the sidebar in the 3D Viewport (press N) → "three.ws" tab.++Networking runs on a worker thread; the GLB import happens on Blender's main+thread inside a modal timer (bpy is not thread-safe). Nothing is faked — the+panel shows the real job status and elapsed time, and surfaces real errors.+"""++import os+import queue+import tempfile+import threading++import bpy+from bpy.props import EnumProperty, PointerProperty, StringProperty+from bpy.types import AddonPreferences, Operator, Panel, PropertyGroup++from .three_ws_client import (+ ASPECT_RATIOS,+ BACKENDS,+ DEFAULT_BASE_URL,+ PATHS,+ TIERS,+ ThreeWSClient,+ ThreeWSError,+ content_type_for_path,+)++bl_info = {+ "name": "three.ws",+ "author": "three.ws",+ "version": (1, 0, 0),+ "blender": (4, 0, 0),+ "location": "View3D ▸ Sidebar ▸ three.ws",+ "description": "Generate 3D models from text or images with three.ws Forge.",+ "category": "Import-Export",+ "doc_url": "https://three.ws/forge",+}+++# -- preferences --------------------------------------------------------------++class ThreeWSPreferences(AddonPreferences):+ bl_idname = __name__++ api_url: StringProperty(+ name="API URL",+ description="three.ws deployment origin",+ default=DEFAULT_BASE_URL,+ )+ provider_key: StringProperty(+ name="Provider API key",+ description="Optional Meshy/Tripo key for the geometry path (BYOK). "+ "Leave blank to use the free image path (FLUX→TRELLIS).",+ default="",+ subtype="PASSWORD",+ )++ def draw(self, context):+ layout = self.layout+ layout.prop(self, "api_url")+ layout.prop(self, "provider_key")+ layout.label(+ text="The image path is free. A provider key is only needed for the "+ "Meshy/Tripo geometry backends.",+ icon="INFO",+ )+++def _prefs(context):+ return context.preferences.addons[__name__].preferences+++# -- scene properties ---------------------------------------------------------++def _enum(items_tuple, labels=None):+ labels = labels or {}+ return [(v, labels.get(v, v.replace("_", " ").title()), "") for v in items_tuple]+++class ThreeWSProps(PropertyGroup):+ mode: EnumProperty(+ name="Source",+ items=[("text", "Text", "Generate from a text prompt"),+ ("image", "Image", "Generate from a reference image")],+ default="text",+ )+ prompt: StringProperty(+ name="Prompt",+ description="Describe one subject",+ default="",+ )+ image_path: StringProperty(+ name="Image",+ description="Reference image (PNG/JPEG/WebP)",+ default="",+ subtype="FILE_PATH",+ )+ tier: EnumProperty(+ name="Quality",+ items=_enum(TIERS),+ default="standard",+ )+ path: EnumProperty(+ name="Pipeline",+ items=[("image", "Image (FLUX→TRELLIS, free)", ""),+ ("geometry", "Geometry (Meshy/Tripo, BYOK)", "")],+ default="image",+ )+ 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"}),+ default="auto",+ )+ aspect_ratio: EnumProperty(+ name="Aspect",+ items=_enum(ASPECT_RATIOS),+ default="1:1",+ )+ status: StringProperty(name="Status", default="")+ running: bpy.props.BoolProperty(name="Running", default=False)+++# -- generation operator ------------------------------------------------------++class THREEWS_OT_generate(Operator):+ """Generate a 3D model and import it into the scene."""++ bl_idname = "threews.generate"+ bl_label = "Generate 3D model"+ bl_options = {"REGISTER"}++ _timer = None+ _thread = None+ _events: "queue.Queue" = None+ _cancel = None+ _result_path = None+ _error = None++ @classmethod+ def poll(cls, context):+ return not context.scene.three_ws.running++ def _worker(self, client, props, image_bytes, image_ct, dest_path):+ def on_progress(status, elapsed):+ self._events.put(("progress", f"{status} — {int(elapsed)}s"))++ try:+ backend = None if props["backend"] == "auto" else props["backend"]+ if props["mode"] == "text":+ glb_url = client.generate_text_to_3d(+ props["prompt"], tier=props["tier"], backend=backend,+ path=props["path"], aspect_ratio=props["aspect_ratio"],+ on_progress=on_progress, should_cancel=lambda: self._cancel.is_set(),+ )+ else:+ glb_url = client.generate_image_to_3d(+ image_bytes, image_ct, tier=props["tier"], backend=backend,+ path=props["path"], on_progress=on_progress,+ should_cancel=lambda: self._cancel.is_set(),+ )+ client.download(glb_url, dest_path)+ self._events.put(("done", dest_path))+ except ThreeWSError as exc:+ self._events.put(("error", exc.message))+ except Exception as exc: # network/file errors → real message, never silent+ self._events.put(("error", str(exc)))++ def execute(self, context):+ props = context.scene.three_ws+ prefs = _prefs(context)++ # Validate inputs on the main thread before spawning work.+ image_bytes, image_ct = None, None+ if props.mode == "text":+ if len((props.prompt or "").strip()) < 3:+ self.report({"ERROR"}, "Enter a prompt of at least 3 characters.")+ return {"CANCELLED"}+ else:+ path = bpy.path.abspath(props.image_path or "")+ if not path or not os.path.isfile(path):+ self.report({"ERROR"}, "Choose a reference image file.")+ return {"CANCELLED"}+ try:+ image_ct = content_type_for_path(path)+ with open(path, "rb") as fh:+ image_bytes = fh.read()+ except (ThreeWSError, OSError) as exc:+ self.report({"ERROR"}, str(exc))+ return {"CANCELLED"}++ client = ThreeWSClient(prefs.api_url, provider_key=prefs.provider_key or None)+ dest_path = os.path.join(tempfile.gettempdir(), f"three-ws-{os.getpid()}-{id(self)}.glb")++ self._events = queue.Queue()+ self._cancel = threading.Event()+ self._result_path = None+ self._error = None+ snapshot = {+ "mode": props.mode, "prompt": props.prompt, "tier": props.tier,+ "path": props.path, "backend": props.backend, "aspect_ratio": props.aspect_ratio,+ }+ self._thread = threading.Thread(+ target=self._worker, args=(client, snapshot, image_bytes, image_ct, dest_path), daemon=True+ )+ props.running = True+ props.status = "Submitting…"+ self._thread.start()++ self._timer = context.window_manager.event_timer_add(0.25, window=context.window)+ context.window_manager.modal_handler_add(self)+ return {"RUNNING_MODAL"}++ def modal(self, context, event):+ props = context.scene.three_ws+ if event.type == "ESC":+ self._cancel.set()+ props.status = "Cancelling…"++ if event.type != "TIMER":+ return {"PASS_THROUGH"}++ # Drain worker events on the main thread.+ try:+ while True:+ kind, payload = self._events.get_nowait()+ if kind == "progress":+ props.status = payload+ elif kind == "done":+ self._result_path = payload+ elif kind == "error":+ self._error = payload+ except queue.Empty:+ pass++ if self._thread and not self._thread.is_alive():+ return self._finish(context)+ return {"PASS_THROUGH"}++ def _finish(self, context):+ props = context.scene.three_ws+ if self._timer:+ context.window_manager.event_timer_remove(self._timer)+ self._timer = None+ props.running = False++ if self._error:+ props.status = ""+ self.report({"ERROR"}, f"three.ws: {self._error}")+ return {"CANCELLED"}++ if not self._result_path or not os.path.isfile(self._result_path):+ props.status = ""+ self.report({"ERROR"}, "three.ws: generation finished without a model.")+ return {"CANCELLED"}++ # GLB import must run on the main thread — that's why it's here, not in+ # the worker. Select + frame the freshly imported objects.+ before = set(context.scene.objects)+ try:+ bpy.ops.import_scene.gltf(filepath=self._result_path)+ except RuntimeError as exc:+ props.status = ""+ self.report({"ERROR"}, f"three.ws: GLB import failed: {exc}")+ return {"CANCELLED"}+ finally:+ try:+ os.remove(self._result_path)+ except OSError:+ pass++ new_objs = [o for o in context.scene.objects if o not in before]+ if new_objs:+ for obj in context.selected_objects:+ obj.select_set(False)+ for obj in new_objs:+ obj.select_set(True)+ context.view_layer.objects.active = new_objs[0]+ _frame_selected(context)++ props.status = ""+ self.report({"INFO"}, f"three.ws: imported {len(new_objs)} object(s).")+ return {"FINISHED"}+++def _frame_selected(context):+ """Frame the imported objects in the first available 3D viewport."""+ for area in context.screen.areas:+ if area.type == "VIEW_3D":+ for region in area.regions:+ if region.type == "WINDOW":+ with context.temp_override(area=area, region=region):+ bpy.ops.view3d.view_selected()+ return+++class THREEWS_OT_check_catalog(Operator):+ """Verify the deployment is reachable and report live backends."""++ bl_idname = "threews.check_catalog"+ bl_label = "Test connection"++ def execute(self, context):+ prefs = _prefs(context)+ client = ThreeWSClient(prefs.api_url, provider_key=prefs.provider_key or None)+ try:+ catalog = client.get_catalog()+ except ThreeWSError as exc:+ self.report({"ERROR"}, f"three.ws: {exc.message}")+ return {"CANCELLED"}+ live = [b.get("label", b.get("id")) for b in catalog.get("backends", []) if b.get("configured")]+ self.report({"INFO"}, "three.ws reachable. Live backends: " + (", ".join(live) or "image path only"))+ return {"FINISHED"}+++# -- panel --------------------------------------------------------------------++class THREEWS_PT_panel(Panel):+ bl_label = "three.ws Forge"+ bl_idname = "THREEWS_PT_panel"+ bl_space_type = "VIEW_3D"+ bl_region_type = "UI"+ bl_category = "three.ws"++ def draw(self, context):+ layout = self.layout+ props = context.scene.three_ws++ layout.prop(props, "mode", expand=True)+ if props.mode == "text":+ layout.prop(props, "prompt")+ layout.prop(props, "aspect_ratio")+ else:+ layout.prop(props, "image_path")++ col = layout.column(align=True)+ col.prop(props, "path")+ col.prop(props, "tier")+ col.prop(props, "backend")++ row = layout.row()+ row.scale_y = 1.4+ row.enabled = not props.running+ row.operator(THREEWS_OT_generate.bl_idname, icon="MESH_MONKEY")++ if props.running:+ box = layout.box()+ box.label(text=props.status or "Working…", icon="SORTTIME")+ box.label(text="Press Esc to cancel.", icon="CANCEL")++ layout.separator()+ layout.operator(THREEWS_OT_check_catalog.bl_idname, icon="URL")+++# -- registration -------------------------------------------------------------++_CLASSES = (+ ThreeWSPreferences,+ ThreeWSProps,+ THREEWS_OT_generate,+ THREEWS_OT_check_catalog,+ THREEWS_PT_panel,+)+++def register():+ for cls in _CLASSES:+ bpy.utils.register_class(cls)+ bpy.types.Scene.three_ws = PointerProperty(type=ThreeWSProps)+++def unregister():+ del bpy.types.Scene.three_ws+ for cls in reversed(_CLASSES):+ bpy.utils.unregister_class(cls)+++if __name__ == "__main__":+ register()diff --git a/integrations/blender/three_ws/three_ws_client.py b/integrations/blender/three_ws/three_ws_client.pynew file mode 100644index 000000000..dc2ea9a66--- /dev/null+++ b/integrations/blender/three_ws/three_ws_client.py@@ -0,0 +1,355 @@+"""three.ws Forge client — shared by the Blender add-on and the ComfyUI nodes.++Single source of truth for the public Forge generation contract+(``api/forge.js`` + ``api/forge-upload.js``). Stdlib-only (``urllib``) so it+runs unmodified inside Blender's bundled Python and inside ComfyUI without+forcing a ``pip install`` into either host.++Public contract this wraps+---------------------------+* ``POST /api/forge`` ``{prompt, aspect_ratio?, path?, tier?, backend?}`` → text→3D+* ``POST /api/forge`` ``{image_urls[], prompt?, path?, tier?, backend?}`` → image→3D+* ``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++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.++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+vendored copies identical.+"""++from __future__ import annotations++import hashlib+import json+import time+import urllib.error+import urllib.parse+import urllib.request+import uuid+from typing import Callable, Optional++DEFAULT_BASE_URL = "https://three.ws"+DEFAULT_TIMEOUT = 30.0 # per HTTP request+DEFAULT_POLL_INTERVAL = 2.0 # seconds between job polls+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")+ASPECT_RATIOS = ("1:1", "4:3", "3:4", "16:9", "9:16")++_CONTENT_TYPE_BY_EXT = {+ "png": "image/png",+ "jpg": "image/jpeg",+ "jpeg": "image/jpeg",+ "webp": "image/webp",+}+++class ThreeWSError(Exception):+ """A Forge request failed. ``message`` is safe to show a user."""++ def __init__(self, message: str, *, code: str = "", status: int = 0):+ super().__init__(message)+ self.message = message+ self.code = code+ self.status = status+++def content_type_for_path(path: str) -> str:+ """Map an image filename to the content-type Forge accepts, or raise."""+ ext = path.rsplit(".", 1)[-1].lower() if "." in path else ""+ ct = _CONTENT_TYPE_BY_EXT.get(ext)+ if not ct:+ raise ThreeWSError(+ f"Unsupported image type '.{ext}'. Use PNG, JPEG, or WebP.",+ code="invalid_content_type",+ )+ return ct+++class ThreeWSClient:+ """Submit, poll, and download three.ws Forge generations.++ Parameters+ ----------+ base_url: deployment origin (default ``https://three.ws``).+ provider_key: optional Meshy/Tripo key for the BYOK geometry path.+ client_handle: anonymous handle that scopes creations; generated if omitted.+ timeout: per-request timeout in seconds.+ """++ def __init__(+ self,+ base_url: str = DEFAULT_BASE_URL,+ *,+ provider_key: Optional[str] = None,+ client_handle: Optional[str] = None,+ timeout: float = DEFAULT_TIMEOUT,+ ):+ self.base_url = (base_url or DEFAULT_BASE_URL).rstrip("/")+ self.provider_key = (provider_key or "").strip() or None+ self.client_handle = client_handle or uuid.uuid4().hex+ self.timeout = timeout++ # -- low-level HTTP ------------------------------------------------------++ def _headers(self, extra: Optional[dict] = None) -> dict:+ headers = {+ "accept": "application/json",+ "x-forge-client": self.client_handle,+ "user-agent": "three-ws-plugin/1.0",+ }+ if self.provider_key:+ headers["x-forge-provider-key"] = self.provider_key+ if extra:+ headers.update(extra)+ return headers++ def _request(self, method: str, path: str, *, body: Optional[dict] = None) -> dict:+ url = f"{self.base_url}{path}"+ data = None+ headers = self._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)+ try:+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:+ payload = resp.read()+ except urllib.error.HTTPError as exc:+ payload = exc.read()+ parsed = _safe_json(payload)+ raise ThreeWSError(+ parsed.get("message") or parsed.get("error") or f"HTTP {exc.code}",+ code=parsed.get("error", ""),+ status=exc.code,+ ) from exc+ except urllib.error.URLError as exc:+ raise ThreeWSError(+ f"Could not reach {self.base_url}: {exc.reason}",+ code="unreachable",+ ) from exc+ return _safe_json(payload)++ # -- catalog -------------------------------------------------------------++ def get_catalog(self) -> dict:+ """Live tier/backend/cost matrix from ``GET /api/forge?catalog``."""+ return self._request("GET", "/api/forge?catalog")++ # -- image upload (image→3D needs a public URL) --------------------------++ def upload_image(self, image_bytes: bytes, content_type: str) -> str:+ """Presign + PUT an image, returning its public URL for image→3D.++ Raises ThreeWSError with actionable guidance if storage is not+ configured on the deployment (the caller may pass a public URL instead).+ """+ if not image_bytes:+ raise ThreeWSError("Image is empty.", code="invalid_size")+ checksum = hashlib.sha256(image_bytes).hexdigest()+ presign = self._request(+ "POST",+ "/api/forge-upload",+ body={+ "content_type": content_type,+ "size_bytes": len(image_bytes),+ "checksum_sha256": checksum,+ },+ )+ 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"+ )+ try:+ with urllib.request.urlopen(put_req, timeout=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+ ) from exc+ except urllib.error.URLError as exc:+ raise ThreeWSError(f"Image upload failed: {exc.reason}", code="upload_failed") from exc+ return public_url++ # -- submit --------------------------------------------------------------++ def submit_text_to_3d(+ self,+ prompt: str,+ *,+ tier: str = "standard",+ backend: Optional[str] = None,+ path: str = "image",+ aspect_ratio: str = "1:1",+ ) -> dict:+ prompt = (prompt or "").strip()+ if len(prompt) < 3:+ raise ThreeWSError("Describe one subject in at least 3 characters.", code="invalid_prompt")+ body = {"prompt": prompt, "tier": tier, "path": path, "aspect_ratio": aspect_ratio}+ if backend:+ body["backend"] = backend+ return self._submit(body)++ def submit_image_to_3d(+ self,+ image_urls,+ *,+ prompt: str = "",+ tier: str = "standard",+ backend: Optional[str] = None,+ path: str = "image",+ ) -> dict:+ if isinstance(image_urls, str):+ image_urls = [image_urls]+ image_urls = [u for u in image_urls if isinstance(u, str) and u.startswith("https://")]+ if not image_urls:+ raise ThreeWSError("image_to_3d needs at least one public https image URL.", code="invalid_image_urls")+ body = {"image_urls": image_urls, "tier": tier, "path": path}+ if prompt.strip():+ body["prompt"] = prompt.strip()+ if backend:+ body["backend"] = backend+ return self._submit(body)++ def _submit(self, body: dict) -> dict:+ result = self._request("POST", "/api/forge", body=body)+ err = result.get("error")+ if err == "needs_key":+ raise ThreeWSError(+ "This backend (Meshy/Tripo) needs your provider API key. "+ "Set it in the add-on preferences / node input.",+ code="needs_key",+ )+ if err == "backend_unconfigured":+ raise ThreeWSError(+ result.get("message") or "That backend is not configured on this deployment.",+ code="backend_unconfigured",+ )+ if err == "unconfigured":+ raise ThreeWSError(+ result.get("message") or "Generation is not configured on this deployment.",+ code="unconfigured",+ )+ if err:+ raise ThreeWSError(result.get("message") or err, code=err)+ job_id = result.get("job_id")+ if not job_id:+ raise ThreeWSError("Forge returned no job id.", code="no_job")+ return result++ # -- poll ----------------------------------------------------------------++ def poll(+ self,+ job_id: str,+ *,+ on_progress: Optional[Callable[[str, float], None]] = None,+ interval: float = DEFAULT_POLL_INTERVAL,+ timeout: float = DEFAULT_POLL_TIMEOUT,+ should_cancel: Optional[Callable[[], bool]] = None,+ _now: Callable[[], float] = time.monotonic,+ _sleep: Callable[[float], None] = time.sleep,+ ) -> str:+ """Block until the job is done; return its GLB URL.++ ``on_progress(status, elapsed_seconds)`` is called each tick. Raises+ ThreeWSError on failure or timeout. ``should_cancel`` lets a host abort.+ """+ 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")+ 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")+ if on_progress:+ on_progress(status, elapsed)+ if status == "done" and result.get("glb_url"):+ return result["glb_url"]+ if status == "failed":+ raise ThreeWSError(result.get("error") or "Generation failed.", code="failed")+ _sleep(interval)++ # -- 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(+ dest_path, "wb"+ ) as out:+ while True:+ chunk = resp.read(64 * 1024)+ if not chunk:+ break+ out.write(chunk)+ except (urllib.error.HTTPError, urllib.error.URLError) as exc:+ raise ThreeWSError(f"Download failed: {exc}", code="download_failed") from exc+ return dest_path++ # -- high-level convenience ---------------------------------------------++ def generate_text_to_3d(+ self,+ prompt: str,+ *,+ tier: str = "standard",+ backend: Optional[str] = None,+ path: str = "image",+ aspect_ratio: str = "1:1",+ on_progress: Optional[Callable[[str, float], None]] = None,+ should_cancel: Optional[Callable[[], bool]] = None,+ poll_timeout: float = DEFAULT_POLL_TIMEOUT,+ ) -> str:+ job = self.submit_text_to_3d(+ prompt, tier=tier, backend=backend, path=path, aspect_ratio=aspect_ratio+ )+ return self.poll(+ job["job_id"], on_progress=on_progress, should_cancel=should_cancel, timeout=poll_timeout+ )++ def generate_image_to_3d(+ self,+ image_bytes: bytes,+ content_type: str,+ *,+ prompt: str = "",+ tier: str = "standard",+ backend: Optional[str] = None,+ path: str = "image",+ on_progress: Optional[Callable[[str, float], None]] = None,+ should_cancel: Optional[Callable[[], bool]] = None,+ poll_timeout: float = DEFAULT_POLL_TIMEOUT,+ ) -> str:+ public_url = self.upload_image(image_bytes, content_type)+ job = self.submit_image_to_3d(public_url, prompt=prompt, tier=tier, backend=backend, path=path)+ return self.poll(+ job["job_id"], on_progress=on_progress, should_cancel=should_cancel, timeout=poll_timeout+ )+++def _safe_json(payload: bytes) -> dict:+ try:+ parsed = json.loads(payload.decode("utf-8"))+ return parsed if isinstance(parsed, dict) else {"value": parsed}+ except (ValueError, UnicodeDecodeError):+ return {}diff --git a/integrations/comfyui/three_ws_nodes/three_ws_client.py b/integrations/comfyui/three_ws_nodes/three_ws_client.pynew file mode 100644index 000000000..dc2ea9a66--- /dev/null+++ b/integrations/comfyui/three_ws_nodes/three_ws_client.py@@ -0,0 +1,355 @@+"""three.ws Forge client — shared by the Blender add-on and the ComfyUI nodes.++Single source of truth for the public Forge generation contract+(``api/forge.js`` + ``api/forge-upload.js``). Stdlib-only (``urllib``) so it+runs unmodified inside Blender's bundled Python and inside ComfyUI without+forcing a ``pip install`` into either host.++Public contract this wraps+---------------------------+* ``POST /api/forge`` ``{prompt, aspect_ratio?, path?, tier?, backend?}`` → text→3D+* ``POST /api/forge`` ``{image_urls[], prompt?, path?, tier?, backend?}`` → image→3D+* ``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++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.++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+vendored copies identical.+"""++from __future__ import annotations++import hashlib+import json+import time+import urllib.error+import urllib.parse+import urllib.request+import uuid+from typing import Callable, Optional++DEFAULT_BASE_URL = "https://three.ws"+DEFAULT_TIMEOUT = 30.0 # per HTTP request+DEFAULT_POLL_INTERVAL = 2.0 # seconds between job polls+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")+ASPECT_RATIOS = ("1:1", "4:3", "3:4", "16:9", "9:16")++_CONTENT_TYPE_BY_EXT = {+ "png": "image/png",+ "jpg": "image/jpeg",+ "jpeg": "image/jpeg",+ "webp": "image/webp",+}+++class ThreeWSError(Exception):+ """A Forge request failed. ``message`` is safe to show a user."""++ def __init__(self, message: str, *, code: str = "", status: int = 0):+ super().__init__(message)+ self.message = message+ self.code = code+ self.status = status+++def content_type_for_path(path: str) -> str:+ """Map an image filename to the content-type Forge accepts, or raise."""+ ext = path.rsplit(".", 1)[-1].lower() if "." in path else ""+ ct = _CONTENT_TYPE_BY_EXT.get(ext)+ if not ct:+ raise ThreeWSError(+ f"Unsupported image type '.{ext}'. Use PNG, JPEG, or WebP.",+ code="invalid_content_type",+ )+ return ct+++class ThreeWSClient:+ """Submit, poll, and download three.ws Forge generations.++ Parameters+ ----------+ base_url: deployment origin (default ``https://three.ws``).+ provider_key: optional Meshy/Tripo key for the BYOK geometry path.+ client_handle: anonymous handle that scopes creations; generated if omitted.+ timeout: per-request timeout in seconds.+ """++ def __init__(+ self,+ base_url: str = DEFAULT_BASE_URL,+ *,+ provider_key: Optional[str] = None,+ client_handle: Optional[str] = None,+ timeout: float = DEFAULT_TIMEOUT,+ ):+ self.base_url = (base_url or DEFAULT_BASE_URL).rstrip("/")+ self.provider_key = (provider_key or "").strip() or None+ self.client_handle = client_handle or uuid.uuid4().hex+ self.timeout = timeout++ # -- low-level HTTP ------------------------------------------------------++ def _headers(self, extra: Optional[dict] = None) -> dict:+ headers = {+ "accept": "application/json",+ "x-forge-client": self.client_handle,+ "user-agent": "three-ws-plugin/1.0",+ }+ if self.provider_key:+ headers["x-forge-provider-key"] = self.provider_key+ if extra:+ headers.update(extra)+ return headers++ def _request(self, method: str, path: str, *, body: Optional[dict] = None) -> dict:+ url = f"{self.base_url}{path}"+ data = None+ headers = self._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)+ try:+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:+ payload = resp.read()+ except urllib.error.HTTPError as exc:+ payload = exc.read()+ parsed = _safe_json(payload)+ raise ThreeWSError(+ parsed.get("message") or parsed.get("error") or f"HTTP {exc.code}",+ code=parsed.get("error", ""),+ status=exc.code,+ ) from exc+ except urllib.error.URLError as exc:+ raise ThreeWSError(+ f"Could not reach {self.base_url}: {exc.reason}",+ code="unreachable",+ ) from exc+ return _safe_json(payload)++ # -- catalog -------------------------------------------------------------++ def get_catalog(self) -> dict:+ """Live tier/backend/cost matrix from ``GET /api/forge?catalog``."""+ return self._request("GET", "/api/forge?catalog")++ # -- image upload (image→3D needs a public URL) --------------------------++ def upload_image(self, image_bytes: bytes, content_type: str) -> str:+ """Presign + PUT an image, returning its public URL for image→3D.++ Raises ThreeWSError with actionable guidance if storage is not+ configured on the deployment (the caller may pass a public URL instead).+ """+ if not image_bytes:+ raise ThreeWSError("Image is empty.", code="invalid_size")+ checksum = hashlib.sha256(image_bytes).hexdigest()+ presign = self._request(+ "POST",+ "/api/forge-upload",+ body={+ "content_type": content_type,+ "size_bytes": len(image_bytes),+ "checksum_sha256": checksum,+ },+ )+ 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"+ )+ try:+ with urllib.request.urlopen(put_req, timeout=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+ ) from exc+ except urllib.error.URLError as exc:+ raise ThreeWSError(f"Image upload failed: {exc.reason}", code="upload_failed") from exc+ return public_url++ # -- submit --------------------------------------------------------------++ def submit_text_to_3d(+ self,+ prompt: str,+ *,+ tier: str = "standard",+ backend: Optional[str] = None,+ path: str = "image",+ aspect_ratio: str = "1:1",+ ) -> dict:+ prompt = (prompt or "").strip()+ if len(prompt) < 3:+ raise ThreeWSError("Describe one subject in at least 3 characters.", code="invalid_prompt")+ body = {"prompt": prompt, "tier": tier, "path": path, "aspect_ratio": aspect_ratio}+ if backend:+ body["backend"] = backend+ return self._submit(body)++ def submit_image_to_3d(+ self,+ image_urls,+ *,+ prompt: str = "",+ tier: str = "standard",+ backend: Optional[str] = None,+ path: str = "image",+ ) -> dict:+ if isinstance(image_urls, str):+ image_urls = [image_urls]+ image_urls = [u for u in image_urls if isinstance(u, str) and u.startswith("https://")]+ if not image_urls:+ raise ThreeWSError("image_to_3d needs at least one public https image URL.", code="invalid_image_urls")+ body = {"image_urls": image_urls, "tier": tier, "path": path}+ if prompt.strip():+ body["prompt"] = prompt.strip()+ if backend:+ body["backend"] = backend+ return self._submit(body)++ def _submit(self, body: dict) -> dict:+ result = self._request("POST", "/api/forge", body=body)+ err = result.get("error")+ if err == "needs_key":+ raise ThreeWSError(+ "This backend (Meshy/Tripo) needs your provider API key. "+ "Set it in the add-on preferences / node input.",+ code="needs_key",+ )+ if err == "backend_unconfigured":+ raise ThreeWSError(+ result.get("message") or "That backend is not configured on this deployment.",+ code="backend_unconfigured",+ )+ if err == "unconfigured":+ raise ThreeWSError(+ result.get("message") or "Generation is not configured on this deployment.",+ code="unconfigured",+ )+ if err:+ raise ThreeWSError(result.get("message") or err, code=err)+ job_id = result.get("job_id")+ if not job_id:+ raise ThreeWSError("Forge returned no job id.", code="no_job")+ return result++ # -- poll ----------------------------------------------------------------++ def poll(+ self,+ job_id: str,+ *,+ on_progress: Optional[Callable[[str, float], None]] = None,+ interval: float = DEFAULT_POLL_INTERVAL,+ timeout: float = DEFAULT_POLL_TIMEOUT,+ should_cancel: Optional[Callable[[], bool]] = None,+ _now: Callable[[], float] = time.monotonic,+ _sleep: Callable[[float], None] = time.sleep,+ ) -> str:+ """Block until the job is done; return its GLB URL.++ ``on_progress(status, elapsed_seconds)`` is called each tick. Raises+ ThreeWSError on failure or timeout. ``should_cancel`` lets a host abort.+ """+ 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")+ 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")+ if on_progress:+ on_progress(status, elapsed)+ if status == "done" and result.get("glb_url"):+ return result["glb_url"]+ if status == "failed":+ raise ThreeWSError(result.get("error") or "Generation failed.", code="failed")+ _sleep(interval)++ # -- 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(+ dest_path, "wb"+ ) as out:+ while True:+ chunk = resp.read(64 * 1024)+ if not chunk:+ break+ out.write(chunk)+ except (urllib.error.HTTPError, urllib.error.URLError) as exc:+ raise ThreeWSError(f"Download failed: {exc}", code="download_failed") from exc+ return dest_path++ # -- high-level convenience ---------------------------------------------++ def generate_text_to_3d(+ self,+ prompt: str,+ *,+ tier: str = "standard",+ backend: Optional[str] = None,+ path: str = "image",+ aspect_ratio: str = "1:1",+ on_progress: Optional[Callable[[str, float], None]] = None,+ should_cancel: Optional[Callable[[], bool]] = None,+ poll_timeout: float = DEFAULT_POLL_TIMEOUT,+ ) -> str:+ job = self.submit_text_to_3d(+ prompt, tier=tier, backend=backend, path=path, aspect_ratio=aspect_ratio+ )+ return self.poll(+ job["job_id"], on_progress=on_progress, should_cancel=should_cancel, timeout=poll_timeout+ )++ def generate_image_to_3d(+ self,+ image_bytes: bytes,+ content_type: str,+ *,+ prompt: str = "",+ tier: str = "standard",+ backend: Optional[str] = None,+ path: str = "image",+ on_progress: Optional[Callable[[str, float], None]] = None,+ should_cancel: Optional[Callable[[], bool]] = None,+ poll_timeout: float = DEFAULT_POLL_TIMEOUT,+ ) -> str:+ public_url = self.upload_image(image_bytes, content_type)+ job = self.submit_image_to_3d(public_url, prompt=prompt, tier=tier, backend=backend, path=path)+ return self.poll(+ job["job_id"], on_progress=on_progress, should_cancel=should_cancel, timeout=poll_timeout+ )+++def _safe_json(payload: bytes) -> dict:+ try:+ parsed = json.loads(payload.decode("utf-8"))+ return parsed if isinstance(parsed, dict) else {"value": parsed}+ except (ValueError, UnicodeDecodeError):+ return {}