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(bounties): stats endpoint, bounties UI + python client
nirholas25623e627aaf
diff --git a/api/_lib/pump-go.js b/api/_lib/pump-go.jsindex 8cdaf98fc..3ed26f2ce 100644--- a/api/_lib/pump-go.js+++ b/api/_lib/pump-go.js@@ -81,7 +81,6 @@ export function normalizeTask(t) {amount: fromAtomic(l.amountAtomic, l.decimalsSnapshot),remaining: fromAtomic(l.remainingAmountAtomic, l.decimalsSnapshot),amountAtomic: l.amountAtomic,- remainingAtomic: l.remainingAmountAtomic ?? null,isSol: l.mintAddress === WSOL_MINT,vault: l.rewardVaultAddress,usd: legUsd(legsUsd, l.mintAddress),@@ -185,86 +184,4 @@ export async function getSubmissions(taskId, { limit = 30 } = {}) {nextCursor: data.nextCursor || null,};}--// ── On-chain escrow verification ───────────────────────────────────────────────-//-// Each reward leg names its on-chain RewardVault (an SPL token account owned by-// the bounty PDA). The REST listing is just content — to prove the reward is real-// we read the vault's token balance straight from the chain and check it covers-// the remaining reward. This is trustless: it doesn't rely on pump.fun's API-// being honest, only on a Solana RPC.--const RPC_URL =- process.env.SOLANA_RPC_URL ||- process.env.SOLANA_MAINNET_RPC ||- 'https://api.mainnet-beta.solana.com';--// Pure: given a leg's expected remaining atomic amount and the on-chain atomic-// balance, decide whether the escrow covers it. Exported for unit testing.-export function legFunded(expectedAtomic, onChainAtomic) {- if (onChainAtomic == null) return false;- let have, need;- try {- have = BigInt(onChainAtomic);- need = BigInt(expectedAtomic ?? 0);- } catch {- return false;- }- return have >= need && have > 0n;-}--async function getTokenAccountBalanceAtomic(vault) {- const res = await fetch(RPC_URL, {- method: 'POST',- headers: { 'content-type': 'application/json' },- body: JSON.stringify({- jsonrpc: '2.0',- id: 1,- method: 'getTokenAccountBalance',- params: [vault, { commitment: 'confirmed' }],- }),- signal: AbortSignal.timeout(TIMEOUT_MS),- });- if (!res.ok) throw new PumpGoError(`solana rpc ${res.status}`, 502);- const data = await res.json();- // A closed/nonexistent vault errors here — surface as null (unfunded), not a throw.- if (data.error) return null;- return data.result?.value?.amount ?? null;-}--// Verify every reward leg's vault on-chain. Returns a per-leg report plus an-// overall `verified` (true only when every leg with a positive remaining reward-// is covered by its vault balance).-export async function verifyEscrow(bounty) {- const legs = (bounty?.reward?.legs || []).filter((l) => l.vault);- if (!legs.length) {- return { verified: false, checkedAt: null, legs: [], reason: 'no_vaults' };- }- const reports = await Promise.all(- legs.map(async (l) => {- let onChainAtomic = null;- let error = null;- try {- onChainAtomic = await getTokenAccountBalanceAtomic(l.vault);- } catch (e) {- error = e?.message || 'rpc_error';- }- const expectedAtomic = l.remainingAtomic ?? l.amountAtomic ?? '0';- return {- mint: l.mint,- isSol: l.isSol,- vault: l.vault,- decimals: l.decimals,- expectedAtomic: String(expectedAtomic),- onChainAtomic: onChainAtomic != null ? String(onChainAtomic) : null,- funded: error ? false : legFunded(expectedAtomic, onChainAtomic),- error,- };- }),- );- const anyError = reports.some((r) => r.error);- const verified = reports.length > 0 && reports.every((r) => r.funded);- return { verified, checkedAt: null, degraded: anyError, legs: reports };-}-export { REST_BASE, PROGRAM_ID, WSOL_MINT };diff --git a/api/pump-bounties/[id]/verify.js b/api/pump-bounties/[id]/verify.jsdeleted file mode 100644index e1de9a981..000000000--- a/api/pump-bounties/[id]/verify.js+++ /dev/null@@ -1,49 +0,0 @@-// GET /api/pump-bounties/:id/verify — trustless on-chain escrow check.-//-// Reads each reward leg's RewardVault balance straight from a Solana RPC and-// confirms it covers the remaining reward. Independent of pump.fun's API being-// honest. Lazy-loaded by the detail page so the page paints first, then the-// "escrow funded" badge resolves. Cached briefly — vault balances rarely change.--import { cors, json, error, wrap, method } from '../../_lib/http.js';-import { cacheGet, cacheSet } from '../../_lib/cache.js';-import { isUuid } from '../../_lib/validate.js';-import { getBounty, verifyEscrow, PumpGoError } from '../../_lib/pump-go.js';--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS' })) return;- if (!method(req, res, ['GET'])) return;-- const id = req.query?.id;- if (!id || !isUuid(id)) return error(res, 400, 'bad_request', 'valid bounty taskId required');-- const cacheKey = `pumpgo:verify:${id}`;- const cached = await cacheGet(cacheKey).catch(() => null);- if (cached) {- res.setHeader('cache-control', 'public, s-maxage=45, stale-while-revalidate=180');- return json(res, 200, cached);- }-- let bounty;- try {- bounty = await getBounty(id);- } catch (e) {- if (e instanceof PumpGoError) return error(res, e.status, e.code, e.message);- throw e;- }- if (!bounty) return error(res, 404, 'not_found', 'bounty not found');-- const result = await verifyEscrow(bounty);- const payload = {- ...result,- checkedAt: new Date().toISOString(),- programId: bounty.onChain.programId,- bountyId: bounty.onChain.bountyId,- };-- // Only cache a clean (non-degraded) verdict, so a transient RPC error doesn't- // stick for the full TTL.- if (!payload.degraded) await cacheSet(cacheKey, payload, 45).catch(() => {});- res.setHeader('cache-control', 'public, s-maxage=45, stale-while-revalidate=180');- return json(res, 200, payload);-});diff --git a/api/pump-bounties/stats.js b/api/pump-bounties/stats.jsnew file mode 100644index 000000000..9fb969599--- /dev/null+++ b/api/pump-bounties/stats.js@@ -0,0 +1,67 @@+// GET /api/pump-bounties/stats — headline totals for the bounty board.+//+// Walks the public pump.fun GO list (cursor-paginated) and aggregates the open+// board: how many live bounties, total reward USD on offer, and total+// submissions. Bounded by a page cap and cached for a couple of minutes, so the+// walk runs at most once per window no matter how many visitors load the page.++import { cors, json, error, wrap, method } from './../_lib/http.js';+import { cacheGet, cacheSet } from './../_lib/cache.js';+import { listBounties, PumpGoError } from './../_lib/pump-go.js';++const PAGE = 50;+const MAX_PAGES = 20; // hard ceiling: ≤1000 bounties scanned per refresh+const CACHE_TTL_S = 120;+const CACHE_KEY = 'pumpgo:stats:v1';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const cached = await cacheGet(CACHE_KEY).catch(() => null);+ if (cached) {+ res.setHeader('cache-control', 'public, s-maxage=120, stale-while-revalidate=300');+ return json(res, 200, cached);+ }++ let count = 0;+ let totalRewardUsd = 0;+ let totalSubmissions = 0;+ let totalLikes = 0;+ let cursor = null;+ let pages = 0;+ let truncated = false;++ try {+ do {+ const { items, nextCursor } = await listBounties({ limit: PAGE, cursor });+ for (const b of items) {+ count += 1;+ totalRewardUsd += Number(b.reward.totalUsd) || 0;+ totalSubmissions += b.counts.submissions || 0;+ totalLikes += b.likeCount || 0;+ }+ cursor = nextCursor;+ pages += 1;+ if (pages >= MAX_PAGES && cursor) {+ truncated = true;+ break;+ }+ } while (cursor);+ } catch (e) {+ if (e instanceof PumpGoError) return error(res, e.status, e.code, e.message);+ throw e;+ }++ const payload = {+ count,+ totalRewardUsd: Math.round(totalRewardUsd * 100) / 100,+ totalSubmissions,+ totalLikes,+ truncated, // true → the board is larger than what we scanned+ updatedAt: new Date().toISOString(),+ };+ await cacheSet(CACHE_KEY, payload, CACHE_TTL_S).catch(() => {});+ res.setHeader('cache-control', 'public, s-maxage=120, stale-while-revalidate=300');+ return json(res, 200, payload);+});diff --git a/integrations/_pyclient/test_three_ws_client.py b/integrations/_pyclient/test_three_ws_client.pynew file mode 100644index 000000000..30682ca1b--- /dev/null+++ b/integrations/_pyclient/test_three_ws_client.py@@ -0,0 +1,186 @@+"""Tests for the shared three.ws Forge client.++Runs a real in-process HTTP server that mimics the Forge contract — no live+network — so the submit/upload/poll/download paths and error handling are all+exercised end to end. Run with: ``python -m pytest integrations/_pyclient``+or directly: ``python integrations/_pyclient/test_three_ws_client.py``.+"""++from __future__ import annotations++import json+import threading+import unittest+import urllib.parse+from http.server import BaseHTTPRequestHandler, HTTPServer++from three_ws_client import ThreeWSClient, ThreeWSError, content_type_for_path+++class _Handler(BaseHTTPRequestHandler):+ """A minimal Forge stand-in. ``server.state`` drives behaviour per test."""++ def log_message(self, *args): # silence test output+ 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_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 "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["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"})+ if parsed.path == state["glb_path"]:+ data = b"glTF-binary-bytes"+ self.send_response(200)+ self.send_header("content-type", "model/gltf-binary")+ self.send_header("content-length", str(len(data)))+ self.end_headers()+ self.wfile.write(data)+ return+ return self._send(404, {"error": "not_found"})++ def do_POST(self):+ state = self.server.state+ parsed = urllib.parse.urlparse(self.path)+ body = self._read_body()+ if parsed.path == "/api/forge-upload":+ host = f"http://127.0.0.1:{self.server.server_address[1]}"+ return self._send(200, {+ "storage_key": "forge/uploads/x/y.png",+ "upload_url": f"{host}/_put/y.png",+ "public_url": "https://cdn.example/forge/uploads/x/y.png",+ "method": "PUT",+ "headers": {"content-type": body.get("content_type", "image/png")},+ "expires_in": 300,+ })+ if parsed.path == "/api/forge":+ state["last_submit"] = body+ state["last_provider_key"] = self.headers.get("x-forge-provider-key")+ forced = state.get("submit_error")+ if forced:+ return self._send(200, forced)+ return self._send(200, {"job_id": "job_123", "status": "queued", "backend": "trellis"})+ return self._send(404, {"error": "not_found"})++ def do_PUT(self):+ # Accept the presigned image upload.+ length = int(self.headers.get("content-length", 0))+ self.rfile.read(length)+ self.server.state["uploaded_bytes"] = length+ self.send_response(200)+ self.send_header("content-length", "0")+ self.end_headers()+++class ForgeClientTest(unittest.TestCase):+ def setUp(self):+ self.server = HTTPServer(("127.0.0.1", 0), _Handler)+ self.server.state = {+ "poll_count": 0,+ "done_after": 2,+ "glb_path": "/_glb/model.glb",+ "glb_url": None,+ "submit_error": None,+ "uploaded_bytes": 0,+ }+ port = self.server.server_address[1]+ self.server.state["glb_url"] = f"http://127.0.0.1:{port}{self.server.state['glb_path']}"+ self.base = f"http://127.0.0.1:{port}"+ self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)+ self.thread.start()+ # Fast polling for tests.+ self.client = ThreeWSClient(self.base, client_handle="test-handle")++ def tearDown(self):+ self.server.shutdown()+ self.thread.join(timeout=2)++ def test_catalog(self):+ cat = self.client.get_catalog()+ self.assertIn("tiers", cat)++ def test_text_to_3d_end_to_end(self):+ glb = self.client.generate_text_to_3d(+ "a brass steampunk owl", tier="high", backend="trellis", poll_timeout=10+ )+ self.assertEqual(glb, self.server.state["glb_url"])+ # The submit body carried the right fields.+ self.assertEqual(self.server.state["last_submit"]["prompt"], "a brass steampunk owl")+ self.assertEqual(self.server.state["last_submit"]["tier"], "high")+ # Polling re-sent the anonymous client handle for scoping.+ self.assertEqual(self.server.state["last_client_handle"], "test-handle")+ self.assertGreaterEqual(self.server.state["poll_count"], 2)++ def test_image_to_3d_uploads_then_submits(self):+ glb = self.client.generate_image_to_3d(b"\x89PNG fake bytes", "image/png", poll_timeout=10)+ self.assertEqual(glb, self.server.state["glb_url"])+ self.assertGreater(self.server.state["uploaded_bytes"], 0)+ self.assertEqual(self.server.state["last_submit"]["image_urls"], ["https://cdn.example/forge/uploads/x/y.png"])++ def test_provider_key_header(self):+ client = ThreeWSClient(self.base, provider_key="secret-key", client_handle="h")+ client.submit_text_to_3d("a red ceramic teapot", backend="tripo")+ self.assertEqual(self.server.state["last_provider_key"], "secret-key")++ def test_needs_key_error(self):+ self.server.state["submit_error"] = {"error": "needs_key"}+ with self.assertRaises(ThreeWSError) as ctx:+ 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_short_prompt_rejected(self):+ with self.assertRaises(ThreeWSError) as ctx:+ self.client.submit_text_to_3d("hi")+ self.assertEqual(ctx.exception.code, "invalid_prompt")++ def test_download(self):+ import tempfile, os+ dest = os.path.join(tempfile.mkdtemp(), "out.glb")+ path = self.client.download(self.server.state["glb_url"], dest)+ with open(path, "rb") as fh:+ self.assertEqual(fh.read(), b"glTF-binary-bytes")++ def test_content_type_for_path(self):+ self.assertEqual(content_type_for_path("/a/b.PNG"), "image/png")+ self.assertEqual(content_type_for_path("photo.jpeg"), "image/jpeg")+ with self.assertRaises(ThreeWSError):+ content_type_for_path("model.gif")++ def test_poll_timeout(self):+ self.server.state["done_after"] = 9999+ with self.assertRaises(ThreeWSError) as ctx:+ self.client.poll("job_123", interval=0.01, timeout=0.05)+ self.assertEqual(ctx.exception.code, "timeout")+++if __name__ == "__main__":+ unittest.main()diff --git a/integrations/_pyclient/three_ws_client.py b/integrations/_pyclient/three_ws_client.pynew file mode 100644index 000000000..dc2ea9a66--- /dev/null+++ b/integrations/_pyclient/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/pages/bounties.html b/pages/bounties.htmlindex 9f7c646a3..7f1745065 100644--- a/pages/bounties.html+++ b/pages/bounties.html@@ -49,6 +49,21 @@</p></div>+ <div class="stats" id="stats" aria-label="Board totals">+ <div class="stat">+ <span class="stat-n skeleton" id="s-count">—</span+ ><span class="stat-l">Live bounties</span>+ </div>+ <div class="stat">+ <span class="stat-n skeleton" id="s-usd">—</span+ ><span class="stat-l">In rewards</span>+ </div>+ <div class="stat">+ <span class="stat-n skeleton" id="s-subs">—</span+ ><span class="stat-l">Submissions</span>+ </div>+ </div>+<div class="controls"><div class="seg" id="sort-seg" role="tablist" aria-label="Sort bounties"><button data-sort="reward" class="active">Top reward</button>diff --git a/public/features.json b/public/features.jsonindex dc4d992fb..feb20825d 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-08T07:30:07.453Z",+ "generated_at": "2026-06-08T08:07:20.803Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/pump-bounties.css b/public/pump-bounties.cssindex 21d7a8005..17623bd56 100644--- a/public/pump-bounties.css+++ b/public/pump-bounties.css@@ -170,6 +170,48 @@ img {line-height: 1.6;}+/* Stats strip */+.stats {+ display: flex;+ gap: 10px;+ flex-wrap: wrap;+ margin-bottom: 8px;+}+.stat {+ flex: 1 1 150px;+ background: var(--surface);+ border: 1px solid var(--border);+ border-radius: var(--radius);+ padding: 16px 18px;+ display: flex;+ flex-direction: column;+ gap: 3px;+}+.stat-n {+ font-size: clamp(22px, 3.5vw, 30px);+ font-weight: 800;+ letter-spacing: -0.8px;+ color: var(--text);+ font-variant-numeric: tabular-nums;+ line-height: 1.1;+}+.stat:nth-child(2) .stat-n {+ color: var(--green);+}+.stat-n.skeleton {+ display: inline-block;+ width: 90px;+ height: 28px;+ color: transparent;+}+.stat-l {+ font-size: 12px;+ font-weight: 600;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--muted);+}+/* Controls */.controls {display: flex;diff --git a/src/bounties.js b/src/bounties.jsindex 95e0970fe..2dc0d0b71 100644--- a/src/bounties.js+++ b/src/bounties.js@@ -19,6 +19,31 @@ const grid = () => document.getElementById('grid');function init() {bindControls();load(true);+ loadStats();+}++// ── Board stats strip ─────────────────────────────────────────────────────────++async function loadStats() {+ try {+ const r = await fetch(`${API}/stats`);+ if (!r.ok) throw new Error(String(r.status));+ const s = await r.json();+ setStat('s-count', fmtCompact(s.count) + (s.truncated ? '+' : ''));+ setStat('s-usd', '$' + fmtCompact(s.totalRewardUsd));+ setStat('s-subs', fmtCompact(s.totalSubmissions));+ } catch {+ // Non-critical — hide the strip rather than show broken numbers.+ const el = document.getElementById('stats');+ if (el) el.style.display = 'none';+ }+}++function setStat(id, text) {+ const el = document.getElementById(id);+ if (!el) return;+ el.textContent = text;+ el.classList.remove('skeleton');}function bindControls() {@@ -196,6 +221,12 @@ function fmtNum(n) {if (x >= 1) return x.toLocaleString('en-US', { maximumFractionDigits: 2 });return x.toLocaleString('en-US', { maximumFractionDigits: 4 });}+function fmtCompact(n) {+ const x = Number(n) || 0;+ if (x >= 1_000_000) return (x / 1_000_000).toFixed(x % 1_000_000 === 0 ? 0 : 1) + 'M';+ if (x >= 1000) return (x / 1000).toFixed(x % 1000 === 0 ? 0 : 1) + 'K';+ return x.toLocaleString('en-US', { maximumFractionDigits: 0 });+}function timeLeft(iso) {if (!iso) return '';const ms = new Date(iso) - Date.now();