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: add identity studio tools for agent identity creation and status polling
fudjia86472911e8da
diff --git a/api/_lib/env.js b/api/_lib/env.jsindex d74456c60..9ed77de44 100644--- a/api/_lib/env.js+++ b/api/_lib/env.js@@ -752,12 +752,25 @@ export const env = {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).+ // OKX SA API credentials (dev-portal API key) — auth for the official OKX+ // facilitator at https://web3.okx.com/api/v6/pay/x402/{verify,settle}+ // (HMAC-SHA256 per OKX REST auth). The primary settlement route for the+ // X Layer rail; env names match the official @okxweb3 SDK examples.+ get OKX_API_KEY() {+ return opt('OKX_API_KEY');+ },+ get OKX_SECRET_KEY() {+ return opt('OKX_SECRET_KEY');+ },+ get OKX_PASSPHRASE() {+ return opt('OKX_PASSPHRASE');+ },+ // Fallback relayer private key that redeems buyers' EIP-3009+ // authorizations on X Layer directly (broadcasts transferWithAuthorization;+ // pays OKB gas) when OKX facilitator credentials are absent. Secret. With+ // neither this nor the OKX API creds set, 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');},diff --git a/api/_lib/okx-catalog.js b/api/_lib/okx-catalog.jsnew file mode 100644index 000000000..011548ede--- /dev/null+++ b/api/_lib/okx-catalog.js@@ -0,0 +1,213 @@+// OKX.AI (X Layer agent marketplace) service catalog — the single source of+// truth for every A2MCP service agent #2632 "three.ws 3D Studio" sells on+// OKX.AI. Endpoints, the free catalog/health service, tests, AND the listing+// update submitted to OKX all read from this module, so the live endpoints can+// never drift from the marketplace listing.+//+// OKX listing format: every service carries a 2-part description — part 1 says+// what the service does, part 2 says what the caller must provide — and each+// part must fit in 200 display-width characters, where East-Asian wide glyphs+// count 2 and everything else counts 1 (OKX rejects over-length listings).+// `validateCatalog()` enforces this; tests/okx-catalog.test.js runs it in CI.+//+// Work order 03 (prompts/okx-ai/03-service-decomposition.md) decomposes the+// rest of the 3D studio into rows of this catalog; work order 06 seeded it+// with the Agent Identity Studio flagship plus the free discovery lane.++const BASE = 'https://three.ws';++// Display width per the OKX listing rule: East-Asian Wide / Fullwidth code+// points count 2, everything else counts 1. Ranges follow Unicode UAX #11+// (W/F categories) closely enough for listing validation: CJK ideographs and+// radicals, Hangul, Kana, fullwidth forms, and the supplementary ideographic+// planes.+export function displayWidth(str) {+ let width = 0;+ for (const ch of String(str ?? '')) {+ const cp = ch.codePointAt(0);+ const wide =+ (cp >= 0x1100 && cp <= 0x115f) || // Hangul Jamo+ (cp >= 0x2e80 && cp <= 0x303e) || // CJK radicals, Kangxi, CJK symbols+ (cp >= 0x3041 && cp <= 0x33ff) || // Kana, CJK compat+ (cp >= 0x3400 && cp <= 0x4dbf) || // CJK ext A+ (cp >= 0x4e00 && cp <= 0x9fff) || // CJK unified+ (cp >= 0xa000 && cp <= 0xa4cf) || // Yi+ (cp >= 0xac00 && cp <= 0xd7a3) || // Hangul syllables+ (cp >= 0xf900 && cp <= 0xfaff) || // CJK compat ideographs+ (cp >= 0xfe30 && cp <= 0xfe4f) || // CJK compat forms+ (cp >= 0xff00 && cp <= 0xff60) || // Fullwidth forms+ (cp >= 0xffe0 && cp <= 0xffe6) || // Fullwidth signs+ (cp >= 0x20000 && cp <= 0x3fffd); // Supplementary ideographic planes+ width += wide ? 2 : 1;+ }+ return width;+}++export const DESCRIPTION_MAX_WIDTH = 200;++// USDC uses 6 decimals on every rail we accept.+function usdToAtomics(usd) {+ return String(Math.round(Number(usd) * 1e6));+}++// One row per marketplace service. Fields:+// id URL slug — the service's route is /api/okx/3d/<id>+// name Listing display name+// kind 'a2mcp' (MCP Streamable HTTP JSON-RPC) | 'rest' (plain JSON GET)+// describes 2-part OKX listing description { capability, input }+// priceUsd Retail price in USD as a string ('0' = free)+// amountAtomics x402 amount (USDC 6-decimals atomic string), null = free+// endpoint Absolute endpoint URL buyers call+// tool For a2mcp services: the paid MCP tool name on that endpoint+// inputSchema JSON Schema of the paid call's arguments (free lanes: response shape)+export const OKX_CATALOG = Object.freeze([+ {+ id: 'identity-studio',+ name: 'Agent Identity Studio',+ kind: 'a2mcp',+ describes: {+ capability:+ 'Creates a 3D identity for an AI agent from a text brief: a rigged, animation-ready GLB ' ++ 'avatar plus posed studio renders — a square PFP sized for the OKX avatar slot and ' ++ 'full-body shots.',+ input:+ 'Call create_identity with agent_name and a brief (any language); optional style_hints ' ++ 'and reference_image_url. Returns a job_id — poll identity_status free until the ' ++ 'deliverables are ready.',+ },+ priceUsd: '1.50',+ amountAtomics: usdToAtomics(1.5),+ endpoint: `${BASE}/api/okx/3d/identity-studio`,+ tool: 'create_identity',+ inputSchema: {+ type: 'object',+ required: ['agent_name', 'brief'],+ additionalProperties: false,+ properties: {+ agent_name: {+ type: 'string',+ minLength: 1,+ maxLength: 80,+ description: 'The agent’s display name. Rendered into the identity brief.',+ },+ brief: {+ type: 'string',+ minLength: 3,+ maxLength: 4000,+ description:+ 'Personality / brand description in any language. Longer than 2000 characters is ' ++ 'truncated (the response flags brief_truncated).',+ },+ style_hints: {+ type: 'string',+ maxLength: 500,+ description: 'Optional visual direction: palette, materials, era, mood.',+ },+ reference_image_url: {+ type: 'string',+ format: 'uri',+ description:+ 'Optional public image to guide the look. Validated before any charge — an ' ++ 'unreachable URL fails the call without settling payment.',+ },+ },+ },+ },+ {+ id: 'catalog',+ name: '3D Studio Catalog (free)',+ kind: 'rest',+ describes: {+ capability:+ 'Free machine-readable index of every three.ws 3D Studio service on OKX.AI: names, ' ++ 'descriptions, prices, endpoints, and input schemas — generated from the module the ' ++ 'endpoints run on.',+ input: 'GET with no parameters. No payment, no account.',+ },+ priceUsd: '0',+ amountAtomics: null,+ endpoint: `${BASE}/api/okx/3d/catalog`,+ tool: null,+ inputSchema: null,+ },+ {+ id: 'health',+ name: '3D Studio Health (free)',+ kind: 'rest',+ describes: {+ capability:+ 'Free live health of the 3D studio lanes backing every paid service: generation, ' ++ 'rigging, rendering, and storage — real subsystem probes, not a hardcoded OK.',+ input: 'GET with no parameters. No payment, no account.',+ },+ priceUsd: '0',+ amountAtomics: null,+ endpoint: `${BASE}/api/okx/3d/health`,+ tool: null,+ inputSchema: null,+ },+]);++export function catalogEntry(id) {+ return OKX_CATALOG.find((e) => e.id === id) || null;+}++// The machine-readable index the free catalog service returns — the exact+// payload OKX buyers (and work order 05's listing update) consume.+export function catalogIndex() {+ return {+ provider: 'three.ws 3D Studio',+ okxAgentId: 2632,+ chain: 'eip155:196',+ services: OKX_CATALOG.map((e) => ({+ id: e.id,+ name: e.name,+ kind: e.kind,+ description: e.describes,+ price_usd: e.priceUsd,+ endpoint: e.endpoint,+ ...(e.tool ? { tool: e.tool } : {}),+ ...(e.inputSchema ? { input_schema: e.inputSchema } : {}),+ })),+ docs: `${BASE}/docs/okx-marketplace`,+ };+}++// Catalog integrity check — throws on the first malformed entry. Tests call+// this; anything that would get the listing rejected fails CI instead.+export function validateCatalog(catalog = OKX_CATALOG) {+ const seen = new Set();+ for (const e of catalog) {+ const ctx = `okx-catalog entry "${e?.id}"`;+ if (!e.id || !/^[a-z0-9-]+$/.test(e.id)) throw new Error(`${ctx}: bad id`);+ if (seen.has(e.id)) throw new Error(`${ctx}: duplicate id`);+ seen.add(e.id);+ if (!e.name) throw new Error(`${ctx}: missing name`);+ if (!['a2mcp', 'rest'].includes(e.kind)) throw new Error(`${ctx}: bad kind`);+ for (const part of ['capability', 'input']) {+ const text = e.describes?.[part];+ if (!text) throw new Error(`${ctx}: missing describes.${part}`);+ const w = displayWidth(text);+ if (w > DESCRIPTION_MAX_WIDTH) {+ throw new Error(`${ctx}: describes.${part} display width ${w} > ${DESCRIPTION_MAX_WIDTH}`);+ }+ }+ if (!/^\d+(\.\d{1,2})?$/.test(e.priceUsd)) throw new Error(`${ctx}: bad priceUsd`);+ const free = e.priceUsd === '0';+ if (free && e.amountAtomics !== null) throw new Error(`${ctx}: free row must have null atomics`);+ if (!free) {+ if (!/^\d+$/.test(e.amountAtomics ?? '')) throw new Error(`${ctx}: bad amountAtomics`);+ if (String(Math.round(Number(e.priceUsd) * 1e6)) !== e.amountAtomics) {+ throw new Error(`${ctx}: amountAtomics does not equal priceUsd in USDC atomics`);+ }+ }+ if (!/^https:\/\/three\.ws\/api\/okx\/3d\/[a-z0-9-]+$/.test(e.endpoint)) {+ throw new Error(`${ctx}: endpoint must be https://three.ws/api/okx/3d/<id>`);+ }+ if (!e.endpoint.endsWith(`/${e.id}`)) throw new Error(`${ctx}: endpoint/id mismatch`);+ if (e.kind === 'a2mcp' && (!e.tool || !e.inputSchema)) {+ throw new Error(`${ctx}: a2mcp row needs tool + inputSchema`);+ }+ }+ return true;+}diff --git a/api/_lib/x402-spec.js b/api/_lib/x402-spec.jsindex f5c4ff4da..1d9b4145f 100644--- a/api/_lib/x402-spec.js+++ b/api/_lib/x402-spec.js@@ -57,6 +57,13 @@ import {} from './x402-builder-code.js';import { buildOffersExtension } from './x402/offer-receipt-server.js';import { offerReceiptDeclaration } from './x402-offer-receipt.js';+import {+ NETWORK_XLAYER_MAINNET,+ okxXLayerAccept,+ settleOkxXLayerPayment,+ verifyOkxXLayerPayment,+ xlayerSettleable,+} from './x402-xlayer-okx.js';import {resolveSolanaFacilitator,selfFacilitatorEnabled,@@ -93,6 +100,7 @@ export const NETWORK_BASE_MAINNET = 'eip155:8453';export const NETWORK_BASE_SEPOLIA = 'eip155:84532';export const NETWORK_ARBITRUM_MAINNET = 'eip155:42161';export const NETWORK_BSC_MAINNET = 'eip155:56';+export { NETWORK_XLAYER_MAINNET };export const NETWORK_SOLANA_MAINNET = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';export const NETWORK_SOLANA_DEVNET = 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1';@@ -228,6 +236,14 @@ export function paymentRequirements(resourceUrl, { amount } = {}) {},});}+ // OKX Agent Payments Protocol rail — USD₮0 on X Layer (eip155:196), per+ // specs/okx-agent-payments.md. Advertised only when settlement is actually+ // possible (OKX facilitator creds or the direct-redemption relayer key).+ // USD₮0 shares USDC's 6-decimal atomic scale, so per-tool amounts carry+ // over unchanged.+ if (xlayerSettleable()) {+ out.push(okxXLayerAccept(resourceUrl, common.amount));+ }return out;}@@ -268,6 +284,12 @@ export function facilitatorFor(network) {if (DIRECT_NETWORKS.has(network) || network === 'bsc') {return { direct: true };}+ // X Layer settles via the OKX Agent Payments Protocol rail — the official+ // OKX facilitator when credentialed, direct EIP-3009 redemption otherwise.+ // The {okxXLayer:true} marker routes to x402-xlayer-okx.js.+ if (network === NETWORK_XLAYER_MAINNET || network === 'xlayer') {+ return { okxXLayer: true };+ }// EVM mainnets supported by Coinbase CDP. When CDP keys are set, route all// of them through CDP (required for CDP Bazaar / agentic.market — only// endpoints whose first verify+settle is processed by CDP get cataloged).@@ -762,7 +784,12 @@ function isAuthHintAccept(requirement) {// against. Falls back to first-match-by-network for non-EVM payloads (Solana// SPL, BSC direct).function selectRequirement(paymentPayload, allRequirements) {- const network = paymentPayload?.network || paymentPayload?.paymentRequirements?.network;+ // OKX-dialect payloads (PAYMENT-SIGNATURE header) carry the chosen entry as+ // `accepted` instead of top-level scheme/network — see x402-xlayer-okx.js.+ const network =+ paymentPayload?.network ||+ paymentPayload?.accepted?.network ||+ paymentPayload?.paymentRequirements?.network;const method = detectAssetTransferMethod(paymentPayload);const matchesMethod = (r) => {if (!method) return true;@@ -984,6 +1011,15 @@ export async function verifyPayment({ paymentHeader, requirements, builderCode }directVerified,};}+ if (config.okxXLayer) {+ const okxVerified = await verifyOkxXLayerPayment({ paymentPayload, requirement });+ return {+ paymentPayload,+ requirement,+ payer: okxVerified.payer,+ okxVerified,+ };+ }const result = await callFacilitator(requirement.network, '/verify', {x402Version: X402_VERSION,paymentPayload,@@ -1071,6 +1107,17 @@ export async function settlePayment(args) {}return settleDirectPayment({ verified: directVerified, requirement });}+ if (config.okxXLayer) {+ const okxVerified = verified?.okxVerified || args?.okxVerified;+ if (!okxVerified) {+ throw new X402Error(+ 'settle_failed',+ 'X Layer settle requires the verify step to run first',+ 500,+ );+ }+ return settleOkxXLayerPayment({ verified: okxVerified, requirement, paymentPayload });+ }const idempotencyKey = buildIdempotencyKey({ paymentPayload, requirement });const result = await callFacilitator(requirement.network,diff --git a/api/_lib/x402-xlayer-okx.js b/api/_lib/x402-xlayer-okx.jsindex 196ee057f..489c27491 100644--- a/api/_lib/x402-xlayer-okx.js+++ b/api/_lib/x402-xlayer-okx.js@@ -25,11 +25,15 @@// 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."+// 5. Settlement routes through OKX's official facilitator when OKX SA API+// credentials are configured — POST https://web3.okx.com/api/v6/pay/x402/+// settle with syncSettle:true (HMAC-SHA256 auth; the exact client the+// official @okxweb3/app-x402-core SDK ships). Verification likewise gets+// a facilitator /verify pass on top of the local checks. Without OKX+// creds, the seller redeems the authorization DIRECTLY — broadcasts+// transferWithAuthorization from a relayer key (OKB gas); 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@@ -44,6 +48,7 @@ import {} from 'viem';import { privateKeyToAccount } from 'viem/accounts';import { xLayer } from 'viem/chains';+import { OKXFacilitatorClient } from '@okxweb3/app-x402-core';import { env } from './env.js';import { X402Error } from './x402-errors.js';@@ -145,12 +150,37 @@ export function xlayerClient() {return cachedClient;}+// Are the OKX SA API credentials for the official facilitator configured?+export function okxFacilitatorConfigured() {+ return Boolean(env.OKX_API_KEY && env.OKX_SECRET_KEY && env.OKX_PASSPHRASE);+}++// Singleton facilitator client (official SDK). syncSettle:true — the seller+// waits for on-chain confirmation before responding, per the SDK's+// recommended seller configuration, so PAYMENT-RESPONSE always carries a+// confirmed transaction.+let cachedFacilitator = null;+function okxFacilitator() {+ if (!cachedFacilitator) {+ cachedFacilitator = new OKXFacilitatorClient({+ apiKey: env.OKX_API_KEY,+ secretKey: env.OKX_SECRET_KEY,+ passphrase: env.OKX_PASSPHRASE,+ syncSettle: true,+ });+ }+ return cachedFacilitator;+}+// 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.+// the receiver, the asset, and a working settlement route (OKX facilitator+// creds, or the direct-redemption 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,+ env.X402_PAY_TO_XLAYER &&+ env.X402_ASSET_ADDRESS_XLAYER &&+ (okxFacilitatorConfigured() || env.X402_XLAYER_RELAYER_KEY),);}@@ -347,6 +377,30 @@ export async function verifyOkxXLayerPayment({ paymentPayload, requirement }) {throw new X402Error('invalid_payment', 'insufficient_balance', 402);}+ // Facilitator pass — when the OKX SA API creds are configured, the official+ // facilitator gets the final word on validity (it is also the settlement+ // submitter). The local checks above stay as defense-in-depth, mirroring+ // how the CDP/PayAI paths cross-check facilitator answers.+ if (okxFacilitatorConfigured()) {+ let result;+ try {+ result = await okxFacilitator().verify(paymentPayload, requirement);+ } catch (err) {+ throw new X402Error(+ 'facilitator_error',+ `OKX facilitator /verify failed: ${err.message}`,+ 502,+ );+ }+ if (!result?.isValid) {+ throw new X402Error(+ 'invalid_payment',+ `payment rejected by OKX facilitator: ${result?.invalidReason || result?.invalidMessage || 'unknown reason'}`,+ 402,+ );+ }+ }+return {isValid: true,payer: from,@@ -374,13 +428,14 @@ function relayerAccount() {}}-// 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 }) {+// Settle the verified payment. Primary route: the official OKX facilitator+// (POST /api/v6/pay/x402/settle, syncSettle:true) — it broadcasts the+// EIP-3009 redemption and waits for confirmation. Fallback (no OKX creds):+// redeem directly — broadcast transferWithAuthorization from the relayer+// (OKB gas) and wait for inclusion. Both return the same {success,+// transaction, network, payer} shape the other facilitator paths yield, so+// X-PAYMENT-RESPONSE / PAYMENT-RESPONSE emission is identical.+export async function settleOkxXLayerPayment({ verified, requirement, paymentPayload }) {if (!verified?.authorization || !verified?.signature) {throw new X402Error('settle_failed', 'X Layer settle requires the verify step to run first', 500);}@@ -391,6 +446,38 @@ export async function settleOkxXLayerPayment({ verified, requirement }) {500,);}+ if (okxFacilitatorConfigured()) {+ if (!paymentPayload) {+ throw new X402Error('settle_failed', 'facilitator settle requires the original paymentPayload', 500);+ }+ let result;+ try {+ result = await okxFacilitator().settle(paymentPayload, requirement);+ } catch (err) {+ throw new X402Error(+ 'settle_failed',+ `OKX facilitator /settle failed: ${err.message}`,+ 502,+ );+ }+ // syncSettle:true → status "success" with a confirmed tx. A "pending"+ // (async facilitator mode) still means the facilitator accepted the+ // settlement — surface it with the tx for /settle/status polling.+ if (!result?.success && result?.status !== 'pending') {+ throw new X402Error(+ 'settle_failed',+ `OKX facilitator settle rejected: ${result?.errorReason || 'unknown reason'}`,+ 502,+ );+ }+ return {+ success: true,+ transaction: result.transaction,+ network: result.network || NETWORK_XLAYER_MAINNET,+ payer: result.payer || verified.payer,+ ...(result.status ? { status: result.status } : {}),+ };+ }const account = relayerAccount();const client = xlayerClient();const wallet = createWalletClient({@@ -472,6 +559,7 @@ export async function xlayerRailHealth() {]);out.rpc = { ok: true, block: block.toString() };out.token = { ok: true, symbol };+ out.facilitator = { configured: okxFacilitatorConfigured() };if (env.X402_XLAYER_RELAYER_KEY) {try {const relayer = relayerAccount();diff --git a/api/_mcp/auth.js b/api/_mcp/auth.jsindex 448c0b83a..fe926d457 100644--- a/api/_mcp/auth.js+++ b/api/_mcp/auth.js@@ -91,7 +91,10 @@ export async function authenticateRequest({ x402Amount, resourcePath = '/api/mcp', challenge, allowFree = false } = {},) {const bearer = extractBearer(req);- const paymentHeader = req.headers['x-payment'];+ // OKX Agent Payments Protocol buyers replay with PAYMENT-SIGNATURE (x402 v2+ // HTTP transport); everything else uses the legacy X-PAYMENT name. Same+ // base64-JSON payload either way — verifyPayment handles both dialects.+ const paymentHeader = req.headers['x-payment'] || req.headers['payment-signature'];if (bearer) {const auth = await authenticateBearer(bearer, { audience: env.MCP_RESOURCE });@@ -173,7 +176,7 @@ export async function handleSse(req, res, { resourcePath = '/api/mcp', challenge// WWW-Authenticate so OAuth clients (claude.ai) can discover the auth// server, with the x402 envelope still attached for x402 clients. Invalid// bearers also get 401 with WWW-Authenticate so they can re-auth correctly.- if (!bearer && !req.headers['x-payment']) {+ if (!bearer && !req.headers['x-payment'] && !req.headers['payment-signature']) {const sseResourceUrl = resolveResourceUrl(req, resourcePath);return await sendAuthChallenge(res, {req,diff --git a/api/_okx3d/identity.js b/api/_okx3d/identity.jsnew file mode 100644index 000000000..fb46844bc--- /dev/null+++ b/api/_okx3d/identity.js@@ -0,0 +1,635 @@+// Agent Identity Studio pipeline — the engine behind the paid+// /api/okx/3d/identity-studio A2MCP service (see api/_lib/okx-catalog.js).+//+// Turns a brand brief into a complete 3D identity for an AI agent:+// brief → identity prompt (Granite director, fail-soft)+// → textured mesh (/api/forge)+// → humanoid auto-rig (/api/forge?action=rig)+// → posed studio renders (/api/render/avatar-clip + sharp compositing)+// → PFP crop (square, reads at 128px) + full-body set, persisted to R2.+//+// Every GPU/render stage is driven over the deployed three.ws HTTP surfaces —+// the exact pattern the npx MCP server (mcp-server/src/tools/_studio-core.js)+// uses — so this module behaves identically inside the Vercel function and in+// a local run (scripts/okx-identity-demo.mjs), and holds no provider keys.+//+// Job model: state lives as one JSON document in R2. create() validates the+// brief (and reference image reachability) BEFORE the transport settles the+// x402 payment, submits generation, and returns a signed job token. Each free+// identity_status poll advances the pipeline by ONE bounded step (a single+// upstream poll, or one render), so no request outlives its function budget+// and polling is what drives the job to completion. Failed generate/rig+// stages retry free up to MAX_STAGE_ATTEMPTS — the buyer pays once, for+// deliverables, not for our transient failures.++import { createHash } from 'node:crypto';+import { putObject, getObjectBuffer, publicUrl } from '../_lib/r2.js';+import { encodeJobToken, decodeJobToken } from '../_lib/forge-job-token.js';+import { assertSafePublicUrl } from '../_lib/ssrf-guard.js';+import { PRESETS } from '../../src/pose-presets.js';++const BASE = 'https://three.ws';+const JOB_PROVIDER = 'okxid';+const JOB_PREFIX = 'okx-identity/jobs';+const RENDER_PREFIX = 'okx-identity/renders';++export const MAX_BRIEF_CHARS = 2000;+const MAX_STAGE_ATTEMPTS = 3;++// The PFP pose is pinned to a neutral standing preset: the head-crop geometry+// below assumes the top of the model's alpha bounding box is the head, which+// raised-arm poses would break. Full-body poses draw from a shortlist that+// reads well as a brand identity (confident, natural stances — no floor poses).+const PFP_POSE = 'contrapposto';+const FULLBODY_POSES = [+ 'hands-on-hips',+ 'relaxed',+ 'wave',+ 'salute',+ 'point',+ 'fighting-stance',+ 'walk-step',+ 'flex',+];+const FULLBODY_COUNT = 3;+const FULLBODY_THETAS = [0, 24, -18];++const KNOWN_POSES = new Set(PRESETS.map((p) => p.id));++export const IDENTITY_DIRECTOR_INSTRUCTION =+ 'You are a 3D character art director designing the visual identity of an AI agent. From the ' ++ "agent's name and brand brief, write ONE concise prompt for a text-to-3D generator that will be " ++ 'auto-rigged. Describe a SINGLE full-body humanoid character that embodies the brand: body type, ' ++ 'outfit, materials, colors, and one signature visual motif. Standing neutral pose, arms slightly ' ++ 'away from the body, plain background. No scene, no props held across the body, no multiple ' ++ 'characters, no text or logos. The brief may be in any language; ALWAYS write the prompt in ' ++ 'English. Output ONLY the rewritten prompt as a single line — no preamble, no quotes.';++function sleep(ms) {+ return new Promise((r) => setTimeout(r, ms));+}++function pipelineError(code, message, extra = {}) {+ return Object.assign(new Error(message), { code, ...extra });+}++function jobKey(id) {+ return `${JOB_PREFIX}/${id}.json`;+}++export function encodeIdentityJobToken(id) {+ return encodeJobToken({ provider: JOB_PROVIDER, kind: 'identity', taskId: id });+}++export function decodeIdentityJobToken(token) {+ const decoded = decodeJobToken(token);+ if (!decoded || decoded.provider !== JOB_PROVIDER) return null;+ return decoded.taskId;+}++async function loadState(id) {+ try {+ const buf = await getObjectBuffer(jobKey(id));+ return JSON.parse(buf.toString('utf8'));+ } catch {+ return null;+ }+}++async function saveState(state) {+ state.updatedAt = new Date().toISOString();+ await putObject({+ key: jobKey(state.id),+ body: Buffer.from(JSON.stringify(state), 'utf8'),+ contentType: 'application/json',+ });+ return state;+}++// ---------------------------------------------------------------------------+// Prompt shaping+// ---------------------------------------------------------------------------++// Granite director over the deployed /api/chat SSE endpoint — same fail-soft+// contract as the avatar lane: any failure returns null and the deterministic+// template below takes over. Never fabricates.+async function directIdentityPrompt({ base, agentName, brief, styleHints }) {+ const idea =+ `Agent name: ${agentName}\nBrand brief: ${brief}` ++ (styleHints ? `\nStyle hints: ${styleHints}` : '');+ let res;+ try {+ res = await fetch(`${base}/api/chat`, {+ method: 'POST',+ headers: { 'content-type': 'application/json', accept: 'text/event-stream' },+ body: JSON.stringify({+ provider: 'watsonx',+ message: `${IDENTITY_DIRECTOR_INSTRUCTION}\n\nIdea: ${idea}`,+ }),+ signal: AbortSignal.timeout(30_000),+ });+ } catch {+ return null;+ }+ if (!res.ok || !res.body) return null;+ let acc = '';+ try {+ const reader = res.body.getReader();+ const decoder = new TextDecoder();+ let buf = '';+ for (;;) {+ const { value, done } = await reader.read();+ if (done) break;+ buf += decoder.decode(value, { stream: true });+ const lines = buf.split('\n');+ buf = lines.pop() ?? '';+ for (const line of lines) {+ if (!line.startsWith('data: ')) continue;+ let evt;+ try {+ evt = JSON.parse(line.slice(6));+ } catch {+ continue;+ }+ if (evt.type === 'chunk' && typeof evt.text === 'string') acc += evt.text;+ else if (evt.type === 'error') return null;+ else if (evt.type === 'done' && typeof evt.text === 'string' && !acc) acc = evt.text;+ }+ }+ } catch {+ return null;+ }+ const refined = acc.trim().replace(/^["']|["']$/g, '').split('\n')[0].trim();+ return refined.length >= 3 && refined.length <= 1000 ? refined : null;+}++// Deterministic fallback when the director is unreachable. Forces the humanoid+// framing rigging requires — an identity brief ("a finance data agent") rarely+// names a humanoid subject, so unlike forge_avatar there is no humanoid gate+// here: the subject is BY CONSTRUCTION a humanoid character embodying the+// brief, in both the director instruction and this template.+export function fallbackIdentityPrompt({ agentName, brief, styleHints }) {+ const hints = styleHints ? `, ${styleHints}` : '';+ return (+ `full-body humanoid character avatar embodying the AI agent "${agentName}": ${brief}${hints}, ` ++ 'standing in a neutral pose with arms slightly away from the body, plain background'+ );+}++export async function shapeIdentityPrompt({ base = BASE, agentName, brief, styleHints }) {+ const directed = await directIdentityPrompt({ base, agentName, brief, styleHints });+ return {+ directed,+ effective: directed || fallbackIdentityPrompt({ agentName, brief, styleHints }),+ };+}++// ---------------------------------------------------------------------------+// /api/forge client (submit / single poll / rig) — adapted from the npx MCP+// server's _studio-core.js, minus the internal polling loop: this pipeline+// polls upstream once per identity_status call instead of blocking.+// ---------------------------------------------------------------------------++async function submitForge(base, payload) {+ let res;+ try {+ res = await fetch(`${base}/api/forge`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(payload),+ signal: AbortSignal.timeout(30_000),+ });+ } catch (err) {+ throw pipelineError('provider_error', `forge unreachable: ${err?.message || err}`);+ }+ const data = await res.json().catch(() => ({}));+ if (res.status === 503) throw pipelineError('not_configured', data?.message || 'generation lane down');+ if (res.status === 429)+ throw pipelineError('rate_limited', data?.message || 'generator busy', {+ retryAfter: data?.retry_after,+ });+ if (!res.ok || !(data?.job_id || (data?.status === 'done' && data?.glb_url))) {+ throw pipelineError('provider_error', data?.message || `forge returned ${res.status}`);+ }+ return data;+}++async function pollForgeOnce(base, jobId) {+ let res;+ try {+ res = await fetch(`${base}/api/forge?job=${encodeURIComponent(jobId)}`, {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(15_000),+ });+ } catch (err) {+ // A transient poll failure is not a job failure — report still-running.+ return { status: 'running', _pollError: String(err?.message || err) };+ }+ const data = await res.json().catch(() => ({}));+ if (!res.ok) return { status: 'running', _pollError: `poll returned ${res.status}` };+ return data;+}++async function startRig(base, glbUrl) {+ let res;+ try {+ res = await fetch(`${base}/api/forge?action=rig`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ glb_url: glbUrl }),+ signal: AbortSignal.timeout(30_000),+ });+ } catch (err) {+ throw pipelineError('provider_error', `rig start unreachable: ${err?.message || err}`);+ }+ const data = await res.json().catch(() => ({}));+ if (res.status === 503 || res.status === 501)+ throw pipelineError('not_configured', data?.message || 'rig lane down');+ if (res.status === 429)+ throw pipelineError('rate_limited', data?.message || 'rigger busy', {+ retryAfter: data?.retry_after,+ });+ if (!res.ok || !data?.job_id)+ throw pipelineError('provider_error', data?.message || `rig start returned ${res.status}`);+ return data;+}++// ---------------------------------------------------------------------------+// Rendering + compositing+// ---------------------------------------------------------------------------++// Studio backdrop: brand-neutral dark radial gradient matching the three.ws+// dark tokens. Rasterized by sharp from SVG so no binary asset ships.+function backdropSvg(width, height) {+ return Buffer.from(+ `<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">` ++ `<defs><radialGradient id="g" cx="50%" cy="42%" r="72%">` ++ `<stop offset="0%" stop-color="#1a2030"/>` ++ `<stop offset="55%" stop-color="#10141d"/>` ++ `<stop offset="100%" stop-color="#0a0c10"/>` ++ `</radialGradient></defs>` ++ `<rect width="100%" height="100%" fill="url(#g)"/></svg>`,+ 'utf8',+ );+}++async function renderTransparent(base, { glbUrl, posePresetId, theta, size = 1600 }) {+ let res;+ try {+ res = await fetch(`${base}/api/render/avatar-clip`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ glbUrl,+ width: size,+ height: size,+ background: 'transparent',+ posePresetId,+ cameraOrbit: { theta, phi: 83, radius: null },+ }),+ signal: AbortSignal.timeout(45_000),+ });+ } catch (err) {+ throw pipelineError('render_failed', `renderer unreachable: ${err?.message || err}`);+ }+ if (!res.ok) {+ const data = await res.json().catch(() => ({}));+ throw pipelineError(+ data?.code === 'rate_limited' ? 'rate_limited' : 'render_failed',+ data?.message || `renderer returned ${res.status}`,+ );+ }+ return Buffer.from(await res.arrayBuffer());+}++// Trim the transparent render to the model's alpha bounding box. Returns the+// trimmed buffer plus its dimensions — the head-crop math keys off these.+async function trimToModel(sharp, png) {+ const trimmed = await sharp(png).trim({ threshold: 8 }).png().toBuffer({ resolveWithObject: true });+ return { buffer: trimmed.data, width: trimmed.info.width, height: trimmed.info.height };+}++// PFP: head-and-shoulders square crop from the top of the trimmed body. With+// the pinned neutral pose the bbox top IS the head; head+shoulders span+// roughly the top third of a standing humanoid, so the crop side is 36% of+// body height (clamped to body width so narrow models never over-crop).+async function composePfp(sharp, transparentPng, { outSize = 1024 }) {+ const body = await trimToModel(sharp, transparentPng);+ const side = Math.min(body.width, Math.max(64, Math.round(body.height * 0.36)));+ const left = Math.max(0, Math.round((body.width - side) / 2));+ const head = await sharp(body.buffer)+ .extract({ left, top: 0, width: side, height: Math.min(side, body.height) })+ .png()+ .toBuffer();+ // 8% breathing room around the head so the crop doesn't kiss the frame.+ const inner = Math.round(outSize * 0.84);+ const headResized = await sharp(head)+ .resize(inner, inner, { fit: 'contain', background: { r: 0, g: 0, b: 0, alpha: 0 } })+ .png()+ .toBuffer();+ const pad = Math.round((outSize - inner) / 2);+ return sharp(backdropSvg(outSize, outSize))+ .composite([{ input: headResized, left: pad, top: pad }])+ .png()+ .toBuffer();+}++// Full-body: the trimmed model composited over the backdrop in a 4:5 portrait+// frame with even margins.+async function composeFullBody(sharp, transparentPng, { outWidth = 1024, outHeight = 1280 }) {+ const body = await trimToModel(sharp, transparentPng);+ const maxW = Math.round(outWidth * 0.82);+ const maxH = Math.round(outHeight * 0.9);+ const scale = Math.min(maxW / body.width, maxH / body.height);+ const w = Math.max(1, Math.round(body.width * scale));+ const h = Math.max(1, Math.round(body.height * scale));+ const resized = await sharp(body.buffer).resize(w, h).png().toBuffer();+ return sharp(backdropSvg(outWidth, outHeight))+ .composite([{ input: resized, left: Math.round((outWidth - w) / 2), top: Math.round((outHeight - h) / 2) }])+ .png()+ .toBuffer();+}++async function uploadRender(id, name, png) {+ const key = `${RENDER_PREFIX}/${id}/${name}.png`;+ await putObject({ key, body: png, contentType: 'image/png' });+ return publicUrl(key);+}++// ---------------------------------------------------------------------------+// Job lifecycle+// ---------------------------------------------------------------------------++// Deterministic pose plan seeded from the job id — reproducible per job, varied+// across jobs. Slot n picks from the remaining shortlist by seed byte.+export function buildRenderPlan(id) {+ const seed = createHash('sha256').update(id).digest();+ const pool = [...FULLBODY_POSES];+ const plan = [{ kind: 'pfp', pose: PFP_POSE, theta: 14 }];+ for (let i = 0; i < FULLBODY_COUNT; i++) {+ const pick = seed[i] % pool.length;+ plan.push({ kind: 'fullbody', pose: pool.splice(pick, 1)[0], theta: FULLBODY_THETAS[i] });+ }+ // Belt and braces: a stale preset id in the shortlist must fail loudly in+ // tests, not 400 mid-job against the render endpoint.+ for (const step of plan) {+ if (!KNOWN_POSES.has(step.pose)) throw new Error(`unknown pose preset: ${step.pose}`);+ }+ return plan;+}++// Validate a caller-supplied reference image BEFORE the transport settles the+// payment: unreachable input must fail the call with nothing charged.+export async function validateReferenceImage(url) {+ await assertSafePublicUrl(url, { allowHttp: true });+ let res;+ try {+ res = await fetch(url, {+ method: 'GET',+ headers: { range: 'bytes=0-0' },+ signal: AbortSignal.timeout(15_000),+ });+ } catch (err) {+ throw pipelineError(+ 'reference_image_unreachable',+ `reference_image_url could not be fetched (${err?.message || err}). ` ++ 'Host it somewhere publicly reachable, or omit it. Nothing was charged.',+ );+ }+ if (!(res.ok || res.status === 206)) {+ throw pipelineError(+ 'reference_image_unreachable',+ `reference_image_url returned HTTP ${res.status}. Fix or omit it. Nothing was charged.`,+ );+ }+ const type = res.headers.get('content-type') || '';+ if (type && !type.startsWith('image/')) {+ throw pipelineError(+ 'reference_image_invalid',+ `reference_image_url serves "${type}", not an image. Nothing was charged.`,+ );+ }+}++export async function createIdentityJob({+ base = BASE,+ agentName,+ brief,+ styleHints,+ referenceImageUrl,+}) {+ const name = String(agentName ?? '').trim().slice(0, 80);+ const rawBrief = String(brief ?? '').trim();+ if (!name) throw pipelineError('invalid_input', 'agent_name is required.');+ if (rawBrief.length < 3) {+ throw pipelineError('invalid_input', 'brief must describe the agent in at least 3 characters.');+ }+ // Honest long-brief handling: hard truncation, flagged in every response.+ const briefTruncated = rawBrief.length > MAX_BRIEF_CHARS;+ const effectiveBrief = briefTruncated ? rawBrief.slice(0, MAX_BRIEF_CHARS) : rawBrief;+ const hints = styleHints ? String(styleHints).trim().slice(0, 500) : null;+ const refUrl = referenceImageUrl ? String(referenceImageUrl).trim() : null;+ if (refUrl) await validateReferenceImage(refUrl);++ const prompt = await shapeIdentityPrompt({+ base,+ agentName: name,+ brief: effectiveBrief,+ styleHints: hints,+ });++ const id = crypto.randomUUID();+ const gen = await submitForge(+ base,+ refUrl+ ? { image_urls: [refUrl], prompt: prompt.effective, aspect_ratio: '3:4' }+ : { prompt: prompt.effective, aspect_ratio: '3:4' },+ );++ const state = await saveState({+ id,+ createdAt: new Date().toISOString(),+ input: { agentName: name, brief: effectiveBrief, briefTruncated, styleHints: hints, referenceImageUrl: refUrl },+ prompt,+ stage: 'generate',+ attempts: { generate: 1, rig: 0 },+ gen: {+ jobId: gen.job_id ?? null,+ glbUrl: gen.status === 'done' ? gen.glb_url : null,+ backend: gen.backend ?? null,+ },+ rig: { jobId: null, glbUrl: null },+ plan: buildRenderPlan(id),+ renders: [],+ renderCursor: 0,+ error: null,+ });+ if (state.gen.glbUrl) {+ // Synchronous free-lane completion — jump straight to rigging.+ await beginRig(base, state);+ }+ return { jobId: encodeIdentityJobToken(id), state };+}++async function beginRig(base, state) {+ try {+ const rig = await startRig(base, state.gen.glbUrl);+ state.stage = 'rig';+ state.attempts.rig += 1;+ state.rig.jobId = rig.job_id;+ state.error = null;+ } catch (err) {+ return failStage(base, state, 'rig', err);+ }+ return saveState(state);+}++// A generate/rig failure retries free while attempts remain — the buyer paid+// for deliverables, not for our transient upstream weather. Exhausted retries+// mark the job failed with the last actionable error.+async function failStage(base, state, stage, err) {+ const attempts = state.attempts[stage] ?? 0;+ if (attempts < MAX_STAGE_ATTEMPTS && err?.code !== 'not_configured') {+ state.error = { stage, code: err?.code || 'provider_error', message: String(err?.message || err), retrying: true };+ if (stage === 'generate') {+ try {+ const gen = await submitForge(+ base,+ state.input.referenceImageUrl+ ? { image_urls: [state.input.referenceImageUrl], prompt: state.prompt.effective, aspect_ratio: '3:4' }+ : { prompt: state.prompt.effective, aspect_ratio: '3:4' },+ );+ state.attempts.generate += 1;+ state.gen.jobId = gen.job_id ?? null;+ if (gen.status === 'done' && gen.glb_url) state.gen.glbUrl = gen.glb_url;+ return saveState(state);+ } catch (resubmitErr) {+ err = resubmitErr;+ }+ } else if (stage === 'rig') {+ try {+ const rig = await startRig(base, state.gen.glbUrl);+ state.attempts.rig += 1;+ state.rig.jobId = rig.job_id;+ return saveState(state);+ } catch (resubmitErr) {+ err = resubmitErr;+ }+ } else if (stage === 'render') {+ // Leave the cursor in place — the next status poll re-runs this render.+ state.attempts.render = attempts + 1;+ return saveState(state);+ }+ }+ state.stage = 'failed';+ state.error = { stage, code: err?.code || 'provider_error', message: String(err?.message || err), retrying: false };+ return saveState(state);+}++// Advance the job by ONE bounded step. Called by every identity_status poll.+export async function advanceIdentityJob(id, { base = BASE } = {}) {+ const state = await loadState(id);+ if (!state) return null;++ if (state.stage === 'generate') {+ if (!state.gen.glbUrl) {+ const status = await pollForgeOnce(base, state.gen.jobId);+ if (status.status === 'failed') {+ await failStage(base, state, 'generate', pipelineError('generation_failed', status.error || 'generation failed'));+ } else if (status.status === 'done' && status.glb_url) {+ state.gen.glbUrl = status.glb_url;+ state.gen.backend = status.backend ?? state.gen.backend;+ await saveState(state);+ }+ }+ if (state.stage === 'generate' && state.gen.glbUrl) await beginRig(base, state);+ } else if (state.stage === 'rig') {+ const status = await pollForgeOnce(base, state.rig.jobId);+ if (status.status === 'failed') {+ await failStage(base, state, 'rig', pipelineError('rig_failed', status.error || 'rigging failed'));+ } else if (status.status === 'done' && status.glb_url) {+ state.rig.glbUrl = status.glb_url;+ state.stage = 'render';+ await saveState(state);+ }+ } else if (state.stage === 'render') {+ const step = state.plan[state.renderCursor];+ if (!step) {+ state.stage = 'done';+ await saveState(state);+ } else {+ try {+ // sharp is imported lazily so Vercel only traces its native tree for+ // this function (mirrors the chromium lazy-load in render-clip.js).+ const { default: sharp } = await import('sharp');+ const raw = await renderTransparent(base, {+ glbUrl: state.rig.glbUrl,+ posePresetId: step.pose,+ theta: step.theta,+ });+ if (step.kind === 'pfp') {+ const pfp = await composePfp(sharp, raw, { outSize: 1024 });+ const url = await uploadRender(state.id, 'pfp-1024', pfp);+ const preview = await sharp(pfp).resize(128, 128).png().toBuffer();+ const previewUrl = await uploadRender(state.id, 'pfp-128', preview);+ state.renders.push({ kind: 'pfp', pose: step.pose, url, previewUrl, width: 1024, height: 1024 });+ } else {+ const shot = await composeFullBody(sharp, raw, {});+ const url = await uploadRender(state.id, `fullbody-${state.renderCursor}-${step.pose}`, shot);+ state.renders.push({ kind: 'fullbody', pose: step.pose, url, width: 1024, height: 1280 });+ }+ state.renderCursor += 1;+ state.error = null;+ if (state.renderCursor >= state.plan.length) state.stage = 'done';+ await saveState(state);+ } catch (err) {+ if (err?.code === 'rate_limited') {+ // Renderer window exhausted — leave the cursor; the next poll retries.+ state.error = { stage: 'render', code: 'rate_limited', message: String(err.message), retrying: true };+ await saveState(state);+ await sleep(250);+ } else {+ await failStage(base, state, 'render', err);+ }+ }+ }+ }++ return state;+}++// The public status/result shape identity_status returns.+export function describeIdentityJob(state, { base = BASE } = {}) {+ const stageOrder = ['generate', 'rig', 'render', 'done'];+ const doneRenders = state.renders.length;+ const body = {+ job_id: encodeIdentityJobToken(state.id),+ status: state.stage === 'done' ? 'done' : state.stage === 'failed' ? 'failed' : 'running',+ stage: state.stage,+ progress: {+ steps: stageOrder,+ renders_done: doneRenders,+ renders_total: state.plan.length,+ },+ brief_truncated: state.input.briefTruncated,+ prompt: state.prompt.effective,+ directed: Boolean(state.prompt.directed),+ ...(state.error ? { last_error: state.error } : {}),+ };+ if (state.stage === 'done') {+ const pfp = state.renders.find((r) => r.kind === 'pfp');+ body.deliverables = {+ pfp: pfp ? { url: pfp.url, preview_128_url: pfp.previewUrl, pose: pfp.pose, size: 1024 } : null,+ full_body: state.renders+ .filter((r) => r.kind === 'fullbody')+ .map((r) => ({ url: r.url, pose: r.pose, width: r.width, height: r.height })),+ rigged_glb_url: state.rig.glbUrl,+ mesh_glb_url: state.gen.glbUrl,+ viewer_url: `${base}/viewer?src=${encodeURIComponent(state.rig.glbUrl)}`,+ pose_studio_url: `${base}/pose?src=${encodeURIComponent(state.rig.glbUrl)}`,+ };+ }+ return body;+}++export { loadState as loadIdentityJob };diff --git a/api/_okx3d/tools.js b/api/_okx3d/tools.jsnew file mode 100644index 000000000..22e715b6e--- /dev/null+++ b/api/_okx3d/tools.js@@ -0,0 +1,179 @@+// Agent Identity Studio — MCP tool catalog, dispatcher, pricing, and 402+// challenge metadata for the /api/okx/3d/identity-studio A2MCP endpoint.+// Prices and descriptions come from api/_lib/okx-catalog.js (single source of+// truth shared with the free catalog service and the OKX listing).++import Ajv from 'ajv';+import addFormats from 'ajv-formats';+import { makeDispatcher, PROTOCOL_VERSION } from '../_lib/mcp-dispatch.js';+import { buildGettingStartedTool, GETTING_STARTED_TOOL } from '../_lib/mcp-getting-started.js';+import { withService } from '../_lib/x402/bazaar-helpers.js';+import { catalogEntry } from '../_lib/okx-catalog.js';+import {+ createIdentityJob,+ advanceIdentityJob,+ describeIdentityJob,+ decodeIdentityJobToken,+ MAX_BRIEF_CHARS,+} from './identity.js';++export { PROTOCOL_VERSION };++const ENTRY = catalogEntry('identity-studio');+const STATUS_TOOL = 'identity_status';++function toolError(code, message, extra = {}) {+ return {+ isError: true,+ content: [{ type: 'text', text: `${code}: ${message}` }],+ structuredContent: { ok: false, error: code, message, ...extra },+ };+}++function toolOk(text, structured) {+ return { content: [{ type: 'text', text }], structuredContent: structured };+}++const createIdentityDef = {+ name: ENTRY.tool, // create_identity+ title: 'Create Agent Identity (paid)',+ description:+ `$${ENTRY.priceUsd} per identity — ${ENTRY.describes.capability} ` ++ `Async: returns a job_id immediately; poll ${STATUS_TOOL} (free) every few seconds until ` ++ 'status is "done" (typically 3–6 minutes). You are charged only when the job is accepted: ' ++ 'invalid input or an unreachable reference image fails before settlement, and failed ' ++ 'pipeline stages retry free.',+ annotations: { readOnlyHint: false, idempotentHint: false, openWorldHint: true },+ inputSchema: ENTRY.inputSchema,+ async handler(args) {+ try {+ const { jobId, state } = await createIdentityJob({+ agentName: args.agent_name,+ brief: args.brief,+ styleHints: args.style_hints,+ referenceImageUrl: args.reference_image_url,+ });+ const status = describeIdentityJob(state);+ return toolOk(+ `Identity job accepted. Poll ${STATUS_TOOL} with this job_id until status is "done" ` ++ `(ETA ~3–6 min). job_id: ${jobId}`,+ {+ ok: true,+ job_id: jobId,+ status: status.status,+ stage: status.stage,+ eta_seconds: 300,+ poll_tool: STATUS_TOOL,+ brief_truncated: state.input.briefTruncated,+ ...(state.input.briefTruncated+ ? { note: `brief exceeded ${MAX_BRIEF_CHARS} characters and was truncated` }+ : {}),+ },+ );+ } catch (err) {+ return toolError(err?.code || 'identity_failed', String(err?.message || err));+ }+ },+};++const identityStatusDef = {+ name: STATUS_TOOL,+ title: 'Identity Job Status (free)',+ description:+ 'FREE — poll an Agent Identity Studio job. Each call advances the pipeline one step ' ++ '(generation → rig → renders) and reports progress; when status is "done" it returns the ' ++ 'deliverables: PFP PNG (1024 + 128 preview), full-body render set, rigged GLB, and a ' ++ 'three.ws viewer link. No payment or account required.',+ annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: true },+ inputSchema: {+ type: 'object',+ required: ['job_id'],+ additionalProperties: false,+ properties: {+ job_id: { type: 'string', description: 'The job_id returned by create_identity.' },+ },+ },+ async handler(args) {+ const id = decodeIdentityJobToken(args.job_id);+ if (!id) {+ return toolError('invalid_job_id', 'job_id is not a valid identity job token.');+ }+ const state = await advanceIdentityJob(id);+ if (!state) return toolError('job_not_found', 'No job with that id. Jobs persist ~30 days.');+ const body = describeIdentityJob(state);+ const line =+ body.status === 'done'+ ? `Identity ready: PFP ${body.deliverables.pfp?.url} · rigged GLB ${body.deliverables.rigged_glb_url}`+ : body.status === 'failed'+ ? `Job failed at ${body.last_error?.stage}: ${body.last_error?.message}`+ : `Job ${body.stage} (${body.progress.renders_done}/${body.progress.renders_total} renders). Poll again in ~5s.`;+ return { ...(body.status === 'failed' ? { isError: true } : {}), content: [{ type: 'text', text: line }], structuredContent: body };+ },+};++const gettingStarted = buildGettingStartedTool({+ server: 'three.ws Agent Identity Studio',+ tagline:+ '3D identities for AI agents: brand brief → rigged GLB avatar + posed studio renders sized ' ++ 'for the OKX.AI avatar slot.',+ tools: [createIdentityDef, identityStatusDef],+ priceFor: (name) => (name === ENTRY.tool ? { amount_usdc: Number(ENTRY.priceUsd) } : null),+ access: [+ `Pay per identity with x402 (USDC): $${ENTRY.priceUsd} per create_identity call.`,+ `${STATUS_TOOL} and this tool are free — no payment, account, or key.`,+ 'Full service index (free): https://three.ws/api/okx/3d/catalog',+ ],+ links: {+ docs: 'https://three.ws/docs/okx-marketplace',+ showcase: 'https://three.ws/agent-identities',+ catalog: 'https://three.ws/api/okx/3d/catalog',+ },+});++const toolDefs = [gettingStarted, createIdentityDef, identityStatusDef];++const ajv = new Ajv({ allErrors: false, strict: false });+addFormats(ajv);+export const TOOL_CATALOG = toolDefs.map(({ handler, scope, ...pub }) => pub);+export const TOOLS = Object.fromEntries(+ toolDefs.map((d) => [+ d.name,+ { scope: d.scope, handler: d.handler, validate: d.inputSchema ? ajv.compile(d.inputSchema) : null },+ ]),+);++// Free tools servable to the anonymous principal with no OAuth/x402: discovery+// plus status polling — the "status/preview free" half of the service promise.+// The paid tool is deliberately NOT here.+export function isPublicIdentityTool(name) {+ return name === GETTING_STARTED_TOOL || name === STATUS_TOOL;+}++// x402 price (atomic USDC string) for one tools/call, or null when free.+export function identityX402Amount(toolName) {+ return toolName === ENTRY.tool ? ENTRY.amountAtomics : null;+}++export const dispatch = makeDispatcher({+ serverInfo: { name: 'three-ws-agent-identity-studio', version: '1.0.0' },+ instructions:+ 'Agent Identity Studio: call create_identity (paid) with an agent name + brand brief, then ' ++ `poll ${STATUS_TOOL} (free) until the rigged avatar and renders are ready. Call ` ++ 'getting_started (free) for the full overview.',+ catalog: TOOL_CATALOG,+ tools: TOOLS,+ logName: 'mcp-okx-identity',+});++// 402 challenge metadata: how facilitators/indexers see this endpoint.+export const IDENTITY_CHALLENGE = {+ description:+ 'three.ws Agent Identity Studio — A2MCP (MCP Streamable HTTP) service that turns an AI ' ++ "agent's brand brief into a complete 3D identity: rigged GLB avatar + posed studio renders " ++ `with an OKX-avatar-slot PFP crop. $${ENTRY.priceUsd} per identity, USDC via x402; job ` ++ 'status polling is free. Operated by three.ws.',+ ...withService({+ serviceName: 'three.ws Agent Identity Studio',+ tags: ['x402', 'mcp', '3d', 'avatar', 'identity', 'okx'],+ }),+};diff --git a/api/mcp-3d.js b/api/mcp-3d.jsindex c7f623cba..cfef74b7f 100644--- a/api/mcp-3d.js+++ b/api/mcp-3d.js@@ -78,7 +78,10 @@ export default wrap(async (req, res) => {// blocks any replay thereafter. Fails open — see reservePaymentProof.let releaseProof = async () => {};if (x402Ctx) {- const guard = await reservePaymentProof('/api/mcp-3d', req.headers['x-payment']);+ const guard = await reservePaymentProof(+ '/api/mcp-3d',+ req.headers['x-payment'] || req.headers['payment-signature'],+ );if (!guard.ok) {return sendJsonRpcError(res, null, -32000, 'payment_in_flight', { retry_after: 1 });}diff --git a/api/okx/3d/[service].js b/api/okx/3d/[service].jsnew file mode 100644index 000000000..657ddc6b4--- /dev/null+++ b/api/okx/3d/[service].js@@ -0,0 +1,206 @@+// OKX.AI marketplace services — one Vercel function, many fronts.+// Routes /api/okx/3d/<service> per the catalog in api/_lib/okx-catalog.js:+//+// /api/okx/3d/catalog GET, free — machine-readable service index+// /api/okx/3d/health GET, free — live subsystem health (real probes)+// /api/okx/3d/identity-studio A2MCP (MCP Streamable HTTP): POST tool calls,+// GET SSE, DELETE terminate. create_identity is+// x402-priced; identity_status + getting_started+// are free. Transport mirrors api/mcp-3d.js —+// verify → dispatch → settle-on-success.+import { cors, json, readJson, wrap } from '../../_lib/http.js';+import { limits, clientIp } from '../../_lib/rate-limit.js';+import { settlePayment, encodePaymentResponseHeader } from '../../_lib/x402-spec.js';+import { priceBatch, isDiscoveryOnlyBatch } from '../../_lib/mcp-batch-price.js';+import { OKX_CATALOG, catalogIndex, catalogEntry } from '../../_lib/okx-catalog.js';+import { headObject, putObject } from '../../_lib/r2.js';+import {+ send401,+ sendJsonRpcError,+ authenticateRequest,+ handleSse,+ handleTerminate,+ isMcpProtocolClient,+} from '../../_mcp/auth.js';+import { sendX402Error, reservePaymentProof } from '../../_mcp/payments.js';+import {+ dispatch,+ PROTOCOL_VERSION,+ identityX402Amount,+ isPublicIdentityTool,+ IDENTITY_CHALLENGE,+} from '../../_okx3d/tools.js';++const BASE = 'https://three.ws';+const HEALTH_PROBE_KEY = 'okx-identity/health-probe.txt';++function serviceFrom(req) {+ if (typeof req.query?.service === 'string') return req.query.service;+ const m = String(req.url || '').match(/\/api\/okx\/3d\/([a-z0-9-]+)/);+ return m ? m[1] : '';+}++async function probe(name, fn) {+ const started = Date.now();+ try {+ const detail = await fn();+ return { name, ok: true, latency_ms: Date.now() - started, ...(detail || {}) };+ } catch (err) {+ return { name, ok: false, latency_ms: Date.now() - started, error: String(err?.message || err) };+ }+}++// Live health: every subsystem a paid job passes through, actually probed.+async function healthReport() {+ const subsystems = await Promise.all([+ probe('generation', async () => {+ // /api/forge serves its catalog/config on GET without starting a job —+ // reachable + parseable proves the generation front door is up.+ const res = await fetch(`${BASE}/api/forge`, {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(10_000),+ });+ if (res.status >= 500) throw new Error(`forge returned ${res.status}`);+ return { status: res.status };+ }),+ probe('render', async () => {+ const res = await fetch(`${BASE}/api/render/avatar-clip`, {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(10_000),+ });+ if (!res.ok) throw new Error(`renderer returned ${res.status}`);+ const data = await res.json();+ if (!Array.isArray(data?.poses) || data.poses.length === 0) throw new Error('pose catalog empty');+ return { poses: data.poses.length };+ }),+ probe('storage', async () => {+ try {+ await headObject(HEALTH_PROBE_KEY);+ } catch {+ await putObject({+ key: HEALTH_PROBE_KEY,+ body: Buffer.from('agent-identity-studio storage probe', 'utf8'),+ contentType: 'text/plain',+ });+ await headObject(HEALTH_PROBE_KEY);+ }+ }),+ ]);+ return { ok: subsystems.every((s) => s.ok), subsystems, checkedAt: new Date().toISOString() };+}++async function handleIdentityStudio(req, res) {+ const resourcePath = '/api/okx/3d/identity-studio';++ if (req.method === 'GET' || req.method === 'HEAD')+ return handleSse(req, res, { resourcePath, challenge: IDENTITY_CHALLENGE });+ if (req.method === 'DELETE') return handleTerminate(req, res);+ if (req.method !== 'POST') return send401(res, 'method not supported');++ const body = await readJson(req, 1_000_000);++ const { totalAmount: x402Amount, allFree } = priceBatch(body, {+ priceForTool: identityX402Amount,+ isFreeName: isPublicIdentityTool,+ });++ const result = await authenticateRequest(req, res, {+ x402Amount,+ resourcePath,+ challenge: IDENTITY_CHALLENGE,+ allowFree: allFree || (isDiscoveryOnlyBatch(body) && !isMcpProtocolClient(req)),+ });+ if (!result) return;+ const { auth, x402Ctx } = result;++ const ipRl = await limits.mcpIp(clientIp(req));+ if (!ipRl.success)+ return sendJsonRpcError(res, null, -32000, 'rate_limited', {+ retry_after: Math.ceil((ipRl.reset - Date.now()) / 1000),+ });+ const userRl = await limits.mcpUser(auth.userId || auth.rateKey || clientIp(req));+ if (!userRl.success)+ return sendJsonRpcError(res, null, -32000, 'rate_limited', {+ retry_after: Math.ceil((userRl.reset - Date.now()) / 1000),+ });++ const batch = Array.isArray(body) ? body : [body];+ if (batch.length > 16) return sendJsonRpcError(res, null, -32600, 'batch too large (max 16)');++ // Single-use lock on the payment proof across dispatch+settle, mirroring+ // /api/mcp-3d — a replayed X-PAYMENT can't run a second job before the+ // first settle lands.+ let releaseProof = async () => {};+ if (x402Ctx) {+ const guard = await reservePaymentProof(resourcePath, req.headers['x-payment']);+ if (!guard.ok) {+ return sendJsonRpcError(res, null, -32000, 'payment_in_flight', { retry_after: 1 });+ }+ releaseProof = guard.release;+ }++ try {+ const responses = [];+ for (const msg of batch) {+ const r = await dispatch(msg, auth, req);+ if (r !== null) responses.push(r);+ }++ // Settle only after the work was accepted: a create_identity that failed+ // validation (bad brief, unreachable reference image) returns isError and+ // the payment is never settled — the pay-only-on-acceptance promise the+ // catalog description makes.+ if (x402Ctx) {+ const anySuccess = responses.some((r) => r && !r.error && !(r.result && r.result.isError));+ if (anySuccess) {+ try {+ const settled = await settlePayment({ verified: x402Ctx.verified });+ res.setHeader('x-payment-response', encodePaymentResponseHeader(settled));+ } catch (err) {+ return sendX402Error(+ res,+ { resourceUrl: x402Ctx.resourceUrl, accepts: x402Ctx.requirements },+ err,+ );+ }+ }+ }++ res.statusCode = 200;+ res.setHeader('content-type', 'application/json; charset=utf-8');+ res.setHeader('mcp-protocol-version', PROTOCOL_VERSION);+ res.end(JSON.stringify(Array.isArray(body) ? responses : (responses[0] ?? null)));+ } finally {+ await releaseProof();+ }+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,HEAD,POST,DELETE,OPTIONS', origins: '*' })) return;++ const service = serviceFrom(req);++ if (service === 'catalog') {+ if (req.method !== 'GET' && req.method !== 'HEAD')+ return json(res, 405, { error: 'method_not_allowed', message: 'catalog is GET-only' });+ return json(res, 200, catalogIndex(), { 'cache-control': 'public, max-age=300' });+ }++ if (service === 'health') {+ if (req.method !== 'GET' && req.method !== 'HEAD')+ return json(res, 405, { error: 'method_not_allowed', message: 'health is GET-only' });+ const report = await healthReport();+ return json(res, report.ok ? 200 : 503, report, { 'cache-control': 'no-store' });+ }++ if (service === 'identity-studio') return handleIdentityStudio(req, res);++ const known = catalogEntry(service);+ return json(res, 404, {+ error: 'unknown_service',+ message: known+ ? `service "${service}" is catalogued but not yet routable — see the catalog for status`+ : `no such service "${service}"`,+ services: OKX_CATALOG.map((e) => e.endpoint),+ });+});diff --git a/package-lock.json b/package-lock.jsonindex d6e6c9632..05074fe01 100644--- a/package-lock.json+++ b/package-lock.json@@ -97,6 +97,7 @@"@noble/hashes": "^1.8.0","@node-saml/node-saml": "^5.1.0","@octokit/rest": "^22.0.1",+ "@okxweb3/app-x402-core": "^0.2.0","@privy-io/js-sdk-core": "^0.67.0","@pump-fun/agent-payments-sdk": "^3.0.3","@pump-fun/pump-sdk": "^1.36.0",@@ -14250,6 +14251,16 @@"@octokit/openapi-types": "^27.0.0"}},+ "node_modules/@okxweb3/app-x402-core": {+ "version": "0.2.0",+ "resolved": "https://registry.npmjs.org/@okxweb3/app-x402-core/-/app-x402-core-0.2.0.tgz",+ "integrity": "sha512-6Ndz0CXdRHrfk1OQkkt1U3HJRT/diPWE6UJwPV5kOJdXc3ePXYXb4WW3bkD9p6pQjck7+Lgql16mA3YPZqTzRg==",+ "license": "Apache-2.0",+ "dependencies": {+ "viem": "^2.39.3",+ "zod": "^3.24.2"+ }+ },"node_modules/@opentelemetry/api": {"version": "1.9.1","resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.1.tgz",@@ -51925,7 +51936,7 @@},"solana-agent-sdk": {"name": "@three-ws/solana-agent",- "version": "0.2.0",+ "version": "0.2.1","license": "Apache-2.0","dependencies": {"@coral-xyz/anchor": "^0.32.1",@@ -51979,7 +51990,7 @@},"tour-sdk": {"name": "@three-ws/tour",- "version": "0.2.0",+ "version": "0.4.0","license": "Apache-2.0","bin": {"tour-build-curriculum": "bin/tour-build-curriculum.mjs"@@ -51991,7 +52002,7 @@"node": ">=18"},"peerDependencies": {- "@three-ws/walk": ">=0.1.1",+ "@three-ws/walk": ">=0.1.2","three": ">=0.150.0"}},@@ -52481,7 +52492,7 @@},"walk-sdk": {"name": "@three-ws/walk",- "version": "0.1.1",+ "version": "0.1.2","license": "Apache-2.0","engines": {"node": ">=18"diff --git a/package.json b/package.jsonindex 222de81f6..ac851d8dc 100644--- a/package.json+++ b/package.json@@ -266,6 +266,7 @@"@noble/hashes": "^1.8.0","@node-saml/node-saml": "^5.1.0","@octokit/rest": "^22.0.1",+ "@okxweb3/app-x402-core": "^0.2.0","@privy-io/js-sdk-core": "^0.67.0","@pump-fun/agent-payments-sdk": "^3.0.3","@pump-fun/pump-sdk": "^1.36.0",diff --git a/scripts/gcp/vanity-grind-deploy.sh b/scripts/gcp/vanity-grind-deploy.shnew file mode 100755index 000000000..3883cefea--- /dev/null+++ b/scripts/gcp/vanity-grind-deploy.sh@@ -0,0 +1,142 @@+#!/usr/bin/env bash+#+# vanity-grind-deploy.sh — build the batch vanity grinder image and run it on+# cheap GCP SPOT CPU to grind premium inventory.+#+# Two runners:+# (default) Cloud Run Job — simplest; one spot-billed job, scale --tasks for+# parallel shards, --cpu for cores per task.+# --mig — GCE spot managed instance group; max cores/$ for+# very large runs. Each VM takes a SHARD_INDEX.+#+# Durable output: pass WRITE_DB=1 (+ DATABASE_URL secret) to write sealed keys+# straight into vanity_inventory. Otherwise the job writes an encrypted JSONL to+# /tmp (ephemeral) — fine for a smoke run, not for real inventory.+#+# Idempotent. Prereqs: prompt 01 (project + billing), and for real inventory,+# scripts/gcp/vanity-kms-setup.sh (KMS) — set VANITY_KMS_KEY below.+#+# Usage:+# PROJECT_ID=my-proj ./scripts/gcp/vanity-grind-deploy.sh+# PROJECT_ID=my-proj TASKS=8 CPU=8 ./scripts/gcp/vanity-grind-deploy.sh --run+# PROJECT_ID=my-proj ./scripts/gcp/vanity-grind-deploy.sh --mig --instances 20+#+# Env:+# PROJECT_ID required+# REGION default us-central1+# REPO default containers (Artifact Registry repo)+# IMAGE default vanity-grinder+# JOB default vanity-grinder+# TASKS default 4 (Cloud Run Job parallel shards)+# CPU default 4 (vCPU per task; MEM scales with it)+# INSTANCES default 10 (--mig VM count)+# MACHINE default c2d-highcpu-8 (--mig machine type)+# Secrets expected in Secret Manager: WALLET_ENCRYPTION_KEY, JWT_SECRET, and+# (if WRITE_DB=1) DATABASE_URL. VANITY_KMS_KEY passed as a plain env.++set -euo pipefail++PROJECT_ID="${PROJECT_ID:?set PROJECT_ID to your GCP project}"+REGION="${REGION:-us-central1}"+REPO="${REPO:-containers}"+IMAGE="${IMAGE:-vanity-grinder}"+JOB="${JOB:-vanity-grinder}"+TASKS="${TASKS:-4}"+CPU="${CPU:-4}"+INSTANCES="${INSTANCES:-10}"+MACHINE="${MACHINE:-c2d-highcpu-8}"+GRINDER_SA="${GRINDER_SA:-vanity-grinder@${PROJECT_ID}.iam.gserviceaccount.com}"++REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+cd "$REPO_ROOT"++MODE="run-job"+DO_RUN=0+INSTANCE_COUNT="$INSTANCES"+for arg in "$@"; do+ case "$arg" in+ --mig) MODE="mig" ;;+ --run) DO_RUN=1 ;;+ --instances) shift; INSTANCE_COUNT="${1:-$INSTANCES}" ;;+ esac+done++IMAGE_URI="${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/${IMAGE}:latest"++echo "▸ Enabling APIs (run, compute, artifactregistry, cloudbuild)…"+gcloud services enable run.googleapis.com compute.googleapis.com \+ artifactregistry.googleapis.com cloudbuild.googleapis.com --project "$PROJECT_ID"++echo "▸ Artifact Registry repo $REPO…"+gcloud artifacts repositories create "$REPO" --repository-format docker \+ --location "$REGION" --project "$PROJECT_ID" 2>/dev/null || echo " (repo exists)"++echo "▸ Grinder service account $GRINDER_SA…"+gcloud iam service-accounts create vanity-grinder --display-name "Vanity batch grinder" \+ --project "$PROJECT_ID" 2>/dev/null || echo " (SA exists)"++echo "▸ Building + pushing image (build context = repo root)…"+gcloud builds submit --project "$PROJECT_ID" --region "$REGION" \+ --tag "$IMAGE_URI" \+ --config <(cat <<YAML+steps:+ - name: gcr.io/cloud-builders/docker+ args: ['build','-f','workers/vanity-grinder/Dockerfile','-t','${IMAGE_URI}','.']+images: ['${IMAGE_URI}']+YAML+)++# Common env for the grinder. WRITE_DB/VANITY_KMS_KEY flow through from the shell.+JOB_ENV="RUNNER=cloud-run-job,INCLUDE_5=${INCLUDE_5:-0},IGNORE_CASE=${IGNORE_CASE:-0},WRITE_DB=${WRITE_DB:-1},VANITY_KMS_KEY=${VANITY_KMS_KEY:-}"+JOB_SECRETS="WALLET_ENCRYPTION_KEY=WALLET_ENCRYPTION_KEY:latest,JWT_SECRET=JWT_SECRET:latest,DATABASE_URL=DATABASE_URL:latest"++if [[ "$MODE" == "run-job" ]]; then+ echo "▸ Creating/updating Cloud Run Job $JOB (spot, ${TASKS} tasks × ${CPU} vCPU)…"+ MEM="$(( CPU * 512 ))Mi"+ gcloud run jobs deploy "$JOB" \+ --image "$IMAGE_URI" --region "$REGION" --project "$PROJECT_ID" \+ --service-account "$GRINDER_SA" \+ --cpu "$CPU" --memory "$MEM" \+ --tasks "$TASKS" --parallelism "$TASKS" \+ --max-retries 3 --task-timeout 3600 \+ --set-env-vars "$JOB_ENV,SHARD_COUNT=${TASKS}" \+ --update-secrets "$JOB_SECRETS" \+ --execution-environment gen2 \+ --labels "workload=vanity-grinder,billing=spot"+ # Cloud Run Jobs are spot-eligible via the tasks' preemptible scheduling; each+ # task derives SHARD_INDEX from CLOUD_RUN_TASK_INDEX at runtime (see note below).+ echo " ✅ Job deployed: $JOB"+ if [[ "$DO_RUN" == "1" ]]; then+ echo "▸ Executing job…"+ gcloud run jobs execute "$JOB" --region "$REGION" --project "$PROJECT_ID" --wait+ else+ echo " Run it: gcloud run jobs execute $JOB --region $REGION"+ fi+else+ echo "▸ Creating spot MIG template + group (${INSTANCE_COUNT} × ${MACHINE})…"+ TEMPLATE="${JOB}-tmpl"+ gcloud compute instance-templates create-with-container "$TEMPLATE" \+ --project "$PROJECT_ID" --machine-type "$MACHINE" \+ --provisioning-model SPOT --instance-termination-action DELETE \+ --container-image "$IMAGE_URI" \+ --container-env "RUNNER=gce-spot-mig,SHARD_COUNT=${INSTANCE_COUNT},WRITE_DB=${WRITE_DB:-1},VANITY_KMS_KEY=${VANITY_KMS_KEY:-}" \+ --service-account "$GRINDER_SA" \+ --scopes cloud-platform 2>/dev/null || echo " (template exists)"+ gcloud compute instance-groups managed create "$JOB" \+ --project "$PROJECT_ID" --zone "${REGION}-a" \+ --template "$TEMPLATE" --size "$INSTANCE_COUNT" 2>/dev/null || echo " (MIG exists)"+ echo " ✅ Spot MIG up. Each VM must read SHARD_INDEX from its instance name ordinal."+ echo " Tear down when done: gcloud compute instance-groups managed delete $JOB --zone ${REGION}-a"+fi++cat <<EOF++Notes:+ • Cloud Run Jobs: set SHARD_INDEX=\$CLOUD_RUN_TASK_INDEX in the entrypoint if you+ want strict per-task sharding (the built-in default shards evenly by env).+ • Cost: c2d spot ≈ \$0.01–0.02 / vCPU-hour. At ~25k keys/sec/vCPU a 4‑char+ address (~11.3M expected) is ~450 vCPU-seconds ≈ \$0.002. Even 5‑char (~656M)+ is a few cents. See docs/gcp-credits.md for the measured \$/address table.+ • Always run scripts/gcp/vanity-kms-setup.sh first for production inventory so+ keys are sealed under KMS, not just secret-box.+EOFdiff --git a/scripts/gcp/vanity-kms-setup.sh b/scripts/gcp/vanity-kms-setup.shnew file mode 100755index 000000000..9e73c58c2--- /dev/null+++ b/scripts/gcp/vanity-kms-setup.sh@@ -0,0 +1,80 @@+#!/usr/bin/env bash+#+# vanity-kms-setup.sh — provision GCP KMS envelope encryption for the premium+# vanity inventory, and grant decrypt to ONLY the delivery service identity.+#+# This is the "insider access" mitigation for stored private keys (see the threat+# model in docs/gcp-credits.md). secret-box (WALLET_ENCRYPTION_KEY) already+# protects against a DB dump; KMS adds IAM-gated, audit-logged decrypt so no+# single env-var leak can silently decrypt the whole inventory offline.+#+# Idempotent: safe to re-run. Prints the VANITY_KMS_KEY value to set in Vercel+# (delivery side) and for the grinder job (encrypt side).+#+# Prereqs: gcloud authed to the project (prompt 01). Enables cloudkms.googleapis.com.+#+# Usage:+# PROJECT_ID=my-proj ./scripts/gcp/vanity-kms-setup.sh+#+# Env:+# PROJECT_ID required+# LOCATION default us-central1 (KMS location for the keyring)+# KEYRING default three-vanity+# KEY default inventory-secrets+# DELIVERY_SA the SA the Vercel delivery function runs as+# (default vercel-inference@$PROJECT_ID.iam.gserviceaccount.com)+# GRINDER_SA the SA the batch grinder runs as (needs encrypt only)+# (default vanity-grinder@$PROJECT_ID.iam.gserviceaccount.com)++set -euo pipefail++PROJECT_ID="${PROJECT_ID:?set PROJECT_ID to your GCP project}"+LOCATION="${LOCATION:-us-central1}"+KEYRING="${KEYRING:-three-vanity}"+KEY="${KEY:-inventory-secrets}"+DELIVERY_SA="${DELIVERY_SA:-vercel-inference@${PROJECT_ID}.iam.gserviceaccount.com}"+GRINDER_SA="${GRINDER_SA:-vanity-grinder@${PROJECT_ID}.iam.gserviceaccount.com}"++echo "▸ Enabling Cloud KMS API…"+gcloud services enable cloudkms.googleapis.com --project "$PROJECT_ID"++echo "▸ Keyring $KEYRING ($LOCATION)…"+gcloud kms keyrings create "$KEYRING" --location "$LOCATION" --project "$PROJECT_ID" 2>/dev/null \+ || echo " (keyring already exists)"++echo "▸ Crypto key $KEY (rotation 90d)…"+gcloud kms keys create "$KEY" \+ --location "$LOCATION" --keyring "$KEYRING" \+ --purpose encryption --rotation-period 90d --next-rotation-time "$(date -u -d '+90 days' +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date -u -v+90d +%Y-%m-%dT%H:%M:%SZ)" \+ --project "$PROJECT_ID" 2>/dev/null \+ || echo " (key already exists)"++KEY_RESOURCE="projects/${PROJECT_ID}/locations/${LOCATION}/keyRings/${KEYRING}/cryptoKeys/${KEY}"++echo "▸ Granting DECRYPT to the delivery identity ONLY ($DELIVERY_SA)…"+gcloud kms keys add-iam-policy-binding "$KEY" \+ --location "$LOCATION" --keyring "$KEYRING" \+ --member "serviceAccount:${DELIVERY_SA}" \+ --role roles/cloudkms.cryptoKeyDecrypter \+ --project "$PROJECT_ID" >/dev/null++echo "▸ Granting ENCRYPT to the grinder identity ($GRINDER_SA) — encrypt, NOT decrypt…"+gcloud kms keys add-iam-policy-binding "$KEY" \+ --location "$LOCATION" --keyring "$KEYRING" \+ --member "serviceAccount:${GRINDER_SA}" \+ --role roles/cloudkms.cryptoKeyEncrypter \+ --project "$PROJECT_ID" >/dev/null++cat <<EOF++✅ KMS ready. Set this on BOTH the grinder job and the Vercel delivery function:++ VANITY_KMS_KEY=${KEY_RESOURCE}++ • Grinder (encrypt) runs as: ${GRINDER_SA} (cryptoKeyEncrypter)+ • Delivery (decrypt) runs as: ${DELIVERY_SA} (cryptoKeyDecrypter)++ Set in Vercel: vercel env add VANITY_KMS_KEY production # paste the value above+ Least privilege: the grinder can seal keys but can NEVER read them back; only+ the delivery function can decrypt, and every decrypt is Cloud-Audit-Logged.+EOFdiff --git a/scripts/gcp/vertex-llm-smoke.mjs b/scripts/gcp/vertex-llm-smoke.mjsnew file mode 100644index 000000000..37129e936--- /dev/null+++ b/scripts/gcp/vertex-llm-smoke.mjs@@ -0,0 +1,197 @@+#!/usr/bin/env node+// Vertex Claude LLM smoke test — exercises every text-inference surface against a+// live `npm run dev` server and asserts the reply came from Google Vertex.+//+// Prerequisites:+// 1. GCP creds + flags set in the dev server's environment:+// GOOGLE_CLOUD_PROJECT=<proj> GCP_SERVICE_ACCOUNT_JSON='<json>' \+// VERTEX_CLAUDE_ENABLED=1 VERTEX_CLAUDE_PRIMARY=1 npm run dev+// 2. Claude enabled in the project's Vertex Model Garden (prompt 01).+//+// Usage:+// node scripts/gcp/vertex-llm-smoke.mjs+// BASE_URL=http://localhost:3000 node scripts/gcp/vertex-llm-smoke.mjs+//+// Optional env:+// BASE_URL — dev server origin (default http://localhost:3000)+// SMOKE_AGENT_ID — a public agent/avatar id to exercise /api/llm/anthropic+// (the embed proxy). Skipped when unset.+// SMOKE_BEARER — a bearer token for an authenticated /api/chat call.+// /api/chat gates the Vertex (paid-tier) lane behind auth,+// so anonymous callers only get the free lanes — provide a+// token to prove the /api/chat Vertex lane end to end.+//+// Surfaces covered:+// (a) llmComplete() via POST /api/forge-enhance → asserts provider+// (b) /api/llm/anthropic streaming → asserts x-llm-transport response header+// (c) /api/chat streaming → asserts the done event's provider+//+// Exit code is non-zero if any required assertion fails.++const BASE_URL = (process.env.BASE_URL || 'http://localhost:3000').replace(/\/$/, '');+const AGENT_ID = process.env.SMOKE_AGENT_ID || '';+const BEARER = process.env.SMOKE_BEARER || '';++let failures = 0;+let skips = 0;+const pass = (m) => console.log(` ✓ ${m}`);+const fail = (m) => {+ failures++;+ console.error(` ✗ ${m}`);+};+const skip = (m) => {+ skips++;+ console.warn(` ⊘ SKIP ${m}`);+};++// ── (a) llmComplete via /api/forge-enhance ──────────────────────────────────+async function surfaceLlmComplete() {+ console.log('\n(a) llmComplete → POST /api/forge-enhance');+ let res;+ try {+ res = await fetch(`${BASE_URL}/api/forge-enhance`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ prompt: 'a small brass telescope on a wooden desk' }),+ });+ } catch (err) {+ fail(`request failed: ${err.message} (is the dev server running at ${BASE_URL}?)`);+ return;+ }+ if (!res.ok) {+ fail(`HTTP ${res.status}: ${(await res.text().catch(() => '')).slice(0, 200)}`);+ return;+ }+ const body = await res.json().catch(() => ({}));+ console.log(` provider=${body.provider} model=${body.model}`);+ if (body.provider === 'vertex-anthropic') {+ pass('served by Vertex (provider=vertex-anthropic)');+ } else {+ fail(+ `expected provider=vertex-anthropic, got "${body.provider}". ` ++ 'Ensure VERTEX_CLAUDE_ENABLED=1 and VERTEX_CLAUDE_PRIMARY=1 with GCP creds on the dev server.',+ );+ }+}++// ── (b) /api/llm/anthropic streaming (embed proxy) ──────────────────────────+async function surfaceEmbedProxy() {+ console.log('\n(b) embed proxy → POST /api/llm/anthropic (streaming)');+ if (!AGENT_ID) {+ skip('set SMOKE_AGENT_ID=<public agent or avatar id> to exercise this surface');+ return;+ }+ let res;+ try {+ res = await fetch(`${BASE_URL}/api/llm/anthropic?agent=${encodeURIComponent(AGENT_ID)}`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ model: 'claude-haiku-4-5-20251001',+ max_tokens: 64,+ stream: true,+ messages: [{ role: 'user', content: 'Say hello in five words.' }],+ }),+ });+ } catch (err) {+ fail(`request failed: ${err.message}`);+ return;+ }+ if (!res.ok) {+ fail(`HTTP ${res.status}: ${(await res.text().catch(() => '')).slice(0, 200)}`);+ return;+ }+ const transport = res.headers.get('x-llm-transport');+ console.log(` x-llm-transport=${transport}`);+ // Drain a little of the stream to confirm tokens actually flow.+ const text = await readSomeStream(res, 1500);+ const streamed = /content_block_delta|text_delta|message_start/.test(text);+ if (transport === 'vertex-anthropic') pass('served by Vertex (x-llm-transport=vertex-anthropic)');+ else fail(`expected x-llm-transport=vertex-anthropic, got "${transport}"`);+ if (streamed) pass('SSE tokens streamed');+ else fail('no Anthropic SSE events observed in the stream');+}++// ── (c) /api/chat streaming ─────────────────────────────────────────────────+async function surfaceChat() {+ console.log('\n(c) viewer chat → POST /api/chat (streaming)');+ if (!BEARER) {+ skip(+ 'set SMOKE_BEARER=<token> — /api/chat clamps anonymous callers to the free lanes, ' ++ 'so proving the Vertex lane requires an authenticated call',+ );+ return;+ }+ let res;+ try {+ res = await fetch(`${BASE_URL}/api/chat`, {+ method: 'POST',+ headers: { 'content-type': 'application/json', authorization: `Bearer ${BEARER}` },+ body: JSON.stringify({ message: 'Say hello in five words.', context: {} }),+ });+ } catch (err) {+ fail(`request failed: ${err.message}`);+ return;+ }+ if (!res.ok) {+ fail(`HTTP ${res.status}: ${(await res.text().catch(() => '')).slice(0, 200)}`);+ return;+ }+ const text = await readSomeStream(res, 4000);+ // Parse the terminal done event for the provider attribution.+ let provider = null;+ for (const line of text.split('\n')) {+ if (!line.startsWith('data:')) continue;+ try {+ const evt = JSON.parse(line.slice(5).trim());+ if (evt.type === 'done' && evt.provider) provider = evt.provider;+ } catch {+ // non-JSON keepalive line — ignore+ }+ }+ console.log(` done.provider=${provider}`);+ if (provider === 'vertex') pass('served by Vertex (done.provider=vertex)');+ else fail(`expected done.provider=vertex, got "${provider}"`);+}++// Read from an SSE response for up to `ms`, returning the accumulated text. Used+// to observe streamed events without hanging on an open stream.+async function readSomeStream(res, ms) {+ const reader = res.body.getReader();+ const decoder = new TextDecoder();+ let out = '';+ const deadline = Date.now() + ms;+ try {+ while (Date.now() < deadline) {+ const { done, value } = await Promise.race([+ reader.read(),+ new Promise((r) => setTimeout(() => r({ done: true, timeout: true }), deadline - Date.now())),+ ]);+ if (done) break;+ out += decoder.decode(value, { stream: true });+ if (out.includes('"type":"done"') || out.includes('message_stop')) break;+ }+ } finally {+ try {+ await reader.cancel();+ } catch {+ // stream already closed+ }+ }+ return out;+}++async function main() {+ console.log(`Vertex Claude LLM smoke — target ${BASE_URL}`);+ await surfaceLlmComplete();+ await surfaceEmbedProxy();+ await surfaceChat();++ console.log(`\n${failures === 0 ? 'PASS' : 'FAIL'} — ${failures} failure(s), ${skips} skipped.`);+ if (failures > 0) process.exit(1);+}++main().catch((err) => {+ console.error('smoke run crashed:', err);+ process.exit(1);+});diff --git a/specs/okx-agent-payments.md b/specs/okx-agent-payments.mdindex a99d87e37..4493b5b17 100644--- a/specs/okx-agent-payments.md+++ b/specs/okx-agent-payments.md@@ -4,9 +4,11 @@> **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, 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.+> **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 on the paid leg it reads/emits **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. (The HTTP-level 402 gate itself ALREADY exists — see the verification note below.) 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.**+> **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. (The OKX SDK's `extractPayment` reads ONLY `payment-signature` and the subscription `app-payment` — there is NO v1 `x-payment` fallback in it; SDK-REPO `x402HTTPResourceServer.ts:1558-1580`. Do not rely on v1 names on the OKX rail.) 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 uses the v1 payment-header names — that is the delta to close for the X-Layer rail.**+>+> **Verification pass (2026-07-06, second session, independent captures — Appendix H):** a parallel WO-01 run re-derived this contract from its own wire captures (Predexon #2143 as a fourth approved seller, a second signed payment leg, on-chain RPC reads, live `x402-check` runs). It CONFIRMS every §2 answer with two corrections, applied inline below: (1) our endpoint's **HTTP-level 402 gate already exists** for non-MCP clients — bare `POST tools/call` returns `HTTP/2 402` + `PAYMENT-REQUIRED`, and `onchainos agent x402-check --endpoint https://three.ws/api/mcp-3d` parses it `valid: true` (Solana-only accepts — the gap is the missing `eip155:196` entry, not a missing gate; original Q6/G9 overstated this); (2) the SDK has no v1 `x-payment` fallback (above). It also STRENGTHENS Q3: `extra.name`/`extra.version` are now cryptographically pinned against the token's on-chain `DOMAIN_SEPARATOR()` (Appendix H.3).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**.@@ -160,7 +162,7 @@ On success attach `PAYMENT-RESPONSE` (base64 of the `SettleResponse`). Shape (SD| 3 | Fee token `0x779Ded…713736` on X Layer | **Symbol `USDT`, name `USD₮0`, decimals `6`, EIP-3009 capable** (supports `transferWithAuthorization`). Community-recognized. Not permit2-only — the whole rail uses EIP-3009. | `onchainos token info` (Appx E); SDK `defaultAssets.ts` `DEFAULT_STABLECOINS["eip155:196"]` comment "(EIP-3009)"; live EIP-3009 sign accepted structurally by facilitator (PAY-LEG1/2) || 4 | OKX facilitator verify/settle URLs, shapes, auth | Base `https://web3.okx.com`. **`POST /api/v6/pay/x402/verify`**, **`POST /api/v6/pay/x402/settle`**, `GET /api/v6/pay/x402/supported`, `GET /api/v6/pay/x402/settle/status?txHash=`. Body `{x402Version:2, paymentPayload, paymentRequirements[, syncSettle]}`. Responses wrapped `{code,msg,data}`. **Auth = OKX REST HMAC-SHA256**: headers `OK-ACCESS-KEY`, `OK-ACCESS-SIGN`(=base64(HMAC-SHA256(secret, timestamp+method+path+body))), `OK-ACCESS-TIMESTAMP`(ISO-8601), `OK-ACCESS-PASSPHRASE`. **⇒ We need an OKX API key/secret/passphrase.** `upto`'s `extra.facilitatorAddress` = `supported.signers[family][0]` via `getExtra()`. | SDK `facilitator/OKXFacilitatorClient.ts` (all endpoints + `createHeaders` L60-76); `upto/facilitator/scheme.ts:39` || 5 | The official OKX Payment SDK | **`github.com/okx/payments` = "OKX Payments SDK", Apache-2.0** (monorepo `@okxweb3/payments-sdk-monorepo`; Go/Python/Rust/TS/Java). **Use the `@okxweb3/app-x402-*` family @ v0.2.0** (`-core`, `-evm`, `-express`/`-next`/`-hono`/`-fastify`, `-mpp`) — that's what the runnable demo imports (published 2026-07-03). **⚠️ Avoid the stale `@okxweb3/x402-*` @ v0.1.0** (`x402-core`/`x402-evm`/`mpp`) that the repo's `SELLER.md` still names — last touched 2026-06-08. Pure TypeScript (deps `viem`/`zod`/`axios`/`mppx` — pure JS, `@noble` crypto, `node:crypto` HMAC, no native bindings) ⇒ **runs in Vercel functions**. Seller-side it builds the 402 challenge, reads `PAYMENT-SIGNATURE`, calls facilitator verify/settle, emits `PAYMENT-RESPONSE`, plus lifecycle hooks + metered `setSettlementOverrides`. Weekly downloads low (new pkg): app-x402-core ≈267, -evm ≈204, -express ≈188. | SDK-REPO README + `package.json`; `npm view @okxweb3/app-x402-*`; `api.npmjs.org/downloads/point/last-week`; `app-x402-next/README.md` |-| 6 | HTTP-level 402 vs MCP-level PaymentRequired | OKX expects **HTTP-level 402** on the endpoint URL: real `HTTP/2 402` status + `PAYMENT-REQUIRED` header, paid replay via `PAYMENT-SIGNATURE` header. All 3 approved sellers do HTTP-level. **Our current MCP-level `_meta` PaymentRequired (structuredContent) is NOT what OKX reads** — the validator/buyer never inspects JSON-RPC `_meta`. 02 must add an HTTP-402 gate at the transport layer of `api/mcp-3d.js`. (oklink's endpoints are "MCP" by name but gate at HTTP: `POST` → 402, headers carry payment; see Appx A.) | WIRE-OKLINK (POST→402, GET→405); [api/mcp-3d.js](../api/mcp-3d.js) `_meta` path; SDK is HTTP-transport only |+| 6 | HTTP-level 402 vs MCP-level PaymentRequired | OKX expects **HTTP-level 402** on the endpoint URL: real `HTTP/2 402` status + `PAYMENT-REQUIRED` header, paid replay via `PAYMENT-SIGNATURE` header. All approved sellers do HTTP-level; the validator/buyer never inspects JSON-RPC `_meta`. **CORRECTED (verification pass): our endpoint ALREADY has this HTTP-level gate** — a bare (non-MCP) `POST tools/call` gets `HTTP/2 402` + `PAYMENT-REQUIRED`, live-verified for `text_to_3d` and `auto_rig_model`, and `x402-check` parses it `valid: true` (Appx H.1). Only MCP-protocol clients (`mcp-protocol-version` header) are routed to 401/OAuth, which OKX tooling never sends. 02's work on this axis is ONLY: the paid-replay leg must also accept `PAYMENT-SIGNATURE` (G7) and emit `PAYMENT-RESPONSE` (G8); the MCP-level `_meta` flow stays for MCP-native clients. | WIRE-OKLINK (POST→402, GET→405); Appx H.1 (live status matrix + x402-check `valid:true`); [api/mcp-3d.js](../api/mcp-3d.js), [api/_mcp/auth.js](../api/_mcp/auth.js); SDK is HTTP-transport only || 7 | How listing review validates the endpoint | Two layers. **(a) Registration-time `validate-listing` is PURE-LOCAL — no HTTP probe** (`onchainos-skills` `cli/…/identity/validate.rs`): it only checks A2MCP has an `endpoint`, the URL is `https://` + publicly reachable (rejects `http`, `localhost`, `127.0.0.1`, RFC-1918, `*.local/.internal`, mock/placeholder, >512 chars), fee is a plain number (USDT implicit), description has no URLs/addresses. It writes the endpoint URL on-chain (ERC-8004). Service-type → rail: **`A2MCP → x402`**. **(b) Approval / rejection** ("A2MCP service has not been integrated with the OKX Agent Payments Protocol") is a **human/off-repo review** — no codified automated probe that asserts the 402 shape exists in `okx/payments` or `onchainos-skills`. To pass it, the live endpoint must emit a v2 `402` whose `accepts` advertise **`eip155:196` + USD₮0** at the registered price. **Self-check tool (manual, not the gate):** `onchainos agent x402-check --endpoint <url>` flags `"Endpoint returned HTTP 200 (not 402); not a valid x402 service"` when the gate is absent (Appx E). **UNRESOLVED:** the exact method/body of any OKX-side automated probe, and whether one exists, are undocumented (dev-portal pages are JS-rendered / 404 to fetch). 02 should register, run `x402-check` against `https://three.ws/api/mcp-3d`, confirm `valid:true`, then resubmit for (human) review. | `onchainos-skills` `identity/validate.rs`, `task-cli-reference.md:396`; `onchainos agent x402-check` (Appx E); rejection email (00-CONTEXT) || 8 | Settlement finality — how seller confirms payment | Seller trusts the facilitator's responses, not its own chain read. `/verify` → `isValid:true` gates doing the work (proves the signed authorization is valid + payer funded — a broke payer gets `isValid:false` / `insufficient_balance`, proven by PAY-LEG2). `/settle` → `{success, status}`: `syncSettle:true` ⇒ `status:"success"` (on-chain confirmed before responding); default async ⇒ `status:"pending"` (safe to release; poll `/settle/status?txHash` for finality). The `PAYMENT-RESPONSE` header carries `{success,status,transaction,payer,amount}` to the buyer. | SDK `OKXFacilitatorClient.ts` settle L124-150 + `syncSettle` docstring; `types/facilitator.ts:26-38`; PAY-LEG2 |@@ -202,7 +204,7 @@ Reference: [api/_lib/x402-spec.js](../api/_lib/x402-spec.js) `paymentRequirement| G6 | Facilitator routing = CDP / PayAI / self / BSC-direct (`facilitatorFor()`). **No OKX facilitator.** | verify/settle at `https://web3.okx.com/api/v6/pay/x402/{verify,settle}` with HMAC auth. | Add an `OKXFacilitatorClient` route for `eip155:196` (adopt SDK, §3). || G7 | Payment header read = **`X-PAYMENT`** (x402 v1 name; `decodePaymentHeader`, `verifyPayment`) — despite the file labeling itself "v2". | Buyer sends **`PAYMENT-SIGNATURE`** (the x402 **v2** standard name). | On the X-Layer path read `PAYMENT-SIGNATURE` (case-insensitive; also accept `x-payment` for v1 back-compat). Keep `X-PAYMENT` for the other rails. || G8 | Success receipt = **`x-payment-response`** (x402 v1 name; set in `api/mcp-3d.js:107` etc.). | **`PAYMENT-RESPONSE`** (x402 v2 name). | Emit `PAYMENT-RESPONSE` on the X-Layer success reply. |-| G9 | Gating is **MCP-level** via `_meta` structuredContent in [api/mcp-3d.js](../api/mcp-3d.js). | **HTTP-level 402** on the endpoint URL. | Add an HTTP-402 gate at the transport layer (before/around the JSON-RPC handler) for the registered A2MCP resource URLs. |+| G9 | ~~Gating is MCP-level only~~ **CORRECTED:** HTTP-level 402 + `PAYMENT-REQUIRED` already emitted to non-MCP clients ([api/_mcp/auth.js](../api/_mcp/auth.js) `send402` path; live-verified `HTTP/2 402` on bare `tools/call`, Appx H.1). MCP-protocol clients get 401/OAuth — fine, OKX tooling never sends `mcp-protocol-version`. | **HTTP-level 402** on the endpoint URL — already satisfied. | No new gate. Verify with `x402-check` after G1-G8 land; keep the 401/OAuth branch for MCP clients as-is. || G10 | Body carries `extensions.bazaar` + `builder-code` + `offer-receipt`. | OKX sellers emit none of these on the `eip155:196` accepts. | Keep the OKX accept body minimal (`x402Version/resource/accepts`); don't attach Bazaar extensions to it. || G11 | Facilitator auth = CDP JWT / bearer token. | OKX HMAC needs `OKX_API_KEY`/`OKX_SECRET_KEY`/`OKX_PASSPHRASE`. | Provision + wire the three env vars (owner blocker). || G12 | `maxTimeoutSeconds: 60`. | Approved sellers use `86400`/`300`. | Use ≥ ~300 on X-Layer (bounds `validBefore`); `86400` matches oklink. |diff --git a/tests/api/okx-identity-studio.test.js b/tests/api/okx-identity-studio.test.jsnew file mode 100644index 000000000..4b25267c0--- /dev/null+++ b/tests/api/okx-identity-studio.test.js@@ -0,0 +1,384 @@+/**+ * Agent Identity Studio — the OKX.AI flagship A2MCP service+ * (/api/okx/3d/identity-studio, engine in api/_okx3d/identity.js, catalog row+ * in api/_lib/okx-catalog.js).+ *+ * Covers the catalog contract, the per-tool 402 pricing, the free lanes+ * (catalog/health/identity_status), the pipeline state machine over mocked+ * three.ws HTTP surfaces, and the honest edge cases the work order names:+ * Chinese brief, over-long brief (flagged truncation), and an unreachable+ * reference image failing BEFORE any payment settles.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { Readable } from 'node:stream';++process.env.PUBLIC_APP_ORIGIN = 'https://three.ws';+process.env.X402_PAY_TO_BASE ||= '0x0000000000000000000000000000000000000001';+process.env.X402_ASSET_ADDRESS_BASE ||= '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';+process.env.JWT_SECRET ||= 'okx-identity-test-secret';++vi.mock('../../api/_lib/auth.js', () => ({+ extractBearer: () => null,+ authenticateBearer: vi.fn(async () => null),+ hasScope: () => true,+}));++vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ mcpIp: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),+ mcpUser: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),+ },+ clientIp: vi.fn(() => '203.0.113.9'),+}));++vi.mock('../../api/_lib/usage.js', () => ({+ recordEvent: vi.fn(),+ logger: () => ({ info: () => {}, warn: () => {}, error: () => {} }),+}));++// In-memory R2 so job state round-trips without creds.+const r2Store = new Map();+vi.mock('../../api/_lib/r2.js', () => ({+ putObject: vi.fn(async ({ key, body }) => {+ r2Store.set(key, Buffer.isBuffer(body) ? body : Buffer.from(body));+ }),+ getObjectBuffer: vi.fn(async (key) => {+ if (!r2Store.has(key)) throw new Error('NoSuchKey');+ return r2Store.get(key);+ }),+ headObject: vi.fn(async (key) => {+ if (!r2Store.has(key)) throw new Error('NotFound');+ return { ContentLength: r2Store.get(key).length };+ }),+ publicUrl: (key) => `https://cdn.test/${key}`,+}));++// Reference-image validation calls the real SSRF guard's public-URL check —+// stub it to a pass-through so tests control reachability via fetch alone.+vi.mock('../../api/_lib/ssrf-guard.js', () => ({+ assertSafePublicUrl: vi.fn(async () => {}),+ SsrfBlockedError: class SsrfBlockedError extends Error {},+}));++// The pipeline is a pure HTTP client over three.ws surfaces — mock global+// fetch with a tiny programmable router.+const fetchRoutes = { chat: null, forgeSubmit: null, forgePoll: null, rig: null, render: null, ref: null };+function jsonResponse(status, body) {+ return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });+}+const realFetch = globalThis.fetch;+beforeEach(() => {+ r2Store.clear();+ fetchRoutes.chat = () => new Response(null, { status: 503 }); // director down → fallback template+ fetchRoutes.forgeSubmit = () => jsonResponse(200, { job_id: 'forge-gen-1', status: 'queued', eta: 30 });+ fetchRoutes.forgePoll = () => jsonResponse(200, { status: 'running' });+ fetchRoutes.rig = () => jsonResponse(200, { job_id: 'forge-rig-1', status: 'queued' });+ fetchRoutes.render = () => new Response(new Uint8Array(PNG_1x1), { status: 200 });+ fetchRoutes.ref = () => new Response(new Uint8Array([0xff]), { status: 206, headers: { 'content-type': 'image/png' } });+ globalThis.fetch = vi.fn(async (url, init = {}) => {+ const u = String(url);+ if (u.includes('/api/chat')) return fetchRoutes.chat(u, init);+ if (u.includes('/api/forge?action=rig')) return fetchRoutes.rig(u, init);+ if (u.includes('/api/forge?job=')) return fetchRoutes.forgePoll(u, init);+ if (u.includes('/api/forge')) return fetchRoutes.forgeSubmit(u, init);+ if (u.includes('/api/render/avatar-clip')) return fetchRoutes.render(u, init);+ return fetchRoutes.ref(u, init);+ });+ return () => {+ globalThis.fetch = realFetch;+ };+});++// Minimal valid 1×1 transparent PNG (for sharp to composite in render tests).+const PNG_1x1 = Buffer.from(+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',+ 'base64',+);++const { OKX_CATALOG, validateCatalog, catalogIndex, displayWidth, DESCRIPTION_MAX_WIDTH } =+ await import('../../api/_lib/okx-catalog.js');+const tools = await import('../../api/_okx3d/tools.js');+const identity = await import('../../api/_okx3d/identity.js');+const { default: handler } = await import('../../api/okx/3d/[service].js');++function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: null,+ setHeader(name, value) {+ this.headers[String(name).toLowerCase()] = value;+ },+ end(body) {+ this.body = body ?? null;+ },+ };+}++function makeReq({ method = 'POST', service = 'identity-studio', headers = {}, body = null } = {}) {+ const payload = body == null ? '' : JSON.stringify(body);+ const req = Readable.from(payload ? [Buffer.from(payload, 'utf8')] : []);+ req.method = method;+ req.url = `/api/okx/3d/${service}`;+ req.query = { service };+ req.headers = {+ 'content-type': 'application/json',+ 'x-forwarded-for': '203.0.113.9',+ ...headers,+ };+ return req;+}++const anonAuth = { userId: null, rateKey: null, scope: '', source: 'free' };+async function call(name, args) {+ return tools.dispatch(+ { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } },+ anonAuth,+ { headers: {} },+ );+}++describe('okx catalog module', () => {+ it('validates: every entry well-formed, prices consistent, descriptions within OKX display width', () => {+ expect(validateCatalog()).toBe(true);+ for (const e of OKX_CATALOG) {+ expect(displayWidth(e.describes.capability)).toBeLessThanOrEqual(DESCRIPTION_MAX_WIDTH);+ expect(displayWidth(e.describes.input)).toBeLessThanOrEqual(DESCRIPTION_MAX_WIDTH);+ }+ });++ it('counts East-Asian wide glyphs as 2 (the OKX listing rule)', () => {+ expect(displayWidth('abc')).toBe(3);+ expect(displayWidth('中文字')).toBe(6);+ expect(displayWidth('a中b')).toBe(4);+ });++ it('prices identity-studio at $1.50 = 1500000 atomics, and the index mirrors the catalog 1:1', () => {+ const row = OKX_CATALOG.find((e) => e.id === 'identity-studio');+ expect(row.amountAtomics).toBe('1500000');+ expect(tools.identityX402Amount('create_identity')).toBe('1500000');+ expect(tools.identityX402Amount('identity_status')).toBe(null);+ expect(tools.identityX402Amount('getting_started')).toBe(null);+ const index = catalogIndex();+ expect(index.services.map((s) => s.id)).toEqual(OKX_CATALOG.map((e) => e.id));+ expect(index.services.find((s) => s.id === 'identity-studio').price_usd).toBe('1.50');+ });+});++describe('free lanes over HTTP', () => {+ it('GET /catalog returns the index with no payment', async () => {+ const res = makeRes();+ await handler(makeReq({ method: 'GET', service: 'catalog' }), res);+ expect(res.statusCode).toBe(200);+ const body = JSON.parse(res.body);+ expect(body.okxAgentId).toBe(2632);+ expect(body.services.length).toBe(OKX_CATALOG.length);+ });++ it('GET /health runs real probes and reports per-subsystem status', async () => {+ fetchRoutes.forgeSubmit = () => jsonResponse(200, { tiers: [] });+ fetchRoutes.render = () => jsonResponse(200, { poses: [{ id: 'tpose' }] });+ const res = makeRes();+ await handler(makeReq({ method: 'GET', service: 'health' }), res);+ expect(res.statusCode).toBe(200);+ const body = JSON.parse(res.body);+ expect(body.ok).toBe(true);+ expect(body.subsystems.map((s) => s.name).sort()).toEqual(['generation', 'render', 'storage']);+ });++ it('GET /health goes 503 when a subsystem is down — never a hardcoded ok', async () => {+ fetchRoutes.render = () => new Response(null, { status: 500 });+ fetchRoutes.forgeSubmit = () => jsonResponse(200, { tiers: [] });+ const res = makeRes();+ await handler(makeReq({ method: 'GET', service: 'health' }), res);+ expect(res.statusCode).toBe(503);+ expect(JSON.parse(res.body).ok).toBe(false);+ });++ it('unknown service 404s with the service index', async () => {+ const res = makeRes();+ await handler(makeReq({ method: 'GET', service: 'nope' }), res);+ expect(res.statusCode).toBe(404);+ expect(JSON.parse(res.body).services.length).toBeGreaterThan(0);+ });+});++describe('402 challenge and pricing', () => {+ it('unpaid create_identity gets a 402 advertising exactly $1.50', async () => {+ const res = makeRes();+ await handler(+ makeReq({+ body: {+ jsonrpc: '2.0',+ id: 1,+ method: 'tools/call',+ params: { name: 'create_identity', arguments: { agent_name: 'X', brief: 'a data agent' } },+ },+ }),+ res,+ );+ expect(res.statusCode).toBe(402);+ const challenge = JSON.parse(res.body);+ expect(challenge.accepts.length).toBeGreaterThan(0);+ for (const a of challenge.accepts) {+ expect(a.maxAmountRequired ?? a.amount ?? a.maxAmount).toBe('1500000');+ }+ expect(JSON.stringify(challenge)).toContain('identity-studio');+ });++ it('identity_status is free — served anonymously, no 402', async () => {+ const res = makeRes();+ await handler(+ makeReq({+ body: {+ jsonrpc: '2.0',+ id: 2,+ method: 'tools/call',+ params: { name: 'identity_status', arguments: { job_id: 'garbage' } },+ },+ }),+ res,+ );+ expect(res.statusCode).toBe(200);+ const rpc = JSON.parse(res.body);+ expect(rpc.result.isError).toBe(true); // invalid token — but no payment demanded+ expect(rpc.result.structuredContent.error).toBe('invalid_job_id');+ });++ it('getting_started lists both tools with the paid price', async () => {+ const rpc = await call('getting_started', {});+ const text = JSON.stringify(rpc.result.structuredContent);+ expect(text).toContain('create_identity');+ expect(text).toContain('identity_status');+ expect(text).toContain('1.5');+ });+});++describe('pipeline state machine', () => {+ it('create → generate → rig → renders → done, with real deliverable shapes', async () => {+ const created = await call('create_identity', {+ agent_name: 'LedgerLynx',+ brief: 'a meticulous on-chain accounting agent, calm and precise',+ });+ expect(created.result.isError).toBeUndefined();+ const jobId = created.result.structuredContent.job_id;+ expect(jobId).toMatch(/^f1\./);++ // generation still running+ let s = await call('identity_status', { job_id: jobId });+ expect(s.result.structuredContent.status).toBe('running');+ expect(s.result.structuredContent.stage).toBe('generate');++ // generation done → same poll submits the rig+ fetchRoutes.forgePoll = () => jsonResponse(200, { status: 'done', glb_url: 'https://cdn.test/mesh.glb' });+ s = await call('identity_status', { job_id: jobId });+ expect(s.result.structuredContent.stage).toBe('rig');++ // rig done → render stage, one render per poll+ fetchRoutes.forgePoll = () => jsonResponse(200, { status: 'done', glb_url: 'https://cdn.test/rigged.glb' });+ s = await call('identity_status', { job_id: jobId });+ expect(s.result.structuredContent.stage).toBe('render');++ let last;+ for (let i = 0; i < 8 && (!last || last.status !== 'done'); i++) {+ const r = await call('identity_status', { job_id: jobId });+ last = r.result.structuredContent;+ }+ expect(last.status).toBe('done');+ const d = last.deliverables;+ expect(d.pfp.url).toContain('okx-identity/renders/');+ expect(d.pfp.preview_128_url).toContain('pfp-128');+ expect(d.full_body.length).toBe(3);+ expect(new Set(d.full_body.map((f) => f.pose)).size).toBe(3);+ expect(d.rigged_glb_url).toBe('https://cdn.test/rigged.glb');+ expect(d.viewer_url).toContain('/viewer?src=');+ }, 30_000);++ it('generation failure retries free, then fails honestly when attempts exhaust', async () => {+ const created = await call('create_identity', { agent_name: 'X', brief: 'test agent brief' });+ const jobId = created.result.structuredContent.job_id;+ fetchRoutes.forgePoll = () => jsonResponse(200, { status: 'failed', error: 'lane exploded' });+ // attempt 1 failed → resubmit (attempts 2), poll fails again → resubmit (3), fail → terminal+ let s;+ for (let i = 0; i < 4; i++) s = await call('identity_status', { job_id: jobId });+ expect(s.result.structuredContent.status).toBe('failed');+ expect(s.result.isError).toBe(true);+ expect(s.result.structuredContent.last_error.message).toContain('lane exploded');+ });++ it('a Chinese brief is accepted and reaches the prompt director verbatim', async () => {+ let directorSaw = null;+ fetchRoutes.chat = (u, init) => {+ directorSaw = JSON.parse(init.body).message;+ return new Response(null, { status: 503 });+ };+ const brief = '一个冷静精准的链上会计智能体,喜欢深蓝色';+ const created = await call('create_identity', { agent_name: '账本猞猁', brief });+ expect(created.result.isError).toBeUndefined();+ expect(directorSaw).toContain(brief);+ expect(directorSaw).toContain('ALWAYS write the prompt in English');+ // Fallback template still embeds the brief when the director is down.+ expect(created.result.structuredContent.brief_truncated).toBe(false);+ });++ it('an absurdly long brief is truncated and flagged, not silently mangled', async () => {+ const created = await call('create_identity', {+ agent_name: 'X',+ brief: 'A'.repeat(3999),+ });+ expect(created.result.isError).toBeUndefined();+ expect(created.result.structuredContent.brief_truncated).toBe(true);+ expect(created.result.structuredContent.note).toContain('truncated');+ });++ it('unreachable reference image fails with an actionable error BEFORE any work or charge', async () => {+ fetchRoutes.ref = () => new Response(null, { status: 404 });+ let forgeCalled = false;+ const origSubmit = fetchRoutes.forgeSubmit;+ fetchRoutes.forgeSubmit = (...a) => {+ forgeCalled = true;+ return origSubmit(...a);+ };+ const created = await call('create_identity', {+ agent_name: 'X',+ brief: 'test agent brief',+ reference_image_url: 'https://img.test/missing.png',+ });+ expect(created.result.isError).toBe(true);+ expect(created.result.structuredContent.error).toBe('reference_image_unreachable');+ expect(created.result.structuredContent.message).toContain('Nothing was charged');+ expect(forgeCalled).toBe(false);+ });++ it('non-image reference URL is rejected with a distinct actionable error', async () => {+ fetchRoutes.ref = () =>+ new Response('<html>', { status: 200, headers: { 'content-type': 'text/html' } });+ const created = await call('create_identity', {+ agent_name: 'X',+ brief: 'test agent brief',+ reference_image_url: 'https://img.test/page.html',+ });+ expect(created.result.isError).toBe(true);+ expect(created.result.structuredContent.error).toBe('reference_image_invalid');+ });++ it('render plan is deterministic per job, PFP pose pinned, full-body poses distinct', () => {+ const a = identity.buildRenderPlan('job-a');+ const b = identity.buildRenderPlan('job-a');+ const c = identity.buildRenderPlan('job-c');+ expect(a).toEqual(b);+ expect(a[0]).toMatchObject({ kind: 'pfp', pose: 'contrapposto' });+ expect(a.filter((s) => s.kind === 'fullbody').length).toBe(3);+ expect(new Set(a.map((s) => s.pose)).size).toBe(a.length);+ expect(JSON.stringify(a) === JSON.stringify(c) && JSON.stringify(a.slice(1)) === JSON.stringify(c.slice(1))).toBe(+ JSON.stringify(a.slice(1)) === JSON.stringify(c.slice(1)),+ );+ });++ it('job tokens from other providers are rejected', async () => {+ const { encodeJobToken } = await import('../../api/_lib/forge-job-token.js');+ const foreign = encodeJobToken({ provider: 'gcp', kind: 'reconstruct', taskId: 'abc' });+ const s = await call('identity_status', { job_id: foreign });+ expect(s.result.structuredContent.error).toBe('invalid_job_id');+ });+});diff --git a/vercel.json b/vercel.jsonindex 82ea60c72..6a5119005 100644--- a/vercel.json+++ b/vercel.json@@ -41,6 +41,10 @@"api/x402-facilitator/[action].js": {"maxDuration": 60},+ "api/okx/3d/[service].js": {+ "includeFiles": "{node_modules/@img/sharp-libvips-linux-x64/**,node_modules/@img/sharp-linux-x64/**}",+ "maxDuration": 120+ },"api/widgets/[id]/knowledge-process.js": {"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}","maxDuration": 300@@ -2116,6 +2120,10 @@"src": "/api/x402-facilitator/([^/]+)","dest": "/api/x402-facilitator/[action]?action=$1"},+ {+ "src": "/api/okx/3d/([a-z0-9-]+)",+ "dest": "/api/okx/3d/[service]?service=$1"+ },{"src": "/api/cron/(audit-log-cleanup|cleanup-csrf-tokens|club-payouts|cosmetic-splits-sweep|erc8004-crawl|expire-pending-purchases|fetch-x-metrics|index-delegations|irl-drops-refund|monetization-payouts|process-subscriptions|process-withdrawals|pump-agent-stats|pumpfun-graduations-sync|pumpfun-monitor|pumpfun-signals|run-buyback|run-coin-cycle|run-coin-payouts|run-dca|run-distribute-payments|run-subscriptions|run-three-buyback|run-x-scheduled-posts|run-x-triggers|settle-royalties|siwx-gc|solana-agents-crawl|solana-attest-event-cleanup|solana-attestations-crawl|treasury-autopilot|unstoppable-tick)","dest": "/api/cron/[name]?name=$1"diff --git a/workers/vanity-grinder/Dockerfile b/workers/vanity-grinder/Dockerfilenew file mode 100644index 000000000..5dc5aa617--- /dev/null+++ b/workers/vanity-grinder/Dockerfile@@ -0,0 +1,35 @@+# Batch vanity grinder — GCP spot CPU container.+#+# Build from the REPO ROOT so the repo-relative imports (../../src, ../../api)+# resolve inside the image exactly as they do in the working tree:+# docker build -f workers/vanity-grinder/Dockerfile -t vanity-grinder .+#+# Runs the same WASM ed25519 grind engine as the serverless tier, seals every+# found key in-process (api/_lib/vanity-vault.js), and writes ONLY ciphertext —+# to the DB (WRITE_DB=1) and/or an encrypted JSONL. No plaintext key ever hits+# disk, a log, or the network. See README.md.++FROM node:22-slim AS base+WORKDIR /app++# Install only the batch grinder's runtime deps (bs58 + optional Neon driver).+COPY workers/vanity-grinder/package.json ./package.json+RUN npm install --omit=dev --no-audit --no-fund++# Copy the source the grinder imports, preserving repo-relative layout so+# ../../src and ../../api resolve. src/solana carries the prebuilt WASM engine.+COPY src/solana ./src/solana+COPY api/_lib ./api/_lib+COPY workers/vanity-grinder ./workers/vanity-grinder++# Non-root: the job never needs privileges.+USER node++# Encrypted output lives under /app/out by default; override OUTPUT_FILE to a+# mounted volume / /tmp, or set WRITE_DB=1 to write straight to vanity_inventory.+ENV OUTPUT_FILE=/tmp/inventory.jsonl \+ CHECKPOINT_FILE=/tmp/checkpoint.json \+ SUMMARY_FILE=/tmp/summary.json \+ RUNNER=cloud-run-job++ENTRYPOINT ["node", "workers/vanity-grinder/grind.mjs"]diff --git a/workers/vanity-grinder/README.md b/workers/vanity-grinder/README.mdnew file mode 100644index 000000000..2d5329ae8--- /dev/null+++ b/workers/vanity-grinder/README.md@@ -0,0 +1,86 @@+# vanity-grinder (batch) — premium inventory producer++Grinds long, brandable Solana vanity addresses **ahead of time** on cheap batch+CPU (GCP spot), so the platform can sell them from stock instantly via the+premium tier (`/api/x402/vanity-premium`). The live `vanity_grinder` MCP tool and+`/api/x402/vanity` still grind a fresh ≤3‑char keypair per request — this is the+separate 4–5+‑char sell-from-stock lane.++It runs the exact same Rust/ed25519 WASM engine as the serverless grinder+(`src/solana/vanity/wasm`), one worker per vCPU, and — critically — **seals every+found key in-process before any write**. Plaintext keys never touch disk, a log,+or the network.++## What it does++1. Loads a **target list** (brandable prefixes/suffixes — see `targets.mjs`, or+ supply `TARGETS_FILE`). Every pattern is brand-neutral (commit-gate safe).+2. Grinds each target to completion across all cores.+3. For each hit: computes rarity + a difficulty-scaled price+ (`api/_lib/vanity-inventory-pricing.js`), **seals** the keypair+ (`api/_lib/vanity-vault.js` → AES‑256‑GCM, or a GCP‑KMS envelope when+ `VANITY_KMS_KEY` is set), and writes the **ciphertext** to an encrypted JSONL+ and/or straight into the `vanity_inventory` table (`WRITE_DB=1`).+4. Checkpoints completed targets so it is **resumable** — a spot preemption+ (SIGTERM) flushes and exits; the next run skips finished targets.++## Run locally++```bash+# from the repo root+export WALLET_ENCRYPTION_KEY=… # required (or set VANITY_KMS_KEY)+export JWT_SECRET=… # secret-box reads it as a decrypt fallback+node workers/vanity-grinder/grind.mjs # grinds the built-in target list+```++Output: encrypted `workers/vanity-grinder/out/inventory.jsonl` + `summary.json`+(throughput). Load it into the DB later with+`node scripts/vanity-inventory-load.mjs --file <inventory.jsonl>`.++### Useful env++| var | default | meaning |+|-----|---------|---------|+| `WALLET_ENCRYPTION_KEY` | — | secret-box master key (required unless KMS) |+| `VANITY_KMS_KEY` | — | KMS crypto-key resource → envelope encryption |+| `TARGETS_FILE` | built-in | JSON array of `{prefix?,suffix?,ignoreCase}` |+| `INCLUDE_5` | `0` | include slow 5‑char stretch targets |+| `IGNORE_CASE` | `0` | fold case on prefix targets (≈½ difficulty/char) |+| `MAX_FOUND` | ∞ | stop after N addresses |+| `WORKERS` | all vCPUs | worker thread count |+| `RETENTION_DAYS` | `0` | ciphertext retention after reveal (0 = delete-on-reveal) |+| `WRITE_DB` | `0` | `1` to upsert into `vanity_inventory` (needs `DATABASE_URL`) |+| `SHARD_INDEX`/`SHARD_COUNT` | `0`/`1` | partition targets across parallel instances |++## Build the image++```bash+# build context MUST be the repo root+docker build -f workers/vanity-grinder/Dockerfile -t vanity-grinder .+docker run --rm -e WALLET_ENCRYPTION_KEY=… -e JWT_SECRET=… -e MAX_FOUND=20 \+ -v "$PWD/out:/tmp" vanity-grinder+```++## Deploy to GCP spot CPU++Two supported runners; pick per the trade-off (see `docs/gcp-credits.md`):++- **Cloud Run Job** (simplest, recommended) — `scripts/gcp/vanity-grind-deploy.sh`+ builds + pushes the image and creates a spot-billed Job you execute on demand.+ Write straight to Neon with `WRITE_DB=1` for durable output.+- **GCE spot MIG** (max cores/$ for very large runs) — the same script's+ `--mig` mode; each instance takes a `SHARD_INDEX` of the target list.++KMS envelope encryption (recommended for production inventory) is provisioned by+`scripts/gcp/vanity-kms-setup.sh`, which creates the keyring/key and grants+decrypt **only** to the delivery service identity.++## Security++- Keys are sealed **before** the first write; the DB and JSONL hold ciphertext+ only. A dump reveals no spendable key.+- Nothing in this worker logs secret material — the only "found" log line is the+ public address + attempt count.+- Single-use delivery + delete-after-reveal are enforced downstream in+ `api/_lib/vanity-inventory-store.js` / `api/x402/vanity-premium.js`.+- See the threat model in `docs/gcp-credits.md` (§ Premium vanity inventory).diff --git a/workers/vanity-grinder/grind.mjs b/workers/vanity-grinder/grind.mjsindex fab566661..e860348d3 100644--- a/workers/vanity-grinder/grind.mjs+++ b/workers/vanity-grinder/grind.mjs@@ -182,6 +182,16 @@ async function persistFound({ target, publicKey, secretKey, attempts, durationMs// ── Orchestration ────────────────────────────────────────────────────────────let stopping = false;+let onStop = null;+const workers = [];++// Abort every worker's in-flight grind. Workers check the stop flag between+// batches (~sub-second) and post 'aborted', letting the run wind down cleanly.+function stopAllWorkers() {+ for (const w of workers) {+ try { w.postMessage({ type: 'stop' }); } catch { /* worker already gone */ }+ }+}async function main() {mkdirSync(dirname(OUTPUT_FILE), { recursive: true });@@ -205,15 +215,23 @@ async function main() {let cursor = 0;let active = 0;- const workers = [];await new Promise((resolveAll) => {+ let settled = false;const maybeFinish = () => {- if ((cursor >= pending.length && active === 0) || stopping) {- for (const w of workers) w.postMessage({ type: 'stop' });+ if (settled) return;+ if ((cursor >= pending.length && active === 0) || (stopping && active === 0)) {+ settled = true;+ stopAllWorkers();resolveAll();}};+ // A SIGTERM (spot preemption) sets `stopping` and asks workers to abort; once+ // each in-flight target reports 'aborted' (active hits 0) the run winds down.+ onStop = () => {+ stopAllWorkers();+ maybeFinish();+ };const assign = (worker) => {if (stopping || cursor >= pending.length || stats.found >= MAX_FOUND) {@@ -299,6 +317,7 @@ for (const sig of ['SIGTERM', 'SIGINT']) {console.log(`[grind] ${sig} received — checkpointing and shutting down`);stopping = true;saveCheckpoint();+ if (onStop) onStop();});}diff --git a/workers/vanity-grinder/package.json b/workers/vanity-grinder/package.jsonnew file mode 100644index 000000000..81f727849--- /dev/null+++ b/workers/vanity-grinder/package.json@@ -0,0 +1,20 @@+{+ "name": "@threews/vanity-grinder-batch",+ "version": "1.0.0",+ "private": true,+ "type": "module",+ "description": "Batch Solana vanity-address grinder for the premium inventory tier — runs on GCP spot CPU, seals every key in-process, writes only ciphertext.",+ "main": "grind.mjs",+ "scripts": {+ "start": "node grind.mjs",+ "grind": "node grind.mjs"+ },+ "dependencies": {+ "bs58": "^5.0.0",+ "@neondatabase/serverless": "^0.10.4",+ "ws": "^8.18.0"+ },+ "engines": {+ "node": ">=20"+ }+}