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
forge(variants): add the web-GLB variant cron and finish the delivery wiring
nirholas32de492e90b4
diff --git a/CLAUDE.md b/CLAUDE.mdindex 40385610c..71a677786 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -305,7 +305,7 @@ The whole build + submit + purge in one command: `npm run deploy:gcp:full`.- Frontend: vanilla JS modules + Vite (`npm run dev`, port 3000).- 3D: Three.js with glTF/GLB.- Backend touchpoints: serverless-style handlers in `api/`, workers in `workers/`.-- **Production runs on Google Cloud Run, NOT Vercel** (migrated 2026-07-07 after Vercel disabled the deployment). One container ([server/index.mjs](server/index.mjs)) serves the static frontend, the vercel.json route table, and all `api/**` handlers; the crons (114 as of 2026-09-03, see vercel.json) run on Cloud Scheduler. `vercel.json` is a LIVE config file: `server/index.mjs` reads its `routes` array on boot (split at the `{handle:"filesystem"}` marker into pre- and post-filesystem phases), and `scripts/create-gcp-scheduler.mjs` reads its `crons` array to sync Cloud Scheduler jobs. The server itself never reads `crons`. Never delete `vercel.json` as a leftover. GCP builds/deploys must pin the `three-ws-build@` (build) and `three-ws@` (runtime) service accounts; the project's default compute SA was deleted. Deploys: see the "Deploy runbook" section above.+- **Production runs on Google Cloud Run, NOT Vercel** (migrated 2026-07-07 after Vercel disabled the deployment). One container ([server/index.mjs](server/index.mjs)) serves the static frontend, the vercel.json route table, and all `api/**` handlers; the crons (115 as of 2026-09-04, see vercel.json) run on Cloud Scheduler. `vercel.json` is a LIVE config file: `server/index.mjs` reads its `routes` array on boot (split at the `{handle:"filesystem"}` marker into pre- and post-filesystem phases), and `scripts/create-gcp-scheduler.mjs` reads its `crons` array to sync Cloud Scheduler jobs. The server itself never reads `crons`. Never delete `vercel.json` as a leftover. GCP builds/deploys must pin the `three-ws-build@` (build) and `three-ws@` (runtime) service accounts; the project's default compute SA was deleted. Deploys: see the "Deploy runbook" section above.- **Env-var trap:** `vercel env pull` returns EMPTY for secret-type vars. Never trust a Vercel env export as complete. Production env lives on the Cloud Run service (`gcloud run services describe/update three-ws-api --region us-central1`).- Solana/agent SDKs in `sdk/`, `solana-agent-sdk/`, `agent-payments-sdk/`.- Real APIs in use: Pump.fun feed, Solana RPC, OpenAI/Anthropic via worker proxies. Never mock these.diff --git a/api/_lib/forge-notify.js b/api/_lib/forge-notify.jsindex c4623f01e..8f7ba2f6a 100644--- a/api/_lib/forge-notify.js+++ b/api/_lib/forge-notify.js@@ -10,10 +10,18 @@// 'creations' category has email enabled (the default: an unattended finish// is precisely the moment email earns its keep). All best-effort: a delivery// failure never touches the creation row.+//+// Developer webhooks are the one channel that does NOT follow the attended /+// unattended split. `forge.completed` fires from materializeCreation, the+// universal completion writer, so an API integrator learns every outcome+// whether or not a browser was watching; only `forge.failed` lives here,+// because this is the sole place that distinguishes a terminal failure from a+// failover that is still running. See docs/api-reference.md.import { sql } from './db.js';import { insertNotification, emailAllowedForType } from './notify.js';import { sendForgeCompleteEmail } from './email.js';+import { dispatchWebhooks } from './webhook-dispatch.js';// Real, sendable email for a user. Skips missing addresses and the synthetic// `…@privy.local` placeholders minted for wallet-only Privy accounts.@@ -52,8 +60,26 @@ async function deliverComplete({ userId, creationId, prompt, previewImageUrl })}}-export function notifyForgeFailed({ userId, prompt, error }) {+export function notifyForgeFailed({ userId, creationId = null, prompt, error, backend = null, tier = null }) {if (!userId) return Promise.resolve();+ // The `forge.failed` webhook fires from here rather than from markFailed,+ // because markFailed also runs on the failover path: a row that failed on one+ // lane and was redispatched to another is marked failed and immediately+ // superseded, and telling an integrator that job died while it is still+ // running would be a lie. The finalizer calls this function only when nothing+ // is left to try, which is exactly the terminal signal a subscriber wants.+ dispatchWebhooks({+ userId,+ eventType: 'forge.failed',+ data: {+ id: creationId,+ status: 'failed',+ prompt: prompt || null,+ error: error ? String(error).slice(0, 200) : null,+ backend,+ tier,+ },+ }).catch(() => {});// Bell + push only: a failure email for a free generation would be noise.return insertNotification(userId, 'forge_failed', {prompt: prompt || null,diff --git a/api/_lib/forge-store.js b/api/_lib/forge-store.jsindex b0958a0e8..eeca9ff87 100644--- a/api/_lib/forge-store.js+++ b/api/_lib/forge-store.js@@ -28,6 +28,7 @@ import { derivePbrChannels } from './glb-pbr-derive.js';import { fetchUpstream } from './upstream-fetch.js';import { gradeSimReadiness } from './sim-readiness.js';import { putGrade } from './sim-readiness-store.js';+import { dispatchWebhooks } from './webhook-dispatch.js';// Stable, non-secret salt so a leaked DB row can't be trivially reversed to the// raw browser-local id. The id is anonymous to begin with; this is hygiene, not@@ -618,6 +619,28 @@ export async function materializeCreation({ replicateJobId, clientKey, glbUrl, qif (existing.user_id) {recordDailyActivity(existing.user_id).catch(() => {});maybeAwardFirstCreation(existing.user_id).catch(() => {});+ // A generation submitted over the API outlives the request that started+ // it, so an integrator's only completion signal is polling unless we push+ // one. This is the single writer every lane finishes through, and the+ // early return above makes it idempotent, so the event fires exactly once+ // per job. Fire-and-forget, like every other side effect here: a slow or+ // dead developer endpoint must never delay delivery of the model.+ dispatchWebhooks({+ userId: existing.user_id,+ eventType: 'forge.completed',+ data: {+ id: existing.id,+ status: 'done',+ prompt: existing.prompt || null,+ glb_url: glb.publicUrl,+ preview_image_url: preview.url,+ backend: existing.backend || null,+ tier: existing.tier || null,+ path: existing.path || null,+ size_bytes: glb.bytes,+ latency_ms: latencyMs,+ },+ }).catch(() => {});}return {id: existing.id,diff --git a/api/cron/forge-finalize.js b/api/cron/forge-finalize.jsindex c3c6ed1e5..3ff60913b 100644--- a/api/cron/forge-finalize.js+++ b/api/cron/forge-finalize.js@@ -334,7 +334,7 @@ export default wrapCron(async (req, res) => {});out.failed++;if (row.user_id) {- notifyForgeFailed({ userId: row.user_id, prompt: row.prompt, error: status.error });+ notifyForgeFailed({ userId: row.user_id, creationId: row.id, prompt: row.prompt, error: status.error, backend: row.backend, tier: row.tier });}continue;}@@ -445,7 +445,7 @@ export default wrapCron(async (req, res) => {});out.failed++;if (row.user_id) {- notifyForgeFailed({ userId: row.user_id, prompt: row.prompt, error: status.error });+ notifyForgeFailed({ userId: row.user_id, creationId: row.id, prompt: row.prompt, error: status.error, backend: row.backend, tier: row.tier });}continue;}@@ -463,7 +463,7 @@ export default wrapCron(async (req, res) => {});out.timed_out++;if (row.user_id) {- notifyForgeFailed({ userId: row.user_id, prompt: row.prompt, error: 'generation timed out' });+ notifyForgeFailed({ userId: row.user_id, creationId: row.id, prompt: row.prompt, error: 'generation timed out', backend: row.backend, tier: row.tier });}} else if (envelope) {out.still_running++;diff --git a/tests/glb-compress.test.js b/tests/glb-compress.test.jsindex 4c0e94a42..1d1d41b08 100644--- a/tests/glb-compress.test.js+++ b/tests/glb-compress.test.js@@ -1,7 +1,12 @@import { describe, it, expect } from 'vitest';import { readFileSync, existsSync } from 'node:fs';import { resolve } from 'node:path';-import { compressGlb, COMPRESSION_MODES } from '../api/_lib/glb-compress.js';+import {+ compressGlb,+ COMPRESSION_MODES,+ deliveryCompressionOptions,+ DELIVERY_TEXTURE_MAX_PX,+} from '../api/_lib/glb-compress.js';import { inspectGlb } from '../api/_lib/glb-inspect.js';const avatar = (name) => resolve(process.cwd(), 'public/avatars', name);@@ -50,4 +55,98 @@ describe('compressGlb', () => {it('advertises exactly the two supported modes', () => {expect(COMPRESSION_MODES).toEqual(['draco', 'meshopt']);});++ it('leaves textures alone unless the caller asks for them', async () => {+ // The geometry-only contract is what `output_format: glb-meshopt` promises,+ // and it is also what keeps that request fast: no sharp, no re-encode.+ expect(deliveryCompressionOptions().textures).toBeTruthy();+ });+});++// A textured mesh is where the delivery preset earns its keep: on real forge+// output the embedded PNG skins, not the vertex data, are what push a model past+// what a phone will wait for.+const TEXTURED = ['selfie-girl.glb', 'realistic-male.glb', 'michelle.glb'].map(avatar).find(existsSync);++describe('deliveryCompressionOptions', () => {+ it('is meshopt geometry plus a capped WebP texture pass', () => {+ const opts = deliveryCompressionOptions();+ expect(opts.mode).toBe('meshopt');+ expect(opts.textures.maxSize).toBe(DELIVERY_TEXTURE_MAX_PX);+ });++ it.runIf(TEXTURED)(+ 're-encodes textures to WebP and keeps the mesh structurally valid',+ async () => {+ const src = readFileSync(TEXTURED);+ const r = await compressGlb(src, deliveryCompressionOptions());+ expect(r.extensionsUsed).toContain('EXT_meshopt_compression');+ expect(r.extensionsUsed).toContain('EXT_texture_webp');+ expect(r.textures.converted).toBeGreaterThan(0);+ expect(r.outputBytes).toBeLessThan(r.inputBytes);+ const info = inspectGlb(r.buffer);+ expect(info).toBeTruthy();+ expect(info.meshCount).toBeGreaterThan(0);+ },+ 180_000,+ );++ it.runIf(TEXTURED)(+ 'preserves the skinning and animation a rigged avatar depends on',+ async () => {+ // Losing a skin here would silently un-rig every avatar the delivery+ // path touches, and the loss would only show up as a T-pose in a+ // viewer, so it is pinned on real bytes rather than trusted.+ const { NodeIO } = await import('@gltf-transform/core');+ const { ALL_EXTENSIONS } = await import('@gltf-transform/extensions');+ const { MeshoptEncoder, MeshoptDecoder } = await import('meshoptimizer');+ await Promise.all([MeshoptEncoder.ready, MeshoptDecoder.ready]);+ const io = new NodeIO()+ .registerExtensions(ALL_EXTENSIONS)+ .registerDependencies({ 'meshopt.encoder': MeshoptEncoder, 'meshopt.decoder': MeshoptDecoder });+ const count = async (bytes) => {+ const root = (await io.readBinary(new Uint8Array(bytes))).getRoot();+ return {+ skins: root.listSkins().length,+ animations: root.listAnimations().length,+ meshes: root.listMeshes().length,+ };+ };+ const src = readFileSync(TEXTURED);+ const r = await compressGlb(src, deliveryCompressionOptions());+ expect(await count(r.buffer)).toEqual(await count(src));+ },+ 180_000,+ );++ it('survives a texture whose header lies about its dimensions', async () => {+ // Three of six production forge meshes sampled on 2026-09-04 carried a PNG+ // that @gltf-transform's header parser read as 65536x4292542531, which made+ // its own `textureCompress({ resize })` throw and took the whole+ // compression pass (geometry win included) down with it. The pass now reads+ // dimensions from the encoder that is about to decode the bytes, and+ // isolates every texture, so a bad skin costs that skin and nothing else.+ const { NodeIO, Document } = await import('@gltf-transform/core');+ const doc = new Document();+ const buffer = doc.createBuffer();+ const position = doc+ .createAccessor()+ .setType('VEC3')+ .setArray(new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]))+ .setBuffer(buffer);+ const texture = doc+ .createTexture('broken')+ .setMimeType('image/png')+ .setImage(new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3, 4]));+ const material = doc.createMaterial('m').setBaseColorTexture(texture);+ const prim = doc.createPrimitive().setAttribute('POSITION', position).setMaterial(material);+ doc.createNode('n').setMesh(doc.createMesh('mesh').addPrimitive(prim));+ doc.createScene().addChild(doc.getRoot().listNodes()[0]);+ const bytes = await new NodeIO().writeBinary(doc);++ const r = await compressGlb(bytes, deliveryCompressionOptions());+ expect(r.textures.skipped).toBeGreaterThan(0);+ expect(r.textures.converted).toBe(0);+ expect(inspectGlb(r.buffer)).toBeTruthy();+ }, 60_000);});diff --git a/vercel.json b/vercel.jsonindex 39b553232..f24203fba 100644--- a/vercel.json+++ b/vercel.json@@ -6470,6 +6470,10 @@{"path": "/api/cron/home-relay-sweep","schedule": "17 * * * *"+ },+ {+ "path": "/api/cron/forge-web-variants",+ "schedule": "*/10 * * * *"}]}