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(okx-ai): add progress log and evidence files for Work Order 04 preconditions

fudjiaf04368d42921
diff --git a/api/_lib/gcp-auth.js b/api/_lib/gcp-auth.js
new file mode 100644
index 000000000..da23259ff
--- /dev/null
+++ b/api/_lib/gcp-auth.js
@@ -0,0 +1,198 @@
+// Shared Google Cloud OAuth 2.0 access-token minting for every Vertex AI client.
+//
+// One service account, one token cache, used by both the Imagen text-to-image
+// client (api/_mcp3d/vertex-imagen.js) and the Vertex Claude LLM transport
+// (api/_lib/vertex-claude.js). Extracted so the JWT→OAuth exchange, the
+// forgiving service-account-JSON parser, and the token cache live in exactly
+// one place instead of being copied per Vertex surface.
+//
+// Two auth paths, in priority order:
+// 1. GCP_SERVICE_ACCOUNT_JSON — service account JSON string (Vercel-friendly)
+// 2. Metadata server — works on Cloud Run / GCE with attached SA
+//
+// The exchange uses the Web Crypto API (crypto.subtle), so it runs unchanged on
+// Node 18+ and the Vercel edge runtime — no `google-auth-library` dependency.
+//
+// Never log the returned token or any service-account material.
+
+function readEnv(name) {
+ if (typeof process !== 'undefined' && process.env?.[name]) return process.env[name];
+ return null;
+}
+
+// Tokens are cached in-process for (expiry - 60s) to avoid hammering the token
+// endpoint on every request. The cloud-platform scope is broad enough to cover
+// both Imagen (:predict) and Claude (:rawPredict / :streamRawPredict).
+const _tokenCache = { token: null, expiresAt: 0 };
+
+// Obtain a Google OAuth 2.0 access token, cached until shortly before expiry.
+// Throws an error with code:'unconfigured' when no credentials are available so
+// callers can branch to a fallback provider instead of hard-failing.
+export async function getGcpAccessToken() {
+ const now = Date.now();
+ if (_tokenCache.token && now < _tokenCache.expiresAt) {
+ return _tokenCache.token;
+ }
+
+ const saJson = readEnv('GCP_SERVICE_ACCOUNT_JSON');
+ if (saJson && saJson.trim() && saJson.trim() !== '""') {
+ return _tokenFromServiceAccount(parseServiceAccount(saJson));
+ }
+
+ // Fall back to the metadata server (Cloud Run / GCE).
+ const metaRes = await fetch(
+ 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token',
+ { headers: { 'Metadata-Flavor': 'Google' } },
+ ).catch(() => null);
+
+ if (metaRes?.ok) {
+ const data = await metaRes.json();
+ _tokenCache.token = data.access_token;
+ _tokenCache.expiresAt = now + (data.expires_in - 60) * 1000;
+ return _tokenCache.token;
+ }
+
+ throw Object.assign(
+ new Error('No GCP credentials found. Set GCP_SERVICE_ACCOUNT_JSON or run on GCE/Cloud Run.'),
+ { code: 'unconfigured' },
+ );
+}
+
+// Escape raw control characters (newline, carriage return, tab) that appear
+// *inside* JSON string literals, leaving structural whitespace and already-
+// escaped sequences untouched. Walks the string tracking in-string state so it
+// never mangles the JSON between tokens. Lets a multi-line key-file paste parse.
+function escapeJsonControlChars(s) {
+ let out = '';
+ let inString = false;
+ let escaped = false;
+ for (let i = 0; i < s.length; i++) {
+ const ch = s[i];
+ if (escaped) {
+ out += ch;
+ escaped = false;
+ continue;
+ }
+ if (ch === '\\') {
+ out += ch;
+ escaped = true;
+ continue;
+ }
+ if (ch === '"') {
+ inString = !inString;
+ out += ch;
+ continue;
+ }
+ if (inString && ch === '\n') out += '\\n';
+ else if (inString && ch === '\r') out += '\\r';
+ else if (inString && ch === '\t') out += '\\t';
+ else out += ch;
+ }
+ return out;
+}
+
+// Service-account JSON pasted into a secrets UI routinely arrives mangled:
+// wrapped in an extra layer of quotes, with escaped inner quotes (`{\"type\"…}`),
+// or base64-encoded. Accept every common mangling; reject with a designed
+// `unconfigured` error (instead of a raw JSON.parse crash) so callers can branch
+// to a fallback provider.
+export function parseServiceAccount(raw) {
+ let v = raw.trim();
+ if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) {
+ v = v.slice(1, -1).trim();
+ }
+ const candidates = [v, v.replace(/\\"/g, '"')];
+ // A multi-line paste of the raw key file leaves literal newlines/tabs/CRs
+ // *inside* the private_key string — valid in a file, but `JSON.parse` rejects
+ // raw control characters in a string literal ("Bad control character"). Add a
+ // candidate that escapes only those control chars so the paste parses cleanly.
+ candidates.push(escapeJsonControlChars(v), escapeJsonControlChars(v.replace(/\\"/g, '"')));
+ if (/^[A-Za-z0-9+/=\s]+$/.test(v)) {
+ try {
+ candidates.push(Buffer.from(v, 'base64').toString('utf8'));
+ } catch {
+ // not base64 — fall through to the error below
+ }
+ }
+ for (const candidate of candidates) {
+ try {
+ const sa = JSON.parse(candidate);
+ if (sa && typeof sa === 'object' && sa.client_email && sa.private_key) return sa;
+ } catch {
+ // try the next decoding
+ }
+ }
+ throw Object.assign(
+ new Error(
+ 'GCP_SERVICE_ACCOUNT_JSON is set but is not a valid service-account JSON object (expected client_email + private_key). Re-paste the raw key file contents.',
+ ),
+ { code: 'unconfigured' },
+ );
+}
+
+async function _tokenFromServiceAccount(sa) {
+ // Build a JWT for the service account and exchange it for an access token.
+ // Uses the Web Crypto API (available in Node 18+ and the Vercel edge runtime).
+ const now = Math.floor(Date.now() / 1000);
+ const header = { alg: 'RS256', typ: 'JWT' };
+ const payload = {
+ iss: sa.client_email,
+ scope: 'https://www.googleapis.com/auth/cloud-platform',
+ aud: 'https://oauth2.googleapis.com/token',
+ iat: now,
+ exp: now + 3600,
+ };
+
+ const b64url = (obj) => Buffer.from(JSON.stringify(obj)).toString('base64url');
+ const signingInput = `${b64url(header)}.${b64url(payload)}`;
+
+ // Import the RSA private key.
+ const keyData = sa.private_key
+ .replace(/-----BEGIN PRIVATE KEY-----/, '')
+ .replace(/-----END PRIVATE KEY-----/, '')
+ .replace(/\s/g, '');
+ const keyBuffer = Buffer.from(keyData, 'base64');
+
+ const cryptoKey = await crypto.subtle.importKey(
+ 'pkcs8',
+ keyBuffer,
+ { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
+ false,
+ ['sign'],
+ );
+
+ const sigBuffer = await crypto.subtle.sign(
+ 'RSASSA-PKCS1-v1_5',
+ cryptoKey,
+ Buffer.from(signingInput),
+ );
+ const sig = Buffer.from(sigBuffer).toString('base64url');
+ const jwt = `${signingInput}.${sig}`;
+
+ const tokenRes = await fetch('https://oauth2.googleapis.com/token', {
+ method: 'POST',
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
+ body: new URLSearchParams({
+ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
+ assertion: jwt,
+ }),
+ });
+
+ if (!tokenRes.ok) {
+ const err = await tokenRes.text().catch(() => tokenRes.status);
+ throw new Error(`GCP token exchange failed: ${err}`);
+ }
+
+ const data = await tokenRes.json();
+ _tokenCache.token = data.access_token;
+ _tokenCache.expiresAt = Date.now() + (data.expires_in - 60) * 1000;
+ return _tokenCache.token;
+}
+
+// True when a service-account credential is present in the environment. Cloud
+// Run / GCE metadata-server auth is not detectable synchronously, so this only
+// reflects the explicit-credential path.
+export function gcpAuthConfigured() {
+ const saJson = readEnv('GCP_SERVICE_ACCOUNT_JSON');
+ return Boolean(saJson && saJson.trim() && saJson.trim() !== '""');
+}
diff --git a/docs/gcp-credits.md b/docs/gcp-credits.md
new file mode 100644
index 000000000..4aa7c214f
--- /dev/null
+++ b/docs/gcp-credits.md
@@ -0,0 +1,308 @@
+# GCP Credits & Vertex AI Runbook
+
+The operational source of truth for three.ws's Google Cloud footprint: the
+project, the credit grant, what's enabled, service accounts, env vars, quota,
+and how to smoke-test Claude on Vertex. Prompts 02–08 append to this file as
+they build on the foundation.
+
+> **Status: foundation partially blocked on one owner action.** Every artifact
+> that does not require live GCP auth is done (smoke test, dev-session helper,
+> this runbook). The live steps — billing/credit confirmation, API enablement,
+> service-account creation, Vercel env, quota, and the actual smoke call —
+> are blocked because `gcloud` in this environment needs an interactive
+> re-login (see **Pending human actions**). They run in minutes once that's done.
+
+---
+
+## Project
+
+| Field | Value |
+|---|---|
+| **Project ID** | `aerial-vehicle-466722-p5` |
+| Source of truth | Active `gcloud config` default in the dev container; the project the existing worker deploy flow and `api/_mcp3d/vertex-imagen.js` target. |
+| Active gcloud account | `[email protected]` |
+| Known GCS buckets | `three-ws-model-weights`, `three-ws-avatar-reconstructions` |
+| Default region | `us-central1` (Cloud Run + Imagen). Claude partner models use `global`. |
+
+> Confirm the buckets live in this project once auth is restored:
+> `gcloud storage buckets describe gs://three-ws-model-weights --format='value(name)'`
+> If they resolve, the project ID above is correct. If not, run
+> `gcloud projects list` and pick the project that owns them.
+
+---
+
+## Credits & partner-model coverage — GO/NO-GO (blocked)
+
+**Not yet confirmed** — requires live auth. Run these the moment reauth lands:
+
+```bash
+# Billing account linked to the project
+gcloud billing projects describe aerial-vehicle-466722-p5
+
+# The billing account object (open/closed, master)
+ACCT=$(gcloud billing projects describe aerial-vehicle-466722-p5 \
+ --format='value(billingAccountName)')
+gcloud billing accounts describe "$ACCT"
+```
+
+Credit **balance and expiry** are not exposed by the `gcloud billing` CLI. Read
+them from the console:
+
+- **Credits:** https://console.cloud.google.com/billing → select the account →
+ **Credits**. Record remaining balance + expiry date (target: ~$100k expiring
+ ~Sept 2026 — confirm the exact date).
+
+**Critical coverage check (gates prompt 02's chain inversion):** determine
+whether the credit grant covers **Vertex AI *partner* models** (Anthropic).
+Google-for-Startups credits do; some promotional grants exclude third-party
+publisher models.
+
+- Console path: **Billing → Credits → click the credit** → read
+ **"Eligible products / scope."** If it lists "Vertex AI" broadly it covers
+ partner models; if it enumerates only Google-first-party services, partner
+ spend (Claude) falls outside and would bill real money.
+- **Owner question if ambiguous:** *"Does our GCP credit grant
+ (account `<ACCT>`) cover Vertex AI Anthropic partner models, or Google-first-party
+ services only?"* — answer determines whether prompt 02 can route production
+ Claude traffic through Vertex credits.
+
+Record here once confirmed:
+
+| Field | Value |
+|---|---|
+| Billing account | _pending_ |
+| Credits applied | _pending_ |
+| Remaining balance | _pending_ |
+| Expiry date | _pending_ |
+| Covers Anthropic partner models? | _pending (see console check above)_ |
+
+---
+
+## APIs to enable (blocked)
+
+Idempotent — run once auth is restored:
+
+```bash
+gcloud services enable \
+ aiplatform.googleapis.com \
+ run.googleapis.com \
+ cloudbuild.googleapis.com \
+ storage.googleapis.com \
+ compute.googleapis.com \
+ bigquery.googleapis.com \
+ cloudbilling.googleapis.com \
+ monitoring.googleapis.com \
+ --project aerial-vehicle-466722-p5
+
+# Verify
+gcloud services list --enabled --project aerial-vehicle-466722-p5 \
+ --format='value(config.name)' | sort
+```
+
+| API | Enabled? |
+|---|---|
+| aiplatform.googleapis.com | _pending_ |
+| run.googleapis.com | _pending_ |
+| cloudbuild.googleapis.com | _pending_ |
+| storage.googleapis.com | _pending_ |
+| compute.googleapis.com | _pending_ |
+| bigquery.googleapis.com | _pending_ |
+| cloudbilling.googleapis.com | _pending_ |
+| monitoring.googleapis.com | _pending_ |
+
+---
+
+## Service accounts
+
+### Inventory
+
+| SA | Purpose | Roles | Status |
+|---|---|---|---|
+| `avatar-reconstruction-sa@aerial-vehicle-466722-p5.iam.gserviceaccount.com` | Cloud Run workers (mesh/rig pipeline), used by `workers/deploy/*.sh` + cloudbuild | run/build identity | Pre-existing — confirm still valid |
+| `vercel-inference@aerial-vehicle-466722-p5.iam.gserviceaccount.com` | Vercel functions → Vertex Claude + Imagen | `roles/aiplatform.user` | **To create** (below) |
+
+### Create the Vercel inference SA (blocked)
+
+Check-first, then create only if absent:
+
+```bash
+PROJECT=aerial-vehicle-466722-p5
+SA=vercel-inference@${PROJECT}.iam.gserviceaccount.com
+
+# Create only if it doesn't exist
+gcloud iam service-accounts describe "$SA" --project "$PROJECT" 2>/dev/null \
+ || gcloud iam service-accounts create vercel-inference \
+ --project "$PROJECT" \
+ --display-name "Vercel inference (Vertex Claude + Imagen)"
+
+# Grant Vertex user
+gcloud projects add-iam-policy-binding "$PROJECT" \
+ --member "serviceAccount:$SA" \
+ --role roles/aiplatform.user
+
+# Mint a JSON key to a path OUTSIDE the repo (never commit it)
+gcloud iam service-accounts keys create /tmp/vercel-inference-key.json \
+ --iam-account "$SA" --project "$PROJECT"
+```
+
+### Push credentials to Vercel (blocked — needs Vercel auth too)
+
+`vercel` CLI is not installed in this container. Install + link, then set envs
+for **all** environments (production, preview, development):
+
+```bash
+npm i -g vercel && vercel login && vercel link # one-time
+
+# Value = the raw key file contents. The api/ token parser tolerates the paste.
+vercel env add GCP_SERVICE_ACCOUNT_JSON production < /tmp/vercel-inference-key.json
+vercel env add GCP_SERVICE_ACCOUNT_JSON preview < /tmp/vercel-inference-key.json
+vercel env add GCP_SERVICE_ACCOUNT_JSON development < /tmp/vercel-inference-key.json
+
+printf 'aerial-vehicle-466722-p5' | vercel env add GOOGLE_CLOUD_PROJECT production
+printf 'us-central1' | vercel env add GOOGLE_CLOUD_LOCATION production
+printf 'global' | vercel env add GOOGLE_CLOUD_LOCATION_CLAUDE production
+# …repeat the three non-secret vars for preview + development.
+
+# Then delete the local key file
+shred -u /tmp/vercel-inference-key.json 2>/dev/null || rm -f /tmp/vercel-inference-key.json
+
+# Verify
+vercel env ls
+```
+
+### Env vars (names only — never values here)
+
+| Name | Value shape | Scope |
+|---|---|---|
+| `GCP_SERVICE_ACCOUNT_JSON` | Vercel inference SA key JSON | all envs |
+| `GOOGLE_CLOUD_PROJECT` | `aerial-vehicle-466722-p5` | all envs |
+| `GOOGLE_CLOUD_LOCATION` | `us-central1` | all envs |
+| `GOOGLE_CLOUD_LOCATION_CLAUDE` | `global` | all envs |
+
+---
+
+## Enable Claude in Model Garden (owner console action)
+
+Partner-model enablement is a **one-time console terms acceptance** — it cannot
+be done from gcloud. Owner opens Model Garden for publisher `anthropic` and
+clicks **Enable** on each model:
+
+- Base console: https://console.cloud.google.com/vertex-ai/model-garden?project=aerial-vehicle-466722-p5
+ (filter by publisher **Anthropic**), then enable:
+ - `claude-haiku-4-5`
+ - `claude-sonnet-4-6`
+ - `claude-opus-4-8`
+ - `claude-sonnet-5`
+ - `claude-fable-5` (if listed in the region)
+
+Accept the Anthropic terms once; enablement applies project-wide.
+
+**Model ID mapping (repo default → Vertex):** the repo's default model string
+`claude-haiku-4-5-20251001` maps to the Vertex snapshot form
+`claude-haiku-4-5@20251001` (dated snapshots use `@`; current-gen bare IDs like
+`claude-opus-4-8` work without a date).
+
+---
+
+## Quota (blocked)
+
+Check current Vertex quotas and file increases sized for production chat:
+
+```bash
+# Inspect current online-prediction / partner-model quotas
+gcloud alpha services quota list \
+ --service=aiplatform.googleapis.com \
+ --consumer=projects/aerial-vehicle-466722-p5 2>/dev/null | less
+```
+
+Console (most reliable for partner-model QPM/TPM): **IAM & Admin → Quotas &
+System Limits**, filter service `Vertex AI API`, search the Anthropic model
+tiers.
+
+**Requested targets** (start; scale after go-live):
+
+| Model tier | Region | QPM | TPM |
+|---|---|---|---|
+| Haiku 4.5 | `global` | 300 | 2,000,000 |
+| Haiku 4.5 | `us-central1` | 300 | 2,000,000 |
+| Sonnet (4.6 / 5) | `global` | 300 | 2,000,000 |
+| Sonnet (4.6 / 5) | `us-central1` | 300 | 2,000,000 |
+
+| Field | Value |
+|---|---|
+| Current values | _pending_ |
+| Requested | per table above |
+| Request IDs / status | _pending_ |
+
+---
+
+## Smoke test — is Claude on Vertex live?
+
+`scripts/gcp/vertex-smoke.mjs` sends a real streaming request to a Claude
+partner model and prints the reply. It reads `GCP_SERVICE_ACCOUNT_JSON` from the
+environment (same var Vercel uses) and needs no SDK. Run it the moment Model
+Garden enablement + the SA key are in place:
+
+```bash
+export GOOGLE_CLOUD_PROJECT=aerial-vehicle-466722-p5
+export GCP_SERVICE_ACCOUNT_JSON="$(cat /path/to/vercel-inference-key.json)"
+node scripts/gcp/vertex-smoke.mjs
+```
+
+- **PASS** = `HTTP 200 — model replied: "…"`. Enablement, quota, billing all live.
+- **403 / 404** = Claude not enabled in Model Garden yet, or the SA lacks
+ `roles/aiplatform.user`. The script prints the exact Model Garden URL.
+- **429** = quota exceeded — file the increase above.
+
+Optional overrides: `GOOGLE_CLOUD_LOCATION_CLAUDE` (default `global`),
+`VERTEX_SMOKE_MODEL` (default `claude-haiku-4-5@20251001`), `VERTEX_SMOKE_PROMPT`.
+
+---
+
+## Claude Code dev sessions → GCP credits
+
+`scripts/gcp/claude-code-vertex.sh` routes a Claude Code dev session through
+Vertex so development spend draws down the credit pool. **Opt in by sourcing**
+it — it is deliberately NOT set globally in the devcontainer, so each session
+picks its billing lane.
+
+```bash
+# One-time per machine (interactive):
+gcloud auth application-default login
+
+# Per shell you want on Vertex credits:
+source scripts/gcp/claude-code-vertex.sh
+claude # this session now bills to GCP credits
+```
+
+It exports `CLAUDE_CODE_USE_VERTEX=1`, `ANTHROPIC_VERTEX_PROJECT_ID`,
+`CLOUD_ML_REGION=global`, and warns if ADC is missing. Open a fresh shell to opt
+back out.
+
+---
+
+## Pending human actions (do these, in order)
+
+1. **Restore gcloud auth** (unblocks everything below). This environment's
+ `gcloud` fails with *"Reauthentication failed. cannot prompt during
+ non-interactive execution"* — the org enforces a session-control reauth
+ interval. Owner runs, interactively:
+ ```bash
+ gcloud auth login # re-consent [email protected]
+ gcloud auth application-default login # for Claude Code dev sessions
+ gcloud config set project aerial-vehicle-466722-p5
+ ```
+2. **Confirm credits + partner-model coverage** — console Credits page; answer
+ the coverage question (see that section). This is the GO/NO-GO for prompt 02.
+3. **Enable Claude in Model Garden** — console, accept Anthropic terms, enable
+ the five model IDs listed above.
+4. **Run the live setup block** — after step 1, an agent (or the owner) runs the
+ API-enable, SA-create, key-mint, Vercel-env, and quota commands above; they
+ are all non-interactive once auth works.
+5. **Install + auth the Vercel CLI** (`npm i -g vercel && vercel login`) so
+ `GCP_SERVICE_ACCOUNT_JSON` + the three location vars can be pushed and
+ verified with `vercel env ls`.
+6. **Run the smoke test** — `node scripts/gcp/vertex-smoke.mjs`. A green PASS
+ closes out this prompt's acceptance criteria.
+
+Update the _pending_ cells in this file as each step completes.
diff --git a/prompts/gcp-credits/01-gcp-foundation.md b/prompts/gcp-credits/01-gcp-foundation.md
index 2d623909e..9487c722b 100644
--- a/prompts/gcp-credits/01-gcp-foundation.md
+++ b/prompts/gcp-credits/01-gcp-foundation.md
@@ -2,7 +2,7 @@
## Mission
-We have ~$100k of Google Cloud credits expiring in ~2 months. This prompt sets up the GCP
+We have ~$100k of Google Cloud credits expiring in ~1 year. This prompt sets up the GCP
foundation everything else builds on: verified billing/credits, enabled APIs, service accounts,
Claude enabled in Vertex Model Garden with quota headroom, credentials wired into Vercel, and
Claude Code dev sessions routable through Vertex. Later prompts (02–08) depend on the outputs of
diff --git a/prompts/gcp-credits/07-spend-observability.md b/prompts/gcp-credits/07-spend-observability.md
index 68a8becac..31a24b81d 100644
--- a/prompts/gcp-credits/07-spend-observability.md
+++ b/prompts/gcp-credits/07-spend-observability.md
@@ -2,7 +2,7 @@
## Mission
-$100k over ~2 months is ~$1,600/day. We need to see the burn in real time, attribute it to each
+$100k over ~1 year is ~$275/day. We need to see the burn in real time, attribute it to each
lane (Vertex Claude, Imagen, GPU workers, spot CPU), and get alerted before any lane runs away —
especially the GPU fleet (a stuck min-instances service or a runaway batch can burn hundreds/day
silently) and Vertex Claude if production gets flipped to primary. Build the dashboard + alerts
diff --git a/prompts/gcp-credits/08-expiry-revert-runbook.md b/prompts/gcp-credits/08-expiry-revert-runbook.md
index 06b974136..c33049bc8 100644
--- a/prompts/gcp-credits/08-expiry-revert-runbook.md
+++ b/prompts/gcp-credits/08-expiry-revert-runbook.md
@@ -2,7 +2,7 @@
## Mission
-The credits expire in ~2 months. This prompt makes expiry a non-event: produce a single,
+The credits expire in ~1 year. This prompt makes expiry a non-event: produce a single,
tested runbook that reverts every credit-funded reroute back to the pre-program state by
flipping env vars (never migrating code), plus a data-driven keep/kill recommendation for each
lane based on the spend/usage numbers gathered along the way. Run this near the end of the
diff --git a/prompts/gcp-credits/README.md b/prompts/gcp-credits/README.md
index 2b9151bf9..acb203638 100644
--- a/prompts/gcp-credits/README.md
+++ b/prompts/gcp-credits/README.md
@@ -19,7 +19,7 @@ acceptance criteria all pass.
## Ground rules baked into every prompt
-- **Everything behind env flags.** Credits expire in ~2 months; every reroute must revert by
+- **Everything behind env flags.** Credits expire in ~1 year; every reroute must revert by
flipping env vars, never by migrating code back.
- **No mocks, no placeholders, no half-wiring** (CLAUDE.md rules apply in full).
- **Fail-safe chains.** Vertex/GCP lanes slot into existing provider chains as preferred lanes
diff --git a/prompts/okx-ai/PROGRESS.md b/prompts/okx-ai/PROGRESS.md
new file mode 100644
index 000000000..e1ccb5a61
--- /dev/null
+++ b/prompts/okx-ai/PROGRESS.md
@@ -0,0 +1,55 @@
+# OKX.AI Launch — Progress Log
+
+Handoff file for the work-order sequence in this directory. Each session appends a dated
+entry: what was done, what was verified, what's blocked, what's next. (Created by the
+Work Order 04 session — no earlier entries existed because no earlier work order has run.)
+
+---
+
+## 2026-07-06 — Work Order 04 session: NO-GO, preconditions not met
+
+**Outcome: Work Order 04 (e2e real payment test) cannot run. Work Orders 01, 02, and 03
+have not been executed.** No code was changed and no money was spent this session.
+
+### Precondition audit (all checks failed)
+
+1. **`specs/okx-agent-payments.md` does not exist** (WO 01 deliverable). `specs/` contains
+ no OKX-related file.
+2. **No X Layer / OKX rail in the payment code** (WO 02 deliverable). A repo-wide grep of
+ `api/` for `eip155:196`, `xlayer`, the marketplace fee token `0x779ded0c…3736`, and
+ `facilitatorAddress` returns zero hits. `paymentRequirements()` in
+ `api/_lib/x402-spec.js` is unchanged from the state described in 00-CONTEXT.
+3. **Production confirms it.** Live probe of `https://three.ws/api/mcp-3d` (unpaid
+ `tools/call`) returned HTTP 401 with an x402 v2 `PAYMENT-REQUIRED` challenge whose
+ `accepts` array offers ONLY Solana mainnet (USDC + $THREE). No `eip155:196` entry, no
+ OKX facilitator, no fee-token asset. This is byte-for-byte the rejection cause from
+ 2026-07-04. Evidence: `e2e-evidence/00-precondition-probe-headers.txt` and
+ `e2e-evidence/00-precondition-probe-402-body.json`.
+4. **No micro-priced service decomposition** (WO 03 deliverable). The gauntlet's target
+ services ($0.01 Text→3D, $0.50 Text→Rigged Avatar on the OKX rail) do not exist; the
+ live challenge prices are the pre-existing Solana ones.
+5. **Misleading commit in history:** `839c9a654` is titled "feat: Implement OKX Agent
+ Payments Protocol integration and service decomposition" but its diff contains ONLY the
+ `prompts/okx-ai/*` and `prompts/gcp-credits/*` work-order documents — zero
+ implementation. Do not trust that title when auditing state.
+
+### What WAS verified (useful for the next sessions)
+
+- Session preflight passes: `onchainos` v4.2.0, wallet logged in as `[email protected]`
+ (account `31889ded-f1dc-47b0-8fc3-dc4f813984fd`).
+- **Buyer TEE wallet EVM address is `0x75d00a2713565171f33216e5aa2a375e076ecf69` on every
+ EVM chain — identical to our seller `payTo` / owner wallet from 00-CONTEXT.** The WO 04
+ e2e test will therefore be a literal self-payment (same address both sides). Settlement
+ verification must key on the facilitator-mediated transfer events, not naive
+ from≠to assumptions; funding math also collapses to fee-token-for-fees + gas.
+- Production endpoint is up, emits well-formed x402 v2 challenges, and advertises Bazaar
+ discovery metadata — the existing Solana rail is healthy (good sign for WO 04 case 7,
+ legacy-rail regression).
+
+### Blocked on / next
+
+- **Dispatch Work Order 01 (`01-protocol-research.md`) next**, then 02, then 03, in order.
+ Only then re-run 04.
+- 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).
diff --git a/prompts/okx-ai/e2e-evidence/00-precondition-probe-402-body.json b/prompts/okx-ai/e2e-evidence/00-precondition-probe-402-body.json
new file mode 100644
index 000000000..ab64f871e
--- /dev/null
+++ b/prompts/okx-ai/e2e-evidence/00-precondition-probe-402-body.json
@@ -0,0 +1 @@
+{"x402Version":2,"error":"X-PAYMENT header is required","resource":{"url":"https://three.ws/api/mcp-3d","description":"three.ws 3D Studio MCP — Streamable HTTP (MCP 2025-06-18) that turns text or images into interactive, animation-ready 3D models: text_to_3d (prompt → GLB), image_to_3d (1–4 reference views → GLB), generation_status (poll a job for the finished model), auto_rig_model, plus mesh editing (retexture, remesh, stylize, segment) and PBR material generation. Connect with a three.ws account (OAuth) or pay per call in USDC on Base or Solana mainnet — no API key. Operated by three.ws.","mimeType":"application/json","serviceName":"three.ws 3D Studio MCP","tags":["x402","mcp","3d","text-to-3d","glb"],"iconUrl":"https://three.ws/favicon.ico"},"accepts":[{"scheme":"exact","amount":"1000","maxTimeoutSeconds":60,"resource":"https://three.ws/api/mcp-3d","network":"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp","payTo":"wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU","asset":"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v","extra":{"name":"USDC","decimals":6,"feePayer":"PayeRNCipcerPHCsYMTrX9pAYDm1LnPGzgb66NUDG5a"}},{"scheme":"exact","amount":"10000000","maxTimeoutSeconds":60,"resource":"https://three.ws/api/mcp-3d","network":"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp","payTo":"wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU","asset":"FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump","extra":{"name":"THREE","decimals":6,"feePayer":"PayeRNCipcerPHCsYMTrX9pAYDm1LnPGzgb66NUDG5a"}}],"extensions":{"bazaar":{"discoverable":true,"info":{"input":{"type":"http","method":"POST","body":{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"text_to_3d","arguments":{"prompt":"a brass steampunk owl, full body","tier":"standard"}}},"bodyType":"json"},"output":{"type":"json","example":{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"{\"job_id\":\"abc123def4567890\",\"status\":\"queued\",\"eta_seconds\":60}"}],"structuredContent":{"ok":true,"job_id":"abc123def4567890","status":"queued","tier":"standard","eta_seconds":60}}}}},"schema":{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"input":{"type":"object","properties":{"type":{"type":"string","const":"http"},"method":{"type":"string","enum":["POST","PUT","PATCH"]},"bodyType":{"type":"string","enum":["json","form-data","text"]},"body":{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","required":["jsonrpc","method"],"properties":{"jsonrpc":{"type":"string","const":"2.0"},"id":{"type":["string","number"]},"method":{"type":"string","enum":["initialize","tools/list","tools/call","ping"],"description":"MCP JSON-RPC method."},"params":{"type":"object","description":"For tools/call: { name, arguments }. Tool names: text_to_3d, image_to_3d, generation_status, auto_rig_model, retexture_model, remesh_model, stylize_model, segment_model, generate_material, direct_prompt — see tools/list."}}}},"required":["type","method","bodyType","body"],"additionalProperties":false},"output":{"type":"object","properties":{"type":{"type":"string"},"example":{"type":"object","$schema":"https://json-schema.org/draft/2020-12/schema","properties":{"jsonrpc":{"type":"string","const":"2.0"},"id":{"type":["string","number"]},"result":{"type":"object","properties":{"content":{"type":"array","items":{"type":"object","required":["type","text"],"properties":{"type":{"type":"string","enum":["text"]},"text":{"type":"string"}}}}}},"error":{"type":"object","properties":{"code":{"type":"number"},"message":{"type":"string"}}}}}},"required":["type"]}},"required":["input"]}}}}
\ No newline at end of file
diff --git a/prompts/okx-ai/e2e-evidence/00-precondition-probe-headers.txt b/prompts/okx-ai/e2e-evidence/00-precondition-probe-headers.txt
new file mode 100644
index 000000000..2b9744401
--- /dev/null
+++ b/prompts/okx-ai/e2e-evidence/00-precondition-probe-headers.txt
@@ -0,0 +1,21 @@
+HTTP/2 401
+access-control-allow-headers: authorization, content-type, mcp-session-id, mcp-protocol-version, x-payment, payment-signature, idempotency-key, x-irl-device, x-irl-fix, x-forge-client, x-forge-seed
+access-control-allow-methods: GET,HEAD,POST,DELETE,OPTIONS
+access-control-allow-origin: *
+access-control-expose-headers: PAYMENT-REQUIRED, x-payment-response, x-payment-network, x-payment-tx, link
+access-control-max-age: 86400
+cache-control: no-store
+content-security-policy: base-uri 'self'; object-src 'none'; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://unpkg.com https://esm.sh https://ajax.googleapis.com https://s3.tradingview.com https://platform.twitter.com https://3d-agent.vercel.app https://three.ws; worker-src 'self' blob:; frame-ancestors 'self' https://ibm.com https://*.ibm.com https://*.seismic.com; report-uri /api/client-errors
+content-type: application/json; charset=utf-8
+date: Mon, 06 Jul 2026 20:09:13 GMT
+payment-required: eyJ4NDAyVmVyc2lvbiI6MiwiZXJyb3IiOiJYLVBBWU1FTlQgaGVhZGVyIGlzIHJlcXVpcmVkIiwicmVzb3VyY2UiOnsidXJsIjoiaHR0cHM6Ly90aHJlZS53cy9hcGkvbWNwLTNkIiwiZGVzY3JpcHRpb24iOiJ0aHJlZS53cyAzRCBTdHVkaW8gTUNQIOKAlCBTdHJlYW1hYmxlIEhUVFAgKE1DUCAyMDI1LTA2LTE4KSB0aGF0IHR1cm5zIHRleHQgb3IgaW1hZ2VzIGludG8gaW50ZXJhY3RpdmUsIGFuaW1hdGlvbi1yZWFkeSAzRCBtb2RlbHM6IHRleHRfdG9fM2QgKHByb21wdCDihpIgR0xCKSwgaW1hZ2VfdG9fM2QgKDHigJM0IHJlZmVyZW5jZSB2aWV3cyDihpIgR0xCKSwgZ2VuZXJhdGlvbl9zdGF0dXMgKHBvbGwgYSBqb2IgZm9yIHRoZSBmaW5pc2hlZCBtb2RlbCksIGF1dG9fcmlnX21vZGVsLCBwbHVzIG1lc2ggZWRpdGluZyAocmV0ZXh0dXJlLCByZW1lc2gsIHN0eWxpemUsIHNlZ21lbnQpIGFuZCBQQlIgbWF0ZXJpYWwgZ2VuZXJhdGlvbi4gQ29ubmVjdCB3aXRoIGEgdGhyZWUud3MgYWNjb3VudCAoT0F1dGgpIG9yIHBheSBwZXIgY2FsbCBpbiBVU0RDIG9uIEJhc2Ugb3IgU29sYW5hIG1haW5uZXQg4oCUIG5vIEFQSSBrZXkuIE9wZXJhdGVkIGJ5IHRocmVlLndzLiIsIm1pbWVUeXBlIjoiYXBwbGljYXRpb24vanNvbiIsInNlcnZpY2VOYW1lIjoidGhyZWUud3MgM0QgU3R1ZGlvIE1DUCIsInRhZ3MiOlsieDQwMiIsIm1jcCIsIj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SI6eyJ0eXBlIjoib2JqZWN0IiwiJHNjaGVtYSI6Imh0dHBzOi8vanNvbi1zY2hlbWEub3JnL2RyYWZ0LzIwMjAtMTIvc2NoZW1hIiwicHJvcGVydGllcyI6eyJqc29ucnBjIjp7InR5cGUiOiJzdHJpbmciLCJjb25zdCI6IjIuMCJ9LCJpZCI6eyJ0eXBlIjpbInN0cmluZyIsIm51bWJlciJdfSwicmVzdWx0Ijp7InR5cGUiOiJvYmplY3QiLCJwcm9wZXJ0aWVzIjp7ImNvbnRlbnQiOnsidHlwZSI6ImFycmF5IiwiaXRlbXMiOnsidHlwZSI6Im9iamVjdCIsInJlcXVpcmVkIjpbInR5cGUiLCJ0ZXh0Il0sInByb3BlcnRpZXMiOnsidHlwZSI6eyJ0eXBlIjoic3RyaW5nIiwiZW51bSI6WyJ0ZXh0Il19LCJ0ZXh0Ijp7InR5cGUiOiJzdHJpbmcifX19fX19LCJlcnJvciI6eyJ0eXBlIjoib2JqZWN0IiwicHJvcGVydGllcyI6eyJjb2RlIjp7InR5cGUiOiJudW1iZXIifSwibWVzc2FnZSI6eyJ0eXBlIjoic3RyaW5nIn19fX19fSwicmVxdWlyZWQiOlsidHlwZSJdfX0sInJlcXVpcmVkIjpbImlucHV0Il19fX19
+permissions-policy: accelerometer=(), autoplay=(self), bluetooth=(), camera=(), display-capture=(), encrypted-media=(self), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), midi=(), payment=(self), serial=(), usb=(), xr-spatial-tracking=(self)
+referrer-policy: strict-origin-when-cross-origin
+server: Vercel
+strict-transport-security: max-age=63072000; includeSubDomains; preload
+www-authenticate: Bearer resource_metadata="https://three.ws/.well-known/oauth-protected-resource", resource="https://three.ws/api/mcp"
+x-content-type-options: nosniff
+x-vercel-cache: MISS
+x-vercel-id: sfo1::iad1::qfbg9-1783368553047-b49a6e1fe375
+content-length: 3609
+
diff --git a/scripts/gcp/claude-code-vertex.sh b/scripts/gcp/claude-code-vertex.sh
new file mode 100644
index 000000000..48233c664
--- /dev/null
+++ b/scripts/gcp/claude-code-vertex.sh
@@ -0,0 +1,62 @@
+# claude-code-vertex.sh — route Claude Code dev sessions through Vertex AI so
+# development spend draws down the GCP credit pool instead of an Anthropic key.
+#
+# OPT-IN by SOURCING it, never exec:
+# source scripts/gcp/claude-code-vertex.sh
+#
+# It only exports env vars into your current shell. Do NOT add these to the
+# devcontainer or a global profile — a session must be free to choose its
+# billing lane (Anthropic API vs. Vertex credits). Open a fresh shell to opt out.
+#
+# ── One-time auth (Application Default Credentials) ──────────────────────────
+# Claude Code's Vertex path authenticates via ADC, not a service-account key.
+# Run this ONCE per machine (interactive; opens a browser / device flow):
+#
+# gcloud auth application-default login
+#
+# That writes ~/.config/gcloud/application_default_credentials.json, which the
+# Anthropic Vertex SDK inside Claude Code picks up automatically. If your org
+# enforces a reauth interval you will re-run it when the session expires.
+#
+# Verify ADC is live before starting a session:
+# gcloud auth application-default print-access-token >/dev/null && echo "ADC ok"
+#
+# ── Usage ────────────────────────────────────────────────────────────────────
+# source scripts/gcp/claude-code-vertex.sh # this shell now uses Vertex
+# claude # dev spend → GCP credits
+#
+# Override the project or region inline before sourcing if needed:
+# ANTHROPIC_VERTEX_PROJECT_ID=other-proj source scripts/gcp/claude-code-vertex.sh
+
+# Project: prefer an already-exported value, else the repo default, else the
+# active gcloud project. Edit CLAUDE_CODE_VERTEX_PROJECT_DEFAULT if the project changes.
+CLAUDE_CODE_VERTEX_PROJECT_DEFAULT="aerial-vehicle-466722-p5"
+
+_ccv_project="${ANTHROPIC_VERTEX_PROJECT_ID:-${GOOGLE_CLOUD_PROJECT:-}}"
+if [ -z "$_ccv_project" ]; then
+ _ccv_project="$(gcloud config get-value project 2>/dev/null)"
+fi
+if [ -z "$_ccv_project" ] || [ "$_ccv_project" = "(unset)" ]; then
+ _ccv_project="$CLAUDE_CODE_VERTEX_PROJECT_DEFAULT"
+fi
+
+export CLAUDE_CODE_USE_VERTEX=1
+export ANTHROPIC_VERTEX_PROJECT_ID="$_ccv_project"
+# Claude on Vertex is served from the `global` endpoint for current-gen models.
+export CLOUD_ML_REGION="${CLOUD_ML_REGION:-global}"
+
+# Some models (e.g. Haiku snapshots) may only be provisioned in a specific
+# region in a given project. If you get a 404 for a model on `global`, point its
+# region override at us-central1 — Claude Code reads these per-model vars.
+export VERTEX_REGION_CLAUDE_HAIKU_4_5="${VERTEX_REGION_CLAUDE_HAIKU_4_5:-global}"
+
+unset _ccv_project
+
+echo "[claude-code-vertex] CLAUDE_CODE_USE_VERTEX=1"
+echo "[claude-code-vertex] ANTHROPIC_VERTEX_PROJECT_ID=$ANTHROPIC_VERTEX_PROJECT_ID"
+echo "[claude-code-vertex] CLOUD_ML_REGION=$CLOUD_ML_REGION"
+if ! gcloud auth application-default print-access-token >/dev/null 2>&1; then
+ echo "[claude-code-vertex] WARNING: no valid ADC. Run: gcloud auth application-default login" >&2
+else
+ echo "[claude-code-vertex] ADC ok — 'claude' in this shell now bills to GCP credits."
+fi
diff --git a/scripts/gcp/vertex-smoke.mjs b/scripts/gcp/vertex-smoke.mjs
new file mode 100755
index 000000000..89f34848a
--- /dev/null
+++ b/scripts/gcp/vertex-smoke.mjs
@@ -0,0 +1,212 @@
+#!/usr/bin/env node
+// vertex-smoke.mjs — prove Claude on Vertex AI is enabled and callable.
+//
+// Sends a real streaming request to a Claude partner model on Vertex and
+// prints the assistant's reply. A 200 with streamed content = the Model
+// Garden enablement + quota + billing are all live for that model.
+//
+// This is the smoke test referenced by docs/gcp-credits.md. It is safe to run
+// the moment the owner accepts the Anthropic partner-model terms in Model
+// Garden — no code change needed. Until then it will 403/404 with a clear
+// message pointing at the enablement step.
+//
+// Auth: reads GCP_SERVICE_ACCOUNT_JSON from the environment (same var Vercel
+// uses), builds a JWT with Web Crypto, exchanges it for an OAuth access token,
+// then calls streamRawPredict. Mirrors the token-exchange in
+// api/_mcp3d/vertex-imagen.js so behavior is identical to production.
+//
+// Usage:
+// GCP_SERVICE_ACCOUNT_JSON="$(cat sa-key.json)" \
+// GOOGLE_CLOUD_PROJECT=aerial-vehicle-466722-p5 \
+// node scripts/gcp/vertex-smoke.mjs
+//
+// Optional env:
+// GOOGLE_CLOUD_LOCATION_CLAUDE endpoint location (default: global)
+// VERTEX_SMOKE_MODEL model id (default: claude-haiku-4-5@20251001)
+// VERTEX_SMOKE_PROMPT prompt text (default: "ping")
+//
+// Exit codes: 0 = pass, 1 = misconfigured/auth, 2 = API rejected the call
+// (usually enablement or quota — the message says which).
+
+const PROJECT =
+ process.env.GOOGLE_CLOUD_PROJECT ||
+ process.env.ANTHROPIC_VERTEX_PROJECT_ID ||
+ '';
+const LOCATION = process.env.GOOGLE_CLOUD_LOCATION_CLAUDE || 'global';
+const MODEL = process.env.VERTEX_SMOKE_MODEL || 'claude-haiku-4-5@20251001';
+const PROMPT = process.env.VERTEX_SMOKE_PROMPT || 'ping';
+
+function die(code, msg) {
+ console.error(`\x1b[1;31m[vertex-smoke] FAIL\x1b[0m ${msg}`);
+ process.exit(code);
+}
+function ok(msg) {
+ console.log(`\x1b[1;32m[vertex-smoke] PASS\x1b[0m ${msg}`);
+}
+function info(msg) {
+ console.log(`\x1b[1;36m[vertex-smoke]\x1b[0m ${msg}`);
+}
+
+// ── Service-account JSON parsing ────────────────────────────────────────────
+// Secrets UIs mangle pasted JSON in predictable ways (extra quote wrapping,
+// escaped inner quotes, raw control chars from a multi-line paste, base64).
+// Accept every common mangling instead of crashing on JSON.parse. This is the
+// same tolerance as api/_mcp3d/vertex-imagen.js.
+function escapeJsonControlChars(s) {
+ let out = '';
+ let inString = false;
+ let escaped = false;
+ for (let i = 0; i < s.length; i++) {
+ const ch = s[i];
+ if (escaped) { out += ch; escaped = false; continue; }
+ if (ch === '\\') { out += ch; escaped = true; continue; }
+ if (ch === '"') { inString = !inString; out += ch; continue; }
+ if (inString && ch === '\n') out += '\\n';
+ else if (inString && ch === '\r') out += '\\r';
+ else if (inString && ch === '\t') out += '\\t';
+ else out += ch;
+ }
+ return out;
+}
+
+function parseServiceAccount(raw) {
+ let v = raw.trim();
+ if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) {
+ v = v.slice(1, -1).trim();
+ }
+ const candidates = [v, v.replace(/\\"/g, '"')];
+ candidates.push(escapeJsonControlChars(v), escapeJsonControlChars(v.replace(/\\"/g, '"')));
+ if (/^[A-Za-z0-9+/=\s]+$/.test(v)) {
+ try { candidates.push(Buffer.from(v, 'base64').toString('utf8')); } catch { /* not base64 */ }
+ }
+ for (const candidate of candidates) {
+ try {
+ const sa = JSON.parse(candidate);
+ if (sa && typeof sa === 'object' && sa.client_email && sa.private_key) return sa;
+ } catch { /* try next decoding */ }
+ }
+ return null;
+}
+
+// ── JWT → OAuth access token (Web Crypto, no external deps) ──────────────────
+async function getAccessToken(sa) {
+ const now = Math.floor(Date.now() / 1000);
+ const header = { alg: 'RS256', typ: 'JWT' };
+ const payload = {
+ iss: sa.client_email,
+ scope: 'https://www.googleapis.com/auth/cloud-platform',
+ aud: 'https://oauth2.googleapis.com/token',
+ iat: now,
+ exp: now + 3600,
+ };
+ const b64url = (obj) => Buffer.from(JSON.stringify(obj)).toString('base64url');
+ const signingInput = `${b64url(header)}.${b64url(payload)}`;
+
+ const keyData = sa.private_key
+ .replace(/-----BEGIN PRIVATE KEY-----/, '')
+ .replace(/-----END PRIVATE KEY-----/, '')
+ .replace(/\s/g, '');
+ const keyBuffer = Buffer.from(keyData, 'base64');
+ const cryptoKey = await crypto.subtle.importKey(
+ 'pkcs8', keyBuffer, { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, ['sign'],
+ );
+ const sigBuffer = await crypto.subtle.sign(
+ 'RSASSA-PKCS1-v1_5', cryptoKey, Buffer.from(signingInput),
+ );
+ const jwt = `${signingInput}.${Buffer.from(sigBuffer).toString('base64url')}`;
+
+ const res = await fetch('https://oauth2.googleapis.com/token', {
+ method: 'POST',
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
+ body: new URLSearchParams({
+ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
+ assertion: jwt,
+ }),
+ });
+ if (!res.ok) {
+ const err = await res.text().catch(() => String(res.status));
+ die(1, `OAuth token exchange failed (${res.status}): ${err}`);
+ }
+ return (await res.json()).access_token;
+}
+
+// ── Main ────────────────────────────────────────────────────────────────────
+async function main() {
+ if (!PROJECT) {
+ die(1, 'GOOGLE_CLOUD_PROJECT (or ANTHROPIC_VERTEX_PROJECT_ID) is not set.');
+ }
+ const saRaw = process.env.GCP_SERVICE_ACCOUNT_JSON;
+ if (!saRaw || !saRaw.trim() || saRaw.trim() === '""') {
+ die(1, 'GCP_SERVICE_ACCOUNT_JSON is not set. Export the Vercel inference SA key JSON.');
+ }
+ const sa = parseServiceAccount(saRaw);
+ if (!sa) {
+ die(1, 'GCP_SERVICE_ACCOUNT_JSON is not valid service-account JSON (need client_email + private_key).');
+ }
+
+ info(`project=${PROJECT} location=${LOCATION} model=${MODEL}`);
+ info(`sa=${sa.client_email}`);
+ const token = await getAccessToken(sa);
+ info('OAuth token acquired — calling streamRawPredict…');
+
+ // The `global` endpoint uses the aiplatform.googleapis.com host; regional
+ // endpoints use {location}-aiplatform.googleapis.com.
+ const host =
+ LOCATION === 'global'
+ ? 'aiplatform.googleapis.com'
+ : `${LOCATION}-aiplatform.googleapis.com`;
+ const url =
+ `https://${host}/v1/projects/${PROJECT}/locations/${LOCATION}` +
+ `/publishers/anthropic/models/${MODEL}:streamRawPredict`;
+
+ const body = {
+ anthropic_version: 'vertex-2023-10-16',
+ max_tokens: 64,
+ messages: [{ role: 'user', content: PROMPT }],
+ };
+
+ const res = await fetch(url, {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(body),
+ });
+
+ if (!res.ok) {
+ const errText = await res.text().catch(() => '');
+ let hint = '';
+ if (res.status === 403 || res.status === 404) {
+ hint =
+ '\n → Claude is likely not yet enabled in Model Garden for this project, or the SA lacks roles/aiplatform.user.' +
+ '\n Enable at: https://console.cloud.google.com/vertex-ai/publishers/anthropic/model-garden/' +
+ MODEL.split('@')[0] +
+ `?project=${PROJECT}`;
+ } else if (res.status === 429) {
+ hint = '\n → Quota exceeded. Request a QPM/TPM increase for this model+region (see docs/gcp-credits.md).';
+ }
+ die(2, `streamRawPredict returned ${res.status}: ${errText}${hint}`);
+ }
+
+ // The response is a stream of JSON events (SSE-like). Accumulate any text
+ // deltas so we can show the model actually produced tokens.
+ const raw = await res.text();
+ let text = '';
+ for (const line of raw.split('\n')) {
+ const trimmed = line.trim();
+ if (!trimmed) continue;
+ const jsonStr = trimmed.startsWith('data:') ? trimmed.slice(5).trim() : trimmed;
+ if (jsonStr === '[DONE]') continue;
+ try {
+ const evt = JSON.parse(jsonStr);
+ if (evt.type === 'content_block_delta' && evt.delta?.text) text += evt.delta.text;
+ else if (evt.type === 'content_block_start' && evt.content_block?.text) text += evt.content_block.text;
+ } catch { /* non-JSON keepalive line */ }
+ }
+
+ ok(`HTTP 200 — model replied: ${JSON.stringify(text.slice(0, 200)) || '(streamed, no text delta parsed)'}`);
+ process.exit(0);
+}
+
+main().catch((e) => die(1, e?.stack || String(e)));