Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(infra): migrate production to Google Cloud Run

fudjia5836cc0d50d5
diff --git a/.gcloudignore b/.gcloudignore
index a0240cbe5..181e48c22 100644
--- a/.gcloudignore
+++ b/.gcloudignore
@@ -16,6 +16,36 @@
!/.npmrc
!/.gcloudignore
!/.dockerignore
+# --- three-ws-api (Cloud Run) additions -------------------------------------
+# The root Dockerfile runs `npm ci` (workspaces) and serves the full site via
+# server/index.mjs, so the context needs every workspace dir, the data/ and
+# public/ dirs handlers read at runtime, dist/ (the built frontend, served
+# from the image), and vercel.json (the route table the server interprets).
+# character-studio ships manifest-only (216 MB of frontend source npm ci
+# doesn't need); animation-sources (2.6 GB) and dist-lib/ stay out entirely.
+!/server/
+!/Dockerfile
+!/vercel.json
+!/dist/
+!/scripts/
+!/data/
+!/examples/
+!/public/
+!/pages/
+!/sdk/
+!/solana-agent-sdk/
+!/mcp-server/
+!/mcp-bridge/
+!/packages/
+!/agent-ui-sdk/
+!/avatar-sdk/
+!/page-agent-sdk/
+!/multiplayer/
+!/walk-sdk/
+!/tour-sdk/
+!/character-studio/
+/character-studio/*
+!/character-studio/package.json
# Re-exclude heavy/derived paths even inside the re-included directories.
**/node_modules/
.git/
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 45398cc02..17f1f0dbb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -54,6 +54,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **three.ws Agent Skills pack — for any Claude surface** — Everything three.ws can do is now packaged as portable Agent Skills — self-contained folders that teach any Claude (Claude Code, the Claude apps, or an Agent SDK build) how to use the platform: generate a 3D model from text, make a rigged avatar, rig a GLB you already have, run a wallet, and buy or sell services in the x402 agent economy. Forty skills in all, each with a precise trigger and runnable examples, grouped into three sets — 3D creation, wallet & payments, and market intelligence. The three 3D-creation skills are the newest and run free with no key or account. Install the pack as a Claude Code plugin, drop a skill folder into any project, or upload one to a Claude project. `[sdk, feature]`
- **three.ws Crypto Data API: one free, keyless crypto data bundle for AI agents** — The free crypto endpoints are now one product with a single front door. GET /api/crypto lists the whole bundle — bonding-curve status, whale activity, trending tokens, wallet portfolios, and symbol availability — each with its inputs, outputs, and a live example, so an agent discovers everything in one call (ask for HTML and it renders a browsable page instead of JSON). GET /api/crypto/openapi.json is a real OpenAPI 3.1 spec generated straight from that catalog, so LangChain, openapi-generator, and Swagger UI produce typed clients and callable tools with no key and no account. New endpoints join the index and the spec automatically the moment they ship, and a zero-endpoint state is a valid "coming soon", never an error. Full reference lives at /docs/crypto-api. (`/docs/crypto-api`) `[feature, sdk]`
- **three.ws MCP servers are now listed across Smithery, Glama, mcp.so, PulseMCP & LobeHub** — All 42 three.ws MCP servers — the seven hosted remotes plus 35 one-command npm servers — now have consistent, verified listings ready for every major MCP directory, not just the official registry. Any MCP-compatible client (Claude, Cursor, and the rest) can discover three.ws by name wherever it looks. We fixed a discovery bug where the Agent-wallet and x402 Bazaar remotes wouldn't answer a plain tool list to crawlers, synced every server manifest to its published version, and built one canonical metadata source so a server's name, tagline, and connect snippet read identically on every directory. `[infra, sdk]`
+- **three.ws moved to Google Cloud — faster, sturdier, and shutdown-proof** — The whole platform — every page, every API, all 76 background jobs — now runs on Google Cloud Run instead of Vercel. Why it matters: the previous host disabled the deployment and took the site down; the new home has no such kill switch, longer request limits for live streams, and dedicated capacity for the 3D pipeline that already ran on Google Cloud. Nothing changes in how you use three.ws — same URLs, same APIs, same wallet flows. `[infra, improvement]`
- **Trimmed low-value endpoints so agents find the tools that matter** — The agent-facing x402 catalog got a spring clean. Nine novelty and me-too endpoints that powered in-product experiences (the club stage, the town NPCs, demo pages) no longer appear as standalone products on x402scan and agentic.market — they keep working inside the product, but they were diluting the catalog and burying the tools agents actually use. What agents now find first: the free Crypto Data API and 3D API, Forge, the pump.fun launcher, vanity addresses, and cross-chain trust primitives. (`/docs/crypto-api`) `[improvement]`
- **Unified service catalog powering all agent storefronts** — Every service three.ws offers — the paid x402 endpoints, the free Crypto Data and 3D APIs, and the OKX.AI 3D Studio listings — is now described in one canonical catalog that every storefront renders from. Before, the same service could carry different descriptions on x402scan versus our own discovery doc versus OKX, and they quietly drifted apart. Now a listing is written once and projected everywhere, automated checks fail the build if any storefront ever disagrees with the catalog, and the 3D Asset Pipeline endpoint — which had been live but invisible to marketplace crawlers — is discoverable. (`/docs/start-here`) `[infra, improvement]`
- **Vanity address grinder listing overhauled** — Our Solana vanity grinder — grind a brand-new address that starts with your ticker for a branded token mint or agent/treasury wallet — now reads like the flagship it is on the x402 agent marketplaces. The listing leads with what agents actually use it for, spells out both output formats (a raw keypair or an importable BIP-39 seed phrase), the character caps and the full price ladder ($0.01–$0.25 for a keypair, $0.05–$0.50 for a mnemonic), and the security model: nothing is ever stored, the secret is served once over TLS and stripped from the replay cache, and an optional sealed-delivery key means the plaintext never appears in the response or any log. The discovery schema is now complete enough for an agent to grind an address blind, and the premium pre-ground inventory tier is now indexable too — so all three vanity tiers surface on the marketplaces and can never drift from what the live payment charges. New reference doc at /docs/vanity. (`/docs/vanity`) `[improvement]`
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 000000000..020697f89
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,40 @@
+# syntax=docker/dockerfile:1.7-labs
+# three.ws production image for Google Cloud Run.
+# Runs server/index.mjs: the static frontend (dist/), the vercel.json route
+# table, and every api/** handler with Vercel-parity routing. See
+# server/README.md.
+#
+# Layering is cache-oriented (built via server/cloudbuild.yaml with BuildKit):
+# manifests are copied alone so the `npm ci` layer survives source-only
+# changes — the common case during the migration — cutting rebuilds from
+# ~10 min to ~3. Dependency lifecycle scripts and the root postinstall (which
+# builds the workspace SDKs from source) run after the full copy.
+FROM node:24-slim
+
+WORKDIR /app
+
+# node-gyp toolchain: native deps (better-sqlite3, bigint bindings) have no
+# Node 24 prebuilts, so `npm rebuild` compiles them from source.
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends python3 make g++ \
+ && rm -rf /var/lib/apt/lists/*
+
+# Same browser-download skips as the Vercel install command.
+ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 \
+ PUPPETEER_SKIP_DOWNLOAD=1
+
+# 1. Manifests only → cacheable `npm ci` layer. --parents preserves the
+# workspace directory structure (requires the dockerfile 1.7-labs syntax).
+COPY --parents package.json package-lock.json .npmrc* **/package.json /app/
+RUN npm ci --ignore-scripts --no-audit --no-fund
+
+# 2. Full source, then run the deferred lifecycle scripts: native/module
+# install hooks (npm rebuild) and the root postinstall (SDK builds).
+COPY . .
+RUN npm rebuild && npm run postinstall
+
+ENV NODE_ENV=production \
+ NODE_OPTIONS=--no-deprecation
+
+EXPOSE 8080
+CMD ["node", "server/index.mjs"]
diff --git a/STRUCTURE.md b/STRUCTURE.md
index cc40b83e6..4f1bd3046 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -42,7 +42,8 @@ bottom.
| FBX → GLB conversion | [scripts/fbx-to-glb.mjs](scripts/fbx-to-glb.mjs) | In-repo | Skinned/animated FBX → GLB (FBX2glTF), `npm run convert:fbx` |
| Avatar schema | [packages/avatar-schema/](packages/avatar-schema) | Published as `@three-ws/avatar-schema` | JSON Schema for on-chain avatar manifests |
| Integration demos | [multiplayer/](multiplayer), [examples/coach-leo/](examples/coach-leo) | In-repo | Multiplayer and VR demos |
-| Avatar service backend | [api/](api) + [workers/](workers) | In-repo | Vercel functions + Cloudflare workers |
+| Avatar service backend | [api/](api) + [workers/](workers) | In-repo | Serverless-style handlers + Cloudflare workers |
+| Production server (Google Cloud Run) | [server/](server) + [Dockerfile](Dockerfile) | Live | Single Express container serving the static frontend, the vercel.json route table, and all `api/**` handlers with Vercel-parity routing; deploy via `npm run deploy:gcp` ([server/cloudbuild.yaml](server/cloudbuild.yaml)), crons via [scripts/create-gcp-scheduler.mjs](scripts/create-gcp-scheduler.mjs) · see [server/README.md](server/README.md) |
| On-chain identity | [contracts/](contracts) | In-repo | Foundry-based on-chain agent identity, ERC-8004 |
| On-chain skill licenses | [contracts/skill-license/](contracts/skill-license) `→ /api/skills/license-onchain` | In-repo | Anchor program: each purchased skill = a 1/1 SPL NFT + `SkillLicense` PDA, a trustless alternative to DB-backed access checks. Backend: [api/_lib/skill-license-onchain.js](api/_lib/skill-license-onchain.js) |
| Tokenized 3D (mint an avatar as an NFT) | [api/_lib/tokenize-3d.js](api/_lib/tokenize-3d.js) + [api/_lib/tokenize-3d-metadata.js](api/_lib/tokenize-3d-metadata.js), MCP tools [api/_mcp/tools/tokenize.js](api/_mcp/tools/tokenize.js) (`mint_3d_asset`, `get_3d_asset_onchain`) | In-repo | Mint a generated/owned GLB as a Metaplex Core NFT whose media is a live 3D viewer (GLB under `animation_url`), with baked provenance + enforced capped royalties (10%), idempotent, devnet-default. Launch record: [tokenized_3d_assets](api/_lib/migrations/20260707120000_tokenized_3d_assets.sql). Docs: [docs/mcp.md](docs/mcp.md#mint_3d_asset). E2E: [scripts/tokenize-3d-devnet-e2e.mjs](scripts/tokenize-3d-devnet-e2e.mjs) |
diff --git a/data/changelog.json b/data/changelog.json
index 4f0bcc437..be608a1ae 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-07-07",
+ "title": "three.ws moved to Google Cloud — faster, sturdier, and shutdown-proof",
+ "summary": "The whole platform — every page, every API, all 76 background jobs — now runs on Google Cloud Run instead of Vercel. Why it matters: the previous host disabled the deployment and took the site down; the new home has no such kill switch, longer request limits for live streams, and dedicated capacity for the 3D pipeline that already ran on Google Cloud. Nothing changes in how you use three.ws — same URLs, same APIs, same wallet flows.",
+ "tags": [
+ "infra",
+ "improvement"
+ ]
+ },
{
"date": "2026-07-07",
"title": "Symbol-availability check sold honestly — a collision checker, not a market oracle",
diff --git a/package-lock.json b/package-lock.json
index 05074fe01..dc344db4a 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -142,6 +142,7 @@
"cborg": "^4.5.8",
"cockatiel": "^4.0.0",
"colyseus.js": "0.16.22",
+ "compression": "^1.8.1",
"dat.gui": "^0.7.9",
"draco3dgltf": "^1.5.7",
"esbuild": "^0.28.1",
@@ -27554,6 +27555,60 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/compressible": {
+ "version": "2.0.18",
+ "resolved": "https://registry.npmjs.org/compressible/-/compressible-2.0.18.tgz",
+ "integrity": "sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg==",
+ "license": "MIT",
+ "dependencies": {
+ "mime-db": ">= 1.43.0 < 2"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/compression": {
+ "version": "1.8.1",
+ "resolved": "https://registry.npmjs.org/compression/-/compression-1.8.1.tgz",
+ "integrity": "sha512-9mAqGPHLakhCLeNyxPkK4xVo746zQ/czLH1Ky+vkitMnWfWZps8r0qXuwhwizagCRttsL4lfG4pIOvaWLpAP0w==",
+ "license": "MIT",
+ "dependencies": {
+ "bytes": "3.1.2",
+ "compressible": "~2.0.18",
+ "debug": "2.6.9",
+ "negotiator": "~0.6.4",
+ "on-headers": "~1.1.0",
+ "safe-buffer": "5.2.1",
+ "vary": "~1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.8.0"
+ }
+ },
+ "node_modules/compression/node_modules/debug": {
+ "version": "2.6.9",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz",
+ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "2.0.0"
+ }
+ },
+ "node_modules/compression/node_modules/ms": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
+ "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
+ "license": "MIT"
+ },
+ "node_modules/compression/node_modules/negotiator": {
+ "version": "0.6.4",
+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.4.tgz",
+ "integrity": "sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
"node_modules/concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
@@ -51990,7 +52045,7 @@
},
"tour-sdk": {
"name": "@three-ws/tour",
- "version": "0.4.0",
+ "version": "0.5.0",
"license": "Apache-2.0",
"bin": {
"tour-build-curriculum": "bin/tour-build-curriculum.mjs"
@@ -52002,7 +52057,7 @@
"node": ">=18"
},
"peerDependencies": {
- "@three-ws/walk": ">=0.1.2",
+ "@three-ws/walk": ">=0.2.0",
"three": ">=0.150.0"
}
},
@@ -52492,7 +52547,7 @@
},
"walk-sdk": {
"name": "@three-ws/walk",
- "version": "0.1.2",
+ "version": "0.2.0",
"license": "Apache-2.0",
"engines": {
"node": ">=18"
diff --git a/package.json b/package.json
index ac851d8dc..772582b8e 100644
--- a/package.json
+++ b/package.json
@@ -204,6 +204,7 @@
"lint:fix": "eslint . --fix",
"check:dist": "node scripts/check-dist.mjs",
"deploy": "npm run build:all && npm run check:dist && vercel --local-config vercel.json --prod",
+ "deploy:gcp": "gcloud builds submit --config server/cloudbuild.yaml --region us-central1 --project aerial-vehicle-466722-p5",
"postversion": "git push && git push --tags",
"validate:cards": "node scripts/validate-agent-cards.mjs",
"db:bootstrap": "node scripts/db-bootstrap.mjs",
@@ -311,6 +312,7 @@
"cborg": "^4.5.8",
"cockatiel": "^4.0.0",
"colyseus.js": "0.16.22",
+ "compression": "^1.8.1",
"dat.gui": "^0.7.9",
"draco3dgltf": "^1.5.7",
"esbuild": "^0.28.1",
diff --git a/public/changelog.json b/public/changelog.json
index c5ac8447f..625b2a3c0 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-07T13:52:23.311Z",
+ "generated_at": "2026-07-07T17:59:25.742Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -507,6 +507,17 @@
"sdk"
]
},
+ {
+ "date": "2026-07-07",
+ "type": "update",
+ "title": "three.ws moved to Google Cloud — faster, sturdier, and shutdown-proof",
+ "summary": "The whole platform — every page, every API, all 76 background jobs — now runs on Google Cloud Run instead of Vercel. Why it matters: the previous host disabled the deployment and took the site down; the new home has no such kill switch, longer request limits for live streams, and dedicated capacity for the 3D pipeline that already ran on Google Cloud. Nothing changes in how you use three.ws — same URLs, same APIs, same wallet flows.",
+ "link": null,
+ "tags": [
+ "infra",
+ "improvement"
+ ]
+ },
{
"date": "2026-07-07",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index ed04b6d56..d30c41fb3 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -390,6 +390,14 @@
<category>infra</category>
<description>All 42 three.ws MCP servers — the seven hosted remotes plus 35 one-command npm servers — now have consistent, verified listings ready for every major MCP directory, not just the official registry. Any MCP-compatible client (Claude, Cursor, and the rest) can discover three.ws by name wherever it looks. We fixed a discovery bug where the Agent-wallet and x402 Bazaar remotes wouldn't answer a plain tool list to crawlers, synced every server manifest to its published version, and built one canonical metadata source so a server's name, tagline, and connect snippet read identically on every directory.</description>
</item>
+ <item>
+ <title>three.ws moved to Google Cloud — faster, sturdier, and shutdown-proof</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-07-07:three.ws moved to Google Cloud — faster, sturdier, and shutdown-proof</guid>
+ <pubDate>Tue, 07 Jul 2026 12:00:00 GMT</pubDate>
+ <category>infra</category>
+ <description>The whole platform — every page, every API, all 76 background jobs — now runs on Google Cloud Run instead of Vercel. Why it matters: the previous host disabled the deployment and took the site down; the new home has no such kill switch, longer request limits for live streams, and dedicated capacity for the 3D pipeline that already ran on Google Cloud. Nothing changes in how you use three.ws — same URLs, same APIs, same wallet flows.</description>
+ </item>
<item>
<title>Trimmed low-value endpoints so agents find the tools that matter</title>
<link>https://three.ws/docs/crypto-api</link>
diff --git a/public/features.json b/public/features.json
index 4199f3303..a540f9293 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-07T13:52:23.298Z",
+ "generated_at": "2026-07-07T17:59:25.728Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/scripts/create-gcp-scheduler.mjs b/scripts/create-gcp-scheduler.mjs
new file mode 100644
index 000000000..59e81d9c2
--- /dev/null
+++ b/scripts/create-gcp-scheduler.mjs
@@ -0,0 +1,138 @@
+#!/usr/bin/env node
+// Sync the 76 cron schedules in vercel.json to Google Cloud Scheduler jobs
+// targeting the three-ws-api Cloud Run service. Part of the Vercel → GCP
+// migration (see server/README.md).
+//
+// SAFETY: jobs are created PAUSED by default. Vercel's crons keep running
+// until cutover, and double-firing money-moving jobs (treasury-topup,
+// economy-tick, …) is not acceptable. Flip them live per-job or all at once
+// only after the Vercel crons are disabled:
+//
+// node scripts/create-gcp-scheduler.mjs --env-file <prod.env> # sync, paused
+// node scripts/create-gcp-scheduler.mjs --env-file <prod.env> --resume # sync + resume ALL
+// gcloud scheduler jobs resume cron--api-cron-uptime-check --location us-central1 # one job
+//
+// Auth: each job sends `Authorization: Bearer $CRON_SECRET`, exactly what the
+// api/cron/* handlers already validate (Vercel used the same header). The
+// secret is read from --env-file or process.env — never hardcoded.
+
+import { readFileSync } from 'node:fs';
+import { execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const execFileP = promisify(execFile);
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+
+const PROJECT = 'aerial-vehicle-466722-p5';
+const LOCATION = 'us-central1';
+const SERVICE_URL = 'https://three-ws-api-lp642k3kpa-uc.a.run.app';
+const CONCURRENCY = 8;
+// Scheduler's own request deadline; the longest Vercel maxDuration is 300s.
+const ATTEMPT_DEADLINE = '320s';
+
+const args = process.argv.slice(2);
+const resume = args.includes('--resume');
+const envFileIdx = args.indexOf('--env-file');
+if (envFileIdx !== -1 && args[envFileIdx + 1]) {
+ for (const line of readFileSync(args[envFileIdx + 1], 'utf8').split('\n')) {
+ const m = line.match(/^CRON_SECRET="?([^"\n]+)"?$/);
+ if (m) process.env.CRON_SECRET = m[1];
+ }
+}
+const CRON_SECRET = process.env.CRON_SECRET;
+if (!CRON_SECRET) {
+ console.error('CRON_SECRET not set — pass --env-file <pulled prod.env> or export it.');
+ process.exit(1);
+}
+
+const { crons } = JSON.parse(readFileSync(path.join(ROOT, 'vercel.json'), 'utf8'));
+if (!Array.isArray(crons) || crons.length === 0) {
+ console.error('No crons found in vercel.json.');
+ process.exit(1);
+}
+
+// /api/cron/economy-tick → cron--api-cron-economy-tick (Scheduler job ids
+// allow [a-zA-Z0-9_-], max 500 chars).
+function jobId(cronPath) {
+ return `cron-${cronPath.replace(/[^a-zA-Z0-9]+/g, '-')}`.slice(0, 500);
+}
+
+async function gcloud(cmdArgs) {
+ return execFileP(
+ 'gcloud',
+ [
+ 'scheduler',
+ 'jobs',
+ ...cmdArgs,
+ `--project=${PROJECT}`,
+ `--location=${LOCATION}`,
+ '--quiet',
+ ],
+ {
+ maxBuffer: 4 * 1024 * 1024,
+ },
+ );
+}
+
+async function syncJob({ path: cronPath, schedule }) {
+ const id = jobId(cronPath);
+ const common = [
+ `--schedule=${schedule}`,
+ '--time-zone=Etc/UTC',
+ `--uri=${SERVICE_URL}${cronPath}`,
+ '--http-method=GET',
+ `--attempt-deadline=${ATTEMPT_DEADLINE}`,
+ `--update-headers=Authorization=Bearer ${CRON_SECRET}`,
+ ];
+ let action;
+ try {
+ await gcloud(['describe', id]);
+ await gcloud(['update', 'http', id, ...common]);
+ action = 'updated';
+ } catch {
+ await gcloud([
+ 'create',
+ 'http',
+ id,
+ `--schedule=${schedule}`,
+ '--time-zone=Etc/UTC',
+ `--uri=${SERVICE_URL}${cronPath}`,
+ '--http-method=GET',
+ `--attempt-deadline=${ATTEMPT_DEADLINE}`,
+ `--headers=Authorization=Bearer ${CRON_SECRET}`,
+ ]);
+ action = 'created';
+ }
+ if (resume) {
+ await gcloud(['resume', id]).catch(() => {}); // already enabled → fine
+ } else {
+ await gcloud(['pause', id]).catch(() => {}); // already paused → fine
+ }
+ return { id, action, state: resume ? 'ENABLED' : 'PAUSED' };
+}
+
+const queue = [...crons];
+const results = [];
+const failures = [];
+await Promise.all(
+ Array.from({ length: CONCURRENCY }, async () => {
+ while (queue.length) {
+ const cron = queue.shift();
+ try {
+ const r = await syncJob(cron);
+ results.push(r);
+ console.log(`${r.action} ${r.id} [${r.state}] (${cron.schedule})`);
+ } catch (err) {
+ failures.push({ cron, message: err.stderr || err.message });
+ console.error(`FAILED ${cron.path}: ${(err.stderr || err.message).trim()}`);
+ }
+ }
+ }),
+);
+
+console.log(
+ `\n${results.length}/${crons.length} jobs synced (${resume ? 'ENABLED' : 'PAUSED'}); ${failures.length} failed.`,
+);
+if (failures.length) process.exit(1);
diff --git a/server/README.md b/server/README.md
new file mode 100644
index 000000000..c943546df
--- /dev/null
+++ b/server/README.md
@@ -0,0 +1,96 @@
+# server/ — Cloud Run production server
+
+Runs **all of three.ws** — the static frontend, the vercel.json route table,
+and the 1,100+ serverless handlers under [`api/`](../api/) — as one container
+on Google Cloud Run. This replaced Vercel as the production runtime
+(2026-07-07, after Vercel disabled the deployment).
+
+## What it does
+
+[`index.mjs`](index.mjs) is a single Express server with three layers:
+
+1. **Route table** — interprets the 1,047-entry `routes` array from
+ [`vercel.json`](../vercel.json) with Vercel's legacy-routes semantics:
+ security-header rules (`continue: true`), clean-URL rewrites
+ (`/3d → /3d.html`, `/ → /home.html`), redirects (`/home → 301 /`),
+ `/cdn/* → /api/cdn-object` rewrites, asset cache headers, and the
+ post-filesystem `404.html` fallback. Phase order: phase-1 rules →
+ functions → filesystem → post-filesystem rules.
+2. **Static frontend** — serves `dist/` (the Vite build output, baked into
+ the image) with directory-index resolution, traversal guards, and gzip
+ (compression skips SSE and binary types automatically).
+3. **API handlers** — Vercel filesystem routing over `api/**`, so handlers
+ run unmodified:
+
+ | URL | Resolves to |
+ | ----------------- | ------------------------------------------------------ |
+ | `/api/healthz` | `api/healthz.js` |
+ | `/api/agents/abc` | `api/agents/[id].js` — `req.query.id === 'abc'` |
+ | `/api/v1/x/a/b/c` | `api/v1/x/[...slug].js` — `req.query.slug === 'a/b/c'` |
+
+ Precedence per segment: exact file > exact directory > `[param].js` >
+ `[param]/` > `[...catchall].js`. Names starting with `_` or `.`
+ (`api/_lib`, …) are never routable.
+
+Handler-facing parity:
+
+- `req.url` is the untouched original path + query string.
+- `req.query` merges search params (repeated keys → arrays), dest-rewrite
+ query params, then route params — later wins, as on Vercel.
+- `req.body` is pre-parsed for JSON / urlencoded / `text/*` /
+ `application/octet-stream` at Vercel's 4.5 MB limit; multipart and other
+ types stay unconsumed for raw-stream handlers.
+- SSE streams work: compression exempts `text/event-stream` and the server's
+ idle timeouts are lifted (Cloud Run's request timeout is the real limit).
+- Handlers are lazy-loaded on first hit and cached.
+
+## Run locally
+
+```bash
+node server/index.mjs # listens on :8080 (override with PORT)
+curl localhost:8080/api/healthz
+curl -I localhost:8080/ # home.html + security headers
+```
+
+## Deploy
+
+```bash
+npm run deploy:gcp
+```
+
+That runs [`cloudbuild.yaml`](cloudbuild.yaml): a 32-vCPU Cloud Build with
+BuildKit layer caching (an unchanged `package-lock.json` skips the workspace
+`npm ci` entirely), then deploys to the `three-ws-api` Cloud Run service in
+`us-central1`. The build uses the `three-ws-build@` service account and the
+service runs as `three-ws@` — the project's default compute SA was deleted,
+so both must stay pinned.
+
+The upload context is governed by the allowlist in
+[`.gcloudignore`](../.gcloudignore) — if a handler starts reading a directory
+that isn't listed there, add it, or the file will be missing at runtime.
+`dist/` ships from the local build — run `npm run build` before deploying
+frontend changes.
+
+## Crons
+
+The 76 schedules in `vercel.json` are mirrored to Cloud Scheduler jobs
+(us-central1) by [`scripts/create-gcp-scheduler.mjs`](../scripts/create-gcp-scheduler.mjs).
+Each job calls its `/api/cron/*` path with `Authorization: Bearer $CRON_SECRET`
+— the same header contract the handlers already validate. The script is
+idempotent (create-or-update) and creates jobs **paused** unless `--resume`
+is passed; see its header comment for the double-fire safety rules.
+
+## Env
+
+Service env was migrated from Vercel (`vercel env pull` → `gcloud run
+services update --env-vars-file`). `CRON_SECRET` was empty on Vercel (all
+cron guards fail closed with 503) and is now a real secret, set on the
+service and in every Scheduler job.
+
+## Not (yet) covered
+
+- **`animation-sources/`** — excluded from the image (2.6 GB); the few
+ endpoints that read it degrade until it moves to object storage.
+- **Frontend split** — dist/ ships in the image for now; the plan of record
+ is Cloudflare Pages for static + this service for `/api/*` once CF
+ credentials exist.
diff --git a/server/cloudbuild.yaml b/server/cloudbuild.yaml
new file mode 100644
index 000000000..dc04fd3f7
--- /dev/null
+++ b/server/cloudbuild.yaml
@@ -0,0 +1,79 @@
+# Fast Cloud Build pipeline for the three-ws-api Cloud Run service.
+# ------------------------------------------------------------------
+# Why not `gcloud run deploy --source`? That path uses the default (small)
+# build VM and the classic Docker builder — no BuildKit, no layer cache, so
+# every deploy re-runs the full workspace `npm ci` (~10 min). This pipeline:
+# - runs on a 32-vCPU machine (E2_HIGHCPU_32)
+# - builds with BuildKit + inline cache pulled from the previous image, so
+# an unchanged package-lock.json skips `npm ci` entirely
+# - deploys the image to Cloud Run in the same run
+#
+# Usage (repo root):
+# npm run deploy:gcp
+# # or directly:
+# gcloud builds submit --config server/cloudbuild.yaml \
+# --region us-central1 --project aerial-vehicle-466722-p5
+
+steps:
+ # Warm the layer cache from the last successful image (best-effort).
+ - id: pull-cache
+ name: gcr.io/cloud-builders/docker
+ entrypoint: bash
+ args: ['-c', 'docker pull $_IMAGE || exit 0']
+
+ - id: build
+ name: gcr.io/cloud-builders/docker
+ env: ['DOCKER_BUILDKIT=1']
+ args:
+ [
+ 'build',
+ '-t',
+ '$_IMAGE',
+ '--cache-from',
+ '$_IMAGE',
+ '--build-arg',
+ 'BUILDKIT_INLINE_CACHE=1',
+ '.',
+ ]
+
+ - id: push
+ name: gcr.io/cloud-builders/docker
+ args: ['push', '$_IMAGE']
+
+ - id: deploy
+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim
+ entrypoint: gcloud
+ args:
+ [
+ 'run',
+ 'deploy',
+ 'three-ws-api',
+ '--image',
+ '$_IMAGE',
+ '--project',
+ '$PROJECT_ID',
+ '--region',
+ 'us-central1',
+ '--allow-unauthenticated',
+ '--memory',
+ '2Gi',
+ '--cpu',
+ '2',
+ '--timeout',
+ '900',
+ '--service-account',
+ ]
+
+substitutions:
+ _IMAGE: us-central1-docker.pkg.dev/aerial-vehicle-466722-p5/cloud-run-source-deploy/three-ws-api:latest
+
+options:
+ machineType: E2_HIGHCPU_32
+ logging: CLOUD_LOGGING_ONLY
+
+serviceAccount: projects/aerial-vehicle-466722-p5/serviceAccounts/[email protected]
+
+timeout: 2400s
+
+images: ['$_IMAGE']
diff --git a/server/index.mjs b/server/index.mjs
new file mode 100644
index 000000000..2655a9ec6
--- /dev/null
+++ b/server/index.mjs
@@ -0,0 +1,368 @@
+// three.ws production server — Cloud Run replacement for the Vercel runtime.
+// -------------------------------------------------------------------------
+// Serves the ENTIRE platform from one Express process:
+//
+// 1. The 1,000+ route table from vercel.json (`routes`) — security headers,
+// clean-URL rewrites (/3d → /3d.html), redirects, /cdn/* → API rewrites,
+// and the 404 fallback — interpreted with Vercel's legacy-routes
+// semantics (phase-1 rules → filesystem → post-filesystem rules).
+// 2. The static frontend from dist/ (Vite build output).
+// 3. Every serverless handler under api/** with Vercel filesystem-routing
+// semantics, so handlers run unmodified:
+// /api/foo → api/foo.js (or api/foo/index.js)
+// /api/agents/abc → api/agents/[id].js (params merged into req.query)
+// /api/v1/x/a/b/c → api/v1/x/[...slug].js (slug = "a/b/c")
+// Precedence per segment: exact file > exact dir > [param].js > [param]/
+// > [...catchall].js. Names starting with `_` or `.` are never routable.
+//
+// Request/response parity notes:
+// - req.url is the untouched original path + query (handlers parse it).
+// - req.query merges URL search params (repeated keys → array), then
+// dest-rewrite query params, then route params — later wins, as on Vercel.
+// - req.body is pre-parsed for JSON / urlencoded / text / octet-stream at
+// Vercel's 4.5 MB limit; multipart and other types stay unconsumed so
+// upload handlers can read the raw stream.
+// - SSE works: compression skips text/event-stream, and the HTTP server's
+// idle timeouts are lifted (Cloud Run enforces the real deadline).
+//
+// Run locally: node server/index.mjs (PORT defaults to 8080)
+
+import express from 'express';
+import compression from 'compression';
+import { existsSync, statSync, readdirSync, readFileSync } from 'node:fs';
+import path from 'node:path';
+import { pathToFileURL, fileURLToPath } from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const ROOT = path.resolve(__dirname, '..');
+const API_ROOT = path.join(ROOT, 'api');
+const DIST_ROOT = path.join(ROOT, 'dist');
+const PORT = Number(process.env.PORT) || 8080;
+const BODY_LIMIT = '4.5mb'; // Vercel serverless body limit
+
+// ---------------------------------------------------------------------------
+// vercel.json route table, split at the {handle: "filesystem"} marker.
+// ---------------------------------------------------------------------------
+
+const vercelConfig = JSON.parse(readFileSync(path.join(ROOT, 'vercel.json'), 'utf8'));
+const fsIndex = vercelConfig.routes.findIndex((r) => r.handle === 'filesystem');
+const compileRoute = (r) => ({ ...r, re: new RegExp(`^${r.src}$`) });
+const phase1Routes = vercelConfig.routes
+ .slice(0, fsIndex === -1 ? vercelConfig.routes.length : fsIndex)
+ .filter((r) => r.src)
+ .map(compileRoute);
+const postFsRoutes =
+ fsIndex === -1
+ ? []
+ : vercelConfig.routes
+ .slice(fsIndex + 1)
+ .filter((r) => r.src)
+ .map(compileRoute);
+
+// "$1"-style capture substitution used by dest and header values.
+function substitute(template, match) {
+ return template.replace(/\$(\d+)/g, (_, n) => match[Number(n)] ?? '');
+}
+
+// ---------------------------------------------------------------------------
+// API route resolution (Vercel filesystem semantics) with caches.
+// ---------------------------------------------------------------------------
+
+/** @type {Map<string, {file: string, params: Record<string, string>} | null>} */
+const routeCache = new Map();
+/** @type {Map<string, Promise<any>>} */
+const moduleCache = new Map();
+/** @type {Map<string, import('node:fs').Dirent[]>} */
+const dirCache = new Map();
+
+function listDir(dir) {
+ let entries = dirCache.get(dir);
+ if (!entries) {
+ entries = readdirSync(dir, { withFileTypes: true });
+ dirCache.set(dir, entries);
+ }
+ return entries;
+}
+
+function isRoutable(name) {
+ return !name.startsWith('_') && !name.startsWith('.');
+}
+
+function resolveApi(dir, segments, params) {
+ if (segments.length === 0) {
+ const index = path.join(dir, 'index.js');
+ return existsSync(index) ? { file: index, params } : null;
+ }
+ const [head, ...rest] = segments;
+
+ if (rest.length === 0) {
+ const exact = path.join(dir, `${head}.js`);
+ if (existsSync(exact)) return { file: exact, params };
+ }
+
+ const exactDir = path.join(dir, head);
+ if (existsSync(exactDir) && statSync(exactDir).isDirectory()) {
+ const hit = resolveApi(exactDir, rest, params);
+ if (hit) return hit;
+ }
+
+ const entries = listDir(dir);
+
+ if (rest.length === 0) {
+ for (const e of entries) {
+ if (!e.isFile() || !isRoutable(e.name)) continue;
+ if (e.name.startsWith('[') && e.name.endsWith('].js') && !e.name.startsWith('[...')) {
+ const name = e.name.slice(1, -4);
+ return { file: path.join(dir, e.name), params: { ...params, [name]: head } };
+ }
+ }
+ }
+
+ for (const e of entries) {
+ if (!e.isDirectory() || !isRoutable(e.name)) continue;
+ if (e.name.startsWith('[') && e.name.endsWith(']') && !e.name.startsWith('[...')) {
+ const name = e.name.slice(1, -1);
+ const hit = resolveApi(path.join(dir, e.name), rest, { ...params, [name]: head });
+ if (hit) return hit;
+ }
+ }
+
+ for (const e of entries) {
+ if (!e.isFile()) continue;
+ if (e.name.startsWith('[...') && e.name.endsWith('].js')) {
+ const name = e.name.slice(4, -4);
+ return {
+ file: path.join(dir, e.name),
+ params: { ...params, [name]: [head, ...rest].join('/') },
+ };
+ }
+ }
+
+ return null;
+}
+
+async function dispatchApi(req, res, pathname, extraQuery) {
+ // Route-table dests may target the file directly ("/api/x402/service.js").
+ const apiPath = pathname.endsWith('.js') ? pathname.slice(0, -3) : pathname;
+ let segments;
+ try {
+ segments = apiPath.slice(5).split('/').filter(Boolean).map(decodeURIComponent);
+ } catch {
+ res.status(400).json({ error: 'bad_request', message: 'Malformed URL encoding.' });
+ return true;
+ }
+ if (segments.length === 0 || segments.some((s) => !isRoutable(s) || s === '..')) return false;
+
+ const cacheKey = segments.join('/');
+ let route = routeCache.get(cacheKey);
+ if (route === undefined) {
+ route = resolveApi(API_ROOT, segments, {});
+ routeCache.set(cacheKey, route);
+ }
+ if (!route) return false;
+
+ // req.query: search params (repeated keys → array), then dest-rewrite
+ // query, then route params — later wins, matching Vercel. Express 5
+ // defines `query` as a prototype getter, so shadow it.
+ const url = new URL(req.url, 'http://internal');
+ const query = {};
+ for (const key of new Set(url.searchParams.keys())) {
+ const all = url.searchParams.getAll(key);
+ query[key] = all.length > 1 ? all : all[0];
+ }
+ Object.assign(query, extraQuery, route.params);
+ Object.defineProperty(req, 'query', { value: query, writable: true, configurable: true });
+
+ try {
+ let mod = moduleCache.get(route.file);
+ if (!mod) {
+ mod = import(pathToFileURL(route.file).href);
+ moduleCache.set(route.file, mod);
+ }
+ const handler = (await mod).default;
+ if (typeof handler !== 'function') {
+ console.error(`[api] ${route.file} has no default-export handler`);
+ res.status(500).json({ error: 'internal_error', message: 'Handler misconfigured.' });
+ return true;
+ }
+ await handler(req, res);
+ } catch (err) {
+ console.error(`[api] ${req.method} ${pathname} failed:`, err);
+ if (!res.headersSent) {
+ res.status(500).json({
+ error: 'internal_error',
+ message: 'The request failed unexpectedly.',
+ });
+ } else if (!res.writableEnded) {
+ res.end();
+ }
+ }
+ return true;
+}
+
+// ---------------------------------------------------------------------------
+// Static file serving from dist/ (the filesystem phase).
+// ---------------------------------------------------------------------------
+
+function resolveStatic(pathname) {
+ let rel;
+ try {
+ rel = decodeURIComponent(pathname);
+ } catch {
+ return null;
+ }
+ const abs = path.normalize(path.join(DIST_ROOT, rel));
+ if (!abs.startsWith(DIST_ROOT + path.sep) && abs !== DIST_ROOT) return null; // traversal guard
+ let target = abs;
+ try {
+ let st = statSync(target);
+ if (st.isDirectory()) {
+ target = path.join(target, 'index.html');
+ st = statSync(target);
+ }
+ return st.isFile() ? target : null;
+ } catch {
+ return null;
+ }
+}
+
+function serveFile(req, res, file, headers, status) {
+ res.set(headers);
+ if (status) res.status(status);
+ return new Promise((resolvePromise) => {
+ res.sendFile(file, { dotfiles: 'deny' }, (err) => {
+ if (err && !res.headersSent) {
+ console.error(`[static] ${req.method} ${req.url} → ${file} failed:`, err.message);
+ res.status(500).end();
+ }
+ resolvePromise();
+ });
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Express app
+// ---------------------------------------------------------------------------
+
+const app = express();
+app.set('trust proxy', true); // Cloud Run sits behind Google front ends
+app.disable('x-powered-by');
+
+// Default filter already skips non-compressible types (text/event-stream,
+// images, GLB), so SSE and binary assets pass through untouched.
+app.use(compression());
+
+// Vercel-parity body parsing. Types not listed (multipart, image/*, …) are
+// left unparsed so handlers can consume the raw request stream.
+app.use(express.json({ limit: BODY_LIMIT }));
+app.use(express.urlencoded({ extended: true, limit: BODY_LIMIT }));
+app.use(express.text({ type: 'text/*', limit: BODY_LIMIT }));
+app.use(express.raw({ type: 'application/octet-stream', limit: BODY_LIMIT }));
+
+app.use(async (req, res) => {
+ const url = new URL(req.url, 'http://internal');
+ let currentPath = url.pathname;
+ const collected = {};
+ const extraQuery = {};
+ let fileStatus = null;
+
+ // Phase 1: rules before {handle: "filesystem"}.
+ for (const route of phase1Routes) {
+ const m = route.re.exec(currentPath);
+ if (!m) continue;
+ if (route.headers) {
+ for (const [k, v] of Object.entries(route.headers)) collected[k] = substitute(v, m);
+ }
+ if (route.continue) continue;
+ if (route.status && !route.dest) {
+ res.status(route.status).set(collected).end();
+ return;
+ }
+ if (route.dest) {
+ const dest = substitute(route.dest, m);
+ const qIdx = dest.indexOf('?');
+ currentPath = qIdx === -1 ? dest : dest.slice(0, qIdx);
+ if (qIdx !== -1) {
+ for (const [k, v] of new URLSearchParams(dest.slice(qIdx + 1))) extraQuery[k] = v;
+ }
+ if (route.status) fileStatus = route.status;
+ break; // non-continue dest ends phase-1 matching
+ }
+ }
+
+ // Functions phase: anything routed under /api/ is a serverless handler.
+ if (currentPath.startsWith('/api/')) {
+ res.set(collected);
+ if (await dispatchApi(req, res, currentPath, extraQuery)) return;
+ res.status(404).json({
+ error: 'not_found',
+ message: `No API route matches ${currentPath}.`,
+ });
+ return;
+ }
+
+ // Filesystem phase (GET/HEAD only, like a static host).
+ if (req.method === 'GET' || req.method === 'HEAD') {
+ const file = resolveStatic(currentPath);
+ if (file) {
+ await serveFile(req, res, file, collected, fileStatus);
+ return;
+ }
+ }
+
+ // Post-filesystem rules (the 404.html fallback).
+ for (const route of postFsRoutes) {
+ const m = route.re.exec(currentPath);
+ if (!m) continue;
+ if (route.headers) {
+ for (const [k, v] of Object.entries(route.headers)) collected[k] = substitute(v, m);
+ }
+ if (route.dest) {
+ const file = resolveStatic(substitute(route.dest, m));
+ if (file) {
+ await serveFile(req, res, file, collected, route.status || 404);
+ return;
+ }
+ }
+ if (route.status) {
+ res.status(route.status).set(collected).end();
+ return;
+ }
+ }
+
+ res.status(404).set(collected).type('text/plain').send('Not found');
+});
+
+// Body-parser failures (malformed JSON, over-limit payloads) → clean 4xx.
+app.use((err, req, res, next) => {
+ if (res.headersSent) return next(err);
+ const status = err?.status || err?.statusCode;
+ if (status && status >= 400 && status < 500) {
+ res.status(status).json({ error: 'bad_request', message: err.message });
+ return;
+ }
+ console.error('[server] unexpected middleware error:', err);
+ res.status(500).json({ error: 'internal_error', message: 'The request failed unexpectedly.' });
+});
+
+process.on('unhandledRejection', (reason) => {
+ console.error('[server] unhandled rejection:', reason);
+});
+
+const server = app.listen(PORT, () => {
+ console.log(
+ `[server] three-ws listening on :${PORT} (api: ${API_ROOT}, static: ${DIST_ROOT}, routes: ${phase1Routes.length}+${postFsRoutes.length})`,
+ );
+});
+// SSE endpoints hold connections open; keep Node's idle timeouts out of the way
+// (Cloud Run enforces the real request deadline).
+server.requestTimeout = 0;
+server.headersTimeout = 65_000;
+server.keepAliveTimeout = 620_000;
+
+// Cloud Run sends SIGTERM before scale-down; finish in-flight work, then exit.
+process.on('SIGTERM', () => {
+ console.log('[server] SIGTERM received, draining…');
+ server.close(() => process.exit(0));
+ setTimeout(() => process.exit(0), 10_000).unref();
+});