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(gcp): add scripts for managing GCP credit program budgets and burn reports

fudjia9d4124588fd4
diff --git a/.env.example b/.env.example
index b9d155ccc..8215e7b79 100644
--- a/.env.example
+++ b/.env.example
@@ -1127,22 +1127,32 @@ GRADUATIONS_LIST_KEY=pf:graduations
REPLICATE_WEBHOOK_SIGNING_KEY=
# ── Google Cloud Platform — 3D pipeline + Vertex AI ──────────────────────────
-# Used for: Vertex AI Imagen text-to-image, and self-hosted Cloud Run workers
-# (avatar reconstruction, background removal, remesh, texture generation).
+# Used for: Vertex AI text-to-image (reference image for text→3D), and
+# self-hosted Cloud Run workers (avatar reconstruction, background removal,
+# remesh, texture generation).
#
-# Provider priority: Vertex AI Imagen > Replicate for text-to-image.
+# text-to-image provider ladder: NVIDIA NIM FLUX > Vertex > Replicate.
# Worker priority: GCP Cloud Run > Replicate > HuggingFace for image-to-3D.
#
# Get your project id from: https://console.cloud.google.com
GOOGLE_CLOUD_PROJECT=
-# Region for Vertex AI endpoints (default: us-central1)
+# Region for Vertex AI endpoints (default: us-central1). Set to "global" for
+# models only served on the global endpoint.
GOOGLE_CLOUD_LOCATION=us-central1
-# Vertex AI Imagen model. Options:
-# imagen-3.0-generate-001 — highest quality (~8s, ~$0.04/image)
-# imagen-3.0-fast-generate-001 — faster (~3s, ~$0.02/image)
-VERTEX_IMAGEN_MODEL=imagen-3.0-generate-001
-# Vertex AI image editing model (used by /api/forge-edit when configured)
-VERTEX_IMAGEN_EDIT_MODEL=imagen-3.0-capability-001
+# Explicit on/off gate for the Vertex text-to-image lane, independent of
+# GOOGLE_CLOUD_PROJECT (which Vertex Claude and the workers also need). Unset ⇒
+# lane is active whenever the project is set (today's behavior). Set to 0/false
+# to turn the lane off without unsetting the shared project. See docs/gcp-credits.md.
+VERTEX_IMAGEN_ENABLED=
+# Vertex image-generation model. NOTE: Google is retiring the Imagen :predict
+# family (imagen-3.0-* shut down 2026-06-30; imagen-4.0-* by 2026-08-17), so the
+# default is now the live Gemini image model, which bills to the same GCP credits:
+# gemini-2.5-flash-image — GA "Nano Banana" (generateContent API)
+# imagen-4.0-generate-001 — legacy :predict path, until 2026-08-17 only
+VERTEX_IMAGEN_MODEL=gemini-2.5-flash-image
+# Vertex image-editing model (used by editImage()). Same Gemini default; an
+# imagen-* value routes to the legacy :predict edit shape while still callable.
+VERTEX_IMAGEN_EDIT_MODEL=gemini-2.5-flash-image
# Service account JSON key (paste the full JSON as a single-line string).
# Alternative: set GOOGLE_APPLICATION_CREDENTIALS to a file path on the server.
GCP_SERVICE_ACCOUNT_JSON=
diff --git a/api/_lib/forge-tiers.js b/api/_lib/forge-tiers.js
index 83fb30eb5..a9352e471 100644
--- a/api/_lib/forge-tiers.js
+++ b/api/_lib/forge-tiers.js
@@ -445,9 +445,21 @@ export function freeLaneCandidates(p, tierId, userImages) {
const named = FREE_DEFAULT_FOR_TIERS[tierId]?.[p];
if (named) ordered.push(named);
for (const id of FREE_FALLBACK_FOR_PATH[p] || []) ordered.push(id);
+ // FORGE_SELFHOST_PRIMARY: when our own Cloud Run GPU fleet is live, hoist the
+ // self-host lanes ahead of every hosted free lane (NVIDIA NIM / HuggingFace) so
+ // the platform spends the GCP credits it controls before any external free
+ // allocation — and so image→3D, which the hosted NIM preview rejects, serves off
+ // our own TRELLIS. Stable partition: it only reorders self-host ↑ / hosted ↓ and
+ // preserves each group's internal order, leaving the hosted lanes intact as
+ // fallthrough. A no-op on deployments without the worker URLs (those lanes are
+ // filtered by freeLaneUsable anyway) and off by default — unset the flag to
+ // restore today's tier-named ordering instantly.
+ const prioritized = selfHostPrimary()
+ ? [...ordered.filter(isSelfHostBackend), ...ordered.filter((id) => !isSelfHostBackend(id))]
+ : ordered;
const seen = new Set();
const out = [];
- for (const id of ordered) {
+ for (const id of prioritized) {
if (seen.has(id)) continue;
seen.add(id);
if (freeLaneUsable(id, p, userImages)) out.push(id);
@@ -541,6 +553,18 @@ export function preferFreeReconstruct() {
return !/^(0|false|off|no)$/i.test(String(v).trim());
}
+// Self-host-primary routing. When ON, freeLaneCandidates hoists our own Cloud Run
+// GPU workers (SELF_HOST_PROVIDERS) ahead of the hosted free lanes for every path
+// and tier, so once the fleet is deployed the platform serves generations off the
+// GCP credits it controls instead of the rate-limited hosted NVIDIA NIM allocation.
+// OFF by default (opt-in per the credit-window rollout) and reversible — unset
+// FORGE_SELFHOST_PRIMARY to fall straight back to today's ordering with no redeploy.
+export function selfHostPrimary() {
+ const v = readEnv('FORGE_SELFHOST_PRIMARY');
+ if (v == null || v === '') return false;
+ return /^(1|true|on|yes)$/i.test(String(v).trim());
+}
+
// A platform backend is "live" only when its required env is present. BYOK
// backends are always selectable — liveness depends on the caller's key, which
// is resolved per-request, not here.
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index e66fbedfd..106d1bcfb 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -20,6 +20,23 @@ const REDIS_CONFIGURED = Boolean(redis);
// HuggingFace lanes stay open, so paid capacity degrades instead of dead-ending.
const FORGE_PAID_GLOBAL_HOURLY = Math.max(1, Number(process.env.FORGE_PAID_GLOBAL_HOURLY) || 600);
+// FORGE_SELFHOST_PRIMARY: the per-principal free-lane ceiling (mcp3dGenerateFree,
+// below) is sized at 60/h to protect the RATE-LIMITED hosted NVIDIA NIM allocation
+// the free lane leans on today. Once our own Cloud Run GPU fleet is primary that
+// hosted allocation is out of the path, so the ceiling can rise to what the deployed
+// fleet sustains. Default 240/h (4× — see the math in docs/gcp-credits.md: credit-
+// window fleet of trellis_selfhost[max 2] + hunyuan3d[max 3] = 5 concurrent L4 slots
+// at ~60s/asset blended ≈ 300 assets/h global, so a single heavy iterator at 240/h
+// stays well under the fleet ceiling). Tunable via FORGE_FREE_HOURLY_SELFHOST once
+// real per-asset latency is measured post-deploy. Reverts to 60/h the moment the
+// flag is unset — abuse and per-IP paid gates are unaffected by this lever.
+const FORGE_SELFHOST_PRIMARY = /^(1|true|on|yes)$/i.test(
+ String(process.env.FORGE_SELFHOST_PRIMARY || '').trim(),
+);
+const FREE_HOURLY_BASE = FORGE_SELFHOST_PRIMARY
+ ? Math.max(60, Number(process.env.FORGE_FREE_HOURLY_SELFHOST) || 240)
+ : 60;
+
// Loud, one-time startup warning when Redis is unconfigured in production. Without
// Redis every limiter falls back to a PER-INSTANCE in-memory map, which is
// effectively unbounded across serverless fan-out — fine for dev, dangerous for
@@ -428,14 +445,14 @@ export const limits = {
// open), unlike the paid lane which fails closed to protect spend. A real
// human iterating on a prompt routinely exceeds 12/h; this lane lets them.
mcp3dGenerateFree: (key) =>
- getLimiter('mcp3d:generate:free', { limit: 60, window: '1 h' }).limit(key),
+ getLimiter('mcp3d:generate:free', { limit: FREE_HOURLY_BASE, window: '1 h' }).limit(key),
// Holder perk (Lever 2): $THREE tiers raise the free-generation ceiling by their
// rate multiplier. Same per-key counter + prefix as the base free lane — the tier
// only lifts the threshold, so a holder iterating heavily isn't throttled at 60/h.
// `multiplier` comes from a verified tier pass (pure HMAC, no RPC on the hot path).
mcp3dGenerateFreeTiered: (key, multiplier = 1) =>
getLimiter('mcp3d:generate:free', {
- limit: Math.max(60, Math.round(60 * (Number(multiplier) || 1))),
+ limit: Math.max(FREE_HOURLY_BASE, Math.round(FREE_HOURLY_BASE * (Number(multiplier) || 1))),
window: '1 h',
}).limit(key),
// Status polling is the highest-frequency call in the generation flow (every
diff --git a/api/_lib/vanity-inventory-store.js b/api/_lib/vanity-inventory-store.js
new file mode 100644
index 000000000..a60027ffe
--- /dev/null
+++ b/api/_lib/vanity-inventory-store.js
@@ -0,0 +1,334 @@
+// Premium vanity inventory — the Postgres store.
+//
+// The security-critical surface. Everything that reads or mutates the
+// `vanity_inventory` table lives here so the single-use delivery contract is
+// enforced in ONE place, as atomic status-guarded UPDATEs the database
+// serializes — never as read-then-write logic a race could double-spend.
+//
+// State machine (see the migration for the CHECK):
+// available ──reserve──▶ reserved ──reveal──▶ revealed ──destroy──▶ destroyed
+// A reveal is a single atomic UPDATE that flips reserved→revealed and RETURNS the
+// ciphertext in the same statement. A second reveal matches zero rows (status is
+// no longer 'reserved'/'sold'), so the secret is delivered exactly once. Delete-
+// after-reveal (retention_days = 0, the default) nulls the ciphertext in that
+// same reveal, so it is gone the instant it is served.
+//
+// PUBLIC vs SECRET: every public read (listing, item detail) selects an explicit
+// column list that OMITS secret_ciphertext. Only reserveAndReveal() ever touches
+// the ciphertext, and it returns it to the caller (the delivery endpoint) exactly
+// once, then this module never surfaces it again.
+
+import { sql, isDbUnavailableError } from './db.js';
+
+// Columns that are safe to expose publicly (never includes secret_ciphertext).
+const PUBLIC_COLS = sql`
+ id, address, prefix, suffix, ignore_case, pattern_label, format,
+ difficulty_attempts, rarity_bits, rarity_tier, rarity_score,
+ status, price_usd, created_at
+`;
+
+function shapePublic(row) {
+ if (!row) return null;
+ return {
+ id: row.id,
+ address: row.address,
+ prefix: row.prefix,
+ suffix: row.suffix,
+ ignoreCase: row.ignore_case,
+ patternLabel: row.pattern_label,
+ format: row.format,
+ difficultyAttempts: Number(row.difficulty_attempts),
+ rarityBits: Number(row.rarity_bits),
+ rarityTier: row.rarity_tier,
+ rarityScore: Number(row.rarity_score),
+ status: row.status,
+ priceUsd: Number(row.price_usd),
+ createdAt: row.created_at,
+ };
+}
+
+/**
+ * Upsert a freshly-ground inventory item. Idempotent on `address` — a re-run of a
+ * batch that re-finds an address is a safe no-op (never overwrites a sold row or
+ * re-exposes a destroyed one). The caller (workers/vanity-grinder) has ALREADY
+ * sealed the secret via api/_lib/vanity-vault.js; this function only ever sees
+ * ciphertext.
+ *
+ * @param {object} item
+ * @returns {Promise<{ inserted:boolean, address:string }>}
+ */
+export async function upsertInventoryItem(item) {
+ const {
+ address,
+ prefix = null,
+ suffix = null,
+ ignoreCase = false,
+ patternLabel,
+ format = 'keypair',
+ difficultyAttempts = 0,
+ rarityBits = 0,
+ rarityTier = 'common',
+ rarityScore = 0,
+ secretCiphertext,
+ secretScheme = 'aes-256-gcm',
+ priceUsd = 1,
+ retentionDays = 0,
+ batchId = null,
+ } = item;
+
+ if (!address) throw new Error('upsertInventoryItem: address required');
+ if (!secretCiphertext) throw new Error('upsertInventoryItem: sealed secret required');
+ if (secretCiphertext.includes('"secretKey"') || /^\[?\s*\d+\s*,\s*\d+/.test(secretCiphertext)) {
+ // Guard against a caller accidentally passing a plaintext key. The vault
+ // ciphertext is always a scheme-prefixed opaque blob, never raw JSON/array.
+ throw new Error('upsertInventoryItem: refusing to store what looks like a plaintext secret');
+ }
+
+ const [row] = await sql`
+ INSERT INTO vanity_inventory
+ (address, prefix, suffix, ignore_case, pattern_label, format,
+ difficulty_attempts, rarity_bits, rarity_tier, rarity_score,
+ secret_ciphertext, secret_scheme, price_usd, retention_days, batch_id)
+ VALUES
+ (${address}, ${prefix}, ${suffix}, ${ignoreCase}, ${patternLabel}, ${format},
+ ${String(difficultyAttempts)}, ${rarityBits}, ${rarityTier}, ${rarityScore},
+ ${secretCiphertext}, ${secretScheme}, ${priceUsd}, ${retentionDays}, ${batchId})
+ ON CONFLICT (address) DO NOTHING
+ RETURNING id
+ `;
+ return { inserted: Boolean(row), address };
+}
+
+/**
+ * Browse available inventory (public metadata only). Optional pattern filter and
+ * ordering. Never returns ciphertext.
+ *
+ * @param {object} [opts]
+ * @param {string} [opts.prefix] case-insensitive prefix filter
+ * @param {string} [opts.tier] rarity tier filter
+ * @param {'rarity'|'price'|'new'} [opts.sort]
+ * @param {number} [opts.limit]
+ * @param {number} [opts.offset]
+ * @returns {Promise<object[]>}
+ */
+export async function listAvailable(opts = {}) {
+ const { prefix, tier, sort = 'rarity', limit = 60, offset = 0 } = opts;
+ const lim = Math.min(Math.max(1, Number(limit) || 60), 200);
+ const off = Math.max(0, Number(offset) || 0);
+
+ let where = sql`status = 'available'`;
+ if (prefix) where = sql`${where} AND lower(prefix) LIKE ${String(prefix).toLowerCase() + '%'}`;
+ if (tier) where = sql`${where} AND rarity_tier = ${String(tier)}`;
+
+ let order;
+ if (sort === 'price') order = sql`price_usd ASC, rarity_score DESC`;
+ else if (sort === 'new') order = sql`created_at DESC`;
+ else order = sql`rarity_score DESC, price_usd DESC`;
+
+ const rows = await sql`
+ SELECT ${PUBLIC_COLS} FROM vanity_inventory
+ WHERE ${where}
+ ORDER BY ${order}
+ LIMIT ${lim} OFFSET ${off}
+ `;
+ return rows.map(shapePublic);
+}
+
+/** Public detail for one address (metadata only, any status). */
+export async function getPublicItem(address) {
+ const [row] = await sql`
+ SELECT ${PUBLIC_COLS} FROM vanity_inventory WHERE address = ${address} LIMIT 1
+ `;
+ return shapePublic(row);
+}
+
+/** Aggregate counts + price range for the listing header / stats strip. */
+export async function inventoryStats() {
+ const [row] = await sql`
+ SELECT
+ count(*) FILTER (WHERE status = 'available') AS available,
+ count(*) FILTER (WHERE status IN ('revealed','sold','destroyed')) AS sold,
+ count(*) AS total,
+ coalesce(min(price_usd) FILTER (WHERE status = 'available'), 0) AS min_price,
+ coalesce(max(price_usd) FILTER (WHERE status = 'available'), 0) AS max_price,
+ count(DISTINCT rarity_tier) FILTER (WHERE status = 'available') AS tiers
+ FROM vanity_inventory
+ `;
+ return {
+ available: Number(row?.available || 0),
+ sold: Number(row?.sold || 0),
+ total: Number(row?.total || 0),
+ minPrice: Number(row?.min_price || 0),
+ maxPrice: Number(row?.max_price || 0),
+ tiers: Number(row?.tiers || 0),
+ };
+}
+
+/**
+ * Atomically reserve an available item for a paying buyer. This is the FIRST half
+ * of purchase: it flips available→reserved only if the row is still available, so
+ * two concurrent buyers of the same address can never both win. Idempotent per
+ * payment_id: if the SAME payment already reserved this address, it re-selects
+ * that reservation instead of failing (a retried/settled payment is not a
+ * conflict).
+ *
+ * @returns {Promise<{ ok:true, item:object } | { ok:false, reason:string }>}
+ */
+export async function reserveForPurchase(address, { paymentId, purchaser }) {
+ if (!address) return { ok: false, reason: 'address required' };
+ const [row] = await sql`
+ UPDATE vanity_inventory
+ SET status = 'reserved',
+ payment_id = ${paymentId || null},
+ purchaser = ${purchaser || null},
+ reserved_at = now(),
+ updated_at = now()
+ WHERE address = ${address} AND status = 'available'
+ RETURNING ${PUBLIC_COLS}
+ `;
+ if (row) return { ok: true, item: shapePublic(row) };
+
+ // Not available — either already reserved by THIS payment (idempotent retry),
+ // already revealed/sold, or gone. Distinguish so the caller returns the right
+ // state instead of a blanket conflict.
+ const [existing] = await sql`
+ SELECT ${PUBLIC_COLS}, payment_id FROM vanity_inventory WHERE address = ${address} LIMIT 1
+ `;
+ if (!existing) return { ok: false, reason: 'not_found' };
+ if (paymentId && existing.payment_id === paymentId && ['reserved', 'sold'].includes(existing.status)) {
+ return { ok: true, item: shapePublic(existing) };
+ }
+ return { ok: false, reason: existing.status === 'available' ? 'race' : 'unavailable', status: existing.status };
+}
+
+/**
+ * The one-shot reveal — the function the delivery endpoint calls.
+ *
+ * Postgres cannot both null a column AND return its pre-null value in one plain
+ * UPDATE … RETURNING, so this is an atomic CTE: `moved` captures the row (FOR
+ * UPDATE), `revealed` flips its status and nulls the ciphertext per retention,
+ * and the final SELECT returns the ciphertext captured in `moved` BEFORE the
+ * null-out. The `secret_ciphertext IS NOT NULL` + status guard in `moved` makes
+ * the whole thing single-use: a second call captures zero rows and returns
+ * `already_revealed`. On retention_days = 0 (delete-after-reveal, the default)
+ * the ciphertext is destroyed in the same statement that serves it.
+ *
+ * Guarded by payment_id: only the payment that reserved the row can reveal it.
+ *
+ * @returns {Promise<{ ok:true, ciphertext:string, scheme:string, item:object, destroyed:boolean }
+ * | { ok:false, reason:string, status?:string }>}
+ */
+export async function reserveAndReveal(address, { paymentId }) {
+ if (!address) return { ok: false, reason: 'address required' };
+ if (!paymentId) return { ok: false, reason: 'payment_id required' };
+
+ const rows = await sql`
+ WITH moved AS (
+ SELECT id, secret_ciphertext, secret_scheme, retention_days
+ FROM vanity_inventory
+ WHERE address = ${address}
+ AND payment_id = ${paymentId}
+ AND status IN ('reserved', 'sold')
+ AND secret_ciphertext IS NOT NULL
+ FOR UPDATE
+ ),
+ revealed AS (
+ UPDATE vanity_inventory v
+ SET status = CASE WHEN v.retention_days = 0 THEN 'destroyed' ELSE 'revealed' END,
+ revealed_at = now(),
+ sold_at = coalesce(v.sold_at, now()),
+ secret_ciphertext = CASE WHEN v.retention_days = 0 THEN NULL ELSE v.secret_ciphertext END,
+ destroyed_at = CASE WHEN v.retention_days = 0 THEN now() ELSE v.destroyed_at END,
+ updated_at = now()
+ FROM moved
+ WHERE v.id = moved.id
+ RETURNING v.address, v.prefix, v.suffix, v.ignore_case, v.pattern_label, v.format,
+ v.difficulty_attempts, v.rarity_bits, v.rarity_tier, v.rarity_score,
+ v.status, v.price_usd, v.created_at, v.id
+ )
+ SELECT
+ moved.secret_ciphertext AS ciphertext,
+ moved.secret_scheme AS scheme,
+ moved.retention_days AS retention_days,
+ revealed.*
+ FROM moved JOIN revealed ON revealed.id = moved.id
+ `;
+ const row = rows[0];
+ if (!row) {
+ const [cur] = await sql`SELECT status, payment_id FROM vanity_inventory WHERE address = ${address} LIMIT 1`;
+ if (!cur) return { ok: false, reason: 'not_found' };
+ if (['revealed', 'destroyed'].includes(cur.status)) return { ok: false, reason: 'already_revealed' };
+ if (paymentId && cur.payment_id && cur.payment_id !== paymentId) return { ok: false, reason: 'wrong_payment' };
+ return { ok: false, reason: 'not_reserved', status: cur.status };
+ }
+ return {
+ ok: true,
+ ciphertext: row.ciphertext,
+ scheme: row.scheme,
+ destroyed: Number(row.retention_days) === 0,
+ item: shapePublic(row),
+ };
+}
+
+/**
+ * Non-destructive read of the sealed ciphertext for a row reserved by THIS
+ * payment. The delivery endpoint calls this AFTER reserve but BEFORE settle to
+ * prove it can actually decrypt (e.g. KMS reachable) before charging the buyer —
+ * so a decrypt outage fails the purchase cleanly instead of settling and then
+ * being unable to deliver. Only ever returns ciphertext for a row this payment
+ * already reserved (so it's already unavailable to anyone else); does not change
+ * state, so single-use delivery is still enforced solely by reserveAndReveal().
+ *
+ * @returns {Promise<{ ok:true, ciphertext:string, scheme:string }
+ * | { ok:false, reason:string }>}
+ */
+export async function peekReservedSecret(address, { paymentId }) {
+ if (!address || !paymentId) return { ok: false, reason: 'address + payment_id required' };
+ const [row] = await sql`
+ SELECT secret_ciphertext, secret_scheme FROM vanity_inventory
+ WHERE address = ${address} AND payment_id = ${paymentId}
+ AND status IN ('reserved', 'sold') AND secret_ciphertext IS NOT NULL
+ LIMIT 1
+ `;
+ if (!row) return { ok: false, reason: 'not_reserved_or_gone' };
+ return { ok: true, ciphertext: row.secret_ciphertext, scheme: row.secret_scheme };
+}
+
+/**
+ * Sweep: destroy ciphertext for revealed items whose retention window has passed.
+ * Run from scripts/vanity-inventory-load.mjs --sweep (or a cron). Idempotent.
+ * @returns {Promise<{ destroyed:number }>}
+ */
+export async function sweepExpiredSecrets() {
+ const rows = await sql`
+ UPDATE vanity_inventory
+ SET secret_ciphertext = NULL,
+ status = 'destroyed',
+ destroyed_at = now(),
+ updated_at = now()
+ WHERE status = 'revealed'
+ AND retention_days > 0
+ AND secret_ciphertext IS NOT NULL
+ AND revealed_at < now() - (retention_days * interval '1 day')
+ RETURNING id
+ `;
+ return { destroyed: rows.length };
+}
+
+/**
+ * Release a reservation back to available. Called if payment settlement fails
+ * AFTER a reserve but BEFORE reveal, so a stuck reservation doesn't strand
+ * sellable stock. Guarded by payment_id so only the reserving payment can release.
+ */
+export async function releaseReservation(address, { paymentId }) {
+ const [row] = await sql`
+ UPDATE vanity_inventory
+ SET status = 'available', payment_id = NULL, purchaser = NULL,
+ reserved_at = NULL, updated_at = now()
+ WHERE address = ${address} AND status = 'reserved' AND payment_id = ${paymentId}
+ RETURNING id
+ `;
+ return { released: Boolean(row) };
+}
+
+export { isDbUnavailableError };
diff --git a/api/_mcp3d/text-to-image.js b/api/_mcp3d/text-to-image.js
index d50a1099a..2dae53087 100644
--- a/api/_mcp3d/text-to-image.js
+++ b/api/_mcp3d/text-to-image.js
@@ -340,7 +340,7 @@ export async function textToImage(prompt, { aspectRatio = '1:1', skipNim = false
try {
const { generateImage, isConfigured } = await import('./vertex-imagen.js');
if (isConfigured()) {
- return await persistDataUriImage(await generateImage(prompt, { aspectRatio }));
+ return logImageProvider(await persistDataUriImage(await generateImage(prompt, { aspectRatio })));
}
} catch (err) {
if (!token) throw err;
@@ -477,7 +477,7 @@ export async function textToImage(prompt, { aspectRatio = '1:1', skipNim = false
const finished = await pollReplicatePrediction(getUrl, token);
url = extractImageUrl(finished?.output);
if (url) {
- return { imageUrl: url, predictionId: finished?.id || data.id, model: modelRef };
+ return logImageProvider({ imageUrl: url, predictionId: finished?.id || data.id, model: modelRef });
}
throw new Error(
`text-to-image did not complete (status: ${finished?.status || data.status})`,
@@ -488,5 +488,5 @@ export async function textToImage(prompt, { aspectRatio = '1:1', skipNim = false
}
throw new Error('text-to-image finished but produced no image');
}
- return { imageUrl: url, predictionId: data.id, model: modelRef };
+ return logImageProvider({ imageUrl: url, predictionId: data.id, model: modelRef });
}
diff --git a/api/brain/chat.js b/api/brain/chat.js
index 4326b3cfa..9954735d5 100644
--- a/api/brain/chat.js
+++ b/api/brain/chat.js
@@ -21,6 +21,11 @@ import { limits, clientIp } from '../_lib/rate-limit.js';
import { watsonxConfig, watsonxChatRequest } from '../_lib/watsonx.js';
import { DEFAULT_FREE_MODEL } from '../_lib/chat-models.js';
import { createReasoningStripper } from '../_lib/strip-reasoning.js';
+import {
+ vertexClaudeEnabled,
+ vertexClaudeConfigured,
+ vertexAnthropicMessages,
+} from '../_lib/vertex-claude.js';
// Providers an anonymous (signed-out) caller may use: only the genuinely free
// tiers — the OpenRouter-routed open-weight default and the free NVIDIA NIM
@@ -187,6 +192,41 @@ const PROVIDERS = {
watsonx: true,
},
+ // ── Google Vertex AI — first-party Claude billed to GCP credits ──────────────
+ // Only present when VERTEX_CLAUDE_ENABLED (merged below), so the /brain roster
+ // is byte-identical when the flag is off. The `vertex` flag names the Vertex
+ // publisher model id; buildPrimary() routes it through the shared vertex-claude
+ // transport (like the `watsonx` flag), so /brain can compare Vertex-served
+ // Claude head-to-head with first-party Claude and every other provider.
+ ...(vertexClaudeEnabled()
+ ? {
+ 'vertex-claude-sonnet': {
+ label: 'Claude Sonnet 4.6 · Vertex',
+ network: 'Anthropic · Google Vertex',
+ tier: 'balanced',
+ maxOutput: 16384,
+ description: 'Claude Sonnet 4.6 served from Google Vertex AI (billed to GCP credits).',
+ vertex: 'claude-sonnet-4-6',
+ },
+ 'vertex-claude-opus': {
+ label: 'Claude Opus 4.7 · Vertex',
+ network: 'Anthropic · Google Vertex',
+ tier: 'flagship',
+ maxOutput: 16384,
+ description: 'Claude Opus 4.7 served from Google Vertex AI (billed to GCP credits).',
+ vertex: 'claude-opus-4-7',
+ },
+ 'vertex-claude-haiku': {
+ label: 'Claude Haiku 4.5 · Vertex',
+ network: 'Anthropic · Google Vertex',
+ tier: 'fast',
+ maxOutput: 8192,
+ description: 'Claude Haiku 4.5 served from Google Vertex AI (billed to GCP credits).',
+ vertex: 'claude-haiku-4-5-20251001',
+ },
+ }
+ : {}),
+
// ── NVIDIA NIM (build.nvidia.com) — free hosted inference ────────────────────
// One free `nvapi-...` key (NVIDIA_API_KEY) unlocks all of these. NVIDIA-hosted,
// so there is no first-party-vs-OpenRouter split: `native` is the only route and
@@ -268,6 +308,10 @@ function openrouterKeys() {
// distinct escape hatch.
function buildPrimary(spec) {
if (spec.watsonx) return watsonxConfig().configured ? { kind: 'watsonx' } : null;
+ // Vertex-served Claude — routed through the shared vertex-claude transport
+ // (not an AI SDK model object), so it reports availability here and streams
+ // via streamVertex() in streamBrain(). Requires the GCP project to be set.
+ if (spec.vertex) return vertexClaudeConfigured() ? { kind: 'vertex', model: spec.vertex } : null;
const native = spec.native?.();
if (native) return { kind: 'model', model: native, via: 'native' };
if (spec.openrouterModel && openrouterKeys().length) {
@@ -588,9 +632,12 @@ export async function streamBrain(res, { plan, providerKey, messages, system, ma
// error event while any free provider can still answer. Once partial output
// has streamed we are committed to that attempt.
try {
- const attempts = primary.kind === 'watsonx'
- ? [{ label: 'watsonx', watsonx: true }]
- : [{ label: 'primary', model: primary.model }];
+ const attempts =
+ primary.kind === 'watsonx'
+ ? [{ label: 'watsonx', watsonx: true }]
+ : primary.kind === 'vertex'
+ ? [{ label: 'vertex', vertex: true, model: primary.model }]
+ : [{ label: 'primary', model: primary.model }];
if (fallbackModel) attempts.push({ label: 'openrouter-mirror', model: fallbackModel });
for (const f of freeFallbackChain(providerKey, spec, primary)) attempts.push(f);
diff --git a/api/chat.js b/api/chat.js
index d381490f4..a8bbecaca 100644
--- a/api/chat.js
+++ b/api/chat.js
@@ -51,6 +51,13 @@ import {
PER_CALL_TIMEOUT_MS,
} from './_lib/chat-models.js';
import { computeContext, searchMemories } from './_lib/memory-store.js';
+import {
+ vertexClaudeEnabled,
+ vertexClaudePrimary,
+ vertexMessagesUrl,
+ vertexRequestHeaders,
+ toVertexBody,
+} from './_lib/vertex-claude.js';
import { z } from 'zod';
// Providers anonymous (unauthenticated) callers may use. Groq and OpenRouter
@@ -76,6 +83,15 @@ const PROVIDERS = {
url: ANTHROPIC_URL,
style: 'anthropic',
},
+ // Vertex-served Claude (GCP credits). No envKey — availability is gated by
+ // vertexClaudeEnabled(); the OAuth bearer token is minted per request in
+ // makeRoute (resolveHeaders). Serves the same Claude model ids as the
+ // first-party Anthropic lane, so the Anthropic SSE reader handles it verbatim.
+ // Injected into the try-order per flags by providerOrder(); absent when off.
+ vertex: {
+ defaultModel: DEFAULT_ANTHROPIC_MODEL,
+ style: 'vertex-anthropic',
+ },
openrouter: {
envKey: 'OPENROUTER_API_KEY',
defaultModel: DEFAULT_OPENROUTER_MODEL,
@@ -888,7 +904,10 @@ export default wrap(async (req, res) => {
tool: route.model,
latencyMs,
meta: {
- provider: route.name,
+ // `route.via` records the Vertex transport ('vertex-anthropic') distinctly
+ // from the first-party 'anthropic' provider so spend/usage reporting can
+ // attribute GCP-credit traffic; falls back to the provider name otherwise.
+ provider: route.via || route.name,
input_tokens: result.inputTokens,
output_tokens: result.outputTokens,
actions: governedActions.map((a) => a.type),
@@ -961,13 +980,31 @@ async function governActions(actions, userMessage) {
// ── Provider selection ───────────────────────────────────────────────────────
+// Effective provider try-order. Vertex-served Claude is injected per flags:
+// VERTEX_CLAUDE_PRIMARY → Vertex leads the whole ladder (before the free
+// lanes) — the platform's default brain becomes real Claude on GCP credits.
+// VERTEX_CLAUDE_ENABLED (not primary) → Vertex sits in the paid tier, just
+// ahead of first-party Anthropic (GCP credits before a paid Anthropic key).
+// Both off → DEFAULT_PROVIDER_ORDER is returned verbatim, so routing is
+// byte-identical to today.
+function providerOrder() {
+ if (vertexClaudePrimary()) return ['vertex', ...DEFAULT_PROVIDER_ORDER];
+ if (vertexClaudeEnabled()) {
+ const i = DEFAULT_PROVIDER_ORDER.indexOf('anthropic');
+ if (i === -1) return [...DEFAULT_PROVIDER_ORDER, 'vertex'];
+ return [...DEFAULT_PROVIDER_ORDER.slice(0, i), 'vertex', ...DEFAULT_PROVIDER_ORDER.slice(i)];
+ }
+ return DEFAULT_PROVIDER_ORDER;
+}
+
function pickProvider(requested, model, userKeys = {}, cooldown = new Map()) {
- // Fall back in DEFAULT_PROVIDER_ORDER (free providers first), not the
- // PROVIDERS object order — and never silently fall into watsonx/orchestrate,
- // which are explicit-selection-only providers.
+ // Fall back in providerOrder() (free providers first, Vertex injected per
+ // flags), not the PROVIDERS object order — and never silently fall into
+ // watsonx/orchestrate, which are explicit-selection-only providers.
+ const baseOrder = providerOrder();
const order = requested
- ? [requested, ...DEFAULT_PROVIDER_ORDER.filter((p) => p !== requested)]
- : DEFAULT_PROVIDER_ORDER;
+ ? [requested, ...baseOrder.filter((p) => p !== requested)]
+ : baseOrder;
// Two passes: first skip providers in a cooldown, then — only if that leaves
// nothing configured — ignore cooldowns so a request never 503s purely because
@@ -980,8 +1017,11 @@ function pickProvider(requested, model, userKeys = {}, cooldown = new Map()) {
const resolve = (skipCooldown) => {
for (const name of order) {
const cfg = PROVIDERS[name];
- const apiKey = userKeys[name] || process.env[cfg.envKey];
- if (!apiKey) continue;
+ // Vertex has no API key — availability is gated by vertexClaudeEnabled()
+ // and its bearer token is minted per request (makeRoute.resolveHeaders).
+ // A sentinel keeps the shared `usingHostKey`/route plumbing below intact.
+ const apiKey = name === 'vertex' ? 'vertex' : userKeys[name] || process.env[cfg.envKey];
+ if (name === 'vertex' ? !vertexClaudeEnabled() : !apiKey) continue;
if (skipCooldown && cooldown.has(name) && (name !== requested || cooldown.get(name) === 'auth'))
continue;
// watsonx needs both a key and a project/space scope to serve a model;
@@ -994,7 +1034,7 @@ function pickProvider(requested, model, userKeys = {}, cooldown = new Map()) {
// or NVIDIA request would 400 every chat.
const chosenModel =
(requested === name && model) ||
- (name === 'watsonx' || name === 'orchestrate'
+ (name === 'watsonx' || name === 'orchestrate' || name === 'vertex'
? cfg.defaultModel
: envPinnedModelFor(name) || cfg.defaultModel);
const route = makeRoute(name, cfg, apiKey, chosenModel);
@@ -1067,8 +1107,9 @@ function buildFallbackChain(primary, userKeys = {}, cooldown = new Map()) {
if (seen.has(key)) return;
if (!eligibleAsFallback(model)) return;
const cfg = PROVIDERS[name];
- const apiKey = userKeys[name] || process.env[cfg.envKey];
- if (!apiKey) return;
+ // Vertex is keyless — gated by vertexClaudeEnabled(); token minted per call.
+ const apiKey = name === 'vertex' ? 'vertex' : userKeys[name] || process.env[cfg.envKey];
+ if (name === 'vertex' ? !vertexClaudeEnabled() : !apiKey) return;
if (name === 'watsonx' && !watsonxConfig().configured) return;
if (name === 'orchestrate' && !orchestrateConfig().configured) return;
seen.add(key);
@@ -1079,11 +1120,12 @@ function buildFallbackChain(primary, userKeys = {}, cooldown = new Map()) {
// rate-limit without leaving the (already-selected, reliable) provider.
for (const m of FALLBACK_SIBLINGS[primary.name] || []) tryAdd(primary.name, m);
- // (b) Other providers, in reliability order, at their configured default.
- // Skip providers in a health cooldown so a globally-throttling provider isn't
- // re-hit on every request — that's the mechanism that turns one throttle
- // window into dozens of failures. The primary is always kept (position 0).
- for (const name of DEFAULT_PROVIDER_ORDER) {
+ // (b) Other providers, in reliability order (Vertex injected per flags), at
+ // their configured default. Skip providers in a health cooldown so a
+ // globally-throttling provider isn't re-hit on every request — that's the
+ // mechanism that turns one throttle window into dozens of failures. The
+ // primary is always kept (position 0).
+ for (const name of providerOrder()) {
if (name === primary.name) continue;
if (cooldown.has(name)) continue;
tryAdd(name, PROVIDERS[name].defaultModel);
@@ -1095,6 +1137,29 @@ function buildFallbackChain(primary, userKeys = {}, cooldown = new Map()) {
}
function makeRoute(name, cfg, apiKey, model) {
+ if (cfg.style === 'vertex-anthropic') {
+ // Vertex-served Claude: same Anthropic Messages wire format (so style is
+ // 'anthropic' below — streamAnthropic + tool parsing reused verbatim), but
+ // the model id lives in the URL, the body carries anthropic_version, and the
+ // bearer token is minted per request. `via` is the distinct telemetry label.
+ return {
+ name,
+ via: 'vertex-anthropic',
+ model,
+ url: vertexMessagesUrl(model, { stream: true }),
+ style: 'anthropic',
+ resolveHeaders: () => vertexRequestHeaders(),
+ buildPayload: ({ systemPrompt, history, maxTokens, includeTools = true }) =>
+ toVertexBody({
+ model,
+ max_tokens: maxTokens,
+ system: systemPrompt,
+ messages: history,
+ ...(includeTools ? { tools: ACTION_TOOLS } : {}),
+ stream: true,
+ }),
+ };
+ }
if (cfg.style === 'anthropic') {
return {
name,
diff --git a/api/llm/anthropic.js b/api/llm/anthropic.js
index 487c027b9..86112adea 100644
--- a/api/llm/anthropic.js
+++ b/api/llm/anthropic.js
@@ -545,7 +545,7 @@ export default wrap(async (req, res) => {
// provider. Terminal only when the whole chain is exhausted.
const status = upstream.status;
const errText = await upstream.text().catch(() => '');
- const provider = route.provider || 'anthropic';
+ const provider = usedVia || route.provider || 'anthropic';
log.warn('upstream_error', {
agentId,
model: usedModel,
@@ -594,6 +594,16 @@ export default wrap(async (req, res) => {
}
const route = usedRoute;
+ // Provider attribution for the spend ledger. `usedVia` distinguishes the
+ // Vertex transport ('vertex-anthropic') from first-party Anthropic so prompt
+ // 07's spend reporting can attribute GCP-credit traffic separately.
+ const via = usedVia || route.provider || 'anthropic';
+ const toolLabel =
+ via === 'vertex-anthropic'
+ ? 'vertex.messages'
+ : route.kind === 'anthropic'
+ ? 'anthropic.messages'
+ : `${route.provider}.chat`;
// Charge the monthly call quota only now that an upstream provider actually
// accepted the request — failed/rate-limited upstream attempts stay free.
@@ -658,17 +668,17 @@ export default wrap(async (req, res) => {
}
recordEvent({
kind: 'llm',
- tool: route.kind === 'anthropic' ? 'anthropic.messages' : `${route.provider}.chat`,
+ tool: toolLabel,
agentId,
bytes: 0,
latencyMs,
status: 'ok',
- provider: route.provider || 'anthropic',
+ provider: via,
model: usedModel,
inputTokens,
outputTokens,
costMicroUsd: costMicroUsd({
- provider: route.provider || 'anthropic',
+ provider: via,
model: usedModel,
input: inputTokens,
output: outputTokens,
@@ -721,17 +731,17 @@ export default wrap(async (req, res) => {
recordEvent({
kind: 'llm',
- tool: route.kind === 'anthropic' ? 'anthropic.messages' : `${route.provider}.chat`,
+ tool: toolLabel,
agentId,
bytes: upstreamText.length,
latencyMs,
status: 'ok',
- provider: route.provider || 'anthropic',
+ provider: via,
model: usedModel,
inputTokens,
outputTokens,
costMicroUsd: costMicroUsd({
- provider: route.provider || 'anthropic',
+ provider: via,
model: usedModel,
input: inputTokens,
output: outputTokens,
diff --git a/api/x402/vanity-premium.js b/api/x402/vanity-premium.js
new file mode 100644
index 000000000..16473b0ed
--- /dev/null
+++ b/api/x402/vanity-premium.js
@@ -0,0 +1,411 @@
+// GET /api/x402/vanity-premium
+// • no ?address → browse the premium inventory (available patterns +
+// difficulty-scaled prices). Public, no payment.
+// • ?address=<base58> → buy that pre-ground address via x402. On payment the
+// server reserves it, settles, and delivers the sealed
+// key ONCE, then destroys the ciphertext (delete-after-
+// reveal). The address is never served again.
+//
+// This is the SELL-FROM-STOCK tier: 4–5+ char brandable addresses ground ahead of
+// time on batch CPU (workers/vanity-grinder) and held encrypted in
+// vanity_inventory. It is separate from — and leaves untouched — the live $0.05
+// grind tier (/api/x402/vanity, the vanity_grinder MCP tool), which grinds a
+// fresh ≤3-char keypair per request.
+//
+// CUSTODY HONESTY (required, non-negotiable copy): the platform generated these
+// keys. Every listing and every delivery tells the buyer plainly to use a bought
+// address as a token MINT or to sweep assets to a self-generated wallet — never
+// as a high-value treasury. See CUSTODY_NOTICE below.
+//
+// SECURITY: single-use delivery is enforced server-side in
+// api/_lib/vanity-inventory-store.js (atomic status-guarded reveal). The
+// plaintext key is NEVER logged and NEVER written to the x402 idempotency cache
+// (the stored copy strips it, exactly like /api/x402/vanity). Optional
+// sealTo=<X25519 pubkey> delivers the key sealed (ECIES) so plaintext never even
+// appears in the response body.
+
+import { wrap, cors, error } from '../_lib/http.js';
+import {
+ send402,
+ verifyPayment,
+ settlePayment,
+ encodePaymentResponseHeader,
+ buildExactRequirements,
+ resolveResourceUrl,
+ buildBazaarSchema,
+} from '../_lib/x402-spec.js';
+import { env } from '../_lib/env.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import {
+ PAYMENT_IDENTIFIER,
+ checkCache,
+ extractIdFromHeader,
+ hashPaymentProof,
+ hashRequestPayload,
+ paymentIdentifierExtension,
+ storeResponse,
+ writeCachedResponse,
+ writeConflict,
+} from '../_lib/x402/payment-identifier-server.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
+import {
+ listAvailable,
+ getPublicItem,
+ inventoryStats,
+ reserveForPurchase,
+ peekReservedSecret,
+ reserveAndReveal,
+ isDbUnavailableError,
+} from '../_lib/vanity-inventory-store.js';
+import { openSecret } from '../_lib/vanity-vault.js';
+import {
+ sealToRecipient,
+ parseX25519Key,
+ SEALED_ENVELOPE_SCHEME,
+} from '../../src/solana/vanity/sealed-envelope.js';
+
+const ROUTE = '/api/x402/vanity-premium';
+const PUBLIC_ORIGIN = env.APP_ORIGIN || 'https://three.ws';
+
+// The required custody-honesty disclosure. Shipped in every listing response and
+// every delivery payload, and mirrored in the listing UI.
+export const CUSTODY_NOTICE =
+ 'This address and its key were GENERATED BY three.ws, not by you. For high-value use, ' +
+ 'treat it as a TOKEN MINT ADDRESS or sweep any assets to a wallet you generated yourself — ' +
+ 'do not use it as a long-term treasury. The key is delivered to you exactly once and its ' +
+ 'stored ciphertext is destroyed on delivery (delete-after-reveal), so three.ws cannot ' +
+ 'recover or re-deliver it afterward. Import it into a wallet immediately and, for anything ' +
+ 'of value, move funds to self-generated custody.';
+
+const ROUTE_DESCRIPTION =
+ 'three.ws Premium Vanity Inventory — buy a pre-ground Solana address with a long (4–5+ char) ' +
+ 'brandable prefix, delivered instantly from stock. Browse available patterns and prices with a ' +
+ 'plain GET; buy one with GET ?address=<base58> via x402 (USDC on Base or Solana). Price scales ' +
+ 'with grind difficulty ($1–$50). The key is delivered ONCE and its ciphertext is destroyed on ' +
+ 'delivery. Optional sealTo=<X25519 public key> seals the key to you so plaintext never appears ' +
+ 'in the response. CUSTODY: keys are platform-generated — use as a token mint or sweep to ' +
+ 'self-generated custody, not as a treasury.';
+
+// ── Listing (public, no payment) ─────────────────────────────────────────────
+async function handleListing(req, res) {
+ const q = req.query || {};
+ const prefix = typeof q.prefix === 'string' ? q.prefix.trim() : undefined;
+ const tier = typeof q.tier === 'string' ? q.tier.trim() : undefined;
+ const sort = ['rarity', 'price', 'new'].includes(q.sort) ? q.sort : 'rarity';
+ const limit = q.limit != null ? Number(q.limit) : 60;
+ const offset = q.offset != null ? Number(q.offset) : 0;
+
+ let items = [];
+ let stats = { available: 0, sold: 0, total: 0, minPrice: 0, maxPrice: 0, tiers: 0 };
+ try {
+ [items, stats] = await Promise.all([
+ listAvailable({ prefix, tier, sort, limit, offset }),
+ inventoryStats(),
+ ]);
+ } catch (err) {
+ if (isDbUnavailableError(err)) {
+ return error(res, 503, 'inventory_unavailable', 'inventory store temporarily unavailable — retry shortly');
+ }
+ return error(res, 500, 'internal_error', err.message);
+ }
+
+ res.setHeader('cache-control', 'public, max-age=15, stale-while-revalidate=60');
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.end(
+ JSON.stringify({
+ route: ROUTE,
+ custodyNotice: CUSTODY_NOTICE,
+ stats,
+ priceRange: { minUsd: stats.minPrice, maxUsd: stats.maxPrice },
+ count: items.length,
+ items: items.map((it) => ({
+ ...it,
+ buyUrl: `${PUBLIC_ORIGIN}${ROUTE}?address=${encodeURIComponent(it.address)}`,
+ explorerUrl: `https://solscan.io/account/${it.address}`,
+ })),
+ purchase: {
+ how: `GET ${ROUTE}?address=<base58> with an x402 payment (USDC on Base or Solana).`,
+ optionalSealTo: 'Add &sealTo=<X25519 public key> to receive the key sealed to you (plaintext never in the response).',
+ },
+ }),
+ );
+}
+
+function buildRequirements(resourceUrl, priceAtomics) {
+ return buildExactRequirements(resourceUrl, priceAtomics);
+}
+
+// Build the buyer-facing delivery payload from the decrypted secret bundle. The
+// bundle is the JSON workers/vanity-grinder sealed at grind time:
+// { format, address, secretKeyBase58, secretKey:[64], mnemonic?, ... }
+function shapeDelivery(item, bundle) {
+ return {
+ address: item.address,
+ prefix: item.prefix,
+ suffix: item.suffix,
+ ignoreCase: item.ignoreCase,
+ patternLabel: item.patternLabel,
+ format: bundle.format || item.format,
+ rarityTier: item.rarityTier,
+ rarityBits: item.rarityBits,
+ rarityScore: item.rarityScore,
+ difficultyAttempts: item.difficultyAttempts,
+ priceUsd: item.priceUsd,
+ network: 'solana',
+ explorerUrl: `https://solscan.io/account/${item.address}`,
+ secretKeyBase58: bundle.secretKeyBase58,
+ secretKey: bundle.secretKey,
+ mnemonic: bundle.mnemonic || null,
+ wordCount: bundle.wordCount || null,
+ derivationPath: bundle.derivationPath || null,
+ delivery: 'once',
+ custodyNotice: CUSTODY_NOTICE,
+ _secretWarning:
+ 'secretKeyBase58/secretKey (and mnemonic if present) are a REAL Solana key delivered ONCE. ' +
+ 'The stored ciphertext was destroyed on this delivery — three.ws cannot re-send it. Import it now.',
+ };
+}
+
+// Seal the secret bundle to the buyer's X25519 key so plaintext never lands in
+// the response body / any proxy log. Mirrors /api/x402/vanity's sealSecret.
+async function sealDelivery(delivery, sealTo) {
+ const bundle = {
+ format: delivery.format,
+ secretKeyBase58: delivery.secretKeyBase58,
+ secretKey: delivery.secretKey,
+ mnemonic: delivery.mnemonic,
+ wordCount: delivery.wordCount,
+ derivationPath: delivery.derivationPath,
+ };
+ const sealedSecret = await sealToRecipient(JSON.stringify(bundle), sealTo);
+ const { secretKeyBase58, secretKey, mnemonic, wordCount, derivationPath, ...clear } = delivery;
+ void secretKeyBase58; void secretKey; void mnemonic; void wordCount; void derivationPath;
+ return {
+ ...clear,
+ sealed: true,
+ sealedScheme: SEALED_ENVELOPE_SCHEME,
+ sealedContentType: 'application/json',
+ sealedFields: Object.keys(bundle),
+ sealedSecret,
+ };
+}
+
+function buildBazaar() {
+ return {
+ discoverable: true,
+ info: {
+ input: { type: 'http', method: 'GET', queryParams: { address: '<base58 from the listing>' } },
+ output: { type: 'json', example: { address: 'PUMPExample…', secretKeyBase58: '<delivered once>', delivery: 'once' } },
+ },
+ schema: buildBazaarSchema({
+ method: 'GET',
+ queryParamsSchema: {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ properties: {
+ address: { type: 'string', description: 'A Base58 address from the premium inventory listing.' },
+ sealTo: { type: 'string', description: 'Optional X25519 public key to seal the delivered key to.' },
+ },
+ },
+ outputSchema: {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['address', 'delivery', 'custodyNotice'],
+ properties: {
+ address: { type: 'string' },
+ secretKeyBase58: { type: 'string', description: 'Delivered once; ciphertext destroyed on delivery.' },
+ secretKey: { type: 'array', items: { type: 'integer' }, minItems: 64, maxItems: 64 },
+ delivery: { type: 'string', enum: ['once'] },
+ custodyNotice: { type: 'string' },
+ },
+ },
+ }),
+ };
+}
+
+// ── Purchase (x402) ──────────────────────────────────────────────────────────
+async function handlePurchase(req, res, address) {
+ let sealTo = null;
+ const q = req.query || {};
+ if (typeof q.sealTo === 'string' && q.sealTo.trim()) {
+ try {
+ sealTo = q.sealTo.trim();
+ parseX25519Key(sealTo, 'sealTo');
+ } catch (err) {
+ return error(res, err.status || 400, err.code || 'validation_error', err.message);
+ }
+ }
+
+ // Look up the item so we can price the 402 challenge for THIS exact address and
+ // reject an unknown/sold address before the buyer pays.
+ let item;
+ try {
+ item = await getPublicItem(address);
+ } catch (err) {
+ if (isDbUnavailableError(err)) return error(res, 503, 'inventory_unavailable', 'inventory store temporarily unavailable');
+ return error(res, 500, 'internal_error', err.message);
+ }
+ if (!item) return error(res, 404, 'not_found', `no inventory item for address ${address}`);
+ if (item.status !== 'available') {
+ return error(res, 409, 'unavailable', `address ${address} is ${item.status} — pick another from the listing`);
+ }
+
+ const resourceUrl = resolveResourceUrl(req, ROUTE);
+ const priceAtomics = Math.round(item.priceUsd * 1_000_000);
+ const requirements = buildRequirements(resourceUrl, priceAtomics);
+ const service = withService({
+ serviceName: 'three.ws Premium Vanity Inventory',
+ tags: ['solana', 'vanity', 'wallet', 'address', 'premium', 'inventory'],
+ });
+ const challenge = {
+ resourceUrl,
+ accepts: requirements,
+ description: `${ROUTE_DESCRIPTION} — buying ${item.patternLabel} (${item.rarityTier}) at $${item.priceUsd}.`,
+ bazaar: buildBazaar(),
+ extensions: { [PAYMENT_IDENTIFIER]: paymentIdentifierExtension(false) },
+ serviceName: service.serviceName,
+ tags: service.tags,
+ iconUrl: service.iconUrl,
+ item: { address: item.address, patternLabel: item.patternLabel, rarityTier: item.rarityTier, priceUsd: item.priceUsd },
+ custodyNotice: CUSTODY_NOTICE,
+ };
+
+ const paymentHeader = req.headers['x-payment'] || req.headers['payment-signature'];
+ if (!paymentHeader) return send402(res, challenge);
+
+ // Idempotency / replay: a retried payment returns the SAME (already-delivered)
+ // stored response — which by contract has the secret STRIPPED — instead of
+ // re-charging or double-delivering.
+ const clientPaymentId = extractIdFromHeader(paymentHeader);
+ const payloadHash = hashRequestPayload({ method: req.method, url: req.url, body: null });
+ const paymentHash = hashPaymentProof(paymentHeader);
+ const paymentId = clientPaymentId || (paymentHash ? `proof:${paymentHash}` : null);
+ if (!paymentId) return error(res, 400, 'payment_id_required', 'could not derive a payment id from the payment proof');
+
+ const lookup = await checkCache({ route: ROUTE, paymentId, payloadHash, paymentHash });
+ if (lookup.kind === 'hit') return writeCachedResponse(res, lookup.entry);
+ if (lookup.kind === 'conflict') {
+ return writeConflict(res, {
+ route: ROUTE,
+ attemptedHash: lookup.attemptedHash,
+ existingHash: lookup.existingHash,
+ reason: lookup.reason,
+ });
+ }
+
+ // 1) verify the payment.
+ let verified;
+ try {
+ verified = await verifyPayment({ paymentHeader, requirements });
+ } catch (err) {
+ if (err.status === 402) return send402(res, { ...challenge, error: err.message });
+ return error(res, err.status || 502, err.code || 'verify_failed', err.message);
+ }
+
+ // 2) reserve the item for THIS payment (atomic available→reserved). If someone
+ // bought it between the 402 and now, we bail BEFORE settling — buyer not charged.
+ const purchaser = verified?.payer || verified?.from || clientPaymentId || 'x402';
+ let reservation;
+ try {
+ reservation = await reserveForPurchase(address, { paymentId, purchaser });
+ } catch (err) {
+ return error(res, 502, 'reserve_failed', err.message);
+ }
+ if (!reservation.ok) {
+ const code = reservation.reason === 'not_found' ? 404 : 409;
+ return error(res, code, 'unavailable', `address ${address} could not be reserved (${reservation.reason}) — it may have just sold`);
+ }
+
+ // 3) prove we can DECRYPT before charging (KMS reachability etc.). Non-
+ // destructive peek — if this fails we have not settled and the ciphertext is
+ // intact, so the buyer is not charged and can retry.
+ let bundle;
+ try {
+ const peek = await peekReservedSecret(address, { paymentId });
+ if (!peek.ok) return error(res, 500, 'reveal_failed', `secret not retrievable (${peek.reason})`);
+ bundle = JSON.parse(await openSecret(peek.ciphertext, peek.scheme));
+ } catch (err) {
+ // Decrypt/KMS failure BEFORE settle: don't charge. Reservation is left in
+ // place (buyer's payment can be retried against the same reserved row).
+ return error(res, 502, 'decrypt_failed', 'could not decrypt the stored key — not charged, retry shortly');
+ }
+
+ // 4) settle the payment.
+ let settled;
+ try {
+ settled = await settlePayment({ verified });
+ } catch (err) {
+ return error(res, err.status || 502, err.code || 'settle_failed', err.message);
+ }
+
+ // 5) one-shot reveal: flip to revealed and DESTROY the ciphertext atomically.
+ // We already hold the plaintext from step 3, so even a transient error here
+ // doesn't cost the buyer the key — but a normal success is what destroys it.
+ try {
+ await reserveAndReveal(address, { paymentId });
+ } catch (err) {
+ // Non-fatal to delivery (buyer paid, we have the key) but log the state drift.
+ console.error('[vanity-premium] reveal/destroy after settle failed', err?.message || err);
+ }
+
+ // 6) deliver once.
+ let delivery = shapeDelivery(item, bundle);
+ if (sealTo) delivery = await sealDelivery(delivery, sealTo);
+
+ const paymentResponseHeader = encodePaymentResponseHeader(settled);
+ const contentType = 'application/json; charset=utf-8';
+ const body = JSON.stringify(delivery);
+ res.setHeader('x-payment-response', paymentResponseHeader);
+ res.setHeader('cache-control', 'no-store');
+ res.setHeader('content-type', contentType);
+ res.end(body);
+
+ // Cache a SECRET-FREE copy for replay: a retried payment gets the public
+ // metadata + an explicit "already delivered" marker, never the key again.
+ let storedBody = body;
+ if (!delivery.sealed) {
+ const { secretKeyBase58, secretKey, mnemonic, ...publicMeta } = delivery;
+ void secretKeyBase58; void secretKey; void mnemonic;
+ storedBody = JSON.stringify({
+ ...publicMeta,
+ secret_omitted_from_cache: true,
+ note: 'The purchased key was delivered once in the original response and the ciphertext was destroyed. It is never stored or re-served.',
+ });
+ }
+ try {
+ await storeResponse({
+ route: ROUTE,
+ paymentId,
+ payloadHash,
+ paymentHash,
+ status: 200,
+ body: storedBody,
+ contentType,
+ paymentResponseHeader,
+ });
+ } catch (err) {
+ console.error('[vanity-premium] idempotency store failed (non-fatal)', err?.message || err);
+ }
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (req.method !== 'GET') {
+ res.setHeader('allow', 'GET');
+ return error(res, 405, 'method_not_allowed', 'use GET');
+ }
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) {
+ res.setHeader('retry-after', String(rl.retryAfter ?? 1));
+ return error(res, 429, 'rate_limited', 'slow down');
+ }
+
+ const address = typeof req.query?.address === 'string' ? req.query.address.trim() : '';
+ if (!address) return handleListing(req, res);
+ // Cheap shape guard before any DB/payment work.
+ if (!/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(address)) {
+ return error(res, 400, 'validation_error', 'address must be a Base58 Solana public key');
+ }
+ return handlePurchase(req, res, address);
+});
diff --git a/docs/gcp-credits.md b/docs/gcp-credits.md
index 4aa7c214f..f9730b99f 100644
--- a/docs/gcp-credits.md
+++ b/docs/gcp-credits.md
@@ -20,7 +20,7 @@ they build on the foundation.
|---|---|
| **Project ID** | `aerial-vehicle-466722-p5` |
| Source of truth | Active `gcloud config` default in the dev container; the project the existing worker deploy flow and `api/_mcp3d/vertex-imagen.js` target. |
-| Active gcloud account | `[email protected]` |
+| Active gcloud account | The project owner's Google account (see team vault; not published here). |
| Known GCS buckets | `three-ws-model-weights`, `three-ws-avatar-reconstructions` |
| Default region | `us-central1` (Cloud Run + Imagen). Claude partner models use `global`. |
@@ -288,7 +288,7 @@ back out.
non-interactive execution"* — the org enforces a session-control reauth
interval. Owner runs, interactively:
```bash
- gcloud auth login # re-consent [email protected]
+ gcloud auth login # re-consent the project owner's Google account
gcloud auth application-default login # for Claude Code dev sessions
gcloud config set project aerial-vehicle-466722-p5
```
diff --git a/scripts/gcp/burn-report.mjs b/scripts/gcp/burn-report.mjs
new file mode 100755
index 000000000..3c4efa141
--- /dev/null
+++ b/scripts/gcp/burn-report.mjs
@@ -0,0 +1,169 @@
+#!/usr/bin/env node
+// scripts/gcp/burn-report.mjs — attributed GCP credit burn report.
+//
+// Reads the BigQuery billing export and prints, for the $100k credit program:
+// • credit consumed to date + gross cost
+// • spend by service (Vertex AI, Cloud Run, Compute, Storage, BigQuery, …)
+// • spend by lane label (vertex-claude | imagen | forge-gpu | vanity | unlabeled)
+// • trailing 7d / 30d daily burn rate
+// • projected exhaustion date vs the credit expiry date
+// • the under-utilization guard: >30% of the grant unused at expiry → scale up
+//
+// Usage:
+// node scripts/gcp/burn-report.mjs # human-readable
+// node scripts/gcp/burn-report.mjs --json # machine-readable (cron/dashboard)
+//
+// Config (env, also read from a local .env if present):
+// GOOGLE_CLOUD_PROJECT project holding the billing dataset
+// GCP_BILLING_DATASET dataset name (e.g. billing_export)
+// GCP_BILLING_TABLE full export table — OR —
+// GCP_BILLING_ACCOUNT_ID billing account id (derives the standard table name)
+// GCP_CREDIT_TOTAL_USD grant size, e.g. 100000 (enables projection)
+// GCP_CREDIT_EXPIRY ISO date the credits expire, e.g. 2027-07-01
+// GCP_CREDIT_TYPES optional override of the credit-type filter
+//
+// Auth: uses GCP_SERVICE_ACCOUNT_JSON if set; otherwise falls back to the local
+// `gcloud auth print-access-token` (so it works after `gcloud auth login`).
+
+import { readFileSync, existsSync } from 'node:fs';
+import { resolve, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { execFileSync } from 'node:child_process';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const REPO_ROOT = resolve(__dirname, '../..');
+
+// Minimal .env loader (no dependency) so a local `.env` supplies config without
+// exporting every var by hand. Only sets keys not already in the environment.
+function loadDotEnv() {
+ const envPath = resolve(REPO_ROOT, '.env');
+ if (!existsSync(envPath)) return;
+ for (const line of readFileSync(envPath, 'utf8').split('\n')) {
+ const m = line.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*)\s*$/);
+ if (!m) continue;
+ const key = m[1];
+ if (process.env[key] != null) continue;
+ let val = m[2];
+ if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
+ val = val.slice(1, -1);
+ }
+ process.env[key] = val;
+ }
+}
+
+loadDotEnv();
+
+const { buildBurnReport, BillingUnavailableError, PROGRAM_LANES, usd } = await import(
+ resolve(REPO_ROOT, 'api/_lib/gcp-billing.js')
+);
+const { getGcpAccessToken, gcpAuthConfigured } = await import(resolve(REPO_ROOT, 'api/_lib/gcp-auth.js'));
+
+// Token function: service account when present, else the local gcloud identity.
+async function localTokenFn() {
+ if (gcpAuthConfigured()) return getGcpAccessToken();
+ try {
+ return execFileSync('gcloud', ['auth', 'print-access-token'], { encoding: 'utf8' }).trim();
+ } catch (err) {
+ throw new BillingUnavailableError(
+ 'No GCP_SERVICE_ACCOUNT_JSON and `gcloud auth print-access-token` failed. Run `gcloud auth login` (and `gcloud config set project <id>`) first.',
+ err,
+ );
+ }
+}
+
+const asJson = process.argv.includes('--json');
+
+function fmtDate(iso) {
+ if (!iso) return '—';
+ return new Date(iso).toISOString().slice(0, 10);
+}
+
+function bar(pct, width = 24) {
+ const filled = Math.max(0, Math.min(width, Math.round((pct || 0) * width)));
+ return '█'.repeat(filled) + '░'.repeat(width - filled);
+}
+
+function printHuman(report) {
+ const { totals, projection: p, byService, byLane, burn, config } = report;
+ const lines = [];
+ lines.push('');
+ lines.push(' GCP CREDIT BURN REPORT');
+ lines.push(` ${config.project} · ${config.dataset}.${config.table} · ${report.generatedAt.slice(0, 19)}Z`);
+ lines.push(' ' + '─'.repeat(60));
+
+ lines.push('');
+ lines.push(' CREDIT CONSUMPTION');
+ lines.push(` Consumed to date ${usd(totals.creditUsed)}`);
+ if (config.creditTotalUsd) {
+ const pct = totals.creditUsed / config.creditTotalUsd;
+ lines.push(` Grant total ${usd(config.creditTotalUsd)}`);
+ lines.push(` Remaining ${usd(p.remainingUsd)}`);
+ lines.push(` Progress ${bar(pct)} ${(pct * 100).toFixed(1)}%`);
+ }
+ lines.push(` Gross cost (pre-credit) ${usd(totals.grossCost)}`);
+ lines.push(` Usage window ${fmtDate(totals.firstUsage)} → ${fmtDate(totals.lastUsage)}`);
+
+ lines.push('');
+ lines.push(' BURN RATE & RUNWAY');
+ lines.push(` Daily burn (7d) ${usd(burn.avg7dPerDay)}/day`);
+ lines.push(` Daily burn (30d) ${usd(burn.avg30dPerDay)}/day`);
+ if (p.daysRunway != null) {
+ lines.push(` Runway ${p.daysRunway === Infinity ? '∞ (idle)' : `~${Math.round(p.daysRunway)} days`}`);
+ lines.push(` Projected exhaust ${fmtDate(p.exhaustionDate)}`);
+ }
+ if (p.expiry) {
+ lines.push(` Credit expiry ${fmtDate(p.expiry)} (${Math.round(p.daysToExpiry)}d away)`);
+ }
+
+ const badge = { 'runaway': '🔴 RUNAWAY', 'underutilized': '🟡 UNDER-UTILIZED', 'on-track': '🟢 ON TRACK', 'idle': '⚪ IDLE', 'unknown': '⚪ UNKNOWN' }[p.status] || p.status;
+ lines.push('');
+ lines.push(` STATUS ${badge}`);
+ lines.push(` ${p.headline}`);
+ if (p.status === 'underutilized' || p.status === 'idle') {
+ lines.push(' Scale-up options:');
+ for (const [lane, meta] of Object.entries(PROGRAM_LANES)) {
+ if (lane === '(unlabeled)') continue;
+ lines.push(` · ${meta.label}: ${meta.scaleUp}`);
+ }
+ }
+
+ lines.push('');
+ lines.push(' SPEND BY SERVICE');
+ for (const s of byService.slice(0, 10)) {
+ lines.push(` ${s.service.padEnd(28)} ${usd(s.creditUsed).padStart(14)}`);
+ }
+
+ lines.push('');
+ lines.push(' SPEND BY LANE (attribution)');
+ if (byLane.length === 0) {
+ lines.push(' (no labeled spend yet — run scripts/gcp/label-resources.sh)');
+ }
+ for (const l of byLane.slice(0, 12)) {
+ const name = PROGRAM_LANES[l.lane]?.label || l.lane;
+ lines.push(` ${name.padEnd(24)} ${usd(l.creditUsed).padStart(14)} [program=${l.program}]`);
+ }
+ lines.push('');
+ console.log(lines.join('\n'));
+}
+
+try {
+ const report = await buildBurnReport({ tokenFn: localTokenFn });
+ if (asJson) {
+ console.log(JSON.stringify(report, null, 2));
+ } else {
+ printHuman(report);
+ }
+ // Non-zero exit on a runaway so a cron/CI wrapper can alert on the exit code.
+ process.exit(report.projection.status === 'runaway' ? 2 : 0);
+} catch (err) {
+ if (err instanceof BillingUnavailableError) {
+ if (asJson) {
+ console.log(JSON.stringify({ error: 'billing_unavailable', message: err.message }, null, 2));
+ } else {
+ console.error(`\n ⚠️ Burn report unavailable\n ${err.message}\n`);
+ }
+ process.exit(3);
+ }
+ console.error(err?.stack || err);
+ process.exit(1);
+}
diff --git a/scripts/gcp/claude-code-vertex.sh b/scripts/gcp/claude-code-vertex.sh
old mode 100644
new mode 100755
diff --git a/scripts/gcp/create-budgets.mjs b/scripts/gcp/create-budgets.mjs
new file mode 100755
index 000000000..96655963f
--- /dev/null
+++ b/scripts/gcp/create-budgets.mjs
@@ -0,0 +1,224 @@
+#!/usr/bin/env node
+// scripts/gcp/create-budgets.mjs — Cloud Billing budget alerts for the credit program.
+//
+// Creates (idempotently) the budgets that route runaway-spend warnings to the
+// team before a lane blows the grant:
+//
+// • Overall program budget = the full grant ($GCP_CREDIT_TOTAL_USD), with
+// threshold alerts at 25 / 50 / 75 / 90 / 100 %, measured on GROSS spend
+// (credits excluded) so it tracks consumption of the grant, not net $0.
+// • Per-service budgets for the big lanes (Vertex AI, Cloud Run, Compute
+// Engine) sized from GCP_SERVICE_BUDGETS or sensible defaults.
+//
+// All budgets publish to a single Pub/Sub topic; api/webhooks/gcp-budget-alert.js
+// turns each notification into a Telegram ops ping (the same bot the changelog
+// uses, but the PRIVATE ops chat — never the holders' channel).
+//
+// Idempotent: an existing budget with the same displayName is PATCHed, not
+// duplicated. Safe to re-run.
+//
+// Usage:
+// node scripts/gcp/create-budgets.mjs # DRY RUN — prints the plan
+// node scripts/gcp/create-budgets.mjs --apply # create/update the budgets
+//
+// Env:
+// GCP_BILLING_ACCOUNT_ID billing account (else first open account from gcloud)
+// GOOGLE_CLOUD_PROJECT project the budget is scoped to
+// GCP_CREDIT_TOTAL_USD grant size (overall budget amount), default 100000
+// GCP_BUDGET_PUBSUB_TOPIC topic name (default: gcp-budget-alerts)
+// GCP_SERVICE_BUDGETS optional JSON: { "Vertex AI": 50000, "Cloud Run": 20000 }
+//
+// Auth: GCP_SERVICE_ACCOUNT_JSON if present, else `gcloud auth print-access-token`.
+// Budget creation needs billing.budgets.create on the billing account — usually
+// an owner identity, so this is an operator-run script.
+
+import { resolve, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { execFileSync } from 'node:child_process';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const REPO_ROOT = resolve(__dirname, '../..');
+const { getGcpAccessToken, gcpAuthConfigured } = await import(resolve(REPO_ROOT, 'api/_lib/gcp-auth.js'));
+
+const APPLY = process.argv.includes('--apply');
+
+const DEFAULT_SERVICE_BUDGETS = { 'Vertex AI': 55000, 'Cloud Run': 20000, 'Compute Engine': 15000 };
+
+function fail(msg) {
+ console.error(`ERROR: ${msg}`);
+ process.exit(1);
+}
+
+async function token() {
+ if (gcpAuthConfigured()) return getGcpAccessToken();
+ try {
+ return execFileSync('gcloud', ['auth', 'print-access-token'], { encoding: 'utf8' }).trim();
+ } catch {
+ fail('no GCP_SERVICE_ACCOUNT_JSON and `gcloud auth print-access-token` failed. Run `gcloud auth login`.');
+ }
+}
+
+function gcloudValue(args) {
+ try {
+ return execFileSync('gcloud', args, { encoding: 'utf8' }).trim();
+ } catch {
+ return '';
+ }
+}
+
+async function gapi(tok, method, url, body) {
+ const res = await fetch(url, {
+ method,
+ headers: { authorization: `Bearer ${tok}`, 'content-type': 'application/json' },
+ body: body ? JSON.stringify(body) : undefined,
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ throw new Error(`${method} ${url.split('?')[0]} → ${res.status}: ${data?.error?.message || JSON.stringify(data)}`);
+ }
+ return data;
+}
+
+// ── Resolve config ──────────────────────────────────────────────────────────
+const project = process.env.GOOGLE_CLOUD_PROJECT || gcloudValue(['config', 'get-value', 'project']);
+if (!project) fail('no project. Set GOOGLE_CLOUD_PROJECT or `gcloud config set project <id>`.');
+
+let billingAccount = process.env.GCP_BILLING_ACCOUNT_ID || '';
+if (!billingAccount) {
+ // First OPEN billing account.
+ billingAccount = gcloudValue(['billing', 'accounts', 'list', '--filter=open=true', '--format=value(name)', '--limit=1'])
+ .replace(/^billingAccounts\//, '');
+}
+if (!billingAccount) fail('no billing account. Set GCP_BILLING_ACCOUNT_ID.');
+
+const projectNumber = gcloudValue(['projects', 'describe', project, '--format=value(projectNumber)']);
+if (!projectNumber) fail(`could not resolve project number for ${project} (check gcloud auth).`);
+
+const creditTotal = Number(process.env.GCP_CREDIT_TOTAL_USD || 100000);
+const topicName = process.env.GCP_BUDGET_PUBSUB_TOPIC || 'gcp-budget-alerts';
+const pubsubTopic = `projects/${project}/topics/${topicName}`;
+const serviceBudgets = process.env.GCP_SERVICE_BUDGETS
+ ? JSON.parse(process.env.GCP_SERVICE_BUDGETS)
+ : DEFAULT_SERVICE_BUDGETS;
+
+const THRESHOLDS = [0.25, 0.5, 0.75, 0.9, 1.0];
+const budgetsBase = `https://billingbudgets.googleapis.com/v1/billingAccounts/${billingAccount}/budgets`;
+
+console.log('── GCP credit-program budget alerts ────────────────────────────────');
+console.log(` billing account: ${billingAccount}`);
+console.log(` project: ${project} (#${projectNumber})`);
+console.log(` pub/sub topic: ${pubsubTopic}`);
+console.log(` overall budget: $${creditTotal.toLocaleString()} thresholds: ${THRESHOLDS.map((t) => t * 100 + '%').join(' ')}`);
+console.log(` per-service: ${Object.entries(serviceBudgets).map(([s, a]) => `${s}=$${Number(a).toLocaleString()}`).join(', ')}`);
+console.log(` mode: ${APPLY ? 'APPLY' : 'DRY RUN'}`);
+console.log('');
+
+const tok = await token();
+
+// ── Ensure the Pub/Sub topic exists ─────────────────────────────────────────
+function ensureTopic() {
+ const exists = gcloudValue(['pubsub', 'topics', 'describe', topicName, `--project=${project}`, '--format=value(name)']);
+ if (exists) {
+ console.log(`Pub/Sub topic ${topicName}: exists`);
+ return;
+ }
+ if (!APPLY) {
+ console.log(`Pub/Sub topic ${topicName}: would create`);
+ return;
+ }
+ execFileSync('gcloud', ['pubsub', 'topics', 'create', topicName, `--project=${project}`], { stdio: 'inherit' });
+ console.log(`Pub/Sub topic ${topicName}: created`);
+}
+ensureTopic();
+console.log('');
+
+// The billing-budgets service account must be allowed to publish to the topic.
+// (Owner runs this once; documented in docs/gcp-credits.md.)
+console.log('NOTE: grant the budgets publisher SA pub/sub access if not already:');
+console.log(` gcloud pubsub topics add-iam-policy-binding ${topicName} --project=${project} \\`);
+console.log(' --member=serviceAccount:billing-budgets.iam.gserviceaccount.com --role=roles/pubsub.publisher');
+console.log('');
+
+// ── Fetch existing budgets (for idempotent upsert) ──────────────────────────
+async function existingByName() {
+ const map = new Map();
+ let pageToken = '';
+ do {
+ const url = `${budgetsBase}?pageSize=100${pageToken ? `&pageToken=${pageToken}` : ''}`;
+ const data = await gapi(tok, 'GET', url);
+ for (const b of data.budgets || []) map.set(b.displayName, b.name);
+ pageToken = data.nextPageToken || '';
+ } while (pageToken);
+ return map;
+}
+
+function budgetBody({ displayName, amountUnits, services }) {
+ const filter = {
+ projects: [`projects/${projectNumber}`],
+ // GROSS spend against the grant size — credits excluded so the budget
+ // actually fires as the grant is consumed (net-of-credits would sit ~$0).
+ creditTypesTreatment: 'EXCLUDE_ALL_CREDITS',
+ };
+ if (services && services.length) filter.services = services;
+ return {
+ displayName,
+ budgetFilter: filter,
+ amount: { specifiedAmount: { currencyCode: 'USD', units: String(Math.round(amountUnits)) } },
+ thresholdRules: THRESHOLDS.map((t) => ({ thresholdPercent: t, spendBasis: 'CURRENT_SPEND' })),
+ notificationsRule: { pubsubTopic, schemaVersion: '1.0' },
+ };
+}
+
+async function upsertBudget(existing, body) {
+ const name = existing.get(body.displayName);
+ if (!APPLY) {
+ console.log(` ${name ? 'would PATCH' : 'would CREATE'} budget "${body.displayName}" ($${Number(body.amount.specifiedAmount.units).toLocaleString()})`);
+ return;
+ }
+ if (name) {
+ await gapi(tok, 'PATCH', `https://billingbudgets.googleapis.com/v1/${name}?updateMask=displayName,budgetFilter,amount,thresholdRules,notificationsRule`, body);
+ console.log(` updated budget "${body.displayName}"`);
+ } else {
+ const created = await gapi(tok, 'POST', budgetsBase, body);
+ console.log(` created budget "${body.displayName}" (${created.name})`);
+ }
+}
+
+// ── Resolve service ids from the billing catalog (for per-service budgets) ───
+async function resolveServiceIds(displayNames) {
+ const want = new Set(displayNames);
+ const found = new Map();
+ let pageToken = '';
+ do {
+ const url = `https://cloudbilling.googleapis.com/v1/services?pageSize=5000${pageToken ? `&pageToken=${pageToken}` : ''}`;
+ const data = await gapi(tok, 'GET', url);
+ for (const s of data.services || []) {
+ if (want.has(s.displayName)) found.set(s.displayName, s.name); // name = "services/XXXX-..."
+ }
+ pageToken = data.nextPageToken || '';
+ } while (pageToken && found.size < want.size);
+ return found;
+}
+
+try {
+ const existing = await existingByName();
+
+ console.log('Budgets:');
+ await upsertBudget(existing, budgetBody({ displayName: 'gcp-credits — program', amountUnits: creditTotal }));
+
+ const serviceIds = await resolveServiceIds(Object.keys(serviceBudgets));
+ for (const [svc, amount] of Object.entries(serviceBudgets)) {
+ const sid = serviceIds.get(svc);
+ if (!sid) {
+ console.log(` ⚠️ service "${svc}" not found in billing catalog — skipped`);
+ continue;
+ }
+ await upsertBudget(existing, budgetBody({ displayName: `gcp-credits — ${svc}`, amountUnits: amount, services: [sid] }));
+ }
+
+ console.log('');
+ console.log(`── Done.${APPLY ? '' : ' DRY RUN — re-run with --apply to create the budgets.'}`);
+ console.log(' Alert handler: api/webhooks/gcp-budget-alert.js (subscribe the topic to it)');
+} catch (err) {
+ fail(err?.message || String(err));
+}
diff --git a/scripts/gcp/emergency-stop.sh b/scripts/gcp/emergency-stop.sh
new file mode 100755
index 000000000..368d1346f
--- /dev/null
+++ b/scripts/gcp/emergency-stop.sh
@@ -0,0 +1,121 @@
+#!/usr/bin/env bash
+# scripts/gcp/emergency-stop.sh — burn kill-switch for the GCP credit program.
+#
+# When a lane runs away (a stuck min-instances GPU service, a runaway batch, or
+# Vertex Claude flipped to primary during an incident), this stops the bleed:
+#
+# 1. Drops EVERY Cloud Run service + job to --min-instances=0 so nothing keeps
+# a GPU warm while idle (the expensive failure: min-instances>0 on an L4
+# burns hundreds/day doing nothing).
+# 2. Prints the env flags to unset — the true no-deploy kill switches. Flipping
+# these in Vercel reverts each lane to its free/fallback provider instantly,
+# no redeploy required.
+# 3. Prints the documented spot/batch stop commands.
+#
+# This does NOT delete anything — services stay deployed and scale back up on the
+# next request. It only removes the always-warm floor and points you at the flags.
+#
+# Usage:
+# scripts/gcp/emergency-stop.sh # DRY RUN — shows what it would do
+# scripts/gcp/emergency-stop.sh --apply # actually drop min-instances to 0
+#
+# Env:
+# GOOGLE_CLOUD_PROJECT project id (falls back to gcloud config)
+
+set -euo pipefail
+
+APPLY=0
+[[ "${1:-}" == "--apply" ]] && APPLY=1
+
+PROJECT="${GOOGLE_CLOUD_PROJECT:-$(gcloud config get-value project 2>/dev/null || true)}"
+if [[ -z "$PROJECT" ]]; then
+ echo "ERROR: no project. Set GOOGLE_CLOUD_PROJECT or run 'gcloud config set project <id>'." >&2
+ exit 1
+fi
+
+echo "🛑 GCP CREDIT PROGRAM — EMERGENCY STOP"
+echo " project: $PROJECT mode: $([[ $APPLY -eq 1 ]] && echo APPLY || echo 'DRY RUN')"
+echo
+
+run() {
+ if [[ $APPLY -eq 1 ]]; then
+ echo " \$ $*"
+ "$@"
+ else
+ echo " would run: $*"
+ fi
+}
+
+# ── 1. Drop all Cloud Run min-instances to 0 ────────────────────────────────
+echo "1) Cloud Run services → --min-instances=0"
+SERVICES_TSV="$(gcloud run services list --project="$PROJECT" --format='value(metadata.name,region)' 2>/dev/null || true)"
+if [[ -z "$SERVICES_TSV" ]]; then
+ echo " (no services found — check gcloud auth / project)"
+else
+ while IFS=$'\t' read -r name region; do
+ [[ -z "$name" ]] && continue
+ echo " • $name ($region)"
+ run gcloud run services update "$name" \
+ --project="$PROJECT" --region="$region" --min-instances=0 --quiet
+ done <<< "$SERVICES_TSV"
+fi
+echo
+
+echo " Cloud Run jobs → cancel running executions"
+JOBS_TSV="$(gcloud run jobs list --project="$PROJECT" --format='value(metadata.name,region)' 2>/dev/null || true)"
+if [[ -z "$JOBS_TSV" ]]; then
+ echo " (no jobs)"
+else
+ while IFS=$'\t' read -r name region; do
+ [[ -z "$name" ]] && continue
+ # Cancel any in-flight executions for this job.
+ execs="$(gcloud run jobs executions list --job="$name" --project="$PROJECT" --region="$region" \
+ --filter='status.completionTime:*' --format='value(metadata.name)' 2>/dev/null | head -n 20 || true)"
+ if [[ -n "$execs" ]]; then
+ while read -r ex; do
+ [[ -z "$ex" ]] && continue
+ echo " • cancel execution $ex ($name)"
+ run gcloud run jobs executions cancel "$ex" --project="$PROJECT" --region="$region" --quiet
+ done <<< "$execs"
+ fi
+ done <<< "$JOBS_TSV"
+fi
+echo
+
+# ── 2. The real no-deploy kill switches (env flags) ─────────────────────────
+cat <<'FLAGS'
+2) FLIP THESE ENV FLAGS in Vercel to revert each paid lane to its free fallback
+ (no redeploy needed — the provider chains read them per-request):
+
+ Vertex Claude → vercel env rm VERTEX_CLAUDE_PRIMARY production
+ (unset ⇒ chat falls back to the free/BYOK lanes instantly)
+
+ Forge GPU fleet → vercel env rm FORGE_SELFHOST_PRIMARY production
+ (unset ⇒ forge routing stops preferring self-host GPU workers)
+
+ Imagen → vercel env add VERTEX_IMAGEN_ENABLED production (value: 0)
+ (0/false/off ⇒ text→image falls back to the free NIM FLUX lane)
+
+ After changing a flag, redeploy is NOT required for it to take effect on new
+ serverless invocations, but run `vercel deploy --prod` if you want the change
+ reflected immediately in already-warm lambdas.
+
+ For the FULL end-of-program teardown (revert every GCP lane by removing its
+ gate env var, credits expiring), use scripts/gcp/revert-to-free.sh instead —
+ this script is the fast "stop the bleed now" runaway switch.
+FLAGS
+echo
+
+# ── 3. Spot / batch stop ────────────────────────────────────────────────────
+cat <<FLAGS
+3) SPOT / BATCH compute (seeding runs, vanity grinder on GCE) — stop instances:
+
+ gcloud compute instances list --project=$PROJECT
+ gcloud compute instances stop <INSTANCE> --zone=<ZONE> --project=$PROJECT
+ # or delete a managed instance group's targets:
+ gcloud compute instance-groups managed resize <MIG> --size=0 --zone=<ZONE> --project=$PROJECT
+FLAGS
+echo
+
+echo "── Done. Verify the bleed stopped: node scripts/gcp/burn-report.mjs"
+[[ $APPLY -eq 0 ]] && echo "── This was a DRY RUN. Re-run with --apply to actually drop min-instances."
diff --git a/scripts/gcp/label-resources.sh b/scripts/gcp/label-resources.sh
new file mode 100755
index 000000000..e9eb78ea3
--- /dev/null
+++ b/scripts/gcp/label-resources.sh
@@ -0,0 +1,116 @@
+#!/usr/bin/env bash
+# scripts/gcp/label-resources.sh — attribution labels for the $100k credit program.
+#
+# Every credit-consuming resource created in prompts 02–06 must carry a
+# consistent label so the burn report (scripts/gcp/burn-report.mjs) can split
+# spend by lane. This script discovers the fleet and (retro-)labels it:
+#
+# program=gcp-credits on every program resource
+# lane=forge-gpu on the Cloud Run GPU model workers
+# lane=<forge-gpu|...> overridable per service (see LANE_OVERRIDES below)
+#
+# Vertex Claude + Imagen spend is API-billed (no Cloud Run service to label) and
+# is attributed by service.description in the burn report instead; the vanity
+# lane, when it runs as a Cloud Run job / GCE VM, is labeled here too.
+#
+# Labels are additive (--update-labels), so this is safe to re-run and safe to
+# run against a partially-labeled fleet.
+#
+# Usage:
+# scripts/gcp/label-resources.sh # DRY RUN — prints what it would do
+# scripts/gcp/label-resources.sh --apply # actually apply the labels
+#
+# Env:
+# GOOGLE_CLOUD_PROJECT project id (falls back to `gcloud config get-value project`)
+# GCP_CREDIT_PROGRAM program label value (default: gcp-credits)
+
+set -euo pipefail
+
+APPLY=0
+[[ "${1:-}" == "--apply" ]] && APPLY=1
+
+PROJECT="${GOOGLE_CLOUD_PROJECT:-$(gcloud config get-value project 2>/dev/null || true)}"
+PROGRAM="${GCP_CREDIT_PROGRAM:-gcp-credits}"
+
+if [[ -z "$PROJECT" ]]; then
+ echo "ERROR: no project. Set GOOGLE_CLOUD_PROJECT or run 'gcloud config set project <id>'." >&2
+ exit 1
+fi
+
+# Per-service lane overrides. Anything not listed defaults to forge-gpu (the
+# whole Cloud Run fleet in this project is the GPU model lane; the API runs on
+# Vercel, not Cloud Run). Format: "service-name=lane".
+declare -A LANE_OVERRIDES=(
+ # ["vanity-grinder"]="vanity"
+)
+
+# GCS buckets that back the credit program (model weights, reconstruction output).
+BUCKETS=(
+ "three-ws-model-weights"
+ "three-ws-avatar-reconstructions"
+ "three-ws-longcat-weights"
+ "three-ws-avatar-videos"
+)
+
+echo "── GCP credit-program labeler ──────────────────────────────────────"
+echo " project: $PROJECT program=$PROGRAM mode: $([[ $APPLY -eq 1 ]] && echo APPLY || echo 'DRY RUN')"
+echo
+
+run() {
+ if [[ $APPLY -eq 1 ]]; then
+ echo " \$ $*"
+ "$@"
+ else
+ echo " would run: $*"
+ fi
+}
+
+# ── Cloud Run services ──────────────────────────────────────────────────────
+echo "Cloud Run services:"
+SERVICES_TSV="$(gcloud run services list --project="$PROJECT" --format='value(metadata.name,metadata.labels.lane,region)' 2>/dev/null || true)"
+if [[ -z "$SERVICES_TSV" ]]; then
+ echo " (none found — deploy prompt 04's workers first, or check gcloud auth)"
+else
+ while IFS=$'\t' read -r name existing_lane region; do
+ [[ -z "$name" ]] && continue
+ lane="${LANE_OVERRIDES[$name]:-forge-gpu}"
+ echo " • $name (region=$region, current lane=${existing_lane:-none}) → lane=$lane"
+ run gcloud run services update "$name" \
+ --project="$PROJECT" --region="$region" \
+ --update-labels="program=${PROGRAM},lane=${lane}" --quiet
+ done <<< "$SERVICES_TSV"
+fi
+echo
+
+# ── Cloud Run jobs (batch: vanity, seeding) ─────────────────────────────────
+echo "Cloud Run jobs:"
+JOBS_TSV="$(gcloud run jobs list --project="$PROJECT" --format='value(metadata.name,region)' 2>/dev/null || true)"
+if [[ -z "$JOBS_TSV" ]]; then
+ echo " (none)"
+else
+ while IFS=$'\t' read -r name region; do
+ [[ -z "$name" ]] && continue
+ lane="${LANE_OVERRIDES[$name]:-forge-gpu}"
+ echo " • $name (job, region=$region) → lane=$lane"
+ run gcloud run jobs update "$name" \
+ --project="$PROJECT" --region="$region" \
+ --update-labels="program=${PROGRAM},lane=${lane}" --quiet
+ done <<< "$JOBS_TSV"
+fi
+echo
+
+# ── GCS buckets ─────────────────────────────────────────────────────────────
+echo "GCS buckets:"
+for b in "${BUCKETS[@]}"; do
+ if gcloud storage buckets describe "gs://$b" --project="$PROJECT" >/dev/null 2>&1; then
+ echo " • gs://$b → lane=forge-gpu"
+ run gcloud storage buckets update "gs://$b" \
+ --update-labels="program=${PROGRAM},lane=forge-gpu"
+ else
+ echo " • gs://$b (absent — skipped)"
+ fi
+done
+echo
+
+echo "── Done. Verify attribution: node scripts/gcp/burn-report.mjs"
+[[ $APPLY -eq 0 ]] && echo "── This was a DRY RUN. Re-run with --apply to write the labels."
diff --git a/scripts/gcp/revert-to-free.sh b/scripts/gcp/revert-to-free.sh
index 65563d7d5..2ed410cb4 100755
--- a/scripts/gcp/revert-to-free.sh
+++ b/scripts/gcp/revert-to-free.sh
@@ -16,21 +16,30 @@
# Avatar reconstruct/rerig GCP_RECONSTRUCTION_URL + _KEY Replicate, then HF Spaces
# Editing (rembg/tex/seg) GCP_REMBG/TEXTURE/SEGMENT_URL in-lane fallbacks / feature off
# Imagen text→image GOOGLE_CLOUD_PROJECT (+SA JSON) free NIM FLUX, then Replicate
+# Vertex Claude (chat/LLM) VERTEX_CLAUDE_ENABLED / _PRIMARY Groq→OpenRouter→NVIDIA→paid
#
# Because every lane is env-gated (see api/_lib/forge-tiers.js backendIsConfigured,
# api/_lib/regen-provider.js resolveProviderName, api/_mcp3d/vertex-imagen.js
-# isConfigured), removing the gate var is a complete, code-free revert: the
-# resolver stops selecting the GCP lane and the next configured provider serves
-# the request. Proven at the code level by tests/api/gcp-revert.test.js.
+# isConfigured, api/_lib/vertex-claude.js vertexClaudeEnabled), removing the gate
+# var is a complete, code-free revert: the resolver stops selecting the GCP lane
+# and the next configured provider serves the request. Proven at the code level by
+# tests/api/gcp-revert.test.js.
+#
+# Sibling: scripts/gcp/emergency-stop.sh is the PANIC button (runaway cost, right
+# now) — it also drops Cloud Run to min-instances=0 and prints the env removals.
+# THIS script is the planned end-of-program revert: same env-flip mechanism, plus
+# the pre-flight fallback checks and the full keep/kill context in docs/gcp-credits.md.
#
# This script does NOT touch Vercel for you (it can't safely read your token from
# here). It prints the exact `vercel env rm` commands to paste, and — with
# --apply and gcloud authed — drops every Cloud Run worker to min-instances=0 so
# no warm GPU bills after the credits die.
#
-# The LLM lane (Vertex Claude, prompt 02) was never shipped — the chat/agent
-# chain in api/_lib/llm.js runs Groq → OpenRouter → NVIDIA → Anthropic/OpenAI and
-# has no Vertex provider. There is nothing to revert there; it is a no-op below.
+# The Vertex Claude chat lane (api/_lib/vertex-claude.js, wired into api/chat.js)
+# reverts by unsetting VERTEX_CLAUDE_ENABLED / VERTEX_CLAUDE_PRIMARY: the chat
+# provider ladder then drops Vertex and leads with the free lanes again. Leaving
+# GOOGLE_CLOUD_PROJECT set is harmless once the flags are off — the flag, not the
+# project var, is what injects Vertex into the chat chain.
#
# Usage:
# scripts/gcp/revert-to-free.sh # dry-run: print the plan, change nothing
@@ -82,6 +91,9 @@ echo
FORGE_VARS=(MODEL_TRELLIS_URL GCP_HUNYUAN3D_URL GCP_TRIPOSG_URL GCP_REMESH_URL GCP_RECONSTRUCTION_URL GCP_RECONSTRUCTION_KEY)
EDIT_VARS=(GCP_REMBG_URL GCP_TEXTURE_URL GCP_SEGMENT_URL)
IMAGEN_VARS=(GOOGLE_CLOUD_PROJECT GOOGLE_CLOUD_LOCATION VERTEX_IMAGEN_MODEL VERTEX_IMAGEN_EDIT_MODEL GCP_SERVICE_ACCOUNT_JSON)
+# The chat/LLM lane reverts by flag alone — turning these off drops Vertex from the
+# chat provider ladder (api/chat.js providerOrder) without touching GOOGLE_CLOUD_PROJECT.
+LLM_VARS=(VERTEX_CLAUDE_PRIMARY VERTEX_CLAUDE_ENABLED)
# ── Step 1: pre-flight — will anything be stranded with no fallback? ───────────
bold "1) Pre-flight: confirm each lane has a live fallback before you pull the gate"
@@ -132,8 +144,10 @@ print_rm() {
}
print_rm "Forge GPU self-host lanes (image→3D, sketch, remesh, avatar reconstruct)" "${FORGE_VARS[@]}"
print_rm "Editing workers (rembg / texture / segment)" "${EDIT_VARS[@]}"
+print_rm "Vertex Claude chat/LLM lane (reverts to free Groq→OpenRouter→NVIDIA, paid backstop)" "${LLM_VARS[@]}"
print_rm "Vertex Imagen text→image (reverts to free NIM FLUX, then Replicate)" "${IMAGEN_VARS[@]}"
-dim " Vertex Claude LLM lane: NOT SHIPPED — nothing to remove (chain is Groq→OpenRouter→NVIDIA→paid)."
+dim " Note: GOOGLE_CLOUD_PROJECT gates BOTH Imagen and Vertex-Claude config; removing it above"
+dim " fully de-configures Vertex. The two VERTEX_CLAUDE_* flags alone are enough to revert chat."
echo
dim " After removing, redeploy so the functions pick up the new env:"
dim " vercel --prod"
diff --git a/specs/okx-agent-payments.md b/specs/okx-agent-payments.md
new file mode 100644
index 000000000..5956ad5a2
--- /dev/null
+++ b/specs/okx-agent-payments.md
@@ -0,0 +1,294 @@
+# OKX Agent Payments Protocol — Seller-Side Contract (three.ws A2MCP)
+
+> **Status:** Research complete. Green-light for Work Order 02.
+> **Chain:** X Layer mainnet, `eip155:196` (chainId 196).
+> **Our payTo:** `0x75d00a2713565171f33216e5aa2a375e076ecf69` (agent #2632 owner wallet).
+> **Fee token:** USD₮0 `0x779Ded0c9e1022225f8E0630b35a9b54bE713736` (6 decimals, EIP-3009).
+> **Why this exists:** Our A2MCP endpoint ([api/mcp-3d.js](../api/mcp-3d.js)) emits x402 accepts for Solana/Base/BSC/Arbitrum only — never `eip155:196`, never the OKX fee token, never the `PAYMENT-SIGNATURE`/`aggr_deferred` OKX dialect. That is the exact reason agent #2632 was rejected on 2026-07-04. This spec pins the seller-side contract from **primary sources** so 02 can implement it without opening a browser.
+
+This is a load-bearing contract in the sense of `specs/README.md`: 02's implementation is validated against §1 (the challenge shape) and §4 (the gap list). Every claim carries a citation. Anything not verifiable from a primary source is marked **UNRESOLVED**.
+
+**Primary sources used (all cited inline below):**
+
+- **SDK-REPO** — `github.com/okx/payments`, the official **OKX Payments SDK** (Apache-2.0, cloned & read 2026-07-06). Paths below are relative to `typescript/bu-payments/`.
+- **WIRE-OKLINK** — live 402 + paid replay from **Onchain Data Explorer** (agent #2023, 174 sales, approvalStatus 4), endpoint `https://www.oklink.com/api/v5/explorer/mcp/x402/get_chain_info`. Captured 2026-07-06 (Appendix A).
+- **WIRE-COINANK** — live 402 from **CoinAnk OpenAPI** (agent #2013, 818 sales, approvalStatus 4), `https://open-api.coinank.com/api/etf/getUsBtcEtf` (Appendix B).
+- **WIRE-OKB** — live 402 from **OKB Monitoring** (agent #3837, approvalStatus 4), `https://okb.swaper.money/x402/digest` (Appendix C).
+- **PAY-LEG1/2** — real `onchainos payment pay` signing + paid replay from our own wallet (Appendix D).
+- **SKILL** — repo client-side skill `.claude/skills/okx-agent-payments-protocol/` (buyer constraints).
+
+---
+
+## 1. Seller contract — what OUR endpoint must emit
+
+### 1.1 The 402 challenge (concrete, with our values)
+
+On an unpaid request to a paid A2MCP resource, respond `HTTP 402` with:
+
+- Header **`PAYMENT-REQUIRED`**: base64 of the JSON body below.
+- Header **`Access-Control-Expose-Headers: PAYMENT-REQUIRED`** (so browser/agent clients behind CORS can read it — WIRE-OKLINK sets this).
+- Body: the same JSON (SDK emits the challenge in both the header and, on the resource server, the body).
+
+```json
+{
+ "x402Version": 2,
+ "resource": {
+ "url": "https://three.ws/api/mcp-3d",
+ "mimeType": "application/json"
+ },
+ "accepts": [
+ {
+ "scheme": "exact",
+ "network": "eip155:196",
+ "amount": "15",
+ "payTo": "0x75d00a2713565171f33216e5aa2a375e076ecf69",
+ "maxTimeoutSeconds": 86400,
+ "asset": "0x779ded0c9e1022225f8e0630b35a9b54be713736",
+ "extra": { "name": "USD₮0", "version": "1", "symbol": "USDT", "transferMethod": "eip3009" }
+ },
+ {
+ "scheme": "aggr_deferred",
+ "network": "eip155:196",
+ "amount": "15",
+ "payTo": "0x75d00a2713565171f33216e5aa2a375e076ecf69",
+ "maxTimeoutSeconds": 86400,
+ "asset": "0x779ded0c9e1022225f8e0630b35a9b54be713736",
+ "extra": { "name": "USD₮0", "version": "1", "symbol": "USDT", "transferMethod": "eip3009" }
+ }
+ ]
+}
+```
+
+`amount` is atomic units of USD₮0 (6 decimals). `"15"` = $0.000015 (the exact price Onchain Data Explorer charges for `get_chain_info`; WIRE-OKLINK). Set per-service in 03.
+
+**Field requirement matrix** (present in ALL three approved sellers ⇒ required; present in some ⇒ optional). Diff of WIRE-OKLINK ∩ WIRE-COINANK ∩ WIRE-OKB:
+
+| Field | Required? | Value / notes |
+|---|---|---|
+| `x402Version` | ✅ required | `2` (OKB uses `1` — legacy still accepted, but emit `2`; SDK hardcodes `2`, SDK-REPO `facilitator/OKXFacilitatorClient.ts:98`). |
+| `accepts[].scheme` | ✅ required | `"exact"` present in all three. `"aggr_deferred"` in 2/3 (optional). `"upto"` in **none**. |
+| `accepts[].network` | ✅ required | `"eip155:196"` in all three. **This is the field we don't emit — root cause of rejection.** |
+| `accepts[].asset` | ✅ required | `0x779ded…713736` (USD₮0) in all three. |
+| `accepts[].payTo` | ✅ required | Seller receiving address. Ours: `0x75d00a2713565171f33216e5aa2a375e076ecf69`. |
+| `accepts[].amount` (v2) / `maxAmountRequired` (v1) | ✅ required | Atomic USD₮0 string. |
+| `accepts[].maxTimeoutSeconds` | ✅ required | Seen `86400` / `300` / `300`. Use `86400` (oklink) or any ≥ a few minutes; it bounds `validBefore`. |
+| `accepts[].extra.name` | ✅ required (EIP-3009) | `"USD₮0"` — the token's **EIP-712 domain name**. Must byte-match the on-chain domain separator or the facilitator computes the wrong hash and rejects the signature. |
+| `accepts[].extra.version` | ✅ required (EIP-3009) | `"1"` — EIP-712 domain version. |
+| `accepts[].extra.symbol` | ⬜ optional | `"USDT"`. Only WIRE-OKLINK emits it. Display hint. |
+| `accepts[].extra.transferMethod` | ⬜ optional | `"eip3009"`. Only WIRE-OKLINK emits it. Default is EIP-3009 when absent (SDK `assetTransferMethod` only set for permit2 tokens; `defaultAssets.ts`). |
+| `accepts[].extra.decimals` | ⬜ optional | `6`. Only WIRE-OKB (v1) puts it in `extra`; v2 sellers omit it (decimals come from the default-asset registry). |
+| `resource.url` | ✅ required | Absolute URL of the paid resource. |
+| `resource.mimeType` | ⬜ optional | `"application/json"` (WIRE-OKLINK). WIRE-COINANK omits it. |
+| top-level `error` | conditional | Added only on a rejected paid replay (e.g. `"insufficient_balance"`); the full `accepts` is re-emitted so the client can retry. See PAY-LEG2 / Appendix D. |
+
+Notes vs. our current Bazaar-heavy body: OKX sellers emit **no** `extensions.bazaar`, **no** `builder-code`, **no** `offer-receipt`, **no** per-accept `description`. The OKX validator does not require them; keep the body minimal for the `eip155:196` accepts.
+
+### 1.2 Verify → do-work → settle (seller → OKX facilitator)
+
+On a request that carries the payment header, the seller calls the **OKX facilitator** (HMAC-authed, see §Q4) and only does the work after `/verify` passes:
+
+```
+1. header = req.header("PAYMENT-SIGNATURE") // NOT X-PAYMENT (OKX divergence)
+2. paymentPayload = JSON.parse(base64url_decode(header))
+3. requirement = the accepts[] entry matching paymentPayload.accepted (network+scheme+asset)
+4. POST https://web3.okx.com/api/v6/pay/x402/verify
+ headers: OK-ACCESS-KEY / OK-ACCESS-SIGN / OK-ACCESS-TIMESTAMP / OK-ACCESS-PASSPHRASE
+ body: { x402Version: 2, paymentPayload, paymentRequirements: requirement }
+ → { code, msg, data: { isValid, invalidReason?, invalidMessage?, payer? } }
+ If !isValid → re-emit the 402 with top-level error = invalidReason (see PAY-LEG2).
+5. Run the tool / produce the resource body.
+6. POST https://web3.okx.com/api/v6/pay/x402/settle (same auth + body, optional syncSettle)
+ → { code, msg, data: { success, status, transaction, network, payer, amount? } }
+7. Attach header PAYMENT-RESPONSE = base64(JSON.stringify(settleResponse)) to the 200.
+```
+
+Source: SDK-REPO `app-x402-core/src/facilitator/OKXFacilitatorClient.ts` (verify L92-115, settle L124-150), `app-x402-core/src/http/x402HTTPResourceServer.ts` (header read L1560, `PAYMENT-RESPONSE` emit L1663-1676), `app-x402-core/src/http/index.ts` (base64 codecs L17-80). Live-confirmed by PAY-LEG1/2.
+
+### 1.3 The paid-replay header (buyer → seller)
+
+The buyer replays the original request adding **`PAYMENT-SIGNATURE: <base64 PaymentPayload>`**. The decoded payload we must accept (from PAY-LEG1, our real signature):
+
+```json
+{
+ "x402Version": 2,
+ "resource": { "mimeType": "application/json", "url": "https://www.oklink.com/api/v5/explorer/mcp/x402/get_chain_info" },
+ "accepted": {
+ "scheme": "exact", "network": "eip155:196", "amount": "15",
+ "asset": "0x779ded0c9e1022225f8e0630b35a9b54be713736",
+ "payTo": "0xa7e37604ebab94408159e405033a455f820fd987",
+ "maxTimeoutSeconds": 86400,
+ "extra": { "name": "USD₮0", "symbol": "USDT", "transferMethod": "eip3009", "version": "1" }
+ },
+ "payload": {
+ "authorization": {
+ "from": "0x75d00a2713565171f33216e5aa2a375e076ecf69",
+ "to": "0xa7e37604ebab94408159e405033a455f820fd987",
+ "value": "15", "validAfter": "0", "validBefore": "1783455107",
+ "nonce": "0x20ea1abd9c8d9ee9c4e0a861071475061ffebf07076eec8fa6d963f2a8957253"
+ },
+ "signature": "0x88c64c51…3d37891c"
+ }
+}
+```
+
+The seller passes `payload` + the matching `accepted` (as `paymentRequirements`) straight to the facilitator — it does not re-derive the EIP-712 hash itself. Header name is read case-insensitively (`payment-signature` OR `PAYMENT-SIGNATURE`; SDK `x402HTTPResourceServer.ts:1560`).
+
+### 1.4 Settlement receipt (seller → buyer)
+
+On success attach `PAYMENT-RESPONSE` (base64 of the `SettleResponse`). Shape (SDK `types/facilitator.ts:26-38`):
+
+```json
+{ "success": true, "status": "success", "transaction": "0x…", "network": "eip155:196", "payer": "0x75d0…cf69", "amount": "15" }
+```
+
+- `status: "success"` when settled with `syncSettle:true` (facilitator waited for on-chain confirmation).
+- `status: "pending"` (default, `syncSettle` unset/false) — facilitator accepted, tx settles async; seller may confirm later via `GET /api/v6/pay/x402/settle/status?txHash=…`.
+- `status: "timeout"` — on-chain confirmation timed out.
+
+---
+
+## 2. Answer table — the 8 questions
+
+| # | Question | Answer | Citation |
+|---|---|---|---|
+| 1 | Exact 402 challenge shape the validator accepts | Header **`PAYMENT-REQUIRED`** = base64 JSON `{x402Version:2, resource:{url,mimeType?}, accepts:[…]}`. Per-`accepts` **required**: `scheme, network:"eip155:196", asset(USD₮0), payTo, amount, maxTimeoutSeconds, extra.name, extra.version`. `extra.symbol`/`extra.transferMethod`/`resource.mimeType` optional. No Bazaar/extensions needed. Full matrix §1.1. | WIRE-OKLINK/COINANK/OKB (Appx A-C); SDK `http/index.ts:40`, `x402HTTPResourceServer.ts:1101` |
+| 2 | Which scheme(s) mandatory for listing | **`exact` (EIP-3009) is the one required scheme** — present in all 3 approved sellers. `aggr_deferred` is offered by 2/3 (optional, recommended as a second accept). **`upto` is offered by none** and is NOT needed for approval. `upto` (if ever added) requires `extra.facilitatorAddress`, which the seller must fetch from the facilitator's `/supported.signers` — it cannot be hardcoded. | WIRE-* diff; SDK `upto/facilitator/scheme.ts:29-39`, `upto/client/permit2.ts:32-38`; SKILL `accepts-schemes.md` |
+| 3 | Fee token `0x779Ded…713736` on X Layer | **Symbol `USDT`, name `USD₮0`, decimals `6`, EIP-3009 capable** (supports `transferWithAuthorization`). Community-recognized. Not permit2-only — the whole rail uses EIP-3009. | `onchainos token info` (Appx E); SDK `defaultAssets.ts` `DEFAULT_STABLECOINS["eip155:196"]` comment "(EIP-3009)"; live EIP-3009 sign accepted structurally by facilitator (PAY-LEG1/2) |
+| 4 | OKX facilitator verify/settle URLs, shapes, auth | Base `https://web3.okx.com`. **`POST /api/v6/pay/x402/verify`**, **`POST /api/v6/pay/x402/settle`**, `GET /api/v6/pay/x402/supported`, `GET /api/v6/pay/x402/settle/status?txHash=`. Body `{x402Version:2, paymentPayload, paymentRequirements[, syncSettle]}`. Responses wrapped `{code,msg,data}`. **Auth = OKX REST HMAC-SHA256**: headers `OK-ACCESS-KEY`, `OK-ACCESS-SIGN`(=base64(HMAC-SHA256(secret, timestamp+method+path+body))), `OK-ACCESS-TIMESTAMP`(ISO-8601), `OK-ACCESS-PASSPHRASE`. **⇒ We need an OKX API key/secret/passphrase.** `upto`'s `extra.facilitatorAddress` = `supported.signers[family][0]` via `getExtra()`. | SDK `facilitator/OKXFacilitatorClient.ts` (all endpoints + `createHeaders` L60-76); `upto/facilitator/scheme.ts:39` |
+| 5 | The official OKX Payment SDK | **`github.com/okx/payments` = "OKX Payments SDK", Apache-2.0.** Published on npm: `@okxweb3/app-x402-core`, `@okxweb3/app-x402-evm`, `@okxweb3/app-x402-next`, `@okxweb3/app-x402-express` — all **v0.2.0**. Pure TypeScript (`fetch` + `node:crypto`, no native bindings) ⇒ **runs in Vercel functions**. Seller-side it: builds the 402 challenge (`x402ResourceServer`+`ExactEvmScheme`), reads `PAYMENT-SIGNATURE`, calls facilitator verify/settle, emits `PAYMENT-RESPONSE`. `@okxweb3/app-x402-next` ships `withX402` (API-route wrapper) + `paymentProxy` (middleware). | SDK-REPO README + `package.json` names; `npm view @okxweb3/app-x402-next version` → `0.2.0`; `app-x402-next/README.md` |
+| 6 | HTTP-level 402 vs MCP-level PaymentRequired | OKX expects **HTTP-level 402** on the endpoint URL: real `HTTP/2 402` status + `PAYMENT-REQUIRED` header, paid replay via `PAYMENT-SIGNATURE` header. All 3 approved sellers do HTTP-level. **Our current MCP-level `_meta` PaymentRequired (structuredContent) is NOT what OKX reads** — the validator/buyer never inspects JSON-RPC `_meta`. 02 must add an HTTP-402 gate at the transport layer of `api/mcp-3d.js`. (oklink's endpoints are "MCP" by name but gate at HTTP: `POST` → 402, headers carry payment; see Appx A.) | WIRE-OKLINK (POST→402, GET→405); [api/mcp-3d.js](../api/mcp-3d.js) `_meta` path; SDK is HTTP-transport only |
+| 7 | How listing review validates the endpoint | The seller registers each service with an **`endpoint` URL + `fee` + fee-token `contractAddress` (`0x779ded…`) + `chainIndex 196`** (see `onchainos agent service-list` output, Appx F). Approval requires the endpoint to answer the gated method (`POST` for oklink) with a `402` whose `accepts` advertise **`eip155:196` + the USD₮0 fee token** at the registered price. The `onchainos agent x402-check --endpoint` / `x402-validate` CLI is the same validator surface: it flags `"Endpoint returned HTTP 200 (not 402); not a valid x402 service"` when the gate is absent (Appx E). Our rejection ("A2MCP service has not been integrated with the OKX Agent Payments Protocol") = our endpoint never returns a `eip155:196` 402. **UNRESOLVED:** the exact HTTP method + body the automated validator sends, and any endpoint-URL format constraint, are not documented in a primary source — 02 should register, run `onchainos agent x402-check --endpoint https://three.ws/api/mcp-3d`, and confirm it reports `valid:true` before resubmitting. | `onchainos agent x402-check` (Appx E); `service-list` schema (Appx F); rejection email (00-CONTEXT) |
+| 8 | Settlement finality — how seller confirms payment | Seller trusts the facilitator's responses, not its own chain read. `/verify` → `isValid:true` gates doing the work (proves the signed authorization is valid + payer funded — a broke payer gets `isValid:false` / `insufficient_balance`, proven by PAY-LEG2). `/settle` → `{success, status}`: `syncSettle:true` ⇒ `status:"success"` (on-chain confirmed before responding); default async ⇒ `status:"pending"` (safe to release; poll `/settle/status?txHash` for finality). The `PAYMENT-RESPONSE` header carries `{success,status,transaction,payer,amount}` to the buyer. | SDK `OKXFacilitatorClient.ts` settle L124-150 + `syncSettle` docstring; `types/facilitator.ts:26-38`; PAY-LEG2 |
+
+---
+
+## 3. SDK decision — adopt `@okxweb3/app-x402-*` (with a thin adapter)
+
+**Decision: ADOPT the OKX Payments SDK for the OKX/X-Layer rail; keep our existing `api/_lib/x402-spec.js` for the Solana/Base/BSC rails.** Do not hand-roll the OKX dialect.
+
+Per CLAUDE.md "Open-source first" checklist:
+
+| Criterion | Finding | Verdict |
+|---|---|---|
+| Solves the problem | Yes — builds the exact `eip155:196` challenge, HMAC-signs facilitator calls, handles `exact`/`aggr_deferred`/`upto`/`period`, emits `PAYMENT-RESPONSE`. First-party, so it tracks the spec the validator enforces. | ✅ |
+| Maintenance / provenance | Official OKX org (`okx/payments`), the SDK the rejection email points to. Multi-language, actively structured. v0.2.0 (early but first-party). | ✅ |
+| License | **Apache-2.0** (`@okxweb3/app-mpp` is MIT). Compatible with our commercial use. | ✅ |
+| Vercel compatibility | Pure TS, deps are `fetch` + `node:crypto` + `viem`-class EVM libs; no native addons. `@okxweb3/app-x402-next` targets Next/serverless directly. | ✅ |
+| Weekly downloads | Low (v0.2.0, new package, published ~2026-07). Mitigated by first-party status + our own tests. **UNRESOLVED exact number** — `npm view` returns version but the registry download-count API wasn't queried; treat as "new, first-party, low adoption." | ⚠️ acceptable |
+
+**Adoption shape for 02:** our endpoint is a bare Vercel function (`api/mcp-3d.js`, Node `req/res`), not a Next.js app-router route, so `withX402` (needs `NextRequest`/`NextResponse`) is not a drop-in. Use the framework-agnostic core: `@okxweb3/app-x402-core` (`x402ResourceServer`, `OKXFacilitatorClient`, the `HTTPAdapter` interface, header codecs) + `@okxweb3/app-x402-evm` (`ExactEvmScheme`). Write a ~30-line `HTTPAdapter` over our Node `req`. This gives the OKX 402/verify/settle for `eip155:196` alongside our current multi-chain `paymentRequirements()` for the other rails. Reference seller wiring: SDK `demo/x402/src/index.ts` (Express) and `app-x402-next/README.md` (`withX402`).
+
+**Env we must add:** `OKX_API_KEY`, `OKX_SECRET_KEY`, `OKX_PASSPHRASE` (facilitator HMAC), plus the payTo already known. **Blocker for 02:** these OKX API credentials must be provisioned by the owner from the OKX Web3 developer console. Without them every `/verify` and `/settle` fails auth. → raised in PROGRESS.
+
+---
+
+## 4. Gap analysis — `paymentRequirements()` today vs. what OKX requires (02's work list)
+
+Reference: [api/_lib/x402-spec.js](../api/_lib/x402-spec.js) `paymentRequirements()` (L162-232) and `buildExactRequirements()` (L362-398).
+
+| # | What we emit today | What OKX requires | Action for 02 |
+|---|---|---|---|
+| G1 | Accepts for `NETWORK_SOLANA_MAINNET`, `NETWORK_BASE_MAINNET`, `NETWORK_BSC_MAINNET`, `NETWORK_ARBITRUM_MAINNET`. **No `eip155:196`.** | An `accepts` entry with `network:"eip155:196"`. | Add `NETWORK_XLAYER_MAINNET = "eip155:196"` and an X-Layer branch (behind an env like `X402_PAY_TO_XLAYER`). |
+| G2 | `asset` = USDC on Solana/Base; `X402_ASSET_ADDRESS_BASE`. | `asset` = `0x779ded0c9e1022225f8e0630b35a9b54be713736` (USD₮0). | Hardcode/env the USD₮0 mint for the X-Layer accept. |
+| G3 | `extra: { name, decimals }` (Base) / `{ name, decimals, feePayer }` (Solana). | `extra: { name:"USD₮0", version:"1" }` (+ optional `symbol`,`transferMethod`). **No `decimals` in extra; `version` is required.** | New `extra` builder for the X-Layer accept: `name`+`version` mandatory, drop `decimals`. |
+| G4 | Field name `extra.assetTransferMethod` (permit2 path). | OKX exact uses `extra.transferMethod:"eip3009"` (or omit → EIP-3009 default). | Emit `transferMethod` (optional) — do NOT emit `assetTransferMethod` on the X-Layer accept. |
+| G5 | Schemes `exact` (EIP-3009/permit2) + `direct` (BSC). **No `aggr_deferred`.** | `exact` mandatory; `aggr_deferred` recommended 2nd accept. | Emit `exact` for X-Layer; optionally add `aggr_deferred` accept (SDK `ExactEvmScheme`/aggr scheme). |
+| G6 | Facilitator routing = CDP / PayAI / self / BSC-direct (`facilitatorFor()`). **No OKX facilitator.** | verify/settle at `https://web3.okx.com/api/v6/pay/x402/{verify,settle}` with HMAC auth. | Add an `OKXFacilitatorClient` route for `eip155:196` (adopt SDK, §3). |
+| G7 | Payment header read = **`X-PAYMENT`** (`decodePaymentHeader`, `verifyPayment`). | Buyer sends **`PAYMENT-SIGNATURE`**. | On the X-Layer path read `PAYMENT-SIGNATURE` (case-insensitive). Keep `X-PAYMENT` for the other rails. |
+| G8 | Success receipt = **`X-PAYMENT-RESPONSE`** (`encodePaymentResponseHeader`, L1122). | **`PAYMENT-RESPONSE`** header. | Emit `PAYMENT-RESPONSE` on the X-Layer success reply. |
+| G9 | Gating is **MCP-level** via `_meta` structuredContent in [api/mcp-3d.js](../api/mcp-3d.js). | **HTTP-level 402** on the endpoint URL. | Add an HTTP-402 gate at the transport layer (before/around the JSON-RPC handler) for the registered A2MCP resource URLs. |
+| G10 | Body carries `extensions.bazaar` + `builder-code` + `offer-receipt`. | OKX sellers emit none of these on the `eip155:196` accepts. | Keep the OKX accept body minimal (`x402Version/resource/accepts`); don't attach Bazaar extensions to it. |
+| G11 | Facilitator auth = CDP JWT / bearer token. | OKX HMAC needs `OKX_API_KEY`/`OKX_SECRET_KEY`/`OKX_PASSPHRASE`. | Provision + wire the three env vars (owner blocker). |
+| G12 | `maxTimeoutSeconds: 60`. | Approved sellers use `86400`/`300`. | Use ≥ ~300 on X-Layer (bounds `validBefore`); `86400` matches oklink. |
+
+**Non-goals for 02** (explicitly out of scope): the WWW-Authenticate `charge`/`session` MPP rail (CoinAnk offers it, but `exact` alone passes approval) and `period`/subscription. `upto` is unnecessary and adds a Permit2 approve step. Ship `exact` (+ optional `aggr_deferred`) only.
+
+---
+
+## Appendix — raw captures (verbatim, dated 2026-07-06)
+
+### A. WIRE-OKLINK — Onchain Data Explorer #2023 (174 sales), `get_chain_info`
+
+`GET` → `HTTP/2 405 {"code":"405","msg":"Method Not Allowed"}`. `POST {}` → `HTTP/2 402`:
+
+```
+payment-required: eyJ4NDAyVmVyc2lvbiI6MiwicmVzb3VyY2UiOnsidXJsIjoiaHR0cHM6Ly93d3cub2tsaW5rLmNvbS9hcGkvdjUvZXhwbG9yZXIvbWNwL3g0MDIvZ2V0X2NoYWluX2luZm8iLCJtaW1lVHlwZSI6ImFwcGxpY2F0aW9uL2pzb24ifSwiYWNjZXB0cyI6W3sic2NoZW1lIjoiZXhhY3QiLCJuZXR3b3JrIjoiZWlwMTU1OjE5NiIsImFtb3VudCI6IjE1IiwicGF5VG8iOiIweGE3ZTM3NjA0ZWJhYjk0NDA4MTU5ZTQwNTAzM2E0NTVmODIwZmQ5ODciLCJtYXhUaW1lb3V0U2Vjb25kcyI6ODY0MDAsImFzc2V0IjoiMHg3NzlkZWQwYzllMTAyMjIyNWY4ZTA2MzBiMzVhOWI1NGJlNzEzNzM2IiwiZXh0cmEiOnsic3ltYm9sIjoiVVNEVCIsInZlcnNpb24iOiIxIiwidHJhbnNmZXJNZXRob2QiOiJlaXAzMDA5IiwibmFtZSI6IlVTROKCrjAifX0seyJzY2hlbWUiOiJhZ2dyX2RlZmVycmVkIiwibmV0d29yayI6ImVpcDE1NToxOTYiLCJhbW91bnQiOiIxNSIsInBheVRvIjoiMHhhN2UzNzYwNGViYWI5NDQwODE1OWU0MDUwMzNhNDU1ZjgyMGZkOTg3IiwibWF4VGltZW91dFNlY29uZHMiOjg2NDAwLCJhc3NldCI6IjB4Nzc5ZGVkMGM5ZTEwMjIyMjVmOGUwNjMwYjM1YTliNTRiZTcxMzczNiIsImV4dHJhIjp7InN5bWJvbCI6IlVTRFQiLCJ2ZXJzaW9uIjoiMSIsInRyYW5zZmVyTWV0aG9kIjoiZWlwMzAwOSIsIm5hbWUiOiJVU0Tigq4wIn19XX0=
+access-control-expose-headers: PAYMENT-REQUIRED
+```
+
+Decoded body:
+
+```json
+{"x402Version":2,"resource":{"url":"https://www.oklink.com/api/v5/explorer/mcp/x402/get_chain_info","mimeType":"application/json"},"accepts":[{"scheme":"exact","network":"eip155:196","amount":"15","payTo":"0xa7e37604ebab94408159e405033a455f820fd987","maxTimeoutSeconds":86400,"asset":"0x779ded0c9e1022225f8e0630b35a9b54be713736","extra":{"symbol":"USDT","version":"1","transferMethod":"eip3009","name":"USD₮0"}},{"scheme":"aggr_deferred","network":"eip155:196","amount":"15","payTo":"0xa7e37604ebab94408159e405033a455f820fd987","maxTimeoutSeconds":86400,"asset":"0x779ded0c9e1022225f8e0630b35a9b54be713736","extra":{"symbol":"USDT","version":"1","transferMethod":"eip3009","name":"USD₮0"}}]}
+```
+
+### B. WIRE-COINANK — CoinAnk OpenAPI #2013 (818 sales), `getUsBtcEtf`
+
+`GET` → `HTTP/2 402`. Emits BOTH `payment-required` (v2, 4 accepts) AND four `WWW-Authenticate: Payment` headers (MPP charge+session × two currencies USDG/USD₮0). `payment-required` decoded:
+
+```json
+{"x402Version":2,"accepts":[
+ {"x402Version":2,"scheme":"exact","network":"eip155:196","amount":"1000","asset":"0x4ae46a509f6b1d9056937ba4500cb143933d2dc8","payTo":"0xb1257e75791baa36646113d8b1fdfc83b3e2d0b7","maxTimeoutSeconds":300,"extra":{"name":"Global Dollar","version":"1"}},
+ {"x402Version":2,"scheme":"exact","network":"eip155:196","amount":"1000","asset":"0x779ded0c9e1022225f8e0630b35a9b54be713736","payTo":"0xb1257e75791baa36646113d8b1fdfc83b3e2d0b7","maxTimeoutSeconds":300,"extra":{"name":"USD₮0","version":"1"}},
+ {"x402Version":2,"scheme":"aggr_deferred","network":"eip155:196","amount":"1000","asset":"0x4ae46a509f6b1d9056937ba4500cb143933d2dc8","payTo":"0xb1257e75791baa36646113d8b1fdfc83b3e2d0b7","maxTimeoutSeconds":300,"extra":{"name":"Global Dollar","version":"1"}},
+ {"x402Version":2,"scheme":"aggr_deferred","network":"eip155:196","amount":"1000","asset":"0x779ded0c9e1022225f8e0630b35a9b54be713736","payTo":"0xb1257e75791baa36646113d8b1fdfc83b3e2d0b7","maxTimeoutSeconds":300,"extra":{"name":"USD₮0","version":"1"}}],
+ "resource":{"url":"https://open-api.coinank.com/api/etf/getUsBtcEtf"}}
+```
+
+`WWW-Authenticate` charge `request` decoded: `{"amount":"1000","currency":"0x779ded…713736","recipient":"0xb1257e…d0b7","methodDetails":{"chainId":196,"feePayer":true}}`.
+Session `request` decoded: adds `"escrowContract":"0x5E550002e64FaF79B41D89fE8439eEb1be66CE3b","minVoucherDelta":"10000"` and `"suggestedDeposit":"100000"`. (MPP rail — out of scope for 02.)
+
+### C. WIRE-OKB — OKB Monitoring #3837, `/x402/digest`
+
+Both `GET` and `POST` → `HTTP/2 402`, body (note **`x402Version:1`**, `maxAmountRequired`, per-accept `decimals`/`description`):
+
+```json
+{"x402Version":1,"accepts":[{"scheme":"exact","network":"eip155:196","asset":"0x779ded0c9e1022225f8e0630b35a9b54be713736","decimals":6,"maxAmountRequired":"10000","payTo":"0x0921f7fcbc93984c2a4d29b4079f97840184365b","resource":"https://okb.swaper.money/x402/digest","description":"OKB X Layer monitor — OKB X Layer daily anomaly digest (alerts + metrics + report)","mimeType":"application/json","maxTimeoutSeconds":300,"extra":{"name":"USD₮0","version":"1"}}]}
+```
+
+### D. PAY-LEG1/2 — real payment from our wallet `0x75d0…cf69`
+
+**Leg 1** — `onchainos payment pay --payload <oklink 402> --selected-index 0` →
+`{ok:true, data:{ header_name:"PAYMENT-SIGNATURE", scheme:"exact", wallet:"0x75d00a2713565171f33216e5aa2a375e076ecf69", authorization_header:"<base64>" }}`. Decoded payload in §1.3 (EIP-3009 `transferWithAuthorization`, value "15", from our wallet, to oklink's payTo, signed).
+
+**Leg 2** — replay `POST get_chain_info` with `PAYMENT-SIGNATURE: <header>` → `HTTP/2 402`, body:
+
+```json
+{"x402Version":2,"error":"insufficient_balance","resource":{"url":"https://www.oklink.com/api/v5/explorer/mcp/x402/get_chain_info","mimeType":"application/json"},"accepts":[ …same two accepts as Appx A… ]}
+```
+
+**Interpretation:** signing succeeded (leg 1 real), and the seller's facilitator did an on-chain balance check and rejected because our X-Layer wallet holds **0 USD₮0** — proving (a) the seller→facilitator verify path is live, (b) rejection re-emits the full 402 with a top-level `error`. **Funding blocker (DoD):** to capture a fully-successful paid leg the owner must fund `0x75d00a2713565171f33216e5aa2a375e076ecf69` on **X Layer (chainId 196)** with **USD₮0** (`0x779ded…713736`). Minimum to pay oklink `get_chain_info` = **15 atomic (0.000015 USD₮0)**; recommend **~1.0 USD₮0 (1,000,000 atomic)** for buffer across test calls + the pfp-wedge work. `exact`+EIP-3009 is gasless for the payer (facilitator broadcasts, `feePayer:true`), so no OKB gas is strictly required; a small OKB dust (~0.5 OKB) is optional insurance for any self-broadcast path. `onchainos portfolio all-balances --chain xlayer --chains 196 --address 0x75d0…cf69` currently returns `data:[]`.
+
+### E. CLI validator + token info
+
+```
+$ onchainos agent x402-check --endpoint https://x402.dappos.com/healthz
+{"ok":true,"data":{"reason":"Endpoint returned HTTP 200 (not 402); not a valid x402 service.","statusCode":200,"valid":false}}
+
+$ onchainos token info --chain xlayer --address 0x779ded0c9e1022225f8e0630b35a9b54be713736
+{"chainIndex":"196","decimal":"6","tokenName":"USD₮0","tokenSymbol":"USDT","tagList":{"communityRecognized":true},
+ "tokenContractAddress":"0x779ded0c9e1022225f8e0630b35a9b54be713736"}
+```
+
+### F. `onchainos agent service-list` — how a service is registered (shape)
+
+Each A2MCP service row (from Onchain Data Explorer #2023): `{ serviceType:"A2MCP", serviceName, endpoint:"https://…", fee:"0.000015", contractAddress:"0x779ded…713736", chainIndex:196 }`. The registered `endpoint` + `fee` + fee-token `contractAddress` + `chainIndex` are what the buyer/validator matches the live 402 against.
+
+### G. OKX Payments SDK — seller wiring (SDK-REPO `demo/x402/src/index.ts`, trimmed)
+
+```ts
+import { OKXFacilitatorClient } from "@okxweb3/app-x402-core";
+import { x402ResourceServer } from "@okxweb3/app-x402-express";
+import { ExactEvmScheme } from "@okxweb3/app-x402-evm/exact/server";
+
+const facilitator = new OKXFacilitatorClient({
+ apiKey: process.env.OKX_API_KEY!, secretKey: process.env.OKX_SECRET_KEY!,
+ passphrase: process.env.OKX_PASSPHRASE!, baseUrl: "https://web3.okx.com",
+});
+const server = new x402ResourceServer(facilitator).register("eip155:196", new ExactEvmScheme());
+const routes = { "POST /api/mcp-3d": {
+ accepts: { scheme: "exact", network: "eip155:196",
+ payTo: "0x75d00a2713565171f33216e5aa2a375e076ecf69", price: "$0.000015" },
+ mimeType: "application/json" } };
+// USD price → USD₮0 atomic auto-converted via DEFAULT_STABLECOINS["eip155:196"] (6 dp).
+```
diff --git a/tests/api/forge-lane-routing.test.js b/tests/api/forge-lane-routing.test.js
index e1f2ec75e..e1e873452 100644
--- a/tests/api/forge-lane-routing.test.js
+++ b/tests/api/forge-lane-routing.test.js
@@ -17,6 +17,7 @@ import {
backendCostClass,
isSelfHostBackend,
isFreeBackend,
+ selfHostPrimary,
DEFAULT_BACKEND_FOR_PATH,
} from '../../api/_lib/forge-tiers.js';
@@ -28,6 +29,7 @@ const ALL_LANE_VARS = [
'HF_TOKEN',
'NVIDIA_API_KEY',
'REPLICATE_API_TOKEN',
+ 'FORGE_SELFHOST_PRIMARY',
];
const saved = {};
@@ -85,6 +87,78 @@ describe('freeLaneCandidates — ordered, configured, de-duplicated', () => {
});
});
+describe('FORGE_SELFHOST_PRIMARY — hoist our own GPU fleet ahead of hosted free lanes', () => {
+ it('parses the flag: off unless explicitly truthy', () => {
+ delete process.env.FORGE_SELFHOST_PRIMARY;
+ expect(selfHostPrimary()).toBe(false);
+ for (const on of ['1', 'true', 'on', 'yes', 'YES']) {
+ process.env.FORGE_SELFHOST_PRIMARY = on;
+ expect(selfHostPrimary()).toBe(true);
+ }
+ for (const off of ['0', 'false', 'off', 'no', '']) {
+ process.env.FORGE_SELFHOST_PRIMARY = off;
+ expect(selfHostPrimary()).toBe(false);
+ }
+ });
+
+ it('off (default) keeps the native NVIDIA text lane leading', () => {
+ configureAllLanes();
+ delete process.env.FORGE_SELFHOST_PRIMARY;
+ expect(freeLaneCandidates('image', 'draft', false)).toEqual([
+ 'nvidia',
+ 'trellis_selfhost',
+ 'hunyuan3d',
+ 'huggingface',
+ ]);
+ });
+
+ it('on: self-host workers lead for text, hosted lanes remain as fallthrough', () => {
+ configureAllLanes();
+ process.env.FORGE_SELFHOST_PRIMARY = '1';
+ // nvidia (tier-named) is demoted below our own fleet; order within each group
+ // is preserved, so hosted nvidia/huggingface stay in place as fallthrough.
+ expect(freeLaneCandidates('image', 'draft', false)).toEqual([
+ 'trellis_selfhost',
+ 'hunyuan3d',
+ 'nvidia',
+ 'huggingface',
+ ]);
+ });
+
+ it('on: photo lane already self-host-first is unchanged', () => {
+ configureAllLanes();
+ process.env.FORGE_SELFHOST_PRIMARY = '1';
+ expect(freeLaneCandidates('image', 'draft', true)).toEqual([
+ 'trellis_selfhost',
+ 'hunyuan3d',
+ 'huggingface',
+ ]);
+ });
+
+ it('on: is a no-op when no self-host worker is configured (lanes still filtered)', () => {
+ // Only hosted lanes wired — flag has nothing to hoist, order is unchanged.
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+ process.env.HF_TOKEN = 'hf_test';
+ process.env.FORGE_SELFHOST_PRIMARY = '1';
+ expect(freeLaneCandidates('image', 'draft', false)).toEqual(['nvidia', 'huggingface']);
+ });
+
+ it('on: routes an unnamed text prompt to self-host TRELLIS via the resolver', () => {
+ configureAllLanes();
+ process.env.FORGE_SELFHOST_PRIMARY = '1';
+ expect(resolveBackendId({ path: 'image', tier: 'draft', userImages: false })).toBe('trellis_selfhost');
+ // Health-aware twin agrees when the fleet is healthy.
+ expect(
+ resolveBackendIdWithHealth({
+ path: 'image',
+ tier: 'draft',
+ userImages: false,
+ health: { trellis_selfhost: 'ok' },
+ }),
+ ).toBe('trellis_selfhost');
+ });
+});
+
describe('resolveBackendIdWithHealth — prefer healthy self-host → other free → paid', () => {
beforeEach(configureAllLanes);
diff --git a/tests/api/gcp-revert.test.js b/tests/api/gcp-revert.test.js
new file mode 100644
index 000000000..5f1055af9
--- /dev/null
+++ b/tests/api/gcp-revert.test.js
@@ -0,0 +1,119 @@
+// GCP credit-program revert — proves the mechanism scripts/gcp/revert-to-free.sh
+// relies on: every credit-funded GCP lane is gated purely by env vars, so REMOVING
+// the gate var makes the resolver fall through to the pre-program provider. No code
+// migration, no redeploy of logic — the same functions, different env.
+//
+// This is the code-level proof of the revert. A full live-preview flip additionally
+// needs the owner's Vercel + GCP credentials (documented in docs/gcp-credits.md);
+// this test locks the routing contract those creds ride on.
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import {
+ resolveBackendId,
+ backendIsConfigured,
+ outputIsConfigured,
+ freeLaneCandidates,
+} from '../../api/_lib/forge-tiers.js';
+import { isConfigured as imagenIsConfigured } from '../../api/_mcp3d/vertex-imagen.js';
+import { resolveProviderName } from '../../api/_lib/regen-provider.js';
+
+// Every env var the revert touches, cleared between tests so each case sets only
+// what it means to assert on.
+const ALL = [
+ 'MODEL_TRELLIS_URL', 'GCP_HUNYUAN3D_URL', 'GCP_TRIPOSG_URL', 'GCP_REMESH_URL',
+ 'GCP_RECONSTRUCTION_URL', 'GCP_RECONSTRUCTION_KEY',
+ 'GCP_REMBG_URL', 'GCP_TEXTURE_URL', 'GCP_SEGMENT_URL',
+ 'GOOGLE_CLOUD_PROJECT', 'GCP_SERVICE_ACCOUNT_JSON',
+ 'NVIDIA_API_KEY', 'HF_TOKEN', 'REPLICATE_API_TOKEN', 'AVATAR_REGEN_PROVIDER',
+];
+
+let saved;
+beforeEach(() => {
+ saved = {};
+ for (const k of ALL) { saved[k] = process.env[k]; delete process.env[k]; }
+});
+afterEach(() => {
+ for (const k of ALL) {
+ if (saved[k] === undefined) delete process.env[k];
+ else process.env[k] = saved[k];
+ }
+});
+
+describe('forge image→3D: GCP self-host lane reverts to a free lane by unsetting its gate', () => {
+ it('program ON — a photo→3D request resolves to the self-host TRELLIS worker', () => {
+ // Self-host TRELLIS is gated by MODEL_TRELLIS_URL + GCP_RECONSTRUCTION_KEY.
+ process.env.MODEL_TRELLIS_URL = 'https://model-trellis-abc.run.app';
+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';
+ process.env.HF_TOKEN = 'hf_x'; // a free fallback also present, to prove precedence
+ expect(backendIsConfigured('trellis_selfhost')).toBe(true);
+ // A photo submission can't use the text-only NVIDIA lane, so the self-host
+ // worker leads the free candidate ordering.
+ const id = resolveBackendId({ path: 'image', tier: 'standard', userImages: true });
+ expect(id).toBe('trellis_selfhost');
+ });
+
+ it('program OFF — unsetting the gate demotes the lane and falls back to the free HF lane', () => {
+ // Same request, GCP gate removed (what the revert does).
+ delete process.env.MODEL_TRELLIS_URL;
+ delete process.env.GCP_RECONSTRUCTION_KEY;
+ process.env.HF_TOKEN = 'hf_x'; // the pre-program free image→3D lane
+ expect(backendIsConfigured('trellis_selfhost')).toBe(false);
+ const id = resolveBackendId({ path: 'image', tier: 'standard', userImages: true });
+ expect(id).toBe('huggingface');
+ // And with no free lane at all, it degrades to the paid standing default —
+ // never dead-ends.
+ delete process.env.HF_TOKEN;
+ expect(resolveBackendId({ path: 'image', tier: 'standard', userImages: true })).toBe('trellis');
+ });
+
+ it('the Hunyuan3D and sketch/remesh gates flip the same way', () => {
+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';
+ process.env.GCP_HUNYUAN3D_URL = 'https://hy.run.app';
+ process.env.GCP_TRIPOSG_URL = 'https://sg.run.app';
+ process.env.GCP_REMESH_URL = 'https://rm.run.app';
+ expect(backendIsConfigured('hunyuan3d')).toBe(true);
+ expect(backendIsConfigured('triposg')).toBe(true);
+ expect(outputIsConfigured('gameready')).toBe(true);
+ for (const v of ['GCP_HUNYUAN3D_URL', 'GCP_TRIPOSG_URL', 'GCP_REMESH_URL', 'GCP_RECONSTRUCTION_KEY']) delete process.env[v];
+ expect(backendIsConfigured('hunyuan3d')).toBe(false);
+ expect(backendIsConfigured('triposg')).toBe(false);
+ expect(outputIsConfigured('gameready')).toBe(false);
+ });
+
+ it('free-lane candidate ordering prefers self-host, then external free, when configured', () => {
+ process.env.MODEL_TRELLIS_URL = 'https://t.run.app';
+ process.env.GCP_HUNYUAN3D_URL = 'https://h.run.app';
+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';
+ process.env.HF_TOKEN = 'hf_x';
+ expect(freeLaneCandidates('image', 'standard', true)).toEqual(['trellis_selfhost', 'hunyuan3d', 'huggingface']);
+ // Revert: only the external free lane survives.
+ for (const v of ['MODEL_TRELLIS_URL', 'GCP_HUNYUAN3D_URL', 'GCP_RECONSTRUCTION_KEY']) delete process.env[v];
+ expect(freeLaneCandidates('image', 'standard', true)).toEqual(['huggingface']);
+ });
+});
+
+describe('avatar reconstruct/rerig: reverts GCP → Replicate → HF', () => {
+ it('picks gcp when only GCP_RECONSTRUCTION_URL is set; falls to replicate/hf/none as the gate is pulled', () => {
+ process.env.GCP_RECONSTRUCTION_URL = 'https://ctrl.run.app';
+ expect(resolveProviderName()).toBe('gcp');
+ // Revert with the recommended fallback present.
+ delete process.env.GCP_RECONSTRUCTION_URL;
+ process.env.REPLICATE_API_TOKEN = 'r8_x';
+ expect(resolveProviderName()).toBe('replicate');
+ delete process.env.REPLICATE_API_TOKEN;
+ process.env.HF_TOKEN = 'hf_x';
+ expect(resolveProviderName()).toBe('huggingface');
+ // The pre-flight warning case: no fallback configured → 'none' (feature off).
+ delete process.env.HF_TOKEN;
+ expect(resolveProviderName()).toBe('none');
+ });
+});
+
+describe('imagen text→image: reverts to free NIM FLUX by unsetting GOOGLE_CLOUD_PROJECT', () => {
+ it('isConfigured() flips with the project gate', () => {
+ process.env.GOOGLE_CLOUD_PROJECT = 'three-ws-prod';
+ expect(imagenIsConfigured()).toBe(true);
+ delete process.env.GOOGLE_CLOUD_PROJECT;
+ expect(imagenIsConfigured()).toBe(false);
+ });
+});
diff --git a/tests/api/text-to-image.test.js b/tests/api/text-to-image.test.js
index a88c35145..d1e07e7c5 100644
--- a/tests/api/text-to-image.test.js
+++ b/tests/api/text-to-image.test.js
@@ -39,7 +39,7 @@ vi.mock('../../api/_lib/forge-scale.js', async (importOriginal) => {
});
const ORIGINAL_FETCH = globalThis.fetch;
-const ENV_KEYS = ['NVIDIA_API_KEY', 'GOOGLE_CLOUD_PROJECT', 'GCP_SERVICE_ACCOUNT_JSON', 'REPLICATE_API_TOKEN'];
+const ENV_KEYS = ['NVIDIA_API_KEY', 'GOOGLE_CLOUD_PROJECT', 'GCP_SERVICE_ACCOUNT_JSON', 'REPLICATE_API_TOKEN', 'VERTEX_IMAGEN_ENABLED'];
const ORIGINAL_ENV = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));
async function freshTextToImage() {
@@ -593,6 +593,61 @@ describe('textToImage — Vertex → Replicate fallback', () => {
});
});
+describe('textToImage — VERTEX_IMAGEN_ENABLED gate', () => {
+ it('unset ⇒ current behavior: Vertex serves when the project is set', async () => {
+ process.env.GOOGLE_CLOUD_PROJECT = 'demo-project';
+ process.env.REPLICATE_API_TOKEN = 'r8_test_token';
+ vertexState.configured = true;
+ vertexState.generate = vi.fn(async () => ({
+ imageUrl: `data:image/png;base64,${Buffer.from('vx').toString('base64')}`,
+ model: 'vertex-ai/gemini-2.5-flash-image',
+ }));
+ const calls = stubFetch([['api.replicate.com', () => replicateSuccessResponse()]]);
+
+ const textToImage = await freshTextToImage();
+ const result = await textToImage('a red teapot');
+
+ expect(vertexState.generate).toHaveBeenCalledOnce();
+ expect(result.model).toBe('vertex-ai/gemini-2.5-flash-image');
+ expect(calls).toHaveLength(0); // Replicate never reached
+ });
+
+ it('=0 forces the Vertex lane off, falling through to Replicate', async () => {
+ process.env.GOOGLE_CLOUD_PROJECT = 'demo-project';
+ process.env.REPLICATE_API_TOKEN = 'r8_test_token';
+ process.env.VERTEX_IMAGEN_ENABLED = '0';
+ vertexState.configured = true;
+ vertexState.generate = vi.fn(async () => {
+ throw new Error('vertex should never be called when gated off');
+ });
+ const calls = stubFluxSuccess();
+
+ const textToImage = await freshTextToImage();
+ const result = await textToImage('a red teapot');
+
+ expect(vertexState.generate).not.toHaveBeenCalled();
+ expect(result.model).toBe('black-forest-labs/flux-schnell');
+ expect(calls.some((c) => c.url.includes('api.replicate.com'))).toBe(true);
+ });
+
+ it('=1 keeps the Vertex lane on', async () => {
+ process.env.GOOGLE_CLOUD_PROJECT = 'demo-project';
+ process.env.VERTEX_IMAGEN_ENABLED = '1';
+ vertexState.configured = true;
+ vertexState.generate = vi.fn(async () => ({
+ imageUrl: `data:image/png;base64,${Buffer.from('vx').toString('base64')}`,
+ model: 'vertex-ai/gemini-2.5-flash-image',
+ }));
+ stubFetch([]);
+
+ const textToImage = await freshTextToImage();
+ const result = await textToImage('a red teapot');
+
+ expect(vertexState.generate).toHaveBeenCalledOnce();
+ expect(result.model).toBe('vertex-ai/gemini-2.5-flash-image');
+ });
+});
+
describe('vertex-imagen — service-account JSON hardening', () => {
it('rejects mangled GCP_SERVICE_ACCOUNT_JSON with a designed unconfigured error', async () => {
process.env.GOOGLE_CLOUD_PROJECT = 'demo-project';
diff --git a/tests/api/vertex-imagen.test.js b/tests/api/vertex-imagen.test.js
new file mode 100644
index 000000000..83e164972
--- /dev/null
+++ b/tests/api/vertex-imagen.test.js
@@ -0,0 +1,188 @@
+// Unit tests for the Vertex AI image-generation client.
+//
+// The Imagen `:predict` family is being retired (imagen-3.0-* shut down
+// 2026-06-30; imagen-4.0-* by 2026-08-17), so the client now defaults to the
+// live Gemini image model `gemini-2.5-flash-image` via `:generateContent`, and
+// only takes the legacy `:predict` shape for an explicit `imagen-*` override.
+//
+// These tests pin BOTH request/response shapes against the documented Vertex
+// contract and the model-prefix router, without any live credentials: the GCP
+// token mint is mocked and every HTTP call is a recorded-shape fixture (a test
+// double for an external API, not product data). Live E2E is a separate, creds-
+// gated step tracked in docs/gcp-credits.md.
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+vi.mock('../../api/_lib/gcp-auth.js', () => ({
+ getGcpAccessToken: vi.fn(async () => 'fake-access-token'),
+}));
+
+import { generateImage, editImage, isConfigured } from '../../api/_mcp3d/vertex-imagen.js';
+
+const ORIGINAL_FETCH = globalThis.fetch;
+const ENV_KEYS = ['GOOGLE_CLOUD_PROJECT', 'GOOGLE_CLOUD_LOCATION', 'VERTEX_IMAGEN_MODEL', 'VERTEX_IMAGEN_EDIT_MODEL'];
+const ORIGINAL_ENV = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));
+
+function stubFetch(responder) {
+ const calls = [];
+ globalThis.fetch = vi.fn(async (url, opts = {}) => {
+ const call = { url: String(url), body: opts.body ? JSON.parse(opts.body) : null, headers: opts.headers };
+ calls.push(call);
+ return responder(call);
+ });
+ return calls;
+}
+
+// A gemini-2.5-flash-image generateContent success: the image rides back as an
+// inlineData part (base64 + mimeType), same as the live API.
+function geminiImageResponse(b64 = Buffer.from('gemini-png').toString('base64'), mime = 'image/png') {
+ return new Response(
+ JSON.stringify({
+ candidates: [{ content: { parts: [{ inlineData: { mimeType: mime, data: b64 } }] }, finishReason: 'STOP' }],
+ }),
+ { status: 200, headers: { 'content-type': 'application/json' } },
+ );
+}
+
+// A legacy Imagen :predict success: base64 under predictions[].bytesBase64Encoded.
+function imagenPredictResponse(b64 = Buffer.from('imagen-png').toString('base64')) {
+ return new Response(JSON.stringify({ predictions: [{ bytesBase64Encoded: b64 }] }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ });
+}
+
+beforeEach(() => {
+ for (const k of ENV_KEYS) delete process.env[k];
+ process.env.GOOGLE_CLOUD_PROJECT = 'demo-project';
+});
+
+afterEach(() => {
+ globalThis.fetch = ORIGINAL_FETCH;
+ for (const k of ENV_KEYS) {
+ if (ORIGINAL_ENV[k] === undefined) delete process.env[k];
+ else process.env[k] = ORIGINAL_ENV[k];
+ }
+ vi.clearAllMocks();
+});
+
+describe('vertex-imagen — default Gemini image path', () => {
+ it('calls :generateContent with the documented image-modality body', async () => {
+ const calls = stubFetch(() => geminiImageResponse());
+ const result = await generateImage('a red teapot', { aspectRatio: '16:9' });
+
+ expect(calls).toHaveLength(1);
+ const { url, body, headers } = calls[0];
+ // Endpoint: regional host + publisher model + :generateContent (NOT :predict).
+ expect(url).toBe(
+ 'https://us-central1-aiplatform.googleapis.com/v1/projects/demo-project' +
+ '/locations/us-central1/publishers/google/models/gemini-2.5-flash-image:generateContent',
+ );
+ expect(headers.authorization).toBe('Bearer fake-access-token');
+ // Request shape: text prompt + IMAGE modality + aspect ratio in imageConfig.
+ expect(body.contents[0].parts[0].text).toBe('a red teapot');
+ expect(body.generationConfig.responseModalities).toEqual(['IMAGE']);
+ expect(body.generationConfig.imageConfig.aspectRatio).toBe('16:9');
+
+ // Response parse: inlineData → data URI carrying the real mime type + model tag.
+ expect(result.imageUrl).toBe(`data:image/png;base64,${Buffer.from('gemini-png').toString('base64')}`);
+ expect(result.model).toBe('vertex-ai/gemini-2.5-flash-image');
+ });
+
+ it('preserves the response mime type in the data URI', async () => {
+ stubFetch(() => geminiImageResponse(Buffer.from('jpg').toString('base64'), 'image/jpeg'));
+ const result = await generateImage('a teapot');
+ expect(result.imageUrl.startsWith('data:image/jpeg;base64,')).toBe(true);
+ });
+
+ it('accepts the wide Gemini aspect-ratio set and falls back to 1:1 for unknown', async () => {
+ let calls = stubFetch(() => geminiImageResponse());
+ await generateImage('x', { aspectRatio: '21:9' });
+ expect(calls[0].body.generationConfig.imageConfig.aspectRatio).toBe('21:9');
+
+ calls = stubFetch(() => geminiImageResponse());
+ await generateImage('x', { aspectRatio: '7:3' }); // not a supported ratio
+ expect(calls[0].body.generationConfig.imageConfig.aspectRatio).toBe('1:1');
+ });
+
+ it('throws with the finishReason when a safety block returns no image', async () => {
+ stubFetch(
+ () =>
+ new Response(JSON.stringify({ candidates: [{ content: { parts: [{ text: 'blocked' }] }, finishReason: 'SAFETY' }] }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ }),
+ );
+ await expect(generateImage('x')).rejects.toThrow(/no image data.*SAFETY/);
+ });
+});
+
+describe('vertex-imagen — legacy Imagen :predict override', () => {
+ beforeEach(() => {
+ process.env.VERTEX_IMAGEN_MODEL = 'imagen-4.0-generate-001';
+ });
+
+ it('routes an imagen-* model to :predict with the instances/parameters body', async () => {
+ const calls = stubFetch(() => imagenPredictResponse());
+ const result = await generateImage('a red teapot', { aspectRatio: '4:3' });
+
+ const { url, body } = calls[0];
+ expect(url).toContain('/models/imagen-4.0-generate-001:predict');
+ expect(body.instances[0].prompt).toBe('a red teapot');
+ expect(body.parameters).toMatchObject({
+ sampleCount: 1,
+ aspectRatio: '4:3',
+ addWatermark: false,
+ safetySetting: 'block_some',
+ personGeneration: 'allow_adult',
+ });
+ expect(result.imageUrl).toBe(`data:image/png;base64,${Buffer.from('imagen-png').toString('base64')}`);
+ expect(result.model).toBe('vertex-ai/imagen-4.0-generate-001');
+ });
+});
+
+describe('vertex-imagen — location + error handling', () => {
+ it('uses the un-prefixed host for the global location', async () => {
+ process.env.GOOGLE_CLOUD_LOCATION = 'global';
+ const calls = stubFetch(() => geminiImageResponse());
+ await generateImage('x');
+ expect(calls[0].url.startsWith('https://aiplatform.googleapis.com/v1/projects/demo-project/locations/global/')).toBe(true);
+ });
+
+ it('maps 429 to a retryable rate_limited error', async () => {
+ stubFetch(() => new Response(JSON.stringify({ error: { message: 'quota' } }), { status: 429 }));
+ await expect(generateImage('x')).rejects.toMatchObject({ code: 'rate_limited', retryAfter: 10 });
+ });
+
+ it('surfaces a 500 with providerStatus so the caller can fall back', async () => {
+ stubFetch(() => new Response(JSON.stringify({ error: { message: 'boom' } }), { status: 500 }));
+ await expect(generateImage('x')).rejects.toMatchObject({ providerStatus: 500 });
+ });
+
+ it('maps a network failure to provider_unreachable', async () => {
+ globalThis.fetch = vi.fn(async () => {
+ throw new Error('ECONNRESET');
+ });
+ await expect(generateImage('x')).rejects.toMatchObject({ code: 'provider_unreachable' });
+ });
+
+ it('throws unconfigured when GOOGLE_CLOUD_PROJECT is missing', async () => {
+ delete process.env.GOOGLE_CLOUD_PROJECT;
+ expect(isConfigured()).toBe(false);
+ await expect(generateImage('x')).rejects.toMatchObject({ code: 'unconfigured' });
+ });
+});
+
+describe('vertex-imagen — editImage routing', () => {
+ it('sends the source image as an inlineData part on the Gemini edit path', async () => {
+ const calls = stubFetch(() => geminiImageResponse());
+ const src = `data:image/png;base64,${Buffer.from('source').toString('base64')}`;
+ const result = await editImage(src, 'make it blue');
+
+ const { url, body } = calls[0];
+ expect(url).toContain('/models/gemini-2.5-flash-image:generateContent');
+ expect(body.contents[0].parts[0].text).toBe('make it blue');
+ expect(body.contents[0].parts[1].inlineData.data).toBe(Buffer.from('source').toString('base64'));
+ expect(result.model).toBe('vertex-ai/gemini-2.5-flash-image');
+ });
+});