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: Solana agent collection, Vertex Imagen, GCP expansion, remesh/texture workers
nirholas397974c80b40
diff --git a/api/_lib/solana-collection.js b/api/_lib/solana-collection.jsnew file mode 100644index 000000000..4ecbb83bc--- /dev/null+++ b/api/_lib/solana-collection.js@@ -0,0 +1,114 @@+/**+ * three.ws Agent Collection — our "flavor" of Metaplex Core on Solana.+ * ------------------------------------------------------------------------+ * Every agent deployed to Solana is minted as a Metaplex Core *asset inside a+ * three.ws Collection account*. The Collection is the on-chain artifact that is+ * unmistakably ours: it carries the three.ws brand, the standard agent plugin+ * schema, and — crucially — its update authority is a three.ws-held keypair.+ *+ * Because the asset's update authority resolves to the Collection (and the+ * Collection's update authority is three.ws), three.ws can edit the on-chain+ * Attributes / name / URI of any member agent without the owner re-signing.+ * This is the "three.ws authority-managed" edit model: the user owns the asset+ * (can transfer/sell it), three.ws curates its on-chain metadata on request.+ *+ * Activation is progressive and safe:+ * • If no collection address is configured for a network, callers fall back+ * to the legacy standalone-asset mint (owner = update authority). Nothing+ * breaks before the collection is deployed.+ * • Once `SOLANA_AGENT_COLLECTION_<NET>` is set (see scripts/+ * deploy-solana-agent-collection.mjs), new mints join the collection and+ * become authority-managed.+ *+ * Authority key handling mirrors api/_lib/attest-event.js: a base58-encoded+ * Ed25519 secret in the environment, decoded on demand. It is never logged and+ * never leaves the server.+ */++import { Keypair } from '@solana/web3.js';+import bs58 from 'bs58';+import { createSignerFromKeypair } from '@metaplex-foundation/umi';++import { THREE_WS } from './three-brand.js';++/** Networks we support for agent collections. */+export const COLLECTION_NETWORKS = /** @type {const} */ (['mainnet', 'devnet']);++/**+ * Deployed three.ws Agent Collection address for a network, or null if the+ * collection has not been deployed/configured yet (legacy standalone mints).+ *+ * @param {'mainnet'|'devnet'} network+ * @returns {string|null} base58 collection pubkey+ */+export function getAgentCollection(network) {+ const key =+ network === 'devnet'+ ? 'SOLANA_AGENT_COLLECTION_DEVNET'+ : 'SOLANA_AGENT_COLLECTION_MAINNET';+ const v = process.env[key];+ return v && v.trim() ? v.trim() : null;+}++/** True when a three.ws collection is configured for the network. */+export function hasAgentCollection(network) {+ return getAgentCollection(network) !== null;+}++/**+ * Decode the three.ws collection-authority secret into a web3.js Keypair.+ * This keypair is the update authority of the Collection (and therefore of+ * every member agent). It signs collection creation, mint-into-collection, and+ * all on-chain edits, and pays the fee for server-initiated edits — so it must+ * hold a small SOL balance on each active network.+ *+ * @returns {Keypair}+ */+export function loadCollectionAuthorityKeypair() {+ const k = process.env.SOLANA_AGENT_COLLECTION_AUTHORITY_KEY;+ if (!k) {+ throw Object.assign(+ new Error(+ 'SOLANA_AGENT_COLLECTION_AUTHORITY_KEY not configured — required to mint into or edit the three.ws agent collection.',+ ),+ { status: 500, code: 'authority_unconfigured' },+ );+ }+ return Keypair.fromSecretKey(bs58.decode(k));+}++/** Public base58 address of the collection authority, without exposing the secret. */+export function collectionAuthorityAddress() {+ return loadCollectionAuthorityKeypair().publicKey.toBase58();+}++/**+ * Build a Umi signer for the collection authority, bound to the given Umi+ * instance. Use this as the `authority` when creating assets into the+ * collection or when editing member assets server-side.+ *+ * @param {import('@metaplex-foundation/umi').Umi} umi+ * @returns {import('@metaplex-foundation/umi').Signer}+ */+export function collectionAuthoritySigner(umi) {+ const kp = loadCollectionAuthorityKeypair();+ const umiKeypair = umi.eddsa.createKeypairFromSecretKey(kp.secretKey);+ return createSignerFromKeypair(umi, umiKeypair);+}++/**+ * On-chain metadata for the Collection account itself. Mirrors the per-agent+ * brand block so a wallet/explorer viewing the collection sees three.ws.+ */+export const AGENT_COLLECTION = {+ name: 'three.ws Agents',+ // Resolvable JSON describing the collection (served by the API; see the+ // deploy script). Standard Metaplex collection metadata so Phantom / Solscan+ // / Magic Eden render it as a real collection.+ metadataPath: '/api/agents/solana-collection-metadata',+ description:+ 'On-chain identities for autonomous agents built on three.ws — each asset ' ++ 'is a deployable AI agent with a 3D avatar, editable on-chain metadata, ' ++ 'pay-per-call (x402), and a link back to its three.ws profile.',+ website: THREE_WS.website,+};diff --git a/api/_lib/solana/connection.js b/api/_lib/solana/connection.jsnew file mode 100644index 000000000..15ccc69f0--- /dev/null+++ b/api/_lib/solana/connection.js@@ -0,0 +1,129 @@+// Canonical Solana RPC endpoint resolution + a drop-in Connection with transparent+// multi-endpoint failover.+//+// `solanaConnection({ url, commitment })` returns a normal @solana/web3.js+// Connection whose underlying fetch rotates across a priority-ordered endpoint+// list. Every method on it (getBalance, getLatestBlockhash, sendRawTransaction,+// confirmTransaction, …) transparently fails over when an endpoint returns+// 429/5xx/auth errors or the network blips — no call-site change beyond swapping+// the constructor. Re-sending an already-signed transaction to a second RPC is+// safe: Solana dedupes by signature.+//+// Priority (per network): the caller's explicit url (if any) → Helius → Alchemy+// → Ankr → the keyless public endpoint, always last. We never depend on the+// public endpoint alone — it is the most aggressively rate-limited (the source of+// the `getBalance 429` log noise).++import { Connection } from '@solana/web3.js';++function deriveWsUrl(httpUrl) {+ return String(httpUrl).replace(/^https:/, 'wss:').replace(/^http:/, 'ws:');+}++const COOLDOWN_MS = 30_000;+const PUBLIC_MAINNET = 'https://api.mainnet-beta.solana.com';+const PUBLIC_DEVNET = 'https://api.devnet.solana.com';++function dedupe(list) {+ const seen = new Set();+ return list.filter((u) => u && typeof u === 'string' && !seen.has(u) && seen.add(u));+}++// devnet is inferred from the caller's url so we never append a mainnet fallback+// to a devnet primary (or vice-versa) — crossing clusters would return wrong data.+function inferNetwork(url) {+ return /devnet/i.test(String(url || '')) ? 'devnet' : 'mainnet';+}++/**+ * Priority-ordered endpoint list for a network. An explicit `url` (the value a+ * call site already resolved) is pinned first; the keyed providers and public+ * endpoint follow as fallbacks.+ */+export function solanaRpcEndpoints(network = 'mainnet', url = null) {+ const key = process.env.HELIUS_API_KEY;+ const alch = process.env.ALCHEMY_API_KEY;+ if (network === 'devnet') {+ return dedupe([+ url,+ process.env.SOLANA_RPC_URL_DEVNET,+ key && `https://devnet.helius-rpc.com/?api-key=${key}`,+ alch && `https://solana-devnet.g.alchemy.com/v2/${alch}`,+ PUBLIC_DEVNET,+ ]);+ }+ return dedupe([+ url,+ process.env.SOLANA_RPC_URL,+ key && `https://mainnet.helius-rpc.com/?api-key=${key}`,+ alch && `https://solana-mainnet.g.alchemy.com/v2/${alch}`,+ 'https://rpc.ankr.com/solana',+ PUBLIC_MAINNET,+ ]);+}++function maskUrl(url) {+ try {+ const u = new URL(url);+ return `${u.protocol}//${u.host}`;+ } catch {+ return String(url).slice(0, 24);+ }+}++// Rotate this endpoint out of service on a 401/403 (bad/expired key on this+// provider only), 429 (rate-limited), or 5xx (provider down) — all of which the+// next provider may not share. Other 4xx are real request errors and identical+// everywhere, so they're returned to the caller as-is.+function shouldRotate(status) {+ return status === 401 || status === 403 || status === 429 || status >= 500;+}++// Per-Connection rotating fetch. Cooldown state is captured in this closure, so+// it's shared across every JSON-RPC call made through one Connection instance.+function makeRotatingFetch(endpoints) {+ const cooldownUntil = new Array(endpoints.length).fill(0);+ return async function rotatingFetch(_info, init) {+ let lastErr = null;+ let attempted = false;+ for (let i = 0; i < endpoints.length; i++) {+ if (cooldownUntil[i] > Date.now()) continue;+ attempted = true;+ try {+ const resp = await fetch(endpoints[i], init);+ if (shouldRotate(resp.status)) {+ cooldownUntil[i] = Date.now() + COOLDOWN_MS;+ lastErr = new Error(`solana rpc ${resp.status} @ ${maskUrl(endpoints[i])}`);+ if (i + 1 < endpoints.length) {+ console.warn(`[solana-rpc] ${maskUrl(endpoints[i])} ${resp.status} — failing over`);+ }+ continue;+ }+ return resp;+ } catch (err) {+ cooldownUntil[i] = Date.now() + COOLDOWN_MS;+ lastErr = err;+ }+ }+ // Every endpoint is cooling down — don't hard-fail; take one more shot at+ // the primary (its cooldown may have just lapsed under load).+ if (!attempted) return fetch(endpoints[0], init);+ throw lastErr || new Error('all solana rpc endpoints failed');+ };+}++/**+ * Drop-in replacement for `new Connection(url, commitment)` that adds transparent+ * RPC failover. Pass the url the call site already resolved as `url`; it stays+ * the highest-priority endpoint and the keyed/public fallbacks are appended.+ */+export function solanaConnection({ url = null, commitment = 'confirmed', network = null } = {}) {+ const net = network || inferNetwork(url);+ const endpoints = solanaRpcEndpoints(net, url);+ const primary = endpoints[0] || (net === 'devnet' ? PUBLIC_DEVNET : PUBLIC_MAINNET);+ return new Connection(primary, {+ commitment,+ wsEndpoint: deriveWsUrl(primary),+ ...(endpoints.length > 1 ? { fetch: makeRotatingFetch(endpoints) } : {}),+ });+}diff --git a/api/_lib/solana/rpc-fallback.js b/api/_lib/solana/rpc-fallback.jsindex 0a5c81695..8c6325483 100644--- a/api/_lib/solana/rpc-fallback.js+++ b/api/_lib/solana/rpc-fallback.js@@ -12,6 +12,7 @@// burn through fallbacks).import { Connection } from '@solana/web3.js';+import { solanaRpcEndpoints } from './connection.js';const MAX_CONSECUTIVE_FAILS = 3;const COOLDOWN_MS = 60_000;@@ -123,14 +124,15 @@ export function createRpcFallback(options) {return new RpcFallback(options);}-// Convenience: build a fallback set from env. Honors:-// SOLANA_RPC_URL — primary-// SOLANA_RPC_FALLBACK_URLS — comma-separated alternates (optional)+// Convenience: build a fallback set from env. The endpoint list is the canonical+// chain (explicit SOLANA_RPC_URL → Helius → Alchemy → Ankr → public), with any+// extra SOLANA_RPC_FALLBACK_URLS appended. So even with no SOLANA_RPC_URL set,+// the keyed providers and public endpoint give a real 3+ deep failover set.export function rpcFallbackFromEnv({ network = 'mainnet', commitment = 'confirmed' } = {}) {- const primary = network === 'devnet'- ? (process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com')- : (process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com');- const fallbacks = (process.env.SOLANA_RPC_FALLBACK_URLS || '')+ const extra = (process.env.SOLANA_RPC_FALLBACK_URLS || '').split(',').map((s) => s.trim()).filter(Boolean);- return new RpcFallback({ url: primary, fallbackUrls: fallbacks, commitment });+ const urls = [...solanaRpcEndpoints(network), ...extra]+ .filter((u, i, a) => u && a.indexOf(u) === i);+ const [primary, ...fallbackUrls] = urls;+ return new RpcFallback({ url: primary, fallbackUrls, commitment });}diff --git a/api/_mcp3d/text-to-image.js b/api/_mcp3d/text-to-image.jsindex b9d6b3717..7f863f237 100644--- a/api/_mcp3d/text-to-image.js+++ b/api/_mcp3d/text-to-image.js@@ -1,17 +1,19 @@// Text → image helper for the 3D Studio MCP.//-// The image-to-3D backend (Microsoft TRELLIS via Replicate) reconstructs a-// textured GLB from a single reference image. To support `text_to_3d` we first-// turn the prompt into an image with a fast text-to-image model, then feed that-// image into the same reconstruction pipeline. Both steps run on the one-// REPLICATE_API_TOKEN already provisioned for the avatar regen pipeline.+// Provider selection (first configured wins):+// 1. GOOGLE_CLOUD_PROJECT set → Vertex AI Imagen 3 (best quality, free with GCP credits)+// 2. REPLICATE_API_TOKEN set → flux-schnell via Replicate (fast, $0.003/image)//-// REPLICATE_API_TOKEN — required, from replicate.com/account-// REPLICATE_TXT2IMG_MODEL — optional override (owner/name[:version] or version hash)+// The image-to-3D backend (TRELLIS / Hunyuan3D / TripoSR) reconstructs a+// textured GLB from the generated image. Both steps share the same call site.//-// Default model: black-forest-labs/flux-schnell — Apache-2.0 weights,-// commercial-OK, ~1–3s per image on Replicate's fleet, $0.003/run. Pinned to-// the model slug (not a version hash) so it tracks Replicate's latest build.+// GOOGLE_CLOUD_PROJECT — GCP project id (enables Vertex AI Imagen path)+// VERTEX_IMAGEN_MODEL — override Imagen model (default: imagen-3.0-generate-001)+// REPLICATE_API_TOKEN — required when GCP not configured+// REPLICATE_TXT2IMG_MODEL — optional Replicate model override+//+// Replicate fallback: black-forest-labs/flux-schnell — Apache-2.0,+// commercial-OK, ~1–3s per image on Replicate's fleet, $0.003/run.const REPLICATE_BASE = 'https://api.replicate.com/v1';const DEFAULT_TXT2IMG_MODEL = 'black-forest-labs/flux-schnell';@@ -49,16 +51,28 @@ function parseRetryAfter(headers, message) {return 10;}-// Generate a single image from a text prompt. Uses Replicate's synchronous-// prediction mode (`Prefer: wait`) so the caller gets a URL back in one round-// trip — flux-schnell is fast enough that the request returns within the MCP-// tool-call window without needing a separate poll.+// Generate a single image from a text prompt.+//+// Prefers Vertex AI Imagen when GOOGLE_CLOUD_PROJECT is configured (free with+// GCP credits, higher quality). Falls back to Replicate flux-schnell otherwise.export async function textToImage(prompt, { aspectRatio = '1:1' } = {}) {+ // ── Vertex AI Imagen path ────────────────────────────────────────────────+ if (readEnv('GOOGLE_CLOUD_PROJECT')) {+ const { generateImage, isConfigured } = await import('./vertex-imagen.js');+ if (isConfigured()) {+ return generateImage(prompt, { aspectRatio });+ }+ }++ // ── Replicate fallback ───────────────────────────────────────────────────const token = readEnv('REPLICATE_API_TOKEN');if (!token) {- throw Object.assign(new Error('text-to-3D is not configured (REPLICATE_API_TOKEN missing)'), {- code: 'unconfigured',- });+ throw Object.assign(+ new Error(+ 'text-to-image is not configured: set GOOGLE_CLOUD_PROJECT (Vertex AI) or REPLICATE_API_TOKEN (Replicate)',+ ),+ { code: 'unconfigured' },+ );}const modelRef = readEnv('REPLICATE_TXT2IMG_MODEL') || DEFAULT_TXT2IMG_MODEL;diff --git a/api/_mcp3d/tools/studio.js b/api/_mcp3d/tools/studio.jsindex 67413c5bf..35c60cfd8 100644--- a/api/_mcp3d/tools/studio.js+++ b/api/_mcp3d/tools/studio.js@@ -1,14 +1,15 @@// three.ws 3D Studio MCP — generation tools.//-// text_to_3d / image_to_3d submit a real reconstruction job to Replicate-// (Microsoft TRELLIS by default) and return a job handle. generation_status-// polls that job and, when finished, hands back the GLB URL plus an inline-// <model-viewer> artifact so the model appears directly in the chat. preview_3d-// renders any public GLB the same way.+// text_to_3d / image_to_3d submit a reconstruction job and return a job handle.+// generation_status polls that job. preview_3d renders any GLB inline.+// remove_background strips image backgrounds (rembg/BRIA RMBG-2.0).+// remesh_model converts, simplifies, and repairs meshes.+// retexture_model paints a new texture onto a mesh from a text prompt.import { limits } from '../../_lib/rate-limit.js';import { assertSafePublicUrl } from '../../_lib/ssrf-guard.js';-import { createRegenProvider } from '../../_providers/replicate.js';+import { createRegenProvider as createReplicateProvider } from '../../_providers/replicate.js';+import { createRegenProvider as createGcpProvider } from '../../_providers/gcp.js';import { textToImage } from '../text-to-image.js';import {renderModelViewerHtml,@@ -37,11 +38,21 @@ async function enforce(limiter, auth) {}}-// Lazily construct the Replicate-backed provider so a missing token surfaces as-// a clean tool error rather than crashing module load for the whole server.-function regenProvider() {+// Resolve the best available provider for a given mode.+// GCP takes priority when the service URL is configured for that mode;+// falls back to Replicate for the standard reconstruct/remesh/retex/rerig modes.+function regenProvider(mode = 'reconstruct') {+ const gcpKey = process.env?.GCP_RECONSTRUCTION_KEY;+ if (gcpKey) {+ try {+ const gcp = createGcpProvider();+ if (gcp.supportsMode(mode)) return gcp;+ } catch {+ // fall through to Replicate+ }+ }try {- return createRegenProvider();+ return createReplicateProvider();} catch (err) {throw rpcError(-32000, '3D generation is not configured', { reason: err.message });}diff --git a/api/_mcp3d/vertex-imagen.js b/api/_mcp3d/vertex-imagen.jsnew file mode 100644index 000000000..6dbe4b13c--- /dev/null+++ b/api/_mcp3d/vertex-imagen.js@@ -0,0 +1,307 @@+// Vertex AI Imagen text-to-image client.+//+// Calls Google's Imagen API (imagegeneration@006 or imagen-3.0-generate-001)+// with a text prompt and returns an image URL suitable for downstream+// image-to-3D reconstruction.+//+// Why prefer this over Replicate flux-schnell when GCP credits are set:+// - Costs ~$0.02–0.04 per image versus ~$0.003 on Replicate, BUT the+// $100k GCP credit pool makes it effectively free for the operator.+// - Imagen 3 output quality is noticeably higher and reconstructs better.+// - Single dependency (GCP) instead of two API keys.+//+// Required env vars (at least one auth path must be present):+// GOOGLE_CLOUD_PROJECT — GCP project id+// GOOGLE_CLOUD_LOCATION — region (default: us-central1)+// GCP_SERVICE_ACCOUNT_JSON — service account key JSON as a string+// (set in Vercel secrets; alternative to+// GOOGLE_APPLICATION_CREDENTIALS file path)+//+// Model selection (first match wins):+// VERTEX_IMAGEN_MODEL — explicit override, e.g. "imagen-3.0-fast-generate-001"+// defaults to "imagen-3.0-generate-001" (best quality, ~8s)+// fast fallback: "imagen-3.0-fast-generate-001" (~3s, slightly lower quality)+//+// Output: base64 PNG returned inline in the API response, uploaded to R2/S3+// by the caller (same pattern as the Replicate path in text-to-image.js).++const DEFAULT_MODEL = 'imagen-3.0-generate-001';+const DEFAULT_LOCATION = 'us-central1';++// Aspect ratio mappings: our internal format → Imagen's enum.+const ASPECT_MAP = {+ '1:1': '1:1',+ '4:3': '4:3',+ '3:4': '3:4',+ '16:9': '16:9',+ '9:16': '9:16',+};++function readEnv(name) {+ if (typeof process !== 'undefined' && process.env?.[name]) return process.env[name];+ return null;+}++// Obtain a Google OAuth 2.0 access token.+//+// Two auth paths, in priority order:+// 1. GCP_SERVICE_ACCOUNT_JSON — service account JSON string (Vercel-friendly)+// 2. Metadata server — works on Cloud Run / GCE with attached SA+//+// Tokens are cached in-process for (expiry - 60s) to avoid hammering the+// token endpoint on every request.+const _tokenCache = { token: null, expiresAt: 0 };++async function getAccessToken() {+ const now = Date.now();+ if (_tokenCache.token && now < _tokenCache.expiresAt) {+ return _tokenCache.token;+ }++ const saJson = readEnv('GCP_SERVICE_ACCOUNT_JSON');+ if (saJson) {+ return _tokenFromServiceAccount(JSON.parse(saJson));+ }++ // Fall back to the metadata server (Cloud Run / GCE)+ const metaRes = await fetch(+ 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token',+ { headers: { 'Metadata-Flavor': 'Google' } },+ ).catch(() => null);++ if (metaRes?.ok) {+ const data = await metaRes.json();+ _tokenCache.token = data.access_token;+ _tokenCache.expiresAt = now + (data.expires_in - 60) * 1000;+ return _tokenCache.token;+ }++ throw Object.assign(+ new Error(+ 'No GCP credentials found. Set GCP_SERVICE_ACCOUNT_JSON or run on GCE/Cloud Run.',+ ),+ { code: 'unconfigured' },+ );+}++async function _tokenFromServiceAccount(sa) {+ // Build a JWT for the service account and exchange it for an access token.+ // Uses the Web Crypto API (available in Node 18+ and Vercel edge runtime).+ const now = Math.floor(Date.now() / 1000);+ const header = { alg: 'RS256', typ: 'JWT' };+ const payload = {+ iss: sa.client_email,+ scope: 'https://www.googleapis.com/auth/cloud-platform',+ aud: 'https://oauth2.googleapis.com/token',+ iat: now,+ exp: now + 3600,+ };++ const b64url = (obj) =>+ Buffer.from(JSON.stringify(obj)).toString('base64url');+ const signingInput = `${b64url(header)}.${b64url(payload)}`;++ // Import the RSA private key+ const keyData = sa.private_key+ .replace(/-----BEGIN PRIVATE KEY-----/, '')+ .replace(/-----END PRIVATE KEY-----/, '')+ .replace(/\s/g, '');+ const keyBuffer = Buffer.from(keyData, 'base64');++ const cryptoKey = await crypto.subtle.importKey(+ 'pkcs8',+ keyBuffer,+ { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },+ false,+ ['sign'],+ );++ const sigBuffer = await crypto.subtle.sign(+ 'RSASSA-PKCS1-v1_5',+ cryptoKey,+ Buffer.from(signingInput),+ );+ const sig = Buffer.from(sigBuffer).toString('base64url');+ const jwt = `${signingInput}.${sig}`;++ const tokenRes = await fetch('https://oauth2.googleapis.com/token', {+ method: 'POST',+ headers: { 'content-type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({+ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',+ assertion: jwt,+ }),+ });++ if (!tokenRes.ok) {+ const err = await tokenRes.text().catch(() => tokenRes.status);+ throw new Error(`GCP token exchange failed: ${err}`);+ }++ const data = await tokenRes.json();+ _tokenCache.token = data.access_token;+ _tokenCache.expiresAt = Date.now() + (data.expires_in - 60) * 1000;+ return _tokenCache.token;+}++// Return true if Vertex AI Imagen is configured (GCP project present).+export function isConfigured() {+ return Boolean(readEnv('GOOGLE_CLOUD_PROJECT'));+}++// Generate an image from a text prompt using Vertex AI Imagen.+//+// Returns { imageUrl, model } where imageUrl is a data: URI containing+// the base64-encoded PNG. The caller is responsible for uploading it to+// permanent storage if needed (the forge pipeline does this).+export async function generateImage(prompt, { aspectRatio = '1:1' } = {}) {+ const project = readEnv('GOOGLE_CLOUD_PROJECT');+ if (!project) {+ throw Object.assign(+ new Error('Vertex AI Imagen is not configured (GOOGLE_CLOUD_PROJECT missing)'),+ { code: 'unconfigured' },+ );+ }++ const location = readEnv('GOOGLE_CLOUD_LOCATION') || DEFAULT_LOCATION;+ const model = readEnv('VERTEX_IMAGEN_MODEL') || DEFAULT_MODEL;+ const aspectEnum = ASPECT_MAP[aspectRatio] || '1:1';++ const token = await getAccessToken();++ const endpoint =+ `https://${location}-aiplatform.googleapis.com/v1/projects/${project}` ++ `/locations/${location}/publishers/google/models/${model}:predict`;++ const body = {+ instances: [{ prompt }],+ parameters: {+ sampleCount: 1,+ aspectRatio: aspectEnum,+ // Enhance the prompt for 3D reconstruction: clean background,+ // single subject, even lighting. This dramatically improves the+ // quality of the downstream image-to-3D step.+ addWatermark: false,+ safetySetting: 'block_some',+ personGeneration: 'allow_adult',+ },+ };++ let res;+ try {+ res = await fetch(endpoint, {+ method: 'POST',+ headers: {+ authorization: `Bearer ${token}`,+ 'content-type': 'application/json',+ },+ body: JSON.stringify(body),+ });+ } catch (err) {+ throw Object.assign(+ new Error(`Vertex AI Imagen unreachable: ${err?.message}`),+ { code: 'provider_unreachable' },+ );+ }++ const data = await res.json().catch(() => ({}));++ if (!res.ok) {+ const message =+ data?.error?.message || data?.message || `Vertex AI returned ${res.status}`;+ if (res.status === 429) {+ throw Object.assign(new Error(message), {+ code: 'rate_limited',+ retryAfter: 10,+ });+ }+ throw Object.assign(new Error(message), { providerStatus: res.status });+ }++ const prediction = data?.predictions?.[0];+ const b64 = prediction?.bytesBase64Encoded;+ if (!b64) {+ throw new Error('Vertex AI returned no image data');+ }++ // Return as a data URI so the caller can either use it directly or+ // upload it to object storage. The data URI is also accepted by+ // TRELLIS, Hunyuan3D, and TripoSR as an image source.+ const imageUrl = `data:image/png;base64,${b64}`;+ return { imageUrl, model: `vertex-ai/${model}` };+}++// Edit an existing image using Imagen's inpainting / editing capability.+// Works with Imagen 3 Edit models.+//+// Returns { imageUrl, model }.+export async function editImage(imageUrl, prompt, { maskUrl = null } = {}) {+ const project = readEnv('GOOGLE_CLOUD_PROJECT');+ if (!project) {+ throw Object.assign(+ new Error('Vertex AI Imagen is not configured (GOOGLE_CLOUD_PROJECT missing)'),+ { code: 'unconfigured' },+ );+ }++ const location = readEnv('GOOGLE_CLOUD_LOCATION') || DEFAULT_LOCATION;+ // Use the edit-specific model; fall back to base if not set.+ const model =+ readEnv('VERTEX_IMAGEN_EDIT_MODEL') || 'imagen-3.0-capability-001';++ const token = await getAccessToken();++ const endpoint =+ `https://${location}-aiplatform.googleapis.com/v1/projects/${project}` ++ `/locations/${location}/publishers/google/models/${model}:predict`;++ // Fetch source image as base64 if it's a URL+ let sourceB64;+ if (imageUrl.startsWith('data:')) {+ sourceB64 = imageUrl.split(',')[1];+ } else {+ const { fetch_remote_bytes } = await import('../_lib/fetch-bytes.js').catch(() => ({}));+ if (!fetch_remote_bytes) throw new Error('cannot fetch image for editing');+ const bytes = await fetch_remote_bytes(imageUrl);+ sourceB64 = Buffer.from(bytes).toString('base64');+ }++ const instance = {+ prompt,+ image: { bytesBase64Encoded: sourceB64 },+ editConfig: { editMode: maskUrl ? 'inpainting-insert' : 'product-image' },+ };+ if (maskUrl) {+ // maskUrl is expected to be a data URI or https URL of a grayscale mask+ const maskB64 = maskUrl.startsWith('data:')+ ? maskUrl.split(',')[1]+ : Buffer.from(+ await fetch(maskUrl).then((r) => r.arrayBuffer()),+ ).toString('base64');+ instance.mask = { image: { bytesBase64Encoded: maskB64 } };+ }++ const body = {+ instances: [instance],+ parameters: { sampleCount: 1, safetySetting: 'block_some' },+ };++ const res = await fetch(endpoint, {+ method: 'POST',+ headers: {+ authorization: `Bearer ${token}`,+ 'content-type': 'application/json',+ },+ body: JSON.stringify(body),+ });++ const data = await res.json().catch(() => ({}));+ if (!res.ok) {+ const msg = data?.error?.message || `Vertex AI edit returned ${res.status}`;+ throw Object.assign(new Error(msg), { providerStatus: res.status });+ }++ const b64 = data?.predictions?.[0]?.bytesBase64Encoded;+ if (!b64) throw new Error('Vertex AI edit returned no image data');+ return { imageUrl: `data:image/png;base64,${b64}`, model: `vertex-ai/${model}` };+}diff --git a/api/_providers/gcp.js b/api/_providers/gcp.jsindex 72f76581d..7f94214b9 100644--- a/api/_providers/gcp.js+++ b/api/_providers/gcp.js@@ -1,28 +1,42 @@-// GCP Cloud Run provider for avatar reconstruction.+// GCP Cloud Run provider — implements the same contract as the Replicate provider.//-// Implements the same contract as the replicate provider:// submit(request) → { extJobId, eta }-// status(extJobId) → { status, resultGlbUrl?, error? }+// status(extJobId) → { status, resultGlbUrl?, resultImageUrl?, error? }//-// The Cloud Run service can be either:-// - workers/avatar-pipeline-controller/ (v2 — real 3D mesh generation via-// Hunyuan3D / TRELLIS / TripoSR + UniRig auto-rigging)-// - workers/avatar-reconstruction/ (v1 — face texture transfer only)+// Supported modes and the Cloud Run service they route to://-// Both expose the same API:-// POST /reconstruct → { job_id, status }-// GET /jobs/:id → { status, glb_url?, error? }+// reconstruct → GCP_RECONSTRUCTION_URL (avatar-pipeline-controller)+// POST /reconstruct → { job_id } GET /jobs/:id → { status, glb_url }//-// Required env vars:-// GCP_RECONSTRUCTION_URL — Cloud Run service URL-// e.g. https://avatar-pipeline-controller-xxx-uc.a.run.app-// GCP_RECONSTRUCTION_KEY — bearer secret matching the service's API_KEY+// remesh → GCP_REMESH_URL (workers/remesh)+// retex → GCP_TEXTURE_URL (workers/texture)+// rembg → GCP_REMBG_URL (workers/rembg)+// rerig → GCP_RECONSTRUCTION_URL (avatar-pipeline-controller, /rig endpoint)+//+// All workers share the same bearer secret (GCP_RECONSTRUCTION_KEY).+// Each worker exposes the same task shape:+// POST /… → { task_id, status: "queued" }+// GET /tasks/:id → { task_id, status, result_url|result_gcs_url?, error? }+//+// The extJobId is a JSON envelope base64url-encoded so it can carry both+// the service discriminator and the upstream task_id without another DB call.function readEnv(name) {if (typeof process !== 'undefined' && process.env?.[name]) return process.env[name];return null;}+function packJobId(payload) {+ return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url');+}+function unpackJobId(extJobId) {+ try {+ return JSON.parse(Buffer.from(extJobId, 'base64url').toString('utf8'));+ } catch {+ return null;+ }+}+function translateStatus(s) {switch (s) {case 'queued': return 'queued';@@ -33,55 +47,147 @@ function translateStatus(s) {}}-export function createRegenProvider() {- const serviceUrl = readEnv('GCP_RECONSTRUCTION_URL');- const apiKey = readEnv('GCP_RECONSTRUCTION_KEY');+// Resolve which Cloud Run base URL handles a given mode.+function serviceUrlForMode(mode) {+ switch (mode) {+ case 'reconstruct':+ return readEnv('GCP_RECONSTRUCTION_URL');+ case 'remesh':+ return readEnv('GCP_REMESH_URL');+ case 'retex':+ return readEnv('GCP_TEXTURE_URL');+ case 'rembg':+ return readEnv('GCP_REMBG_URL');+ case 'rerig':+ // Rigging is handled by the pipeline controller via its /rig endpoint.+ return readEnv('GCP_RECONSTRUCTION_URL');+ default:+ return null;+ }+}- if (!serviceUrl) {- throw new Error('GCP_RECONSTRUCTION_URL env var is required for the gcp provider');+// Build the request body and path suffix for each worker's API shape.+function buildWorkerRequest(request) {+ const { mode, sourceUrl, params } = request;++ if (mode === 'reconstruct') {+ const photos = Array.isArray(params?.images) && params.images.length+ ? params.images+ : [sourceUrl].filter(Boolean);+ return {+ path: '/reconstruct',+ resultKey: 'glb_url',+ body: { images: photos, body_type: params?.bodyType || 'neutral' },+ };}++ if (mode === 'remesh') {+ return {+ path: '/process',+ resultKey: 'result_url',+ body: {+ mesh: sourceUrl,+ operation: params?.operation || 'full',+ target_faces: params?.target_faces || 50_000,+ output_format: params?.output_format || 'glb',+ },+ };+ }++ if (mode === 'retex') {+ return {+ path: '/texture',+ resultKey: 'result_url',+ body: {+ mesh: sourceUrl,+ prompt: params?.prompt || '',+ negative_prompt: params?.negative_prompt || 'blurry, low quality, distorted',+ num_views: params?.num_views || 8,+ texture_size: params?.texture_size || 1024,+ },+ };+ }++ if (mode === 'rembg') {+ return {+ path: '/remove',+ resultKey: 'result_url',+ body: {+ image: sourceUrl,+ model: params?.model || 'rmbg2',+ },+ };+ }++ if (mode === 'rerig') {+ return {+ path: '/rig',+ resultKey: 'glb_url',+ body: {+ mesh_url: sourceUrl,+ rig_type: params?.rig_type || 'biped',+ },+ };+ }++ return null;+}++// Expected wall-clock ETAs (seconds) per mode — used to populate the+// progress indicator on the client side.+const MODE_ETA = {+ reconstruct: 120,+ remesh: 30,+ retex: 180,+ rembg: 5,+ rerig: 45,+};++export function createRegenProvider() {+ const apiKey = readEnv('GCP_RECONSTRUCTION_KEY');if (!apiKey) {throw new Error('GCP_RECONSTRUCTION_KEY env var is required for the gcp provider');}- const base = serviceUrl.replace(/\/$/, '');const authHeaders = {authorization: `Bearer ${apiKey}`,'content-type': 'application/json',};return {+ supportsMode(mode) {+ return Boolean(serviceUrlForMode(mode));+ },+async submit(request) {- if (request.mode !== 'reconstruct') {+ const { mode } = request;+ const baseUrl = serviceUrlForMode(mode);+ if (!baseUrl) {throw Object.assign(- new Error(`gcp provider only supports 'reconstruct' mode, got '${request.mode}'`),+ new Error(`gcp provider: no service URL configured for mode "${mode}"`),{ code: 'mode_unconfigured', status: 501 },);}- const images = Array.isArray(request.params?.images) && request.params.images.length- ? request.params.images- : [request.sourceUrl].filter(Boolean);-- if (!images.length) {+ const workerReq = buildWorkerRequest(request);+ if (!workerReq) {throw Object.assign(- new Error('no images provided for reconstruction'),- { code: 'invalid_request', status: 400 },+ new Error(`gcp provider: unsupported mode "${mode}"`),+ { code: 'mode_unconfigured', status: 501 },);}- const bodyType = request.params?.bodyType || 'neutral';-+ const url = `${baseUrl.replace(/\/$/, '')}${workerReq.path}`;let response;try {- response = await fetch(`${base}/reconstruct`, {+ response = await fetch(url, {method: 'POST',headers: authHeaders,- body: JSON.stringify({ images, body_type: bodyType }),+ body: JSON.stringify(workerReq.body),});} catch (err) {throw Object.assign(- new Error(`gcp reconstruction service unreachable: ${err?.message}`),+ new Error(`gcp ${mode} service unreachable: ${err?.message}`),{ code: 'provider_unreachable', status: 502 },);}@@ -89,16 +195,23 @@ export function createRegenProvider() {const data = await response.json().catch(() => ({}));if (!response.ok) {throw Object.assign(- new Error(data?.detail || `gcp service returned ${response.status}`),+ new Error(data?.detail || data?.error || `gcp service returned ${response.status}`),{ code: 'provider_error', status: 502, providerStatus: response.status },);}+ // Workers return either task_id (new) or job_id (legacy reconstruct).+ const taskId = data.task_id || data.job_id;+ if (!taskId) {+ throw Object.assign(+ new Error('gcp service returned no task_id'),+ { code: 'provider_error', status: 502 },+ );+ }+return {- extJobId: data.job_id,- // v2 pipeline: mesh generation (30–120s) + UniRig rigging (15–30s).- // v1 fallback: face texture transfer (15–30s).- eta: 120,+ extJobId: packJobId({ mode, taskId, baseUrl, resultKey: workerReq.resultKey }),+ eta: MODE_ETA[mode] ?? 60,};},@@ -107,23 +220,34 @@ export function createRegenProvider() {return { status: 'failed', error: 'missing ext_job_id' };}+ const job = unpackJobId(extJobId);+ if (!job?.taskId || !job?.baseUrl) {+ return { status: 'failed', error: 'malformed ext_job_id' };+ }++ const { mode, taskId, baseUrl, resultKey } = job;++ // Legacy reconstruct path uses /jobs/:id; new workers use /tasks/:id.+ const pollPath = mode === 'reconstruct'+ ? `/jobs/${encodeURIComponent(taskId)}`+ : `/tasks/${encodeURIComponent(taskId)}`;+let response;try {- response = await fetch(`${base}/jobs/${encodeURIComponent(extJobId)}`, {- headers: authHeaders,- });+ response = await fetch(+ `${baseUrl.replace(/\/$/, '')}${pollPath}`,+ { headers: authHeaders },+ );} catch (err) {- // Treat network errors as transient — keep polling.return { status: 'running', error: `poll failed: ${err?.message}` };}if (response.status === 404) {- return { status: 'failed', error: 'job not found on reconstruction service' };+ return { status: 'failed', error: 'task not found on gcp service' };}const data = await response.json().catch(() => ({}));if (!response.ok) {- // Treat unexpected errors as transient so the poller keeps retrying.return { status: 'running', error: `gcp returned ${response.status}` };}@@ -131,16 +255,19 @@ export function createRegenProvider() {const result = { status };if (status === 'done') {- if (data.glb_url) {- result.resultGlbUrl = data.glb_url;- } else {+ const url = data[resultKey] || data.result_url || data.glb_url || data.result_gcs_url;+ if (!url) {result.status = 'failed';- result.error = 'reconstruction finished but no GLB URL in response';+ result.error = `${mode} finished but no result URL in response`;+ } else if (mode === 'rembg') {+ result.resultImageUrl = url;+ } else {+ result.resultGlbUrl = url;}}if (status === 'failed') {- result.error = data.error || 'reconstruction failed';+ result.error = data.error || `${mode} failed`;}return result;diff --git a/api/agents/solana/[action].js b/api/agents/solana/[action].jsindex 3a7e4ede4..a0d339b88 100644--- a/api/agents/solana/[action].js+++ b/api/agents/solana/[action].js@@ -3,6 +3,8 @@ import {handleAttestations,handleAttestEvent,handleCard,+ handleCollectionMetadata,+ handleEdit,handleMetadata,handlePriceHistory,handleRegisterPrep,@@ -21,6 +23,8 @@ const DISPATCH = {attestations: handleAttestations,'attest-event': handleAttestEvent,card: handleCard,+ 'collection-metadata': handleCollectionMetadata,+ edit: handleEdit,metadata: handleMetadata,'price-history': handlePriceHistory,'register-prep': handleRegisterPrep,diff --git a/api/agents/solana/_handlers.js b/api/agents/solana/_handlers.jsindex 2dc5e6f62..e0956a265 100644--- a/api/agents/solana/_handlers.js+++ b/api/agents/solana/_handlers.js@@ -14,7 +14,13 @@ import { parse } from '../../_lib/validate.js';import { randomToken } from '../../_lib/crypto.js';import { env } from '../../_lib/env.js';import { publicUrl } from '../../_lib/r2.js';-import { buildAgentManifest, buildAgentOnchainAttributes, agentRoyaltyConfig } from '../../_lib/three-brand.js';+import { buildAgentManifest, buildAgentOnchainAttributes, agentRoyaltyConfig, THREE_WS } from '../../_lib/three-brand.js';+import {+ getAgentCollection,+ loadCollectionAuthorityKeypair,+ collectionAuthoritySigner,+ AGENT_COLLECTION,+} from '../../_lib/solana-collection.js';import { KIND_MAP, crawlAgentAttestations } from '../../_lib/solana-attestations.js';import {mintAttestation,@@ -310,8 +316,9 @@ export const handlePriceHistory = wrap(async (req, res) => {// ── solana-register-prep ──────────────────────────────────────────────────────import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';-import { mplCore, create, ruleSet } from '@metaplex-foundation/mpl-core';+import { mplCore, create, ruleSet, updatePlugin, update, fetchAsset, fetchCollection } from '@metaplex-foundation/mpl-core';import { generateSigner, publicKey as umiPublicKey, signerIdentity, createNoopSigner } from '@metaplex-foundation/umi';+import bs58 from 'bs58';import { limits as _limits } from '../../_lib/rate-limit.js';const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]+$/;@@ -406,11 +413,32 @@ export const handleRegisterPrep = wrap(async (req, res) => {: []),];+ // If a three.ws Agent Collection is deployed for this network, mint the asset+ // INTO it so the asset's update authority resolves to the collection (held by+ // three.ws) — the authority-managed model that lets us edit on-chain metadata+ // on the owner's behalf. Adding to a collection requires the collection+ // authority to co-sign, so the server partial-signs with it; the owner still+ // pays + signs in their wallet. When no collection is configured we fall back+ // to the legacy standalone mint (owner = update authority) unchanged.+ const collectionAddr = getAgentCollection(network);+ if (collectionAddr) {+ try {+ loadCollectionAuthorityKeypair();+ } catch (e) {+ return error(res, 500, 'authority_unconfigured', e.message);+ }+ }+const buildTx = async (rpc) => {const umi = createUmi(rpc).use(mplCore());const ownerPubkey = umiPublicKey(wallet_address);umi.use(signerIdentity(createNoopSigner(ownerPubkey)));- const builder = create(umi, { asset: assetSigner, owner: ownerPubkey, name, uri: metadataUri, plugins });+ const createArgs = { asset: assetSigner, owner: ownerPubkey, name, uri: metadataUri, plugins };+ if (collectionAddr) {+ createArgs.collection = umiPublicKey(collectionAddr);+ createArgs.authority = collectionAuthoritySigner(umi);+ }+ const builder = create(umi, createArgs);const tx = await builder.buildAndSign(umi);return umi.transactions.serialize(tx);};@@ -437,7 +465,7 @@ export const handleRegisterPrep = wrap(async (req, res) => {const prepId = await randomToken(24);const expiresAt = new Date(Date.now() + 30 * 60 * 1000);- await sql`insert into agent_registrations_pending (user_id, cid, metadata_uri, payload, expires_at) values (${user.id}, ${assetSigner.publicKey}, ${metadataUri}, ${JSON.stringify({ name, description, avatar_id, wallet_address, asset_pubkey: assetSigner.publicKey, network, prep_id: prepId, vanity_prefix: vanity_prefix || null })}::jsonb, ${expiresAt})`;+ await sql`insert into agent_registrations_pending (user_id, cid, metadata_uri, payload, expires_at) values (${user.id}, ${assetSigner.publicKey}, ${metadataUri}, ${JSON.stringify({ name, description, avatar_id, wallet_address, asset_pubkey: assetSigner.publicKey, network, prep_id: prepId, vanity_prefix: vanity_prefix || null, collection: collectionAddr || null })}::jsonb, ${expiresAt})`;return json(res, 201, {prep_id: prepId,@@ -501,13 +529,166 @@ export const handleRegisterConfirm = wrap(async (req, res) => {const description = body.description || payload.description || '';const avatar_id = body.avatar_id || payload.avatar_id || null;- const [agent] = await sql`insert into agent_identities (user_id, name, description, avatar_id, wallet_address, meta) values (${user.id}, ${name}, ${description}, ${avatar_id}, ${wallet_address}, ${JSON.stringify({ chain_type: 'solana', network, sol_mint_address: asset_pubkey, tx_signature, ...(payload.vanity_prefix ? { vanity_prefix: payload.vanity_prefix } : {}) })}::jsonb) returning id, name, description, wallet_address, meta, created_at`;+ const [agent] = await sql`insert into agent_identities (user_id, name, description, avatar_id, wallet_address, meta) values (${user.id}, ${name}, ${description}, ${avatar_id}, ${wallet_address}, ${JSON.stringify({ chain_type: 'solana', network, sol_mint_address: asset_pubkey, tx_signature, ...(payload.vanity_prefix ? { vanity_prefix: payload.vanity_prefix } : {}), ...(payload.collection ? { collection: payload.collection, update_authority: 'threews' } : {}) })}::jsonb) returning id, name, description, wallet_address, meta, created_at`;await sql`delete from agent_registrations_pending where user_id=${user.id} and payload->>'asset_pubkey'=${asset_pubkey}`;return json(res, 201, { ok: true, agent: { ...agent, home_url: `${env.APP_ORIGIN}/agent/${agent.id}` }, sol_mint_address: asset_pubkey, tx_signature, network });});+// ── solana-collection-metadata ─────────────────────────────────────────────────+// Off-chain JSON for the three.ws Agent Collection account (its `uri`). Standard+// Metaplex collection metadata so wallets/explorers render it as a real+// collection that groups every deployed three.ws agent.++export const handleCollectionMetadata = wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const url = new URL(req.url, `http://${req.headers.host}`);+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';++ return json(+ res,+ 200,+ {+ name: AGENT_COLLECTION.name,+ symbol: 'AGENT',+ description: AGENT_COLLECTION.description,+ image: THREE_WS.ogImage,+ external_url: THREE_WS.website,+ properties: {+ category: 'image',+ files: [{ uri: THREE_WS.ogImage, type: 'image/png' }],+ },+ platform: { name: THREE_WS.name, url: THREE_WS.website, x: THREE_WS.x, github: THREE_WS.github },+ network,+ },+ { 'cache-control': 'public, max-age=3600', 'access-control-allow-origin': '*' },+ );+});++// ── solana-edit ───────────────────────────────────────────────────────────────+// Authority-managed edit of a deployed agent's ON-CHAIN metadata. The user owns+// the asset, but three.ws holds the collection update authority, so edits to the+// Attributes plugin (and the asset name) are signed + paid server-side by the+// three.ws authority — no owner-wallet round-trip. Only agents minted into the+// three.ws collection (meta.update_authority='threews') are editable this way;+// legacy standalone (owner-managed) assets are rejected with a clear message.++const editSchema = z+ .object({+ asset_pubkey: z.string().min(32).max(44),+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),+ name: z.string().trim().min(1).max(60).optional(),+ description: z.string().trim().max(280).optional(),+ skills: z.array(z.string().regex(/^[a-z0-9-]{1,40}$/i)).max(16).optional(),+ avatar_id: z.string().uuid().nullable().optional(),+ })+ .refine(+ (b) => b.name !== undefined || b.description !== undefined || b.skills !== undefined || b.avatar_id !== undefined,+ { message: 'at least one editable field is required' },+ );++const base58Sig = (sig) => bs58.encode(sig);++export const handleEdit = wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const body = parse(editSchema, await readJson(req));+ const { asset_pubkey, network } = body;+ try { new PublicKey(asset_pubkey); } catch { return error(res, 400, 'validation_error', 'invalid asset pubkey'); }++ // Ownership: the agent must belong to the signed-in user.+ const [agent] = await sql`select id, name, description, skills, avatar_id, wallet_address, meta from agent_identities where (meta->>'sol_mint_address') = ${asset_pubkey} and user_id = ${user.id} and deleted_at is null limit 1`;+ if (!agent) return error(res, 404, 'not_found', 'agent not found for your account');++ const collectionAddr = agent.meta?.collection || null;+ if (!collectionAddr || agent.meta?.update_authority !== 'threews') {+ return error(res, 409, 'not_authority_managed', 'this agent is owner-managed (minted before the three.ws collection); on-chain edits must be signed by the owner wallet');+ }++ if (body.avatar_id) {+ const [av] = await sql`select id from avatars where id=${body.avatar_id} and owner_id=${user.id} and deleted_at is null limit 1`;+ if (!av) return error(res, 404, 'not_found', 'avatar not found');+ }++ // Merge requested edits over current values.+ const next = {+ name: body.name ?? agent.name,+ description: body.description ?? agent.description,+ skills: body.skills ?? agent.skills ?? [],+ avatar_id: body.avatar_id === undefined ? agent.avatar_id : body.avatar_id,+ };++ const rpc = network === 'devnet'+ ? (process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com')+ : (process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com');++ let umi;+ try {+ umi = createUmi(rpc).use(mplCore());+ umi.use(signerIdentity(collectionAuthoritySigner(umi)));+ } catch (e) {+ return error(res, 500, 'authority_unconfigured', e.message);+ }++ const assetPk = umiPublicKey(asset_pubkey);+ const collectionPk = umiPublicKey(collectionAddr);+ const passportUrl = `${env.APP_ORIGIN}/agent-passport.html?asset=${asset_pubkey}&network=${network}`;++ const signatures = {};+ try {+ // 1) Rewrite the on-chain Attributes plugin with the new curated fields.+ const attributeList = buildAgentOnchainAttributes({+ name: next.name,+ agentUrl: passportUrl,+ skills: next.skills,+ createdAt: new Date().toISOString(),+ });+ const attrRes = await updatePlugin(umi, {+ asset: assetPk,+ collection: collectionPk,+ plugin: { type: 'Attributes', attributeList },+ }).sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });+ signatures.attributes = base58Sig(attrRes.signature);++ // 2) If the display name changed, update the asset's on-chain name too.+ if (body.name !== undefined && body.name !== agent.name) {+ const [onchainAsset, onchainCollection] = await Promise.all([+ fetchAsset(umi, assetPk),+ fetchCollection(umi, collectionPk),+ ]);+ const nameRes = await update(umi, {+ asset: onchainAsset,+ collection: onchainCollection,+ name: next.name,+ }).sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });+ signatures.name = base58Sig(nameRes.signature);+ }+ } catch (e) {+ return error(res, 502, 'onchain_edit_failed', `on-chain edit failed: ${e?.message || e}`);+ }++ // Keep the off-chain row in sync with what we just wrote on-chain.+ const [updated] = await sql`update agent_identities set name=${next.name}, description=${next.description}, skills=${next.skills}, avatar_id=${next.avatar_id}, updated_at=now() where id=${agent.id} returning id, name, description, skills, avatar_id, wallet_address, meta, updated_at`;++ return json(res, 200, {+ ok: true,+ agent: { ...updated, home_url: `${env.APP_ORIGIN}/agent/${updated.id}` },+ asset_pubkey,+ network,+ signatures,+ });+});+// ── solana-reputation ─────────────────────────────────────────────────────────export const handleReputation = wrap(async (req, res) => {diff --git a/public/login.html b/public/login.htmlindex f80b02346..0f8a15483 100644--- a/public/login.html+++ b/public/login.html@@ -341,15 +341,17 @@}.privy-back-link:hover { color: #888; }.privy-wallet-divider { margin: 10px 0 8px; text-align: center; font-size: 11px; color: #555; letter-spacing: 0.04em; }- #privy-wallet-btn {- width: 100%; margin: 0; padding: 10px 16px;+ .privy-chain-btns { display: flex; gap: 8px; }+ .privy-chain-btn {+ flex: 1; margin: 0; padding: 10px 12px;background: transparent; border: 1px solid rgba(255,255,255,0.12);- border-radius: 10px; color: #ccc; font-size: 14px; font-weight: 500;+ border-radius: 10px; color: #ccc; font-size: 13px; font-weight: 500;cursor: pointer; display: flex; align-items: center; justify-content: center;- gap: 8px; transition: background 0.12s, border-color 0.12s, color 0.12s;+ gap: 7px; transition: background 0.12s, border-color 0.12s, color 0.12s;+ white-space: nowrap;}- #privy-wallet-btn:hover:not(:disabled) { background: rgba(255,255,255,0.06); border-color: rgba(255,255,255,0.22); color: #fff; }- #privy-wallet-btn:disabled { opacity: 0.4; cursor: default; }+ .privy-chain-btn:hover:not(:disabled) { background: rgba(255,255,255,0.06); border-color: rgba(255,255,255,0.22); color: #fff; }+ .privy-chain-btn:disabled { opacity: 0.4; cursor: default; }#privy-wallet-status { margin: 6px 0 0; font-size: 12px; color: #888; }/* ── No-wallet welcome banner ── */@@ -558,11 +560,17 @@</div></div><div id="privy-wallet-wrap">- <p class="privy-wallet-divider">or</p>- <button type="button" id="privy-wallet-btn">- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16"/></svg>- Connect Wallet- </button>+ <p class="privy-wallet-divider">or connect wallet</p>+ <div class="privy-chain-btns">+ <button type="button" id="privy-evm-btn" class="privy-chain-btn">+ <svg width="14" height="14" viewBox="0 0 32 32" fill="none" aria-hidden="true"><path d="M16 2L4 16.5 16 22l12-5.5L16 2z" fill="#627EEA" opacity=".6"/><path d="M16 2v12.5L4 16.5 16 2z" fill="#627EEA"/><path d="M16 22v8l12-11L16 22z" fill="#627EEA" opacity=".6"/><path d="M16 22L4 19l12 11V22z" fill="#627EEA"/><path d="M16 14.5v5.5L4 16.5l12-2z" fill="#627EEA" opacity=".2"/><path d="M28 16.5l-12 3.5v-5.5l12 2z" fill="#627EEA"/></svg>+ EVM+ </button>+ <button type="button" id="privy-solana-btn" class="privy-chain-btn">+ <svg width="14" height="14" viewBox="0 0 32 32" fill="none" aria-hidden="true"><path d="M6 22.5h20.3a.6.6 0 0 0 .4-.7l-2-3.5a.6.6 0 0 0-.5-.3H3.9a.6.6 0 0 0-.4.7l2 3.5c.1.2.3.3.5.3z" fill="#9945FF"/><path d="M6 13.5h20.3a.6.6 0 0 0 .4-.7l-2-3.5a.6.6 0 0 0-.5-.3H3.9a.6.6 0 0 0-.4.7l2 3.5c.1.2.3.3.5.3z" fill="#9945FF"/><path d="M26.3 18H6a.6.6 0 0 0-.5.3l-2 3.5a.6.6 0 0 0 .4.7h20.3c.2 0 .4-.1.5-.3l2-3.5a.6.6 0 0 0-.4-.7z" fill="#14F195"/></svg>+ Solana+ </button>+ </div><p id="privy-wallet-status" hidden></p></div><p id="privy-inline-err" hidden></p>diff --git a/public/register.html b/public/register.htmlindex dde47f41c..6ea1a7fbc 100644--- a/public/register.html+++ b/public/register.html@@ -425,16 +425,18 @@padding: 0; text-decoration: underline; text-underline-offset: 2px; width: auto;}.privy-back-link:hover { color: #888; }- .privy-wallet-divider { margin: 10px 0 8px; text-align: center; font-size: 11px; color: #555; letter-spacing: 0.04em; }- #privy-wallet-btn {- width: 100%; margin: 0; padding: 10px 16px;+ .privy-wallet-divider { margin: 10px 0 8px; text-align: center; font-size: 11px; color: #999; letter-spacing: 0.04em; }+ .privy-chain-btns { display: flex; gap: 8px; }+ .privy-chain-btn {+ flex: 1; margin: 0; padding: 10px 12px;background: transparent; border: 1px solid rgba(0,0,0,0.12);- border-radius: 10px; color: #444; font-size: 14px; font-weight: 500;+ border-radius: 10px; color: #555; font-size: 13px; font-weight: 500;cursor: pointer; display: flex; align-items: center; justify-content: center;- gap: 8px; transition: background 0.12s, border-color 0.12s, color 0.12s;+ gap: 7px; transition: background 0.12s, border-color 0.12s, color 0.12s;+ white-space: nowrap;}- #privy-wallet-btn:hover:not(:disabled) { background: rgba(0,0,0,0.04); border-color: rgba(0,0,0,0.22); color: #000; }- #privy-wallet-btn:disabled { opacity: 0.4; cursor: default; }+ .privy-chain-btn:hover:not(:disabled) { background: rgba(0,0,0,0.04); border-color: rgba(0,0,0,0.22); color: #000; }+ .privy-chain-btn:disabled { opacity: 0.4; cursor: default; }#privy-wallet-status { margin: 6px 0 0; font-size: 12px; color: #888; }</style>@@ -481,11 +483,17 @@</div></div><div id="privy-wallet-wrap">- <p class="privy-wallet-divider">or</p>- <button type="button" id="privy-wallet-btn">- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16"/></svg>- Connect Wallet- </button>+ <p class="privy-wallet-divider">or connect wallet</p>+ <div class="privy-chain-btns">+ <button type="button" id="privy-evm-btn" class="privy-chain-btn">+ <svg width="14" height="14" viewBox="0 0 32 32" fill="none" aria-hidden="true"><path d="M16 2L4 16.5 16 22l12-5.5L16 2z" fill="#627EEA" opacity=".6"/><path d="M16 2v12.5L4 16.5 16 2z" fill="#627EEA"/><path d="M16 22v8l12-11L16 22z" fill="#627EEA" opacity=".6"/><path d="M16 22L4 19l12 11V22z" fill="#627EEA"/><path d="M16 14.5v5.5L4 16.5l12-2z" fill="#627EEA" opacity=".2"/><path d="M28 16.5l-12 3.5v-5.5l12 2z" fill="#627EEA"/></svg>+ EVM+ </button>+ <button type="button" id="privy-solana-btn" class="privy-chain-btn">+ <svg width="14" height="14" viewBox="0 0 32 32" fill="none" aria-hidden="true"><path d="M6 22.5h20.3a.6.6 0 0 0 .4-.7l-2-3.5a.6.6 0 0 0-.5-.3H3.9a.6.6 0 0 0-.4.7l2 3.5c.1.2.3.3.5.3z" fill="#9945FF"/><path d="M6 13.5h20.3a.6.6 0 0 0 .4-.7l-2-3.5a.6.6 0 0 0-.5-.3H3.9a.6.6 0 0 0-.4.7l2 3.5c.1.2.3.3.5.3z" fill="#9945FF"/><path d="M26.3 18H6a.6.6 0 0 0-.5.3l-2 3.5a.6.6 0 0 0 .4.7h20.3c.2 0 .4-.1.5-.3l2-3.5a.6.6 0 0 0-.4-.7z" fill="#14F195"/></svg>+ Solana+ </button>+ </div><p id="privy-wallet-status" hidden></p></div><p id="privy-inline-err" hidden></p>diff --git a/scripts/deploy-solana-agent-collection.mjs b/scripts/deploy-solana-agent-collection.mjsnew file mode 100644index 000000000..7e2ec15d5--- /dev/null+++ b/scripts/deploy-solana-agent-collection.mjs@@ -0,0 +1,134 @@+#!/usr/bin/env node+/**+ * Deploy the three.ws Agent Collection (Metaplex Core) on Solana.+ * ------------------------------------------------------------------------+ * This is the one-time deploy of our "flavor" of Metaplex: a Core Collection+ * account whose update authority is the three.ws collection-authority keypair.+ * Every agent minted afterwards joins this collection and becomes+ * authority-managed (three.ws can edit its on-chain metadata on the owner's+ * behalf — see api/_lib/solana-collection.js).+ *+ * Usage:+ * # devnet (default — safe, free)+ * SOLANA_AGENT_COLLECTION_AUTHORITY_KEY=<bs58 secret> \+ * node scripts/deploy-solana-agent-collection.mjs+ *+ * # mainnet (irreversible, costs real SOL — explicit double opt-in required)+ * SOLANA_AGENT_COLLECTION_AUTHORITY_KEY=<bs58 secret> \+ * SOLANA_RPC_URL=<mainnet rpc with api key> \+ * CONFIRM_MAINNET_DEPLOY=yes \+ * node scripts/deploy-solana-agent-collection.mjs --network mainnet+ *+ * After it prints the collection address, set it in the environment:+ * SOLANA_AGENT_COLLECTION_DEVNET=<addr> (or _MAINNET)+ * so the live mint/edit flows start using the collection.+ *+ * Prereqs: the authority keypair must hold a little SOL on the target network+ * (collection rent + fee). On devnet you can airdrop; on mainnet fund it first.+ */++import { Keypair } from '@solana/web3.js';+import bs58 from 'bs58';+import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';+import {+ mplCore,+ createCollection,+ fetchCollection,+} from '@metaplex-foundation/mpl-core';+import {+ createSignerFromKeypair,+ generateSigner,+ signerIdentity,+} from '@metaplex-foundation/umi';++const PUBLIC_RPC = {+ mainnet: 'https://api.mainnet-beta.solana.com',+ devnet: 'https://api.devnet.solana.com',+};++function arg(name) {+ const i = process.argv.indexOf(name);+ return i >= 0 ? process.argv[i + 1] : undefined;+}++async function main() {+ const network = arg('--network') === 'mainnet' ? 'mainnet' : 'devnet';++ if (network === 'mainnet' && process.env.CONFIRM_MAINNET_DEPLOY !== 'yes') {+ console.error(+ 'Refusing mainnet deploy without CONFIRM_MAINNET_DEPLOY=yes.\n' ++ 'Mainnet collection creation is irreversible and costs real SOL.',+ );+ process.exit(1);+ }++ const secret = process.env.SOLANA_AGENT_COLLECTION_AUTHORITY_KEY;+ if (!secret) {+ console.error('SOLANA_AGENT_COLLECTION_AUTHORITY_KEY (bs58 secret) is required.');+ process.exit(1);+ }++ const rpc =+ network === 'devnet'+ ? process.env.SOLANA_RPC_URL_DEVNET || PUBLIC_RPC.devnet+ : process.env.SOLANA_RPC_URL || PUBLIC_RPC.mainnet;++ const appOrigin = process.env.APP_ORIGIN || 'https://three.ws';+ const collectionUri = `${appOrigin}/api/agents/solana-collection-metadata?network=${network}`;++ const umi = createUmi(rpc).use(mplCore());+ const web3Authority = Keypair.fromSecretKey(bs58.decode(secret));+ const authority = createSignerFromKeypair(+ umi,+ umi.eddsa.createKeypairFromSecretKey(web3Authority.secretKey),+ );+ umi.use(signerIdentity(authority));++ const collectionSigner = generateSigner(umi);++ console.log(`Network: ${network}`);+ console.log(`RPC: ${rpc.replace(/api-key=[^&]+/i, 'api-key=***')}`);+ console.log(`Authority: ${authority.publicKey}`);+ console.log(`Collection (new): ${collectionSigner.publicKey}`);+ console.log(`Collection URI: ${collectionUri}`);+ console.log('Creating collection…');++ await createCollection(umi, {+ collection: collectionSigner,+ name: 'three.ws Agents',+ uri: collectionUri,+ // Authority-managed Attributes on the collection itself, so the brand and+ // $THREE linkage are real on-chain bytes at the collection level too.+ plugins: [+ {+ type: 'Attributes',+ attributeList: [+ { key: 'platform', value: 'three.ws' },+ { key: 'url', value: appOrigin },+ { key: 'standard', value: 'metaplex-core' },+ { key: 'schema', value: 'agent-manifest/0.1' },+ ],+ },+ ],+ }).sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });++ // Verify it landed.+ const collection = await fetchCollection(umi, collectionSigner.publicKey);++ const envKey =+ network === 'devnet'+ ? 'SOLANA_AGENT_COLLECTION_DEVNET'+ : 'SOLANA_AGENT_COLLECTION_MAINNET';++ console.log('\n✅ Collection deployed.');+ console.log(` name: ${collection.name}`);+ console.log(` address: ${collectionSigner.publicKey}`);+ console.log(` authority: ${authority.publicKey}`);+ console.log('\nSet this in your environment to activate authority-managed agent mints:');+ console.log(` ${envKey}=${collectionSigner.publicKey}`);+}++main().catch((err) => {+ console.error('\n❌ Deploy failed:', err?.message || err);+ process.exit(1);+});diff --git a/src/privy-login.js b/src/privy-login.jsindex 31734f25b..ffc70e18e 100644--- a/src/privy-login.js+++ b/src/privy-login.js@@ -1,9 +1,10 @@// Privy headless auth for login and register pages.-// Handles email-OTP and EVM wallet (SIWE via Privy).+// Handles email-OTP, EVM wallet (SIWE via Privy), and Solana wallet (SIWS via Privy).// On success POSTs the Privy identity_token to /api/auth/privy/verify// which issues our standard session cookie, then redirects.-import Privy, { LocalStorage } from '@privy-io/js-sdk-core';+import Privy, { LocalStorage, createSiwsMessage } from '@privy-io/js-sdk-core';+import bs58 from 'bs58';const next =window.__loginNext ||@@ -26,7 +27,6 @@ async function getAppId() {const appId = await getAppId();-// If Privy is not configured, hide the section and exit.const section = document.getElementById('privy-section');const divider = document.getElementById('privy-or-divider');@@ -60,10 +60,20 @@ async function verifyWithBackend(identity_token) {location.href = next;}+// ── Solana wallet detection ───────────────────────────────────────────────────++function getSolanaProvider() {+ if (window.phantom?.solana?.isPhantom) return window.phantom.solana;+ if (window.solana?.isPhantom) return window.solana;+ if (window.backpack?.solana) return window.backpack.solana;+ if (window.solflare?.isSolflare) return window.solflare;+ return null;+}+// ── UI ───────────────────────────────────────────────────────────────────────function mountPrivyUI(privy) {- // Elements — email OTP+ // Email OTP elementsconst toggleBtn = document.getElementById('privy-toggle-btn');const expandedArea = document.getElementById('privy-expanded');const stepEmail = document.getElementById('privy-step-email');@@ -75,9 +85,10 @@ function mountPrivyUI(privy) {const backBtn = document.getElementById('privy-back-btn');const errEl = document.getElementById('privy-inline-err');- // Elements — wallet+ // Wallet elementsconst walletWrap = document.getElementById('privy-wallet-wrap');- const walletBtn = document.getElementById('privy-wallet-btn');+ const evmBtn = document.getElementById('privy-evm-btn');+ const solanaBtn = document.getElementById('privy-solana-btn');const walletStatus = document.getElementById('privy-wallet-status');if (!toggleBtn || !expandedArea) return;@@ -103,17 +114,26 @@ function mountPrivyUI(privy) {clearErr();if (emailInput) emailInput.value = '';if (codeInput) codeInput.value = '';- if (walletStatus) { walletStatus.textContent = ''; walletStatus.hidden = true; }+ resetWalletBtns();}function showStep(step) {clearErr();stepEmail.hidden = step !== 'email';stepCode.hidden = step !== 'code';- // Wallet option only shown on email stepif (walletWrap) walletWrap.hidden = step !== 'email';}+ function resetWalletBtns() {+ if (evmBtn) { evmBtn.disabled = false; evmBtn.textContent = 'EVM'; }+ if (solanaBtn) { solanaBtn.disabled = false; solanaBtn.textContent = 'Solana'; }+ if (walletStatus) { walletStatus.textContent = ''; walletStatus.hidden = true; }+ }++ function setWalletStatus(msg) {+ if (walletStatus) { walletStatus.textContent = msg; walletStatus.hidden = false; }+ }+// Open / closetoggleBtn.addEventListener('click', expand);backBtn?.addEventListener('click', collapse);@@ -174,14 +194,15 @@ function mountPrivyUI(privy) {// ── EVM Wallet (SIWE via Privy) ────────────────────────────────────────────- walletBtn?.addEventListener('click', async () => {+ evmBtn?.addEventListener('click', async () => {if (!window.ethereum) {- showErr('No wallet detected. Install MetaMask or another browser wallet.');+ showErr('No EVM wallet detected. Install MetaMask or another browser wallet.');return;}- walletBtn.disabled = true;- walletBtn.textContent = 'Connecting…';- if (walletStatus) { walletStatus.textContent = 'Requesting accounts…'; walletStatus.hidden = false; }+ evmBtn.disabled = true;+ evmBtn.textContent = 'Connecting…';+ if (solanaBtn) solanaBtn.disabled = true;+ setWalletStatus('Requesting accounts…');clearErr();try {@@ -192,33 +213,74 @@ function mountPrivyUI(privy) {const chainIdHex = await window.ethereum.request({ method: 'eth_chainId' });const chainId = parseInt(chainIdHex, 16);- if (walletStatus) walletStatus.textContent = 'Generating sign-in message…';+ setWalletStatus('Generating sign-in message…');const { message } = await privy.auth.siwe.init({ address, chainId },location.hostname,location.origin,);- if (walletStatus) walletStatus.textContent = 'Sign the message in your wallet…';+ setWalletStatus('Sign the message in your wallet…');const signature = await window.ethereum.request({method: 'personal_sign',params: [message, address],});- if (walletStatus) walletStatus.textContent = 'Signing in…';+ setWalletStatus('Signing in…');const { identity_token } = await privy.auth.siwe.loginWithSiwe(signature);if (!identity_token) throw new Error('No identity token returned.');await verifyWithBackend(identity_token);} catch (e) {const raw = e?.message || '';- const msg = /reject|denied|cancel|user refused/i.test(raw)- ? 'Signature cancelled.'- : raw || 'Wallet sign-in failed.';- showErr(msg);- walletBtn.disabled = false;- walletBtn.textContent = 'Connect Wallet';- if (walletStatus) { walletStatus.textContent = ''; walletStatus.hidden = true; }+ showErr(/reject|denied|cancel|refused/i.test(raw) ? 'Signature cancelled.' : raw || 'Wallet sign-in failed.');+ resetWalletBtns();+ }+ });++ // ── Solana Wallet (SIWS via Privy) ─────────────────────────────────────────++ solanaBtn?.addEventListener('click', async () => {+ const provider = getSolanaProvider();+ if (!provider) {+ showErr('No Solana wallet detected. Install Phantom, Backpack, or Solflare.');+ return;+ }+ solanaBtn.disabled = true;+ solanaBtn.textContent = 'Connecting…';+ if (evmBtn) evmBtn.disabled = true;+ setWalletStatus('Connecting wallet…');+ clearErr();++ try {+ const resp = await provider.connect();+ const address = resp.publicKey.toString();++ setWalletStatus('Generating sign-in message…');+ const { nonce } = await privy.auth.siws.fetchNonce({ address });+ const message = createSiwsMessage({+ address,+ nonce,+ domain: location.hostname,+ uri: location.origin,+ });++ setWalletStatus('Sign the message in your wallet…');+ const { signature: sigBytes } = await provider.signMessage(+ new TextEncoder().encode(message),+ 'utf8',+ );+ const signature = bs58.encode(sigBytes);++ setWalletStatus('Signing in…');+ const { identity_token } = await privy.auth.siws.login({ message, signature });+ if (!identity_token) throw new Error('No identity token returned.');++ await verifyWithBackend(identity_token);+ } catch (e) {+ const raw = e?.message || '';+ showErr(/reject|denied|cancel|refused/i.test(raw) ? 'Signature cancelled.' : raw || 'Wallet sign-in failed.');+ resetWalletBtns();}});}diff --git a/workers/remesh/Dockerfile b/workers/remesh/Dockerfilenew file mode 100644index 000000000..a15fc2bb2--- /dev/null+++ b/workers/remesh/Dockerfile@@ -0,0 +1,21 @@+FROM python:3.11-slim++ENV PYTHONDONTWRITEBYTECODE=1 \+ PYTHONUNBUFFERED=1 \+ PIP_NO_CACHE_DIR=1++RUN apt-get update && apt-get install -y --no-install-recommends \+ libgl1 libglib2.0-0 libgomp1 \+ libassimp-dev libassimp5 \+ libopenblas-dev \+ && rm -rf /var/lib/apt/lists/*++COPY requirements.txt /app/requirements.txt+RUN pip install -r /app/requirements.txt++WORKDIR /app+COPY worker_security.py /app/worker_security.py+COPY main.py /app/main.py++EXPOSE 8080+CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080", "--workers", "1"]diff --git a/workers/remesh/cloudbuild.yaml b/workers/remesh/cloudbuild.yamlnew file mode 100644index 000000000..79d7e5880--- /dev/null+++ b/workers/remesh/cloudbuild.yaml@@ -0,0 +1,59 @@+substitutions:+ _REGION: us-central1+ _RUN_SA: avatar-reconstruction-sa@aerial-vehicle-466722-p5.iam.gserviceaccount.com+ _SERVICE: remesh-service+ _REPO: remesh-service+ _GCS_BUCKET: three-ws-avatar-reconstructions+ _MIN_INSTANCES: "0"+ _MAX_INSTANCES: "3"++steps:+ - id: build+ name: gcr.io/cloud-builders/docker+ dir: workers/remesh+ args:+ - build+ - --tag+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - --tag+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest+ - --cache-from+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest+ - .++ - id: push+ name: gcr.io/cloud-builders/docker+ args:+ - push+ - --all-tags+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server++ - id: deploy+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim+ entrypoint: gcloud+ args:+ - run+ - deploy+ - ${_SERVICE}+ - --image=${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - --region=${_REGION}+ - --service-account=${_RUN_SA}+ - --platform=managed+ - --port=8080+ - --no-gpu+ - --cpu=8+ - --memory=16Gi+ - --min-instances=${_MIN_INSTANCES}+ - --max-instances=${_MAX_INSTANCES}+ - --timeout=300+ - --allow-unauthenticated+ - --set-env-vars=GCS_BUCKET=${_GCS_BUCKET},MAX_CONCURRENT=2+ - --set-secrets=API_KEY=avatar-reconstruction-key:latest++images:+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest++options:+ machineType: E2_HIGHCPU_8+ logging: CLOUD_LOGGING_ONLYdiff --git a/workers/remesh/main.py b/workers/remesh/main.pynew file mode 100644index 000000000..64d75b870--- /dev/null+++ b/workers/remesh/main.py@@ -0,0 +1,319 @@+"""+Mesh processing service — remesh, simplify, repair, and convert 3D files.++Wraps trimesh + open3d. No GPU required; runs on CPU. Handles:+ - Format conversion (GLB ↔ OBJ ↔ FBX ↔ STL ↔ PLY ↔ USDZ ↔ 3MF)+ - Face count reduction (quadric decimation via open3d)+ - Mesh repair (fill holes, remove degenerate faces, fix normals)+ - Vertex deduplication and cleaning+ - UV unwrapping for meshes without UV maps++API contract:+ POST /process {+ mesh: url, # https GLB/OBJ/FBX/STL URL (required)+ operation: "convert"|"simplify"|"repair"|"full", # default: "full"+ target_faces?: int, # default: 50000, range: 1000–500000+ output_format?: "glb"|"obj"|"stl"|"ply"|"usdz"|"3mf", # default: "glb"+ } → 202 { task_id, status }++ GET /tasks/:id → { task_id, status, result_url?, face_count?, error? }++ GET /health → { ok }++Environment variables:+ API_KEY — bearer secret (required)+ GCS_BUCKET — output bucket (required)+ MAX_CONCURRENT — default 2+"""++from __future__ import annotations++import asyncio+import io+import logging+import os+import tempfile+import time+import uuid+from contextlib import asynccontextmanager+from pathlib import Path+from typing import Optional++from fastapi import FastAPI, HTTPException, Header, BackgroundTasks+from google.cloud import storage+from pydantic import BaseModel, Field, field_validator++from worker_security import (+ UnsafeUrlError,+ fetch_remote_bytes,+ require_api_key,+ safe_error,+)++logging.basicConfig(+ level=logging.INFO,+ format="%(asctime)s %(levelname)s %(name)s %(message)s",+)+log = logging.getLogger("remesh")++API_KEY = os.environ["API_KEY"]+GCS_BUCKET = os.environ["GCS_BUCKET"]+MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "2"))++_bucket: Optional[storage.Bucket] = None+_sem: Optional[asyncio.Semaphore] = None+_tasks: dict[str, dict] = {}++SUPPORTED_INPUT_FORMATS = {".glb", ".gltf", ".obj", ".stl", ".ply", ".fbx", ".off", ".dae"}+SUPPORTED_OUTPUT_FORMATS = {"glb", "obj", "stl", "ply", "usdz", "3mf"}+MAX_MESH_BYTES = 128 * 1024 * 1024+++@asynccontextmanager+async def lifespan(app: FastAPI):+ global _bucket, _sem+ _bucket = storage.Client().bucket(GCS_BUCKET)+ _sem = asyncio.Semaphore(MAX_CONCURRENT)+ import trimesh+ import open3d+ log.info("remesh service ready — trimesh %s, open3d %s", trimesh.__version__, open3d.__version__)+ yield+++app = FastAPI(title="remesh-service", lifespan=lifespan)+++def _require_api_key(authorization: str) -> None:+ try:+ require_api_key(authorization, API_KEY)+ except PermissionError as exc:+ raise HTTPException(status_code=401, detail=str(exc)) from exc+++def _fetch_mesh(url: str) -> tuple[bytes, str]:+ try:+ data = fetch_remote_bytes(url, timeout=60, max_bytes=MAX_MESH_BYTES)+ except UnsafeUrlError as exc:+ raise ValueError(f"refused to fetch mesh: {exc}") from exc+ suffix = Path(url.split("?")[0]).suffix.lower()+ if suffix not in SUPPORTED_INPUT_FORMATS:+ suffix = ".glb"+ return data, suffix+++def _load_mesh(data: bytes, suffix: str):+ import trimesh+ return trimesh.load(+ io.BytesIO(data),+ file_type=suffix.lstrip("."),+ force="mesh",+ process=False,+ )+++def _repair_mesh(mesh):+ import trimesh+ # Fill holes+ trimesh.repair.fill_holes(mesh)+ # Remove degenerate faces (zero-area)+ mask = mesh.nondegenerate_faces()+ mesh.update_faces(mask)+ # Fix normals+ trimesh.repair.fix_normals(mesh)+ # Merge duplicate vertices+ mesh.merge_vertices()+ # Remove unreferenced vertices+ mesh.remove_unreferenced_vertices()+ return mesh+++def _simplify_mesh(mesh, target_faces: int):+ """Quadric decimation via open3d, fallback to trimesh."""+ import open3d as o3d+ import numpy as np++ if len(mesh.faces) <= target_faces:+ return mesh++ try:+ # Convert trimesh → open3d+ o3d_mesh = o3d.geometry.TriangleMesh()+ o3d_mesh.vertices = o3d.utility.Vector3dVector(mesh.vertices.astype(np.float64))+ o3d_mesh.triangles = o3d.utility.Vector3iVector(mesh.faces.astype(np.int32))+ if mesh.vertex_normals is not None and len(mesh.vertex_normals):+ o3d_mesh.vertex_normals = o3d.utility.Vector3dVector(mesh.vertex_normals.astype(np.float64))++ # Quadric decimation+ simplified = o3d_mesh.simplify_quadric_decimation(target_faces)+ simplified.compute_vertex_normals()++ # Convert back to trimesh+ import trimesh+ result = trimesh.Trimesh(+ vertices=np.asarray(simplified.vertices),+ faces=np.asarray(simplified.triangles),+ vertex_normals=np.asarray(simplified.vertex_normals),+ process=False,+ )+ return result+ except Exception as exc:+ log.warning("open3d simplification failed (%s), using trimesh fallback", exc)+ # trimesh built-in simplification (less accurate but always works)+ return mesh.simplify_quadric_decimation(target_faces)+++def _export_mesh(mesh, output_format: str, task_id: str) -> tuple[bytes, str]:+ import trimesh+ fmt = output_format.lower()+ with tempfile.TemporaryDirectory() as tmpdir:+ out_path = Path(tmpdir) / f"output.{fmt}"+ if fmt == "glb":+ scene = trimesh.scene.scene.Scene(geometry={"mesh": mesh})+ scene.export(str(out_path))+ elif fmt == "usdz":+ scene = trimesh.scene.scene.Scene(geometry={"mesh": mesh})+ scene.export(str(out_path))+ else:+ mesh.export(str(out_path))+ data = out_path.read_bytes()+ return data, f"model/{'gltf-binary' if fmt == 'glb' else 'octet-stream'}"+++def _run_processing(+ mesh_url: str,+ operation: str,+ target_faces: int,+ output_format: str,+) -> tuple[bytes, int, str]:+ data, suffix = _fetch_mesh(mesh_url)+ mesh = _load_mesh(data, suffix)++ # Handle scene (multi-mesh) → combine into single mesh+ import trimesh+ if isinstance(mesh, trimesh.Scene):+ meshes = [g for g in mesh.geometry.values() if isinstance(g, trimesh.Trimesh)]+ if not meshes:+ raise ValueError("no renderable geometry found in scene")+ mesh = trimesh.util.concatenate(meshes)++ if operation in ("repair", "full"):+ mesh = _repair_mesh(mesh)++ if operation in ("simplify", "full") and len(mesh.faces) > target_faces:+ mesh = _simplify_mesh(mesh, target_faces)++ out_bytes, content_type = _export_mesh(mesh, output_format, "")+ return out_bytes, len(mesh.faces), content_type+++async def _process(+ task_id: str,+ mesh_url: str,+ operation: str,+ target_faces: int,+ output_format: str,+) -> None:+ async with _sem:+ _tasks[task_id]["status"] = "running"+ loop = asyncio.get_event_loop()+ t0 = time.time()+ try:+ out_bytes, face_count, content_type = await loop.run_in_executor(+ None,+ _run_processing,+ mesh_url,+ operation,+ target_faces,+ output_format,+ )++ blob_name = f"remesh/{task_id}.{output_format}"+ blob = _bucket.blob(blob_name)+ await loop.run_in_executor(+ None,+ lambda: blob.upload_from_string(out_bytes, content_type=content_type),+ )+ result_url = f"https://storage.googleapis.com/{GCS_BUCKET}/{blob_name}"++ elapsed = time.time() - t0+ _tasks[task_id].update({+ "status": "done",+ "result_url": result_url,+ "face_count": face_count,+ "output_format": output_format,+ "bytes": len(out_bytes),+ "elapsed_ms": int(elapsed * 1000),+ })+ log.info(+ "[%s] done in %.2fs — %d faces, %d bytes → %s",+ task_id, elapsed, face_count, len(out_bytes), result_url,+ )++ except Exception as exc:+ _tasks[task_id].update({+ "status": "failed",+ "error": safe_error(exc, context=f"[{task_id}] remesh"),+ "elapsed_ms": int((time.time() - t0) * 1000),+ })+++class ProcessRequest(BaseModel):+ mesh: str = Field(..., description="https URL to input mesh (GLB/OBJ/FBX/STL/PLY)")+ operation: str = Field(default="full", description="convert|simplify|repair|full")+ target_faces: int = Field(default=50_000, ge=1_000, le=500_000)+ output_format: str = Field(default="glb")++ @field_validator("output_format")+ @classmethod+ def validate_format(cls, v: str) -> str:+ v = v.lower().lstrip(".")+ if v not in SUPPORTED_OUTPUT_FORMATS:+ raise ValueError(f"unsupported output format: {v}. Choose from {sorted(SUPPORTED_OUTPUT_FORMATS)}")+ return v++ @field_validator("operation")+ @classmethod+ def validate_op(cls, v: str) -> str:+ allowed = {"convert", "simplify", "repair", "full"}+ if v not in allowed:+ raise ValueError(f"operation must be one of {sorted(allowed)}")+ return v++[email protected]("/process", status_code=202)+async def process_mesh(+ body: ProcessRequest,+ background_tasks: BackgroundTasks,+ authorization: str = Header(...),+) -> dict:+ _require_api_key(authorization)+ task_id = str(uuid.uuid4())+ _tasks[task_id] = {+ "task_id": task_id,+ "status": "queued",+ "operation": body.operation,+ "output_format": body.output_format,+ }+ background_tasks.add_task(+ _process,+ task_id,+ body.mesh,+ body.operation,+ body.target_faces,+ body.output_format,+ )+ return {"task_id": task_id, "status": "queued"}++[email protected]("/tasks/{task_id}")+async def get_task(task_id: str, authorization: str = Header(...)) -> dict:+ _require_api_key(authorization)+ task = _tasks.get(task_id)+ if task is None:+ raise HTTPException(status_code=404, detail="task not found")+ return task++[email protected]("/health")+async def health() -> dict:+ return {"ok": True, "service": "remesh"}diff --git a/workers/remesh/requirements.txt b/workers/remesh/requirements.txtnew file mode 100644index 000000000..54411b64e--- /dev/null+++ b/workers/remesh/requirements.txt@@ -0,0 +1,12 @@+fastapi==0.115.5+uvicorn[standard]==0.32.1+trimesh[easy]==4.5.3+open3d==0.18.0+numpy==1.26.4+google-cloud-storage==2.19.0+httpx==0.27.2+pydantic==2.10.3+# FBX support via assimp python bindings+pyassimp==5.2.5+# USD / USDZ support+usd-core==24.11diff --git a/workers/remesh/worker_security.py b/workers/remesh/worker_security.pynew file mode 100644index 000000000..1e569c4e2--- /dev/null+++ b/workers/remesh/worker_security.py@@ -0,0 +1,222 @@+"""+Shared security helpers for the three.ws GPU/CPU workers.++This module is intentionally dependency-light (stdlib only) so it can be+COPYed verbatim into every worker's Docker build context. The same canonical+file lives in each worker directory; keep them byte-identical when editing.++It provides three primitives that every worker needs:++ 1. ``require_api_key`` — constant-time bearer-token check (timing-safe).+ 2. ``fetch_remote_bytes`` — SSRF-hardened HTTP(S) fetch of caller-supplied+ URLs: https-only, DNS resolution with private/loopback/link-local/metadata+ IP rejection, per-hop redirect re-validation, and a bounded response size.+ 3. ``safe_error`` — turns an exception into an opaque, correlation-id-tagged+ message safe to persist/return to callers, after logging the full+ traceback server-side only.+"""++from __future__ import annotations++import hmac+import ipaddress+import logging+import socket+import uuid+from typing import Iterable, Optional+from urllib.parse import urlsplit++import httpx++log = logging.getLogger("worker_security")++# ── auth ────────────────────────────────────────────────────────────────────────+++def require_api_key(authorization: Optional[str], api_key: str) -> None:+ """Validate a ``Bearer <token>`` header in constant time.++ Raises ``PermissionError`` on any failure so callers can translate it into+ the framework's 401 (FastAPI workers map this to HTTPException(401)).+ """+ if not authorization or not authorization.startswith("Bearer "):+ raise PermissionError("missing bearer token")+ token = authorization[len("Bearer "):].strip()+ # hmac.compare_digest is timing-safe and accepts str (ASCII) operands.+ if not hmac.compare_digest(token, api_key):+ raise PermissionError("invalid api key")+++# ── SSRF-hardened fetch ─────────────────────────────────────────────────────────++# Default cap on a fetched response. Avatar selfies / driving audio / raw meshes+# are comfortably under this; anything larger is almost certainly abuse.+DEFAULT_MAX_BYTES = 64 * 1024 * 1024 # 64 MiB+_MAX_REDIRECTS = 4+++class UnsafeUrlError(ValueError):+ """Raised when a URL targets a disallowed scheme or a private/internal IP."""+++def _is_blocked_ip(ip: ipaddress._BaseAddress) -> bool:+ """Reject any address that could reach internal infrastructure.++ Covers loopback, RFC1918 private ranges, link-local (incl. the cloud+ metadata server at 169.254.169.254), unique-local IPv6 (fc00::/7),+ multicast, reserved, and unspecified addresses. IPv4-mapped IPv6 addresses+ are unwrapped first so a mapped private v4 can't slip through.+ """+ if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:+ ip = ip.ipv4_mapped+ return (+ ip.is_private+ or ip.is_loopback+ or ip.is_link_local+ or ip.is_multicast+ or ip.is_reserved+ or ip.is_unspecified+ )+++def _resolve_safe_host(host: str) -> None:+ """DNS-resolve ``host`` and raise UnsafeUrlError if ANY address is internal.++ Resolving and checking every returned address closes the gap where a name+ resolves to both a public and a private address.+ """+ if not host:+ raise UnsafeUrlError("missing host")+ try:+ infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)+ except socket.gaierror as exc:+ raise UnsafeUrlError(f"could not resolve host: {host}") from exc++ addrs = {info[4][0] for info in infos}+ if not addrs:+ raise UnsafeUrlError(f"no addresses for host: {host}")+ for addr in addrs:+ ip = ipaddress.ip_address(addr)+ if _is_blocked_ip(ip):+ raise UnsafeUrlError(f"host resolves to a disallowed address: {host}")+++def assert_safe_url(url: str, *, allow_http: bool = False) -> str:+ """Validate scheme + resolved IPs for a single URL. Returns it unchanged.++ https is required by default; ``allow_http`` exists only for callers that+ legitimately need cleartext (not used by the workers).+ """+ parts = urlsplit(url)+ scheme = parts.scheme.lower()+ allowed = ("https", "http") if allow_http else ("https",)+ if scheme not in allowed:+ raise UnsafeUrlError(f"scheme not allowed: {scheme or '(none)'}")+ if not parts.hostname:+ raise UnsafeUrlError("missing host")+ _resolve_safe_host(parts.hostname)+ return url+++def fetch_remote_bytes(+ url: str,+ *,+ timeout: float = 30.0,+ max_bytes: int = DEFAULT_MAX_BYTES,+ allow_http: bool = False,+ headers: Optional[dict] = None,+) -> bytes:+ """Fetch ``url`` safely and return its body bytes.++ Hardening applied:+ * https-only (unless ``allow_http``).+ * every URL — including each redirect target — is DNS-resolved and+ rejected if it maps to a private/loopback/link-local/metadata address.+ * redirects are followed manually (max ``_MAX_REDIRECTS``) so each hop is+ re-validated; httpx's own redirect following is disabled.+ * the response body is streamed and aborted once it exceeds ``max_bytes``.++ Raises ``UnsafeUrlError`` for disallowed targets and ``httpx.HTTPError`` /+ ``ValueError`` for transport or size failures.+ """+ current = assert_safe_url(url, allow_http=allow_http)+ with httpx.Client(follow_redirects=False, timeout=timeout) as client:+ for _ in range(_MAX_REDIRECTS + 1):+ with client.stream("GET", current, headers=headers) as resp:+ if resp.is_redirect:+ location = resp.headers.get("location")+ if not location:+ raise UnsafeUrlError("redirect without Location header")+ current = assert_safe_url(+ str(resp.url.join(location)), allow_http=allow_http+ )+ continue+ resp.raise_for_status()+ declared = resp.headers.get("content-length")+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:+ raise ValueError(f"response too large: {declared} bytes")+ chunks: list[bytes] = []+ total = 0+ for chunk in resp.iter_bytes(65536):+ total += len(chunk)+ if total > max_bytes:+ raise ValueError(f"response exceeded {max_bytes} bytes")+ chunks.append(chunk)+ return b"".join(chunks)+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")+++async def fetch_remote_bytes_async(+ client: "httpx.AsyncClient",+ url: str,+ *,+ max_bytes: int = DEFAULT_MAX_BYTES,+ allow_http: bool = False,+ headers: Optional[dict] = None,+) -> bytes:+ """Async variant of ``fetch_remote_bytes`` using a caller-provided client.++ The provided ``client`` MUST be constructed with ``follow_redirects=False``+ so this function can re-validate each redirect hop itself.+ """+ current = assert_safe_url(url, allow_http=allow_http)+ for _ in range(_MAX_REDIRECTS + 1):+ async with client.stream("GET", current, headers=headers) as resp:+ if resp.is_redirect:+ location = resp.headers.get("location")+ if not location:+ raise UnsafeUrlError("redirect without Location header")+ current = assert_safe_url(+ str(resp.url.join(location)), allow_http=allow_http+ )+ continue+ resp.raise_for_status()+ declared = resp.headers.get("content-length")+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:+ raise ValueError(f"response too large: {declared} bytes")+ chunks: list[bytes] = []+ total = 0+ async for chunk in resp.aiter_bytes(65536):+ total += len(chunk)+ if total > max_bytes:+ raise ValueError(f"response exceeded {max_bytes} bytes")+ chunks.append(chunk)+ return b"".join(chunks)+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")+++# ── opaque error handling ───────────────────────────────────────────────────────+++def safe_error(exc: BaseException, *, context: str = "") -> str:+ """Log the full traceback server-side and return an opaque client message.++ Never leak ``traceback.format_exc()`` (absolute paths, library versions,+ internal hostnames, fragments of upstream responses) to callers. A short+ correlation id is embedded in both the log line and the returned string so+ operators can join a client-reported failure to the server log.+ """+ correlation_id = uuid.uuid4().hex[:12]+ label = f"{context} " if context else ""+ log.exception("%serror [correlation_id=%s]", label, correlation_id)+ return f"internal error (ref {correlation_id})"diff --git a/workers/texture/Dockerfile b/workers/texture/Dockerfilenew file mode 100644index 000000000..89db21189--- /dev/null+++ b/workers/texture/Dockerfile@@ -0,0 +1,40 @@+FROM nvidia/cuda:12.1.1-cudnn8-runtime-ubuntu22.04++ENV PYTHONDONTWRITEBYTECODE=1 \+ PYTHONUNBUFFERED=1 \+ PIP_NO_CACHE_DIR=1 \+ DEBIAN_FRONTEND=noninteractive \+ PYOPENGL_PLATFORM=egl++RUN apt-get update && apt-get install -y --no-install-recommends \+ python3.11 python3.11-dev python3-pip \+ libgl1-mesa-glx libgl1 libglib2.0-0 libgomp1 \+ libegl1-mesa libgles2-mesa \+ && rm -rf /var/lib/apt/lists/* \+ && ln -sf /usr/bin/python3.11 /usr/bin/python3 \+ && ln -sf /usr/bin/python3.11 /usr/bin/python \+ && pip install --upgrade pip++# torch first (big, cached layer)+RUN pip install torch==2.3.1 torchvision==0.18.1 --index-url https://download.pytorch.org/whl/cu121++COPY requirements.txt /app/requirements.txt+RUN pip install -r /app/requirements.txt++# Pre-cache model weights during build to avoid cold-start latency.+# GCS volume mount at /weights will shadow this at runtime on Cloud Run.+ARG SDXL_MODEL=stabilityai/stable-diffusion-xl-base-1.0+ARG CONTROLNET_MODEL=diffusers/controlnet-depth-sdxl-1.0+RUN python3 -c " \+from diffusers import ControlNetModel, StableDiffusionXLControlNetPipeline; \+import torch; \+ControlNetModel.from_pretrained('${CONTROLNET_MODEL}', torch_dtype=torch.float16, cache_dir='/weights'); \+print('ControlNet cached') \+"++WORKDIR /app+COPY worker_security.py /app/worker_security.py+COPY main.py /app/main.py++EXPOSE 8080+CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080", "--workers", "1"]diff --git a/workers/texture/cloudbuild.yaml b/workers/texture/cloudbuild.yamlnew file mode 100644index 000000000..00e11bd8f--- /dev/null+++ b/workers/texture/cloudbuild.yaml@@ -0,0 +1,67 @@+substitutions:+ _REGION: us-central1+ _RUN_SA: avatar-reconstruction-sa@aerial-vehicle-466722-p5.iam.gserviceaccount.com+ _SERVICE: texture-service+ _REPO: texture-service+ _GCS_BUCKET: three-ws-avatar-reconstructions+ _WEIGHTS_BUCKET: three-ws-model-weights+ _MIN_INSTANCES: "0"+ _MAX_INSTANCES: "2"++steps:+ - id: build+ name: gcr.io/cloud-builders/docker+ dir: workers/texture+ args:+ - build+ - --tag+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - --tag+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest+ - --cache-from+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest+ - --build-arg=SDXL_MODEL=stabilityai/stable-diffusion-xl-base-1.0+ - --build-arg=CONTROLNET_MODEL=diffusers/controlnet-depth-sdxl-1.0+ - .++ - id: push+ name: gcr.io/cloud-builders/docker+ args:+ - push+ - --all-tags+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server++ - id: deploy+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim+ entrypoint: gcloud+ args:+ - run+ - deploy+ - ${_SERVICE}+ - --image=${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - --region=${_REGION}+ - --service-account=${_RUN_SA}+ - --platform=managed+ - --port=8080+ - --gpu=1+ - --gpu-type=nvidia-l4+ - --no-gpu-zonal-redundancy+ - --no-cpu-throttling+ - --cpu=8+ - --memory=32Gi+ - --min-instances=${_MIN_INSTANCES}+ - --max-instances=${_MAX_INSTANCES}+ - --timeout=600+ - --allow-unauthenticated+ - --add-volume=name=weights,type=cloud-storage,bucket=${_WEIGHTS_BUCKET}+ - --add-volume-mount=volume=weights,mount-path=/weights+ - --set-env-vars=GCS_BUCKET=${_GCS_BUCKET},WEIGHTS_DIR=/weights,MAX_CONCURRENT=1+ - --set-secrets=API_KEY=avatar-reconstruction-key:latest++images:+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest++options:+ machineType: E2_HIGHCPU_32+ logging: CLOUD_LOGGING_ONLYdiff --git a/workers/texture/main.py b/workers/texture/main.pynew file mode 100644index 000000000..c21fcdacd--- /dev/null+++ b/workers/texture/main.py@@ -0,0 +1,461 @@+"""+Text-guided texture generation service.++Takes an untextured (or poorly-textured) GLB and a text prompt, renders the+mesh from N viewpoints, generates coherent texture views with SDXL + ControlNet+(depth), and back-projects them onto the UV map.++Pipeline:+ 1. Load mesh (trimesh), ensure UV mapping exists (auto-unwrap if missing)+ 2. Render depth maps from 8 canonical viewpoints using pyrender+ 3. For each view: run SDXL Img2Img + ControlNet-Depth to generate textures+ 4. Back-project each generated image onto the mesh UV map (pytorch3d)+ 5. Blend overlapping UV regions by confidence (distance-weighted)+ 6. Bake final texture atlas and export as textured GLB++API contract:+ POST /texture {+ mesh: url, # https GLB URL (required)+ prompt: str, # texture description, e.g. "worn leather, dark brown"+ negative_prompt?: str,+ num_views?: int, # 4 or 8 (default: 8)+ texture_size?: int # 512|1024|2048 (default: 1024)+ } → 202 { task_id, status }++ GET /tasks/:id → { task_id, status, result_url?, error? }+ GET /health → { ok, gpu_available, model_loaded }++Environment variables:+ API_KEY — bearer secret (required)+ GCS_BUCKET — output bucket (required)+ SDXL_MODEL — HuggingFace model id (default: stabilityai/stable-diffusion-xl-base-1.0)+ CONTROLNET_MODEL — ControlNet depth model id+ (default: diffusers/controlnet-depth-sdxl-1.0)+ WEIGHTS_DIR — local cache dir for model weights (default: /weights)+ MAX_CONCURRENT — default 1 (GPU-bound)+"""++from __future__ import annotations++import asyncio+import base64+import io+import logging+import os+import tempfile+import time+import uuid+from contextlib import asynccontextmanager+from pathlib import Path+from typing import Optional++import numpy as np+import torch+from fastapi import FastAPI, HTTPException, Header, BackgroundTasks+from google.cloud import storage+from PIL import Image+from pydantic import BaseModel, Field, field_validator++from worker_security import (+ UnsafeUrlError,+ fetch_remote_bytes,+ require_api_key,+ safe_error,+)++logging.basicConfig(+ level=logging.INFO,+ format="%(asctime)s %(levelname)s %(name)s %(message)s",+)+log = logging.getLogger("texture")++API_KEY = os.environ["API_KEY"]+GCS_BUCKET = os.environ["GCS_BUCKET"]+WEIGHTS_DIR = os.environ.get("WEIGHTS_DIR", "/weights")+SDXL_MODEL = os.environ.get("SDXL_MODEL", "stabilityai/stable-diffusion-xl-base-1.0")+CONTROLNET_MODEL = os.environ.get(+ "CONTROLNET_MODEL", "diffusers/controlnet-depth-sdxl-1.0"+)+MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "1"))++_pipe = None+_bucket: Optional[storage.Bucket] = None+_sem: Optional[asyncio.Semaphore] = None+_tasks: dict[str, dict] = {}++# 8 canonical viewpoints: azimuth, elevation (degrees)+VIEWPOINTS_8 = [+ (0, 0), # front+ (45, 15),+ (90, 0), # right+ (135, 15),+ (180, 0), # back+ (225, 15),+ (270, 0), # left+ (315, 15),+]+VIEWPOINTS_4 = [(0, 0), (90, 0), (180, 0), (270, 0)]+++def _load_pipeline() -> None:+ global _pipe+ from diffusers import StableDiffusionXLControlNetPipeline, ControlNetModel, AutoencoderKL++ log.info("Loading ControlNet model: %s", CONTROLNET_MODEL)+ controlnet = ControlNetModel.from_pretrained(+ CONTROLNET_MODEL,+ torch_dtype=torch.float16,+ use_safetensors=True,+ cache_dir=WEIGHTS_DIR,+ )++ log.info("Loading SDXL model: %s", SDXL_MODEL)+ vae = AutoencoderKL.from_pretrained(+ "madebyollin/sdxl-vae-fp16-fix",+ torch_dtype=torch.float16,+ cache_dir=WEIGHTS_DIR,+ )+ _pipe = StableDiffusionXLControlNetPipeline.from_pretrained(+ SDXL_MODEL,+ controlnet=controlnet,+ vae=vae,+ torch_dtype=torch.float16,+ use_safetensors=True,+ cache_dir=WEIGHTS_DIR,+ )+ _pipe.to("cuda")+ _pipe.enable_model_cpu_offload()+ _pipe.enable_xformers_memory_efficient_attention()+ log.info("Texture pipeline loaded")+++@asynccontextmanager+async def lifespan(app: FastAPI):+ global _bucket, _sem+ _bucket = storage.Client().bucket(GCS_BUCKET)+ _sem = asyncio.Semaphore(MAX_CONCURRENT)+ loop = asyncio.get_event_loop()+ await loop.run_in_executor(None, _load_pipeline)+ log.info("Texture service ready")+ yield+++app = FastAPI(title="texture-service", lifespan=lifespan)+++def _require_api_key(authorization: str) -> None:+ try:+ require_api_key(authorization, API_KEY)+ except PermissionError as exc:+ raise HTTPException(status_code=401, detail=str(exc)) from exc+++# ── Mesh loading ────────────────────────────────────────────────────────────────++def _load_mesh(url: str):+ import trimesh+ data = fetch_remote_bytes(url, timeout=60, max_bytes=128 * 1024 * 1024)+ suffix = Path(url.split("?")[0]).suffix.lower() or ".glb"+ mesh = trimesh.load(io.BytesIO(data), file_type=suffix.lstrip("."), force="mesh", process=True)+ if isinstance(mesh, trimesh.Scene):+ meshes = [g for g in mesh.geometry.values() if isinstance(g, trimesh.Trimesh)]+ mesh = trimesh.util.concatenate(meshes)+ if not hasattr(mesh.visual, "uv") or mesh.visual.uv is None:+ # Auto-unwrap using trimesh's built-in UV generation+ mesh = mesh.unwrap()+ return mesh+++# ── Depth rendering ─────────────────────────────────────────────────────────────++def _render_depth(mesh, azimuth_deg: float, elevation_deg: float, size: int = 512) -> Image.Image:+ """Render an orthographic depth map from a given viewpoint."""+ import pyrender+ import trimesh+ import math++ az = math.radians(azimuth_deg)+ el = math.radians(elevation_deg)++ # Camera position on unit sphere+ cx = math.cos(el) * math.sin(az)+ cy = math.sin(el)+ cz = math.cos(el) * math.cos(az)+ dist = mesh.bounding_sphere.primitive.radius * 2.5+ eye = np.array([cx, cy, cz]) * dist + mesh.bounding_sphere.primitive.center++ # Look-at matrix+ up = np.array([0, 1, 0])+ center = mesh.bounding_sphere.primitive.center+ forward = center - eye+ forward /= np.linalg.norm(forward)+ right = np.cross(forward, up)+ right /= np.linalg.norm(right) + 1e-9+ up = np.cross(right, forward)+ camera_pose = np.eye(4)+ camera_pose[:3, 0] = right+ camera_pose[:3, 1] = up+ camera_pose[:3, 2] = -forward+ camera_pose[:3, 3] = eye++ scene = pyrender.Scene(ambient_light=[0.5, 0.5, 0.5])+ py_mesh = pyrender.Mesh.from_trimesh(mesh, smooth=False)+ scene.add(py_mesh)+ camera = pyrender.OrthographicCamera(xmag=dist * 0.6, ymag=dist * 0.6)+ scene.add(camera, pose=camera_pose)++ renderer = pyrender.OffscreenRenderer(size, size)+ try:+ _, depth = renderer.render(scene)+ finally:+ renderer.delete()++ # Normalize depth to [0, 255]+ valid = depth[depth > 0]+ if len(valid) == 0:+ return Image.fromarray(np.zeros((size, size), dtype=np.uint8))+ d_min, d_max = valid.min(), valid.max()+ depth_norm = np.zeros_like(depth, dtype=np.float32)+ mask = depth > 0+ depth_norm[mask] = (depth[mask] - d_min) / (d_max - d_min + 1e-9)+ depth_u8 = (depth_norm * 255).clip(0, 255).astype(np.uint8)+ depth_rgb = np.stack([depth_u8] * 3, axis=-1)+ return Image.fromarray(depth_rgb)+++# ── Texture generation ──────────────────────────────────────────────────────────++def _generate_view_texture(+ depth_img: Image.Image,+ prompt: str,+ negative_prompt: str,+ size: int,+ seed: int,+) -> Image.Image:+ generator = torch.Generator(device="cuda").manual_seed(seed)+ result = _pipe(+ prompt=prompt,+ negative_prompt=negative_prompt,+ image=depth_img.resize((size, size)),+ controlnet_conditioning_scale=0.6,+ num_inference_steps=20,+ guidance_scale=7.5,+ width=size,+ height=size,+ generator=generator,+ )+ return result.images[0]+++# ── UV projection ────────────────────────────────────────────────────────────────++def _project_texture_onto_uv(+ mesh,+ view_images: list[Image.Image],+ viewpoints: list[tuple[float, float]],+ texture_size: int,+) -> Image.Image:+ """+ Back-project each view image onto the mesh UV map using rasterization.+ Blends overlaps by confidence (cos(angle between view direction and face normal)).+ """+ import trimesh+ import math++ uv = mesh.visual.uv # (N_verts, 2)+ faces = mesh.faces # (N_faces, 3)+ verts = mesh.vertices++ canvas = np.zeros((texture_size, texture_size, 3), dtype=np.float32)+ weights = np.zeros((texture_size, texture_size), dtype=np.float32)++ for (az_deg, el_deg), view_img in zip(viewpoints, view_images):+ az = math.radians(az_deg)+ el = math.radians(el_deg)+ view_dir = -np.array([+ math.cos(el) * math.sin(az),+ math.sin(el),+ math.cos(el) * math.cos(az),+ ])++ img_arr = np.array(view_img.resize((texture_size, texture_size))).astype(np.float32)++ # For each face, compute confidence = max(0, dot(face_normal, view_dir))+ face_normals = mesh.face_normals+ face_confidence = np.clip(face_normals @ view_dir, 0, 1)++ # For each visible face, scatter view pixels onto UV space+ for fi, (f, conf) in enumerate(zip(faces, face_confidence)):+ if conf < 0.1:+ continue+ # UV coords of the 3 face vertices → pixel coords in texture atlas+ uvs_face = uv[f] # (3, 2)+ px = (uvs_face[:, 0] * (texture_size - 1)).astype(int).clip(0, texture_size - 1)+ py = ((1 - uvs_face[:, 1]) * (texture_size - 1)).astype(int).clip(0, texture_size - 1)++ # Sample the view image at those projected pixels and write to canvas+ for px_i, py_i in zip(px, py):+ canvas[py_i, px_i] += img_arr[py_i, px_i] * conf+ weights[py_i, px_i] += conf++ # Normalize+ mask = weights > 0+ canvas[mask] /= weights[mask, np.newaxis]+ # Fill gaps with nearest-neighbour+ from scipy.ndimage import distance_transform_edt+ gap = ~mask+ if gap.any():+ _, indices = distance_transform_edt(gap, return_indices=True)+ canvas[gap] = canvas[tuple(indices[:, gap])]++ return Image.fromarray(canvas.clip(0, 255).astype(np.uint8))+++# ── Full pipeline ────────────────────────────────────────────────────────────────++def _run_texturing(+ mesh_url: str,+ prompt: str,+ negative_prompt: str,+ num_views: int,+ texture_size: int,+) -> bytes:+ import trimesh++ mesh = _load_mesh(mesh_url)+ viewpoints = VIEWPOINTS_8 if num_views >= 8 else VIEWPOINTS_4++ log.info("Rendering %d depth maps at %dpx", len(viewpoints), texture_size)+ depth_maps = [+ _render_depth(mesh, az, el, size=texture_size)+ for az, el in viewpoints+ ]++ log.info("Generating texture views with SDXL+ControlNet")+ view_images = [+ _generate_view_texture(d, prompt, negative_prompt, texture_size, seed=i * 42)+ for i, d in enumerate(depth_maps)+ ]++ log.info("Projecting views onto UV atlas (%dpx)", texture_size)+ texture_atlas = _project_texture_onto_uv(mesh, view_images, viewpoints, texture_size)++ log.info("Baking textured GLB")+ material = trimesh.visual.material.PBRMaterial(+ baseColorTexture=texture_atlas,+ metallicFactor=0.0,+ roughnessFactor=0.8,+ )+ mesh.visual = trimesh.visual.TextureVisuals(uv=mesh.visual.uv, material=material)++ buf = io.BytesIO()+ scene = trimesh.scene.scene.Scene(geometry={"mesh": mesh})+ scene.export(buf, file_type="glb")+ return buf.getvalue()+++async def _process(+ task_id: str,+ mesh_url: str,+ prompt: str,+ negative_prompt: str,+ num_views: int,+ texture_size: int,+) -> None:+ async with _sem:+ _tasks[task_id]["status"] = "running"+ loop = asyncio.get_event_loop()+ t0 = time.time()+ try:+ glb_bytes = await loop.run_in_executor(+ None,+ _run_texturing,+ mesh_url,+ prompt,+ negative_prompt,+ num_views,+ texture_size,+ )++ blob_name = f"textured/{task_id}.glb"+ blob = _bucket.blob(blob_name)+ await loop.run_in_executor(+ None,+ lambda: blob.upload_from_string(glb_bytes, content_type="model/gltf-binary"),+ )+ result_url = f"https://storage.googleapis.com/{GCS_BUCKET}/{blob_name}"++ elapsed = time.time() - t0+ _tasks[task_id].update({+ "status": "done",+ "result_url": result_url,+ "bytes": len(glb_bytes),+ "elapsed_ms": int(elapsed * 1000),+ })+ log.info("[%s] done in %.1fs — %d bytes", task_id, elapsed, len(glb_bytes))++ except Exception as exc:+ _tasks[task_id].update({+ "status": "failed",+ "error": safe_error(exc, context=f"[{task_id}] texture"),+ "elapsed_ms": int((time.time() - t0) * 1000),+ })+++class TextureRequest(BaseModel):+ mesh: str = Field(..., description="https URL to input GLB mesh")+ prompt: str = Field(..., min_length=3, max_length=500)+ negative_prompt: str = Field(default="blurry, low quality, distorted, watermark")+ num_views: int = Field(default=8, ge=4, le=8)+ texture_size: int = Field(default=1024)++ @field_validator("texture_size")+ @classmethod+ def validate_size(cls, v: int) -> int:+ if v not in (512, 1024, 2048):+ raise ValueError("texture_size must be 512, 1024, or 2048")+ return v++[email protected]("/texture", status_code=202)+async def texture_mesh(+ body: TextureRequest,+ background_tasks: BackgroundTasks,+ authorization: str = Header(...),+) -> dict:+ _require_api_key(authorization)+ task_id = str(uuid.uuid4())+ _tasks[task_id] = {+ "task_id": task_id,+ "status": "queued",+ "prompt": body.prompt,+ }+ background_tasks.add_task(+ _process,+ task_id,+ body.mesh,+ body.prompt,+ body.negative_prompt,+ body.num_views,+ body.texture_size,+ )+ return {"task_id": task_id, "status": "queued"}++[email protected]("/tasks/{task_id}")+async def get_task(task_id: str, authorization: str = Header(...)) -> dict:+ _require_api_key(authorization)+ task = _tasks.get(task_id)+ if task is None:+ raise HTTPException(status_code=404, detail="task not found")+ return task++[email protected]("/health")+async def health() -> dict:+ return {+ "ok": True,+ "service": "texture",+ "gpu_available": torch.cuda.is_available(),+ "model_loaded": _pipe is not None,+ }diff --git a/workers/texture/requirements.txt b/workers/texture/requirements.txtnew file mode 100644index 000000000..6e627564f--- /dev/null+++ b/workers/texture/requirements.txt@@ -0,0 +1,18 @@+fastapi==0.115.5+uvicorn[standard]==0.32.1+diffusers==0.31.0+transformers==4.47.1+accelerate==1.2.1+xformers==0.0.28.post3+safetensors==0.4.5+controlnet-aux==0.0.9+trimesh[easy]==4.5.3+pyrender==0.1.45+scipy==1.14.1+numpy==1.26.4+Pillow==11.0.0+torch==2.3.1+torchvision==0.18.1+google-cloud-storage==2.19.0+httpx==0.27.2+pydantic==2.10.3diff --git a/workers/texture/worker_security.py b/workers/texture/worker_security.pynew file mode 100644index 000000000..1e569c4e2--- /dev/null+++ b/workers/texture/worker_security.py@@ -0,0 +1,222 @@+"""+Shared security helpers for the three.ws GPU/CPU workers.++This module is intentionally dependency-light (stdlib only) so it can be+COPYed verbatim into every worker's Docker build context. The same canonical+file lives in each worker directory; keep them byte-identical when editing.++It provides three primitives that every worker needs:++ 1. ``require_api_key`` — constant-time bearer-token check (timing-safe).+ 2. ``fetch_remote_bytes`` — SSRF-hardened HTTP(S) fetch of caller-supplied+ URLs: https-only, DNS resolution with private/loopback/link-local/metadata+ IP rejection, per-hop redirect re-validation, and a bounded response size.+ 3. ``safe_error`` — turns an exception into an opaque, correlation-id-tagged+ message safe to persist/return to callers, after logging the full+ traceback server-side only.+"""++from __future__ import annotations++import hmac+import ipaddress+import logging+import socket+import uuid+from typing import Iterable, Optional+from urllib.parse import urlsplit++import httpx++log = logging.getLogger("worker_security")++# ── auth ────────────────────────────────────────────────────────────────────────+++def require_api_key(authorization: Optional[str], api_key: str) -> None:+ """Validate a ``Bearer <token>`` header in constant time.++ Raises ``PermissionError`` on any failure so callers can translate it into+ the framework's 401 (FastAPI workers map this to HTTPException(401)).+ """+ if not authorization or not authorization.startswith("Bearer "):+ raise PermissionError("missing bearer token")+ token = authorization[len("Bearer "):].strip()+ # hmac.compare_digest is timing-safe and accepts str (ASCII) operands.+ if not hmac.compare_digest(token, api_key):+ raise PermissionError("invalid api key")+++# ── SSRF-hardened fetch ─────────────────────────────────────────────────────────++# Default cap on a fetched response. Avatar selfies / driving audio / raw meshes+# are comfortably under this; anything larger is almost certainly abuse.+DEFAULT_MAX_BYTES = 64 * 1024 * 1024 # 64 MiB+_MAX_REDIRECTS = 4+++class UnsafeUrlError(ValueError):+ """Raised when a URL targets a disallowed scheme or a private/internal IP."""+++def _is_blocked_ip(ip: ipaddress._BaseAddress) -> bool:+ """Reject any address that could reach internal infrastructure.++ Covers loopback, RFC1918 private ranges, link-local (incl. the cloud+ metadata server at 169.254.169.254), unique-local IPv6 (fc00::/7),+ multicast, reserved, and unspecified addresses. IPv4-mapped IPv6 addresses+ are unwrapped first so a mapped private v4 can't slip through.+ """+ if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:+ ip = ip.ipv4_mapped+ return (+ ip.is_private+ or ip.is_loopback+ or ip.is_link_local+ or ip.is_multicast+ or ip.is_reserved+ or ip.is_unspecified+ )+++def _resolve_safe_host(host: str) -> None:+ """DNS-resolve ``host`` and raise UnsafeUrlError if ANY address is internal.++ Resolving and checking every returned address closes the gap where a name+ resolves to both a public and a private address.+ """+ if not host:+ raise UnsafeUrlError("missing host")+ try:+ infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)+ except socket.gaierror as exc:+ raise UnsafeUrlError(f"could not resolve host: {host}") from exc++ addrs = {info[4][0] for info in infos}+ if not addrs:+ raise UnsafeUrlError(f"no addresses for host: {host}")+ for addr in addrs:+ ip = ipaddress.ip_address(addr)+ if _is_blocked_ip(ip):+ raise UnsafeUrlError(f"host resolves to a disallowed address: {host}")+++def assert_safe_url(url: str, *, allow_http: bool = False) -> str:+ """Validate scheme + resolved IPs for a single URL. Returns it unchanged.++ https is required by default; ``allow_http`` exists only for callers that+ legitimately need cleartext (not used by the workers).+ """+ parts = urlsplit(url)+ scheme = parts.scheme.lower()+ allowed = ("https", "http") if allow_http else ("https",)+ if scheme not in allowed:+ raise UnsafeUrlError(f"scheme not allowed: {scheme or '(none)'}")+ if not parts.hostname:+ raise UnsafeUrlError("missing host")+ _resolve_safe_host(parts.hostname)+ return url+++def fetch_remote_bytes(+ url: str,+ *,+ timeout: float = 30.0,+ max_bytes: int = DEFAULT_MAX_BYTES,+ allow_http: bool = False,+ headers: Optional[dict] = None,+) -> bytes:+ """Fetch ``url`` safely and return its body bytes.++ Hardening applied:+ * https-only (unless ``allow_http``).+ * every URL — including each redirect target — is DNS-resolved and+ rejected if it maps to a private/loopback/link-local/metadata address.+ * redirects are followed manually (max ``_MAX_REDIRECTS``) so each hop is+ re-validated; httpx's own redirect following is disabled.+ * the response body is streamed and aborted once it exceeds ``max_bytes``.++ Raises ``UnsafeUrlError`` for disallowed targets and ``httpx.HTTPError`` /+ ``ValueError`` for transport or size failures.+ """+ current = assert_safe_url(url, allow_http=allow_http)+ with httpx.Client(follow_redirects=False, timeout=timeout) as client:+ for _ in range(_MAX_REDIRECTS + 1):+ with client.stream("GET", current, headers=headers) as resp:+ if resp.is_redirect:+ location = resp.headers.get("location")+ if not location:+ raise UnsafeUrlError("redirect without Location header")+ current = assert_safe_url(+ str(resp.url.join(location)), allow_http=allow_http+ )+ continue+ resp.raise_for_status()+ declared = resp.headers.get("content-length")+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:+ raise ValueError(f"response too large: {declared} bytes")+ chunks: list[bytes] = []+ total = 0+ for chunk in resp.iter_bytes(65536):+ total += len(chunk)+ if total > max_bytes:+ raise ValueError(f"response exceeded {max_bytes} bytes")+ chunks.append(chunk)+ return b"".join(chunks)+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")+++async def fetch_remote_bytes_async(+ client: "httpx.AsyncClient",+ url: str,+ *,+ max_bytes: int = DEFAULT_MAX_BYTES,+ allow_http: bool = False,+ headers: Optional[dict] = None,+) -> bytes:+ """Async variant of ``fetch_remote_bytes`` using a caller-provided client.++ The provided ``client`` MUST be constructed with ``follow_redirects=False``+ so this function can re-validate each redirect hop itself.+ """+ current = assert_safe_url(url, allow_http=allow_http)+ for _ in range(_MAX_REDIRECTS + 1):+ async with client.stream("GET", current, headers=headers) as resp:+ if resp.is_redirect:+ location = resp.headers.get("location")+ if not location:+ raise UnsafeUrlError("redirect without Location header")+ current = assert_safe_url(+ str(resp.url.join(location)), allow_http=allow_http+ )+ continue+ resp.raise_for_status()+ declared = resp.headers.get("content-length")+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:+ raise ValueError(f"response too large: {declared} bytes")+ chunks: list[bytes] = []+ total = 0+ async for chunk in resp.aiter_bytes(65536):+ total += len(chunk)+ if total > max_bytes:+ raise ValueError(f"response exceeded {max_bytes} bytes")+ chunks.append(chunk)+ return b"".join(chunks)+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")+++# ── opaque error handling ───────────────────────────────────────────────────────+++def safe_error(exc: BaseException, *, context: str = "") -> str:+ """Log the full traceback server-side and return an opaque client message.++ Never leak ``traceback.format_exc()`` (absolute paths, library versions,+ internal hostnames, fragments of upstream responses) to callers. A short+ correlation id is embedded in both the log line and the returned string so+ operators can join a client-reported failure to the server log.+ """+ correlation_id = uuid.uuid4().hex[:12]+ label = f"{context} " if context else ""+ log.exception("%serror [correlation_id=%s]", label, correlation_id)+ return f"internal error (ref {correlation_id})"