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: add OKX Agent Payments Protocol support and GCP burn reporting

fudjiaf5595005a046
diff --git a/api/_lib/env.js b/api/_lib/env.js
index f547c4ddb..d74456c60 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -740,6 +740,27 @@ export const env = {
get X402_ASSET_ADDRESS_BASE() {
return addr(opt('X402_ASSET_ADDRESS_BASE', '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'));
},
+ // ── OKX Agent Payments Protocol rail (X Layer, eip155:196) ──────────────
+ // payTo follows the same fail-closed rule: unset → the X Layer accept is
+ // not advertised. Production sets the agent #2632 owner wallet.
+ get X402_PAY_TO_XLAYER() {
+ return addr(opt('X402_PAY_TO_XLAYER'));
+ },
+ // USD₮0 on X Layer — the OKX.AI marketplace fee token (6 decimals,
+ // EIP-3009). Public constant, verified on-chain (symbol()/decimals() via
+ // eth_call) and against live approved-seller 402 challenges.
+ get X402_ASSET_ADDRESS_XLAYER() {
+ return addr(opt('X402_ASSET_ADDRESS_XLAYER', '0x779ded0c9e1022225f8e0630b35a9b54be713736'));
+ },
+ // Relayer private key that redeems buyers' EIP-3009 authorizations on
+ // X Layer (broadcasts transferWithAuthorization; pays OKB gas). In the OKX
+ // dialect the SELLER submits settlement — there is no external facilitator.
+ // Secret. Unset → X Layer accepts are not advertised (same
+ // never-advertise-what-we-can't-settle rule as baseSettleable /
+ // solanaSettleable).
+ get X402_XLAYER_RELAYER_KEY() {
+ return opt('X402_XLAYER_RELAYER_KEY');
+ },
// Price per /api/mcp call, in the asset's base units (USDC = 6 decimals; "1000" = 0.001 USDC).
get X402_MAX_AMOUNT_REQUIRED() {
return opt('X402_MAX_AMOUNT_REQUIRED', '1000');
diff --git a/api/_lib/x402-xlayer-okx.js b/api/_lib/x402-xlayer-okx.js
new file mode 100644
index 000000000..196ee057f
--- /dev/null
+++ b/api/_lib/x402-xlayer-okx.js
@@ -0,0 +1,490 @@
+// OKX Agent Payments Protocol rail — x402 `exact` + EIP-3009 on X Layer (chain 196).
+//
+// The OKX.AI marketplace (agents hire agents; A2MCP services) requires sellers
+// to speak its x402 v2 dialect on X Layer. The wire contract in
+// specs/okx-agent-payments.md is pinned to live captures from approved sellers
+// (Onchain Data Explorer, 174 sales) and the `onchainos` buyer CLI:
+//
+// 1. Unpaid request → HTTP 402. The envelope {x402Version:2, resource:{url,
+// mimeType}, accepts:[…]} ships BOTH as the JSON body and base64-encoded in
+// the `PAYMENT-REQUIRED` response header (plus
+// `access-control-expose-headers: PAYMENT-REQUIRED`).
+// 2. The accepts entry: { scheme:'exact', network:'eip155:196', amount:<base
+// units>, payTo, maxTimeoutSeconds:86400, asset:<USD₮0>, extra:{ symbol:
+// 'USDT', name:'USD₮0', version:'1', transferMethod:'eip3009' } }.
+// extra.name/version are the token's EIP-712 domain — USD₮0's on-chain
+// domain is name "USD₮0", version "1" (verified via eth_call).
+// 3. The buyer replays with `PAYMENT-SIGNATURE: <base64 JSON>` decoding to
+// { x402Version:2, accepted:<chosen accepts entry>, payload:{
+// authorization:{from,to,value,validAfter,validBefore,nonce}, signature },
+// resource } — note `accepted`, not the standard x402 top-level
+// scheme/network fields.
+// 4. Verification is seller-side and on-chain: EIP-712 signature recovery
+// (ERC-1271-aware — OKX agentic wallets may be smart accounts), recipient/
+// amount/time-window checks, unused authorizationState, and a balanceOf
+// check. Insufficient balance re-issues the 402 with top-level
+// error:"insufficient_balance" — the exact behavior captured from the
+// approved seller.
+// 5. Settlement: the SELLER redeems the authorization — broadcasts
+// transferWithAuthorization on the token from a relayer key (OKB gas).
+// There is no external facilitator in this scheme; per the protocol docs
+// "settlement happens on-chain when the recipient redeems the
+// authorization."
+//
+// This module is the X Layer sibling of x402-bsc-direct.js: verify/settle live
+// here, x402-spec.js routes to them by network, and callers keep the exact
+// verifyPayment()/settlePayment() surface they already use.
+
+import {
+ createPublicClient,
+ createWalletClient,
+ fallback,
+ getAddress,
+ http,
+} from 'viem';
+import { privateKeyToAccount } from 'viem/accounts';
+import { xLayer } from 'viem/chains';
+
+import { env } from './env.js';
+import { X402Error } from './x402-errors.js';
+
+export const NETWORK_XLAYER_MAINNET = 'eip155:196';
+export const XLAYER_CHAIN_ID = 196;
+
+// USD₮0's EIP-712 domain, verified on-chain (name()/symbol() both return
+// "USD₮0") and matched against the live approved-seller 402s (extra.name
+// "USD₮0", extra.version "1"). The ₮ is U+20AE — keep it exact: the domain
+// separator hashes the byte string.
+const USDT0_DOMAIN_NAME = 'USD₮0';
+const USDT0_DOMAIN_VERSION = '1';
+const USDT0_SYMBOL = 'USDT';
+
+// EIP-3009 typed data — the struct the buyer's wallet signs.
+const TRANSFER_WITH_AUTHORIZATION_TYPES = {
+ TransferWithAuthorization: [
+ { name: 'from', type: 'address' },
+ { name: 'to', type: 'address' },
+ { name: 'value', type: 'uint256' },
+ { name: 'validAfter', type: 'uint256' },
+ { name: 'validBefore', type: 'uint256' },
+ { name: 'nonce', type: 'bytes32' },
+ ],
+};
+
+const EIP3009_ABI = [
+ {
+ type: 'function',
+ name: 'transferWithAuthorization',
+ stateMutability: 'nonpayable',
+ inputs: [
+ { name: 'from', type: 'address' },
+ { name: 'to', type: 'address' },
+ { name: 'value', type: 'uint256' },
+ { name: 'validAfter', type: 'uint256' },
+ { name: 'validBefore', type: 'uint256' },
+ { name: 'nonce', type: 'bytes32' },
+ { name: 'signature', type: 'bytes' },
+ ],
+ outputs: [],
+ },
+ {
+ type: 'function',
+ name: 'transferWithAuthorization',
+ stateMutability: 'nonpayable',
+ inputs: [
+ { name: 'from', type: 'address' },
+ { name: 'to', type: 'address' },
+ { name: 'value', type: 'uint256' },
+ { name: 'validAfter', type: 'uint256' },
+ { name: 'validBefore', type: 'uint256' },
+ { name: 'nonce', type: 'bytes32' },
+ { name: 'v', type: 'uint8' },
+ { name: 'r', type: 'bytes32' },
+ { name: 's', type: 'bytes32' },
+ ],
+ outputs: [],
+ },
+ {
+ type: 'function',
+ name: 'authorizationState',
+ stateMutability: 'view',
+ inputs: [
+ { name: 'authorizer', type: 'address' },
+ { name: 'nonce', type: 'bytes32' },
+ ],
+ outputs: [{ type: 'bool' }],
+ },
+ {
+ type: 'function',
+ name: 'balanceOf',
+ stateMutability: 'view',
+ inputs: [{ name: 'account', type: 'address' }],
+ outputs: [{ type: 'uint256' }],
+ },
+];
+
+// RPC failover for chain 196 — X Layer is not in the shared erc8004 chain
+// registry, so the endpoint list lives here: explicit override first, then
+// viem's curated default, then OKX's public node.
+function xlayerEndpoints() {
+ const urls = [
+ env.getRpcUrl(XLAYER_CHAIN_ID),
+ xLayer.rpcUrls.default.http[0],
+ 'https://rpc.xlayer.tech',
+ ].filter(Boolean);
+ return [...new Set(urls)];
+}
+
+let cachedClient = null;
+export function xlayerClient() {
+ if (cachedClient) return cachedClient;
+ cachedClient = createPublicClient({
+ chain: xLayer,
+ transport: fallback(xlayerEndpoints().map((u) => http(u, { retryCount: 1 }))),
+ });
+ return cachedClient;
+}
+
+// Can we actually settle on X Layer right now? Advertise the rail only when
+// the receiver, the asset, and the redeeming relayer key are all configured —
+// the same never-402-then-502 rule baseSettleable()/solanaSettleable() enforce.
+export function xlayerSettleable() {
+ return Boolean(
+ env.X402_PAY_TO_XLAYER && env.X402_ASSET_ADDRESS_XLAYER && env.X402_XLAYER_RELAYER_KEY,
+ );
+}
+
+// The X Layer accepts[] entry, byte-shaped to the approved-seller captures.
+// `amount` is a base-units string (USD₮0 = 6 decimals, same atomic scale as
+// USDC, so per-tool USDC atomic prices carry over unchanged).
+export function okxXLayerAccept(resourceUrl, amount) {
+ return {
+ scheme: 'exact',
+ network: NETWORK_XLAYER_MAINNET,
+ amount: String(amount),
+ payTo: env.X402_PAY_TO_XLAYER,
+ maxTimeoutSeconds: 86400,
+ asset: env.X402_ASSET_ADDRESS_XLAYER,
+ ...(resourceUrl ? { resource: resourceUrl } : {}),
+ extra: {
+ symbol: USDT0_SYMBOL,
+ name: USDT0_DOMAIN_NAME,
+ version: USDT0_DOMAIN_VERSION,
+ transferMethod: 'eip3009',
+ },
+ };
+}
+
+// Send the OKX-dialect 402: the minimal {x402Version, resource:{url,mimeType},
+// accepts[, error]} envelope as BOTH body and base64 PAYMENT-REQUIRED header.
+// Deliberately not build402Body(): the OKX validator's reference sellers emit
+// exactly this shape (no extensions envelope, no top-level description), and
+// the listing contract is "look like an approved seller", not "look like our
+// Bazaar catalog".
+export function sendOkx402(res, { resourceUrl, accepts, error }) {
+ const body = {
+ x402Version: 2,
+ ...(error ? { error } : {}),
+ resource: { url: resourceUrl, mimeType: 'application/json' },
+ accepts: Array.isArray(accepts) ? accepts : [accepts],
+ };
+ const encoded = Buffer.from(JSON.stringify(body), 'utf8').toString('base64');
+ res.statusCode = 402;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.setHeader('cache-control', 'no-store');
+ res.setHeader('PAYMENT-REQUIRED', encoded);
+ res.setHeader('access-control-expose-headers', 'PAYMENT-REQUIRED, PAYMENT-RESPONSE');
+ res.end(JSON.stringify(body));
+}
+
+// Pull {authorization, signature} out of either payload dialect:
+// OKX: { accepted:{…}, payload:{ authorization, signature } }
+// standard: { scheme, network, payload:{ authorization, signature } }
+function extractAuthorization(paymentPayload) {
+ const inner = paymentPayload?.payload;
+ const auth = inner?.authorization;
+ const signature = inner?.signature;
+ if (!auth || typeof auth !== 'object' || typeof signature !== 'string') {
+ throw new X402Error(
+ 'invalid_payment',
+ 'X Layer payment must carry payload.authorization + payload.signature (EIP-3009)',
+ 402,
+ );
+ }
+ return { auth, signature };
+}
+
+function asAddress(value, field) {
+ try {
+ return getAddress(String(value));
+ } catch {
+ throw new X402Error('invalid_payment', `${field} is not a valid EVM address`, 402);
+ }
+}
+
+function asBigInt(value, field) {
+ try {
+ return BigInt(value);
+ } catch {
+ throw new X402Error('invalid_payment', `${field} must be an integer string`, 402);
+ }
+}
+
+// Verify an OKX/X Layer EIP-3009 payment end to end WITHOUT trusting any
+// third party: typed-data signature (ERC-1271-aware via the public client, so
+// smart-account agentic wallets verify too), recipient binding, amount, time
+// window, unused nonce, and payer balance. Insufficient balance throws the
+// exact `insufficient_balance` error string the approved sellers emit.
+export async function verifyOkxXLayerPayment({ paymentPayload, requirement }) {
+ const { auth, signature } = extractAuthorization(paymentPayload);
+ if (!/^0x[0-9a-fA-F]+$/.test(signature)) {
+ throw new X402Error('invalid_payment', 'signature must be 0x-prefixed hex', 402);
+ }
+ if (typeof auth.nonce !== 'string' || !/^0x[0-9a-fA-F]{64}$/.test(auth.nonce)) {
+ throw new X402Error('invalid_payment', 'authorization.nonce must be 32-byte hex', 402);
+ }
+
+ const from = asAddress(auth.from, 'authorization.from');
+ const to = asAddress(auth.to, 'authorization.to');
+ const value = asBigInt(auth.value, 'authorization.value');
+ const validAfter = asBigInt(auth.validAfter ?? '0', 'authorization.validAfter');
+ const validBefore = asBigInt(auth.validBefore ?? '0', 'authorization.validBefore');
+
+ const expectedTo = asAddress(requirement.payTo, 'requirement.payTo');
+ if (to !== expectedTo) {
+ throw new X402Error(
+ 'invalid_payment',
+ `authorization.to ${to} does not match required payTo ${expectedTo}`,
+ 402,
+ );
+ }
+ const required = asBigInt(requirement.amount, 'requirement.amount');
+ if (value < required) {
+ throw new X402Error(
+ 'invalid_payment',
+ `authorized amount ${value} is below required ${required}`,
+ 402,
+ );
+ }
+ const nowSec = BigInt(Math.floor(Date.now() / 1000));
+ if (validAfter > nowSec) {
+ throw new X402Error('invalid_payment', 'authorization is not yet valid (validAfter in the future)', 402);
+ }
+ if (validBefore <= nowSec) {
+ throw new X402Error('invalid_payment', 'authorization has expired (validBefore in the past)', 402);
+ }
+
+ const asset = asAddress(requirement.asset || env.X402_ASSET_ADDRESS_XLAYER, 'requirement.asset');
+ const client = xlayerClient();
+
+ // EIP-712 recovery. Domain name/version come from the requirement's extra
+ // block (what the buyer signed against) with the on-chain-verified USD₮0
+ // defaults. verifyTypedData on a PUBLIC client falls back to ERC-6492/1271
+ // isValidSignature for contract accounts.
+ let sigOk = false;
+ try {
+ sigOk = await client.verifyTypedData({
+ address: from,
+ domain: {
+ name: requirement.extra?.name || USDT0_DOMAIN_NAME,
+ version: requirement.extra?.version || USDT0_DOMAIN_VERSION,
+ chainId: XLAYER_CHAIN_ID,
+ verifyingContract: asset,
+ },
+ types: TRANSFER_WITH_AUTHORIZATION_TYPES,
+ primaryType: 'TransferWithAuthorization',
+ message: {
+ from,
+ to,
+ value,
+ validAfter,
+ validBefore,
+ nonce: auth.nonce,
+ },
+ signature,
+ });
+ } catch (err) {
+ throw new X402Error(
+ 'verify_failed',
+ `X Layer signature verification errored: ${err.shortMessage || err.message}`,
+ 502,
+ );
+ }
+ if (!sigOk) {
+ throw new X402Error('invalid_payment', 'EIP-3009 signature does not verify for authorization.from', 402);
+ }
+
+ // On-chain state: the nonce must be unredeemed and the payer funded. These
+ // are the checks behind the approved seller's `insufficient_balance` reply.
+ let nonceUsed;
+ let balance;
+ try {
+ [nonceUsed, balance] = await Promise.all([
+ client.readContract({
+ address: asset,
+ abi: EIP3009_ABI,
+ functionName: 'authorizationState',
+ args: [from, auth.nonce],
+ }),
+ client.readContract({
+ address: asset,
+ abi: EIP3009_ABI,
+ functionName: 'balanceOf',
+ args: [from],
+ }),
+ ]);
+ } catch (err) {
+ throw new X402Error(
+ 'verify_failed',
+ `X Layer RPC state check failed: ${err.shortMessage || err.message}`,
+ 502,
+ );
+ }
+ if (nonceUsed) {
+ throw new X402Error('invalid_payment', 'authorization nonce has already been used', 402);
+ }
+ if (balance < value) {
+ throw new X402Error('invalid_payment', 'insufficient_balance', 402);
+ }
+
+ return {
+ isValid: true,
+ payer: from,
+ amount: value.toString(),
+ authorization: { from, to, value: value.toString(), validAfter: validAfter.toString(), validBefore: validBefore.toString(), nonce: auth.nonce },
+ signature,
+ asset,
+ };
+}
+
+function relayerAccount() {
+ const key = env.X402_XLAYER_RELAYER_KEY;
+ if (!key) {
+ throw new X402Error(
+ 'settle_failed',
+ 'X Layer settlement requires X402_XLAYER_RELAYER_KEY (the relayer that redeems EIP-3009 authorizations)',
+ 500,
+ );
+ }
+ const hex = key.startsWith('0x') ? key : `0x${key}`;
+ try {
+ return privateKeyToAccount(hex);
+ } catch {
+ throw new X402Error('settle_failed', 'X402_XLAYER_RELAYER_KEY is not a valid secp256k1 private key', 500);
+ }
+}
+
+// Redeem the verified authorization: broadcast transferWithAuthorization from
+// the relayer (OKB gas) and wait for inclusion. Tries the bytes-signature
+// EIP-3009 variant first, then the (v,r,s) split — token implementations ship
+// one or the other. Returns the same {success, transaction, network, payer}
+// shape the facilitator /settle path yields, so X-PAYMENT-RESPONSE /
+// PAYMENT-RESPONSE emission is identical.
+export async function settleOkxXLayerPayment({ verified, requirement }) {
+ if (!verified?.authorization || !verified?.signature) {
+ throw new X402Error('settle_failed', 'X Layer settle requires the verify step to run first', 500);
+ }
+ if (requirement.network !== NETWORK_XLAYER_MAINNET) {
+ throw new X402Error(
+ 'settle_failed',
+ `X Layer settle expected network ${NETWORK_XLAYER_MAINNET}, got ${requirement.network}`,
+ 500,
+ );
+ }
+ const account = relayerAccount();
+ const client = xlayerClient();
+ const wallet = createWalletClient({
+ account,
+ chain: xLayer,
+ transport: fallback(xlayerEndpoints().map((u) => http(u, { retryCount: 1 }))),
+ });
+ const a = verified.authorization;
+ const baseArgs = [a.from, a.to, BigInt(a.value), BigInt(a.validAfter), BigInt(a.validBefore), a.nonce];
+ const sig = verified.signature;
+ const variants = [
+ { args: [...baseArgs, sig] },
+ { args: [...baseArgs, ...splitSignature(sig)] },
+ ];
+ let lastErr = null;
+ for (const variant of variants) {
+ try {
+ const { request } = await client.simulateContract({
+ account,
+ address: verified.asset,
+ abi: EIP3009_ABI,
+ functionName: 'transferWithAuthorization',
+ args: variant.args,
+ });
+ const hash = await wallet.writeContract(request);
+ const receipt = await client.waitForTransactionReceipt({ hash, timeout: 60_000 });
+ if (receipt.status !== 'success') {
+ throw new X402Error('settle_failed', `transferWithAuthorization reverted in tx ${hash}`, 502);
+ }
+ return {
+ success: true,
+ transaction: hash,
+ network: NETWORK_XLAYER_MAINNET,
+ payer: verified.payer,
+ };
+ } catch (err) {
+ if (err instanceof X402Error) throw err;
+ lastErr = err;
+ }
+ }
+ throw new X402Error(
+ 'settle_failed',
+ `X Layer transferWithAuthorization failed: ${lastErr?.shortMessage || lastErr?.message || 'unknown'}`,
+ 502,
+ );
+}
+
+function splitSignature(signature) {
+ const hex = signature.slice(2);
+ if (hex.length !== 130) {
+ throw new X402Error('settle_failed', 'cannot split a non-65-byte signature into (v,r,s)', 502);
+ }
+ const r = `0x${hex.slice(0, 64)}`;
+ const s = `0x${hex.slice(64, 128)}`;
+ let v = parseInt(hex.slice(128, 130), 16);
+ if (v < 27) v += 27;
+ return [v, r, s];
+}
+
+// Live subsystem probe for the free health endpoint (WO-03's "real checks, not
+// {ok:true}"): RPC liveness, fee-token readability, and whether the settlement
+// relayer is configured + gas-funded. Never throws — health reports state.
+export async function xlayerRailHealth() {
+ const out = {
+ network: NETWORK_XLAYER_MAINNET,
+ payTo: env.X402_PAY_TO_XLAYER || null,
+ asset: env.X402_ASSET_ADDRESS_XLAYER || null,
+ settleable: xlayerSettleable(),
+ };
+ try {
+ const client = xlayerClient();
+ const [block, symbol] = await Promise.all([
+ client.getBlockNumber(),
+ client.readContract({
+ address: env.X402_ASSET_ADDRESS_XLAYER,
+ abi: [{ type: 'function', name: 'symbol', stateMutability: 'view', inputs: [], outputs: [{ type: 'string' }] }],
+ functionName: 'symbol',
+ }),
+ ]);
+ out.rpc = { ok: true, block: block.toString() };
+ out.token = { ok: true, symbol };
+ if (env.X402_XLAYER_RELAYER_KEY) {
+ try {
+ const relayer = relayerAccount();
+ const gas = await client.getBalance({ address: relayer.address });
+ out.relayer = { configured: true, address: relayer.address, okbWei: gas.toString(), funded: gas > 0n };
+ } catch (err) {
+ out.relayer = { configured: true, error: err.message };
+ }
+ } else {
+ out.relayer = { configured: false };
+ }
+ } catch (err) {
+ out.rpc = { ok: false, error: err.shortMessage || err.message };
+ }
+ return out;
+}
diff --git a/api/admin/gcp-burn.js b/api/admin/gcp-burn.js
new file mode 100644
index 000000000..9b412ea75
--- /dev/null
+++ b/api/admin/gcp-burn.js
@@ -0,0 +1,169 @@
+// GET /api/admin/gcp-burn
+//
+// Internal spend dashboard data for the $100k GCP credit program. Two views,
+// cross-referenced:
+//
+// 1. APP-SIDE TELEMETRY (always available, from Neon):
+// • LLM lane usage per day — requests + tokens + cost estimate, grouped by
+// provider, with `vertex-anthropic` broken out as the Vertex Claude lane.
+// • Forge generations per backend (forge_creations.backend), flagged
+// self-host (our Cloud Run GPU fleet, provider=gcp) vs external.
+//
+// 2. BILLING GROUND TRUTH (best-effort, from BigQuery billing export):
+// • The attributed burn report (credit consumed, projection vs expiry).
+// Degrades to { available:false, reason } when the export isn't wired yet
+// or the SA can't reach BigQuery — the app-side view still renders.
+//
+// Auth: session+admin OR Bearer $CRON_SECRET (matches api/admin/all-systems.js,
+// circulation-health.js — lets the daily cron + monitoring scrapers read it).
+// No secrets are returned.
+
+import { sql } from '../_lib/db.js';
+import { requireAdmin } from '../_lib/admin.js';
+import { cors, json, method, wrap } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+import { isSelfHostBackend } from '../_lib/forge-tiers.js';
+import { buildBurnReport, billingConfigured, BillingUnavailableError } from '../_lib/gcp-billing.js';
+
+// Which credit-program lane a usage_events.provider belongs to. Providers not
+// funded by the GCP grant (free BYOK lanes, Replicate) map to null and are
+// reported under "other" so the lane totals stay honest.
+function providerLane(provider) {
+ if (provider === 'vertex-anthropic') return 'vertex-claude';
+ if (provider === 'gcp') return 'forge-gpu';
+ if (provider === 'vertex-imagen' || provider === 'imagen') return 'imagen';
+ return null;
+}
+
+function isCronAuth(req) {
+ const auth = req.headers.authorization || '';
+ const bearer = auth.toLowerCase().startsWith('bearer ') ? auth.slice(7).trim() : '';
+ return !!env.CRON_SECRET && constantTimeEquals(bearer, env.CRON_SECRET);
+}
+
+const microToUsd = (micro) => Number(micro || 0) / 1_000_000;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ if (!isCronAuth(req)) {
+ const admin = await requireAdmin(req, res);
+ if (!admin) return; // requireAdmin already wrote 401/403
+ }
+
+ // ── App-side telemetry (Neon) ────────────────────────────────────────────
+ // LLM lane usage per day (last 14 days) — real provider/token/cost columns.
+ const llmDailyP = sql`
+ SELECT
+ date_trunc('day', created_at)::date AS day,
+ provider,
+ count(*)::int AS requests,
+ coalesce(sum(input_tokens), 0)::bigint AS input_tokens,
+ coalesce(sum(output_tokens), 0)::bigint AS output_tokens,
+ coalesce(sum(cost_micro_usd), 0)::bigint AS cost_micro_usd
+ FROM usage_events
+ WHERE kind = 'llm'
+ AND created_at > now() - interval '14 days'
+ AND provider IS NOT NULL
+ GROUP BY day, provider
+ ORDER BY day DESC, cost_micro_usd DESC`;
+
+ // Vertex Claude spend estimate — 24h and 30d windows, by model.
+ const vertexP = sql`
+ SELECT
+ model,
+ count(*)::int AS requests,
+ coalesce(sum(input_tokens), 0)::bigint AS input_tokens,
+ coalesce(sum(output_tokens), 0)::bigint AS output_tokens,
+ coalesce(sum(cost_micro_usd), 0)::bigint AS cost_micro_usd,
+ coalesce(sum(cost_micro_usd) FILTER (WHERE created_at > now() - interval '24 hours'), 0)::bigint AS cost_micro_usd_24h
+ FROM usage_events
+ WHERE kind = 'llm' AND provider = 'vertex-anthropic'
+ AND created_at > now() - interval '30 days'
+ GROUP BY model
+ ORDER BY cost_micro_usd DESC`;
+
+ // Forge generations per backend (last 30 days) — the self-host GPU fleet is
+ // what burns Cloud Run credits.
+ const forgeP = sql`
+ SELECT
+ coalesce(backend, '(unknown)') AS backend,
+ count(*)::int AS generations,
+ count(*) FILTER (WHERE created_at > now() - interval '24 hours')::int AS generations_24h
+ FROM forge_creations
+ WHERE created_at > now() - interval '30 days'
+ GROUP BY backend
+ ORDER BY generations DESC`;
+
+ const [llmDaily, vertexRows, forgeRows] = await Promise.all([
+ llmDailyP.catch(() => []),
+ vertexP.catch(() => []),
+ forgeP.catch(() => []),
+ ]);
+
+ // Roll LLM rows up into per-lane 14-day totals + a per-day series.
+ const laneTotals = {};
+ const daySeries = {};
+ for (const r of llmDaily) {
+ const lane = providerLane(r.provider) || 'other';
+ const day = r.day instanceof Date ? r.day.toISOString().slice(0, 10) : String(r.day);
+ const t = (laneTotals[lane] ||= { lane, requests: 0, inputTokens: 0, outputTokens: 0, costUsd: 0 });
+ t.requests += Number(r.requests);
+ t.inputTokens += Number(r.input_tokens);
+ t.outputTokens += Number(r.output_tokens);
+ t.costUsd += microToUsd(r.cost_micro_usd);
+ const d = (daySeries[day] ||= { day });
+ d[lane] = (d[lane] || 0) + microToUsd(r.cost_micro_usd);
+ }
+
+ const vertexClaude = {
+ requests30d: vertexRows.reduce((a, r) => a + Number(r.requests), 0),
+ inputTokens30d: vertexRows.reduce((a, r) => a + Number(r.input_tokens), 0),
+ outputTokens30d: vertexRows.reduce((a, r) => a + Number(r.output_tokens), 0),
+ costUsd30d: vertexRows.reduce((a, r) => a + microToUsd(r.cost_micro_usd), 0),
+ costUsd24h: vertexRows.reduce((a, r) => a + microToUsd(r.cost_micro_usd_24h), 0),
+ byModel: vertexRows.map((r) => ({
+ model: r.model,
+ requests: Number(r.requests),
+ inputTokens: Number(r.input_tokens),
+ outputTokens: Number(r.output_tokens),
+ costUsd: microToUsd(r.cost_micro_usd),
+ })),
+ };
+
+ const forgeByBackend = forgeRows.map((r) => ({
+ backend: r.backend,
+ generations30d: Number(r.generations),
+ generations24h: Number(r.generations_24h),
+ selfHost: r.backend !== '(unknown)' && isSelfHostBackend(r.backend),
+ }));
+
+ // ── Billing ground truth (BigQuery, best-effort) ─────────────────────────
+ let billing;
+ if (!billingConfigured()) {
+ billing = { available: false, reason: 'BigQuery billing export not configured (see docs/gcp-credits.md).' };
+ } else {
+ try {
+ const report = await buildBurnReport({});
+ billing = { available: true, report };
+ } catch (err) {
+ billing = {
+ available: false,
+ reason: err instanceof BillingUnavailableError ? err.message : `billing query failed: ${err?.message || err}`,
+ };
+ }
+ }
+
+ return json(res, 200, {
+ generated_at: new Date().toISOString(),
+ app_side: {
+ lane_totals_14d: Object.values(laneTotals).sort((a, b) => b.costUsd - a.costUsd),
+ daily_llm_cost_usd: Object.values(daySeries).sort((a, b) => a.day.localeCompare(b.day)),
+ vertex_claude: vertexClaude,
+ forge_by_backend: forgeByBackend,
+ },
+ billing,
+ });
+});
diff --git a/api/cron/gcp-burn-report.js b/api/cron/gcp-burn-report.js
new file mode 100644
index 000000000..626a9f25f
--- /dev/null
+++ b/api/cron/gcp-burn-report.js
@@ -0,0 +1,110 @@
+// @ts-check
+// GET /api/cron/gcp-burn-report — daily GCP credit burn report → ops channel.
+//
+// Runs once a day. Builds the attributed burn report from the BigQuery billing
+// export (api/_lib/gcp-billing.js) and posts a summary to the PRIVATE ops
+// Telegram channel (sendOpsAlert → TELEGRAM_ALERTS_CHAT_ID): credit consumed,
+// daily burn, days of runway, projected exhaustion vs expiry, and the
+// under-utilization guard (>30% of the grant projected unused at expiry).
+//
+// Both failure modes ping the channel:
+// • runaway — credits exhaust BEFORE expiry → throttle / kill-switch
+// • underutilized — credits expire unused → scale a lane up
+// A healthy on-track day posts a quiet one-line status (deduped) so the channel
+// still shows the report ran.
+//
+// If the billing export isn't wired yet the cron no-ops quietly (one alert/day
+// max, deduped) rather than erroring — the alerting scaffold is allowed to exist
+// before prompt 01's export lands.
+//
+// Kept as a concrete file (not [name].js) so the burn module + its fetch/crypto
+// deps don't share a cold start with the heavy SDK bundles.
+
+import { json, method, wrapCron } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+import { error } from '../_lib/http.js';
+import { sendOpsAlert } from '../_lib/alerts.js';
+import { buildBurnReport, billingConfigured, BillingUnavailableError, usd, PROGRAM_LANES } from '../_lib/gcp-billing.js';
+
+function requireCron(req, res) {
+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;
+ if (!secret) {
+ error(res, 503, 'not_configured', 'CRON_SECRET unset');
+ return false;
+ }
+ const auth = req.headers['authorization'] || '';
+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';
+ if (!constantTimeEquals(presented, secret)) {
+ error(res, 401, 'unauthorized', 'invalid cron secret');
+ return false;
+ }
+ return true;
+}
+
+const STATUS_EMOJI = { runaway: '🔴', underutilized: '🟡', 'on-track': '🟢', idle: '⚪', unknown: '⚪' };
+
+function formatReport(report) {
+ const { totals, projection: p, burn } = report;
+ const lines = [];
+ lines.push(`Consumed ${usd(totals.creditUsed)}${p.creditTotalUsd ? ` of ${usd(p.creditTotalUsd)} (${Math.round((totals.creditUsed / p.creditTotalUsd) * 100)}%)` : ''}`);
+ lines.push(`Burn ${usd(burn.avg7dPerDay)}/day (7d), ${usd(burn.avg30dPerDay)}/day (30d)`);
+ if (p.daysRunway != null && p.daysRunway !== Infinity) {
+ lines.push(`Runway ~${Math.round(p.daysRunway)}d → exhausts ${String(p.exhaustionDate).slice(0, 10)}`);
+ }
+ if (p.expiry) lines.push(`Expiry ${String(p.expiry).slice(0, 10)} (${Math.round(p.daysToExpiry)}d)`);
+ lines.push('');
+ lines.push(p.headline);
+ if (p.status === 'underutilized' || p.status === 'idle') {
+ lines.push('Scale up: ' + Object.entries(PROGRAM_LANES)
+ .filter(([k]) => k !== '(unlabeled)')
+ .map(([, m]) => m.label)
+ .join(', '));
+ }
+ return lines.join('\n');
+}
+
+export default wrapCron(async (req, res) => {
+ if (!method(req, res, ['GET'])) return;
+ if (!requireCron(req, res)) return;
+
+ if (!billingConfigured()) {
+ // Scaffold exists before the export lands — say so once/day, don't error.
+ await sendOpsAlert(
+ 'GCP burn report — billing export not wired',
+ 'Set GOOGLE_CLOUD_PROJECT + GCP_BILLING_DATASET + GCP_BILLING_TABLE (prompt 01). See docs/gcp-credits.md.',
+ { signature: 'gcp-burn-unconfigured' },
+ );
+ return json(res, 200, { ok: true, configured: false });
+ }
+
+ let report;
+ try {
+ report = await buildBurnReport({});
+ } catch (err) {
+ const msg = err instanceof BillingUnavailableError ? err.message : (err?.message || String(err));
+ await sendOpsAlert('GCP burn report failed', msg, { signature: 'gcp-burn-failed' });
+ return json(res, 200, { ok: false, error: msg });
+ }
+
+ const p = report.projection;
+ const emoji = STATUS_EMOJI[p.status] || '⚪';
+ const body = formatReport(report);
+
+ // Runaway + under-utilization get a distinct signature so they aren't deduped
+ // against the daily on-track status line and always land.
+ const signature =
+ p.status === 'runaway' ? 'gcp-burn-runaway'
+ : p.status === 'underutilized' ? 'gcp-burn-underutilized'
+ : `gcp-burn-daily:${new Date().toISOString().slice(0, 10)}`;
+
+ await sendOpsAlert(`${emoji} GCP daily burn — ${p.status}`, body, { signature });
+
+ return json(res, 200, {
+ ok: true,
+ status: p.status,
+ creditUsed: report.totals.creditUsed,
+ daysRunway: p.daysRunway,
+ projectedUnusedPct: p.projectedUnusedPct,
+ });
+});
diff --git a/api/llm/anthropic.js b/api/llm/anthropic.js
index 86112adea..4f8f9c136 100644
--- a/api/llm/anthropic.js
+++ b/api/llm/anthropic.js
@@ -617,6 +617,9 @@ export default wrap(async (req, res) => {
res.setHeader('content-type', 'text/event-stream');
res.setHeader('cache-control', 'no-cache');
res.setHeader('x-accel-buffering', 'no');
+ // Provider/transport attribution — lets smoke tests and observability tell
+ // Vertex-served Claude ('vertex-anthropic') apart from first-party.
+ res.setHeader('x-llm-transport', via);
let inputTokens = 0;
let outputTokens = 0;
@@ -757,6 +760,7 @@ export default wrap(async (req, res) => {
res.statusCode = 200;
res.setHeader('content-type', outContentType);
+ res.setHeader('x-llm-transport', via);
return res.end(outBody);
});
diff --git a/pages/dashboard-next/spend.html b/pages/dashboard-next/spend.html
new file mode 100644
index 000000000..628d8d399
--- /dev/null
+++ b/pages/dashboard-next/spend.html
@@ -0,0 +1,16 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>GCP Spend · Dashboard · three.ws</title>
+ <meta name="robots" content="noindex" />
+ <link rel="icon" href="/favicon.ico" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/dashboard-next/shell.css" />
+ </head>
+ <body>
+ <script src="/embed.js"></script>
+ <script type="module" src="/src/dashboard-next/pages/spend.js"></script>
+ </body>
+</html>
diff --git a/specs/okx-agent-payments.md b/specs/okx-agent-payments.md
index 5956ad5a2..c0f1cbd77 100644
--- a/specs/okx-agent-payments.md
+++ b/specs/okx-agent-payments.md
@@ -4,7 +4,9 @@
> **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.
+> **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, and it gates at MCP `_meta` level using **x402 v1 header names** (`X-PAYMENT`/`X-PAYMENT-RESPONSE`) rather than the **x402 v2** names OKX uses (`PAYMENT-SIGNATURE`/`PAYMENT-RESPONSE`). 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.
+>
+> **Header-naming premise correction (important):** `PAYMENT-SIGNATURE` (buyer→seller) and `PAYMENT-RESPONSE` (seller→buyer) are the **vanilla x402 _v2_ standard** header names (Coinbase `x402` `specs/transports-v2/http.md`; `specs/x402-specification-v2.md:77` literally errors `"PAYMENT-SIGNATURE header is required"`). `X-PAYMENT`/`X-PAYMENT-RESPONSE` are **x402 _v1_**. OKX matches x402 v2 exactly on header naming (and accepts the v1 `x-payment` for back-compat). So these are **not** OKX-specific; the genuine OKX extensions are only: the `aggr_deferred`/`upto` schemes, the HMAC-signed OKX-hosted facilitator, `syncSettle`, `settle/status`, subscriptions, and the parallel `WWW-Authenticate: Payment` MPP rail. **Our own code labels itself "v2" but emits the v1 header names — that is the delta to close for the X-Layer rail.**
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**.
@@ -88,7 +90,7 @@ Notes vs. our current Bazaar-heavy body: OKX sellers emit **no** `extensions.baz
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)
+1. header = req.header("PAYMENT-SIGNATURE") // x402 v2 std; also accept v1 `x-payment` for back-compat
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
diff --git a/tests/vertex-claude.test.js b/tests/vertex-claude.test.js
new file mode 100644
index 000000000..2edb134e5
--- /dev/null
+++ b/tests/vertex-claude.test.js
@@ -0,0 +1,198 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import {
+ toVertexModelId,
+ vertexMessagesUrl,
+ toVertexBody,
+ vertexClaudeConfigured,
+ vertexClaudeEnabled,
+ vertexClaudePrimary,
+} from '../api/_lib/vertex-claude.js';
+import { providerChain } from '../api/_lib/llm.js';
+
+// Snapshot and restore the env keys these tests mutate so nothing leaks between
+// cases (the flag/config helpers read process.env at call time).
+const TOUCHED = [
+ 'GOOGLE_CLOUD_PROJECT',
+ 'GOOGLE_CLOUD_LOCATION_CLAUDE',
+ 'VERTEX_CLAUDE_ENABLED',
+ 'VERTEX_CLAUDE_PRIMARY',
+ 'GROQ_API_KEY',
+ 'OPENROUTER_API_KEY',
+ 'OPENROUTER_FALLBACK_KEYS',
+ 'NVIDIA_API_KEY',
+ 'ANTHROPIC_API_KEY',
+ 'OPENAI_API_KEY',
+];
+let saved;
+beforeEach(() => {
+ saved = {};
+ for (const k of TOUCHED) saved[k] = process.env[k];
+ for (const k of TOUCHED) delete process.env[k];
+});
+afterEach(() => {
+ for (const k of TOUCHED) {
+ if (saved[k] === undefined) delete process.env[k];
+ else process.env[k] = saved[k];
+ }
+});
+
+describe('toVertexModelId (shared model-id mapper)', () => {
+ it('converts a dated first-party id to the Vertex @ form', () => {
+ expect(toVertexModelId('claude-haiku-4-5-20251001')).toBe('claude-haiku-4-5@20251001');
+ });
+
+ it('passes bare aliases through unchanged', () => {
+ expect(toVertexModelId('claude-sonnet-4-6')).toBe('claude-sonnet-4-6');
+ expect(toVertexModelId('claude-opus-4-7')).toBe('claude-opus-4-7');
+ });
+
+ it('leaves an already-@ id untouched', () => {
+ expect(toVertexModelId('claude-haiku-4-5@20251001')).toBe('claude-haiku-4-5@20251001');
+ });
+
+ it('only rewrites a trailing 8-digit date, not shorter numeric suffixes', () => {
+ expect(toVertexModelId('claude-sonnet-4-6')).toBe('claude-sonnet-4-6');
+ expect(toVertexModelId('some-model-2025')).toBe('some-model-2025');
+ });
+
+ it('handles empty/nullish input without throwing', () => {
+ expect(toVertexModelId('')).toBe('');
+ expect(toVertexModelId(undefined)).toBe(undefined);
+ });
+});
+
+describe('vertexMessagesUrl', () => {
+ beforeEach(() => {
+ process.env.GOOGLE_CLOUD_PROJECT = 'my-proj';
+ });
+
+ it('uses the global host + path and puts the model in the URL (default location)', () => {
+ const url = vertexMessagesUrl('claude-sonnet-4-6', { stream: false });
+ expect(url).toBe(
+ 'https://aiplatform.googleapis.com/v1/projects/my-proj/locations/global/publishers/anthropic/models/claude-sonnet-4-6:rawPredict',
+ );
+ });
+
+ it('uses :streamRawPredict for streaming', () => {
+ const url = vertexMessagesUrl('claude-sonnet-4-6', { stream: true });
+ expect(url.endsWith(':streamRawPredict')).toBe(true);
+ });
+
+ it('maps a dated id to @ form in the path', () => {
+ const url = vertexMessagesUrl('claude-haiku-4-5-20251001', { stream: true });
+ expect(url).toContain('/models/claude-haiku-4-5@20251001:streamRawPredict');
+ });
+
+ it('prefixes the host for a regional endpoint', () => {
+ process.env.GOOGLE_CLOUD_LOCATION_CLAUDE = 'us-east5';
+ const url = vertexMessagesUrl('claude-sonnet-4-6', { stream: false });
+ expect(url.startsWith('https://us-east5-aiplatform.googleapis.com/')).toBe(true);
+ expect(url).toContain('/locations/us-east5/');
+ });
+});
+
+describe('toVertexBody', () => {
+ it('drops model + stream, adds anthropic_version, keeps the rest', () => {
+ const out = toVertexBody({
+ model: 'claude-sonnet-4-6',
+ stream: true,
+ max_tokens: 512,
+ system: 'be brief',
+ messages: [{ role: 'user', content: 'hi' }],
+ tools: [{ name: 'x' }],
+ });
+ expect(out.model).toBeUndefined();
+ expect(out.stream).toBeUndefined();
+ expect(out.anthropic_version).toBe('vertex-2023-10-16');
+ expect(out.max_tokens).toBe(512);
+ expect(out.system).toBe('be brief');
+ expect(out.messages).toEqual([{ role: 'user', content: 'hi' }]);
+ expect(out.tools).toEqual([{ name: 'x' }]);
+ });
+});
+
+describe('flag helpers under the four combinations', () => {
+ // configured = GOOGLE_CLOUD_PROJECT present; enabled requires the flag AND
+ // configured; primary requires enabled AND its flag.
+ it('off/off: not enabled, not primary (even when configured)', () => {
+ process.env.GOOGLE_CLOUD_PROJECT = 'p';
+ expect(vertexClaudeConfigured()).toBe(true);
+ expect(vertexClaudeEnabled()).toBe(false);
+ expect(vertexClaudePrimary()).toBe(false);
+ });
+
+ it('enabled/off: enabled but not primary', () => {
+ process.env.GOOGLE_CLOUD_PROJECT = 'p';
+ process.env.VERTEX_CLAUDE_ENABLED = '1';
+ expect(vertexClaudeEnabled()).toBe(true);
+ expect(vertexClaudePrimary()).toBe(false);
+ });
+
+ it('enabled/primary: both true', () => {
+ process.env.GOOGLE_CLOUD_PROJECT = 'p';
+ process.env.VERTEX_CLAUDE_ENABLED = '1';
+ process.env.VERTEX_CLAUDE_PRIMARY = '1';
+ expect(vertexClaudeEnabled()).toBe(true);
+ expect(vertexClaudePrimary()).toBe(true);
+ });
+
+ it('primary flag alone (not enabled) does nothing', () => {
+ process.env.GOOGLE_CLOUD_PROJECT = 'p';
+ process.env.VERTEX_CLAUDE_PRIMARY = '1';
+ expect(vertexClaudeEnabled()).toBe(false);
+ expect(vertexClaudePrimary()).toBe(false);
+ });
+
+ it('enabled flag without a configured project stays disabled', () => {
+ process.env.VERTEX_CLAUDE_ENABLED = '1';
+ expect(vertexClaudeConfigured()).toBe(false);
+ expect(vertexClaudeEnabled()).toBe(false);
+ });
+});
+
+describe('providerChain ordering under the four flag combinations', () => {
+ // A representative free lane (Groq) plus a paid backstop (Anthropic) so the
+ // relative position of Vertex is observable.
+ beforeEach(() => {
+ process.env.GROQ_API_KEY = 'g';
+ process.env.ANTHROPIC_API_KEY = 'a';
+ process.env.GOOGLE_CLOUD_PROJECT = 'p';
+ });
+
+ const names = () => providerChain().map((p) => p.name);
+
+ it('off/off: no vertex lane; byte-identical free-first chain', () => {
+ expect(names()).toEqual(['groq', 'anthropic']);
+ });
+
+ it('enabled/off: vertex is a paid backstop AHEAD of first-party anthropic, behind free lanes', () => {
+ process.env.VERTEX_CLAUDE_ENABLED = '1';
+ const n = names();
+ expect(n).toEqual(['groq', 'vertex-anthropic', 'anthropic']);
+ expect(n.indexOf('groq')).toBeLessThan(n.indexOf('vertex-anthropic'));
+ expect(n.indexOf('vertex-anthropic')).toBeLessThan(n.indexOf('anthropic'));
+ });
+
+ it('enabled/primary: vertex LEADS the chain, before the free lanes', () => {
+ process.env.VERTEX_CLAUDE_ENABLED = '1';
+ process.env.VERTEX_CLAUDE_PRIMARY = '1';
+ const n = names();
+ expect(n[0]).toBe('vertex-anthropic');
+ expect(n.indexOf('vertex-anthropic')).toBeLessThan(n.indexOf('groq'));
+ // Not added twice (primary path only).
+ expect(n.filter((x) => x === 'vertex-anthropic')).toHaveLength(1);
+ });
+
+ it('primary flag alone (enabled unset) leaves the chain unchanged', () => {
+ process.env.VERTEX_CLAUDE_PRIMARY = '1';
+ expect(names()).toEqual(['groq', 'anthropic']);
+ });
+
+ it('a caller BYOK key still leads even when vertex is primary', () => {
+ process.env.VERTEX_CLAUDE_ENABLED = '1';
+ process.env.VERTEX_CLAUDE_PRIMARY = '1';
+ const n = providerChain({ anthropicKey: 'byok' }).map((p) => p.name);
+ expect(n[0]).toBe('anthropic'); // BYOK anthropicProvider leads
+ expect(n[1]).toBe('vertex-anthropic');
+ });
+});
diff --git a/vercel.json b/vercel.json
index 7655619f3..82ea60c72 100644
--- a/vercel.json
+++ b/vercel.json
@@ -4737,6 +4737,10 @@
"path": "/api/cron/dead-man-switch",
"schedule": "0 5 * * *"
},
+ {
+ "path": "/api/cron/gcp-burn-report",
+ "schedule": "0 14 * * *"
+ },
{
"path": "/api/cron/auto-rig-sweep",
"schedule": "*/5 * * * *"
diff --git a/workers/vanity-grinder/grind.mjs b/workers/vanity-grinder/grind.mjs
new file mode 100644
index 000000000..fab566661
--- /dev/null
+++ b/workers/vanity-grinder/grind.mjs
@@ -0,0 +1,308 @@
+#!/usr/bin/env node
+// Batch vanity grinder — the premium-inventory producer.
+//
+// Runs a pool of WASM grind workers (one per vCPU) over a target list, SEALS each
+// found keypair in-process (api/_lib/vanity-vault.js) BEFORE any write, and
+// appends the ENCRYPTED record to an output JSONL (and, when configured, straight
+// into the vanity_inventory table). Plaintext keys never touch disk, a log, or
+// the network.
+//
+// RESUMABLE: a checkpoint file records which targets are already done. On restart
+// (spot preemption → the MIG relaunches, or Cloud Run Job retry) it skips
+// completed targets and continues. SIGTERM (the preemption signal) flushes the
+// checkpoint and exits cleanly so no in-flight state is lost — an interrupted
+// target simply restarts from scratch (a random search has no resumable inner
+// state; expected work is unchanged).
+//
+// Designed for GCP spot CPU (Cloud Run Job or a GCE spot MIG) but runs anywhere
+// with Node — the local dev run that seeds the initial inventory uses the exact
+// same code path (see docs/gcp-credits.md).
+//
+// Config (all via env):
+// OUTPUT_FILE encrypted JSONL out (default ./out/inventory.jsonl)
+// CHECKPOINT_FILE resume state (default ./out/checkpoint.json)
+// SUMMARY_FILE throughput summary (default ./out/summary.json)
+// TARGETS_FILE JSON array of {prefix?,suffix?,ignoreCase} (default: built-in list)
+// INCLUDE_5 '1' to include slow 5-char stretch targets
+// IGNORE_CASE '1' to fold case on prefix targets
+// MAX_FOUND stop after N addresses (default: all targets)
+// WORKERS worker count (default: available parallelism)
+// RETENTION_DAYS ciphertext retention after reveal (default 0 = delete-on-reveal)
+// BATCH_LABEL label for this run (default: timestamped)
+// RUNNER 'local' | 'cloud-run-job' | 'gce-spot-mig'
+// SHARD_INDEX/SHARD_COUNT partition the target list across parallel instances
+// WRITE_DB '1' to upsert into vanity_inventory (needs DATABASE_URL)
+// VANITY_KMS_KEY (optional) KMS crypto-key resource → envelope encryption
+// WALLET_ENCRYPTION_KEY the secret-box master key (required unless KMS)
+
+import { Worker } from 'node:worker_threads';
+import { fileURLToPath } from 'node:url';
+import { dirname, join, resolve } from 'node:path';
+import { mkdirSync, appendFileSync, writeFileSync, readFileSync, existsSync, openSync, fsyncSync, closeSync } from 'node:fs';
+import os from 'node:os';
+import bs58 from 'bs58';
+
+import { defaultTargets, targetId, labelFor } from './targets.mjs';
+import { computeRarity } from '../../src/solana/vanity/rarity.js';
+import { priceFromRarity } from '../../api/_lib/vanity-inventory-pricing.js';
+import { sealSecret, preferredScheme } from '../../api/_lib/vanity-vault.js';
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const env = process.env;
+
+const OUTPUT_FILE = resolve(env.OUTPUT_FILE || join(HERE, 'out', 'inventory.jsonl'));
+const CHECKPOINT_FILE = resolve(env.CHECKPOINT_FILE || join(HERE, 'out', 'checkpoint.json'));
+const SUMMARY_FILE = resolve(env.SUMMARY_FILE || join(HERE, 'out', 'summary.json'));
+const RETENTION_DAYS = Math.max(0, parseInt(env.RETENTION_DAYS || '0', 10) || 0);
+const MAX_FOUND = env.MAX_FOUND ? parseInt(env.MAX_FOUND, 10) : Infinity;
+const WORKER_COUNT = Math.max(1, parseInt(env.WORKERS || String(os.availableParallelism?.() || os.cpus().length), 10));
+const RUNNER = env.RUNNER || 'local';
+const BATCH_LABEL = env.BATCH_LABEL || `batch-${new Date().toISOString().replace(/[:.]/g, '-')}`;
+const WRITE_DB = env.WRITE_DB === '1' || env.WRITE_DB === 'true';
+
+function loadTargets() {
+ let list;
+ if (env.TARGETS_FILE && existsSync(resolve(env.TARGETS_FILE))) {
+ const raw = JSON.parse(readFileSync(resolve(env.TARGETS_FILE), 'utf8'));
+ list = raw.map((t) => ({ ignoreCase: !!t.ignoreCase, ...t, label: t.label || labelFor(t) }));
+ } else {
+ list = defaultTargets({ include5: env.INCLUDE_5 === '1', ignoreCase: env.IGNORE_CASE === '1' });
+ }
+ // Shard across parallel instances (a GCE MIG runs N of these).
+ const shardCount = Math.max(1, parseInt(env.SHARD_COUNT || '1', 10));
+ const shardIndex = Math.max(0, parseInt(env.SHARD_INDEX || '0', 10));
+ if (shardCount > 1) list = list.filter((_, i) => i % shardCount === shardIndex);
+ return list;
+}
+
+function loadCheckpoint() {
+ if (existsSync(CHECKPOINT_FILE)) {
+ try {
+ return JSON.parse(readFileSync(CHECKPOINT_FILE, 'utf8'));
+ } catch {
+ /* corrupt checkpoint — start fresh */
+ }
+ }
+ return { batchLabel: BATCH_LABEL, completed: [], found: 0, startedAt: new Date().toISOString() };
+}
+
+let checkpoint = loadCheckpoint();
+const completed = new Set(checkpoint.completed || []);
+
+function saveCheckpoint() {
+ checkpoint.completed = [...completed];
+ writeFileSync(CHECKPOINT_FILE, JSON.stringify(checkpoint, null, '\t'));
+}
+
+// Append an encrypted record durably (fsync so a preemption can't lose a found key).
+function appendEncrypted(record) {
+ const fd = openSync(OUTPUT_FILE, 'a');
+ try {
+ appendFileSync(fd, JSON.stringify(record) + '\n');
+ fsyncSync(fd);
+ } finally {
+ closeSync(fd);
+ }
+}
+
+// Lazily-loaded DB writer (only pulled in when WRITE_DB is set, so a file-only run
+// never needs Neon/DATABASE_URL).
+let _dbStore = null;
+async function dbUpsert(item) {
+ if (!WRITE_DB) return;
+ if (!_dbStore) _dbStore = await import('../../api/_lib/vanity-inventory-store.js');
+ await _dbStore.upsertInventoryItem(item);
+}
+
+// ── Stats ────────────────────────────────────────────────────────────────────
+const stats = { found: checkpoint.found || 0, totalAttempts: 0, startedAt: performance.now() };
+
+// ── Seal + persist a found keypair (MAIN thread only) ────────────────────────
+async function persistFound({ target, publicKey, secretKey, attempts, durationMs }) {
+ const rarity = computeRarity({ prefix: target.prefix, suffix: target.suffix, ignoreCase: target.ignoreCase });
+ const { priceUsd } = priceFromRarity(rarity);
+
+ // The plaintext bundle — sealed immediately, never written in the clear.
+ const secretKeyBase58 = bs58.encode(Buffer.from(secretKey));
+ const plaintext = JSON.stringify({
+ format: 'keypair',
+ address: publicKey,
+ secretKeyBase58,
+ secretKey: Array.from(secretKey),
+ });
+ const { ciphertext, scheme } = await sealSecret(plaintext);
+ // Scrub the plaintext material from local scope ASAP.
+ secretKey.fill(0);
+
+ const record = {
+ address: publicKey,
+ prefix: target.prefix || null,
+ suffix: target.suffix || null,
+ ignoreCase: !!target.ignoreCase,
+ patternLabel: target.label || labelFor(target),
+ format: 'keypair',
+ difficultyAttempts: rarity.expectedAttempts,
+ rarityBits: rarity.rarityBits,
+ rarityTier: rarity.tier,
+ rarityScore: rarity.rarityScore,
+ priceUsd,
+ retentionDays: RETENTION_DAYS,
+ secretCiphertext: ciphertext,
+ secretScheme: scheme,
+ batchLabel: BATCH_LABEL,
+ groundAt: new Date().toISOString(),
+ attempts,
+ foundInMs: Math.round(durationMs),
+ };
+ appendEncrypted(record);
+ await dbUpsert({
+ address: record.address,
+ prefix: record.prefix,
+ suffix: record.suffix,
+ ignoreCase: record.ignoreCase,
+ patternLabel: record.patternLabel,
+ format: record.format,
+ difficultyAttempts: record.difficultyAttempts,
+ rarityBits: record.rarityBits,
+ rarityTier: record.rarityTier,
+ rarityScore: record.rarityScore,
+ secretCiphertext: ciphertext,
+ secretScheme: scheme,
+ priceUsd,
+ retentionDays: RETENTION_DAYS,
+ });
+
+ stats.found += 1;
+ checkpoint.found = stats.found;
+ completed.add(targetId(target));
+ saveCheckpoint();
+ // One safe, secret-free progress line.
+ console.log(`[grind] found ${record.patternLabel} → ${publicKey} (${attempts.toLocaleString()} attempts, ${Math.round(durationMs)}ms) $${priceUsd} [${scheme}]`);
+}
+
+// ── Orchestration ────────────────────────────────────────────────────────────
+let stopping = false;
+
+async function main() {
+ mkdirSync(dirname(OUTPUT_FILE), { recursive: true });
+ // Fail fast if we can't encrypt — never grind keys we can't seal.
+ try {
+ await sealSecret('preflight');
+ } catch (err) {
+ console.error(`[grind] FATAL: cannot seal secrets (${err.message}). Set WALLET_ENCRYPTION_KEY (or VANITY_KMS_KEY). Refusing to grind unsealed keys.`);
+ process.exit(3);
+ }
+
+ const all = loadTargets();
+ const pending = all.filter((t) => !completed.has(targetId(t)));
+ console.log(`[grind] ${BATCH_LABEL} runner=${RUNNER} scheme=${preferredScheme()} workers=${WORKER_COUNT}`);
+ console.log(`[grind] targets: ${all.length} total, ${completed.size} already done, ${pending.length} to grind`);
+ if (!pending.length) {
+ await writeSummary(all.length);
+ console.log('[grind] nothing to do — inventory target list already complete.');
+ return;
+ }
+
+ let cursor = 0;
+ let active = 0;
+ const workers = [];
+
+ await new Promise((resolveAll) => {
+ const maybeFinish = () => {
+ if ((cursor >= pending.length && active === 0) || stopping) {
+ for (const w of workers) w.postMessage({ type: 'stop' });
+ resolveAll();
+ }
+ };
+
+ const assign = (worker) => {
+ if (stopping || cursor >= pending.length || stats.found >= MAX_FOUND) {
+ maybeFinish();
+ return;
+ }
+ const target = pending[cursor++];
+ active += 1;
+ worker.postMessage({ type: 'grind', target });
+ };
+
+ for (let i = 0; i < WORKER_COUNT; i++) {
+ const worker = new Worker(join(HERE, 'grind-worker.mjs'), { workerData: { index: i } });
+ workers.push(worker);
+ worker.on('message', async (msg) => {
+ if (msg.type === 'ready') {
+ assign(worker);
+ return;
+ }
+ if (msg.type === 'progress') {
+ stats.totalAttempts += msg.attempts;
+ return;
+ }
+ if (msg.type === 'found') {
+ stats.totalAttempts += msg.attempts;
+ try {
+ await persistFound(msg);
+ } catch (err) {
+ console.error(`[grind] persist failed for ${msg.publicKey}: ${err.message}`);
+ }
+ active -= 1;
+ if (stats.found >= MAX_FOUND) {
+ stopping = true;
+ maybeFinish();
+ return;
+ }
+ assign(worker);
+ return;
+ }
+ if (msg.type === 'aborted') {
+ active -= 1;
+ maybeFinish();
+ }
+ });
+ worker.on('error', (err) => {
+ console.error(`[grind] worker error: ${err.message}`);
+ active = Math.max(0, active - 1);
+ maybeFinish();
+ });
+ }
+ });
+
+ for (const w of workers) await w.terminate();
+ await writeSummary(all.length);
+}
+
+async function writeSummary(targetCount) {
+ const elapsedSec = (performance.now() - stats.startedAt) / 1000;
+ const keysPerSec = elapsedSec > 0 ? stats.totalAttempts / elapsedSec : 0;
+ const summary = {
+ batchLabel: BATCH_LABEL,
+ runner: RUNNER,
+ workers: WORKER_COUNT,
+ scheme: preferredScheme(),
+ targetCount,
+ found: stats.found,
+ totalAttempts: stats.totalAttempts,
+ elapsedSec: Math.round(elapsedSec * 100) / 100,
+ keysPerSec: Math.round(keysPerSec),
+ keysPerSecPerWorker: Math.round(keysPerSec / WORKER_COUNT),
+ preempted: stopping && stats.found < targetCount,
+ finishedAt: new Date().toISOString(),
+ };
+ writeFileSync(SUMMARY_FILE, JSON.stringify(summary, null, '\t'));
+ console.log(`[grind] summary: found ${summary.found}, ${summary.keysPerSec.toLocaleString()} keys/sec (${summary.keysPerSecPerWorker.toLocaleString()}/worker), ${summary.elapsedSec}s`);
+ return summary;
+}
+
+// Spot preemption: SIGTERM arrives ~30s before shutdown. Flush + exit cleanly.
+for (const sig of ['SIGTERM', 'SIGINT']) {
+ process.on(sig, () => {
+ if (stopping) return;
+ console.log(`[grind] ${sig} received — checkpointing and shutting down`);
+ stopping = true;
+ saveCheckpoint();
+ });
+}
+
+main().catch((err) => {
+ console.error('[grind] fatal:', err);
+ process.exit(1);
+});
diff --git a/workers/vanity-grinder/wasm-grind.mjs b/workers/vanity-grinder/wasm-grind.mjs
index 22d10d62f..e8e78e0fd 100644
--- a/workers/vanity-grinder/wasm-grind.mjs
+++ b/workers/vanity-grinder/wasm-grind.mjs
@@ -10,10 +10,12 @@
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
-import { dirname, join } from 'node:path';
-import { initSync, grind } from './wasm/vanity_grinder.js';
+import { initSync, grind } from '../../src/solana/vanity/wasm/vanity_grinder.js';
-const HERE = dirname(fileURLToPath(import.meta.url));
+// The .wasm sits next to its glue in the canonical source tree; the container
+// preserves that repo-relative layout (see Dockerfile), so one path works both
+// locally and in the image.
+const WASM_PATH = fileURLToPath(new URL('../../src/solana/vanity/wasm/vanity_grinder_bg.wasm', import.meta.url));
// Keypairs per WASM call. Big enough that per-call overhead is negligible, small
// enough that a SIGTERM (spot preemption) is observed within a fraction of a
@@ -23,8 +25,7 @@ const BATCH_SIZE = 25_000;
let ready = false;
function ensureWasm() {
if (ready) return;
- const bytes = readFileSync(join(HERE, 'wasm', 'vanity_grinder_bg.wasm'));
- initSync({ module: bytes });
+ initSync({ module: readFileSync(WASM_PATH) });
ready = true;
}