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(modly): add a Publish to three.ws node that saves any Modly mesh to the user's account

nirholasdf8cfd13e0ba
diff --git a/integrations/modly/three-ws-publish/LICENSE b/integrations/modly/three-ws-publish/LICENSE
new file mode 100644
index 000000000..b5ae2a4e1
--- /dev/null
+++ b/integrations/modly/three-ws-publish/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2026 nirholas
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/integrations/modly/three-ws-publish/README.md b/integrations/modly/three-ws-publish/README.md
new file mode 100644
index 000000000..46518a173
--- /dev/null
+++ b/integrations/modly/three-ws-publish/README.md
@@ -0,0 +1,103 @@
+# Publish to three.ws (Modly process node)
+
+A [Modly](https://github.com/lightningpixel/modly) workflow node that saves the
+mesh coming out of any Modly node into your three.ws account. The model gets
+its own page at `three.ws/avatars/<id>` with a 3D viewer, an embed snippet, and
+everything else a dashboard upload gets (humanoid meshes are auto-rigged).
+
+The mesh passes through unchanged, so the node can sit in the middle of a
+workflow. Its text output is the new model's page URL, and the same URL is
+written to Modly's run log.
+
+It pairs with the [three.ws Cloud generator](../three-ws/) in this folder:
+that extension generates meshes on three.ws GPUs, this one publishes any mesh,
+including ones Modly generated on your own GPU.
+
+Modly is MIT licensed, by [Lightning Pixel](https://github.com/lightningpixel).
+
+## Install
+
+1. Copy this folder somewhere permanent:
+
+ ```bash
+ git clone --depth 1 https://github.com/nirholas/three.ws /tmp/three.ws
+ cp -r /tmp/three.ws/integrations/modly/three-ws-publish ~/modly-three-ws-publish
+ ```
+
+2. In Modly open the **Models** page, click **Link local folder**, and pick
+ `~/modly-three-ws-publish`. Modly links the folder in place (so keep it) and
+ reads `manifest.json` from its root.
+3. The node appears in the workflow editor as **Publish to three.ws**.
+
+The three.ws Forge desktop app (`apps/forge-desktop`) ships this node built
+in, signed in with your account, so there is nothing to install there.
+
+## Use
+
+1. Create an API key with the `avatars:write` scope at
+ <https://three.ws/dashboard/api>.
+2. Wire a mesh node (for example **Generate Mesh**) into **Publish to three.ws**.
+3. Set the node's fields:
+
+ | Field | Default | Meaning |
+ |---|---|---|
+ | Name | file name | Title on three.ws |
+ | Visibility | `private` | `private`, `unlisted` (anyone with the link) or `public` (listed) |
+ | Tags | `modly` | Comma separated, up to 20 |
+ | API Key | empty | Paste once. It is saved to your user profile, so you can clear the field before sharing the workflow |
+
+4. Run the workflow. The node's output text is the page URL, for example
+ `https://three.ws/avatars/be5ac3e2-40dc-4645-a8bb-9789f97edcf2`.
+
+### Where the API key comes from
+
+The first non-empty source wins:
+
+1. The node's **API Key** field. A typed key is also saved to
+ `$XDG_CONFIG_HOME/three-ws/modly-api-key` (Linux/macOS, default
+ `~/.config`, file mode 600) or `%APPDATA%\three-ws\modly-api-key` (Windows).
+2. The `THREE_WS_API_KEY` environment variable. The Forge desktop app injects
+ its signed-in account's key here.
+3. The saved key file from step 1.
+
+`THREE_WS_BASE_URL` points the node at another deployment (default
+`https://three.ws`).
+
+## Limits and errors
+
+- The input must be a `.glb`. Place the node before any export to another
+ format.
+- Files up to 50 MB go through the three.ws upload proxy; larger files (up to
+ the account's plan limit) use a presigned direct upload.
+- A refused key reports that it may be revoked, expired, or missing
+ `avatars:write`, with the link to create a new one. Plan quota errors are
+ shown as three.ws reports them.
+
+## How it runs
+
+Modly runs process extensions as a Python subprocess
+(`electron/main/process-runner.ts`):
+
+- **stdin:** one JSON line,
+ `{"input": {"filePath": "..."}, "params": {...}, "workspaceDir": "...", "tempDir": "..."}`.
+ A relative `filePath` resolves against `workspaceDir`.
+- **stdout:** JSON lines, `{"type": "progress", "percent": 30, "label": "..."}`,
+ `{"type": "log", "message": "..."}`, then `{"type": "done", "result": {"filePath": "...", "text": "<page url>"}}`
+ or `{"type": "error", "message": "..."}`.
+
+The node is standard library only, so it runs on Modly's bundled Python with
+no setup. You can drive it by hand the same way Modly does:
+
+```bash
+echo '{"input":{"filePath":"/path/to/model.glb"},"params":{"visibility":"private"},"workspaceDir":"/tmp","tempDir":"/tmp"}' \
+ | THREE_WS_API_KEY=sk_live_... python3 processor.py
+```
+
+## Files
+
+| File | Role |
+|---|---|
+| `manifest.json` | Modly extension manifest (`"type": "process"`, one `publish` node) |
+| `processor.py` | The node: key resolution, input checks, upload, progress |
+| `three_ws_client.py` | Vendored copy of `integrations/_pyclient/three_ws_client.py`; `publish_glb` does the upload and create. Never edit it here: edit the canonical file and re-copy (`integrations/_pyclient/test_no_drift.py` fails on drift) |
+| `test_processor.py` | Spawns `processor.py` exactly like Modly against a local stand-in server: `python3 -m pytest test_processor.py` |
diff --git a/integrations/modly/three-ws-publish/manifest.json b/integrations/modly/three-ws-publish/manifest.json
new file mode 100644
index 000000000..a4b89b22e
--- /dev/null
+++ b/integrations/modly/three-ws-publish/manifest.json
@@ -0,0 +1,53 @@
+{
+ "id": "three-ws-publish",
+ "name": "Publish to three.ws",
+ "type": "process",
+ "entry": "processor.py",
+ "version": "1.0.0",
+ "author": "three.ws",
+ "description": "Saves the incoming GLB into your three.ws account, where it gets a shareable 3D page, an embed, and an AI agent. Humanoid meshes are auto-rigged.",
+ "tags": ["publish", "share", "cloud"],
+ "nodes": [
+ {
+ "id": "publish",
+ "name": "Publish to three.ws",
+ "input": "mesh",
+ "output": "mesh",
+ "params_schema": [
+ {
+ "id": "name",
+ "label": "Name",
+ "type": "string",
+ "default": "",
+ "tooltip": "Title shown on three.ws. Leave empty to use the file name."
+ },
+ {
+ "id": "visibility",
+ "label": "Visibility",
+ "type": "select",
+ "default": "private",
+ "options": [
+ { "value": "private", "label": "Private (only you)" },
+ { "value": "unlisted", "label": "Unlisted (anyone with the link)" },
+ { "value": "public", "label": "Public (listed on three.ws)" }
+ ],
+ "tooltip": "Who can open the model's page on three.ws. You can change this later from your dashboard."
+ },
+ {
+ "id": "tags",
+ "label": "Tags",
+ "type": "string",
+ "default": "modly",
+ "tooltip": "Comma-separated tags, up to 20."
+ },
+ {
+ "id": "api_key",
+ "label": "API Key",
+ "type": "string",
+ "default": "",
+ "tooltip": "A three.ws API key with the avatars:write scope (three.ws/dashboard/api). Paste it once: it is saved to your user profile, so you can clear this field before sharing the workflow. The THREE_WS_API_KEY environment variable also works."
+ }
+ ]
+ }
+ ]
+}
diff --git a/integrations/modly/three-ws-publish/processor.py b/integrations/modly/three-ws-publish/processor.py
new file mode 100644
index 000000000..5fc3693c5
--- /dev/null
+++ b/integrations/modly/three-ws-publish/processor.py
@@ -0,0 +1,155 @@
+"""Publish to three.ws: a Modly process extension.
+
+Takes the GLB coming out of any Modly mesh node and saves it into the three.ws
+account that owns the API key. The mesh passes through unchanged so the node
+can sit in the middle of a workflow; the new model's page URL is returned as the
+node's text output and written to the run log.
+
+Modly's Python process protocol (electron/main/process-runner.ts):
+ stdin: one JSON line {input: {filePath?, text?}, params, workspaceDir, tempDir}
+ stdout: JSON lines {type: progress|log|done|error, ...}
+
+Stdlib only, so it runs on Modly's bundled Python with no setup step. The API
+contract lives in the vendored ``three_ws_client.py``.
+
+API key resolution order: the node's ``api_key`` field (saved to the user
+profile on first use), the ``THREE_WS_API_KEY`` environment variable, then the
+saved key file. ``THREE_WS_BASE_URL`` points at another deployment.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from pathlib import Path
+from typing import Optional
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+
+from three_ws_client import ( # noqa: E402
+ AVATAR_VISIBILITIES,
+ DEFAULT_BASE_URL,
+ ThreeWSClient,
+ ThreeWSError,
+)
+
+
+def key_file() -> Path:
+ """Per-user location of the saved API key, outside any workflow file."""
+ if os.name == "nt":
+ root = Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming")
+ else:
+ root = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config")
+ return root / "three-ws" / "modly-api-key"
+
+
+def resolve_api_key(param_value: str) -> str:
+ typed = (param_value or "").strip()
+ if typed:
+ path = key_file()
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(typed, encoding="utf-8")
+ if os.name != "nt":
+ path.chmod(0o600)
+ except OSError:
+ pass
+ return typed
+ env = os.environ.get("THREE_WS_API_KEY", "").strip()
+ if env:
+ return env
+ try:
+ return key_file().read_text(encoding="utf-8").strip()
+ except OSError:
+ return ""
+
+
+def resolve_mesh_path(file_path: Optional[str], workspace_dir: str) -> Path:
+ if not file_path:
+ raise ThreeWSError(
+ "Publish to three.ws needs a mesh. Connect a mesh node to its input.",
+ code="no_input",
+ )
+ path = Path(file_path)
+ if not path.is_absolute():
+ path = Path(workspace_dir or ".") / path
+ if not path.is_file():
+ raise ThreeWSError(f"Mesh file not found: {path}", code="no_input")
+ if path.suffix.lower() != ".glb":
+ raise ThreeWSError(
+ f"three.ws stores GLB files and this mesh is {path.suffix or 'unknown'}. "
+ "Place this node before any export to another format.",
+ code="invalid_glb",
+ )
+ return path
+
+
+def parse_tags(raw) -> list:
+ if isinstance(raw, list):
+ items = raw
+ else:
+ items = str(raw or "").split(",")
+ return [t.strip() for t in items if isinstance(t, str) and t.strip()][:20]
+
+
+def run(message: dict, emit) -> dict:
+ params = message.get("params") or {}
+ node_input = message.get("input") or {}
+ mesh = resolve_mesh_path(node_input.get("filePath"), message.get("workspaceDir", ""))
+
+ api_key = resolve_api_key(str(params.get("api_key") or ""))
+ visibility = params.get("visibility")
+ if visibility not in AVATAR_VISIBILITIES:
+ visibility = "private"
+ name = str(params.get("name") or "").strip() or mesh.stem.replace("_", " ")
+
+ base_url = os.environ.get("THREE_WS_BASE_URL", "").strip() or DEFAULT_BASE_URL
+ client = ThreeWSClient(base_url)
+
+ emit({"type": "progress", "percent": 10, "label": "Reading mesh"})
+ data = mesh.read_bytes()
+ emit({"type": "progress", "percent": 30, "label": "Uploading to three.ws"})
+ avatar = client.publish_glb(
+ data,
+ api_key=api_key,
+ name=name,
+ visibility=visibility,
+ tags=parse_tags(params.get("tags")),
+ source_meta={"generator": "modly", "client": "modly-three-ws-publish"},
+ )
+ url = client.avatar_page_url(avatar)
+ emit({"type": "progress", "percent": 100, "label": "Published"})
+ emit({"type": "log", "message": f"Published to three.ws: {url}"})
+ return {"filePath": str(mesh), "text": url}
+
+
+def main() -> int:
+ def emit(obj: dict) -> None:
+ sys.stdout.write(json.dumps(obj) + "\n")
+ sys.stdout.flush()
+
+ try:
+ message = json.loads(sys.stdin.readline() or "{}")
+ result = run(message, emit)
+ except ThreeWSError as exc:
+ text = exc.message.rstrip()
+ if text and text[-1] not in ".!?":
+ text += "."
+ if exc.status == 401 or exc.code in ("unauthorized", "insufficient_scope"):
+ text += (
+ " The API key was refused: it may be revoked, expired, or missing the"
+ " avatars:write scope. Create a key with that scope at"
+ " https://three.ws/dashboard/api and paste it into the node."
+ )
+ emit({"type": "error", "message": f"three.ws: {text}"})
+ return 1
+ except Exception as exc: # the runner shows this message in the node
+ emit({"type": "error", "message": f"Publish to three.ws failed: {exc}"})
+ return 1
+ emit({"type": "done", "result": result})
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/integrations/modly/three-ws-publish/test_processor.py b/integrations/modly/three-ws-publish/test_processor.py
new file mode 100644
index 000000000..a976f570f
--- /dev/null
+++ b/integrations/modly/three-ws-publish/test_processor.py
@@ -0,0 +1,152 @@
+"""Tests for the Publish to three.ws Modly process extension.
+
+Spawns ``processor.py`` exactly the way Modly's PythonProcessRunner does (one
+JSON line on stdin, JSON lines back on stdout) against an in-process stub of
+the avatar upload + create endpoints. No Modly install, no live network. Run:
+ ( cd integrations/modly/three-ws-publish && python -m unittest test_processor )
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import threading
+import unittest
+import urllib.parse
+from http.server import BaseHTTPRequestHandler, HTTPServer
+from pathlib import Path
+
+_HERE = os.path.dirname(os.path.abspath(__file__))
+GLB = b"glTF" + (2).to_bytes(4, "little") + (16).to_bytes(4, "little") + b"JSON"
+
+
+class _Account(BaseHTTPRequestHandler):
+ def log_message(self, *a):
+ pass
+
+ def _send(self, status, obj):
+ body = json.dumps(obj).encode()
+ 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):
+ st = self.server.state
+ raw = self.rfile.read(int(self.headers.get("content-length", 0)))
+ if self.headers.get("authorization") != "Bearer sk_live_good":
+ return self._send(401, {"error": "unauthorized", "message": "sign in or provide a valid bearer token"})
+ p = urllib.parse.urlparse(self.path)
+ if p.path == "/api/avatars/upload":
+ st["uploaded"] = raw
+ return self._send(200, {"storage_key": "u/1/k.glb", "size_bytes": len(raw), "checksum_sha256": "a" * 64})
+ if p.path == "/api/avatars":
+ st["create"] = json.loads(raw)
+ return self._send(201, {"avatar": {"id": "av_9"}})
+ return self._send(404, {"error": "nf"})
+
+
+class ProcessorTest(unittest.TestCase):
+ def setUp(self):
+ self.server = HTTPServer(("127.0.0.1", 0), _Account)
+ self.server.state = {}
+ self.host = f"http://127.0.0.1:{self.server.server_address[1]}"
+ threading.Thread(target=self.server.serve_forever, daemon=True).start()
+ self.tmp = Path(tempfile.mkdtemp())
+ self.mesh = self.tmp / "workspace" / "Default" / "1700000000_ab12cd34.glb"
+ self.mesh.parent.mkdir(parents=True)
+ self.mesh.write_bytes(GLB)
+
+ def tearDown(self):
+ self.server.shutdown()
+ self.server.server_close()
+
+ def _run(self, message, extra_env=None):
+ env = {
+ "PATH": os.environ.get("PATH", ""),
+ "HOME": str(self.tmp / "home"),
+ "XDG_CONFIG_HOME": str(self.tmp / "config"),
+ "APPDATA": str(self.tmp / "config"),
+ "THREE_WS_BASE_URL": self.host,
+ }
+ env.update(extra_env or {})
+ proc = subprocess.run(
+ [sys.executable, os.path.join(_HERE, "processor.py")],
+ input=json.dumps(message) + "\n",
+ capture_output=True,
+ text=True,
+ env=env,
+ timeout=30,
+ )
+ lines = [json.loads(l) for l in proc.stdout.splitlines() if l.strip()]
+ return proc.returncode, lines
+
+ def _message(self, **params):
+ return {
+ "input": {"filePath": "Default/1700000000_ab12cd34.glb"},
+ "params": params,
+ "workspaceDir": str(self.tmp / "workspace"),
+ "tempDir": str(self.tmp),
+ }
+
+ def test_publishes_and_passes_mesh_through(self):
+ code, lines = self._run(self._message(name="Brass Owl", visibility="unlisted", tags="modly, owl", api_key="sk_live_good"))
+ self.assertEqual(code, 0, lines)
+ done = lines[-1]
+ self.assertEqual(done["type"], "done")
+ self.assertEqual(done["result"]["filePath"], str(self.mesh))
+ self.assertEqual(done["result"]["text"], f"{self.host}/avatars/av_9")
+ self.assertEqual(self.server.state["uploaded"], GLB)
+ create = self.server.state["create"]
+ self.assertEqual(create["name"], "Brass Owl")
+ self.assertEqual(create["visibility"], "unlisted")
+ self.assertEqual(create["tags"], ["modly", "owl"])
+ self.assertEqual(create["source_meta"]["generator"], "modly")
+ self.assertTrue(any(l["type"] == "progress" for l in lines))
+
+ def test_typed_key_is_saved_for_later_runs(self):
+ self._run(self._message(api_key="sk_live_good"))
+ saved = (self.tmp / "config" / "three-ws" / "modly-api-key").read_text()
+ self.assertEqual(saved, "sk_live_good")
+ code, lines = self._run(self._message())
+ self.assertEqual(code, 0, lines)
+ self.assertEqual(lines[-1]["type"], "done")
+
+ def test_env_key(self):
+ code, lines = self._run(self._message(), {"THREE_WS_API_KEY": "sk_live_good"})
+ self.assertEqual(code, 0, lines)
+
+ def test_missing_key_is_actionable(self):
+ code, lines = self._run(self._message())
+ self.assertEqual(code, 1)
+ self.assertEqual(lines[-1]["type"], "error")
+ self.assertIn("dashboard/api", lines[-1]["message"])
+
+ def test_bad_key_hints_scope(self):
+ code, lines = self._run(self._message(api_key="sk_live_bad"))
+ self.assertEqual(code, 1)
+ self.assertIn("avatars:write", lines[-1]["message"])
+
+ def test_non_glb_input_is_explained(self):
+ stl = self.mesh.with_suffix(".stl")
+ stl.write_bytes(b"solid x")
+ msg = self._message(api_key="sk_live_good")
+ msg["input"]["filePath"] = str(stl)
+ code, lines = self._run(msg)
+ self.assertEqual(code, 1)
+ self.assertIn("before any export", lines[-1]["message"])
+
+ def test_missing_input(self):
+ msg = self._message(api_key="sk_live_good")
+ msg["input"] = {}
+ code, lines = self._run(msg)
+ self.assertEqual(code, 1)
+ self.assertIn("Connect a mesh node", lines[-1]["message"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/integrations/modly/three-ws-publish/three_ws_client.py b/integrations/modly/three-ws-publish/three_ws_client.py
new file mode 100644
index 000000000..98ad00cd9
--- /dev/null
+++ b/integrations/modly/three-ws-publish/three_ws_client.py
@@ -0,0 +1,721 @@
+"""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
+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
+* ``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. 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
+vendored copies identical.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import ssl
+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", "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",
+ "jpg": "image/jpeg",
+ "jpeg": "image/jpeg",
+ "webp": "image/webp",
+}
+
+
+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."""
+
+ 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,
+ raw: Optional[bytes] = None,
+ headers: Optional[dict] = None,
+ timeout: Optional[float] = None,
+ ) -> dict:
+ url = f"{self.base_url}{path}"
+ data = None
+ merged = self._headers(headers)
+ if body is not None:
+ data = json.dumps(body).encode("utf-8")
+ 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 _urlopen(req, timeout or 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,
+ },
+ )
+ 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=data, headers=put_headers, method="PUT")
+ try:
+ with _urlopen(put_req, max(self.timeout, 60)) as resp:
+ resp.read()
+ except urllib.error.HTTPError as exc:
+ raise ThreeWSError(
+ f"{label} upload failed (HTTP {exc.code}).", code="upload_failed", status=exc.code
+ ) from exc
+ except urllib.error.URLError as exc:
+ raise ThreeWSError(f"{label} 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.
+ """
+ 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()
+ while True:
+ if should_cancel and should_cancel():
+ raise ThreeWSError(f"{label} cancelled.", code="cancelled")
+ elapsed = _now() - start
+ if elapsed > timeout:
+ 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(result_key):
+ return result[result_key]
+ if status == "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 _urlopen(req, 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
+
+ # -- 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(
+ 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 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"))
+ return parsed if isinstance(parsed, dict) else {"value": parsed}
+ except (ValueError, UnicodeDecodeError):
+ return {}