Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: implement GCP credits management script and add vanity vault for secure key storage
fudjiad7e15ed04a86
diff --git a/api/_lib/gcp-billing.js b/api/_lib/gcp-billing.jsnew file mode 100644index 000000000..3981f592f--- /dev/null+++ b/api/_lib/gcp-billing.js@@ -0,0 +1,376 @@+// Cloud Billing → BigQuery burn attribution + projection.+//+// The $100k GCP credit program (prompts/gcp-credits/) burns across several+// lanes — Vertex Claude, Imagen, the self-host GPU forge fleet, vanity mining.+// This module reads the BigQuery billing export (line-item, label-attributable+// cost data) and turns it into an attributed burn report: credit consumed to+// date, spend by service, spend by lane label, daily burn rate, and — the+// number that actually matters — projected credit-exhaustion date vs the credit+// expiry date, plus the inverse failure mode (credits left unused at expiry).+//+// One implementation, three consumers:+// • scripts/gcp/burn-report.mjs — human-readable CLI + --json+// • api/cron/gcp-burn-report.js — daily ops ping+// • api/admin/gcp-burn.js — internal spend dashboard cross-ref+//+// Auth reuses the shared Vertex service account (api/_lib/gcp-auth.js,+// cloud-platform scope). In serverless (no gcloud/bq CLI) the query runs over+// the BigQuery REST jobs.query endpoint; the CLI script can also feed a token+// from `gcloud auth print-access-token` for local runs.+//+// Everything degrades to a designed error (BillingUnavailableError) rather than+// throwing raw when the export dataset isn't wired yet — a burn report that+// can't reach BigQuery must say so clearly, not 500.++import { getGcpAccessToken } from './gcp-auth.js';++const DAY_MS = 86_400_000;++// Credit types that represent the grant we're burning down. Sustained- and+// committed-use discounts on paid spend are excluded by default so the "credit+// consumed" number tracks the promotional/startup grant, not routine discounts.+// Override with GCP_CREDIT_TYPES (comma-separated) if the grant lands under a+// different credit type in this billing account.+const DEFAULT_CREDIT_TYPES = ['PROMOTION', 'FREE_TRIAL', 'COMMITTED_USAGE_DISCOUNT', 'SUBSCRIPTION_BENEFIT'];++// The label every program resource carries (prompts 02–06). Attribution hangs+// off this: `program=gcp-credits` scopes the burn, `lane=<name>` splits it.+export const PROGRAM_LABEL = 'gcp-credits';++// Known lanes, for display ordering + the under-utilization scale-up hints.+export const PROGRAM_LANES = Object.freeze({+ 'vertex-claude': { label: 'Vertex Claude', scaleUp: 'flip VERTEX_CLAUDE_PRIMARY on for production chat traffic' },+ imagen: { label: 'Imagen', scaleUp: 'route more forge image generations through Vertex Imagen' },+ 'forge-gpu': { label: 'Forge GPU fleet', scaleUp: 'raise seed-batch volume / min-instances on the Cloud Run GPU workers' },+ vanity: { label: 'Vanity mining', scaleUp: 'schedule larger vanity grinder runs' },+ '(unlabeled)': { label: 'Unlabeled', scaleUp: 'label the resource (scripts/gcp/label-resources.sh) so this spend is attributable' },+});++export class BillingUnavailableError extends Error {+ constructor(message, cause) {+ super(message);+ this.name = 'BillingUnavailableError';+ this.code = 'billing_unavailable';+ if (cause) this.cause = cause;+ }+}++function readEnv(name) {+ return (typeof process !== 'undefined' && process.env?.[name]) || null;+}++// Resolve the fully-qualified billing export table + program config from env.+// Throws BillingUnavailableError (not a raw error) when a required piece is+// missing so every caller can branch to a "not wired yet" state.+export function resolveBillingConfig(env = process.env) {+ const project = env.GOOGLE_CLOUD_PROJECT || env.GCP_BILLING_PROJECT || null;+ const dataset = env.GCP_BILLING_DATASET || null;+ // Standard export table name is derived from the billing account id with+ // dashes replaced by underscores. `resource` export prefixes with+ // `gcp_billing_export_resource_v1_`; standard uses `gcp_billing_export_v1_`.+ let table = env.GCP_BILLING_TABLE || null;+ if (!table && env.GCP_BILLING_ACCOUNT_ID) {+ const suffix = env.GCP_BILLING_ACCOUNT_ID.replace(/-/g, '_');+ const kind = (env.GCP_BILLING_EXPORT_KIND || 'standard').toLowerCase();+ const prefix = kind === 'resource' ? 'gcp_billing_export_resource_v1_' : 'gcp_billing_export_v1_';+ table = `${prefix}${suffix}`;+ }+ if (!project || !dataset || !table) {+ throw new BillingUnavailableError(+ 'BigQuery billing export not configured. Set GOOGLE_CLOUD_PROJECT, GCP_BILLING_DATASET, and GCP_BILLING_TABLE (or GCP_BILLING_ACCOUNT_ID). See docs/gcp-credits.md.',+ );+ }++ const creditTypes = (env.GCP_CREDIT_TYPES+ ? env.GCP_CREDIT_TYPES.split(',')+ : DEFAULT_CREDIT_TYPES+ )+ .map((t) => t.trim().toUpperCase())+ .filter((t) => /^[A-Z_]+$/.test(t)); // only well-formed enum tokens reach SQL++ const creditTotalUsd = Number(env.GCP_CREDIT_TOTAL_USD || 0) || null;+ const creditExpiry = env.GCP_CREDIT_EXPIRY ? new Date(env.GCP_CREDIT_EXPIRY) : null;++ return {+ project,+ dataset,+ table,+ fqTable: `\`${project}.${dataset}.${table}\``,+ creditTypes,+ creditTotalUsd,+ creditExpiry: creditExpiry && !Number.isNaN(creditExpiry.getTime()) ? creditExpiry : null,+ programLabel: env.GCP_CREDIT_PROGRAM || PROGRAM_LABEL,+ };+}++// True when the billing export is wired well enough to attempt a query.+export function billingConfigured(env = process.env) {+ try {+ resolveBillingConfig(env);+ return true;+ } catch {+ return false;+ }+}++// ── BigQuery REST query ─────────────────────────────────────────────────────++// Run one standard-SQL query via the BigQuery jobs.query REST endpoint and+// return rows as plain objects keyed by the SELECT aliases. `tokenFn` lets the+// CLI inject a `gcloud`-minted token; defaults to the shared SA token.+export async function queryBilling(query, { project, tokenFn = getGcpAccessToken, timeoutMs = 60_000 } = {}) {+ let token;+ try {+ token = await tokenFn();+ } catch (err) {+ throw new BillingUnavailableError(`GCP auth unavailable: ${err?.message || err}`, err);+ }++ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), timeoutMs);+ let res;+ try {+ res = await fetch(+ `https://bigquery.googleapis.com/bigquery/v2/projects/${encodeURIComponent(project)}/queries`,+ {+ method: 'POST',+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },+ body: JSON.stringify({ query, useLegacySql: false, timeoutMs: Math.min(timeoutMs, 55_000) }),+ signal: controller.signal,+ },+ );+ } catch (err) {+ throw new BillingUnavailableError(`BigQuery unreachable: ${err?.message || err}`, err);+ } finally {+ clearTimeout(timer);+ }++ const data = await res.json().catch(() => ({}));+ if (!res.ok) {+ const msg = data?.error?.message || `BigQuery returned ${res.status}`;+ // A missing dataset/table is the "not wired yet" case, not a hard fault.+ if (res.status === 404 || /Not found|does not exist/i.test(msg)) {+ throw new BillingUnavailableError(`Billing export table not found: ${msg}`);+ }+ throw new BillingUnavailableError(`BigQuery query failed: ${msg}`);+ }++ return mapRows(data);+}++// Map a jobs.query response { schema.fields[], rows[{ f:[{v}] }] } into plain+// row objects. Numeric-typed columns are coerced to Number; everything else+// stays a string (BigQuery returns all scalars as strings over REST).+function mapRows(data) {+ const fields = data?.schema?.fields || [];+ const rows = data?.rows || [];+ const numeric = new Set(['INTEGER', 'INT64', 'FLOAT', 'FLOAT64', 'NUMERIC', 'BIGNUMERIC']);+ return rows.map((r) => {+ const obj = {};+ (r.f || []).forEach((cell, i) => {+ const field = fields[i];+ if (!field) return;+ const raw = cell?.v;+ obj[field.name] = raw != null && numeric.has(field.type) ? Number(raw) : raw;+ });+ return obj;+ });+}++// SQL fragment: credit amount (negative) restricted to the grant credit types.+function creditSumExpr(creditTypes) {+ const list = creditTypes.map((t) => `'${t}'`).join(', ');+ const filter = list ? `WHERE c.type IN (${list})` : '';+ return `IFNULL((SELECT SUM(c.amount) FROM UNNEST(credits) c ${filter}), 0)`;+}++// ── Report assembly ─────────────────────────────────────────────────────────++// Build the full attributed burn report. Runs four aggregate queries in+// parallel, then folds in the pure projection math.+export async function buildBurnReport({ now = new Date(), env = process.env, tokenFn } = {}) {+ const cfg = resolveBillingConfig(env);+ const creditExpr = creditSumExpr(cfg.creditTypes);+ const q = (query) => queryBilling(query, { project: cfg.project, tokenFn });++ const totalsQ = `+ SELECT+ SUM(cost) AS gross_cost,+ -SUM(${creditExpr}) AS credit_used,+ MIN(usage_start_time) AS first_usage,+ MAX(usage_start_time) AS last_usage+ FROM ${cfg.fqTable}`;++ const byServiceQ = `+ SELECT+ service.description AS service,+ SUM(cost) AS gross,+ -SUM(${creditExpr}) AS credit_used+ FROM ${cfg.fqTable}+ GROUP BY service+ ORDER BY credit_used DESC+ LIMIT 25`;++ const byLaneQ = `+ SELECT+ IFNULL((SELECT l.value FROM UNNEST(labels) l WHERE l.key = 'lane'), '(unlabeled)') AS lane,+ IFNULL((SELECT l.value FROM UNNEST(labels) l WHERE l.key = 'program'), '(none)') AS program,+ SUM(cost) AS gross,+ -SUM(${creditExpr}) AS credit_used+ FROM ${cfg.fqTable}+ GROUP BY lane, program+ ORDER BY credit_used DESC+ LIMIT 50`;++ const dailyQ = `+ SELECT+ DATE(usage_start_time) AS day,+ SUM(cost) AS gross,+ -SUM(${creditExpr}) AS credit_used+ FROM ${cfg.fqTable}+ WHERE usage_start_time >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 30 DAY)+ GROUP BY day+ ORDER BY day`;++ const [totals, byService, byLane, daily] = await Promise.all([+ q(totalsQ),+ q(byServiceQ),+ q(byLaneQ),+ q(dailyQ),+ ]);++ const t = totals[0] || {};+ const creditUsed = Number(t.credit_used || 0);+ const grossCost = Number(t.gross_cost || 0);++ const avg7 = averageDailyBurn(daily, 7);+ const avg30 = averageDailyBurn(daily, 30);+ // Projection uses the shorter trailing window when it's meaningfully higher+ // (a lane just ramped) so a fresh runaway isn't averaged away by quiet weeks.+ const avgDailyBurn = Math.max(avg7, avg30 * 0.5) || avg30 || avg7;++ const projection = projectExhaustion({+ creditUsed,+ avgDailyBurn,+ creditTotal: cfg.creditTotalUsd,+ now,+ expiry: cfg.creditExpiry,+ });++ return {+ generatedAt: now.toISOString(),+ config: {+ project: cfg.project,+ dataset: cfg.dataset,+ table: cfg.table,+ creditTotalUsd: cfg.creditTotalUsd,+ creditExpiry: cfg.creditExpiry ? cfg.creditExpiry.toISOString() : null,+ creditTypes: cfg.creditTypes,+ },+ totals: {+ creditUsed,+ grossCost,+ firstUsage: t.first_usage || null,+ lastUsage: t.last_usage || null,+ },+ byService: byService.map((r) => ({+ service: r.service || '(unknown)',+ gross: Number(r.gross || 0),+ creditUsed: Number(r.credit_used || 0),+ })),+ byLane: byLane.map((r) => ({+ lane: r.lane || '(unlabeled)',+ program: r.program || '(none)',+ gross: Number(r.gross || 0),+ creditUsed: Number(r.credit_used || 0),+ })),+ daily: daily.map((r) => ({ day: r.day, gross: Number(r.gross || 0), creditUsed: Number(r.credit_used || 0) })),+ burn: { avg7dPerDay: avg7, avg30dPerDay: avg30, usedForProjection: avgDailyBurn },+ projection,+ };+}++// Average daily credit burn over the trailing `days` window of the daily rows.+// Pure; exported for tests.+export function averageDailyBurn(daily, days) {+ if (!Array.isArray(daily) || daily.length === 0) return 0;+ const window = daily.slice(-days);+ const sum = window.reduce((acc, r) => acc + Number(r.creditUsed ?? r.credit_used ?? 0), 0);+ // Divide by the window length actually requested (not rows present) so a+ // lane live for 3 of the last 7 days still reports a true 7-day daily rate.+ return sum / days;+}++// Pure projection: given credit consumed to date, an average daily burn, the+// total grant, and the expiry date, compute runway + the two failure modes+// (runaway before expiry, or >30% unused at expiry). Exported for tests.+export function projectExhaustion({ creditUsed, avgDailyBurn, creditTotal, now = new Date(), expiry }) {+ const nowMs = now instanceof Date ? now.getTime() : new Date(now).getTime();+ const expiryMs = expiry ? (expiry instanceof Date ? expiry.getTime() : new Date(expiry).getTime()) : null;+ const daysToExpiry = expiryMs != null ? Math.max(0, (expiryMs - nowMs) / DAY_MS) : null;++ const out = {+ creditTotalUsd: creditTotal ?? null,+ creditUsedUsd: creditUsed,+ remainingUsd: creditTotal != null ? Math.max(0, creditTotal - creditUsed) : null,+ avgDailyBurnUsd: avgDailyBurn,+ daysToExpiry,+ expiry: expiryMs != null ? new Date(expiryMs).toISOString() : null,+ daysRunway: null,+ exhaustionDate: null,+ projectedSpendByExpiryUsd: null,+ projectedUnusedUsd: null,+ projectedUnusedPct: null,+ status: 'unknown', // 'on-track' | 'runaway' | 'underutilized' | 'idle' | 'unknown'+ headline: '',+ };++ if (creditTotal == null) {+ out.headline = 'Set GCP_CREDIT_TOTAL_USD to enable runway + exhaustion projection.';+ return out;+ }++ const remaining = out.remainingUsd;++ if (avgDailyBurn <= 0) {+ out.daysRunway = Infinity;+ out.status = 'idle';+ out.projectedSpendByExpiryUsd = creditUsed;+ out.projectedUnusedUsd = remaining;+ out.projectedUnusedPct = creditTotal > 0 ? remaining / creditTotal : null;+ out.headline = 'No burn detected — credits are idle. Scale a lane up or they expire unused.';+ return out;+ }++ out.daysRunway = remaining / avgDailyBurn;+ out.exhaustionDate = new Date(nowMs + out.daysRunway * DAY_MS).toISOString();++ if (daysToExpiry != null) {+ const projectedSpend = Math.min(creditTotal, creditUsed + avgDailyBurn * daysToExpiry);+ out.projectedSpendByExpiryUsd = projectedSpend;+ out.projectedUnusedUsd = Math.max(0, creditTotal - projectedSpend);+ out.projectedUnusedPct = creditTotal > 0 ? out.projectedUnusedUsd / creditTotal : null;++ if (out.daysRunway < daysToExpiry) {+ out.status = 'runaway';+ out.headline = `On current burn, credits run out in ~${Math.round(out.daysRunway)}d — ${Math.round(daysToExpiry - out.daysRunway)}d BEFORE expiry. Throttle or the platform loses the free lane early.`;+ } else if (out.projectedUnusedPct > 0.3) {+ out.status = 'underutilized';+ out.headline = `At current burn ~${Math.round(out.projectedUnusedPct * 100)}% of the grant ($${Math.round(out.projectedUnusedUsd).toLocaleString()}) expires UNUSED. Scale up.`;+ } else {+ out.status = 'on-track';+ out.headline = `On track: ~${Math.round(out.projectedUnusedPct * 100)}% unused at expiry, ~${Math.round(out.daysRunway)}d runway.`;+ }+ } else {+ out.status = 'on-track';+ out.headline = `~${Math.round(out.daysRunway)}d of runway at current burn (set GCP_CREDIT_EXPIRY to check against the deadline).`;+ }++ return out;+}++// Human-readable USD.+export function usd(n) {+ if (n == null || Number.isNaN(n)) return '—';+ return `$${Number(n).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;+}diff --git a/api/_lib/llm.js b/api/_lib/llm.jsindex e7777238d..6a2c7ec5b 100644--- a/api/_lib/llm.js+++ b/api/_lib/llm.js@@ -190,6 +190,12 @@ function providerChain({ anthropicKey, anthropicModel, preferNvidia = false, nvi}));}if (anthropicKey) chain.push(anthropicProvider(anthropicKey, anthropicModel));+ // VERTEX_CLAUDE_PRIMARY: real Claude on GCP credits leads the chain, before+ // the free lanes — the platform's default brain becomes Vertex Claude. It+ // still sits behind a caller BYOK key (the caller's explicit billing choice)+ // and degrades to the free chain below on any Vertex failure. Model follows+ // the call site's Anthropic intent (anthropicModel), else the utility default.+ if (vertexClaudePrimary()) chain.push(vertexAnthropicProvider(anthropicModel));if (env.GROQ_API_KEY) {chain.push(openaiCompatProvider({name: 'groq',@@ -220,6 +226,13 @@ function providerChain({ anthropicKey, anthropicModel, preferNvidia = false, nvimodel: NVIDIA_MODEL,}));}+ // VERTEX_CLAUDE_ENABLED (without PRIMARY): Vertex Claude is a paid-tier+ // backstop, tried ahead of first-party Anthropic — GCP credits before a paid+ // Anthropic key. Skipped when it already leads (primary) so it's not added+ // twice, and when a BYOK key leads (the caller chose their own billing).+ if (!anthropicKey && vertexClaudeEnabled() && !vertexClaudePrimary()) {+ chain.push(vertexAnthropicProvider(anthropicModel));+ }// Paid backstops — always appended, never leading. Server Anthropic is// skipped when a BYOK key already leads the chain (the caller chose their// own Claude billing; the platform doesn't re-buy the same model for them).@@ -285,9 +298,13 @@ export async function llmComplete({ system, user, maxTokens = 1024, anthropicKeyconst startedAt = Date.now();let upstream;try {+ // Vertex resolves a fresh (cached) GCP OAuth token per request via an+ // async getHeaders; every other provider carries static headers. A+ // token-exchange failure throws here and is caught below → next provider.+ const headers = p.getHeaders ? await p.getHeaders() : p.headers;upstream = await fetch(p.url, {method: 'POST',- headers: p.headers,+ headers,body: JSON.stringify(p.buildBody(system, user, maxTokens)),signal: AbortSignal.timeout(timeoutMs),});diff --git a/api/_lib/vanity-inventory-pricing.js b/api/_lib/vanity-inventory-pricing.jsnew file mode 100644index 000000000..620247e1c--- /dev/null+++ b/api/_lib/vanity-inventory-pricing.js@@ -0,0 +1,60 @@+// Premium vanity inventory — the difficulty → price curve.+//+// The live grind tier is a flat ~$0.05 for ≤3 chars. Premium inventory sells+// 4–5+ char patterns that cost real batch CPU to find, so price scales with+// grind difficulty. We price on RARITY BITS (log2 of expected attempts, plus the+// dictionary/palindrome/bookend bonuses from src/solana/vanity/rarity.js) rather+// than raw attempts so a "real word" or palindrome automatically commands a+// premium the naive attempt count would miss.+//+// Curve: price = A·e^(B·bits), clamped to [MIN, MAX] = [$1, $50], then snapped to+// a clean price point. Anchored so:+// • ~2-char / ~11 bits → the $1 floor+// • 4-char / ~23 bits → ~$13+// • 5-char / ~29 bits → ~$45, i.e. near the $50 ceiling+// Each extra Base58 character is ~5.86 bits (58×) harder, so the curve roughly+// doubles the price every ~3.3 bits — tracking the exponential jump in grind cost+// while staying inside a sane retail band. Cloud spot CPU cost per address is a+// fraction of a cent even at 5 chars, so this is value-based pricing with a huge+// margin, not cost-plus — the point of grinding ahead on cheap credits.++import { computeRarity } from '../../src/solana/vanity/rarity.js';++export const MIN_PRICE_USD = 1;+export const MAX_PRICE_USD = 50;++// e^(B·bits) coefficients (see header for the anchor points they satisfy).+const A = 0.1014;+const B = 0.208;++/** Snap a raw price into a curated retail point (whole/half-dollar bands). */+function snapPrice(usd) {+ if (usd <= MIN_PRICE_USD) return MIN_PRICE_USD;+ if (usd >= MAX_PRICE_USD) return MAX_PRICE_USD;+ if (usd < 5) return Math.round(usd * 2) / 2; // nearest $0.50+ if (usd < 20) return Math.round(usd); // nearest $1+ return Math.round(usd / 5) * 5; // nearest $5+}++/**+ * Price a rarity breakdown (from computeRarity).+ * @param {{ rarityBits:number }} rarity+ * @returns {{ priceUsd:number, priceAtomics:number }}+ */+export function priceFromRarity(rarity) {+ const bits = Math.max(0, Number(rarity?.rarityBits) || 0);+ const raw = A * Math.exp(B * bits);+ const priceUsd = snapPrice(raw);+ return { priceUsd, priceAtomics: Math.round(priceUsd * 1_000_000) };+}++/**+ * Full pricing for a pattern: computes rarity, then price.+ * @param {{ prefix?:string, suffix?:string, ignoreCase?:boolean }} pattern+ * @returns {{ priceUsd:number, priceAtomics:number, rarity:object }}+ */+export function priceForPattern(pattern) {+ const rarity = computeRarity(pattern || {});+ const { priceUsd, priceAtomics } = priceFromRarity(rarity);+ return { priceUsd, priceAtomics, rarity };+}diff --git a/api/_lib/vanity-vault.js b/api/_lib/vanity-vault.jsnew file mode 100644index 000000000..17545d4db--- /dev/null+++ b/api/_lib/vanity-vault.js@@ -0,0 +1,169 @@+// Vanity inventory vault — the single seal/open primitive for pre-ground private+// keys held in `vanity_inventory`.+//+// WHY THIS EXISTS (and why not just secret-box directly):+// The platform's strongest at-rest primitive is api/_lib/secret-box.js —+// AES-256-GCM under a dedicated WALLET_ENCRYPTION_KEY with a random per-record+// salt, fail-closed in production. It already protects agent wallet keys and+// pump.fun creator keys, so it is the correct, consistent default here and IS+// strong enough against a DB dump (keys are unreadable without the env key).+//+// Inventory adds ONE threat secret-box alone does not address: INSIDER ACCESS.+// secret-box's key is an env var — anyone who can read the delivery service's+// environment can decrypt every stored key offline, forever. For a store whose+// entire value is unspent private keys, that is worth defense-in-depth. So this+// vault supports an OPTIONAL GCP-KMS ENVELOPE layer: a fresh 32-byte data-key+// (DEK) encrypts each payload with AES-256-GCM, and the DEK is wrapped by a KMS+// crypto key whose decrypt permission is granted (via IAM) ONLY to the delivery+// service identity. A DB dump then yields nothing; even the env key yields+// nothing without a KMS decrypt call that IAM can revoke and Cloud Audit Logs+// record. When VANITY_KMS_KEY is unset the vault transparently uses secret-box —+// no feature breaks, no plaintext is ever exposed either way.+//+// Both schemes are authenticated (AES-GCM), so a wrong key throws rather than+// returning garbage plaintext. Nothing in this module logs secret material.++import { webcrypto } from 'node:crypto';+import { encryptSecret, decryptSecret } from './secret-box.js';+import { getGcpAccessToken } from './gcp-auth.js';++const subtle = globalThis.crypto?.subtle || webcrypto.subtle;+const randomBytes = (n) => {+ const b = new Uint8Array(n);+ (globalThis.crypto || webcrypto).getRandomValues(b);+ return b;+};++// Scheme tags — persisted in vanity_inventory.secret_scheme and self-described in+// the ciphertext prefix so open() can dispatch even if the column drifts.+export const SCHEME_SECRETBOX = 'aes-256-gcm';+export const SCHEME_KMS_ENVELOPE = 'gcp-kms+aes-256-gcm';+const KMS_PREFIX = 'kms1:';++const readEnv = (name) =>+ typeof process !== 'undefined' && process.env?.[name] ? process.env[name].trim() : '';++// The KMS crypto-key resource name:+// projects/<P>/locations/<L>/keyRings/<R>/cryptoKeys/<K>+// When present (and reachable), sealing uses the envelope scheme.+export function kmsKeyName() {+ return readEnv('VANITY_KMS_KEY');+}++/** True when the KMS envelope layer is configured (does not prove reachability). */+export function kmsConfigured() {+ return Boolean(kmsKeyName());+}++/** The scheme sealSecret() will use given current configuration. */+export function preferredScheme() {+ return kmsConfigured() ? SCHEME_KMS_ENVELOPE : SCHEME_SECRETBOX;+}++// ── KMS REST: wrap/unwrap a 32-byte DEK ──────────────────────────────────────+// Uses the shared service-account OAuth token (api/_lib/gcp-auth.js) — the same+// credential Vertex uses. On Cloud Run / GCE the attached SA works with no env.+async function kmsEncrypt(dek) {+ const token = await getGcpAccessToken();+ const url = `https://cloudkms.googleapis.com/v1/${kmsKeyName()}:encrypt`;+ const res = await fetch(url, {+ method: 'POST',+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },+ body: JSON.stringify({ plaintext: Buffer.from(dek).toString('base64') }),+ });+ if (!res.ok) {+ const detail = await res.text().catch(() => res.status);+ throw new Error(`KMS encrypt failed (${res.status}): ${String(detail).slice(0, 300)}`);+ }+ const data = await res.json();+ return data.ciphertext; // base64 wrapped DEK+}++async function kmsDecrypt(wrappedDekB64) {+ const token = await getGcpAccessToken();+ const url = `https://cloudkms.googleapis.com/v1/${kmsKeyName()}:decrypt`;+ const res = await fetch(url, {+ method: 'POST',+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },+ body: JSON.stringify({ ciphertext: wrappedDekB64 }),+ });+ if (!res.ok) {+ const detail = await res.text().catch(() => res.status);+ throw new Error(`KMS decrypt failed (${res.status}): ${String(detail).slice(0, 300)}`);+ }+ const data = await res.json();+ return new Uint8Array(Buffer.from(data.plaintext, 'base64')); // 32-byte DEK+}++// AES-256-GCM under a raw 32-byte DEK. Layout inside the envelope: iv[12] || ct.+async function aesGcmEncryptRaw(dek, plaintext) {+ const key = await subtle.importKey('raw', dek, { name: 'AES-GCM' }, false, ['encrypt']);+ const iv = randomBytes(12);+ const ct = await subtle.encrypt({ name: 'AES-GCM', iv }, key, new TextEncoder().encode(plaintext));+ return { iv: Buffer.from(iv).toString('base64'), ct: Buffer.from(new Uint8Array(ct)).toString('base64') };+}++async function aesGcmDecryptRaw(dek, ivB64, ctB64) {+ const key = await subtle.importKey('raw', dek, { name: 'AES-GCM' }, false, ['decrypt']);+ const iv = new Uint8Array(Buffer.from(ivB64, 'base64'));+ const ct = new Uint8Array(Buffer.from(ctB64, 'base64'));+ const plain = await subtle.decrypt({ name: 'AES-GCM', iv }, key, ct);+ return new TextDecoder().decode(plain);+}++/**+ * Seal a plaintext secret for at-rest storage in vanity_inventory.+ *+ * @param {string} plaintext - the secret JSON/string (e.g. the 64-byte key + meta).+ * @returns {Promise<{ ciphertext: string, scheme: string }>}+ *+ * Uses the KMS envelope when VANITY_KMS_KEY is set, else secret-box. If the KMS+ * path is configured but the encrypt call fails, sealing FAILS CLOSED (throws) —+ * we never silently downgrade a key the operator asked KMS to protect. (The+ * unconfigured path is the deliberate, documented secret-box default.)+ */+export async function sealSecret(plaintext) {+ if (typeof plaintext !== 'string' || !plaintext) {+ throw new Error('sealSecret: plaintext must be a non-empty string');+ }+ if (kmsConfigured()) {+ const dek = randomBytes(32);+ const { iv, ct } = await aesGcmEncryptRaw(dek, plaintext);+ const wrappedDek = await kmsEncrypt(dek);+ // Best-effort scrub of the DEK from memory after wrapping.+ dek.fill(0);+ const envelope = { v: 1, k: kmsKeyName(), dek: wrappedDek, iv, ct };+ const ciphertext = KMS_PREFIX + Buffer.from(JSON.stringify(envelope)).toString('base64');+ return { ciphertext, scheme: SCHEME_KMS_ENVELOPE };+ }+ const ciphertext = await encryptSecret(plaintext);+ return { ciphertext, scheme: SCHEME_SECRETBOX };+}++/**+ * Open a sealed secret. Dispatches on the ciphertext's own prefix first (robust+ * to a drifted scheme column), falling back to the provided scheme hint.+ *+ * @param {string} ciphertext+ * @param {string} [scheme]+ * @returns {Promise<string>} the plaintext secret.+ */+export async function openSecret(ciphertext, scheme) {+ if (typeof ciphertext !== 'string' || !ciphertext) {+ throw new Error('openSecret: missing ciphertext (already destroyed?)');+ }+ const isKms = ciphertext.startsWith(KMS_PREFIX) || scheme === SCHEME_KMS_ENVELOPE;+ if (isKms) {+ if (!ciphertext.startsWith(KMS_PREFIX)) {+ throw new Error('openSecret: scheme says KMS but ciphertext is not a KMS envelope');+ }+ const envelope = JSON.parse(Buffer.from(ciphertext.slice(KMS_PREFIX.length), 'base64').toString('utf8'));+ const dek = await kmsDecrypt(envelope.dek);+ try {+ return await aesGcmDecryptRaw(dek, envelope.iv, envelope.ct);+ } finally {+ dek.fill(0);+ }+ }+ return decryptSecret(ciphertext);+}diff --git a/api/_mcp3d/vertex-imagen.js b/api/_mcp3d/vertex-imagen.jsindex cd0a06728..f1e85c46c 100644--- a/api/_mcp3d/vertex-imagen.js+++ b/api/_mcp3d/vertex-imagen.js@@ -1,37 +1,55 @@-// Vertex AI Imagen text-to-image client.+// Vertex AI image-generation client for the 3D forge pipeline.//-// Calls Google's Imagen API (imagegeneration@006 or imagen-3.0-generate-001)-// with a text prompt and returns an image URL suitable for downstream-// image-to-3D reconstruction.+// Turns a text prompt into a reference image that the image-to-3D backend+// (TRELLIS / Hunyuan3D / TripoSR) reconstructs into a textured GLB. The+// reference image drives 3D quality, so this lane's output quality directly+// affects the paid product.//-// Why prefer this over Replicate flux-schnell when GCP credits are set:-// - Costs ~$0.02–0.04 per image versus ~$0.003 on Replicate, BUT the-// $100k GCP credit pool makes it effectively free for the operator.-// - Imagen 3 output quality is noticeably higher and reconstructs better.-// - Single dependency (GCP) instead of two API keys.+// Why route this through Vertex when GCP credits are set:+// - The $100k GCP credit pool makes it effectively free for the operator+// (raw list price ~$0.02–0.04/image vs ~$0.003 on Replicate).+// - Single dependency (GCP) instead of two third-party API keys.//-// Required env vars (at least one auth path must be present):-// GOOGLE_CLOUD_PROJECT — GCP project id-// GOOGLE_CLOUD_LOCATION — region (default: us-central1)-// GCP_SERVICE_ACCOUNT_JSON — service account key JSON as a string-// (set in Vercel secrets; alternative to-// GOOGLE_APPLICATION_CREDENTIALS file path)+// ── Model landscape (verified against Vertex docs, 2026-07) ────────────────+// Google is RETIRING the entire Imagen `:predict` family. The old defaults here+// are dead or dying:+// - imagen-3.0-generate-001 / -002, imagen-3.0-capability-001 (edit):+// shut down ~2026-06-30 (already past) — these 404 now.+// - imagen-4.0-generate-001 / -fast / -ultra: deprecated, discontinued+// 2026-06-30…2026-08-17. A dead end even where still callable.+// The recommended, still-live replacement is the Gemini image model+// `gemini-2.5-flash-image` ("Nano Banana"), which uses the `:generateContent`+// API shape (not `:predict`). It still bills to GCP credits, so it remains the+// credit-burner this lane was built to be — it just talks a different endpoint.//-// Model selection (first match wins):-// VERTEX_IMAGEN_MODEL — explicit override, e.g. "imagen-3.0-fast-generate-001"-// defaults to "imagen-3.0-generate-001" (best quality, ~8s)-// fast fallback: "imagen-3.0-fast-generate-001" (~3s, slightly lower quality)+// This client supports BOTH shapes and routes on the model id:+// - id starts with "gemini" → `:generateContent` (default, live)+// - id starts with "imagen" → legacy `:predict` (for an explicit override+// while any Imagen endpoint is still callable)//-// Output: base64 PNG returned inline in the API response, uploaded to R2/S3-// by the caller (same pattern as the Replicate path in text-to-image.js).+// ── Env vars ───────────────────────────────────────────────────────────────+// GOOGLE_CLOUD_PROJECT — GCP project id (required)+// GOOGLE_CLOUD_LOCATION — region (default: us-central1). Set to "global"+// for models only served on the global endpoint.+// GCP_SERVICE_ACCOUNT_JSON — service-account key JSON (via gcp-auth.js)+// VERTEX_IMAGEN_MODEL — override the generation model+// (default: gemini-2.5-flash-image)+// VERTEX_IMAGEN_EDIT_MODEL — override the edit model+// (default: gemini-2.5-flash-image)+//+// Output: a base64 image returned inline as a data: URI. The caller+// (text-to-image.js) uploads it to R2/S3 before handing it to the 3D backend.import { getGcpAccessToken } from '../_lib/gcp-auth.js';-const DEFAULT_MODEL = 'imagen-3.0-generate-001';+// Default to the live Gemini image model; the Imagen `:predict` ids it replaced+// are past or near their shutdown (see the model-landscape note above).+const DEFAULT_MODEL = 'gemini-2.5-flash-image';+const DEFAULT_EDIT_MODEL = 'gemini-2.5-flash-image';const DEFAULT_LOCATION = 'us-central1';-// Aspect ratio mappings: our internal format → Imagen's enum.-const ASPECT_MAP = {+// Aspect ratios the legacy Imagen `:predict` API accepts (our format → its enum).+const IMAGEN_ASPECT_MAP = {'1:1': '1:1','4:3': '4:3','3:4': '3:4',@@ -39,6 +57,11 @@ const ASPECT_MAP = {'9:16': '9:16',};+// Gemini image generation accepts a wider set via generationConfig.imageConfig.+const GEMINI_ASPECTS = new Set([+ '1:1', '3:2', '2:3', '3:4', '4:3', '4:5', '5:4', '9:16', '16:9', '21:9',+]);+function readEnv(name) {if (typeof process !== 'undefined' && process.env?.[name]) return process.env[name];return null;@@ -47,33 +70,94 @@ function readEnv(name) {// Token minting (service-account JWT→OAuth exchange, caching, metadata-server// fallback) is shared with the Vertex Claude transport — see api/_lib/gcp-auth.js.-// Return true if Vertex AI Imagen is configured (GCP project present).+// A model id is a Gemini image model (generateContent shape) unless it's an+// Imagen `:predict` model. Default and unknown ids take the Gemini path.+function isImagenPredictModel(model) {+ return /^imagen/i.test(model);+}++// Vertex's `global` location is served from the un-prefixed host; every regional+// location uses a `${region}-` prefix. Getting this wrong yields a DNS failure.+function aiplatformHost(location) {+ return location === 'global'+ ? 'https://aiplatform.googleapis.com'+ : `https://${location}-aiplatform.googleapis.com`;+}++// Map a fetch/HTTP failure onto the same designed error codes the caller's+// fallback ladder already branches on (rate_limited / provider_unreachable /+// providerStatus), so a broken Vertex call degrades to FLUX cleanly.+function throwVertexHttpError(res, data, label) {+ const message =+ data?.error?.message || data?.message || `Vertex AI ${label} returned ${res.status}`;+ if (res.status === 429) {+ throw Object.assign(new Error(message), { code: 'rate_limited', retryAfter: 10 });+ }+ throw Object.assign(new Error(message), { providerStatus: res.status });+}++// Return true if the Vertex image lane is configured (GCP project present).export function isConfigured() {return Boolean(readEnv('GOOGLE_CLOUD_PROJECT'));}-// Generate an image from a text prompt using Vertex AI Imagen.+// Generate an image from a text prompt.//-// Returns { imageUrl, model } where imageUrl is a data: URI containing-// the base64-encoded PNG. The caller is responsible for uploading it to-// permanent storage if needed (the forge pipeline does this).+// Returns { imageUrl, model } where imageUrl is a data: URI containing the+// base64-encoded image. The caller uploads it to permanent storage.export async function generateImage(prompt, { aspectRatio = '1:1' } = {}) {const project = readEnv('GOOGLE_CLOUD_PROJECT');if (!project) {throw Object.assign(- new Error('Vertex AI Imagen is not configured (GOOGLE_CLOUD_PROJECT missing)'),+ new Error('Vertex AI image lane is not configured (GOOGLE_CLOUD_PROJECT missing)'),{ code: 'unconfigured' },);}const location = readEnv('GOOGLE_CLOUD_LOCATION') || DEFAULT_LOCATION;const model = readEnv('VERTEX_IMAGEN_MODEL') || DEFAULT_MODEL;- const aspectEnum = ASPECT_MAP[aspectRatio] || '1:1';-const token = await getGcpAccessToken();+ return isImagenPredictModel(model)+ ? generateViaImagenPredict({ prompt, aspectRatio, project, location, model, token })+ : generateViaGemini({ prompt, aspectRatio, project, location, model, token });+}++// ── Gemini image (generateContent) — the live default path ──────────────────+async function generateViaGemini({ prompt, aspectRatio, project, location, model, token }) {+ const aspect = GEMINI_ASPECTS.has(aspectRatio) ? aspectRatio : '1:1';const endpoint =- `https://${location}-aiplatform.googleapis.com/v1/projects/${project}` ++ `${aiplatformHost(location)}/v1/projects/${project}` ++ `/locations/${location}/publishers/google/models/${model}:generateContent`;++ const body = {+ contents: [{ role: 'user', parts: [{ text: prompt }] }],+ generationConfig: {+ responseModalities: ['IMAGE'],+ imageConfig: { aspectRatio: aspect },+ },+ };++ const data = await postJson(endpoint, body, token, 'image generation');+ const parts = data?.candidates?.[0]?.content?.parts || [];+ const imgPart = parts.find((p) => p?.inlineData?.data);+ const b64 = imgPart?.inlineData?.data;+ if (!b64) {+ // A safety block returns candidates with no image part and a finishReason.+ const reason = data?.candidates?.[0]?.finishReason;+ throw new Error(+ `Vertex Gemini returned no image data${reason ? ` (finishReason: ${reason})` : ''}`,+ );+ }+ const mime = imgPart.inlineData.mimeType || 'image/png';+ return { imageUrl: `data:${mime};base64,${b64}`, model: `vertex-ai/${model}` };+}++// ── Imagen (predict) — legacy path for an explicit imagen-* override ─────────+async function generateViaImagenPredict({ prompt, aspectRatio, project, location, model, token }) {+ const aspectEnum = IMAGEN_ASPECT_MAP[aspectRatio] || '1:1';+ const endpoint =+ `${aiplatformHost(location)}/v1/projects/${project}` +`/locations/${location}/publishers/google/models/${model}:predict`;const body = {@@ -81,15 +165,22 @@ export async function generateImage(prompt, { aspectRatio = '1:1' } = {}) {parameters: {sampleCount: 1,aspectRatio: aspectEnum,- // Enhance the prompt for 3D reconstruction: clean background,- // single subject, even lighting. This dramatically improves the- // quality of the downstream image-to-3D step.addWatermark: false,safetySetting: 'block_some',personGeneration: 'allow_adult',},};+ const data = await postJson(endpoint, body, token, 'image generation');+ const b64 = data?.predictions?.[0]?.bytesBase64Encoded;+ if (!b64) throw new Error('Vertex AI returned no image data');+ return { imageUrl: `data:image/png;base64,${b64}`, model: `vertex-ai/${model}` };+}++// POST a JSON body to Vertex and return the parsed response. Throws a designed+// error (rate_limited / provider_unreachable / providerStatus) on any failure so+// the caller's fallback ladder can branch on it.+async function postJson(endpoint, body, token, label) {let res;try {res = await fetch(endpoint, {@@ -102,72 +193,77 @@ export async function generateImage(prompt, { aspectRatio = '1:1' } = {}) {});} catch (err) {throw Object.assign(- new Error(`Vertex AI Imagen unreachable: ${err?.message}`),+ new Error(`Vertex AI ${label} unreachable: ${err?.message}`),{ code: 'provider_unreachable' },);}-const data = await res.json().catch(() => ({}));-- if (!res.ok) {- const message =- data?.error?.message || data?.message || `Vertex AI returned ${res.status}`;- if (res.status === 429) {- throw Object.assign(new Error(message), {- code: 'rate_limited',- retryAfter: 10,- });- }- throw Object.assign(new Error(message), { providerStatus: res.status });- }-- const prediction = data?.predictions?.[0];- const b64 = prediction?.bytesBase64Encoded;- if (!b64) {- throw new Error('Vertex AI returned no image data');- }-- // Return as a data URI so the caller can either use it directly or- // upload it to object storage. The data URI is also accepted by- // TRELLIS, Hunyuan3D, and TripoSR as an image source.- const imageUrl = `data:image/png;base64,${b64}`;- return { imageUrl, model: `vertex-ai/${model}` };+ if (!res.ok) throwVertexHttpError(res, data, label);+ return data;}-// Edit an existing image using Imagen's inpainting / editing capability.-// Works with Imagen 3 Edit models.+// Edit an existing image. Routes the same way as generation: a Gemini model+// takes an image + instruction via generateContent; an explicit imagen-* edit+// model takes the legacy `:predict` inpainting/product shape.//// Returns { imageUrl, model }.export async function editImage(imageUrl, prompt, { maskUrl = null } = {}) {const project = readEnv('GOOGLE_CLOUD_PROJECT');if (!project) {throw Object.assign(- new Error('Vertex AI Imagen is not configured (GOOGLE_CLOUD_PROJECT missing)'),+ new Error('Vertex AI image lane is not configured (GOOGLE_CLOUD_PROJECT missing)'),{ code: 'unconfigured' },);}const location = readEnv('GOOGLE_CLOUD_LOCATION') || DEFAULT_LOCATION;- // Use the edit-specific model; fall back to base if not set.- const model =- readEnv('VERTEX_IMAGEN_EDIT_MODEL') || 'imagen-3.0-capability-001';-+ const model = readEnv('VERTEX_IMAGEN_EDIT_MODEL') || DEFAULT_EDIT_MODEL;const token = await getGcpAccessToken();+ const sourceB64 = await imageToBase64(imageUrl);++ return isImagenPredictModel(model)+ ? editViaImagenPredict({ sourceB64, prompt, maskUrl, project, location, model, token })+ : editViaGemini({ sourceB64, prompt, project, location, model, token });+}++async function imageToBase64(imageUrl) {+ if (imageUrl.startsWith('data:')) return imageUrl.split(',')[1];+ const { fetch_remote_bytes } = await import('../_lib/fetch-bytes.js').catch(() => ({}));+ if (!fetch_remote_bytes) throw new Error('cannot fetch image for editing');+ const bytes = await fetch_remote_bytes(imageUrl);+ return Buffer.from(bytes).toString('base64');+}++async function editViaGemini({ sourceB64, prompt, project, location, model, token }) {const endpoint =- `https://${location}-aiplatform.googleapis.com/v1/projects/${project}` +- `/locations/${location}/publishers/google/models/${model}:predict`;+ `${aiplatformHost(location)}/v1/projects/${project}` ++ `/locations/${location}/publishers/google/models/${model}:generateContent`;+ const body = {+ contents: [+ {+ role: 'user',+ parts: [+ { text: prompt },+ { inlineData: { mimeType: 'image/png', data: sourceB64 } },+ ],+ },+ ],+ generationConfig: { responseModalities: ['IMAGE'] },+ };+ const data = await postJson(endpoint, body, token, 'edit');+ const parts = data?.candidates?.[0]?.content?.parts || [];+ const imgPart = parts.find((p) => p?.inlineData?.data);+ const b64 = imgPart?.inlineData?.data;+ if (!b64) throw new Error('Vertex Gemini edit returned no image data');+ const mime = imgPart.inlineData.mimeType || 'image/png';+ return { imageUrl: `data:${mime};base64,${b64}`, model: `vertex-ai/${model}` };+}- // Fetch source image as base64 if it's a URL- let sourceB64;- if (imageUrl.startsWith('data:')) {- sourceB64 = imageUrl.split(',')[1];- } else {- const { fetch_remote_bytes } = await import('../_lib/fetch-bytes.js').catch(() => ({}));- if (!fetch_remote_bytes) throw new Error('cannot fetch image for editing');- const bytes = await fetch_remote_bytes(imageUrl);- sourceB64 = Buffer.from(bytes).toString('base64');- }+async function editViaImagenPredict({ sourceB64, prompt, maskUrl, project, location, model, token }) {+ const endpoint =+ `${aiplatformHost(location)}/v1/projects/${project}` ++ `/locations/${location}/publishers/google/models/${model}:predict`;const instance = {prompt,@@ -175,12 +271,9 @@ export async function editImage(imageUrl, prompt, { maskUrl = null } = {}) {editConfig: { editMode: maskUrl ? 'inpainting-insert' : 'product-image' },};if (maskUrl) {- // maskUrl is expected to be a data URI or https URL of a grayscale maskconst maskB64 = maskUrl.startsWith('data:')? maskUrl.split(',')[1]- : Buffer.from(- await fetch(maskUrl).then((r) => r.arrayBuffer()),- ).toString('base64');+ : Buffer.from(await fetch(maskUrl).then((r) => r.arrayBuffer())).toString('base64');instance.mask = { image: { bytesBase64Encoded: maskB64 } };}@@ -188,22 +281,7 @@ export async function editImage(imageUrl, prompt, { maskUrl = null } = {}) {instances: [instance],parameters: { sampleCount: 1, safetySetting: 'block_some' },};-- const res = await fetch(endpoint, {- method: 'POST',- headers: {- authorization: `Bearer ${token}`,- 'content-type': 'application/json',- },- body: JSON.stringify(body),- });-- const data = await res.json().catch(() => ({}));- if (!res.ok) {- const msg = data?.error?.message || `Vertex AI edit returned ${res.status}`;- throw Object.assign(new Error(msg), { providerStatus: res.status });- }-+ const data = await postJson(endpoint, body, token, 'edit');const b64 = data?.predictions?.[0]?.bytesBase64Encoded;if (!b64) throw new Error('Vertex AI edit returned no image data');return { imageUrl: `data:image/png;base64,${b64}`, model: `vertex-ai/${model}` };diff --git a/api/llm/anthropic.js b/api/llm/anthropic.jsindex 02318f27a..2c20b406e 100644--- a/api/llm/anthropic.js+++ b/api/llm/anthropic.js@@ -24,6 +24,12 @@ import {defaultEmbedPolicy,} from '../_lib/embed-policy.js';import { getAvatar } from '../_lib/avatars.js';+import {+ vertexClaudeEnabled,+ vertexMessagesUrl,+ vertexRequestHeaders,+ toVertexBody,+} from '../_lib/vertex-claude.js';const log = logger('llm.anthropic');diff --git a/scripts/gcp/revert-to-free.sh b/scripts/gcp/revert-to-free.shnew file mode 100755index 000000000..65563d7d5--- /dev/null+++ b/scripts/gcp/revert-to-free.sh@@ -0,0 +1,200 @@+#!/usr/bin/env bash+#+# revert-to-free.sh — flip every credit-funded GCP reroute back to its+# pre-program provider by REMOVING env vars. Never migrates code.+#+# The GCP $THREE credit program routed three real, shipped lanes onto Google+# infrastructure, each behind an env-var gate with an automatic fall-through to+# the provider it displaced:+#+# Lane GCP env gate (present ⇒ lane live) Falls back to+# ─────────────────────────────────────────────────────────────────────────────+# Forge image→3D (native) MODEL_TRELLIS_URL + GCP_RECON_KEY free NIM/HF, then Replicate+# Forge image→3D (hi-poly) GCP_HUNYUAN3D_URL + GCP_RECON_KEY free HF Spaces, then Replicate+# Forge sketch→3D GCP_TRIPOSG_URL + GCP_RECON_KEY (no fallback — lane simply off)+# Game-Ready remesh export GCP_REMESH_URL + GCP_RECON_KEY (export hidden until reconfigured)+# 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+#+# 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.+#+# 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.+#+# Usage:+# scripts/gcp/revert-to-free.sh # dry-run: print the plan, change nothing+# scripts/gcp/revert-to-free.sh --apply # run the Cloud Run min-instances=0 updates+# scripts/gcp/revert-to-free.sh --apply --yes # …without the confirm prompt+#+# Idempotent: running it twice is a no-op the second time (min-instances already+# 0, env vars already the ones you're told to remove). Safe to re-run.+#+# Env (only used with --apply, for the Cloud Run half):+# PROJECT_ID GCP project the workers live in (default: gcloud's active project)+# REGION Cloud Run region (default: us-central1)+# SERVICES space-separated Cloud Run service names to zero out+# (default: the full known worker set)++set -euo pipefail++# ── args ──────────────────────────────────────────────────────────────────────+APPLY=0+ASSUME_YES=0+for arg in "$@"; do+ case "$arg" in+ --apply) APPLY=1 ;;+ --dry-run) APPLY=0 ;;+ --yes|-y) ASSUME_YES=1 ;;+ -h|--help) sed -n '2,55p' "$0"; exit 0 ;;+ *) echo "unknown flag: $arg (try --help)" >&2; exit 2 ;;+ esac+done++REGION="${REGION:-us-central1}"+SERVICES="${SERVICES:-model-trellis model-hunyuan3d model-triposr model-triposg unirig avatar-pipeline-controller rembg remesh texture segment}"++# ── styling ───────────────────────────────────────────────────────────────────+bold() { printf '\033[1m%s\033[0m\n' "$*"; }+dim() { printf '\033[2m%s\033[0m\n' "$*"; }+warn() { printf '\033[33m%s\033[0m\n' "$*"; }+ok() { printf '\033[32m%s\033[0m\n' "$*"; }++if [ "$APPLY" -eq 1 ]; then+ bold "▶ revert-to-free — APPLY mode (Cloud Run min-instances → 0)"+else+ bold "▶ revert-to-free — DRY RUN (nothing will change; re-run with --apply to execute)"+fi+echo++# ── the env vars that gate each GCP lane, grouped by what removing them reverts ─+# Keep this list in sync with .env.example and the *_URL gates read in api/.+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)++# ── 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"+echo+# Avatar reconstruct/rerig falls back to Replicate then HF. If NEITHER is set,+# removing GCP_RECONSTRUCTION_URL turns avatar reconstruction OFF. Warn loudly.+if [ -z "${REPLICATE_API_TOKEN:-}" ] && [ -z "${HF_TOKEN:-}" ]; then+ warn " ⚠ Avatar reconstruct/rerig: neither REPLICATE_API_TOKEN nor HF_TOKEN is set in this shell."+ warn " After revert, api/_lib/regen-provider.js resolveProviderName() returns 'none' and"+ warn " avatar reconstruction stops working. Set REPLICATE_API_TOKEN (or HF_TOKEN) in Vercel"+ warn " BEFORE removing GCP_RECONSTRUCTION_URL. (This check reads THIS shell — verify prod env too.)"+else+ ok " ✓ Avatar reconstruct/rerig has a non-GCP fallback available (Replicate and/or HF)."+fi+# Forge image→3D falls back to the free NIM/HF lanes; sketch/remesh just turn off.+if [ -z "${NVIDIA_API_KEY:-}" ] && [ -z "${HF_TOKEN:-}" ] && [ -z "${REPLICATE_API_TOKEN:-}" ]; then+ warn " ⚠ Forge image→3D: no NVIDIA_API_KEY, HF_TOKEN, or REPLICATE_API_TOKEN in this shell —"+ warn " after revert there is no image→3D engine at all. Configure at least NVIDIA_API_KEY (free)."+else+ ok " ✓ Forge image→3D has a non-GCP engine available (free NIM/HF and/or Replicate)."+fi+if [ -z "${NVIDIA_API_KEY:-}" ] && [ -z "${REPLICATE_API_TOKEN:-}" ]; then+ warn " ⚠ Imagen text→image: no NVIDIA_API_KEY (free FLUX) or REPLICATE_API_TOKEN backstop —"+ warn " after revert, image synthesis for text prompts has no provider. Set NVIDIA_API_KEY."+else+ ok " ✓ Imagen text→image has a non-GCP provider available (free NIM FLUX and/or Replicate)."+fi+echo+dim " Sketch→3D (GCP_TRIPOSG_URL) and Game-Ready remesh (GCP_REMESH_URL) have no non-GCP"+dim " equivalent — reverting simply hides those two options from the forge catalog. No error;"+dim " the UI stops advertising them (backendIsConfigured / outputIsConfigured return false)."+echo++# ── Step 2: the Vercel env removals (printed — run these yourself) ─────────────+bold "2) Remove the GCP env gates from Vercel (production + preview)"+echo+dim " Paste these. Each 'vercel env rm' prompts for confirm unless you add -y."+dim " Removing the gate is the revert — the resolver falls through to the provider it displaced."+echo+print_rm() {+ local group_label="$1"; shift+ echo " # ${group_label}"+ for v in "$@"; do+ printf ' vercel env rm %s production\n' "$v"+ printf ' vercel env rm %s preview\n' "$v"+ done+ echo+}+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 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)."+echo+dim " After removing, redeploy so the functions pick up the new env:"+dim " vercel --prod"+echo++# ── Step 3: Cloud Run min-instances → 0 (the only ongoing GPU bill) ───────────+bold "3) Drop every Cloud Run worker to min-instances=0 (stop warm-GPU billing)"+echo+dim " The deploy scripts (workers/deploy/*.sh) never set --min-instances, so services"+dim " deploy at Cloud Run's default of 0 (scale-to-zero) already. This step is a belt-and-"+dim " -suspenders confirm: it is a no-op on a service that is already at 0."+echo++if [ "$APPLY" -eq 1 ]; then+ command -v gcloud >/dev/null 2>&1 || { warn " gcloud not on PATH — skipping Cloud Run step. Install gcloud or run this half on a machine that has it."; APPLY_CR=0; }+ APPLY_CR="${APPLY_CR:-1}"+ if [ "${APPLY_CR}" -eq 1 ]; then+ if ! gcloud auth print-access-token >/dev/null 2>&1; then+ warn " gcloud is not authenticated — run 'gcloud auth login'. Skipping Cloud Run step."+ else+ PROJECT_ID="${PROJECT_ID:-$(gcloud config get-value project 2>/dev/null)}"+ [ -n "$PROJECT_ID" ] || { warn " No PROJECT_ID and no active gcloud project — skipping."; PROJECT_ID=""; }+ if [ -n "$PROJECT_ID" ]; then+ echo " project=$PROJECT_ID region=$REGION"+ if [ "$ASSUME_YES" -ne 1 ]; then+ read -r -p " Set min-instances=0 on: $SERVICES ? [y/N] " reply+ case "$reply" in y|Y|yes|YES) ;; *) warn " aborted by user"; exit 0 ;; esac+ fi+ for svc in $SERVICES; do+ if gcloud run services describe "$svc" --region "$REGION" --project "$PROJECT_ID" >/dev/null 2>&1; then+ printf ' → %s: ' "$svc"+ if gcloud run services update "$svc" --region "$REGION" --project "$PROJECT_ID" \+ --min-instances=0 --quiet >/dev/null 2>&1; then+ ok "min-instances=0"+ else+ warn "update failed (check IAM / service state)"+ fi+ else+ dim " · $svc: not found in $PROJECT_ID/$REGION — skipping"+ fi+ done+ fi+ fi+ fi+else+ echo " Would run, for each existing service in [$SERVICES]:"+ echo " gcloud run services update <svc> --region $REGION --min-instances=0 --quiet"+fi+echo++# ── Step 4: what to verify after ──────────────────────────────────────────────+bold "4) Verify the revert took (no GCP dependency left in the hot path)"+echo+dim " • curl \"\$SITE/api/forge?catalog=1\" — every backend with a GCP requiresEnv shows"+dim " configured:false; free NIM/HF lanes show configured:true. UI stops offering GCP lanes."+dim " • Generate a text→3D (free NIM) and a photo→3D (free HF) — both succeed."+dim " • Generate an avatar — reconstruct routes to Replicate/HF (check the response provider)."+dim " • A text→image request returns from nvidia (NIM FLUX), not vertex-ai/*."+dim " • GCP billing: after min-instances=0 and no traffic, Cloud Run GPU spend trends to \$0."+echo+ok "Revert plan complete. Nothing on three.ws should break — every GCP lane hands off to the"+ok "provider it displaced. Keep the credits' durable output (R2 assets, vanity inventory) — it"+ok "does not depend on any GCP resource. See docs/gcp-credits.md for the keep/kill cost math and"+ok "scripts/gcp/teardown.sh for deleting the (now idle) GCP resources when you're ready."diff --git a/scripts/gcp/teardown.sh b/scripts/gcp/teardown.shnew file mode 100755index 000000000..c0e29ed6e--- /dev/null+++ b/scripts/gcp/teardown.sh@@ -0,0 +1,173 @@+#!/usr/bin/env bash+#+# teardown.sh — delete the GCP resources the $THREE credit program stood up, so+# nothing keeps billing after the credits expire. DRY-RUN BY DEFAULT: it lists+# what it *would* delete and changes nothing until you pass --apply.+#+# Run this ONLY after scripts/gcp/revert-to-free.sh is done and verified — i.e.+# every lane is serving from its non-GCP fallback and no traffic hits these+# services. Deleting first would break live features.+#+# What it removes (matches what workers/deploy/*.sh created):+# • Cloud Run services — the GPU workers + the avatar-pipeline-controller+# • Artifact Registry — the docker repo their images live in+# • GCS buckets — WEIGHTS bucket (model weights) always safe to delete;+# OUTPUT bucket only with --include-output (see warning)+# • Secret Manager secret — the worker bearer key+# • Service account — the Cloud Run runtime SA+#+# What it NEVER touches (durable assets that outlive the credits):+# • R2 — every user-facing GLB / avatar / animation is persisted to R2, not GCS.+# • The Firestore (default) DB — may hold job history; deleting a DB is+# irreversible and out of scope. Listed as a manual decision, never auto-deleted.+# • Vanity inventory — lives in the app DB / R2, independent of GCP.+#+# Usage:+# scripts/gcp/teardown.sh # dry-run: list everything, delete nothing+# scripts/gcp/teardown.sh --apply # delete Cloud Run + registry + weights bucket + secret + SA+# scripts/gcp/teardown.sh --apply --include-output # ALSO delete the OUTPUT bucket (see warning)+# scripts/gcp/teardown.sh --apply --yes # skip the confirm prompt+#+# Env:+# PROJECT_ID (default: gcloud active project)+# REGION (default: us-central1)+# SERVICES Cloud Run services to delete (default: full known set)+# WEIGHTS_BUCKET (default: three-ws-model-weights)+# OUTPUT_BUCKET (default: three-ws-avatar-reconstructions)+# ARTIFACT_REPO (default: three-ws-workers)+# SECRET_NAME (default: avatar-reconstruction-key)+# RUN_SA_NAME (default: avatar-reconstruction-sa)++set -euo pipefail++APPLY=0; ASSUME_YES=0; INCLUDE_OUTPUT=0+for arg in "$@"; do+ case "$arg" in+ --apply) APPLY=1 ;;+ --dry-run) APPLY=0 ;;+ --include-output) INCLUDE_OUTPUT=1 ;;+ --yes|-y) ASSUME_YES=1 ;;+ -h|--help) sed -n '2,50p' "$0"; exit 0 ;;+ *) echo "unknown flag: $arg (try --help)" >&2; exit 2 ;;+ esac+done++REGION="${REGION:-us-central1}"+SERVICES="${SERVICES:-model-trellis model-hunyuan3d model-triposr model-triposg unirig avatar-pipeline-controller rembg remesh texture segment}"+WEIGHTS_BUCKET="${WEIGHTS_BUCKET:-three-ws-model-weights}"+OUTPUT_BUCKET="${OUTPUT_BUCKET:-three-ws-avatar-reconstructions}"+ARTIFACT_REPO="${ARTIFACT_REPO:-three-ws-workers}"+SECRET_NAME="${SECRET_NAME:-avatar-reconstruction-key}"+RUN_SA_NAME="${RUN_SA_NAME:-avatar-reconstruction-sa}"++bold() { printf '\033[1m%s\033[0m\n' "$*"; }+dim() { printf '\033[2m%s\033[0m\n' "$*"; }+warn() { printf '\033[33m%s\033[0m\n' "$*"; }+ok() { printf '\033[32m%s\033[0m\n' "$*"; }+del() { printf '\033[31m%s\033[0m\n' "$*"; }++command -v gcloud >/dev/null 2>&1 || { echo "gcloud not found on PATH" >&2; exit 1; }+gcloud auth print-access-token >/dev/null 2>&1 || { echo "gcloud not authenticated — run 'gcloud auth login'" >&2; exit 1; }+PROJECT_ID="${PROJECT_ID:-$(gcloud config get-value project 2>/dev/null)}"+[ -n "$PROJECT_ID" ] || { echo "No PROJECT_ID and no active gcloud project" >&2; exit 1; }+RUN_SA="${RUN_SA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com"++if [ "$APPLY" -eq 1 ]; then+ bold "▶ teardown — APPLY mode. Resources below WILL BE DELETED."+else+ bold "▶ teardown — DRY RUN. Nothing is deleted. Re-run with --apply to execute."+fi+echo " project=$PROJECT_ID region=$REGION"+echo++# Guard: make sure the revert ran first. If any forge/imagen gate var is still in+# your shell, you may not have reverted prod — warn, don't block (env lives in Vercel).+if [ -n "${MODEL_TRELLIS_URL:-}${GCP_RECONSTRUCTION_URL:-}${GOOGLE_CLOUD_PROJECT:-}" ]; then+ warn " ⚠ GCP gate vars are still set in THIS shell. Confirm scripts/gcp/revert-to-free.sh"+ warn " has been applied to PRODUCTION (Vercel) and traffic has drained before deleting."+ echo+fi++# Helper: describe existence, then delete (or print) per resource.+run_or_echo() {+ # $1 = human label, rest = the command+ local label="$1"; shift+ if [ "$APPLY" -eq 1 ]; then+ printf ' '; del "DELETE $label"+ "$@" --quiet || warn " (failed — may already be gone or blocked by IAM)"+ else+ printf ' would delete: %s\n' "$label"+ dim " \$ $*"+ fi+}++# ── 1) Cloud Run services ─────────────────────────────────────────────────────+bold "1) Cloud Run services"+for svc in $SERVICES; do+ if gcloud run services describe "$svc" --region "$REGION" --project "$PROJECT_ID" >/dev/null 2>&1; then+ run_or_echo "run service $svc" gcloud run services delete "$svc" --region "$REGION" --project "$PROJECT_ID"+ else+ dim " · $svc — not present, skipping"+ fi+done+echo++# ── 2) Artifact Registry repo (the worker images) ─────────────────────────────+bold "2) Artifact Registry"+if gcloud artifacts repositories describe "$ARTIFACT_REPO" --location "$REGION" --project "$PROJECT_ID" >/dev/null 2>&1; then+ run_or_echo "artifact repo $ARTIFACT_REPO" gcloud artifacts repositories delete "$ARTIFACT_REPO" --location "$REGION" --project "$PROJECT_ID"+else+ dim " · $ARTIFACT_REPO — not present, skipping"+fi+echo++# ── 3) GCS buckets ────────────────────────────────────────────────────────────+bold "3) GCS buckets"+if gcloud storage buckets describe "gs://$WEIGHTS_BUCKET" --project "$PROJECT_ID" >/dev/null 2>&1; then+ run_or_echo "weights bucket gs://$WEIGHTS_BUCKET (model weights — re-downloadable, safe)" \+ gcloud storage rm --recursive "gs://$WEIGHTS_BUCKET"+else+ dim " · gs://$WEIGHTS_BUCKET — not present, skipping"+fi+if [ "$INCLUDE_OUTPUT" -eq 1 ]; then+ warn " ⚠ OUTPUT bucket gs://$OUTPUT_BUCKET is the pipeline's GCS handoff. User-facing assets"+ warn " are copied to R2, but confirm nothing serves gs:// URLs directly before deleting."+ if gcloud storage buckets describe "gs://$OUTPUT_BUCKET" --project "$PROJECT_ID" >/dev/null 2>&1; then+ run_or_echo "output bucket gs://$OUTPUT_BUCKET" gcloud storage rm --recursive "gs://$OUTPUT_BUCKET"+ else+ dim " · gs://$OUTPUT_BUCKET — not present, skipping"+ fi+else+ dim " · gs://$OUTPUT_BUCKET — kept (pass --include-output to delete; verify R2 copy first)"+fi+echo++# ── 4) Secret + service account ───────────────────────────────────────────────+bold "4) Secret Manager + service account"+if gcloud secrets describe "$SECRET_NAME" --project "$PROJECT_ID" >/dev/null 2>&1; then+ run_or_echo "secret $SECRET_NAME" gcloud secrets delete "$SECRET_NAME" --project "$PROJECT_ID"+else+ dim " · secret $SECRET_NAME — not present, skipping"+fi+if gcloud iam service-accounts describe "$RUN_SA" --project "$PROJECT_ID" >/dev/null 2>&1; then+ run_or_echo "service account $RUN_SA" gcloud iam service-accounts delete "$RUN_SA" --project "$PROJECT_ID"+else+ dim " · $RUN_SA — not present, skipping"+fi+echo++# ── 5) Manual decisions (never auto-deleted) ──────────────────────────────────+bold "5) Manual — decide, then run yourself (irreversible / out of scope)"+dim " • Firestore (default) DB — may hold job history. Delete only if you don't need it:"+dim " gcloud firestore databases delete --database='(default)' --project $PROJECT_ID"+dim " • The GCP project itself — if it exists solely for this program, shut it down last:"+dim " gcloud projects delete $PROJECT_ID"+dim " • Budget alerts / dashboards created for observability — remove in the console."+echo++if [ "$APPLY" -eq 1 ]; then+ ok "Teardown applied. Verify in the console that Cloud Run + Artifact Registry show no billable"+ ok "resources and that GCP billing for the project trends to \$0."+else+ bold "Dry run only — nothing deleted. Re-run with --apply (and --include-output if you're sure)."+fi