Skip to content

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

feat: add Vertex Claude model support and GCP budget alert webhook

fudjia3d16c2e71d13
diff --git a/api/_lib/chat-models.js b/api/_lib/chat-models.js
index 658d4352c..6f1d222cf 100644
--- a/api/_lib/chat-models.js
+++ b/api/_lib/chat-models.js
@@ -82,6 +82,26 @@ export const MODEL_CATALOG = {
'gpt-4o-mini': { provider: 'openai', tools: true },
};
+/**
+ * Anthropic model ids that the Vertex Claude transport (api/_lib/vertex-claude.js)
+ * can serve when VERTEX_CLAUDE_ENABLED is set. The SAME ids serve both first-party
+ * Anthropic and Vertex — the transport is chosen by flag at request time, not by
+ * the catalog — so these keep their `provider: 'anthropic'` entries above (tools,
+ * gating, capability are identical). This list only tells the routing brain WHICH
+ * Claude ids have a Vertex transport available; `vertexServesModel()` is the gate.
+ * The dated Haiku id maps to Vertex's `@` form via toVertexModelId() at call time.
+ */
+export const VERTEX_ANTHROPIC_MODELS = [
+ 'claude-opus-4-7',
+ 'claude-sonnet-4-6',
+ 'claude-haiku-4-5-20251001',
+];
+
+/** Whether the Vertex Claude transport can serve a given Anthropic model id. */
+export function vertexServesModel(modelId) {
+ return VERTEX_ANTHROPIC_MODELS.includes(modelId);
+}
+
/** Whether a model exposes a tool/function-calling endpoint. Unknown → false. */
export function modelSupportsTools(modelId) {
return MODEL_CATALOG[modelId]?.tools === true;
diff --git a/api/_lib/llm.js b/api/_lib/llm.js
index 6a2c7ec5b..ddc4fcf05 100644
--- a/api/_lib/llm.js
+++ b/api/_lib/llm.js
@@ -173,7 +173,7 @@ function openaiCompatProvider({ name, key, url, model, extraHeaders = {} }) {
// free provider: the prod paid keys are routinely invalid or out of quota, so
// platform spend never leads and nothing depends on it — but when a key does
// work, a request that exhausted the free tier still succeeds.
-function providerChain({ anthropicKey, anthropicModel, preferNvidia = false, nvidiaModel = null } = {}) {
+export function providerChain({ anthropicKey, anthropicModel, preferNvidia = false, nvidiaModel = null } = {}) {
const chain = [];
// Opt-in: lead with the NVIDIA NIM lane on a chosen Nemotron model. Used by
// features that want the NVIDIA-native model to actually produce the result
diff --git a/api/brain/chat.js b/api/brain/chat.js
index 9954735d5..fecb4d128 100644
--- a/api/brain/chat.js
+++ b/api/brain/chat.js
@@ -447,6 +447,68 @@ async function streamWatsonx(res, { messages, system, maxTokens, t0 }) {
res.end();
}
+// Stream Vertex-served Claude to the /brain page using the same SSE protocol as
+// the AI SDK path. Vertex returns first-party Anthropic Messages SSE, so we parse
+// content_block_delta text_delta events and re-emit them as brain first/chunk/done
+// events. Like streamWatsonx it only throws before writing tokens (a non-ok
+// upstream or connection failure), so streamBrain can fall back to the free chain.
+async function streamVertex(res, { messages, system, maxTokens, t0, model }) {
+ const upstream = await vertexAnthropicMessages(
+ { model, max_tokens: maxTokens, ...(system ? { system } : {}), messages },
+ { stream: true },
+ );
+ if (!upstream.ok || !upstream.body) {
+ const detail = await upstream.text().catch(() => '');
+ throw new Error(`vertex ${upstream.status}: ${detail.slice(0, 200)}`);
+ }
+
+ const reader = upstream.body.getReader();
+ const decoder = new TextDecoder();
+ let buf = '';
+ let firstTokenMs = null;
+ let inputTokens = 0;
+ let outputTokens = 0;
+
+ while (true) {
+ 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;
+ const raw = line.slice(5).trim();
+ if (!raw || raw === '[DONE]') continue;
+ let evt;
+ try {
+ evt = JSON.parse(raw);
+ } catch {
+ continue;
+ }
+ if (evt.type === 'message_start') {
+ inputTokens = evt.message?.usage?.input_tokens ?? inputTokens;
+ } else if (evt.type === 'content_block_delta' && evt.delta?.type === 'text_delta') {
+ const text = evt.delta.text || '';
+ if (text) {
+ if (firstTokenMs === null) {
+ firstTokenMs = Date.now() - t0;
+ res.write(`event: first\ndata: ${JSON.stringify({ firstTokenMs })}\n\n`);
+ }
+ res.write(`data: ${JSON.stringify(text)}\n\n`);
+ }
+ } else if (evt.type === 'message_delta') {
+ outputTokens = evt.usage?.output_tokens ?? outputTokens;
+ }
+ }
+ }
+
+ const elapsedMs = Date.now() - t0;
+ const usage = { inputTokens, outputTokens, totalTokens: inputTokens + outputTokens };
+ res.write(`event: done\ndata: ${JSON.stringify({ elapsedMs, firstTokenMs, usage })}\n\n`);
+ res.write('data: [DONE]\n\n');
+ res.end();
+}
+
export function validateMessages(input) {
if (!Array.isArray(input)) {
throw Object.assign(new Error('messages must be an array'), { status: 400 });
@@ -656,6 +718,8 @@ export async function streamBrain(res, { plan, providerKey, messages, system, ma
// client, emitting the same first/chunk/done event protocol. It only
// throws before writing tokens, so falling through is safe.
if (attempt.watsonx) await streamWatsonx(res, { messages, system, maxTokens, t0 });
+ else if (attempt.vertex)
+ await streamVertex(res, { messages, system, maxTokens, t0, model: attempt.model });
else await streamOnce(maxTokens, attempt.model);
return;
} catch (err) {
diff --git a/api/webhooks/gcp-budget-alert.js b/api/webhooks/gcp-budget-alert.js
new file mode 100644
index 000000000..8dcfd5a8d
--- /dev/null
+++ b/api/webhooks/gcp-budget-alert.js
@@ -0,0 +1,109 @@
+// POST /api/webhooks/gcp-budget-alert
+//
+// Receives Cloud Billing budget notifications (Pub/Sub push) and turns each
+// threshold crossing into a Telegram ops ping via sendOpsAlert — the same path
+// the changelog bot uses, but the PRIVATE ops chat (TELEGRAM_ALERTS_CHAT_ID),
+// never the holders' channel. This is how the $100k credit program (see
+// prompts/gcp-credits/ and docs/gcp-credits.md) surfaces a runaway lane BEFORE
+// it drains the grant: scripts/gcp/create-budgets.mjs registers budgets at
+// 25/50/75/90/100% pointing at a Pub/Sub topic; that topic pushes here.
+//
+// Pub/Sub push envelope (JSON body):
+// { message: { data: <base64>, attributes, messageId, publishTime }, subscription }
+// The base64 `data` decodes to the budget notification JSON:
+// { budgetDisplayName, alertThresholdExceeded, costAmount, budgetAmount,
+// currencyCode, costIntervalStart }
+//
+// Auth: Pub/Sub push can't carry a session, so the subscription is created with
+// a shared secret in the endpoint query string (?token=…). We constant-time
+// compare it against GCP_BUDGET_WEBHOOK_SECRET. Without the secret set, the
+// endpoint refuses (503) rather than accepting unauthenticated pings.
+//
+// Always ACK (200) once authenticated — even on a malformed message — so Pub/Sub
+// doesn't redeliver in a retry storm. Parse/alert failures are logged, not 5xx'd.
+
+import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+import { sendOpsAlert } from '../_lib/alerts.js';
+
+function presentedToken(req) {
+ // Accept the secret from the query string (how GCP push subscriptions attach
+ // it) or an x-webhook-token header (for manual/curl testing).
+ try {
+ const url = new URL(req.url, 'http://localhost');
+ const q = url.searchParams.get('token');
+ if (q) return q;
+ } catch { /* fall through */ }
+ const h = req.headers['x-webhook-token'];
+ return Array.isArray(h) ? h[0] : h || '';
+}
+
+function decodeNotification(body) {
+ const data = body?.message?.data;
+ if (!data || typeof data !== 'string') return null;
+ try {
+ return JSON.parse(Buffer.from(data, 'base64').toString('utf8'));
+ } catch {
+ return null;
+ }
+}
+
+function fmtUsd(n) {
+ const v = Number(n);
+ if (!Number.isFinite(v)) return '—';
+ return `$${v.toLocaleString('en-US', { maximumFractionDigits: 2 })}`;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const secret = process.env.GCP_BUDGET_WEBHOOK_SECRET;
+ if (!secret) return error(res, 503, 'not_configured', 'GCP_BUDGET_WEBHOOK_SECRET unset');
+ if (!constantTimeEquals(presentedToken(req), secret)) {
+ return error(res, 401, 'unauthorized', 'invalid webhook token');
+ }
+
+ let body;
+ try {
+ body = await readJson(req);
+ } catch {
+ // Malformed JSON — ack so Pub/Sub stops retrying, but say we couldn't parse.
+ return json(res, 200, { ok: true, parsed: false });
+ }
+
+ const note = decodeNotification(body);
+ if (!note) {
+ // A subscription-verification ping or an attributes-only message: ack.
+ return json(res, 200, { ok: true, parsed: false });
+ }
+
+ const cost = Number(note.costAmount);
+ const budget = Number(note.budgetAmount);
+ const pct = budget > 0 ? cost / budget : null;
+ const threshold = Number(note.alertThresholdExceeded); // e.g. 0.9 — absent on info pings
+
+ // Only ping on an actual threshold crossing. Budget notifications also fire
+ // as periodic info messages with no alertThresholdExceeded — those would be
+ // noise in the ops channel.
+ if (!Number.isFinite(threshold)) {
+ return json(res, 200, { ok: true, alerted: false, reason: 'no_threshold' });
+ }
+
+ const name = note.budgetDisplayName || 'GCP budget';
+ const pctStr = pct != null ? `${Math.round(pct * 100)}%` : '—';
+ const emoji = threshold >= 0.9 ? '🔴' : threshold >= 0.75 ? '🟠' : '🟡';
+
+ await sendOpsAlert(
+ `${emoji} GCP budget ${Math.round(threshold * 100)}% — ${name}`,
+ [
+ `Spend ${fmtUsd(cost)} of ${fmtUsd(budget)} (${pctStr}) ${note.currencyCode || 'USD'}`,
+ threshold >= 0.9 ? 'Runaway risk — check `node scripts/gcp/burn-report.mjs`, consider scripts/gcp/emergency-stop.sh.' : 'Burn-down tracking on schedule; review the spend dashboard (/dashboard/spend).',
+ ].join('\n'),
+ // Dedup per budget + threshold so each crossing pings once/hour, not each
+ // time the budget re-evaluates within the window.
+ { signature: `gcp-budget:${name}:${threshold}` },
+ );
+
+ return json(res, 200, { ok: true, alerted: true, threshold, pct });
+});
diff --git a/prompts/okx-ai/PROGRESS.md b/prompts/okx-ai/PROGRESS.md
index e1ccb5a61..ed89e8374 100644
--- a/prompts/okx-ai/PROGRESS.md
+++ b/prompts/okx-ai/PROGRESS.md
@@ -53,3 +53,67 @@ have not been executed.** No code was changed and no money was spent this sessio
- No funding request was presented to the owner: the amounts in WO 04 Phase 1 depend on
WO 03's price points, which don't exist yet. Requesting funds now would be premature.
- **GO/NO-GO for Work Order 05: NO-GO** (transitively — 04 never ran).
+
+---
+
+## 2026-07-06 — Work Order 01 session: COMPLETE, green-light for Work Order 02
+
+**Outcome: Seller-side OKX Agent Payments Protocol contract fully pinned down from primary
+sources. Deliverable written: [`specs/okx-agent-payments.md`](../../specs/okx-agent-payments.md).**
+All 8 questions answered with citations; one real signature produced on-chain-ready; funding
+is the only blocker to a fully-successful paid leg.
+
+### What was done / verified
+
+- **Reverse-engineered THREE live approved A2MCP sellers** (mandatory evidence): Onchain Data
+ Explorer #2023 (174 sales), CoinAnk OpenAPI #2013 (818 sales), OKB Monitoring #3837. Captured
+ each 402 verbatim, decoded, and diffed to derive the required-vs-optional field matrix.
+- **Executed a real payment leg** from our wallet: `onchainos payment pay` signed a valid
+ EIP-3009 authorization (leg 1 real, header `PAYMENT-SIGNATURE`). Replay returned
+ `402 error:"insufficient_balance"` — proving the seller→facilitator verify path is live and
+ does an on-chain balance check (leg 2 real, just unfunded). Full captures in spec Appendix D.
+- **Read the official OKX Payments SDK** (`github.com/okx/payments`, Apache-2.0, published on
+ npm as `@okxweb3/app-x402-*@0.2.0`, pure-TS ⇒ Vercel-safe). Extracted the facilitator
+ endpoints, HMAC auth, header codecs, and a concrete seller wiring example.
+
+### Answers that unblock WO 02 (details + citations in the spec)
+
+- **Header divergence (the核心 delta):** buyer sends **`PAYMENT-SIGNATURE`** (not vanilla
+ x402's `X-PAYMENT`); success receipt is **`PAYMENT-RESPONSE`** (not `X-PAYMENT-RESPONSE`).
+- **Challenge:** `PAYMENT-REQUIRED` header (base64) + body; per-accept required fields =
+ `scheme, network:"eip155:196", asset(USD₮0 0x779ded…), payTo, amount, maxTimeoutSeconds,
+ extra.name:"USD₮0", extra.version:"1"`. `extra` uses `transferMethod` (NOT
+ `assetTransferMethod`) and carries NO `decimals`. No Bazaar extensions.
+- **Required scheme:** `exact` (EIP-3009) — the only one all 3 sellers share. `aggr_deferred`
+ optional/recommended. `upto` unneeded (and needs a Permit2 approve + facilitatorAddress).
+- **Facilitator:** `https://web3.okx.com/api/v6/pay/x402/{verify,settle,supported,settle/status}`,
+ body `{x402Version:2, paymentPayload, paymentRequirements[, syncSettle]}`, auth = OKX REST
+ **HMAC-SHA256** (`OK-ACCESS-KEY/SIGN/TIMESTAMP/PASSPHRASE`).
+- **Gating level:** OKX validates **HTTP-level 402** on the endpoint URL — our current
+ MCP-level `_meta` PaymentRequired is invisible to it. 02 must add an HTTP-402 transport gate.
+- **Fee token:** USD₮0 `0x779Ded0c9e1022225f8E0630b35a9b54bE713736`, symbol USDT, 6 decimals,
+ EIP-3009.
+- **SDK decision:** ADOPT `@okxweb3/app-x402-core` + `@okxweb3/app-x402-evm` for the X-Layer
+ rail (thin `HTTPAdapter` over our bare Vercel `req/res`); keep `api/_lib/x402-spec.js` for
+ Solana/Base/BSC. 12-item gap list is spec §4 (that's 02's work-list).
+
+### Blocked on / next (raise with owner)
+
+1. **OKX API credentials** — the facilitator verify/settle needs `OKX_API_KEY`,
+ `OKX_SECRET_KEY`, `OKX_PASSPHRASE` from the OKX Web3 developer console. Without them every
+ `/verify`/`/settle` fails auth. Owner must provision. **(Blocks WO 02 runtime + WO 04.)**
+2. **Funding for a fully-successful paid leg** — fund `0x75d00a2713565171f33216e5aa2a375e076ecf69`
+ on **X Layer (chainId 196)** with **USD₮0** (`0x779ded…713736`). Min 15 atomic (0.000015)
+ to pay oklink's cheapest call; recommend **~1.0 USD₮0 (1,000,000 atomic)** for buffer.
+ EIP-3009 is gasless for the payer, so no OKB strictly required (optional ~0.5 OKB dust).
+ Current X-Layer balance = 0.
+3. **One UNRESOLVED item** (spec Q7): the exact HTTP method/body the *automated* listing
+ validator sends is undocumented — 02 should register, run
+ `onchainos agent x402-check --endpoint https://three.ws/api/mcp-3d`, and confirm
+ `valid:true` before resubmitting. Not a blocker; a verification step.
+
+### GO/NO-GO
+
+- **Work Order 02: GO** — spec is the implementation contract; §4 is the field-by-field
+ work-list. Two owner-provisioning items above should be requested in parallel with 02's code
+ (credentials block runtime/testing, not the code changes themselves).
diff --git a/scripts/gcp/revert-to-free.sh b/scripts/gcp/revert-to-free.sh
index 2ed410cb4..cbb30263c 100755
--- a/scripts/gcp/revert-to-free.sh
+++ b/scripts/gcp/revert-to-free.sh
@@ -206,6 +206,8 @@ dim " configured:false; free NIM/HF lanes show configured:true. UI stops off
dim " • Generate a text→3D (free NIM) and a photo→3D (free HF) — both succeed."
dim " • Generate an avatar — reconstruct routes to Replicate/HF (check the response provider)."
dim " • A text→image request returns from nvidia (NIM FLUX), not vertex-ai/*."
+dim " • A chat completion's route.via is a free provider (groq/openrouter/nvidia), not"
+dim " 'vertex-anthropic' — confirms VERTEX_CLAUDE_* removal dropped Vertex from the ladder."
dim " • GCP billing: after min-instances=0 and no traffic, Cloud Run GPU spend trends to \$0."
echo
ok "Revert plan complete. Nothing on three.ws should break — every GCP lane hands off to the"
diff --git a/tests/api/gcp-revert.test.js b/tests/api/gcp-revert.test.js
index 5f1055af9..e65168481 100644
--- a/tests/api/gcp-revert.test.js
+++ b/tests/api/gcp-revert.test.js
@@ -16,6 +16,10 @@ import {
} from '../../api/_lib/forge-tiers.js';
import { isConfigured as imagenIsConfigured } from '../../api/_mcp3d/vertex-imagen.js';
import { resolveProviderName } from '../../api/_lib/regen-provider.js';
+import {
+ vertexClaudeEnabled,
+ vertexClaudePrimary,
+} from '../../api/_lib/vertex-claude.js';
// Every env var the revert touches, cleared between tests so each case sets only
// what it means to assert on.
@@ -24,6 +28,7 @@ const ALL = [
'GCP_RECONSTRUCTION_URL', 'GCP_RECONSTRUCTION_KEY',
'GCP_REMBG_URL', 'GCP_TEXTURE_URL', 'GCP_SEGMENT_URL',
'GOOGLE_CLOUD_PROJECT', 'GCP_SERVICE_ACCOUNT_JSON',
+ 'VERTEX_CLAUDE_ENABLED', 'VERTEX_CLAUDE_PRIMARY',
'NVIDIA_API_KEY', 'HF_TOKEN', 'REPLICATE_API_TOKEN', 'AVATAR_REGEN_PROVIDER',
];
@@ -109,6 +114,26 @@ describe('avatar reconstruct/rerig: reverts GCP → Replicate → HF', () => {
});
});
+describe('vertex claude chat lane: reverts by unsetting the VERTEX_CLAUDE_* flags', () => {
+ it('enabled/primary require both the flag and GOOGLE_CLOUD_PROJECT; clear the flags to revert', () => {
+ process.env.GOOGLE_CLOUD_PROJECT = 'three-ws-prod';
+ process.env.VERTEX_CLAUDE_ENABLED = '1';
+ process.env.VERTEX_CLAUDE_PRIMARY = '1';
+ expect(vertexClaudeEnabled()).toBe(true);
+ expect(vertexClaudePrimary()).toBe(true);
+ // Revert step 1: demote from primary (leaves it available but not leading).
+ delete process.env.VERTEX_CLAUDE_PRIMARY;
+ expect(vertexClaudeEnabled()).toBe(true);
+ expect(vertexClaudePrimary()).toBe(false);
+ // Revert step 2: fully off — Vertex drops out of the chat provider ladder.
+ delete process.env.VERTEX_CLAUDE_ENABLED;
+ expect(vertexClaudeEnabled()).toBe(false);
+ expect(vertexClaudePrimary()).toBe(false);
+ // Config alone (project set, flags off) never enables the lane — the flag gates it.
+ expect(vertexClaudeEnabled()).toBe(false);
+ });
+});
+
describe('imagen text→image: reverts to free NIM FLUX by unsetting GOOGLE_CLOUD_PROJECT', () => {
it('isConfigured() flips with the project gate', () => {
process.env.GOOGLE_CLOUD_PROJECT = 'three-ws-prod';
diff --git a/workers/vanity-grinder/grind-worker.mjs b/workers/vanity-grinder/grind-worker.mjs
new file mode 100644
index 000000000..746e53ad7
--- /dev/null
+++ b/workers/vanity-grinder/grind-worker.mjs
@@ -0,0 +1,56 @@
+// Worker thread — pure grinding, no secret persistence.
+//
+// The main thread (grind.mjs) owns all sealing and writing so secret handling
+// stays centralized. A worker only receives a target, grinds it to completion in
+// the WASM engine, and posts the raw keypair back over the in-process thread
+// channel (never to disk, never to a log). It then waits for the next target.
+//
+// Protocol:
+// main → worker: { type: 'grind', target } | { type: 'stop' }
+// worker → main: { type: 'ready' }
+// { type: 'found', target, publicKey, secretKey, attempts, durationMs }
+// { type: 'progress', attempts }
+
+import { parentPort, workerData } from 'node:worker_threads';
+import { grindToCompletion } from './wasm-grind.mjs';
+
+let stop = false;
+const PROGRESS_EVERY = 2_000_000; // report roughly every ~80s of single-thread work
+
+parentPort.on('message', (msg) => {
+ if (!msg || typeof msg !== 'object') return;
+ if (msg.type === 'stop') {
+ stop = true;
+ return;
+ }
+ if (msg.type === 'grind') {
+ let lastReported = 0;
+ const result = grindToCompletion(msg.target, {
+ stopRequested: () => stop,
+ onProgress: (attempts) => {
+ if (attempts - lastReported >= PROGRESS_EVERY) {
+ lastReported = attempts;
+ parentPort.postMessage({ type: 'progress', attempts: PROGRESS_EVERY, worker: workerData?.index });
+ }
+ },
+ });
+ if (stop || !result) {
+ parentPort.postMessage({ type: 'aborted', target: msg.target });
+ return;
+ }
+ parentPort.postMessage(
+ {
+ type: 'found',
+ target: msg.target,
+ publicKey: result.publicKey,
+ secretKey: result.secretKey,
+ attempts: result.attempts,
+ durationMs: result.durationMs,
+ },
+ // Transfer the secret-key buffer instead of copying it — one owner at a time.
+ [result.secretKey.buffer],
+ );
+ }
+});
+
+parentPort.postMessage({ type: 'ready' });
diff --git a/workers/vanity-grinder/targets.mjs b/workers/vanity-grinder/targets.mjs
new file mode 100644
index 000000000..51233f365
--- /dev/null
+++ b/workers/vanity-grinder/targets.mjs
@@ -0,0 +1,71 @@
+// The premium-inventory target list — which brandable patterns are worth grinding
+// ahead of time.
+//
+// COMMIT-GATE NOTE: every pattern here is a GENERIC, brand-neutral prefix (product
+// nouns, three.ws-aligned words, human names, aesthetic letter runs). None names a
+// third-party crypto project. `$THREE`-aligned patterns (THREE, WS, 3WS) are
+// welcome; a third-party ticker is NOT. Keep it that way — see CLAUDE.md's commit
+// gate.
+//
+// A target is { prefix?, suffix?, ignoreCase }. Difficulty ≈ 58^(len) case-
+// sensitive, ~33^(len) case-insensitive. The default list is weighted toward 3–4
+// char prefixes (minutes of batch CPU each) with a few 5-char stretch goals.
+
+// Brandable 3-char prefixes — fast to grind, broadly appealing.
+const PREFIX_3 = [
+ 'SOL', 'AiA', 'GM3', 'WS3', 'DEV', 'BOT', 'API', 'GPU', 'LAB', 'ZAP',
+ 'ARC', 'ORB', 'ION', 'NEO', 'VIP', 'ACE', 'FOX', 'OWL', 'JET', 'RAY',
+];
+
+// Brandable 4-char prefixes — the premium sweet spot (unreachable by the live
+// ≤3-char grind tier, so this is what makes the inventory worth selling).
+const PREFIX_4 = [
+ 'PUMP', 'AGNT', 'MOON', 'MINT', 'FORG', 'DEGN', 'GOLD', 'NODE', 'DASH',
+ 'ECHO', 'FLUX', 'HALO', 'IRIS', 'JADE', 'KILO', 'LUNA', 'NOVA', 'ONYX',
+ 'THRE', 'WS3D', 'VOID', 'ZERO', 'BASE', 'CORE',
+];
+
+// 5-char stretch goals — hours of single-thread CPU, trivial on a wide spot MIG.
+// Kept short so a modest batch still completes them; expand on bigger runs.
+const PREFIX_5 = ['THREE', 'AGENT', 'SOLAN', 'HELLO', 'BRAND'];
+
+// Suffix targets — the tail is uniformly distributed (unlike the biased leading
+// char), so these are cleaner to grind. `pump`-suffix addresses are consumable as
+// pump.fun mints where the launcher accepts a supplied keypair at runtime.
+const SUFFIX = [
+ { suffix: 'ws', ignoreCase: true },
+ { suffix: '3', ignoreCase: false },
+ { suffix: 'x', ignoreCase: false },
+];
+
+/**
+ * Build the default target list.
+ * @param {object} [opts]
+ * @param {boolean} [opts.include5=false] - include the slow 5-char stretch goals.
+ * @param {boolean} [opts.ignoreCase=false] - fold case on the prefix targets (≈half difficulty/char).
+ * @returns {Array<{prefix?:string, suffix?:string, ignoreCase:boolean, label:string}>}
+ */
+export function defaultTargets(opts = {}) {
+ const { include5 = false, ignoreCase = false } = opts;
+ const out = [];
+ const push = (t) => out.push({ ignoreCase: !!t.ignoreCase, ...t, label: labelFor(t) });
+
+ for (const p of PREFIX_3) push({ prefix: p, ignoreCase });
+ for (const p of PREFIX_4) push({ prefix: p, ignoreCase });
+ if (include5) for (const p of PREFIX_5) push({ prefix: p, ignoreCase });
+ for (const s of SUFFIX) push(s);
+ return out;
+}
+
+/** Human label for a target, e.g. "PUMP…" or "…ws". */
+export function labelFor(t) {
+ if (t.prefix && t.suffix) return `${t.prefix}…${t.suffix}`;
+ if (t.prefix) return `${t.prefix}…`;
+ if (t.suffix) return `…${t.suffix}`;
+ return '(any)';
+}
+
+/** Stable id for a target (for the checkpoint dedup key). */
+export function targetId(t) {
+ return `${t.prefix || ''}|${t.suffix || ''}|${t.ignoreCase ? 'i' : 'c'}`;
+}
diff --git a/workers/vanity-grinder/wasm-grind.mjs b/workers/vanity-grinder/wasm-grind.mjs
new file mode 100644
index 000000000..22d10d62f
--- /dev/null
+++ b/workers/vanity-grinder/wasm-grind.mjs
@@ -0,0 +1,70 @@
+// Self-contained WASM grind loop for the batch grinder container.
+//
+// Loads the same Rust/ed25519-dalek WASM engine the serverless grinder uses
+// (src/solana/vanity/wasm), but grinds a target to COMPLETION (no wall-clock
+// budget) — batch CPU has all the time it needs. First match wins; the caller
+// (grind-worker.mjs, running in a worker_thread) posts the found keypair back to
+// the main thread, which seals it before any write.
+//
+// The .wasm ships in the image next to this file (see Dockerfile COPY).
+
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+import { initSync, grind } from './wasm/vanity_grinder.js';
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+
+// Keypairs per WASM call. Big enough that per-call overhead is negligible, small
+// enough that a SIGTERM (spot preemption) is observed within a fraction of a
+// second between batches.
+const BATCH_SIZE = 25_000;
+
+let ready = false;
+function ensureWasm() {
+ if (ready) return;
+ const bytes = readFileSync(join(HERE, 'wasm', 'vanity_grinder_bg.wasm'));
+ initSync({ module: bytes });
+ ready = true;
+}
+
+/**
+ * Grind one target to completion.
+ *
+ * @param {object} target
+ * @param {string} [target.prefix]
+ * @param {string} [target.suffix]
+ * @param {boolean} [target.ignoreCase]
+ * @param {object} [opts]
+ * @param {() => boolean} [opts.stopRequested] - return true to abort (preemption).
+ * @param {(attempts:number)=>void} [opts.onProgress] - called each batch.
+ * @returns {{ publicKey:string, secretKey:Uint8Array, attempts:number, durationMs:number } | null}
+ * null only if aborted before a match.
+ */
+export function grindToCompletion(target, opts = {}) {
+ ensureWasm();
+ const prefix = target.prefix || '';
+ const suffix = target.suffix || '';
+ const ignoreCase = !!target.ignoreCase;
+ const { stopRequested, onProgress } = opts;
+
+ const seed = new Uint8Array(32);
+ const startedAt = performance.now();
+ let attempts = 0;
+
+ for (;;) {
+ if (stopRequested && stopRequested()) return null;
+ crypto.getRandomValues(seed);
+ const hit = grind(prefix, suffix, ignoreCase, BATCH_SIZE, seed);
+ attempts += BATCH_SIZE;
+ if (onProgress) onProgress(attempts);
+ if (hit) {
+ return {
+ publicKey: hit.publicKey,
+ secretKey: Uint8Array.from(hit.secretKey),
+ attempts,
+ durationMs: performance.now() - startedAt,
+ };
+ }
+ }
+}