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.

chore: sync platform changes — world health, redis usage/migration, llm health, x402-fetch + react packages, pump launchpad tasks

nirholascccb6196e2d3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6bb78faa7..6b5df6a95 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,11 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-06-14
- **Building 3D AI Agents Live** (`/events/build-3d-agents-live`) — A live build session: from a single prompt to an interactive 3D AI agent embedded in any app, in minutes — then a live Q&A. Hosted by three.ws, in partnership with IBM.
+- **Forge stays up: live Redis quota monitoring and early-warning alerts** — The shared rate-limiter store has a hard monthly request ceiling, and when it's exhausted every paid generation and payment stops at once. We've made that failure mode impossible to sneak up on us. The forge health check (/api/forge?health) now reports the live daily request rate, how much of the budget it's burning, and projects whether it's on track to run out — and a daily check pages our ops team the moment the projection crosses 80% of the ceiling, long before anything breaks. We also moved the highest-traffic, lowest-risk traffic guards (public page reads, status polling, the notifications badge) to in-process enforcement so they no longer spend from that budget at all, cutting burn dramatically. Net effect: more headroom, and a deliberate upgrade decision instead of a surprise outage. `[infra]`
+- **pump.fun MCP server only lists tools it can actually run** — The free pump.fun MCP server (three.ws/api/pump-fun-mcp) now advertises its discovery tools — token search, trending, new, graduated, king-of-the-hill, and creator profiles — only when its real-time indexer backend is connected. Previously those six tools always appeared in the tool list and returned an error if the indexer wasn't wired, which confused MCP clients and assistants that tried to call them. They now stay hidden until the backend is live, and reappear automatically the moment it is. We also added a always-available pumpfun_bot_status tool that reports whether the indexer is configured and healthy (with round-trip latency), and an indexerEnabled flag on the server handshake so client authors can check capability in one call. On-chain tools (bonding curve, holders, token details, trades, swap quotes, fee claims) were unaffected and remain fully available with no API key. `[sdk, improvement]`
+- **React component library for embedding 3D AI agents** — npm install @three-ws/react gives you <Agent3D> — a React wrapper around the three.ws walk embed player. Drop a 3D AI agent into any React app in two lines of code, with props for controls, size, and background, plus onLoad/onError callbacks and a ref handle to drive the avatar live. (`/embed/walk`) `[feature, sdk]`
+- **world.three.ws locked down and watched around the clock** — The multiplayer world (world.three.ws) is now protected against unauthorized edits: visitors join as spectators and only a holder of the admin code can build, move, or delete anything in the scene. We also added a continuous health watch. Every 15 minutes a monitor confirms the world is still protected and checks that every asset the scene depends on is actually reachable — the exact gap that briefly dropped visitors into an empty void earlier this month, now caught and paged to our ops team before anyone notices. The forge health surface (/api/forge?health) reports the world's status alongside the generation backends, and a post-deploy gate refuses to call a deploy healthy unless the world comes back protected. `[security, infra]`
+- **x402-fetch — automatic pay-per-call fetch wrapper** — npm install @three-ws/x402-fetch gives you withX402(wallet) — a drop-in fetch wrapper that silently handles x402 payment challenges. Connect a wallet once; call any paid three.ws API like a free one. It signs USDC-on-Base payments locally with zero dependencies, refuses to overspend past a maxPaymentUsd guard you set, and works in the browser (MetaMask), in Node (private key), or with a three.ws agent wallet. (`/docs/sdk`) `[feature, sdk]`
## 2026-06-13
diff --git a/api/_lib/env.js b/api/_lib/env.js
index 78396f993..f273cbf48 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -78,6 +78,26 @@ export const env = {
);
},
+ // ── Upstash quota-burn visibility (api/_lib/redis-usage.js) ──────────────
+ // The free plan ceils at 500k commands/month; when it is exhausted every
+ // critical limiter fails closed and all paid forge + x402 flows 503 (the
+ // June 2026 incident). To read the real daily command count BEFORE the
+ // ceiling we use the Upstash Management API (api.upstash.com), which is a
+ // SEPARATE credential from the per-store REST token above — the REST token
+ // can run commands but cannot read account usage. All three are optional:
+ // when unset, burn reporting degrades to `unknown` and never fabricates a
+ // number. The store id is the only non-secret one, so it carries the known
+ // default for the live `three-ratelimit` store.
+ get UPSTASH_EMAIL() {
+ return opt('UPSTASH_EMAIL');
+ },
+ get UPSTASH_MANAGEMENT_API_KEY() {
+ return opt('UPSTASH_MANAGEMENT_API_KEY') || opt('UPSTASH_API_KEY');
+ },
+ get UPSTASH_REDIS_STORE_ID() {
+ return opt('UPSTASH_REDIS_STORE_ID', 'store_QnjIWaKv4d5MvmA9');
+ },
+
get JWT_SECRET() {
return req('JWT_SECRET');
},
diff --git a/api/_lib/forge-health.js b/api/_lib/forge-health.js
index c1f06d4f1..f1cd9204e 100644
--- a/api/_lib/forge-health.js
+++ b/api/_lib/forge-health.js
@@ -21,6 +21,8 @@
import { BACKENDS, backendIsConfigured } from './forge-tiers.js';
import { env } from './env.js';
+import { getRedisBurn } from './redis-usage.js';
+import { probeLlmHealth } from './llm-health.js';
const PROBE_TIMEOUT_MS = 4_000;
const CACHE_TTL_MS = 60_000;
@@ -176,6 +178,54 @@ async function probeLimiterStore() {
return result(id, 'down', `The rate-limiter store rejected commands (${detail}) — paid generation lanes fail closed.`, { http_status: res.status, latency_ms: latency });
}
+// world.three.ws (Hyperfy multiplayer world) is a separate Cloud Run service,
+// but a forge user who generates an avatar wants to walk it into the world — so
+// the forge health report surfaces the world too. Two real outage modes:
+// unprotected (every visitor can delete the scene) and a missing blueprint
+// asset (the scene crashes on join — the 2026-06-12 void-fall). The patched
+// /status enumerates blueprint assets with absolute URLs; we HEAD a bounded
+// sample so this probe stays as cheap as the others.
+const WORLD_STATUS_URL =
+ (env.WORLD_URL ? env.WORLD_URL.replace(/\/+$/, '') : 'https://world.three.ws') + '/status';
+const WORLD_ASSET_SAMPLE = 12;
+
+async function probeWorld() {
+ const id = 'world';
+ const started = Date.now();
+ const res = await probeFetch(WORLD_STATUS_URL, {
+ headers: { accept: 'application/json', 'user-agent': 'threews-forge-health/1.0' },
+ });
+ const latency = Date.now() - started;
+ if (!res) return result(id, 'down', 'world.three.ws is unreachable.', { latency_ms: latency });
+ if (!res.ok) {
+ return result(id, 'down', `world.three.ws /status returned HTTP ${res.status}.`, { http_status: res.status, latency_ms: latency });
+ }
+ let status = null;
+ try {
+ status = await res.json();
+ } catch {
+ return result(id, 'down', 'world.three.ws /status returned an unparseable body.', { latency_ms: latency });
+ }
+ const isProtected = status?.protected === true;
+ const blueprints = Array.isArray(status?.blueprints) ? status.blueprints : [];
+ const assetUrls = blueprints
+ .map((b) => b?.assetUrl)
+ .filter((u) => typeof u === 'string' && /^https?:\/\//.test(u))
+ .slice(0, WORLD_ASSET_SAMPLE);
+ const heads = await Promise.all(
+ assetUrls.map((u) => probeFetch(u, { method: 'HEAD', redirect: 'follow' })),
+ );
+ const missing = heads.filter((h) => !h || !h.ok).length;
+ const extra = { protected: isProtected, blueprint_count: blueprints.length, latency_ms: latency };
+ if (missing > 0) {
+ return result(id, 'down', `${missing} blueprint asset(s) are missing — the scene will crash on join.`, extra);
+ }
+ if (!isProtected) {
+ return result(id, 'degraded', 'The world is unprotected — ADMIN_CODE is unset, so every visitor has build rights.', extra);
+ }
+ return result(id, 'ok', 'The world is protected and all sampled blueprint assets are present.', extra);
+}
+
let cache = null; // { at: epoch-ms, payload }
// Probe every backend in the registry, in parallel, with per-instance caching.
@@ -184,7 +234,7 @@ export async function probeForgeHealth({ force = false } = {}) {
return { ...cache.payload, cached: true };
}
- const [entries, limiter] = await Promise.all([
+ const [entries, limiter, llm, world, redis] = await Promise.all([
Promise.all(
Object.values(BACKENDS).map(async (b) => {
if (b.byok) return byokResult(b.id);
@@ -200,10 +250,29 @@ export async function probeForgeHealth({ force = false } = {}) {
}),
),
probeLimiterStore(),
+ // LLM providers gate every AI-driven generation surface (prompt rewriting,
+ // agent responses). A dead provider chain degrades the product the same way
+ // a dead 3D backend does, so it folds into the same overall verdict.
+ probeLlmHealth(),
+ // The multiplayer world is downstream of the forge (generate → walk it in),
+ // so a down/unprotected world degrades the overall verdict too.
+ probeWorld(),
+ // Quota-burn reading for the SAME store probeLimiterStore() pings. That
+ // probe answers "is Redis reachable?"; this answers "is Redis about to run
+ // out of quota?" — the slow failure that took the platform down in June
+ // 2026 while every reachability check still read green.
+ getRedisBurn(),
]);
const backends = Object.fromEntries(entries.map((e) => [e.id, e]));
- const statuses = entries.map((e) => e.status).concat(limiter.status);
+ // llm carries an 'ok' | 'degraded' | 'down' overall plus per-provider verdicts.
+ // A down world degrades overall to 'degraded' (never 'down' — the forge still
+ // functions when the world is offline), which the cap below already enforces.
+ // A critical Redis burn rate degrades overall too: it predicts the limiters
+ // failing closed before they actually do, so it warns rather than waits.
+ const statuses = entries
+ .map((e) => e.status)
+ .concat(limiter.status, llm.overall, world.status, redis.status === 'critical' ? 'down' : 'ok');
const overall = statuses.includes('down') || statuses.includes('degraded') ? 'degraded' : 'ok';
const payload = {
@@ -211,6 +280,9 @@ export async function probeForgeHealth({ force = false } = {}) {
generated_at: new Date().toISOString(),
backends,
limiter,
+ llm,
+ world,
+ redis,
};
cache = { at: Date.now(), payload };
return { ...payload, cached: false };
diff --git a/api/_lib/llm-health.js b/api/_lib/llm-health.js
new file mode 100644
index 000000000..dad4598c7
--- /dev/null
+++ b/api/_lib/llm-health.js
@@ -0,0 +1,129 @@
+// @ts-check
+// Live LLM provider health — the truth behind "AI features are up".
+//
+// `llm.js` fails over silently across a free-first chain (Groq → OpenRouter →
+// NVIDIA → paid Anthropic/OpenAI), which is exactly what keeps user-facing AI
+// alive when a provider dies — and exactly what hides a dead provider from ops.
+// The June 2026 outage took out all three paid providers at once while chat
+// stayed (barely) up on a free-tier OpenRouter key; nobody saw it until users
+// hit `:free`-only quality. This module probes the paid providers the platform
+// depends on with a near-zero-cost ping (max_tokens: 1) so an outage is visible
+// before it degrades the product.
+//
+// Probed providers mirror the paid tier of the routing chain:
+// • OpenRouter (primary, env.OPENROUTER_API_KEY) — leads the paid path
+// • Anthropic (env.ANTHROPIC_API_KEY) — paid backstop
+// • OpenAI (env.OPENAI_API_KEY) — paid backstop
+// A provider with no key is simply not probed (omitted from the report) — it is
+// not "down", it is "not part of this deployment".
+//
+// Statuses per provider: 'ok' (2xx) | 'error' (timeout, unreachable, or non-2xx,
+// e.g. a 402 out-of-credits or a 401 bad key). `overall` is 'ok' when every
+// configured provider passes, 'down' when none do, 'degraded' in between, and
+// 'unconfigured' when no paid key is set at all (the free-first chain still
+// serves, so that is not an outage — see the overall calc below).
+//
+// Reused directly (not over HTTP) by api/_lib/forge-health.js and exposed,
+// gated, at GET /api/llm/health.
+
+import { env } from './env.js';
+
+const PROBE_TIMEOUT_MS = 5_000;
+
+// Cheapest live model per provider — a max_tokens:1 completion costs a fraction
+// of a cent and the probe only reads the HTTP status, not the body.
+const OPENROUTER_MODEL = 'openai/gpt-4o-mini';
+const ANTHROPIC_MODEL = 'claude-haiku-4-5-20251001';
+const OPENAI_MODEL = 'gpt-4o-mini';
+
+// fetch with a hard 5s timeout; returns the Response (or null on transport
+// error) plus the measured round-trip so the report can surface latency.
+async function timedFetch(url, options) {
+ const started = Date.now();
+ try {
+ const res = await fetch(url, { ...options, signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
+ return { res, latencyMs: Date.now() - started };
+ } catch (err) {
+ return { res: null, latencyMs: Date.now() - started, err };
+ }
+}
+
+// Turn a probe response into a provider verdict. A 2xx means the key authed and
+// the account has quota; anything else (timeout, network, 401/402/429/5xx) is an
+// error carrying a short, account-detail-free reason.
+function judge({ res, latencyMs, err }, model) {
+ if (!res) {
+ const reason = err?.name === 'TimeoutError' ? `timed out after ${PROBE_TIMEOUT_MS}ms` : 'unreachable';
+ return { status: 'error', error: reason, latencyMs };
+ }
+ if (res.status >= 200 && res.status < 300) {
+ return { status: 'ok', model, latencyMs };
+ }
+ return { status: 'error', error: `${res.status} ${res.statusText || ''}`.trim(), latencyMs };
+}
+
+async function probeOpenAiCompat({ key, url, model, extraHeaders = {} }) {
+ const r = await timedFetch(url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}`, ...extraHeaders },
+ body: JSON.stringify({ model, max_tokens: 1, messages: [{ role: 'user', content: 'ping' }] }),
+ });
+ return judge(r, model);
+}
+
+async function probeAnthropic({ key, model }) {
+ const r = await timedFetch('https://api.anthropic.com/v1/messages', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', 'x-api-key': key, 'anthropic-version': '2023-06-01' },
+ body: JSON.stringify({ model, max_tokens: 1, messages: [{ role: 'user', content: 'ping' }] }),
+ });
+ return judge(r, model);
+}
+
+// Probe every configured paid provider in parallel and fold the per-provider
+// verdicts into one `overall`. Returns { [provider]: verdict, ..., overall }.
+export async function probeLlmHealth() {
+ const probes = [];
+ if (env.OPENROUTER_API_KEY) {
+ probes.push([
+ 'openrouter',
+ probeOpenAiCompat({
+ key: env.OPENROUTER_API_KEY,
+ url: 'https://openrouter.ai/api/v1/chat/completions',
+ model: OPENROUTER_MODEL,
+ extraHeaders: { 'HTTP-Referer': 'https://three.ws', 'X-Title': 'three.ws' },
+ }),
+ ]);
+ }
+ if (env.ANTHROPIC_API_KEY) {
+ probes.push(['anthropic', probeAnthropic({ key: env.ANTHROPIC_API_KEY, model: ANTHROPIC_MODEL })]);
+ }
+ if (env.OPENAI_API_KEY) {
+ probes.push([
+ 'openai',
+ probeOpenAiCompat({
+ key: env.OPENAI_API_KEY,
+ url: 'https://api.openai.com/v1/chat/completions',
+ model: OPENAI_MODEL,
+ }),
+ ]);
+ }
+
+ const verdicts = await Promise.all(probes.map(async ([name, p]) => [name, await p]));
+ const report = Object.fromEntries(verdicts);
+
+ const total = verdicts.length;
+ const passed = verdicts.filter(([, v]) => v.status === 'ok').length;
+ let overall;
+ // No paid key on this deployment is not an outage: the free-first chain
+ // (Groq / OpenRouter-free / NVIDIA) still serves, so report 'unconfigured'
+ // rather than 'down' — otherwise a free-only install would page ops forever
+ // and permanently degrade forge?health against the platform's own policy.
+ if (total === 0) overall = 'unconfigured';
+ else if (passed === 0) overall = 'down';
+ else if (passed === total) overall = 'ok';
+ else overall = 'degraded';
+
+ report.overall = overall;
+ return report;
+}
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 7c95c6109..7c7b7990c 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -339,7 +339,11 @@ export const limits = {
ensResolve: (ip) => getLimiter('ens:resolve:ip', { limit: 60, window: '1 m' }).limit(ip),
snsResolve: (ip) => getLimiter('sns:resolve:ip', { limit: 60, window: '1 m' }).limit(ip),
// Generic public read endpoints (explore, showcase, public agent fetch). 60/min per IP.
- publicIp: (ip) => getLimiter('public:ip', { limit: 60, window: '1 m' }).limit(ip),
+ // local: high-frequency public reads with no side effects — the only job is
+ // flood protection, and a per-instance cap (60 × warm instances, bounded by
+ // Vercel) bounds one IP's throughput just as well without spending a Redis
+ // command per page view. The largest single source of avoidable quota burn.
+ publicIp: (ip) => getLimiter('public:ip', { limit: 60, window: '1 m', local: true }).limit(ip),
// Client-side error report ingestion (api/client-errors). The browser
// reporter batches and caps itself at 25 events/page, so legitimate traffic
// is a handful of requests per pageview even on a broken page; 30/min per
@@ -392,7 +396,11 @@ export const limits = {
previewAgent: (agentId) =>
getLimiter('preview:agent', { limit: 200, window: '1 h' }).limit(agentId),
widgetWrite: (userId) => getLimiter('widget:write', { limit: 60, window: '1 m' }).limit(userId),
- widgetRead: (ip) => getLimiter('widget:read', { limit: 600, window: '1 m' }).limit(ip),
+ // local: embedded-widget read fetch — flood protection only, no side effects.
+ // Widgets on third-party pages poll continuously, so a Redis command per read
+ // at 600/min is pure burn; a per-instance cap bounds throughput just as well.
+ widgetRead: (ip) =>
+ getLimiter('widget:read', { limit: 600, window: '1 m', local: true }).limit(ip),
// Per-widget visitor chat. Limit is dynamic — one bucket per (widgetId, perMinute).
widgetChat: ({ ip, widgetId, perMinute }) =>
getLimiter('widget:chat', {
@@ -414,7 +422,11 @@ export const limits = {
strict: (key) =>
getLimiter('permissions:redeem:strict', { limit: 10, window: '5 m' }).limit(key),
pinUser: (userId) => getLimiter('pin:user', { limit: 30, window: '1 h' }).limit(userId),
- pinStatusIp: (ip) => getLimiter('pin:status:ip', { limit: 60, window: '1 m' }).limit(ip),
+ // local: pin-status poll — read-only progress check, flood guard only. The
+ // pin UI polls this on an interval, so a per-instance cap saves a Redis
+ // command per poll without weakening the throughput bound.
+ pinStatusIp: (ip) =>
+ getLimiter('pin:status:ip', { limit: 60, window: '1 m', local: true }).limit(ip),
agentByAddress: (ip) =>
getLimiter('agents:by-address', { limit: 120, window: '1 m' }).limit(ip),
pricingPerIp: (ip) => getLimiter('pricing:ip', { limit: 120, window: '1 m' }).limit(ip),
@@ -482,14 +494,21 @@ export const limits = {
getLimiter('withdrawal:user', { limit: 5, window: '1 d' }).limit(userId),
// Per-user audit-log reads — the page polls on mount + "load older". 120/min
// per user is generous for browse but discourages scraping the full year.
+ // local: per-user browse/poll of one's own audit log — no side effects, no
+ // shared resource. A per-instance 120/min still discourages bulk scraping
+ // while spending zero Redis commands on a mount-poll + "load older" surface.
auditLogRead: (userId) =>
- getLimiter('audit-log:read', { limit: 120, window: '1 m' }).limit(userId),
+ getLimiter('audit-log:read', { limit: 120, window: '1 m', local: true }).limit(userId),
// Notifications inbox poll — the nav badge polls every 30s and re-polls on
// each navigation + tab focus. Keyed by userId with its own generous bucket so
// it never competes with the strict per-IP `authIp` budget (which a shared
// office/NAT IP would otherwise exhaust, 429-ing the badge for everyone).
+ // local: pure poll-flood guard on a read with no side effects and no shared
+ // resource — a per-instance cap suffices, and at one Redis command per poll
+ // (every 30s × focus/navigation re-polls × every signed-in user) this is one
+ // of the heaviest avoidable burners. Never critical.
notificationsRead: (userId) =>
- getLimiter('notifications:read', { limit: 120, window: '1 m' }).limit(userId),
+ getLimiter('notifications:read', { limit: 120, window: '1 m', local: true }).limit(userId),
// $THREE token payment layer (api/token/*).
// quote: 30 per user per minute — prevents price-polling abuse; each quote
// hits a live price feed and signs a HMAC. Generous enough for interactive
@@ -500,7 +519,11 @@ export const limits = {
tokenSettle: (userId) => getLimiter('token:settle', { limit: 10, window: '1 m' }).limit(userId),
// price: public endpoint, 120/min per IP — fast cache-served; upstream
// Jupiter is rate-limit-free, but the cache makes this essentially free.
- tokenPriceIp: (ip) => getLimiter('token:price:ip', { limit: 120, window: '1 m' }).limit(ip),
+ // local: cache-served price reads; upstream Jupiter is rate-limit-free, so
+ // this bucket only bounds poll floods. A per-instance cap does that without
+ // a Redis command per quote refresh on a high-traffic public endpoint.
+ tokenPriceIp: (ip) =>
+ getLimiter('token:price:ip', { limit: 120, window: '1 m', local: true }).limit(ip),
// Livepeer LLM comparison endpoint — calls both Claude and Livepeer per POST.
// Per-IP only (unauthenticated public demo). Critical so Redis outage in prod
// fails closed rather than opening the LLM floodgate.
diff --git a/api/_lib/redis-usage.js b/api/_lib/redis-usage.js
new file mode 100644
index 000000000..6fef4ddf0
--- /dev/null
+++ b/api/_lib/redis-usage.js
@@ -0,0 +1,201 @@
+// @ts-check
+// Upstash Redis quota-burn visibility.
+//
+// The free plan ceils at 500,000 commands/month. When it is exhausted every
+// `critical: true` limiter fails closed and ALL paid forge generations + x402
+// payments 503 platform-wide (the June 2026 incident: ~42k commands/day burned
+// the quota in ~12 days). This module reads the REAL daily command count so the
+// burn rate is visible — in the forge health endpoint and as an ops alert —
+// well before the ceiling, turning the upgrade into a deliberate decision rather
+// than an outage post-mortem.
+//
+// It never fabricates a number: when usage cannot be read (no management
+// credentials, or the stats API is unreachable) it reports `unknown` and
+// degrades nothing. Two real sources are tried, in order:
+//
+// 1. Upstash Management API — GET https://api.upstash.com/v2/redis/stats/{id}
+// with HTTP Basic auth (UPSTASH_EMAIL : UPSTASH_MANAGEMENT_API_KEY). This
+// is the authoritative account-usage source; the per-store REST token
+// cannot read it.
+// 2. Upstash REST `/stats/daily` — some deployments expose a daily usage
+// summary over the same REST credentials the limiter already uses. Used as
+// a fallback when management credentials are absent.
+
+import { env } from './env.js';
+
+export const REDIS_MONTHLY_BUDGET = 500_000;
+// The daily budget the monthly ceiling implies — burn measured against this is
+// what "on track" means: 100% of the daily budget projects to exactly the
+// monthly ceiling.
+export const REDIS_DAILY_BUDGET = REDIS_MONTHLY_BUDGET / 30; // ≈ 16_667/day
+
+// Projected-monthly alert thresholds (projected = dailyCommands × 30).
+export const REDIS_WARN_PROJECTED = 400_000; // 80% of the free ceiling
+export const REDIS_CRITICAL_PROJECTED = 450_000; // 90% of the free ceiling
+
+const STATS_TIMEOUT_MS = 4_000;
+const MANAGEMENT_STATS_URL = 'https://api.upstash.com/v2/redis/stats';
+
+/** fetch with a hard timeout; resolves to the Response or null on network error. */
+async function timedFetch(url, options = {}) {
+ try {
+ return await fetch(url, { ...options, signal: AbortSignal.timeout(STATS_TIMEOUT_MS) });
+ } catch {
+ return null;
+ }
+}
+
+// Pull a finite daily-command count out of whatever shape the stats payload
+// takes. Upstash has changed these field names over time and the two sources
+// disagree, so we probe the known shapes and bail to null rather than guess.
+// Time-series fields ([{x,y}, …] or [[ts, y], …]) are reduced to their most
+// recent sample — the current day's running total.
+function extractDailyCount(body) {
+ if (!body || typeof body !== 'object') return null;
+ const root = /** @type {Record<string, unknown>} */ (body.result ?? body);
+
+ for (const key of ['totalCommands', 'dailyCommands', 'daily_commands', 'commands', 'count']) {
+ const n = Number(root[key]);
+ if (Number.isFinite(n) && n >= 0) return n;
+ }
+
+ for (const key of ['dailyrequests', 'daily_requests', 'days', 'command_count']) {
+ const last = lastSeriesValue(root[key]);
+ if (last != null) return last;
+ }
+ return null;
+}
+
+// Reduce a time-series ([{x,y}], [[ts,y]], or [n]) to its most recent numeric y.
+function lastSeriesValue(series) {
+ if (!Array.isArray(series) || series.length === 0) return null;
+ const last = series[series.length - 1];
+ let y;
+ if (Array.isArray(last)) y = Number(last[1]);
+ else if (last && typeof last === 'object') y = Number(last.y ?? last.value ?? last.count);
+ else y = Number(last);
+ return Number.isFinite(y) && y >= 0 ? y : null;
+}
+
+async function fetchViaManagementApi() {
+ const email = env.UPSTASH_EMAIL;
+ const apiKey = env.UPSTASH_MANAGEMENT_API_KEY;
+ const id = env.UPSTASH_REDIS_STORE_ID;
+ if (!email || !apiKey || !id) return null;
+ const auth = Buffer.from(`${email}:${apiKey}`).toString('base64');
+ const res = await timedFetch(`${MANAGEMENT_STATS_URL}/${encodeURIComponent(id)}`, {
+ headers: { authorization: `Basic ${auth}`, accept: 'application/json' },
+ });
+ if (!res || !res.ok) return null;
+ const body = await res.json().catch(() => null);
+ return extractDailyCount(body);
+}
+
+async function fetchViaRestStats() {
+ const url = env.UPSTASH_REDIS_REST_URL;
+ const token = env.UPSTASH_REDIS_REST_TOKEN;
+ if (!url || !token) return null;
+ const res = await timedFetch(`${url.replace(/\/$/, '')}/stats/daily`, {
+ headers: { authorization: `Bearer ${token}`, accept: 'application/json' },
+ });
+ if (!res || !res.ok) return null;
+ const body = await res.json().catch(() => null);
+ return extractDailyCount(body);
+}
+
+/**
+ * Read the current day's Redis command count from Upstash. Returns a finite
+ * number, or null when usage cannot be determined (never a fabricated value).
+ * @returns {Promise<number | null>}
+ */
+export async function fetchRedisDailyCommands() {
+ try {
+ const viaMgmt = await fetchViaManagementApi();
+ if (Number.isFinite(viaMgmt)) return /** @type {number} */ (viaMgmt);
+ const viaRest = await fetchViaRestStats();
+ if (Number.isFinite(viaRest)) return /** @type {number} */ (viaRest);
+ } catch {
+ // fall through — burn visibility is best-effort, never throws to callers
+ }
+ return null;
+}
+
+/**
+ * @typedef {Object} RedisBurn
+ * @property {number | null} dailyCommands today's command count (null = unknown)
+ * @property {number} monthlyBudget the free-plan ceiling
+ * @property {number | null} projectedMonthly dailyCommands × 30
+ * @property {number | null} percentUsed % of the daily budget consumed
+ * @property {'ok' | 'warning' | 'critical' | 'unknown'} status
+ */
+
+/**
+ * Classify a daily command count against the free-plan budget. Pure — the unit
+ * tests drive it directly with a stubbed high count.
+ * @param {number | null | undefined} dailyCommands
+ * @returns {RedisBurn}
+ */
+export function evaluateRedisBurn(dailyCommands) {
+ if (!Number.isFinite(dailyCommands) || /** @type {number} */ (dailyCommands) < 0) {
+ return {
+ dailyCommands: null,
+ monthlyBudget: REDIS_MONTHLY_BUDGET,
+ projectedMonthly: null,
+ percentUsed: null,
+ status: 'unknown',
+ };
+ }
+ const daily = /** @type {number} */ (dailyCommands);
+ const projectedMonthly = Math.round(daily * 30);
+ const percentUsed = Number(((daily / REDIS_DAILY_BUDGET) * 100).toFixed(1));
+ let status = /** @type {'ok' | 'warning' | 'critical'} */ ('ok');
+ if (percentUsed > 90) status = 'critical';
+ else if (percentUsed > 70) status = 'warning';
+ return {
+ dailyCommands: daily,
+ monthlyBudget: REDIS_MONTHLY_BUDGET,
+ projectedMonthly,
+ percentUsed,
+ status,
+ };
+}
+
+/**
+ * Build the ops alert for a burn reading, or null when no alert is warranted.
+ * Pure — the cron sends whatever this returns; tests assert it directly.
+ * @param {RedisBurn} burn
+ * @returns {{ level: 'warning' | 'critical', title: string, message: string } | null}
+ */
+export function redisBurnAlert(burn) {
+ if (!burn || burn.status === 'unknown' || !Number.isFinite(burn.projectedMonthly)) return null;
+ const projected = /** @type {number} */ (burn.projectedMonthly);
+ const k = Math.round(projected / 1000);
+ if (projected >= REDIS_CRITICAL_PROJECTED) {
+ return {
+ level: 'critical',
+ title: 'Redis quota CRITICAL — forge + x402 outage imminent',
+ message:
+ `Redis is on track to exceed quota: ${k}k/500k requests this month ` +
+ `(${burn.percentUsed}% of the daily budget). Upgrade Upstash to Pay-As-You-Go ` +
+ `NOW — once the ceiling hits, every paid forge generation and x402 payment fails closed.`,
+ };
+ }
+ if (projected >= REDIS_WARN_PROJECTED) {
+ return {
+ level: 'warning',
+ title: 'Redis quota warning',
+ message:
+ `⚠️ Redis on track to exceed quota: ${k}k/500k requests this month. ` +
+ `Upgrade the Upstash plan to prevent a forge outage.`,
+ };
+ }
+ return null;
+}
+
+/**
+ * Convenience: fetch + classify in one call, for the health endpoint.
+ * @returns {Promise<RedisBurn>}
+ */
+export async function getRedisBurn() {
+ return evaluateRedisBurn(await fetchRedisDailyCommands());
+}
diff --git a/api/cron/forge-smoke.js b/api/cron/forge-smoke.js
index 9f78c5e5a..fe849efd3 100644
--- a/api/cron/forge-smoke.js
+++ b/api/cron/forge-smoke.js
@@ -19,6 +19,10 @@
// the unpaid 402 names /api/mcp-3d and quotes the standard tier price,
// /.well-known/x402.json lists every generation surface, and the paid
// REST endpoint still challenges with usable accepts.
+// 5. LLM completion — runs a trivial llmComplete through the real free-first
+// provider chain. A dead paid chain hides behind the free-tier fallback in
+// day-to-day use; this leg fails loudly so ops sees it. Runs concurrently
+// with the 3D legs so it never delays them.
//
// Failures page the ops Telegram channel; recovery is announced once. Like
// uptime-check, a concrete file keeps the import graph tiny.
@@ -28,6 +32,8 @@ import { env } from '../_lib/env.js';
import { cacheGet, cacheSet } from '../_lib/cache.js';
import { sendOpsAlert } from '../_lib/alerts.js';
import { constantTimeEquals } from '../_lib/crypto.js';
+import { llmComplete } from '../_lib/llm.js';
+import { fetchRedisDailyCommands, evaluateRedisBurn, redisBurnAlert } from '../_lib/redis-usage.js';
const SMOKE_PROMPT = 'a small wooden toy boat with a striped sail';
const SUBMIT_TIMEOUT_MS = 90_000;
@@ -131,9 +137,35 @@ async function runHealthCheck(origin) {
]
.filter((b) => b.status === 'down' || b.status === 'degraded')
.map((b) => `${b.id}: ${b.message}`);
+ // The LLM section is shaped { [provider]: { status, error }, overall } — flag
+ // any failing provider by name so a degraded chain isn't a nameless "degraded".
+ for (const [name, v] of Object.entries(health.body?.llm || {})) {
+ if (name !== 'overall' && v?.status === 'error') broken.push(`llm/${name}: ${v.error}`);
+ }
return { ok: false, reason: broken.join('\n') || `health status: ${health.body?.status}` };
}
+// Exercise the real LLM completion path (in-process, not over HTTP) so a dead
+// provider chain pages ops even when the free-tier fallback masks it from users.
+// Runs through llmComplete so it follows the exact free-first ordering production
+// uses; any successful provider returning the sentinel is a pass.
+async function runLlmSmoke() {
+ try {
+ const { text, provider } = await llmComplete({
+ system: 'You are a health probe. Reply with exactly one word.',
+ user: 'Respond with exactly the word: HEALTHY',
+ maxTokens: 10,
+ timeoutMs: 20_000,
+ });
+ if (!/healthy/i.test(text || '')) {
+ return { ok: false, reason: `LLM replied "${(text || '').slice(0, 80)}" via ${provider}, expected HEALTHY` };
+ }
+ return { ok: true, provider };
+ } catch (err) {
+ return { ok: false, reason: `LLM completion failed: ${err?.message || err}` };
+ }
+}
+
// What a wallet-holding agent actually experiences, end to end minus the
// payment broadcast. Each probe asserts the exact contract the agent tooling
// keys on; any drift (wrong resource URL, missing catalog entry, vanished
@@ -198,17 +230,40 @@ async function runAgentSurfaceCheck(origin) {
return failures.length ? { ok: false, reason: failures.join('\n') } : { ok: true };
}
+// Redis quota-burn early warning. The free Upstash plan ceils at 500k
+// commands/month; when it's exhausted every critical limiter fails closed and
+// the whole paid surface 503s (June 2026). We read the real daily command count
+// and, if the 30-day projection crosses the upgrade thresholds, page ops BEFORE
+// the ceiling instead of after the outage. This is advisory — a burn warning
+// never fails the smoke run (generation is still up today); it exists to make
+// the upgrade a deliberate decision. Unknown usage (no management creds) is a
+// no-op, never a false alarm.
+async function runRedisQuotaCheck() {
+ const burn = evaluateRedisBurn(await fetchRedisDailyCommands());
+ const alert = redisBurnAlert(burn);
+ if (alert) {
+ sendOpsAlert(alert.title, alert.message, {
+ signature: `forge-smoke:redis-quota:${alert.level}`,
+ });
+ }
+ return burn;
+}
+
export default wrap(async (req, res) => {
if (!method(req, res, ['GET'])) return;
if (!requireCron(req, res)) return;
const origin = env.APP_ORIGIN || 'https://three.ws';
- const [generation, health, agentSurfaces] = await Promise.all([
+ const [generation, health, agentSurfaces, llm, redisBurn] = await Promise.all([
runGeneration(origin),
runHealthCheck(origin),
runAgentSurfaceCheck(origin),
+ runLlmSmoke(),
+ runRedisQuotaCheck(),
]);
- const ok = generation.ok && health.ok && agentSurfaces.ok;
+ // Redis burn is an early-warning signal, not a liveness check — it pages ops
+ // on its own threshold but never fails the smoke run (generation is up today).
+ const ok = generation.ok && health.ok && agentSurfaces.ok && llm.ok;
const previous = await cacheGet(LAST_STATUS_KEY);
await cacheSet(LAST_STATUS_KEY, { ok, at: Date.now() }, LAST_STATUS_TTL_S);
@@ -230,11 +285,23 @@ export default wrap(async (req, res) => {
signature: 'forge-smoke:agent-surfaces',
});
}
+ if (!llm.ok) {
+ sendOpsAlert('FORGE SMOKE: LLM completion path down', llm.reason, {
+ signature: 'forge-smoke:llm',
+ });
+ }
if (ok && previous && previous.ok === false) {
sendOpsAlert('RECOVERED: forge generation smoke test', `${origin}/forge — prompt→GLB verified`, {
signature: `forge-smoke:recovered:${Date.now()}`,
});
}
- return json(res, 200, { ok, generation, health, agent_surfaces: agentSurfaces });
+ return json(res, 200, {
+ ok,
+ generation,
+ health,
+ agent_surfaces: agentSurfaces,
+ llm: llm.ok ? { status: 'ok', provider: llm.provider } : { status: 'error', reason: llm.reason },
+ redis: redisBurn,
+ });
});
diff --git a/api/cron/world-health.js b/api/cron/world-health.js
new file mode 100644
index 000000000..12383591e
--- /dev/null
+++ b/api/cron/world-health.js
@@ -0,0 +1,152 @@
+// @ts-check
+// GET /api/cron/world-health — synthetic monitor for world.three.ws (Hyperfy).
+//
+// Two failure modes, both user-facing and both seen in production:
+// 1. UNPROTECTED — the Cloud Run service is serving without ADMIN_CODE, so
+// every visitor joins with build rights and can delete the scene. This is
+// how the 2026-06-12 void-fall started. /status reports `protected`.
+// 2. MISSING ASSET — a blueprint references an asset URL that 404s. When the
+// $scene script asset vanished on 2026-06-12 the ground unloaded and every
+// joiner fell into a black void. The patched /status enumerates every
+// content-hashed blueprint asset with an absolute URL; we HEAD each one.
+//
+// Runs every 15 minutes (vercel.json crons). Like uptime-check, this is a
+// concrete handler so its import graph stays tiny — a monitor must not share a
+// cold start with the heavy generation/pump SDKs behind the [name].js dispatcher.
+
+import { json, method, wrap } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { sendOpsAlert } from '../_lib/alerts.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+
+const WORLD_STATUS_URL = process.env.WORLD_URL
+ ? `${process.env.WORLD_URL.replace(/\/+$/, '')}/status`
+ : 'https://world.three.ws/status';
+const FETCH_TIMEOUT_MS = 10_000;
+const ASSET_TIMEOUT_MS = 8_000;
+const ASSET_CONCURRENCY = 10;
+
+// Vercel cron invokes with `Authorization: Bearer <CRON_SECRET>`; manual probes
+// may use `X-Cron-Secret: <CRON_SECRET>`. Accept either, constant-time. 503 if
+// the secret is unset (misconfiguration), 403 if presented and wrong/absent.
+function requireCron(req, res) {
+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;
+ if (!secret) {
+ json(res, 503, { error: 'not_configured', error_description: 'CRON_SECRET unset' });
+ return false;
+ }
+ const auth = req.headers['authorization'] || '';
+ const bearer = auth.startsWith('Bearer ') ? auth.slice(7) : '';
+ const header = req.headers['x-cron-secret'] || '';
+ if (constantTimeEquals(bearer, secret) || constantTimeEquals(header, secret)) return true;
+ json(res, 403, { error: 'forbidden', error_description: 'invalid cron secret' });
+ return false;
+}
+
+// HEAD every asset URL with a bounded number in flight so the whole sweep
+// finishes well inside the 10s cron budget even with a large scene.
+async function headAll(urls, concurrency) {
+ const results = new Array(urls.length);
+ let cursor = 0;
+ async function worker() {
+ while (cursor < urls.length) {
+ const i = cursor++;
+ try {
+ const res = await fetch(urls[i], {
+ method: 'HEAD',
+ redirect: 'follow',
+ headers: { 'user-agent': 'threews-world-health/1.0' },
+ signal: AbortSignal.timeout(ASSET_TIMEOUT_MS),
+ });
+ results[i] = { ok: res.ok, status: res.status };
+ } catch (e) {
+ results[i] = { ok: false, status: 0, error: e?.name === 'TimeoutError' ? 'timeout' : 'unreachable' };
+ }
+ }
+ }
+ await Promise.all(Array.from({ length: Math.min(concurrency, urls.length) }, worker));
+ return results;
+}
+
+export default wrap(async (req, res) => {
+ if (!method(req, res, ['GET'])) return;
+ if (!requireCron(req, res)) return;
+
+ // 1. Pull /status. A timeout or non-2xx means the world is down outright.
+ let status;
+ try {
+ const r = await fetch(WORLD_STATUS_URL, {
+ headers: { 'user-agent': 'threews-world-health/1.0', accept: 'application/json' },
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
+ });
+ if (!r.ok) {
+ sendOpsAlert('World DOWN', `${WORLD_STATUS_URL} returned HTTP ${r.status}`, {
+ signature: 'world-health:status-http',
+ });
+ return json(res, 200, { status: 'down', protected: null, blueprintCount: 0, reason: `HTTP ${r.status}` });
+ }
+ status = await r.json();
+ } catch (e) {
+ const reason = e?.name === 'TimeoutError' ? 'timeout' : e?.message || 'unreachable';
+ sendOpsAlert('World DOWN', `${WORLD_STATUS_URL} unreachable — ${reason}`, {
+ signature: 'world-health:status-unreachable',
+ });
+ return json(res, 200, { status: 'down', protected: null, blueprintCount: 0, reason });
+ }
+
+ const isProtected = status?.protected === true;
+ // `blueprints` is the patched-/status asset list ({id, assetUrl}); tolerate an
+ // older revision that predates the patch by treating an absent list as empty.
+ const blueprints = Array.isArray(status?.blueprints) ? status.blueprints : [];
+ const assetUrls = blueprints
+ .map((b) => b?.assetUrl)
+ .filter((u) => typeof u === 'string' && /^https?:\/\//.test(u));
+
+ const problems = [];
+
+ // 2. Unprotected → every visitor can edit the world. The admin code was lost
+ // or a revision shipped without the secret mounted.
+ if (!isProtected) {
+ problems.push('world is UNPROTECTED — ADMIN_CODE is not set; every visitor has build rights');
+ sendOpsAlert(
+ 'World UNPROTECTED',
+ 'world.three.ws is serving without ADMIN_CODE — every visitor has build rights. Re-run deploy/world/apply-hardening.sh.',
+ { signature: 'world-health:unprotected' },
+ );
+ }
+
+ // 3. HEAD every referenced asset; a 404 will crash the scene on join.
+ const checks = await headAll(assetUrls, ASSET_CONCURRENCY);
+ const missing = [];
+ checks.forEach((c, i) => {
+ if (!c.ok) {
+ const bp = blueprints.find((b) => b.assetUrl === assetUrls[i]);
+ missing.push({ assetUrl: assetUrls[i], blueprintId: bp?.id, status: c.status, error: c.error });
+ }
+ });
+ if (missing.length) {
+ problems.push(`${missing.length} blueprint asset(s) missing`);
+ const detail = missing
+ .map((m) => `${m.blueprintId || 'unknown'}: ${m.assetUrl} (${m.error || `HTTP ${m.status}`})`)
+ .join('\n');
+ sendOpsAlert('World asset MISSING', detail, {
+ // Signature keyed to the set of missing URLs so a new gap re-alerts but
+ // the same sustained outage dedups to once an hour.
+ signature: `world-health:missing:${missing.map((m) => m.assetUrl).sort().join(',')}`,
+ });
+ }
+
+ const outcome = !isProtected || missing.length ? 'degraded' : 'ok';
+ if (outcome === 'ok') {
+ console.log(`[world-health] ok, ${blueprints.length} blueprints, protected: true`);
+ } else {
+ console.warn(`[world-health] ${outcome} — ${problems.join('; ')}`);
+ }
+
+ return json(res, 200, {
+ status: outcome,
+ protected: isProtected,
+ blueprintCount: blueprints.length,
+ ...(missing.length ? { missingAssets: missing } : {}),
+ });
+});
diff --git a/api/llm/health.js b/api/llm/health.js
new file mode 100644
index 000000000..a183d4a07
--- /dev/null
+++ b/api/llm/health.js
@@ -0,0 +1,50 @@
+// @ts-check
+// GET /api/llm/health — gated, real-time status of every configured paid LLM
+// provider (OpenRouter primary, Anthropic, OpenAI). The free-first chain in
+// _lib/llm.js degrades silently, so a dead paid provider is invisible to users
+// until quality drops; this surfaces it for the hourly cron and on-call checks.
+//
+// Auth: a valid cron secret, presented EITHER as `X-Cron-Secret: <secret>` (the
+// header an operator or external monitor sends) OR as `Authorization: Bearer
+// <secret>` (the header Vercel Cron sends on the scheduled invocation). Anything
+// else gets 403 with no provider names or error detail — those reveal which key
+// is bad and may carry account/quota specifics, so they stay behind the gate.
+//
+// On 'degraded'/'down' it pages the ops Telegram channel (see _lib/alerts.js),
+// deduped per failing-provider signature so a sustained outage alerts once.
+
+import { json, error, method, wrap } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+import { sendOpsAlert } from '../_lib/alerts.js';
+import { probeLlmHealth } from '../_lib/llm-health.js';
+
+function authorized(req, secret) {
+ const headerSecret = req.headers['x-cron-secret'];
+ if (headerSecret && constantTimeEquals(headerSecret, secret)) return true;
+ const auth = req.headers['authorization'] || '';
+ const bearer = auth.startsWith('Bearer ') ? auth.slice(7) : '';
+ if (bearer && constantTimeEquals(bearer, secret)) return true;
+ return false;
+}
+
+export default wrap(async (req, res) => {
+ if (!method(req, res, ['GET'])) return;
+
+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;
+ if (!secret) return error(res, 503, 'not_configured', 'CRON_SECRET is not set on this deployment');
+ if (!authorized(req, secret)) return error(res, 403, 'forbidden', 'a valid cron secret is required');
+
+ const health = await probeLlmHealth();
+
+ if (health.overall === 'degraded' || health.overall === 'down') {
+ const failing = Object.entries(health)
+ .filter(([k, v]) => k !== 'overall' && v?.status === 'error')
+ .map(([k, v]) => `${k}: ${v.error}`);
+ sendOpsAlert(`LLM providers ${health.overall.toUpperCase()}`, failing.join('\n') || 'no providers passed', {
+ signature: `llm-health:${health.overall}:${failing.join(',')}`,
+ });
+ }
+
+ return json(res, 200, health);
+});
diff --git a/api/pump-fun-mcp.js b/api/pump-fun-mcp.js
index 9e6f52b5c..4d69ae289 100644
--- a/api/pump-fun-mcp.js
+++ b/api/pump-fun-mcp.js
@@ -207,6 +207,22 @@ async function handleSnsReverseLookup({ address }) {
// ── Indexer-backed handlers (route through pumpfunMcp) ─────────────────────
+// Tools whose data comes exclusively from the external pump.fun indexer
+// (PUMPFUN_BOT_URL). When the bot is unconfigured these are filtered out of
+// tools/list entirely so MCP clients only ever see tools they can call — they
+// reappear automatically once the env var is set, with no code change. The
+// -32004 guard in indexerOrUnavailable() stays as defence for any client that
+// calls one anyway (e.g. from a cached tool list). get_token_trades is NOT
+// here: it has a real on-chain fallback and works without the indexer.
+const INDEXER_TOOLS = new Set([
+ 'search_tokens',
+ 'get_trending_tokens',
+ 'get_new_tokens',
+ 'get_graduated_tokens',
+ 'get_king_of_the_hill',
+ 'get_creator_profile',
+]);
+
function indexerOrUnavailable(name) {
return async (args) => {
if (!pumpfunBotEnabled()) {
@@ -735,6 +751,58 @@ async function handleGetTokenTrades({ mint, limit = 20, network = 'mainnet' }) {
return readTradesFromChain({ mint, limit, network });
}
+// ── pumpfun_bot_status (metadata, always available) ────────────────────────
+
+// Reports whether the indexer is configured and, when it is, whether it's
+// answering. Always available (never gated, never filtered) so MCP clients can
+// discover backend capability without parsing tools/list. The health ping uses
+// the same transport as the indexer tools (MCP tools/call against the bot) with
+// a tight 3 s budget so a slow/dead bot can't stall the metadata call.
+async function handlePumpfunBotStatus() {
+ if (!pumpfunBotEnabled()) {
+ return {
+ configured: false,
+ healthy: false,
+ message:
+ 'PUMPFUN_BOT_URL is not configured. On-chain tools are available; indexer-backed discovery tools are disabled.',
+ };
+ }
+ const url = process.env.PUMPFUN_BOT_URL.replace(/\/$/, '');
+ const headers = { 'content-type': 'application/json', accept: 'application/json' };
+ if (process.env.PUMPFUN_BOT_TOKEN)
+ headers.authorization = `Bearer ${process.env.PUMPFUN_BOT_TOKEN}`;
+ const ctrl = new AbortController();
+ const timer = setTimeout(() => ctrl.abort(), 3000);
+ const startedAt = Date.now();
+ try {
+ const r = await fetch(url, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'getNewTokens', arguments: { limit: 1 } },
+ }),
+ signal: ctrl.signal,
+ });
+ const latencyMs = Date.now() - startedAt;
+ if (!r.ok) return { configured: true, healthy: false, latencyMs, error: `bot ${r.status}` };
+ const j = await r.json().catch(() => null);
+ if (j?.error)
+ return { configured: true, healthy: false, latencyMs, error: j.error.message || 'rpc error' };
+ return { configured: true, healthy: true, latencyMs };
+ } catch (err) {
+ return {
+ configured: true,
+ healthy: false,
+ error: err?.name === 'AbortError' ? 'timeout after 3000ms' : err?.message || 'fetch failed',
+ };
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
// ── Dispatch ───────────────────────────────────────────────────────────────
// Keyed by CANONICAL (snake_case) names. tools/call resolves legacy camelCase
@@ -762,6 +830,7 @@ const HANDLERS = {
pumpfun_quote_swap: handleQuoteSwap,
sns_resolve: handleSnsResolve,
sns_reverseLookup: handleSnsReverseLookup,
+ pumpfun_bot_status: handlePumpfunBotStatus,
};
// ── HTTP entrypoint ────────────────────────────────────────────────────────
@@ -780,8 +849,11 @@ const INSTRUCTIONS =
'pumpfun_list_claims, pumpfun_watch_claims, pumpfun_first_claims), Solana Name ' +
'Service (sns_resolve, sns_reverseLookup), market signals (kol_radar, ' +
'kol_leaderboard, pumpfun_quote_swap, pumpfun_watch_whales), and social ' +
- 'sentiment (social_cashtag_sentiment, social_x_post_impact). All data is live ' +
- 'and on-chain; no API keys required for the free tools.';
+ 'sentiment (social_cashtag_sentiment, social_x_post_impact). Discovery tools ' +
+ '(search_tokens, get_trending_tokens, get_new_tokens, get_graduated_tokens, ' +
+ 'get_king_of_the_hill, get_creator_profile) require the indexer backend and are ' +
+ 'listed only when it is configured — call pumpfun_bot_status (always available) ' +
+ 'to check. All data is live and on-chain; no API keys required for the free tools.';
const MAX_BATCH = 16;
// Tools that are expensive (CPU grind or long-lived RPC subscriptions) or that
@@ -924,13 +996,23 @@ async function dispatchRpc(msg, ctx) {
return rpcEnvelope(id, {
protocolVersion: PROTOCOL_VERSION,
capabilities: { tools: { listChanged: false } },
- serverInfo: SERVER_INFO,
+ // indexerEnabled lets client authors check indexer capability without a
+ // tools/list round-trip — it tracks the same env presence as the filter.
+ serverInfo: { ...SERVER_INFO, indexerEnabled: pumpfunBotEnabled() },
instructions: INSTRUCTIONS,
});
}
if (rpcMethod === 'ping') return rpcEnvelope(id, {});
if (rpcMethod === 'notifications/initialized') return null;
- if (rpcMethod === 'tools/list') return rpcEnvelope(id, { tools: TOOLS });
+ if (rpcMethod === 'tools/list') {
+ // Advertise indexer-backed tools only when the bot is configured, so MCP
+ // clients never see a tool that would just return -32004 on call. The
+ // always-on pumpfun_bot_status (not in INDEXER_TOOLS) reports capability.
+ const tools = pumpfunBotEnabled()
+ ? TOOLS
+ : TOOLS.filter((t) => !INDEXER_TOOLS.has(t.name));
+ return rpcEnvelope(id, { tools });
+ }
if (rpcMethod === 'resources/list') return rpcEnvelope(id, { resources: [] });
if (rpcMethod === 'resources/templates/list') return rpcEnvelope(id, { resourceTemplates: [] });
if (rpcMethod === 'prompts/list') return rpcEnvelope(id, { prompts: [] });
diff --git a/data/changelog.json b/data/changelog.json
index 443500754..5d1e2c978 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,46 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-14",
+ "title": "React component library for embedding 3D AI agents",
+ "summary": "npm install @three-ws/react gives you <Agent3D> — a React wrapper around the three.ws walk embed player. Drop a 3D AI agent into any React app in two lines of code, with props for controls, size, and background, plus onLoad/onError callbacks and a ref handle to drive the avatar live.",
+ "tags": ["feature", "sdk"],
+ "link": "/embed/walk"
+ },
+ {
+ "date": "2026-06-14",
+ "title": "x402-fetch — automatic pay-per-call fetch wrapper",
+ "summary": "npm install @three-ws/x402-fetch gives you withX402(wallet) — a drop-in fetch wrapper that silently handles x402 payment challenges. Connect a wallet once; call any paid three.ws API like a free one. It signs USDC-on-Base payments locally with zero dependencies, refuses to overspend past a maxPaymentUsd guard you set, and works in the browser (MetaMask), in Node (private key), or with a three.ws agent wallet.",
+ "tags": ["feature", "sdk"],
+ "link": "/docs/sdk"
+ },
+ {
+ "date": "2026-06-14",
+ "title": "pump.fun MCP server only lists tools it can actually run",
+ "summary": "The free pump.fun MCP server (three.ws/api/pump-fun-mcp) now advertises its discovery tools — token search, trending, new, graduated, king-of-the-hill, and creator profiles — only when its real-time indexer backend is connected. Previously those six tools always appeared in the tool list and returned an error if the indexer wasn't wired, which confused MCP clients and assistants that tried to call them. They now stay hidden until the backend is live, and reappear automatically the moment it is. We also added a always-available pumpfun_bot_status tool that reports whether the indexer is configured and healthy (with round-trip latency), and an indexerEnabled flag on the server handshake so client authors can check capability in one call. On-chain tools (bonding curve, holders, token details, trades, swap quotes, fee claims) were unaffected and remain fully available with no API key.",
+ "tags": [
+ "sdk",
+ "improvement"
+ ]
+ },
+ {
+ "date": "2026-06-14",
+ "title": "world.three.ws locked down and watched around the clock",
+ "summary": "The multiplayer world (world.three.ws) is now protected against unauthorized edits: visitors join as spectators and only a holder of the admin code can build, move, or delete anything in the scene. We also added a continuous health watch. Every 15 minutes a monitor confirms the world is still protected and checks that every asset the scene depends on is actually reachable — the exact gap that briefly dropped visitors into an empty void earlier this month, now caught and paged to our ops team before anyone notices. The forge health surface (/api/forge?health) reports the world's status alongside the generation backends, and a post-deploy gate refuses to call a deploy healthy unless the world comes back protected.",
+ "tags": [
+ "security",
+ "infra"
+ ]
+ },
+ {
+ "date": "2026-06-14",
+ "title": "Forge stays up: live Redis quota monitoring and early-warning alerts",
+ "summary": "The shared rate-limiter store has a hard monthly request ceiling, and when it's exhausted every paid generation and payment stops at once. We've made that failure mode impossible to sneak up on us. The forge health check (/api/forge?health) now reports the live daily request rate, how much of the budget it's burning, and projects whether it's on track to run out — and a daily check pages our ops team the moment the projection crosses 80% of the ceiling, long before anything breaks. We also moved the highest-traffic, lowest-risk traffic guards (public page reads, status polling, the notifications badge) to in-process enforcement so they no longer spend from that budget at all, cutting burn dramatically. Net effect: more headroom, and a deliberate upgrade decision instead of a surprise outage.",
+ "tags": [
+ "infra"
+ ]
+ },
{
"date": "2026-06-13",
"title": "The IBM partnership page, rebuilt in IBM's own design language",
diff --git a/deploy/world/patches/0002-status-blueprint-assets.patch b/deploy/world/patches/0002-status-blueprint-assets.patch
new file mode 100644
index 000000000..ee629d8f9
--- /dev/null
+++ b/deploy/world/patches/0002-status-blueprint-assets.patch
@@ -0,0 +1,30 @@
+diff --git a/src/server/index.js b/src/server/index.js
+index 67d7345..4d99ad5 100644
+--- a/src/server/index.js
++++ b/src/server/index.js
+@@ -199,6 +199,25 @@ fastify.get('/status', async (request, reply) => {
+ connectedUsers: [],
+ commitHash: process.env.COMMIT_HASH,
+ }
++ // Expose every content-hashed asset each blueprint references, with an
++ // absolute URL, so an external monitor can HEAD them over plain HTTP and
++ // catch a missing asset before it crashes the scene for every joiner —
++ // the exact failure mode of the 2026-06-12 void-fall (a lost $scene
++ // script asset unloaded the ground and dropped every player into the void).
++ const assetsBaseUrl = (process.env.ASSETS_BASE_URL || '').replace(/\/+$/, '')
++ status.blueprints = []
++ for (const data of world.blueprints.serialize()) {
++ const refs = new Set()
++ for (const m of JSON.stringify(data).matchAll(/asset:\/\/([a-f0-9]{64}\.\w+)/g)) {
++ refs.add(m[1])
++ }
++ for (const file of refs) {
++ status.blueprints.push({
++ id: data.id,
++ assetUrl: assetsBaseUrl ? `${assetsBaseUrl}/${file}` : `asset://${file}`,
++ })
++ }
++ }
+ for (const socket of world.network.sockets.values()) {
+ status.connectedUsers.push({
+ id: socket.player.data.userId,
diff --git a/docs/ops/redis.md b/docs/ops/redis.md
new file mode 100644
index 000000000..f3d955ee0
--- /dev/null
+++ b/docs/ops/redis.md
@@ -0,0 +1,270 @@
+# Redis (Upstash) — quota, burn rate, and limiter classification
+
+The platform's distributed rate limiters and the shared cache run on a single
+Upstash Redis store. On the free plan that store has a hard ceiling of
+**500,000 commands/month**. When the ceiling is hit, every `critical: true`
+limiter **fails closed** — which blocks every paid forge generation and every
+x402 payment platform-wide. This is not theoretical: in early June 2026 the
+previous store burned ~42,000 commands/day and exhausted the quota in ~12 days,
+taking the paid surface down for all users.
+
+This doc is the deliberate-decision playbook: what burns quota, how to see the
+burn before it's a crisis, and when/how to upgrade.
+
+## Upstash plan management
+
+### Current plan
+
+Free tier: 500,000 requests/month. Store: `three-ratelimit`
+(`store_QnjIWaKv4d5MvmA9`).
+
+### Upgrade trigger
+
+Upgrade to the Pay-As-You-Go plan when **projected monthly usage exceeds
+400,000 requests (~80% of the free ceiling)**. At $0.20 per 100k additional
+commands the cost is negligible relative to the revenue lost during a quota
+outage.
+
+"Projected monthly" = today's command count × 30. It is computed and surfaced
+automatically — see _Visibility_ below — so the trigger fires on a number, not a
+hunch.
+
+### How to upgrade
+
+1. Upstash console → `three-ratelimit` store → Billing → Upgrade to
+ Pay-As-You-Go.
+2. **No code change required** — the store endpoint and token remain the same,
+ so `UPSTASH_REDIS_REST_URL` / `UPSTASH_REDIS_REST_TOKEN` are untouched.
+3. Update this doc with the plan-change date.
+
+### Reducing burn without upgrading
+
+See `api/_lib/rate-limit.js` — limiters marked `local: true` use **zero Redis
+commands** (per-instance in-memory enforcement). Eligible candidates: status-poll
+limiters, public health-check limiters, public read endpoints, cron rate guards.
+**Never mark a `critical: true` limiter as `local`** — the fail-closed behavior
+on a missing/exhausted Redis is the correct safety behavior for money-moving
+operations.
+
+## Visibility
+
+### Health endpoint
+
+`GET /api/forge?health` includes a `redis` block:
+
+```json
+"redis": {
+ "dailyCommands": 9120,
+ "monthlyBudget": 500000,
+ "projectedMonthly": 273600,
+ "percentUsed": 54.7,
+ "status": "ok"
+}
+```
+
+- `percentUsed` is the share of the **daily** budget (`500000 / 30 ≈ 16,667`)
+ consumed today — 100% projects to exactly the monthly ceiling.
+- `status`: `ok` (≤70%), `warning` (>70%), `critical` (>90%), or `unknown`
+ (usage could not be read — never a fabricated number).
+- A `critical` Redis status degrades the endpoint's `overall` to `degraded`,
+ so the early warning rides the same signal as a dead backend.
+
+Source: `api/_lib/redis-usage.js` (`getRedisBurn` / `evaluateRedisBurn`). The
+daily command count is read from the **Upstash Management API**
+(`GET https://api.upstash.com/v2/redis/stats/{id}`, HTTP Basic auth with
+`UPSTASH_EMAIL` : `UPSTASH_MANAGEMENT_API_KEY`), falling back to the REST
+`/stats/daily` summary. These are read-only credentials distinct from the
+limiter's command token; when none are configured, burn reports `unknown` and
+degrades nothing.
+
+### Ops alert
+
+`api/cron/forge-smoke.js` (daily cron) reads the same burn number and pages the
+ops Telegram channel when the 30-day projection crosses a threshold:
+
+- **> 400,000 (80%)** → warning: "Redis on track to exceed quota …".
+- **> 450,000 (90%)** → critical: "forge + x402 outage imminent …".
+
+Requires `TELEGRAM_BOT_TOKEN` + `TELEGRAM_ALERTS_CHAT_ID` (shared with the rest
+of the ops alerting). The alert is advisory and never fails the smoke run.
+
+### Config
+
+| Env var | Purpose | Required? |
+| --- | --- | --- |
+| `UPSTASH_REDIS_REST_URL` / `UPSTASH_REDIS_REST_TOKEN` | limiter + cache commands (and REST `/stats/daily` fallback) | yes (already set) |
+| `UPSTASH_EMAIL` | Management API basic-auth user | for burn visibility |
+| `UPSTASH_MANAGEMENT_API_KEY` | Management API key (read-only usage) | for burn visibility |
+| `UPSTASH_REDIS_STORE_ID` | store id for the Management API | defaults to the live store |
+
+## Redis call-site catalogue
+
+Every Redis touch is one of three classes. The class decides whether it may move
+to `local` (no Redis command) or must stay Redis-backed.
+
+- **local** — per-instance in-memory is sufficient; spends zero Redis commands.
+ Only for high-frequency, low-stakes flood guards where cross-instance
+ coordination buys nothing.
+- **critical** — cost/money-moving or auth-security; must be Redis-backed and
+ **fail closed** when Redis is absent/exhausted.
+- **cross-instance-required** — correctness depends on shared state across
+ serverless instances (atomic spend ledgers, idempotency/replay dedup, shared
+ feeds/caches). Redis-backed, but fails *open* or degrades rather than denying.
+
+### Rate limiters (`api/_lib/rate-limit.js`)
+
+| Limiter | Class | Note |
+| --- | --- | --- |
+| `mcp3dStatus` | local | generation status poll — highest-frequency call; per-instance cap |
+| `publicIp` | local | generic public reads (explore/showcase/feeds) — flood guard only |
+| `notificationsRead` | local | nav-badge poll (30s + focus/nav) — per-user, no shared resource |
+| `auditLogRead` | local | per-user audit-log browse/poll |
+| `tokenPriceIp` | local | cache-served price reads; upstream Jupiter is rate-limit-free |
+| `widgetRead` | local | embedded-widget read fetch — continuous third-party-page polling |
+| `pinStatusIp` | local | pin-status progress poll |
+| `authIp`, `registerIp`, `verifyEmailIp`, `forgotPasswordEmail`, `resendVerifyUser` | critical | auth/credential-guessing — fail closed |
+| `chatUser`, `chatIp`, `chatHostKeyGlobal`, `brainChatUser`, `brainChatIp`, `livepeerIp` | critical | paid LLM inference |
+| `mcp3dGenerate`, `mcpValidate`, `mcpInspect`, `mcpOptimize`, `mcpBazaar`, `mcpAgent`, `mcpAgentPay` | critical | paid compute / paid tools |
+| `avatarPayoutDaily`, `agentBuy`, `x402PayGlobal`, `videoGenerateUser`, `videoGenerateGlobal` | critical | real money movement |
+| `bountyJudge`, `voiceClone`, `ttsSpeakUser`, `ttsSpeakIp` | critical | paid synthesis / inference |
+| all other `*Ip` / `*User` read & write limiters | cross-instance-required | distributed per-principal caps; fail open on outage |
+
+### Direct Redis usage (cache, feeds, ledgers)
+
+| File | Class | Operation |
+| --- | --- | --- |
+| `api/_lib/cache.js` | cross-instance-required | shared cache GET/SET/DEL (read-memo + single-flight in front to cut burn) |
+| `api/_lib/feed.js` | cross-instance-required | activity feed LPUSH/LTRIM/LRANGE (8s read-coalesce window) |
+| `api/_lib/usage.js` | cross-instance-required | usage-event buffer RPUSH/LRANGE/LTRIM (batched flush) |
+| `api/_lib/x402-spending-ledger.js` | critical / cross-instance-required | atomic INCRBY spend caps per hour/day/address |
+| `api/_lib/a2a/spend-ledger.js` | critical / cross-instance-required | agent-to-agent daily payout caps |
+| `api/_lib/x402/idempotency-cache.js` | critical / cross-instance-required | payment replay dedup (GET/SET) |
+| `api/_lib/builds-store.js` | cross-instance-required | build metadata + per-mint index cache |
+| `api/_lib/alerts.js` | cross-instance-required | ops-alert dedup + hourly ceiling |
+| `api/x402-pay.js`, `api/feed-stream.js`, `api/_lib/channel-feed-sources.js`, `api/_lib/pumpfun-mcp.js` | cross-instance-required | demo payment feed + feed reads |
+| `api/cron/uptime-check.js`, `api/cron/quota-check.js`, `api/cron/flush-usage-events.js` | cross-instance-required | cron cache snapshots + buffer drain |
+
+> The spend-ledger and idempotency entries are both critical (money-moving) and
+> cross-instance-required (atomicity across instances) — they can never move to
+> `local`, and they must keep Redis-backed atomic increments even under quota
+> pressure. They are the floor on how low burn can go without an upgrade.
+
+### History
+
+- **2026-06-12** — previous store hit the 500k ceiling; all paid lanes failed
+ closed. New store `three-ratelimit` provisioned (same limits), daily
+ forge-smoke + limiter health probe added. `mcp3dStatus` moved to `local`.
+- **2026-06-14** — `publicIp`, `notificationsRead`, `auditLogRead`,
+ `tokenPriceIp`, `widgetRead`, `pinStatusIp` moved to `local`; burn-rate block
+ added to `/api/forge?health`; projected-quota Telegram alert added to the
+ forge-smoke cron; this doc created.
+
+## Data durability
+
+Keys in the active Upstash store fall into two durability classes.
+
+### Durable keys — must survive store rotation
+
+These keys hold user-owned data. If the store is rotated (new free-tier store
+provisioned) without migrating them, user data is lost.
+
+| Pattern | Type | TTL | What it holds |
+| --- | --- | --- | --- |
+| `cosmetics:owned:<account>` | SET | 2 years | Cosmetics purchased via x402 — a user's paid unlocks |
+| `x402:pay:call:<tx_hash>` | STRING | 30 days | Payment dedup record by transaction hash — prevents replay |
+| `featured-builds:<mint>` | STRING/JSON | 45 days | Forge build gallery index per mint |
+| `play-build:<id>` | STRING/JSON | 45 days | Individual forge build thumbnail + metadata |
+| `x402:pay:feed` | LIST (≤50 items) | none | Recent x402 payment activity feed |
+| `feed:events` | LIST (≤200 items) | none | General platform activity feed |
+
+### Ephemeral keys — safe to lose
+
+These keys regenerate automatically within seconds to minutes.
+
+| Pattern | Why safe |
+| --- | --- |
+| `rl:*` | Rate-limit windows; rebuild on next request |
+| `x402:rl:*` | Subscription rate-limit sorted sets; rebuild on next call |
+| `forge-smoke:last` | Last cron result; regenerated on next run (≤24h) |
+| `uptime:snapshots` | Rolling 24h probe data; regenerated on next uptime cron |
+| `uptime:daily` | 90-day aggregate; rebuilds incrementally from new probes |
+| `usage:buffer` | Usage-event RPUSH buffer; flushed to DB by cron, then DEL'd |
+| `feed:joined:<key>` | World-join dedup (60s TTL) |
+| `rep:<agentId>:<chain>` | Reputation cache (5-min TTL) |
+| `quota:redis` | Quota check cache (25h TTL) |
+| `a2a:spend:<mandateId>` | A2A mandate spend ledger; mandate-scoped, short-lived |
+| `<route>|<paymentId>` | Idempotency cache for x402 paid endpoints |
+
+## Store rotation procedure
+
+When a store must be rotated (quota exhausted, billing migration, etc.):
+
+### Step 1 — Recover dead store credentials
+
+The dead store's REST URL and token are needed for migration. Try in order:
+
+1. **Upstash console** — log in at [console.upstash.com](https://console.upstash.com),
+ locate the old store, click "REST API" tab. Copy URL and token.
+
+2. **Vercel env history** — if credentials were set as Vercel env vars and then
+ overwritten, they may still exist in revision history:
+ ```bash
+ curl -s "https://api.vercel.com/v9/projects/<project_id>/env?teamId=<team_id>&includeDeleted=true&limit=100" \
+ -H "Authorization: Bearer <VERCEL_PAT>" \
+ | jq '.envs[] | select(.key | startswith("UPSTASH")) | {key, value}'
+ ```
+ Project id: `prj_IWZmEnqR1pCZRCRuvhCFCDcOx5Wc` · Team id: `team_zRpaxHPiMnQGXurBbegM3PCA`.
+
+3. **Known active store** (for local dev): `smiling-crane-148172.upstash.io`,
+ credentials in `.env.local` as `three_KV_REST_API_*`. This is the
+ `three-ratelimit` store provisioned 2026-06-12.
+
+### Step 2 — Dry-run and review
+
+```bash
+DEAD_REDIS_URL=<old-url> DEAD_REDIS_TOKEN=<old-token> \
+ node scripts/migrate-redis.mjs --dry-run
+```
+
+Review the output. Expected: all `cosmetics:owned:*` and build keys appear
+under COPY. If the count looks wrong (e.g. 0 cosmetics when purchases are
+known to have been made), check that DEAD_REDIS_URL points to the correct store.
+
+### Step 3 — Run the migration
+
+```bash
+DEAD_REDIS_URL=<old-url> DEAD_REDIS_TOKEN=<old-token> \
+ node scripts/migrate-redis.mjs
+```
+
+The script uses `SET NX` for strings and `SADD` for sets, so re-running is
+safe — it never clobbers newer data that landed in the active store after the
+rotation.
+
+### Step 4 — Post-migration verification
+
+**Cosmetics** — check that a wallet known to have purchased a cosmetic still
+owns it:
+```bash
+curl -s "https://three.ws/api/cosmetics?wallet=<address>" | jq '.items | length'
+```
+
+**Payment feed** — confirm the x402 pay feed is non-empty:
+```bash
+curl -s "https://three.ws/api/x402-pay?feed=1" | jq '.feed | length'
+```
+
+**Build gallery** — verify a known agent's forge builds are visible:
+```bash
+curl -s "https://three.ws/api/builds?mint=<mint>" | jq '.builds | length'
+```
+
+### Backup strategy
+
+- Run `node scripts/migrate-redis.mjs --dry-run` monthly (or wire it to a
+ cron) to log durable key counts. A sudden drop signals data loss before
+ users notice.
+- Upstash supports point-in-time snapshots on paid plans. Enable this once
+ the store is on Pay-As-You-Go to avoid needing a migration window at all.
+- The migration window for the free plan is the first few days of each billing
+ month (when quota resets) or after a plan upgrade.
diff --git a/package.json b/package.json
index 378eb15da..1f9746dd6 100644
--- a/package.json
+++ b/package.json
@@ -91,6 +91,8 @@
"build:lib:full": "TARGET=lib LIB_FORMATS=es,umd vite build",
"build:artifact": "vite build --config vite.config.artifact.js",
"publish:lib": "node scripts/publish-lib.mjs",
+ "publish:packages": "node scripts/publish-packages.mjs",
+ "publish:packages:dry": "node scripts/publish-packages.mjs --dry-run",
"publish:mcp": "node scripts/publish-mcp-servers.mjs",
"publish:mcp:dry": "node scripts/publish-mcp-servers.mjs --dry-run",
"build:chat": "cd chat && node scripts/ensure-deps.mjs && npm run build && cd .. && mkdir -p dist/chat && cp -rf public/chat/. dist/chat/",
diff --git a/packages/pumpfun-mcp/src/tools.js b/packages/pumpfun-mcp/src/tools.js
index 2a52021be..c6d7b66e9 100644
--- a/packages/pumpfun-mcp/src/tools.js
+++ b/packages/pumpfun-mcp/src/tools.js
@@ -114,6 +114,7 @@ export const TOOL_ANNOTATIONS = Object.freeze({
kol_leaderboard: { title: 'KOL Leaderboard', ...LIVE_READ },
pumpfun_quote_swap: { title: 'Swap Quote (Read-Only)', ...LIVE_READ },
social_x_post_impact: { title: 'X Post Price Impact', ...LIVE_READ },
+ pumpfun_bot_status: { title: 'Indexer Status', ...LIVE_READ },
});
// outputSchema policy (mirrors src/pump/mcp-tools.js): only tools whose
@@ -457,6 +458,36 @@ export const FALLBACK_TOOLS = [
required: ['postUrl', 'mint'],
},
},
+ {
+ name: 'pumpfun_bot_status',
+ description:
+ 'Returns the configuration and health status of the pump.fun indexer backend. Always available — does not require PUMPFUN_BOT_URL.',
+ inputSchema: { type: 'object', properties: {}, required: [] },
+ outputSchema: {
+ type: 'object',
+ properties: {
+ configured: {
+ type: 'boolean',
+ description: 'true when PUMPFUN_BOT_URL is set on the server',
+ },
+ healthy: {
+ type: 'boolean',
+ description: 'true when the indexer answered the health ping',
+ },
+ latencyMs: {
+ type: 'number',
+ description: 'Round-trip ms of the health ping (configured backends only)',
+ },
+ error: { type: 'string', description: 'Failure reason when healthy is false' },
+ message: {
+ type: 'string',
+ description: 'Human-readable note when the indexer is unconfigured',
+ },
+ },
+ required: ['configured', 'healthy'],
+ additionalProperties: true,
+ },
+ },
];
// Stamp title + annotations onto every fallback tool from the map above. The
diff --git a/packages/react/.npmignore b/packages/react/.npmignore
new file mode 100644
index 000000000..10db8eee2
--- /dev/null
+++ b/packages/react/.npmignore
@@ -0,0 +1,5 @@
+# Source is shipped (src/) for sourcemap + reference; everything else excluded.
+node_modules
+vite.config.js
+.DS_Store
+*.log
diff --git a/packages/react/README.md b/packages/react/README.md
new file mode 100644
index 000000000..2a3073024
--- /dev/null
+++ b/packages/react/README.md
@@ -0,0 +1,121 @@
+# @three-ws/react
+
+React components for embedding [three.ws](https://three.ws) 3D AI agents. Drop a
+walking 3D avatar into any React app in two lines — no Three.js, no WebGL setup,
+no build config. The 3D runtime lives inside three.ws and renders through a
+sandboxed iframe.
+
+```bash
+npm install @three-ws/react
+```
+
+## Quick start
+
+```jsx
+import { Agent3D } from '@three-ws/react';
+
+export default function Page() {
+ return <Agent3D agentId="your-agent-id" controls="joystick" />;
+}
+```
+
+That's it. `<Agent3D>` renders a responsive 3D viewer (default `100%` × `600px`)
+that loads your agent's avatar and lets visitors walk it around.
+
+`WalkEmbed` is exported as an alias of `Agent3D` for backwards compatibility:
+
+```jsx
+import { WalkEmbed } from '@three-ws/react';
+```
+
+## Lifecycle & imperative control
+
+```jsx
+import { useRef } from 'react';
+import { Agent3D } from '@three-ws/react';
+
+export function Avatar() {
+ const ref = useRef(null);
+
+ return (
+ <Agent3D
+ ref={ref}
+ agentId="your-agent-id"
+ controls="joystick"
+ width={480}
+ height={720}
+ onLoad={() => console.log('scene ready')}
+ onError={(err) => console.error(err)}
+ />
+ );
+}
+
+// Later, drive the live embed:
+ref.current.setMotion('walk'); // 'idle' | 'walk' | 'run'
+ref.current.setAvatar('av-1234'); // swap avatar live
+ref.current.setSpeed(1.5); // walk-speed multiplier (0.3–3)
+ref.current.narrate('Hi there!'); // speech bubble over the avatar
+ref.current.setEnvironment('studio');
+ref.current.resetPose();
+```
+
+## Props
+
+| Prop | Type | Default | Description |
+|---------------|---------------------------------------|----------------|--------------------------------------------------------|
+| `agentId` | `string` (required) | — | The three.ws agent ID — its avatar is rendered. |
+| `avatarId` | `string` | — | Override the agent's default avatar. |
+| `controls` | `"joystick" \| "keyboard" \| "none"` | `"joystick"` | Movement controls. |
+| `background` | `string` | transparent | `"transparent"` or a hex color like `"#1b1b1b"`. |
+| `environment` | `string` | `"studio"` | Environment preset. |
+| `autoplay` | `boolean` | `false` | Autoplay an idle walk loop. |
+| `ground` | `boolean` | `true` | Show the shadow ground disc. |
+| `orbit` | `boolean` | `true` | Allow orbit drag on desktop. |
+| `speed` | `number` | `1` | Walk-speed multiplier (0.3–3), applied once ready. |
+| `width` | `string \| number` | `"100%"` | Container width (number → px). |
+| `height` | `string \| number` | `"600px"` | Container height (number → px). |
+| `onLoad` | `() => void` | — | Fires when the 3D scene is ready. |
+| `onError` | `(err: Error) => void` | — | Fires on load failure. |
+| `className` | `string` | — | CSS class on the wrapper `<div>`. |
+| `style` | `React.CSSProperties` | — | Inline styles on the wrapper `<div>`. |
+| `title` | `string` | three.ws title | Accessible title for the underlying iframe. |
+
+### Imperative handle (via `ref`)
+
+| Method | Description |
+|---------------------------|----------------------------------------------|
+| `sendMessage(msg)` | Post an arbitrary message to the embed. |
+| `setAvatar(id)` | Swap the rendered avatar live. |
+| `setMotion(motion)` | `"idle" \| "walk" \| "run"`. |
+| `setEnvironment(env)` | Switch the environment preset live. |
+| `setSpeed(value)` | Set the walk-speed multiplier (0.3–3). |
+| `narrate(text)` | Show a speech bubble above the avatar. |
+| `resetPose()` | Recenter the avatar on the ground. |
+| `iframe` | The underlying `HTMLIFrameElement` (or null).|
+
+## Security
+
+Inbound `postMessage` events are accepted **only** from the three.ws origin and
+**only** from this component's own iframe — messages from any other origin or
+window are ignored. This is enforced regardless of which `onLoad`/`onError`
+handlers you pass.
+
+## TypeScript
+
+Types ship with the package (`Agent3DProps`, `Agent3DHandle`, `Agent3DControls`).
+No `@types` install needed.
+
+## Requirements
+
+`react` and `react-dom` `>= 17` are peer dependencies — the package never bundles
+its own React.
+
+## Links
+
+- Full docs: <https://three.ws/docs>
+- Live embed configurator: <https://three.ws/embed/walk>
+- Live player: <https://three.ws/walk-embed>
+
+## License
+
+MIT © three.ws
diff --git a/packages/react/package-lock.json b/packages/react/package-lock.json
new file mode 100644
index 000000000..f731134c1
--- /dev/null
+++ b/packages/react/package-lock.json
@@ -0,0 +1,1688 @@
+{
+ "name": "@three-ws/react",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "@three-ws/react",
+ "version": "1.0.0",
+ "license": "MIT",
+ "devDependencies": {
+ "@vitejs/plugin-react": "^4.0.0",
+ "react": "^18.0.0",
+ "react-dom": "^18.0.0",
+ "vite": "^5.0.0"
+ },
+ "peerDependencies": {
+ "react": ">=17.0.0",
+ "react-dom": ">=17.0.0"
+ }
+ },
+ "node_modules/@babel/code-frame": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",
+ "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/helper-validator-identifier": "^7.29.7",
+ "js-tokens": "^4.0.0",
+ "picocolors": "^1.1.1"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/compat-data": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz",
+ "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/core": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz",
+ "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/code-frame": "^7.29.7",
+ "@babel/generator": "^7.29.7",
+ "@babel/helper-compilation-targets": "^7.29.7",
+ "@babel/helper-module-transforms": "^7.29.7",
+ "@babel/helpers": "^7.29.7",
+ "@babel/parser": "^7.29.7",
+ "@babel/template": "^7.29.7",
+ "@babel/traverse": "^7.29.7",
+ "@babel/types": "^7.29.7",
+ "@jridgewell/remapping": "^2.3.5",
+ "convert-source-map": "^2.0.0",
+ "debug": "^4.1.0",
+ "gensync": "^1.0.0-beta.2",
+ "json5": "^2.2.3",
+ "semver": "^6.3.1"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/babel"
+ }
+ },
+ "node_modules/@babel/generator": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.7.tgz",
+ "integrity": "sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/parser": "^7.29.7",
+ "@babel/types": "^7.29.7",
+ "@jridgewell/gen-mapping": "^0.3.12",
+ "@jridgewell/trace-mapping": "^0.3.28",
+ "jsesc": "^3.0.2"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-compilation-targets": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz",
+ "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/compat-data": "^7.29.7",
+ "@babel/helper-validator-option": "^7.29.7",
+ "browserslist": "^4.24.0",
+ "lru-cache": "^5.1.1",
+ "semver": "^6.3.1"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-globals": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz",
+ "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-module-imports": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz",
+ "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/traverse": "^7.29.7",
+ "@babel/types": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-module-transforms": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz",
+ "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/helper-module-imports": "^7.29.7",
+ "@babel/helper-validator-identifier": "^7.29.7",
+ "@babel/traverse": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ },
+ "peerDependencies": {
+ "@babel/core": "^7.0.0"
+ }
+ },
+ "node_modules/@babel/helper-plugin-utils": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz",
+ "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-string-parser": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz",
+ "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-validator-identifier": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
+ "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-validator-option": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz",
+ "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helpers": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz",
+ "integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/template": "^7.29.7",
+ "@babel/types": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/parser": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.7.tgz",
+ "integrity": "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/types": "^7.29.7"
+ },
+ "bin": {
+ "parser": "bin/babel-parser.js"
+ },
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@babel/plugin-transform-react-jsx-self": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.29.7.tgz",
+ "integrity": "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/helper-plugin-utils": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ },
+ "peerDependencies": {
+ "@babel/core": "^7.0.0-0"
+ }
+ },
+ "node_modules/@babel/plugin-transform-react-jsx-source": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.29.7.tgz",
+ "integrity": "sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/helper-plugin-utils": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ },
+ "peerDependencies": {
+ "@babel/core": "^7.0.0-0"
+ }
+ },
+ "node_modules/@babel/template": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz",
+ "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/code-frame": "^7.29.7",
+ "@babel/parser": "^7.29.7",
+ "@babel/types": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/traverse": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.7.tgz",
+ "integrity": "sha512-EhlfNQtZ+NK22w5BM61ciuiq1m58ed33Wr1Xan//ZRTy6hgjnwyCffRYwzsGXdASJSUJ1guZILsErh1eQcl+zw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/code-frame": "^7.29.7",
+ "@babel/generator": "^7.29.7",
+ "@babel/helper-globals": "^7.29.7",
+ "@babel/parser": "^7.29.7",
+ "@babel/template": "^7.29.7",
+ "@babel/types": "^7.29.7",
+ "debug": "^4.3.1"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/types": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.7.tgz",
+ "integrity": "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/helper-string-parser": "^7.29.7",
+ "@babel/helper-validator-identifier": "^7.29.7"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",
+ "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz",
+ "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz",
+ "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz",
+ "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz",
+ "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz",
+ "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz",
+ "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz",
+ "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz",
+ "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz",
+ "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz",
+ "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz",
+ "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz",
+ "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz",
+ "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz",
+ "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz",
+ "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz",
+ "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz",
+ "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz",
+ "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz",
+ "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz",
+ "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz",
+ "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz",
+ "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@jridgewell/gen-mapping": {
+ "version": "0.3.13",
+ "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
+ "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.0",
+ "@jridgewell/trace-mapping": "^0.3.24"
+ }
+ },
+ "node_modules/@jridgewell/remapping": {
+ "version": "2.3.5",
+ "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz",
+ "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/gen-mapping": "^0.3.5",
+ "@jridgewell/trace-mapping": "^0.3.24"
+ }
+ },
+ "node_modules/@jridgewell/resolve-uri": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@jridgewell/sourcemap-codec": {
+ "version": "1.5.5",
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
+ "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@jridgewell/trace-mapping": {
+ "version": "0.3.31",
+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
+ "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/resolve-uri": "^3.1.0",
+ "@jridgewell/sourcemap-codec": "^1.4.14"
+ }
+ },
+ "node_modules/@rolldown/pluginutils": {
+ "version": "1.0.0-beta.27",
+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.27.tgz",
+ "integrity": "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@rollup/rollup-android-arm-eabi": {
+ "version": "4.62.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.62.0.tgz",
+ "integrity": "sha512-IPIQ55ythEHkfEd9jMEi32OQ7SxURsGA43JI22lj01OLZNt2NUbJX8YUHxkVWyQ6daHPNn0truF5nSj3DQp6YQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ]
+ },
+ "node_modules/@rollup/rollup-android-arm64": {
+ "version": "4.62.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.62.0.tgz",
+ "integrity": "sha512-M6s9cr10MibETyo8JsOkq+Lo1+lU6hcvb1MApnUql5qte/5hMEgzlN8/ReIKNfRV8rrqX50W1BX9zoUhC192RA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ]
+ },
+ "node_modules/@rollup/rollup-darwin-arm64": {
+ "version": "4.62.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.62.0.tgz",
+ "integrity": "sha512-BqCoMoIbn0keKys+dEAdBa70EtOwV1bEsQCUgU9FdiZmmMge/Zk7LlkYGqbrdHR+Frnt0E1FOanly+rlwvvQzw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@rollup/rollup-darwin-x64": {
+ "version": "4.62.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.62.0.tgz",
+ "integrity": "sha512-SIMzST3VFNXDAbeIWDWiFCNM5qncUBDWaEV7NfE7oZbDt2mgfW4MvbKdbYiGOLoM32gbTv608UMd0XktEYSD7w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@rollup/rollup-freebsd-arm64": {
+ "version": "4.62.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.62.0.tgz",
+ "integrity": "sha512-ezjfSQMP7ArdUsbBwbQIfwAlhE84I2iVnzQNCFSveqV42q+BmKlzVpf7mxv5EchLcoWU4y6/heFzVg1F+hodUQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-freebsd-x64": {
+ "version": "4.62.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.62.0.tgz",
+ "integrity": "sha512-9+qTWGW9AZRhnUgwtTwzNwcPlL87ngkeN0LA+q1bADvmY9aNvWaF2TFW8BZgnQPYxpDI7+rMVLivcd4V737TAQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm-gnueabihf": {
+ "version": "4.62.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.62.0.tgz",
+ "integrity": "sha512-T1dMEQhXA/jkJ/jyMIw9IovK8bSUq7A8kLIlvZTb/6YIVsp2zLavr4F3oyllHWo7eIVJRyE5n3tUjQJEbE1IuQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm-musleabihf": {
+ "version": "4.62.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.62.0.tgz",
+ "integrity": "sha512-2as0LgT7qQpyceQq6VUJYnumUMUrgGQCWIiDIN9DE0/tglsk6o66uCB4f3djRawAltvfCNLyZZrsqbPA6inCsA==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm64-gnu": {
+ "version": "4.62.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.62.0.tgz",
+ "integrity": "sha512-bVURMg+6eNN9C/yc0aVjooZcwTTtYF4YW3xta5pP0//r3o1V8gXEHXWCndj47w/HhwsFroZrFhR+6uQP5T0n0g==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm64-musl": {
+ "version": "4.62.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.62.0.tgz",
+ "integrity": "sha512-Ful8pM/2yYI83PViWdFdpZhdI8HJ5qsXANe5atypbHDf+KIBBDsZsbyy8hbXnULVvW9NsTh5DHwbcBftyLTfiw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-loong64-gnu": {
+ "version": "4.62.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.62.0.tgz",
+ "integrity": "sha512-9Gp/DgrkzfUBmNPVTyPTvay+4xEP7M/clXpj3efXBcm6uTIVIgDg4rqUpqKXvLEuFRVuEpSAOkhgNeecvaZ4Cg==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-loong64-musl": {
+ "version": "4.62.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.62.0.tgz",
+ "integrity": "sha512-m9tsJz54LUXkSYM8+8PG81B9IKK5r+2T0clMq4QrS16xFosufU7firBDAZEsDheDs7wTlP7h3++S7lMsU955HA==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-ppc64-gnu": {
+ "version": "4.62.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.62.0.tgz",
+ "integrity": "sha512-3UvJ5PNVU16aJf6M3tFI24pWzAl2/ynfbyRN3ICyQajK1lSkrnVYNnLz3v04J32qKa0FczJc22zeToc0lr2A3w==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-ppc64-musl": {
+ "version": "4.62.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.62.0.tgz",
+ "integrity": "sha512-vRWUAbYLGHBZS6Q8Msb2sfnf1fvJf+47t8l/TwOerM2qArzy+IeNMTHrYLHXh95h8MoatPHI5hhSZNs+mGXKPg==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-riscv64-gnu": {
+ "version": "4.62.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.62.0.tgz",
+ "integrity": "sha512-c00T5SYENHAt86cfW47URaP3Us5vLC/4QO7GYud1G5VNRffCwwCuBspwqYrriuJB+5m0WFzClCn9wed0FBjKvg==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-riscv64-musl": {
+ "version": "4.62.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.62.0.tgz",
+ "integrity": "sha512-krrCDilhXOwFkSkO3Wm9I/f9H0L92XHHwy2fwxjukxIbh0dem8gZqOW5Y8BsHrpJv5qwlRBV+Wl4ZFyRWhUpwg==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-s390x-gnu": {
+ "version": "4.62.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.62.0.tgz",
+ "integrity": "sha512-7pfYFSTc4/rUC/FtAI0Qp6QthDBCIi6/AuP1xYqFk5vanI6KnL5dWKP60OM/05LOsbwTmIcvr6eXC4CJuJ75IA==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-x64-gnu": {
+ "version": "4.62.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.62.0.tgz",
+ "integrity": "sha512-7SDIalKeIpG0Ifogbbdn58HmSotYMlf23K3dCJEmiVd9Fg36Vmni82iPQec27N3wY4Bvbxftkxz6vSx9OcouTg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-x64-musl": {
+ "version": "4.62.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.62.0.tgz",
+ "integrity": "sha512-eRZevouTH2i1HeAVLqJuLnt256krQkGY0TN6WsTmsIhuzbh457HuWDMakKwmi0Cjadux983CoSr8Lim2QhUIFw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-openbsd-x64": {
+ "version": "4.62.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.62.0.tgz",
+ "integrity": "sha512-3oVS7FLGa4U1qcvao9ylGxrjXZyUQqR8UwxEcnUEyPX53O/C/mKDZegNXTdHCP+h3e6ta/f1EN38Yif1mmZHYg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-openharmony-arm64": {
+ "version": "4.62.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.62.0.tgz",
+ "integrity": "sha512-yTB9TgfWj5wHe5QgktAgXTLLot1gvEjl1NiPPAUiCs4oPrIWFl5V4nC3GrkNdj9LaAU4s94nVrGbGOCqUpyWsg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-arm64-msvc": {
+ "version": "4.62.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.62.0.tgz",
+ "integrity": "sha512-5LOhoaesY3doG1c+ac/2JtgREpKoJr5bUHH8tKY0V8di7+uSV6BwLs2PlR0/yzefGOkR+wE7ZolZphHCsyG5Rw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-ia32-msvc": {
+ "version": "4.62.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.62.0.tgz",
+ "integrity": "sha512-yYkWHhmbhRTWTnWos5HC4GcPQfjlzzCNbM9e/+GXrLuaBXYA3qSDR9f0Vgufd5S8yX81U8jPKp7ZnAjZFMtRnw==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-x64-gnu": {
+ "version": "4.62.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.62.0.tgz",
+ "integrity": "sha512-SoTb6lPg25xZlA2ibwQ++ahCCnH+FP0qmEuafMJ4gznZKOlXioKEAeJLgCrqjM98ACziXM9V1amFjICVL4IFoA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-x64-msvc": {
+ "version": "4.62.0",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.62.0.tgz",
+ "integrity": "sha512-5L+T1fMX4RIEBoZzT0+sQ0PhTS36NULFmMXtl1TZo44TMAROIMHbZufSOjVWt/Y622BtxgxtaNOokbTDvfsrZA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@types/babel__core": {
+ "version": "7.20.5",
+ "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
+ "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/parser": "^7.20.7",
+ "@babel/types": "^7.20.7",
+ "@types/babel__generator": "*",
+ "@types/babel__template": "*",
+ "@types/babel__traverse": "*"
+ }
+ },
+ "node_modules/@types/babel__generator": {
+ "version": "7.27.0",
+ "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz",
+ "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/types": "^7.0.0"
+ }
+ },
+ "node_modules/@types/babel__template": {
+ "version": "7.4.4",
+ "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz",
+ "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/parser": "^7.1.0",
+ "@babel/types": "^7.0.0"
+ }
+ },
+ "node_modules/@types/babel__traverse": {
+ "version": "7.28.0",
+ "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz",
+ "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/types": "^7.28.2"
+ }
+ },
+ "node_modules/@types/estree": {
+ "version": "1.0.9",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
+ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@vitejs/plugin-react": {
+ "version": "4.7.0",
+ "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.7.0.tgz",
+ "integrity": "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@babel/core": "^7.28.0",
+ "@babel/plugin-transform-react-jsx-self": "^7.27.1",
+ "@babel/plugin-transform-react-jsx-source": "^7.27.1",
+ "@rolldown/pluginutils": "1.0.0-beta.27",
+ "@types/babel__core": "^7.20.5",
+ "react-refresh": "^0.17.0"
+ },
+ "engines": {
+ "node": "^14.18.0 || >=16.0.0"
+ },
+ "peerDependencies": {
+ "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"
+ }
+ },
+ "node_modules/baseline-browser-mapping": {
+ "version": "2.10.37",
+ "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.37.tgz",
+ "integrity": "sha512-girxaJ7WZssDOFhzCGZTDKoTa1gk6A1TbflaYTpykLJ4UU9Fz9kx1aREM8JCuoVHbL8X8T/mJg7w2oYSq72Oig==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "baseline-browser-mapping": "dist/cli.cjs"
+ },
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/browserslist": {
+ "version": "4.28.2",
+ "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.2.tgz",
+ "integrity": "sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/browserslist"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/browserslist"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "baseline-browser-mapping": "^2.10.12",
+ "caniuse-lite": "^1.0.30001782",
+ "electron-to-chromium": "^1.5.328",
+ "node-releases": "^2.0.36",
+ "update-browserslist-db": "^1.2.3"
+ },
+ "bin": {
+ "browserslist": "cli.js"
+ },
+ "engines": {
+ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
+ }
+ },
+ "node_modules/caniuse-lite": {
+ "version": "1.0.30001799",
+ "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001799.tgz",
+ "integrity": "sha512-hG1bReV+OUU+MOqK4t/ZWI0tZOyz3rqS9XuhOUz1cIcbwBKjOyJEJuw9ER5JuNyqxNk8u/JUVbGibBOL1yrjFw==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/browserslist"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/caniuse-lite"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "CC-BY-4.0"
+ },
+ "node_modules/convert-source-map": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
+ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/electron-to-chromium": {
+ "version": "1.5.372",
+ "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.372.tgz",
+ "integrity": "sha512-M3yhbAlilnwqC8D21t28UCDGHyitShTmmLRU/H+b74P6Ski16Nb9HONYEaVpMj/pwC7BEo5B95FpjODLCWbtfA==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/esbuild": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz",
+ "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.21.5",
+ "@esbuild/android-arm": "0.21.5",
+ "@esbuild/android-arm64": "0.21.5",
+ "@esbuild/android-x64": "0.21.5",
+ "@esbuild/darwin-arm64": "0.21.5",
+ "@esbuild/darwin-x64": "0.21.5",
+ "@esbuild/freebsd-arm64": "0.21.5",
+ "@esbuild/freebsd-x64": "0.21.5",
+ "@esbuild/linux-arm": "0.21.5",
+ "@esbuild/linux-arm64": "0.21.5",
+ "@esbuild/linux-ia32": "0.21.5",
+ "@esbuild/linux-loong64": "0.21.5",
+ "@esbuild/linux-mips64el": "0.21.5",
+ "@esbuild/linux-ppc64": "0.21.5",
+ "@esbuild/linux-riscv64": "0.21.5",
+ "@esbuild/linux-s390x": "0.21.5",
+ "@esbuild/linux-x64": "0.21.5",
+ "@esbuild/netbsd-x64": "0.21.5",
+ "@esbuild/openbsd-x64": "0.21.5",
+ "@esbuild/sunos-x64": "0.21.5",
+ "@esbuild/win32-arm64": "0.21.5",
+ "@esbuild/win32-ia32": "0.21.5",
+ "@esbuild/win32-x64": "0.21.5"
+ }
+ },
+ "node_modules/escalade": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
+ "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/gensync": {
+ "version": "1.0.0-beta.2",
+ "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",
+ "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/js-tokens": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
+ "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/jsesc": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",
+ "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "jsesc": "bin/jsesc"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/json5": {
+ "version": "2.2.3",
+ "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz",
+ "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "json5": "lib/cli.js"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/loose-envify": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
+ "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "js-tokens": "^3.0.0 || ^4.0.0"
+ },
+ "bin": {
+ "loose-envify": "cli.js"
+ }
+ },
+ "node_modules/lru-cache": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
+ "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "yallist": "^3.0.2"
+ }
+ },
+ "node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/nanoid": {
+ "version": "3.3.12",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.12.tgz",
+ "integrity": "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/node-releases": {
+ "version": "2.0.47",
+ "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.47.tgz",
+ "integrity": "sha512-Uzmd6LXpouKo8EUK68IjH4+E01w/hXyV3R3g/geCJo+rXLNfh1xucB+LOzYEOQPSiUK3h/xZf0cQGcSsmyL2Og==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/postcss": {
+ "version": "8.5.15",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.15.tgz",
+ "integrity": "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "nanoid": "^3.3.12",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.1"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/react": {
+ "version": "18.3.1",
+ "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
+ "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "loose-envify": "^1.1.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/react-dom": {
+ "version": "18.3.1",
+ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
+ "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "loose-envify": "^1.1.0",
+ "scheduler": "^0.23.2"
+ },
+ "peerDependencies": {
+ "react": "^18.3.1"
+ }
+ },
+ "node_modules/react-refresh": {
+ "version": "0.17.0",
+ "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz",
+ "integrity": "sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/rollup": {
+ "version": "4.62.0",
+ "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.0.tgz",
+ "integrity": "sha512-nc72Wgq62I7rtDV4izT5/aaS0zxy3kttkinf9586ApknY3jZO9NYsmtc24fUckA0X7Q2v+ML4a15pdUlV5V/jA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "1.0.9"
+ },
+ "bin": {
+ "rollup": "dist/bin/rollup"
+ },
+ "engines": {
+ "node": ">=18.0.0",
+ "npm": ">=8.0.0"
+ },
+ "optionalDependencies": {
+ "@rollup/rollup-android-arm-eabi": "4.62.0",
+ "@rollup/rollup-android-arm64": "4.62.0",
+ "@rollup/rollup-darwin-arm64": "4.62.0",
+ "@rollup/rollup-darwin-x64": "4.62.0",
+ "@rollup/rollup-freebsd-arm64": "4.62.0",
+ "@rollup/rollup-freebsd-x64": "4.62.0",
+ "@rollup/rollup-linux-arm-gnueabihf": "4.62.0",
+ "@rollup/rollup-linux-arm-musleabihf": "4.62.0",
+ "@rollup/rollup-linux-arm64-gnu": "4.62.0",
+ "@rollup/rollup-linux-arm64-musl": "4.62.0",
+ "@rollup/rollup-linux-loong64-gnu": "4.62.0",
+ "@rollup/rollup-linux-loong64-musl": "4.62.0",
+ "@rollup/rollup-linux-ppc64-gnu": "4.62.0",
+ "@rollup/rollup-linux-ppc64-musl": "4.62.0",
+ "@rollup/rollup-linux-riscv64-gnu": "4.62.0",
+ "@rollup/rollup-linux-riscv64-musl": "4.62.0",
+ "@rollup/rollup-linux-s390x-gnu": "4.62.0",
+ "@rollup/rollup-linux-x64-gnu": "4.62.0",
+ "@rollup/rollup-linux-x64-musl": "4.62.0",
+ "@rollup/rollup-openbsd-x64": "4.62.0",
+ "@rollup/rollup-openharmony-arm64": "4.62.0",
+ "@rollup/rollup-win32-arm64-msvc": "4.62.0",
+ "@rollup/rollup-win32-ia32-msvc": "4.62.0",
+ "@rollup/rollup-win32-x64-gnu": "4.62.0",
+ "@rollup/rollup-win32-x64-msvc": "4.62.0",
+ "fsevents": "~2.3.2"
+ }
+ },
+ "node_modules/scheduler": {
+ "version": "0.23.2",
+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",
+ "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "loose-envify": "^1.1.0"
+ }
+ },
+ "node_modules/semver": {
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ }
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/update-browserslist-db": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",
+ "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/browserslist"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/browserslist"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "escalade": "^3.2.0",
+ "picocolors": "^1.1.1"
+ },
+ "bin": {
+ "update-browserslist-db": "cli.js"
+ },
+ "peerDependencies": {
+ "browserslist": ">= 4.21.0"
+ }
+ },
+ "node_modules/vite": {
+ "version": "5.4.21",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz",
+ "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "esbuild": "^0.21.3",
+ "postcss": "^8.4.43",
+ "rollup": "^4.20.0"
+ },
+ "bin": {
+ "vite": "bin/vite.js"
+ },
+ "engines": {
+ "node": "^18.0.0 || >=20.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/vitejs/vite?sponsor=1"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ },
+ "peerDependencies": {
+ "@types/node": "^18.0.0 || >=20.0.0",
+ "less": "*",
+ "lightningcss": "^1.21.0",
+ "sass": "*",
+ "sass-embedded": "*",
+ "stylus": "*",
+ "sugarss": "*",
+ "terser": "^5.4.0"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ },
+ "less": {
+ "optional": true
+ },
+ "lightningcss": {
+ "optional": true
+ },
+ "sass": {
+ "optional": true
+ },
+ "sass-embedded": {
+ "optional": true
+ },
+ "stylus": {
+ "optional": true
+ },
+ "sugarss": {
+ "optional": true
+ },
+ "terser": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/yallist": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
+ "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==",
+ "dev": true,
+ "license": "ISC"
+ }
+ }
+}
diff --git a/packages/react/package.json b/packages/react/package.json
new file mode 100644
index 000000000..58fdd121b
--- /dev/null
+++ b/packages/react/package.json
@@ -0,0 +1,41 @@
+{
+ "name": "@three-ws/react",
+ "version": "1.0.0",
+ "description": "React components for embedding three.ws 3D AI agents",
+ "main": "dist/index.cjs.js",
+ "module": "dist/index.esm.js",
+ "types": "dist/index.d.ts",
+ "exports": {
+ ".": {
+ "import": "./dist/index.esm.js",
+ "require": "./dist/index.cjs.js",
+ "types": "./dist/index.d.ts"
+ }
+ },
+ "files": ["dist", "src"],
+ "sideEffects": false,
+ "scripts": {
+ "build": "vite build && node -e \"require('fs').copyFileSync('src/index.d.ts','dist/index.d.ts')\"",
+ "prepublishOnly": "npm run build"
+ },
+ "peerDependencies": {
+ "react": ">=17.0.0",
+ "react-dom": ">=17.0.0"
+ },
+ "devDependencies": {
+ "react": "^18.0.0",
+ "react-dom": "^18.0.0",
+ "vite": "^5.0.0",
+ "@vitejs/plugin-react": "^4.0.0"
+ },
+ "keywords": ["three.ws", "3d", "ai-agent", "react", "embed", "avatar", "walk"],
+ "author": "three.ws <[email protected]> (https://three.ws)",
+ "homepage": "https://three.ws",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/nirholas/three.ws.git",
+ "directory": "packages/react"
+ },
+ "bugs": { "url": "https://github.com/nirholas/three.ws/issues" },
+ "license": "MIT"
+}
diff --git a/packages/react/src/Agent3D.jsx b/packages/react/src/Agent3D.jsx
new file mode 100644
index 000000000..23630b3f4
--- /dev/null
+++ b/packages/react/src/Agent3D.jsx
@@ -0,0 +1,181 @@
+import {
+ forwardRef,
+ useCallback,
+ useEffect,
+ useImperativeHandle,
+ useMemo,
+ useRef,
+} from 'react';
+
+const DEFAULT_BASE_URL = 'https://three.ws';
+
+/** Coerce a width/height prop (number → px, string passed through). */
+function toCssSize(value) {
+ if (value == null) return undefined;
+ return typeof value === 'number' ? `${value}px` : value;
+}
+
+/**
+ * Build the embed player URL from props using URL + searchParams (never string
+ * concat). Maps 1:1 to the params accepted by https://three.ws/walk-embed.
+ */
+function buildEmbedSrc({
+ baseUrl,
+ agentId,
+ avatarId,
+ controls,
+ background,
+ environment,
+ autoplay,
+ ground,
+ orbit,
+}) {
+ const url = new URL('/walk-embed', baseUrl);
+ const p = url.searchParams;
+
+ // avatarId overrides the agent's default avatar; otherwise the agent id is the avatar.
+ const avatar = avatarId || agentId;
+ if (avatar) p.set('avatar', avatar);
+ if (controls) p.set('controls', controls);
+ if (background) p.set('bg', background);
+ if (environment) p.set('env', environment);
+ if (autoplay) p.set('autoplay', 'true');
+ // Player defaults ground/orbit to ON; only emit the param to turn them off.
+ if (ground === false) p.set('ground', 'false');
+ if (orbit === false) p.set('orbit', 'false');
+
+ return url.toString();
+}
+
+/**
+ * <Agent3D> — embeds a three.ws walking 3D AI agent via a sandboxed iframe.
+ *
+ * The 3D runtime (Three.js / WebGL) lives inside three.ws; this component is a
+ * thin, dependency-free wrapper around the embed player and its postMessage
+ * protocol. Also exported as <WalkEmbed>.
+ */
+const Agent3D = forwardRef(function Agent3D(
+ {
+ agentId,
+ avatarId,
+ controls = 'joystick',
+ background,
+ environment,
+ autoplay,
+ ground,
+ orbit,
+ speed,
+ width = '100%',
+ height = '600px',
+ baseUrl = DEFAULT_BASE_URL,
+ onLoad,
+ onError,
+ className,
+ style,
+ title = 'three.ws 3D agent',
+ ...rest
+ },
+ ref,
+) {
+ const iframeRef = useRef(null);
+
+ const src = useMemo(
+ () =>
+ buildEmbedSrc({
+ baseUrl,
+ agentId,
+ avatarId,
+ controls,
+ background,
+ environment,
+ autoplay,
+ ground,
+ orbit,
+ }),
+ [baseUrl, agentId, avatarId, controls, background, environment, autoplay, ground, orbit],
+ );
+
+ // The only origin we trust for inbound messages — derived from the embed URL.
+ const targetOrigin = useMemo(() => new URL(src).origin, [src]);
+
+ const post = useCallback(
+ (msg) => {
+ iframeRef.current?.contentWindow?.postMessage(msg, targetOrigin);
+ },
+ [targetOrigin],
+ );
+
+ // Imperative handle: drive the live embed from the host app.
+ useImperativeHandle(
+ ref,
+ () => ({
+ sendMessage: (msg) => post(msg),
+ setAvatar: (id) => post({ type: 'walk:setAvatar', id }),
+ setMotion: (motion) => post({ type: 'walk:setMotion', motion }),
+ setEnvironment: (env) => post({ type: 'walk:setEnv', env }),
+ setSpeed: (value) => post({ type: 'walk:config', speed: value }),
+ narrate: (text) => post({ type: 'walk:narrate', text }),
+ resetPose: () => post({ type: 'walk:resetPose' }),
+ get iframe() {
+ return iframeRef.current;
+ },
+ }),
+ [post],
+ );
+
+ // Latest-callback refs so the message listener never goes stale and we don't
+ // re-bind it on every render.
+ const onLoadRef = useRef(onLoad);
+ const onErrorRef = useRef(onError);
+ onLoadRef.current = onLoad;
+ onErrorRef.current = onError;
+
+ useEffect(() => {
+ function handleMessage(event) {
+ // Strictly reject any origin that isn't the embed origin (XSS guard), and
+ // ignore messages that didn't come from our own iframe.
+ if (event.origin !== targetOrigin) return;
+ if (iframeRef.current && event.source !== iframeRef.current.contentWindow) return;
+
+ const data = event.data;
+ if (!data || typeof data !== 'object') return;
+
+ if (data.type === 'walk:ready') {
+ if (typeof speed === 'number') post({ type: 'walk:config', speed });
+ onLoadRef.current?.();
+ } else if (data.type === 'walk:error') {
+ onErrorRef.current?.(new Error(data.error || 'three.ws embed failed to load'));
+ }
+ }
+
+ window.addEventListener('message', handleMessage);
+ return () => window.removeEventListener('message', handleMessage);
+ }, [targetOrigin, speed, post]);
+
+ const wrapperStyle = {
+ position: 'relative',
+ width: toCssSize(width),
+ height: toCssSize(height),
+ ...style,
+ };
+
+ return (
+ <div className={className} style={wrapperStyle} {...rest}>
+ <iframe
+ ref={iframeRef}
+ src={src}
+ title={title}
+ allow="xr-spatial-tracking; microphone; camera; autoplay"
+ loading="lazy"
+ style={{
+ display: 'block',
+ width: '100%',
+ height: '100%',
+ border: 0,
+ }}
+ />
+ </div>
+ );
+});
+
+export { Agent3D };
diff --git a/packages/react/src/index.d.ts b/packages/react/src/index.d.ts
new file mode 100644
index 000000000..67bb44a1f
--- /dev/null
+++ b/packages/react/src/index.d.ts
@@ -0,0 +1,67 @@
+import type * as React from 'react';
+
+export type Agent3DControls = 'joystick' | 'keyboard' | 'none';
+
+export interface Agent3DProps {
+ /** The three.ws agent ID. Used as the avatar to render unless `avatarId` is set. */
+ agentId: string;
+ /** Override the agent's default avatar with a specific avatar ID. */
+ avatarId?: string;
+ /** Movement controls. Defaults to `"joystick"`. */
+ controls?: Agent3DControls;
+ /** Background: `"transparent"` or a hex color like `"#1b1b1b"`. */
+ background?: string;
+ /** Environment preset (e.g. `"studio"`). */
+ environment?: string;
+ /** Autoplay an idle walk loop. */
+ autoplay?: boolean;
+ /** Show the shadow ground disc. Defaults to `true`. */
+ ground?: boolean;
+ /** Allow orbit drag on desktop. Defaults to `true`. */
+ orbit?: boolean;
+ /** Walk-speed multiplier (0.3–3). Applied live once the scene is ready. */
+ speed?: number;
+ /** Container width. Number is treated as px. Defaults to `"100%"`. */
+ width?: string | number;
+ /** Container height. Number is treated as px. Defaults to `"600px"`. */
+ height?: string | number;
+ /** Override the embed origin (advanced / self-host). Defaults to `https://three.ws`. */
+ baseUrl?: string;
+ /** Fires when the 3D scene is ready. */
+ onLoad?: () => void;
+ /** Fires on load failure. */
+ onError?: (err: Error) => void;
+ /** CSS class on the wrapper `<div>`. */
+ className?: string;
+ /** Inline styles on the wrapper `<div>`. */
+ style?: React.CSSProperties;
+ /** Accessible title for the underlying iframe. */
+ title?: string;
+}
+
+/** Imperative handle exposed via `ref` for driving the live embed. */
+export interface Agent3DHandle {
+ /** Post an arbitrary message to the embed (advanced). */
+ sendMessage: (msg: unknown) => void;
+ /** Swap the rendered avatar live. */
+ setAvatar: (id: string) => void;
+ /** Set motion: `"idle" | "walk" | "run"`. */
+ setMotion: (motion: 'idle' | 'walk' | 'run') => void;
+ /** Switch the environment preset live. */
+ setEnvironment: (env: string) => void;
+ /** Set the walk-speed multiplier live (0.3–3). */
+ setSpeed: (value: number) => void;
+ /** Show a speech bubble above the avatar. */
+ narrate: (text: string) => void;
+ /** Recenter the avatar on the ground. */
+ resetPose: () => void;
+ /** The underlying iframe element, if mounted. */
+ readonly iframe: HTMLIFrameElement | null;
+}
+
+export declare const Agent3D: React.ForwardRefExoticComponent<
+ Agent3DProps & React.RefAttributes<Agent3DHandle>
+>;
+
+/** Alias for {@link Agent3D} — matches existing three.ws embed snippets. */
+export declare const WalkEmbed: typeof Agent3D;
diff --git a/packages/react/src/index.js b/packages/react/src/index.js
new file mode 100644
index 000000000..a4296b854
--- /dev/null
+++ b/packages/react/src/index.js
@@ -0,0 +1,2 @@
+export { Agent3D } from './Agent3D.jsx';
+export { Agent3D as WalkEmbed } from './Agent3D.jsx'; // alias — matches existing embed snippets
diff --git a/packages/react/vite.config.js b/packages/react/vite.config.js
new file mode 100644
index 000000000..39e29722b
--- /dev/null
+++ b/packages/react/vite.config.js
@@ -0,0 +1,21 @@
+import { defineConfig } from 'vite';
+import react from '@vitejs/plugin-react';
+import { resolve } from 'path';
+
+export default defineConfig({
+ plugins: [react()],
+ build: {
+ lib: {
+ entry: resolve(__dirname, 'src/index.js'),
+ name: 'ThreeWSReact',
+ formats: ['es', 'cjs'],
+ fileName: (format) => `index.${format === 'es' ? 'esm' : 'cjs'}.js`,
+ },
+ rollupOptions: {
+ external: ['react', 'react-dom', 'react/jsx-runtime'],
+ output: {
+ globals: { react: 'React', 'react-dom': 'ReactDOM' },
+ },
+ },
+ },
+});
diff --git a/packages/x402-fetch/.gitignore b/packages/x402-fetch/.gitignore
new file mode 100644
index 000000000..746087d37
--- /dev/null
+++ b/packages/x402-fetch/.gitignore
@@ -0,0 +1,3 @@
+dist/
+node_modules/
+*.log
diff --git a/packages/x402-fetch/.npmignore b/packages/x402-fetch/.npmignore
new file mode 100644
index 000000000..1e93c7a5d
--- /dev/null
+++ b/packages/x402-fetch/.npmignore
@@ -0,0 +1,6 @@
+tests/
+vite.config.js
+src/*.js
+src/crypto/
+.gitignore
+*.log
diff --git a/packages/x402-fetch/LICENSE b/packages/x402-fetch/LICENSE
new file mode 100644
index 000000000..bbb838721
--- /dev/null
+++ b/packages/x402-fetch/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 three.ws
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/packages/x402-fetch/README.md b/packages/x402-fetch/README.md
new file mode 100644
index 000000000..1a5da2c07
--- /dev/null
+++ b/packages/x402-fetch/README.md
@@ -0,0 +1,99 @@
+# @three-ws/x402-fetch
+
+A drop-in `fetch` that silently answers [x402](https://x402.org) payment
+challenges. Wrap a wallet once, then call any paid [three.ws](https://three.ws)
+(or CDP-x402 / agentic.market) endpoint as if it were free.
+
+```bash
+npm install @three-ws/x402-fetch
+```
+
+- **Zero production dependencies.** The secp256k1 / keccak256 / EIP-712 signing
+ stack is inlined — no `viem`, `ethers`, or `@wagmi/core` pulled into your bundle.
+- **Works in the browser and Node.** MetaMask / EIP-1193 providers, the three.ws
+ agent SDK wallet, or a raw private key all work.
+- **Safe by default.** A `maxPaymentUsd` guard refuses to auto-pay more than you
+ authorize. Descriptive errors instead of silent failures.
+- **USDC on Base.** Signs EIP-3009 `transferWithAuthorization` — the same payload
+ MetaMask's `eth_signTypedData_v4` produces, byte-for-byte.
+
+## Quick start
+
+```js
+import { withX402 } from '@three-ws/x402-fetch';
+
+// Browser: pass the injected wallet provider.
+const pay = withX402(window.ethereum, { maxPaymentUsd: 0.1 });
+
+const res = await pay('https://three.ws/api/mcp', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }),
+});
+
+const data = await res.json(); // paid + unlocked, transparently
+```
+
+On a `402 Payment Required`, the wrapper parses the challenge, selects the USDC-on-Base
+requirement, signs the authorization, and retries with the `X-PAYMENT` header — all
+before your `await` resolves. Non-402 responses pass through untouched.
+
+## Wallet forms
+
+**Browser (MetaMask / any EIP-1193 provider):**
+
+```js
+withX402(window.ethereum);
+```
+
+**Node.js (private key):**
+
+```js
+import { withX402 } from '@three-ws/x402-fetch';
+import { privateKeyToWallet } from '@three-ws/x402-fetch/wallet';
+
+const pay = withX402(privateKeyToWallet(process.env.WALLET_PRIVATE_KEY));
+```
+
+**Pre-built signer (three.ws agent SDK / viem account):**
+
+```js
+withX402({ address, signTypedData });
+```
+
+## Options
+
+```js
+withX402(wallet, {
+ maxPaymentUsd: 1.0, // refuse to auto-pay more than this per request (default 0.10)
+ onPayment: ({ amount, to, requestUrl }) => console.log(`paying $${amount} to ${to}`),
+ timeout: 30000, // ms to wait for payment authorization (default 15000)
+ network: 'eip155:8453', // prefer a specific CAIP-2 network from accepts[]
+});
+```
+
+`maxPaymentUsd` is a hard guard: a challenge above the limit throws rather than
+paying, so a misconfigured or hostile server can never silently overcharge you.
+
+## Compatibility alias
+
+For parity with the upstream `x402-fetch` package, `wrapFetchWithPayment` is
+exported with the fetch-first signature:
+
+```js
+import { wrapFetchWithPayment } from '@three-ws/x402-fetch';
+const pay = wrapFetchWithPayment(fetch, wallet);
+```
+
+## Errors
+
+| Message | Meaning |
+| --- | --- |
+| `no supported network/asset was found in accepts[]` | The server only offered networks/assets this wrapper can't sign (it signs USDC on Base / EVM EIP-3009). |
+| `payment of $X exceeds maxPaymentUsd limit` | The challenge asked for more than your authorized ceiling. |
+| `user rejected payment` | The wallet user cancelled the signature. |
+| `payment submitted but server still returned 402` | The retry was still gated — usually an amount/recipient mismatch. |
+
+## License
+
+MIT © three.ws
diff --git a/packages/x402-fetch/package.json b/packages/x402-fetch/package.json
new file mode 100644
index 000000000..8c9c66e0a
--- /dev/null
+++ b/packages/x402-fetch/package.json
@@ -0,0 +1,60 @@
+{
+ "name": "@three-ws/x402-fetch",
+ "version": "1.0.0",
+ "description": "Drop-in fetch wrapper that automatically pays x402 payment challenges with USDC on Base",
+ "type": "module",
+ "main": "dist/index.cjs",
+ "module": "dist/index.esm.js",
+ "types": "src/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./src/index.d.ts",
+ "import": "./dist/index.esm.js",
+ "require": "./dist/index.cjs"
+ },
+ "./wallet": {
+ "types": "./src/wallet.d.ts",
+ "import": "./dist/wallet.esm.js",
+ "require": "./dist/wallet.cjs"
+ }
+ },
+ "files": [
+ "dist",
+ "src/*.d.ts",
+ "README.md",
+ "LICENSE"
+ ],
+ "scripts": {
+ "build": "vite build",
+ "test": "node --test tests/*.test.mjs",
+ "prepublishOnly": "npm run build && npm test"
+ },
+ "dependencies": {},
+ "devDependencies": {
+ "vite": "^5.0.0"
+ },
+ "keywords": [
+ "x402",
+ "payments",
+ "fetch",
+ "usdc",
+ "base",
+ "eip-3009",
+ "agent",
+ "three.ws"
+ ],
+ "author": "nirholas <[email protected]>",
+ "homepage": "https://three.ws",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/nirholas/three.ws.git",
+ "directory": "packages/x402-fetch"
+ },
+ "bugs": {
+ "url": "https://github.com/nirholas/three.ws/issues"
+ },
+ "publishConfig": {
+ "access": "public"
+ },
+ "license": "MIT"
+}
diff --git a/packages/x402-fetch/src/client.js b/packages/x402-fetch/src/client.js
new file mode 100644
index 000000000..290a38bbf
--- /dev/null
+++ b/packages/x402-fetch/src/client.js
@@ -0,0 +1,112 @@
+// Payment client — turns a selected 402 requirement + a wallet into a signed
+// X-PAYMENT header, mirroring the wire shape the three.ws server verifies
+// (api/_lib/x402-spec.js) and the in-repo browser paywall builds
+// (public/x402-pay-core.js): an EIP-3009 transferWithAuthorization signature
+// wrapped in a v2 PaymentPayload.
+
+import { isEvmNetwork } from './parse-challenge.js';
+
+const EVM_CHAIN_IDS = {
+ 'eip155:8453': 8453,
+ 'eip155:84532': 84532,
+ 'eip155:42161': 42161,
+ 'eip155:1': 1,
+ 'eip155:10': 10,
+};
+
+function randomNonce() {
+ const arr = new Uint8Array(32);
+ (globalThis.crypto || crypto).getRandomValues(arr);
+ return '0x' + Array.from(arr, (b) => b.toString(16).padStart(2, '0')).join('');
+}
+
+function b64encode(obj) {
+ const json = JSON.stringify(obj);
+ if (typeof Buffer !== 'undefined') return Buffer.from(json, 'utf8').toString('base64');
+ return btoa(unescape(encodeURIComponent(json)));
+}
+
+/**
+ * Build EIP-3009 transferWithAuthorization typed data for a USDC payment.
+ * `nowSeconds` and `nonce` are injectable so builds are deterministic in tests.
+ */
+export function buildEip3009TypedData({ accept, payerAddress, chainId, nowSeconds, nonce }) {
+ const now = nowSeconds != null ? nowSeconds : Math.floor(Date.now() / 1000);
+ const validBefore = now + (Number(accept.maxTimeoutSeconds) || 600);
+ const domain = {
+ name: accept.extra?.name || 'USD Coin',
+ version: accept.extra?.version || '2',
+ chainId,
+ verifyingContract: accept.asset,
+ };
+ const types = {
+ EIP712Domain: [
+ { name: 'name', type: 'string' },
+ { name: 'version', type: 'string' },
+ { name: 'chainId', type: 'uint256' },
+ { name: 'verifyingContract', type: 'address' },
+ ],
+ TransferWithAuthorization: [
+ { name: 'from', type: 'address' },
+ { name: 'to', type: 'address' },
+ { name: 'value', type: 'uint256' },
+ { name: 'validAfter', type: 'uint256' },
+ { name: 'validBefore', type: 'uint256' },
+ { name: 'nonce', type: 'bytes32' },
+ ],
+ };
+ const authorization = {
+ from: payerAddress,
+ to: accept.payTo,
+ value: String(accept.amount),
+ validAfter: 0,
+ validBefore,
+ nonce: nonce || randomNonce(),
+ };
+ return {
+ typedData: { primaryType: 'TransferWithAuthorization', types, domain, message: authorization },
+ authorization,
+ };
+}
+
+/** Assemble the v2 PaymentPayload for an EVM EIP-3009 signature. */
+export function buildPaymentPayload({ accept, signature, authorization, resourceUrl }) {
+ return {
+ x402Version: 2,
+ scheme: 'exact',
+ network: accept.network,
+ resource: resourceUrl ? { url: resourceUrl, mimeType: 'application/json' } : undefined,
+ accepted: accept,
+ payload: { signature, authorization },
+ };
+}
+
+/**
+ * Sign the selected requirement and return the base64 X-PAYMENT header value.
+ * @param {{ accept: any, adapter: { getAddress: () => Promise<string>, signTypedData: (td:any)=>Promise<string> }, resourceUrl?: string, nowSeconds?: number, nonce?: string }} args
+ * @returns {Promise<string>}
+ */
+export async function createPaymentHeader({ accept, adapter, resourceUrl, nowSeconds, nonce }) {
+ if (!isEvmNetwork(accept.network)) {
+ throw new Error(
+ `x402: network "${accept.network}" is not locally signable by @three-ws/x402-fetch (EVM EIP-3009 / USDC on Base only)`,
+ );
+ }
+ const chainId = EVM_CHAIN_IDS[accept.network];
+ if (!chainId) throw new Error(`x402: unknown EVM chain for network "${accept.network}"`);
+ if (!accept.asset) throw new Error('x402: payment requirement is missing an asset address');
+
+ const payerAddress = await adapter.getAddress();
+ const { typedData, authorization } = buildEip3009TypedData({
+ accept,
+ payerAddress,
+ chainId,
+ nowSeconds,
+ nonce,
+ });
+ const signature = await adapter.signTypedData(typedData);
+ const payload = buildPaymentPayload({ accept, signature, authorization, resourceUrl });
+ return b64encode(payload);
+}
+
+export { b64encode };
diff --git a/packages/x402-fetch/src/crypto/eip712.js b/packages/x402-fetch/src/crypto/eip712.js
new file mode 100644
index 000000000..71246ea08
--- /dev/null
+++ b/packages/x402-fetch/src/crypto/eip712.js
@@ -0,0 +1,101 @@
+// EIP-712 typed structured-data hashing — pure JavaScript, zero dependencies.
+//
+// Produces the 32-byte digest that gets ECDSA-signed for an
+// `eth_signTypedData_v4` request: keccak256(0x1901 ‖ domainSeparator ‖ hashStruct(message)).
+// Only the value types the x402 EIP-3009 TransferWithAuthorization payload uses
+// are implemented (address, uintN, bool, bytesN, bytes, string) — enough to be a
+// correct general encoder for flat structs without dragging in nested-struct
+// recursion we don't need.
+
+import { keccak256 } from './keccak.js';
+import { hexToBytes, bytesToHex } from './secp256k1.js';
+
+function toBigInt(v) {
+ if (typeof v === 'bigint') return v;
+ if (typeof v === 'number') return BigInt(v);
+ if (typeof v === 'string') return v.startsWith('0x') ? BigInt(v) : BigInt(v);
+ throw new Error(`x402: cannot coerce ${typeof v} to integer`);
+}
+
+function pad32(bytes) {
+ if (bytes.length > 32) throw new Error('x402: value exceeds 32 bytes');
+ const out = new Uint8Array(32);
+ out.set(bytes, 32 - bytes.length);
+ return out;
+}
+
+function uintToBytes(v) {
+ let n = toBigInt(v);
+ const out = new Uint8Array(32);
+ for (let i = 31; i >= 0; i--) {
+ out[i] = Number(n & 0xffn);
+ n >>= 8n;
+ }
+ return out;
+}
+
+// Encode a single field value to its 32-byte EIP-712 representation.
+function encodeValue(type, value) {
+ if (type === 'string') {
+ return keccak256(new TextEncoder().encode(String(value)));
+ }
+ if (type === 'bytes') {
+ return keccak256(hexToBytes(value));
+ }
+ if (type === 'bool') {
+ return uintToBytes(value ? 1 : 0);
+ }
+ if (type === 'address') {
+ return pad32(hexToBytes(String(value).toLowerCase()));
+ }
+ if (type.startsWith('uint') || type.startsWith('int')) {
+ return uintToBytes(value);
+ }
+ if (type.startsWith('bytes')) {
+ // Fixed bytesN — left-aligned (high-order), already ≤32 bytes.
+ const bytes = hexToBytes(value);
+ const out = new Uint8Array(32);
+ out.set(bytes.slice(0, 32), 0);
+ return out;
+ }
+ throw new Error(`x402: unsupported EIP-712 type "${type}"`);
+}
+
+function encodeType(primaryType, types) {
+ const fields = types[primaryType];
+ const args = fields.map((f) => `${f.type} ${f.name}`).join(',');
+ return `${primaryType}(${args})`;
+}
+
+function typeHash(primaryType, types) {
+ return keccak256(new TextEncoder().encode(encodeType(primaryType, types)));
+}
+
+function hashStruct(primaryType, data, types) {
+ const parts = [typeHash(primaryType, types)];
+ for (const field of types[primaryType]) {
+ parts.push(encodeValue(field.type, data[field.name]));
+ }
+ const encoded = new Uint8Array(parts.length * 32);
+ parts.forEach((p, i) => encoded.set(p, i * 32));
+ return keccak256(encoded);
+}
+
+/**
+ * Compute the EIP-712 signing digest for a typed-data object of the shape
+ * `{ domain, types, primaryType, message }` (the same object passed to
+ * `eth_signTypedData_v4`).
+ * @returns {Uint8Array} 32-byte digest
+ */
+export function eip712Digest({ domain, types, primaryType, message }) {
+ const domainSeparator = hashStruct('EIP712Domain', domain, types);
+ const structHash = hashStruct(primaryType, message, types);
+ const prefixed = new Uint8Array(2 + 32 + 32);
+ prefixed[0] = 0x19;
+ prefixed[1] = 0x01;
+ prefixed.set(domainSeparator, 2);
+ prefixed.set(structHash, 34);
+ return keccak256(prefixed);
+}
+
+export { bytesToHex };
diff --git a/packages/x402-fetch/src/crypto/keccak.js b/packages/x402-fetch/src/crypto/keccak.js
new file mode 100644
index 000000000..ecdc582ef
--- /dev/null
+++ b/packages/x402-fetch/src/crypto/keccak.js
@@ -0,0 +1,110 @@
+// Keccak-256 (the hash Ethereum uses — NOT FIPS-202 SHA3, which differs only in
+// the domain-separation pad byte). Pure JavaScript, zero dependencies.
+//
+// Implemented with BigInt lanes for legibility and correctness over raw speed:
+// the only inputs we hash are 32-byte EIP-712 digests and 64-byte public keys,
+// so the BigInt overhead is irrelevant and a hand-unrolled uint32 variant would
+// only add risk. Verified against the canonical empty-input vector
+// (keccak256("") = c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470).
+
+const MASK64 = (1n << 64n) - 1n;
+
+// Round constants for Keccak-f[1600] (24 rounds).
+const RC = [
+ 0x0000000000000001n, 0x0000000000008082n, 0x800000000000808an, 0x8000000080008000n,
+ 0x000000000000808bn, 0x0000000080000001n, 0x8000000080008081n, 0x8000000000008009n,
+ 0x000000000000008an, 0x0000000000000088n, 0x0000000080008009n, 0x000000008000000an,
+ 0x000000008000808bn, 0x800000000000008bn, 0x8000000000008089n, 0x8000000000008003n,
+ 0x8000000000008002n, 0x8000000000000080n, 0x000000000000800an, 0x800000008000000an,
+ 0x8000000080008081n, 0x8000000000008080n, 0x0000000080000001n, 0x8000000080008008n,
+];
+
+// Rotation offsets ρ, indexed by lane position x + 5*y.
+const ROT = [
+ 0n, 1n, 62n, 28n, 27n,
+ 36n, 44n, 6n, 55n, 20n,
+ 3n, 10n, 43n, 25n, 39n,
+ 41n, 45n, 15n, 21n, 8n,
+ 18n, 2n, 61n, 56n, 14n,
+];
+
+function rotl(x, n) {
+ if (n === 0n) return x & MASK64;
+ return ((x << n) | (x >> (64n - n))) & MASK64;
+}
+
+function keccakF(state) {
+ for (let round = 0; round < 24; round++) {
+ // θ
+ const C = new Array(5);
+ for (let x = 0; x < 5; x++) {
+ C[x] = state[x] ^ state[x + 5] ^ state[x + 10] ^ state[x + 15] ^ state[x + 20];
+ }
+ const D = new Array(5);
+ for (let x = 0; x < 5; x++) {
+ D[x] = C[(x + 4) % 5] ^ rotl(C[(x + 1) % 5], 1n);
+ }
+ for (let x = 0; x < 5; x++) {
+ for (let y = 0; y < 5; y++) state[x + 5 * y] = state[x + 5 * y] ^ D[x];
+ }
+ // ρ and π
+ const B = new Array(25);
+ for (let x = 0; x < 5; x++) {
+ for (let y = 0; y < 5; y++) {
+ const idx = x + 5 * y;
+ const newX = y;
+ const newY = (2 * x + 3 * y) % 5;
+ B[newX + 5 * newY] = rotl(state[idx], ROT[idx]);
+ }
+ }
+ // χ
+ for (let x = 0; x < 5; x++) {
+ for (let y = 0; y < 5; y++) {
+ state[x + 5 * y] =
+ B[x + 5 * y] ^ (~B[((x + 1) % 5) + 5 * y] & B[((x + 2) % 5) + 5 * y]);
+ state[x + 5 * y] &= MASK64;
+ }
+ }
+ // ι
+ state[0] ^= RC[round];
+ }
+}
+
+/**
+ * Keccac-256 digest.
+ * @param {Uint8Array} input
+ * @returns {Uint8Array} 32-byte digest
+ */
+export function keccak256(input) {
+ const rate = 136; // 1088-bit rate for the 256-bit capacity variant
+ const state = new Array(25).fill(0n);
+
+ // Pad: append 0x01, zero-fill, set high bit of the final rate byte (pad10*1).
+ const padded = new Uint8Array(Math.ceil((input.length + 1) / rate) * rate);
+ padded.set(input);
+ padded[input.length] = 0x01;
+ padded[padded.length - 1] |= 0x80;
+
+ // Absorb
+ for (let offset = 0; offset < padded.length; offset += rate) {
+ for (let i = 0; i < rate / 8; i++) {
+ let lane = 0n;
+ for (let b = 0; b < 8; b++) {
+ lane |= BigInt(padded[offset + i * 8 + b]) << BigInt(8 * b);
+ }
+ state[i] ^= lane;
+ }
+ keccakF(state);
+ }
+
+ // Squeeze (single block — 32 bytes ≤ rate)
+ const out = new Uint8Array(32);
+ for (let i = 0; i < 4; i++) {
+ let lane = state[i];
+ for (let b = 0; b < 8; b++) {
+ out[i * 8 + b] = Number(lane & 0xffn);
+ lane >>= 8n;
+ }
+ }
+ return out;
+}
diff --git a/packages/x402-fetch/src/crypto/secp256k1.js b/packages/x402-fetch/src/crypto/secp256k1.js
new file mode 100644
index 000000000..2d5f5428f
--- /dev/null
+++ b/packages/x402-fetch/src/crypto/secp256k1.js
@@ -0,0 +1,202 @@
+// secp256k1 ECDSA — pure JavaScript, zero dependencies.
+//
+// Just enough of the curve to: derive an Ethereum address from a private key and
+// produce a 65-byte (r‖s‖v) recoverable signature over a 32-byte digest, with
+// RFC-6979 deterministic nonces and low-s normalisation — byte-for-byte what
+// MetaMask's eth_signTypedData_v4 and viem's signTypedData emit, so the x402
+// facilitator's ecrecover lands on the same address.
+//
+// HMAC-SHA256 (for RFC-6979) and SHA-256 come from Web Crypto (globalThis.crypto.subtle),
+// which is present in Node ≥18 and every modern browser — keeping the dependency
+// count at zero without re-implementing two more hashes by hand.
+
+import { keccak256 } from './keccak.js';
+
+const P = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn;
+const N = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;
+const Gx = 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n;
+const Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n;
+const B = 7n;
+
+function mod(a, m) {
+ const r = a % m;
+ return r >= 0n ? r : r + m;
+}
+
+// Modular inverse via the extended Euclidean algorithm.
+function invMod(a, m) {
+ a = mod(a, m);
+ let [old_r, r] = [a, m];
+ let [old_s, s] = [1n, 0n];
+ while (r !== 0n) {
+ const q = old_r / r;
+ [old_r, r] = [r, old_r - q * r];
+ [old_s, s] = [s, old_s - q * s];
+ }
+ if (old_r !== 1n) throw new Error('x402: not invertible');
+ return mod(old_s, m);
+}
+
+// Affine point arithmetic. `null` is the point at infinity.
+function pointAdd(p, q) {
+ if (p === null) return q;
+ if (q === null) return p;
+ const [x1, y1] = p;
+ const [x2, y2] = q;
+ if (x1 === x2 && mod(y1 + y2, P) === 0n) return null;
+ let m;
+ if (x1 === x2 && y1 === y2) {
+ m = mod(3n * x1 * x1 * invMod(2n * y1, P), P);
+ } else {
+ m = mod((y2 - y1) * invMod(x2 - x1, P), P);
+ }
+ const x3 = mod(m * m - x1 - x2, P);
+ const y3 = mod(m * (x1 - x3) - y1, P);
+ return [x3, y3];
+}
+
+function scalarMul(k, point) {
+ let result = null;
+ let addend = point;
+ while (k > 0n) {
+ if (k & 1n) result = pointAdd(result, addend);
+ addend = pointAdd(addend, addend);
+ k >>= 1n;
+ }
+ return result;
+}
+
+function bytesToBig(bytes) {
+ let n = 0n;
+ for (const b of bytes) n = (n << 8n) | BigInt(b);
+ return n;
+}
+
+function bigToBytes(n, length) {
+ const out = new Uint8Array(length);
+ for (let i = length - 1; i >= 0; i--) {
+ out[i] = Number(n & 0xffn);
+ n >>= 8n;
+ }
+ return out;
+}
+
+export function hexToBytes(hex) {
+ let h = hex.startsWith('0x') ? hex.slice(2) : hex;
+ if (h.length % 2) h = '0' + h;
+ const out = new Uint8Array(h.length / 2);
+ for (let i = 0; i < out.length; i++) out[i] = parseInt(h.slice(i * 2, i * 2 + 2), 16);
+ return out;
+}
+
+export function bytesToHex(bytes) {
+ let s = '0x';
+ for (const b of bytes) s += b.toString(16).padStart(2, '0');
+ return s;
+}
+
+function getSubtle() {
+ const c = globalThis.crypto;
+ if (!c || !c.subtle) {
+ throw new Error('x402: Web Crypto (crypto.subtle) is required for private-key signing');
+ }
+ return c.subtle;
+}
+
+async function hmacSha256(key, msg) {
+ const subtle = getSubtle();
+ const k = await subtle.importKey('raw', key, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
+ return new Uint8Array(await subtle.sign('HMAC', k, msg));
+}
+
+function concatBytes(...arrays) {
+ const total = arrays.reduce((n, a) => n + a.length, 0);
+ const out = new Uint8Array(total);
+ let off = 0;
+ for (const a of arrays) {
+ out.set(a, off);
+ off += a.length;
+ }
+ return out;
+}
+
+// RFC-6979 §3.2 — deterministic k generation using HMAC-SHA256.
+async function rfc6979(privKey, msgHash) {
+ const x = bigToBytes(privKey, 32);
+ const h1 = msgHash; // already a 32-byte hash, qlen == hlen == 256
+ let v = new Uint8Array(32).fill(1);
+ let k = new Uint8Array(32).fill(0);
+ k = await hmacSha256(k, concatBytes(v, new Uint8Array([0]), x, h1));
+ v = await hmacSha256(k, v);
+ k = await hmacSha256(k, concatBytes(v, new Uint8Array([1]), x, h1));
+ v = await hmacSha256(k, v);
+ for (;;) {
+ v = await hmacSha256(k, v);
+ const candidate = bytesToBig(v);
+ if (candidate >= 1n && candidate < N) return candidate;
+ k = await hmacSha256(k, concatBytes(v, new Uint8Array([0])));
+ v = await hmacSha256(k, v);
+ }
+}
+
+/**
+ * Sign a 32-byte digest with a private key, returning a 65-byte recoverable
+ * signature (r‖s‖v) where v ∈ {27, 28} — the Ethereum convention.
+ * @param {Uint8Array} digest 32-byte message hash
+ * @param {bigint} privKey
+ * @returns {Promise<string>} 0x-prefixed 65-byte hex signature
+ */
+export async function signDigest(digest, privKey) {
+ const z = bytesToBig(digest);
+ for (;;) {
+ const k = await rfc6979(privKey, digest);
+ const R = scalarMul(k, [Gx, Gy]);
+ const r = mod(R[0], N);
+ if (r === 0n) continue;
+ let s = mod(invMod(k, N) * (z + r * privKey), N);
+ if (s === 0n) continue;
+ // Recovery id: low bit is R.y parity; bit 1 set when R.x overflowed N.
+ let recovery = (R[1] & 1n ? 1 : 0) | (R[0] >= N ? 2 : 0);
+ // Enforce low-s (EIP-2). Flipping s flips the y-parity, hence the recovery bit.
+ if (s > N / 2n) {
+ s = N - s;
+ recovery ^= 1;
+ }
+ const sig = concatBytes(bigToBytes(r, 32), bigToBytes(s, 32), new Uint8Array([27 + recovery]));
+ return bytesToHex(sig);
+ }
+}
+
+/** Public key (uncompressed, 64 bytes X‖Y without the 0x04 prefix) for a private key. */
+export function privateKeyToPublicKey(privKey) {
+ const Q = scalarMul(privKey, [Gx, Gy]);
+ if (!Q) throw new Error('x402: invalid private key');
+ return concatBytes(bigToBytes(Q[0], 32), bigToBytes(Q[1], 32));
+}
+
+/** Checksummed-lowercase Ethereum address (0x + 40 hex) for a private key. */
+export function privateKeyToAddress(privKey) {
+ const pub = privateKeyToPublicKey(privKey);
+ const hash = keccak256(pub);
+ return bytesToHex(hash.slice(12));
+}
+
+export function normalizePrivateKey(pk) {
+ const bytes = typeof pk === 'string' ? hexToBytes(pk) : pk;
+ if (bytes.length !== 32) throw new Error('x402: private key must be 32 bytes');
+ const n = bytesToBig(bytes);
+ if (n <= 0n || n >= N) throw new Error('x402: private key out of range');
+ return n;
+}
+
+// EIP-55 checksum casing for display addresses.
+export function toChecksumAddress(address) {
+ const addr = address.toLowerCase().replace(/^0x/, '');
+ const hash = keccak256(new TextEncoder().encode(addr));
+ let out = '0x';
+ for (let i = 0; i < addr.length; i++) {
+ const nibble = hash[i >> 1] >> (i % 2 === 0 ? 4 : 0);
+ out += (nibble & 0x8) !== 0 ? addr[i].toUpperCase() : addr[i];
+ }
+ return out;
+}
diff --git a/packages/x402-fetch/src/index.d.ts b/packages/x402-fetch/src/index.d.ts
new file mode 100644
index 000000000..b8f83e7d8
--- /dev/null
+++ b/packages/x402-fetch/src/index.d.ts
@@ -0,0 +1,62 @@
+// Type definitions for @three-ws/x402-fetch
+
+export interface EIP1193Provider {
+ request(args: { method: string; params?: unknown[] | object }): Promise<unknown>;
+}
+
+export interface TypedDataSigner {
+ address?: string;
+ account?: { address: string };
+ signTypedData(typedData: unknown): Promise<string>;
+}
+
+/**
+ * A wallet accepted by `withX402`. One of:
+ * - a 0x-prefixed private key string (Node),
+ * - an EIP-1193 provider (browser `window.ethereum`),
+ * - a pre-built signer object `{ address, signTypedData }` (three.ws SDK / viem account).
+ */
+export type Wallet = string | EIP1193Provider | TypedDataSigner;
+
+export interface X402PaymentInfo {
+ /** Amount in USD that will be paid for this request. */
+ amount: number;
+ /** Recipient address (payTo) from the selected requirement. */
+ to: string;
+ /** URL of the request being paid for. */
+ requestUrl: string;
+}
+
+export interface X402Options {
+ /** Refuse to auto-pay more than this many USD per request. Default: 0.10. */
+ maxPaymentUsd?: number;
+ /** Called immediately before signing each payment. */
+ onPayment?: (info: X402PaymentInfo) => void;
+ /** Milliseconds to wait for payment authorization before aborting. Default: 15000. */
+ timeout?: number;
+ /** Prefer this CAIP-2 network id from accepts[] (e.g. "eip155:8453"). */
+ network?: string;
+}
+
+/** Wrap a wallet into a fetch that automatically pays x402 challenges. */
+export function withX402(wallet: Wallet, options?: X402Options): typeof fetch;
+/** fetch-first convention: withX402(fetch, wallet) or withX402(fetch, { wallet, ...options }). */
+export function withX402(
+ baseFetch: typeof fetch,
+ wallet: Wallet | ({ wallet: Wallet } & X402Options),
+): typeof fetch;
+
+/** Upstream-compatible alias: wrapFetchWithPayment(fetch, wallet, options?). */
+export function wrapFetchWithPayment(
+ fetchFn: typeof fetch,
+ wallet: Wallet,
+ options?: X402Options,
+): typeof fetch;
+
+/** Build a Node signer from a raw private key (no external wallet library). */
+export function privateKeyToWallet(pk: string | Uint8Array): {
+ address: string;
+ signTypedData(typedData: unknown): Promise<string>;
+};
+
+export default withX402;
diff --git a/packages/x402-fetch/src/index.js b/packages/x402-fetch/src/index.js
new file mode 100644
index 000000000..ef2bf58fc
--- /dev/null
+++ b/packages/x402-fetch/src/index.js
@@ -0,0 +1,131 @@
+// @three-ws/x402-fetch — a drop-in `fetch` that silently answers x402 payment
+// challenges. Wrap a wallet once, then call any paid three.ws (or CDP-x402)
+// endpoint as if it were free: on a 402 the wrapper parses the challenge, signs
+// a USDC-on-Base EIP-3009 authorization, and retries with the X-PAYMENT proof.
+//
+// import { withX402 } from '@three-ws/x402-fetch';
+// const pay = withX402(wallet, { maxPaymentUsd: 0.10 });
+// const res = await pay('https://three.ws/api/mcp', { method: 'POST', body });
+//
+// Zero production dependencies — the secp256k1 / keccak256 / EIP-712 stack is
+// inlined (src/crypto/*). See README for wallet forms and options.
+
+import { adaptWallet, privateKeyToWallet } from './wallet.js';
+import { parseChallenge, selectRequirement, amountToUsd } from './parse-challenge.js';
+import { createPaymentHeader } from './client.js';
+
+const DEFAULT_MAX_PAYMENT_USD = 0.1;
+const DEFAULT_TIMEOUT_MS = 15000;
+
+// The package supports three call conventions so the generated snippets across
+// three.ws (wallet-first) and the upstream x402-fetch (fetch-first) both work:
+// withX402(wallet, options?)
+// withX402(fetch, wallet) // upstream wrapFetchWithPayment shape
+// withX402(fetch, { wallet, ...options })
+function normalizeArgs(arg1, arg2) {
+ // fetch-first: first arg is a base fetch implementation.
+ if (typeof arg1 === 'function') {
+ const baseFetch = arg1;
+ if (arg2 && typeof arg2 === 'object' && 'wallet' in arg2) {
+ const { wallet, ...options } = arg2;
+ return { baseFetch, wallet, options };
+ }
+ return { baseFetch, wallet: arg2, options: {} };
+ }
+ // wallet-first (canonical).
+ return {
+ baseFetch: globalThis.fetch?.bind(globalThis),
+ wallet: arg1,
+ options: arg2 && typeof arg2 === 'object' ? arg2 : {},
+ };
+}
+
+function withTimeout(promise, ms, label) {
+ if (!ms || ms <= 0) return promise;
+ return new Promise((resolve, reject) => {
+ const t = setTimeout(() => reject(new Error(`x402: ${label} timed out after ${ms}ms`)), ms);
+ promise.then(
+ (v) => {
+ clearTimeout(t);
+ resolve(v);
+ },
+ (e) => {
+ clearTimeout(t);
+ reject(e);
+ },
+ );
+ });
+}
+
+/**
+ * Wrap a wallet (and optionally a base fetch) into a fetch-compatible function
+ * that automatically pays x402 challenges.
+ * @returns {typeof fetch}
+ */
+export function withX402(arg1, arg2) {
+ const { baseFetch, wallet, options } = normalizeArgs(arg1, arg2);
+ if (typeof baseFetch !== 'function') {
+ throw new Error('x402: no fetch implementation available (pass one or run on a platform with global fetch)');
+ }
+ const adapter = adaptWallet(wallet);
+ const maxPaymentUsd = Number.isFinite(options.maxPaymentUsd)
+ ? options.maxPaymentUsd
+ : DEFAULT_MAX_PAYMENT_USD;
+ const timeout = Number.isFinite(options.timeout) ? options.timeout : DEFAULT_TIMEOUT_MS;
+ const onPayment = typeof options.onPayment === 'function' ? options.onPayment : null;
+ const preferNetwork = options.network || options.preferNetwork || null;
+
+ return async function paidFetch(input, init) {
+ const first = await baseFetch(input, init);
+ if (first.status !== 402) return first;
+
+ const challenge = await parseChallenge(first);
+ if (!challenge || !challenge.accepts.length) {
+ throw new Error('x402: server returned 402 but no parseable payment challenge was found');
+ }
+
+ const accept = selectRequirement(challenge.accepts, { preferNetwork });
+ if (!accept) {
+ throw new Error(
+ 'x402: server requires payment but no supported network/asset was found in accepts[]. Supported: USDC on Base mainnet.',
+ );
+ }
+
+ const usd = amountToUsd(accept);
+ if (usd > maxPaymentUsd) {
+ throw new Error(
+ `x402: payment of $${usd.toFixed(4)} exceeds maxPaymentUsd limit of $${maxPaymentUsd.toFixed(4)} — raise the limit to authorize this call`,
+ );
+ }
+
+ const requestUrl =
+ typeof input === 'string' ? input : input?.url || challenge.resource?.url || String(input);
+ const payTo = accept.payTo;
+ if (onPayment) onPayment({ amount: usd, to: payTo, requestUrl });
+
+ const xPayment = await withTimeout(
+ createPaymentHeader({ accept, adapter, resourceUrl: challenge.resource?.url || requestUrl }),
+ timeout,
+ 'payment authorization',
+ );
+
+ const retryHeaders = new Headers(init?.headers || (typeof input === 'object' ? input.headers : undefined));
+ retryHeaders.set('X-PAYMENT', xPayment);
+ const retried = await baseFetch(input, { ...init, headers: retryHeaders });
+
+ if (retried.status === 402) {
+ throw new Error(
+ 'x402: payment submitted but server still returned 402 — check payment amount and recipient',
+ );
+ }
+ return retried;
+ };
+}
+
+// Upstream-compatible alias. Always fetch-first: wrapFetchWithPayment(fetch, wallet, options?).
+export function wrapFetchWithPayment(fetchFn, wallet, options) {
+ return withX402(fetchFn, options ? { wallet, ...options } : wallet);
+}
+
+export { privateKeyToWallet };
+export default withX402;
diff --git a/packages/x402-fetch/src/parse-challenge.js b/packages/x402-fetch/src/parse-challenge.js
new file mode 100644
index 000000000..06a483cd2
--- /dev/null
+++ b/packages/x402-fetch/src/parse-challenge.js
@@ -0,0 +1,105 @@
+// Parse a 402 Payment Required response into a normalised list of payment
+// requirements. three.ws (and every CDP-x402 / agentic.market merchant) emits the
+// v2 envelope both as the JSON body and as the base64 `PAYMENT-REQUIRED` response
+// header; we read the header first (it survives an already-consumed body and a
+// non-JSON content-type) and fall back to the body.
+//
+// { x402Version: 2, error, resource: { url, ... },
+// accepts: [{ scheme, network, amount, asset, payTo, maxTimeoutSeconds, extra }],
+// extensions }
+
+// Base USDC — the asset/network this wrapper signs for locally (EIP-3009).
+export const USDC_BASE = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913';
+export const NETWORK_BASE = 'eip155:8453';
+
+function b64decodeJson(str) {
+ if (!str) return null;
+ try {
+ const json =
+ typeof Buffer !== 'undefined'
+ ? Buffer.from(str, 'base64').toString('utf8')
+ : decodeURIComponent(escape(atob(str)));
+ return JSON.parse(json);
+ } catch {
+ return null;
+ }
+}
+
+function isEvmNetwork(net) {
+ return typeof net === 'string' && net.startsWith('eip155:');
+}
+
+// EIP-3009 transferWithAuthorization is the only EVM asset-transfer method this
+// zero-dep wrapper signs. Skip Permit2 siblings (extra.assetTransferMethod ===
+// 'permit2') — signing typed data against them yields a payload the facilitator
+// rejects.
+function isEip3009Accept(accept) {
+ if (!isEvmNetwork(accept?.network)) return false;
+ if (accept.scheme && accept.scheme !== 'exact') return false;
+ const method = accept?.extra?.assetTransferMethod;
+ return !method || method === 'eip3009';
+}
+
+// Auth-hint placeholders (amount "0" / extra.authRequired) are never payable.
+function isPayable(accept) {
+ if (!accept || typeof accept !== 'object') return false;
+ if (accept.extra?.authRequired != null) return false;
+ return String(accept.amount ?? accept.maxAmountRequired ?? '') !== '0';
+}
+
+// Coerce the spec's `maxAmountRequired` alias onto `amount`.
+function normalizeAccept(accept) {
+ const amount = accept.amount ?? accept.maxAmountRequired;
+ return amount != null && accept.amount == null ? { ...accept, amount: String(amount) } : accept;
+}
+
+/**
+ * Read the challenge envelope from a 402 Response.
+ * @param {Response} response
+ * @returns {Promise<{ accepts: any[], resource: any, raw: any } | null>}
+ */
+export async function parseChallenge(response) {
+ let envelope = b64decodeJson(
+ response.headers.get('payment-required') || response.headers.get('x-payment-required'),
+ );
+ if (!envelope) {
+ const ct = response.headers.get('content-type') || '';
+ if (!ct.includes('json')) return null;
+ try {
+ envelope = await response.clone().json();
+ } catch {
+ return null;
+ }
+ }
+ const accepts = Array.isArray(envelope?.accepts)
+ ? envelope.accepts.map(normalizeAccept)
+ : [];
+ return { accepts, resource: envelope?.resource || null, raw: envelope };
+}
+
+/**
+ * Select the payment requirement this wrapper can satisfy. Prefers Base USDC
+ * (the spec target), then any other EVM EIP-3009 USDC entry.
+ * @param {any[]} accepts
+ * @param {{ preferNetwork?: string }} [opts]
+ * @returns {any | null}
+ */
+export function selectRequirement(accepts, { preferNetwork } = {}) {
+ const payable = accepts.filter((a) => isPayable(a) && isEip3009Accept(a));
+ if (!payable.length) return null;
+ if (preferNetwork) {
+ const want = payable.find((a) => a.network === preferNetwork);
+ if (want) return want;
+ }
+ const base = payable.find((a) => a.network === NETWORK_BASE);
+ return base || payable[0];
+}
+
+/** Atomic price → USD float, honouring the asset's declared decimals (default 6). */
+export function amountToUsd(accept) {
+ const decimals = Number(accept?.extra?.decimals ?? 6);
+ const atomic = Number(accept?.amount ?? 0);
+ return atomic / 10 ** decimals;
+}
+
+export { isEvmNetwork, isEip3009Accept };
diff --git a/packages/x402-fetch/src/wallet.d.ts b/packages/x402-fetch/src/wallet.d.ts
new file mode 100644
index 000000000..215550ef7
--- /dev/null
+++ b/packages/x402-fetch/src/wallet.d.ts
@@ -0,0 +1,6 @@
+// Type definitions for @three-ws/x402-fetch/wallet
+
+export function privateKeyToWallet(pk: string | Uint8Array): {
+ address: string;
+ signTypedData(typedData: unknown): Promise<string>;
+};
diff --git a/packages/x402-fetch/src/wallet.js b/packages/x402-fetch/src/wallet.js
new file mode 100644
index 000000000..4280daa7b
--- /dev/null
+++ b/packages/x402-fetch/src/wallet.js
@@ -0,0 +1,98 @@
+// Wallet adapter — normalises every accepted wallet form to one internal
+// interface: `{ address: Promise<string>, signTypedData(typedData) }` where
+// signTypedData returns a 0x-prefixed 65-byte EIP-712 signature.
+//
+// Accepted inputs:
+// 1. EIP-1193 provider (window.ethereum / any object with `.request`) — browser.
+// 2. A pre-built wallet object `{ address, signTypedData(typedData) }` —
+// the three.ws agent SDK and viem LocalAccounts both satisfy this.
+// 3. A private key (0x-hex string) via `privateKeyToWallet(pk)` — Node.
+
+import { eip712Digest } from './crypto/eip712.js';
+import {
+ signDigest,
+ normalizePrivateKey,
+ privateKeyToAddress,
+ toChecksumAddress,
+} from './crypto/secp256k1.js';
+
+function isEip1193(w) {
+ return w && typeof w === 'object' && typeof w.request === 'function';
+}
+
+/**
+ * Build a Node signer from a raw private key. Signs EIP-712 typed data locally
+ * with the inlined secp256k1 implementation — no external wallet library.
+ * @param {string|Uint8Array} pk 32-byte private key (0x-hex or bytes)
+ * @returns {{ address: string, signTypedData: (td: any) => Promise<string> }}
+ */
+export function privateKeyToWallet(pk) {
+ const key = normalizePrivateKey(pk);
+ const address = toChecksumAddress(privateKeyToAddress(key));
+ return {
+ address,
+ async signTypedData(typedData) {
+ return signDigest(eip712Digest(typedData), key);
+ },
+ };
+}
+
+// Resolve the payer address for a wallet form, prompting the EIP-1193 provider
+// for accounts when necessary.
+async function resolveAddress(wallet) {
+ if (typeof wallet === 'string') return privateKeyToWallet(wallet).address;
+ if (isEip1193(wallet)) {
+ const accounts = await wallet.request({ method: 'eth_requestAccounts' });
+ const addr = Array.isArray(accounts) ? accounts[0] : null;
+ if (!addr) throw new Error('x402: wallet returned no account');
+ return addr;
+ }
+ // Pre-built wallet object (three.ws SDK / viem LocalAccount / viem WalletClient).
+ const addr = wallet?.address || wallet?.account?.address;
+ if (!addr) throw new Error('x402: wallet object must expose an `address`');
+ return addr;
+}
+
+const USER_REJECTED = /user rejected|user denied|reject|cancell?ed|4001/i;
+
+/**
+ * Normalise any accepted wallet form into `{ getAddress(), signTypedData(td) }`.
+ * @param {any} wallet
+ */
+export function adaptWallet(wallet) {
+ if (wallet == null) throw new Error('x402: a wallet is required');
+
+ let cachedAddress = null;
+ const getAddress = async () => {
+ if (!cachedAddress) cachedAddress = await resolveAddress(wallet);
+ return cachedAddress;
+ };
+
+ const signTypedData = async (typedData) => {
+ try {
+ if (typeof wallet === 'string') {
+ return await privateKeyToWallet(wallet).signTypedData(typedData);
+ }
+ if (isEip1193(wallet)) {
+ const from = await getAddress();
+ return await wallet.request({
+ method: 'eth_signTypedData_v4',
+ params: [from, JSON.stringify(typedData)],
+ });
+ }
+ if (typeof wallet.signTypedData === 'function') {
+ // viem accounts take the typed-data object directly; the three.ws SDK
+ // wallet uses the same shape. Both resolve to a hex signature.
+ return await wallet.signTypedData(typedData);
+ }
+ throw new Error('x402: wallet does not support signTypedData');
+ } catch (err) {
+ if (USER_REJECTED.test(err?.message || String(err))) {
+ throw new Error('x402: user rejected payment');
+ }
+ throw err;
+ }
+ };
+
+ return { getAddress, signTypedData };
+}
diff --git a/packages/x402-fetch/tests/client.test.mjs b/packages/x402-fetch/tests/client.test.mjs
new file mode 100644
index 000000000..8c00c5e8c
--- /dev/null
+++ b/packages/x402-fetch/tests/client.test.mjs
@@ -0,0 +1,170 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+
+import { withX402, wrapFetchWithPayment, privateKeyToWallet } from '../src/index.js';
+
+// Deterministic Node signer — exercises the real secp256k1 / keccak256 / EIP-712
+// stack on every payment, no mock signatures.
+const WALLET = privateKeyToWallet(
+ '0x4646464646464646464646464646464646464646464646464646464646464646',
+);
+
+const USDC_BASE = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913';
+const PAY_TO = '0x1111111111111111111111111111111111111111';
+
+function baseAccept(amount) {
+ return {
+ scheme: 'exact',
+ network: 'eip155:8453',
+ amount: String(amount),
+ asset: USDC_BASE,
+ payTo: PAY_TO,
+ maxTimeoutSeconds: 60,
+ extra: { name: 'USD Coin', version: '2', decimals: 6 },
+ };
+}
+
+function challenge402(accepts, resourceUrl = 'https://three.ws/api/mcp') {
+ return new Response(
+ JSON.stringify({
+ x402Version: 2,
+ error: 'X-PAYMENT header is required',
+ resource: { url: resourceUrl, mimeType: 'application/json' },
+ accepts,
+ }),
+ { status: 402, headers: { 'content-type': 'application/json' } },
+ );
+}
+
+// Build a mock fetch that 402s until an X-PAYMENT header arrives, then returns
+// `success`. Records every call for assertions.
+function mockFetch({ accepts, success }) {
+ const calls = [];
+ const fn = async (input, init) => {
+ const headers = new Headers(init?.headers || undefined);
+ calls.push({ input, init, xPayment: headers.get('X-PAYMENT') });
+ if (headers.get('X-PAYMENT')) return success();
+ return challenge402(accepts);
+ };
+ fn.calls = calls;
+ return fn;
+}
+
+test('1. valid accepts[] triggers a payment + retry, returning the 200', async () => {
+ const fetchMock = mockFetch({
+ accepts: [baseAccept(50_000)], // $0.05
+ success: () => new Response(JSON.stringify({ ok: true, reply: 'hi' }), { status: 200 }),
+ });
+ const pay = withX402(fetchMock, { wallet: WALLET, maxPaymentUsd: 1 });
+ const res = await pay('https://three.ws/api/mcp', { method: 'POST' });
+
+ assert.equal(res.status, 200);
+ assert.deepEqual(await res.json(), { ok: true, reply: 'hi' });
+ assert.equal(fetchMock.calls.length, 2, 'one 402 + one paid retry');
+});
+
+test('2. the retried request carries a correct X-PAYMENT header', async () => {
+ const fetchMock = mockFetch({
+ accepts: [baseAccept(50_000)],
+ success: () => new Response('{}', { status: 200 }),
+ });
+ const pay = withX402(fetchMock, { wallet: WALLET, maxPaymentUsd: 1 });
+ await pay('https://three.ws/api/mcp', { method: 'POST' });
+
+ const retry = fetchMock.calls[1];
+ assert.ok(retry.xPayment, 'retry has an X-PAYMENT header');
+
+ const payload = JSON.parse(Buffer.from(retry.xPayment, 'base64').toString('utf8'));
+ assert.equal(payload.x402Version, 2);
+ assert.equal(payload.scheme, 'exact');
+ assert.equal(payload.network, 'eip155:8453');
+ assert.equal(payload.payload.authorization.to, PAY_TO);
+ assert.equal(payload.payload.authorization.value, '50000');
+ assert.equal(payload.payload.authorization.from, WALLET.address);
+ // 65-byte recoverable signature (0x + 130 hex).
+ assert.match(payload.payload.signature, /^0x[0-9a-f]{130}$/);
+});
+
+test('3. a 402 with no matching network/asset throws descriptively', async () => {
+ const solanaOnly = [
+ {
+ scheme: 'exact',
+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
+ amount: '50000',
+ asset: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ payTo: 'SoLPayToAddr1111111111111111111111111111111',
+ extra: { name: 'USDC', decimals: 6 },
+ },
+ ];
+ const fetchMock = mockFetch({ accepts: solanaOnly, success: () => new Response('{}') });
+ const pay = withX402(fetchMock, { wallet: WALLET, maxPaymentUsd: 1 });
+
+ await assert.rejects(
+ () => pay('https://three.ws/api/mcp'),
+ /no supported network\/asset was found in accepts\[\]\. Supported: USDC on Base mainnet\./,
+ );
+});
+
+test('4. maxPaymentUsd is enforced — a $5 challenge throws when the limit is $1', async () => {
+ const fetchMock = mockFetch({
+ accepts: [baseAccept(5_000_000)], // $5.00
+ success: () => new Response('{}', { status: 200 }),
+ });
+ const pay = withX402(fetchMock, { wallet: WALLET, maxPaymentUsd: 1 });
+
+ await assert.rejects(
+ () => pay('https://three.ws/api/mcp'),
+ /exceeds maxPaymentUsd limit of \$1\.0000/,
+ );
+ assert.equal(fetchMock.calls.length, 1, 'never retried — no payment signed');
+});
+
+test('5. a successful payment → 200 returns the 200 response body', async () => {
+ const fetchMock = mockFetch({
+ accepts: [baseAccept(10_000)],
+ success: () =>
+ new Response(JSON.stringify({ content: 'unlocked', tx: '0xabc' }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ }),
+ });
+ const pay = wrapFetchWithPayment(fetchMock, WALLET, { maxPaymentUsd: 1 });
+ const res = await pay('https://three.ws/api/mcp');
+
+ assert.equal(res.status, 200);
+ assert.deepEqual(await res.json(), { content: 'unlocked', tx: '0xabc' });
+});
+
+test('6. non-402 responses (200, 404, 500) pass through unchanged', async () => {
+ for (const status of [200, 404, 500]) {
+ let calls = 0;
+ const passthrough = async () => {
+ calls++;
+ return new Response(JSON.stringify({ status }), { status });
+ };
+ const pay = withX402(passthrough, { wallet: WALLET, maxPaymentUsd: 1 });
+ const res = await pay('https://three.ws/api/x');
+ assert.equal(res.status, status);
+ assert.deepEqual(await res.json(), { status });
+ assert.equal(calls, 1, `status ${status}: no payment attempt, single call`);
+ }
+});
+
+test('onPayment callback fires before signing with USD amount + recipient', async () => {
+ const seen = [];
+ const fetchMock = mockFetch({
+ accepts: [baseAccept(50_000)],
+ success: () => new Response('{}', { status: 200 }),
+ });
+ const pay = withX402(fetchMock, {
+ wallet: WALLET,
+ maxPaymentUsd: 1,
+ onPayment: (info) => seen.push(info),
+ });
+ await pay('https://three.ws/api/mcp');
+
+ assert.equal(seen.length, 1);
+ assert.equal(seen[0].amount, 0.05);
+ assert.equal(seen[0].to, PAY_TO);
+ assert.equal(seen[0].requestUrl, 'https://three.ws/api/mcp');
+});
diff --git a/packages/x402-fetch/vite.config.js b/packages/x402-fetch/vite.config.js
new file mode 100644
index 000000000..1ead18ad0
--- /dev/null
+++ b/packages/x402-fetch/vite.config.js
@@ -0,0 +1,33 @@
+import { defineConfig } from 'vite';
+
+// Two entry points (main + the /wallet subpath), each emitted as ESM and CJS.
+// Zero runtime dependencies, so nothing is externalised — the crypto core is
+// bundled in. `node:crypto` is never imported (we use Web Crypto), so there is
+// no Node built-in to mark external.
+export default defineConfig({
+ build: {
+ target: 'es2021',
+ minify: false,
+ sourcemap: true,
+ lib: {
+ entry: {
+ index: 'src/index.js',
+ wallet: 'src/wallet.js',
+ },
+ formats: ['es', 'cjs'],
+ // `.esm.js` is ESM under the package's "type": "module"; CJS uses the
+ // `.cjs` extension so Node always treats it as CommonJS regardless of
+ // the package type field.
+ fileName: (format, name) => (format === 'es' ? `${name}.esm.js` : `${name}.cjs`),
+ },
+ rollupOptions: {
+ output: {
+ // Keep the shared crypto chunk readable and deterministic.
+ chunkFileNames: 'chunks/[name].[format].js',
+ // Named CJS exports (withX402, wrapFetchWithPayment, privateKeyToWallet)
+ // without a `.default` interop wrapper.
+ exports: 'named',
+ },
+ },
+ },
+});
diff --git a/pages/embed-walk.html b/pages/embed-walk.html
index c1c081432..e2e95c129 100644
--- a/pages/embed-walk.html
+++ b/pages/embed-walk.html
@@ -407,7 +407,9 @@
</div>
<p id="framework-note" class="ew-note" style="display:none">
- Install the React wrapper: <code>npm i @three-ws/react</code> — then import <code>WalkEmbed</code> from it.
+ Install: <code>npm i @three-ws/react</code> then
+ <code>import { Agent3D } from '@three-ws/react';</code> and render
+ <code>&lt;Agent3D agentId="…" controls="joystick" /&gt;</code> — props map 1:1 to the options above.
</p>
</div>
</main>
@@ -502,10 +504,28 @@ function buildSrc() {
return `${ORIGIN}/walk-embed?${p}`;
}
+// React always uses the published @three-ws/react component, not raw embed code.
+function buildReactComponent() {
+ const props = [];
+ if (cfg.avatarId) props.push(`agentId="${cfg.avatarId}"`);
+ if (cfg.controls && cfg.controls !== 'auto') props.push(`controls="${cfg.controls}"`);
+ const bg = cfg.bgType === 'transparent' ? null : cfg.bgType === 'color' ? cfg.bgColor : '#000000';
+ if (bg) props.push(`background="${bg}"`);
+ if (cfg.speed !== 1) props.push(`speed={${cfg.speed}}`);
+ if (cfg.autoplay) props.push(`autoplay`);
+ if (cfg.ground) props.push(`ground`);
+ if (cfg.orbit) props.push(`orbit`);
+ props.push(`width={${cfg.w}}`, `height={${cfg.h}}`);
+ const indented = props.map((p) => ` ${p}`).join('\n');
+ return `import { Agent3D } from '@three-ws/react';\n\nexport function WalkAvatar() {\n return (\n <Agent3D\n${indented}\n />\n );\n}`;
+}
+
function buildSnippet(tab) {
const src = buildSrc();
const w = cfg.w, h = cfg.h;
+ if (tab === 'react') return buildReactComponent();
+
if (cfg.embedType === 'js') {
const attrs = [`src="${ORIGIN}/walk-embed-sdk.js"`];
if (cfg.avatarId) attrs.push(`data-avatar="${cfg.avatarId}"`);
@@ -518,7 +538,6 @@ function buildSnippet(tab) {
if (cfg.ground) attrs.push(`data-ground="true"`);
if (cfg.orbit) attrs.push(`data-orbit="true"`);
const tag = `<script\n ${attrs.join('\n ')}>\n<\/script>`;
- if (tab === 'react') return `import { useEffect } from 'react';\n\nexport function WalkAvatar() {\n useEffect(() => {\n const s = document.createElement('script');\n s.src = '${ORIGIN}/walk-embed-sdk.js';\n ${cfg.avatarId ? `s.dataset.avatar = '${cfg.avatarId}';\n ` : ''}s.dataset.controls = '${cfg.controls}';\n s.dataset.width = '${w}';\n s.dataset.height = '${h}';\n document.body.appendChild(s);\n return () => window.ThreeWalkAvatar?.unmount();\n }, []);\n return null;\n}`;
if (tab === 'vue') return `<!-- In your component -->\n<script setup>\nimport { onMounted, onUnmounted } from 'vue';\nonMounted(() => {\n const s = document.createElement('script');\n s.src = '${ORIGIN}/walk-embed-sdk.js';\n ${cfg.avatarId ? `s.dataset.avatar = '${cfg.avatarId}';\n ` : ''}s.dataset.controls = '${cfg.controls}';\n s.dataset.width = '${w}';\n s.dataset.height = '${h}';\n document.body.appendChild(s);\n});\nonUnmounted(() => window.ThreeWalkAvatar?.unmount());\n<\/script>`;
if (tab === 'svelte') return `<script>\n import { onMount, onDestroy } from 'svelte';\n onMount(() => {\n const s = document.createElement('script');\n s.src = '${ORIGIN}/walk-embed-sdk.js';\n ${cfg.avatarId ? `s.dataset.avatar = '${cfg.avatarId}';\n ` : ''}s.dataset.controls = '${cfg.controls}';\n s.dataset.width = '${w}';\n s.dataset.height = '${h}';\n document.body.appendChild(s);\n return () => window.ThreeWalkAvatar?.unmount();\n });\n<\/script>`;
return tag;
@@ -528,7 +547,6 @@ function buildSnippet(tab) {
const style = `border:0;border-radius:12px;max-width:100%`;
const base = `<iframe\n src="${src}"\n width="${w}"\n height="${h}"\n style="${style}"\n allow="autoplay"\n title="Walking avatar"\n loading="lazy">\n</iframe>`;
- if (tab === 'react') return `export function WalkAvatar() {\n return (\n <iframe\n src="${src}"\n width={${w}}\n height={${h}}\n style={{ border: 0, borderRadius: 12, maxWidth: '100%' }}\n allow="autoplay"\n title="Walking avatar"\n loading="lazy"\n />\n );\n}`;
if (tab === 'vue') return `<template>\n <iframe\n :src="\`${src}\`"\n :width="${w}"\n :height="${h}"\n style="border:0;border-radius:12px;max-width:100%"\n allow="autoplay"\n title="Walking avatar"\n loading="lazy"\n />\n</template>`;
if (tab === 'svelte') return `<iframe\n src="${src}"\n width="${w}"\n height="${h}"\n style="border:0;border-radius:12px;max-width:100%"\n allow="autoplay"\n title="Walking avatar"\n loading="lazy"\n/>`;
return base;
@@ -560,7 +578,7 @@ function update() {
// Snippet
const activeTab = document.querySelector('.ew-tab.active')?.dataset.tab || 'html';
snippetCode.textContent = buildSnippet(activeTab);
- frameworkNote.style.display = (activeTab !== 'html' && cfg.embedType === 'iframe') ? 'none' : (activeTab !== 'html' ? 'block' : 'none');
+ frameworkNote.style.display = activeTab === 'react' ? 'block' : 'none';
// URL state
const p = new URLSearchParams();
diff --git a/public/changelog.json b/public/changelog.json
index 98c3bdd87..28202ecd2 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-14T06:31:37.780Z",
+ "generated_at": "2026-06-14T23:36:26.646Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -16,6 +16,60 @@
"launch"
]
},
+ {
+ "date": "2026-06-14",
+ "type": "update",
+ "title": "Forge stays up: live Redis quota monitoring and early-warning alerts",
+ "summary": "The shared rate-limiter store has a hard monthly request ceiling, and when it's exhausted every paid generation and payment stops at once. We've made that failure mode impossible to sneak up on us. The forge health check (/api/forge?health) now reports the live daily request rate, how much of the budget it's burning, and projects whether it's on track to run out — and a daily check pages our ops team the moment the projection crosses 80% of the ceiling, long before anything breaks. We also moved the highest-traffic, lowest-risk traffic guards (public page reads, status polling, the notifications badge) to in-process enforcement so they no longer spend from that budget at all, cutting burn dramatically. Net effect: more headroom, and a deliberate upgrade decision instead of a surprise outage.",
+ "link": null,
+ "tags": [
+ "infra"
+ ]
+ },
+ {
+ "date": "2026-06-14",
+ "type": "update",
+ "title": "pump.fun MCP server only lists tools it can actually run",
+ "summary": "The free pump.fun MCP server (three.ws/api/pump-fun-mcp) now advertises its discovery tools — token search, trending, new, graduated, king-of-the-hill, and creator profiles — only when its real-time indexer backend is connected. Previously those six tools always appeared in the tool list and returned an error if the indexer wasn't wired, which confused MCP clients and assistants that tried to call them. They now stay hidden until the backend is live, and reappear automatically the moment it is. We also added a always-available pumpfun_bot_status tool that reports whether the indexer is configured and healthy (with round-trip latency), and an indexerEnabled flag on the server handshake so client authors can check capability in one call. On-chain tools (bonding curve, holders, token details, trades, swap quotes, fee claims) were unaffected and remain fully available with no API key.",
+ "link": null,
+ "tags": [
+ "sdk",
+ "improvement"
+ ]
+ },
+ {
+ "date": "2026-06-14",
+ "type": "update",
+ "title": "React component library for embedding 3D AI agents",
+ "summary": "npm install @three-ws/react gives you <Agent3D> — a React wrapper around the three.ws walk embed player. Drop a 3D AI agent into any React app in two lines of code, with props for controls, size, and background, plus onLoad/onError callbacks and a ref handle to drive the avatar live.",
+ "link": "/embed/walk",
+ "tags": [
+ "feature",
+ "sdk"
+ ]
+ },
+ {
+ "date": "2026-06-14",
+ "type": "update",
+ "title": "world.three.ws locked down and watched around the clock",
+ "summary": "The multiplayer world (world.three.ws) is now protected against unauthorized edits: visitors join as spectators and only a holder of the admin code can build, move, or delete anything in the scene. We also added a continuous health watch. Every 15 minutes a monitor confirms the world is still protected and checks that every asset the scene depends on is actually reachable — the exact gap that briefly dropped visitors into an empty void earlier this month, now caught and paged to our ops team before anyone notices. The forge health surface (/api/forge?health) reports the world's status alongside the generation backends, and a post-deploy gate refuses to call a deploy healthy unless the world comes back protected.",
+ "link": null,
+ "tags": [
+ "security",
+ "infra"
+ ]
+ },
+ {
+ "date": "2026-06-14",
+ "type": "update",
+ "title": "x402-fetch — automatic pay-per-call fetch wrapper",
+ "summary": "npm install @three-ws/x402-fetch gives you withX402(wallet) — a drop-in fetch wrapper that silently handles x402 payment challenges. Connect a wallet once; call any paid three.ws API like a free one. It signs USDC-on-Base payments locally with zero dependencies, refuses to overspend past a maxPaymentUsd guard you set, and works in the browser (MetaMask), in Node (private key), or with a three.ws agent wallet.",
+ "link": "/docs/sdk",
+ "tags": [
+ "feature",
+ "sdk"
+ ]
+ },
{
"date": "2026-06-13",
"type": "launch",
diff --git a/public/changelog.xml b/public/changelog.xml
index 1953d1209..e4f3cf09d 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -14,6 +14,46 @@
<category>launch</category>
<description>A live build session: from a single prompt to an interactive 3D AI agent embedded in any app, in minutes — then a live Q&amp;A. Hosted by three.ws, in partnership with IBM.</description>
</item>
+ <item>
+ <title>Forge stays up: live Redis quota monitoring and early-warning alerts</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-14:Forge stays up: live Redis quota monitoring and early-warning alerts</guid>
+ <pubDate>Sun, 14 Jun 2026 12:00:00 GMT</pubDate>
+ <category>infra</category>
+ <description>The shared rate-limiter store has a hard monthly request ceiling, and when it's exhausted every paid generation and payment stops at once. We've made that failure mode impossible to sneak up on us. The forge health check (/api/forge?health) now reports the live daily request rate, how much of the budget it's burning, and projects whether it's on track to run out — and a daily check pages our ops team the moment the projection crosses 80% of the ceiling, long before anything breaks. We also moved the highest-traffic, lowest-risk traffic guards (public page reads, status polling, the notifications badge) to in-process enforcement so they no longer spend from that budget at all, cutting burn dramatically. Net effect: more headroom, and a deliberate upgrade decision instead of a surprise outage.</description>
+ </item>
+ <item>
+ <title>pump.fun MCP server only lists tools it can actually run</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-14:pump.fun MCP server only lists tools it can actually run</guid>
+ <pubDate>Sun, 14 Jun 2026 12:00:00 GMT</pubDate>
+ <category>sdk</category>
+ <description>The free pump.fun MCP server (three.ws/api/pump-fun-mcp) now advertises its discovery tools — token search, trending, new, graduated, king-of-the-hill, and creator profiles — only when its real-time indexer backend is connected. Previously those six tools always appeared in the tool list and returned an error if the indexer wasn't wired, which confused MCP clients and assistants that tried to call them. They now stay hidden until the backend is live, and reappear automatically the moment it is. We also added a always-available pumpfun_bot_status tool that reports whether the indexer is configured and healthy (with round-trip latency), and an indexerEnabled flag on the server handshake so client authors can check capability in one call. On-chain tools (bonding curve, holders, token details, trades, swap quotes, fee claims) were unaffected and remain fully available with no API key.</description>
+ </item>
+ <item>
+ <title>React component library for embedding 3D AI agents</title>
+ <link>https://three.ws/embed/walk</link>
+ <guid isPermaLink="false">2026-06-14:React component library for embedding 3D AI agents</guid>
+ <pubDate>Sun, 14 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>npm install @three-ws/react gives you &lt;Agent3D&gt; — a React wrapper around the three.ws walk embed player. Drop a 3D AI agent into any React app in two lines of code, with props for controls, size, and background, plus onLoad/onError callbacks and a ref handle to drive the avatar live.</description>
+ </item>
+ <item>
+ <title>world.three.ws locked down and watched around the clock</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-14:world.three.ws locked down and watched around the clock</guid>
+ <pubDate>Sun, 14 Jun 2026 12:00:00 GMT</pubDate>
+ <category>security</category>
+ <description>The multiplayer world (world.three.ws) is now protected against unauthorized edits: visitors join as spectators and only a holder of the admin code can build, move, or delete anything in the scene. We also added a continuous health watch. Every 15 minutes a monitor confirms the world is still protected and checks that every asset the scene depends on is actually reachable — the exact gap that briefly dropped visitors into an empty void earlier this month, now caught and paged to our ops team before anyone notices. The forge health surface (/api/forge?health) reports the world's status alongside the generation backends, and a post-deploy gate refuses to call a deploy healthy unless the world comes back protected.</description>
+ </item>
+ <item>
+ <title>x402-fetch — automatic pay-per-call fetch wrapper</title>
+ <link>https://three.ws/docs/sdk</link>
+ <guid isPermaLink="false">2026-06-14:x402-fetch — automatic pay-per-call fetch wrapper</guid>
+ <pubDate>Sun, 14 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>npm install @three-ws/x402-fetch gives you withX402(wallet) — a drop-in fetch wrapper that silently handles x402 payment challenges. Connect a wallet once; call any paid three.ws API like a free one. It signs USDC-on-Base payments locally with zero dependencies, refuses to overspend past a maxPaymentUsd guard you set, and works in the browser (MetaMask), in Node (private key), or with a three.ws agent wallet.</description>
+ </item>
<item>
<title>AR &amp; WebXR — Place Any 3D Agent in Your Real World</title>
<link>https://three.ws/features/ar</link>
diff --git a/public/features.json b/public/features.json
index 2c6879e75..65f2e22bc 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-14T06:31:37.771Z",
+ "generated_at": "2026-06-14T23:36:26.626Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 4dfe8802e..3e7c516cc 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -56,20 +56,6 @@
.sm-brand img { width: 24px; height: 24px; border-radius: 5px; }
.sm-brand:hover { text-decoration: none; }
</style>
-
- <meta property="og:type" content="website">
- <meta property="og:site_name" content="three.ws">
- <meta property="og:title" content="Sitemap · three.ws">
- <meta property="og:description" content="Human-readable index of every page on three.ws.">
- <meta property="og:url" content="https://three.ws/sitemap">
- <meta property="og:image" content="https://three.ws/og-image.png">
- <meta property="og:image:width" content="1200">
- <meta property="og:image:height" content="630">
- <meta name="twitter:card" content="summary_large_image">
- <meta name="twitter:title" content="Sitemap · three.ws">
- <meta name="twitter:description" content="Human-readable index of every page on three.ws.">
- <meta name="twitter:image" content="https://three.ws/og-image.png">
- <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Sitemap","description":"Human-readable index of every page on three.ws.","url":"https://three.ws/sitemap","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
</head>
<body>
<header class="sm-topbar">
diff --git a/scripts/devnet-smoke-trade.mjs b/scripts/devnet-smoke-trade.mjs
new file mode 100644
index 000000000..32e0bef5f
--- /dev/null
+++ b/scripts/devnet-smoke-trade.mjs
@@ -0,0 +1,253 @@
+#!/usr/bin/env node
+// Devnet smoke trade — real bonding-curve buy + sell against the pump.fun
+// program on Solana devnet.
+//
+// Purpose: verify on-chain the GAP-1 fix from
+// docs/pumpfun-program/AUDIT-2026-06-11.md — curve buys used to send
+// `amount: new BN(0)` to the bonding curve, so they could never execute. This
+// script drives the SAME production helpers the fixed dispatcher buy-prep /
+// sell-prep handlers use (getPumpSdk, slippagePercentFromBps,
+// resolveTokenProgramForMintOwner, buyV2Instructions / sellV2Instructions with
+// a real getBuyTokenAmountFromSolAmount / getSellSolAmountFromTokenAmount),
+// signs the transactions with a funded devnet keypair, and submits them.
+//
+// It does three things end to end:
+// 1. (optional) creates a fresh create_v2 bonding-curve token on devnet,
+// 2. buys ~0.01 SOL of it on the curve (buy_v2 — the path that was broken),
+// 3. sells the full received balance back (sell_v2, with a real min-out floor).
+//
+// Devnet only. Never point this at mainnet or a mainnet key.
+//
+// Env / flags:
+// --rpc <url> | SOLANA_RPC_URL_DEVNET devnet RPC (default api.devnet.solana.com)
+// --keypair <path> | DEVNET_TEST_WALLET JSON byte-array or base58 secret key
+// --mint <base58> existing devnet curve mint to trade;
+// if omitted, a fresh token is created
+// --sol <n> quote SOL to spend on the buy (default 0.01)
+// --slippage-bps <n> default 500 (5%)
+//
+// Example:
+// node scripts/devnet-smoke-trade.mjs \
+// --rpc https://api.devnet.solana.com \
+// --keypair /tmp/devnet-test-wallet.json
+
+import fs from 'node:fs';
+import {
+ Connection,
+ Keypair,
+ PublicKey,
+ Transaction,
+ sendAndConfirmTransaction,
+ LAMPORTS_PER_SOL,
+} from '@solana/web3.js';
+import bs58 from 'bs58';
+import BN from 'bn.js';
+import * as spl from '@solana/spl-token';
+import {
+ getBuyTokenAmountFromSolAmount,
+ getSellSolAmountFromTokenAmount,
+ isLegacyQuoteMint,
+} from '@pump-fun/pump-sdk';
+
+import { getPumpSdk } from '../api/_lib/pump.js';
+import {
+ slippagePercentFromBps,
+ resolveTokenProgramForMintOwner,
+} from '../api/_lib/pump-trade-args.js';
+
+// ── args ─────────────────────────────────────────────────────────────────────
+
+function flag(name, fallbackEnv) {
+ const i = process.argv.indexOf(`--${name}`);
+ if (i !== -1 && process.argv[i + 1]) return process.argv[i + 1];
+ return fallbackEnv ? process.env[fallbackEnv] : undefined;
+}
+
+const RPC = flag('rpc', 'SOLANA_RPC_URL_DEVNET') || 'https://api.devnet.solana.com';
+const KEYPAIR_PATH = flag('keypair', 'DEVNET_TEST_WALLET');
+const EXISTING_MINT = flag('mint');
+const BUY_SOL = Number(flag('sol') || '0.01');
+const SLIPPAGE_BPS = Number(flag('slippage-bps') || '500');
+
+if (/mainnet/i.test(RPC)) {
+ console.error('Refusing to run against a mainnet RPC. Devnet only.');
+ process.exit(1);
+}
+if (!KEYPAIR_PATH) {
+ console.error('Missing --keypair <path> (or DEVNET_TEST_WALLET). Devnet signer required.');
+ process.exit(1);
+}
+
+function loadKeypair(path) {
+ const raw = fs.readFileSync(path, 'utf8').trim();
+ try {
+ return Keypair.fromSecretKey(Uint8Array.from(JSON.parse(raw)));
+ } catch {
+ return Keypair.fromSecretKey(bs58.decode(raw));
+ }
+}
+
+// ── send helper ──────────────────────────────────────────────────────────────
+
+async function send(connection, instructions, signers, label) {
+ const tx = new Transaction();
+ tx.add(...instructions);
+ tx.feePayer = signers[0].publicKey;
+ const sig = await sendAndConfirmTransaction(connection, tx, signers, {
+ commitment: 'confirmed',
+ skipPreflight: false,
+ });
+ console.log(`${label} tx: ${sig}`);
+ console.log(` explorer: https://explorer.solana.com/tx/${sig}?cluster=devnet`);
+ return sig;
+}
+
+// ── main ─────────────────────────────────────────────────────────────────────
+
+const connection = new Connection(RPC, 'confirmed');
+const wallet = loadKeypair(KEYPAIR_PATH);
+console.log(`RPC: ${RPC}`);
+console.log(`Wallet: ${wallet.publicKey.toBase58()}`);
+
+const balance = await connection.getBalance(wallet.publicKey);
+console.log(`Balance: ${balance / LAMPORTS_PER_SOL} SOL`);
+if (balance < 0.05 * LAMPORTS_PER_SOL) {
+ console.error(
+ `Insufficient devnet SOL (need ~0.05 for create + buy + sell + rent). ` +
+ `Fund ${wallet.publicKey.toBase58()} via https://faucet.solana.com (devnet).`,
+ );
+ process.exit(1);
+}
+
+// getPumpSdk reads SOLANA_RPC_URL_DEVNET for the 'devnet' network — make sure
+// the helper sees the same RPC we resolved here.
+process.env.SOLANA_RPC_URL_DEVNET = RPC;
+const { sdk } = await getPumpSdk({ network: 'devnet' });
+
+const slippagePct = slippagePercentFromBps(SLIPPAGE_BPS);
+console.log(`Slippage: ${SLIPPAGE_BPS} bps -> ${slippagePct}% (SDK percent unit)`);
+
+// 1) Resolve or create the test mint ─────────────────────────────────────────
+let mintPk;
+if (EXISTING_MINT) {
+ mintPk = new PublicKey(EXISTING_MINT);
+ console.log(`\nUsing existing mint: ${mintPk.toBase58()}`);
+} else {
+ const mintKp = Keypair.generate();
+ mintPk = mintKp.publicKey;
+ console.log(`\nCreating devnet test token: ${mintPk.toBase58()}`);
+ // create_v2 (Token-2022 base mint), no initial dev buy — the curve starts
+ // empty and the standalone buy below exercises the buy_v2 fix in isolation.
+ const createIx = await sdk.createV2Instruction({
+ mint: mintPk,
+ name: 'THREE Test Token',
+ symbol: 'T3T',
+ uri: 'https://three.ws/t3t-devnet-smoke.json',
+ creator: wallet.publicKey,
+ user: wallet.publicKey,
+ mayhemMode: false,
+ });
+ await send(connection, Array.isArray(createIx) ? createIx : [createIx], [wallet, mintKp], 'Create');
+}
+
+// base_token_program from the mint owner (create_v2 => Token-2022).
+const mintInfo = await connection.getAccountInfo(mintPk);
+if (!mintInfo) {
+ console.error(`mint ${mintPk.toBase58()} not found on devnet`);
+ process.exit(1);
+}
+const baseTokenProgram = resolveTokenProgramForMintOwner(mintInfo.owner);
+console.log(`Base token program: ${baseTokenProgram.toBase58()}`);
+
+// 2) BUY on the bonding curve ─────────────────────────────────────────────────
+console.log(`\nBuying ${BUY_SOL} SOL of ${mintPk.toBase58()} ...`);
+const buyState = await sdk.fetchBuyState(mintPk, wallet.publicKey, baseTokenProgram);
+if (!buyState?.bondingCurve || buyState.bondingCurve.complete) {
+ console.error('No active bonding curve for this mint (graduated or missing).');
+ process.exit(1);
+}
+
+const quoteMintPk = buyState.bondingCurve.quoteMint ?? new PublicKey('So11111111111111111111111111111111111111112');
+const isUsdcQuote = !isLegacyQuoteMint(quoteMintPk);
+if (isUsdcQuote) {
+ console.error('This smoke script trades SOL-paired curves only; mint is USDC-paired.');
+ process.exit(1);
+}
+
+const [global, feeConfig] = await Promise.all([
+ sdk.fetchGlobal(),
+ sdk.fetchFeeConfig().catch(() => null),
+]);
+const quoteAtomics = new BN(Math.floor(BUY_SOL * LAMPORTS_PER_SOL));
+
+// The GAP-1 fix: derive a real base-token amount (> 0) from the SOL input.
+const tokenAmount = getBuyTokenAmountFromSolAmount({
+ global,
+ feeConfig,
+ mintSupply: buyState.bondingCurve.tokenTotalSupply,
+ bondingCurve: buyState.bondingCurve,
+ amount: quoteAtomics,
+ quoteMint: quoteMintPk,
+});
+console.log(` expected tokens out: ${tokenAmount.toString()} (must be > 0 — the fix)`);
+if (!tokenAmount.gt(new BN(0))) {
+ console.error('amount_too_small: quote amount buys zero tokens. Increase --sol.');
+ process.exit(1);
+}
+
+const buyIxs = await sdk.buyV2Instructions({
+ global,
+ bondingCurveAccountInfo: buyState.bondingCurveAccountInfo,
+ bondingCurve: buyState.bondingCurve,
+ associatedUserAccountInfo: buyState.associatedUserAccountInfo,
+ mint: mintPk,
+ user: wallet.publicKey,
+ amount: tokenAmount,
+ quoteAmount: quoteAtomics,
+ slippage: slippagePct,
+ tokenProgram: baseTokenProgram,
+ quoteTokenProgram: spl.TOKEN_PROGRAM_ID,
+});
+const buyTxSig = await send(connection, buyIxs, [wallet], 'Buy');
+
+// 3) SELL the full received balance back ──────────────────────────────────────
+await new Promise((r) => setTimeout(r, 2000));
+const userAta = spl.getAssociatedTokenAddressSync(mintPk, wallet.publicKey, true, baseTokenProgram);
+const ataBalance = await connection.getTokenAccountBalance(userAta);
+const tokensHeld = new BN(ataBalance.value.amount);
+console.log(`\nToken balance after buy: ${tokensHeld.toString()}`);
+if (!tokensHeld.gt(new BN(0))) {
+ console.error('Buy produced zero tokens — the GAP-1 bug would do exactly this. FAIL.');
+ process.exit(1);
+}
+
+const sellState = await sdk.fetchSellState(mintPk, wallet.publicKey, baseTokenProgram);
+const expectedQuoteOut = getSellSolAmountFromTokenAmount({
+ global,
+ feeConfig,
+ mintSupply: sellState.bondingCurve.tokenTotalSupply,
+ bondingCurve: sellState.bondingCurve,
+ amount: tokensHeld,
+});
+console.log(` expected SOL out: ${Number(expectedQuoteOut.toString()) / LAMPORTS_PER_SOL}`);
+
+const sellIxs = await sdk.sellV2Instructions({
+ global,
+ bondingCurveAccountInfo: sellState.bondingCurveAccountInfo,
+ bondingCurve: sellState.bondingCurve,
+ mint: mintPk,
+ user: wallet.publicKey,
+ amount: tokensHeld,
+ quoteAmount: expectedQuoteOut,
+ slippage: slippagePct,
+ tokenProgram: baseTokenProgram,
+ quoteTokenProgram: spl.TOKEN_PROGRAM_ID,
+});
+const sellTxSig = await send(connection, sellIxs, [wallet], 'Sell');
+
+// ── summary ──────────────────────────────────────────────────────────────────
+console.log('\n──────────────────────────────────────────────');
+console.log(`Mint: ${mintPk.toBase58()}`);
+console.log(`Buy tx: ${buyTxSig}`);
+console.log(`Sell tx: ${sellTxSig}`);
+console.log('✓ Smoke trade complete — both buy and sell confirmed on devnet.');
diff --git a/scripts/migrate-redis.mjs b/scripts/migrate-redis.mjs
new file mode 100644
index 000000000..230f3da27
--- /dev/null
+++ b/scripts/migrate-redis.mjs
@@ -0,0 +1,333 @@
+#!/usr/bin/env node
+// Migrate durable keys from the dead Upstash store to the active store.
+//
+// Background: On 2026-06-12 the original Upstash store (three-ws) hit its
+// 500k/mo free-tier ceiling. A new store (three-ratelimit) was provisioned
+// with new credentials. This script copies durable user data from the old
+// store to the new one.
+//
+// Usage:
+// DEAD_REDIS_URL=<url> DEAD_REDIS_TOKEN=<token> node scripts/migrate-redis.mjs [--dry-run]
+//
+// Credential sources:
+// DEAD_REDIS_URL / DEAD_REDIS_TOKEN — old store (three-ws).
+// Retrieve from console.upstash.com → three-ws store → REST API tab.
+// Or via Vercel env history (needs Vercel PAT): see docs/ops/redis.md.
+//
+// Active store credentials are auto-resolved from .env.local using the
+// same fallback chain as api/_lib/env.js:
+// UPSTASH_REDIS_REST_URL / UPSTASH_REDIS_REST_TOKEN
+// three_KV_REST_API_URL / three_KV_REST_API_TOKEN ← local .env.local
+// KV_REST_API_URL / KV_REST_API_TOKEN
+//
+// Override with ACTIVE_REDIS_URL / ACTIVE_REDIS_TOKEN if needed.
+//
+// Key patterns migrated (actual patterns used by the codebase — no "three:" prefix):
+// cosmetics:owned:* — SET, 2-year TTL. User cosmetic purchases. Critical.
+// x402:pay:call:* — STRING, 30-day TTL. Payment dedup by tx hash.
+// featured-builds:* — STRING, 45-day TTL. Forge build gallery indexes.
+// play-build:* — STRING, 45-day TTL. Individual build thumbnails.
+// x402:pay:feed — LIST, no TTL. Recent x402 payment display feed.
+// feed:events — LIST, no TTL. General activity event feed.
+//
+// Keys skipped (ephemeral, auto-regenerate):
+// rl:* — rate limit windows
+// x402:rl:* — subscription rate limit sorted sets
+// forge-smoke:* — forge health cron state
+// uptime:* — uptime cron data
+// usage:* — usage buffer flushed by cron
+// feed:joined:* — world join dedup (short TTL)
+// rep:* — reputation cache (5-min TTL)
+// quota:* — quota check cache (25h TTL)
+// a2a:spend:* — A2A mandate spend ledger
+// keys containing | — idempotency cache (route|paymentId)
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+const DRY_RUN = process.argv.includes('--dry-run');
+
+// ── Credential resolution ────────────────────────────────────────────────────
+
+function loadEnvLocal() {
+ try {
+ const raw = readFileSync(resolve(process.cwd(), '.env.local'), 'utf8');
+ for (const line of raw.split('\n')) {
+ const trimmed = line.trim();
+ if (!trimmed || trimmed.startsWith('#')) continue;
+ const eq = trimmed.indexOf('=');
+ if (eq < 1) continue;
+ const key = trimmed.slice(0, eq).trim();
+ let val = trimmed.slice(eq + 1).trim();
+ if ((val.startsWith('"') && val.endsWith('"')) ||
+ (val.startsWith("'") && val.endsWith("'"))) {
+ val = val.slice(1, -1);
+ }
+ if (key && !process.env[key]) process.env[key] = val;
+ }
+ } catch { /* .env.local absent in CI — fine */ }
+}
+
+loadEnvLocal();
+
+const DEAD_URL = (process.env.DEAD_REDIS_URL || '').replace(/\/$/, '');
+const DEAD_TOKEN = process.env.DEAD_REDIS_TOKEN || '';
+
+const ACTIVE_URL = (
+ process.env.ACTIVE_REDIS_URL ||
+ process.env.UPSTASH_REDIS_REST_URL ||
+ process.env.three_KV_REST_API_URL ||
+ process.env.KV_REST_API_URL || ''
+).replace(/\/$/, '');
+
+const ACTIVE_TOKEN =
+ process.env.ACTIVE_REDIS_TOKEN ||
+ process.env.UPSTASH_REDIS_REST_TOKEN ||
+ process.env.three_KV_REST_API_TOKEN ||
+ process.env.KV_REST_API_TOKEN || '';
+
+function validateCredentials() {
+ const errs = [];
+ if (!DEAD_URL) errs.push('DEAD_REDIS_URL is not set');
+ if (!DEAD_TOKEN) errs.push('DEAD_REDIS_TOKEN is not set');
+ if (!ACTIVE_URL) errs.push('Active store URL not found (set UPSTASH_REDIS_REST_URL or ensure .env.local has three_KV_REST_API_URL)');
+ if (!ACTIVE_TOKEN) errs.push('Active store token not found (set UPSTASH_REDIS_REST_TOKEN or ensure .env.local has three_KV_REST_API_TOKEN)');
+ if (DEAD_URL && ACTIVE_URL && DEAD_URL === ACTIVE_URL) {
+ errs.push('DEAD_REDIS_URL and active store URL are the same — refusing to migrate store to itself');
+ }
+ if (errs.length) {
+ console.error('\nCannot start migration:\n' + errs.map(e => ' • ' + e).join('\n'));
+ console.error('\nSee the credential recovery guide in docs/ops/redis.md');
+ process.exit(1);
+ }
+}
+
+// ── Upstash REST helpers ─────────────────────────────────────────────────────
+
+async function pipeline(baseUrl, token, commands) {
+ const res = await fetch(`${baseUrl}/pipeline`, {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(commands),
+ });
+ if (!res.ok) throw new Error(`Upstash pipeline HTTP ${res.status}: ${await res.text()}`);
+ const body = await res.json();
+ if (!Array.isArray(body)) throw new Error(`Unexpected pipeline response: ${JSON.stringify(body)}`);
+ return body.map((r, i) => {
+ if (r && r.error) throw new Error(`Pipeline cmd ${i} error: ${r.error}`);
+ return r.result;
+ });
+}
+
+async function cmd(baseUrl, token, ...args) {
+ const [result] = await pipeline(baseUrl, token, [args]);
+ return result;
+}
+
+// Cursor-based SCAN returning all matching keys.
+async function scanAll(baseUrl, token, pattern) {
+ const keys = [];
+ let cursor = '0';
+ do {
+ const result = await cmd(baseUrl, token, 'SCAN', cursor, 'MATCH', pattern, 'COUNT', '200');
+ if (!Array.isArray(result) || result.length < 2) break;
+ cursor = String(result[0]);
+ if (Array.isArray(result[1])) keys.push(...result[1]);
+ } while (cursor !== '0');
+ return keys;
+}
+
+// ── Key patterns ─────────────────────────────────────────────────────────────
+
+// Patterns to scan (user data that must survive store rotation).
+const SCAN_PATTERNS = [
+ 'cosmetics:owned:*',
+ 'x402:pay:call:*',
+ 'featured-builds:*',
+ 'play-build:*',
+];
+
+// Single well-known list keys (existence checked individually, not via SCAN).
+const SINGLE_LIST_KEYS = [
+ 'x402:pay:feed',
+ 'feed:events',
+];
+
+// Keys that match these prefixes are ephemeral and always skipped even if
+// somehow discovered via SCAN (belt-and-suspenders).
+const SKIP_PREFIXES = [
+ 'rl:',
+ 'x402:rl:',
+ 'forge-smoke:',
+ 'uptime:',
+ 'usage:',
+ 'feed:joined:',
+ 'rep:',
+ 'quota:',
+ 'a2a:spend:',
+];
+
+function shouldSkip(key) {
+ if (key.includes('|')) return true; // idempotency cache: route|paymentId
+ return SKIP_PREFIXES.some(p => key.startsWith(p));
+}
+
+// ── Migration logic per key type ─────────────────────────────────────────────
+
+async function migrateSet(key) {
+ const [members, ttl] = await pipeline(DEAD_URL, DEAD_TOKEN, [
+ ['SMEMBERS', key],
+ ['TTL', key],
+ ]);
+ if (!Array.isArray(members) || members.length === 0) return { action: 'skip', reason: 'empty set' };
+
+ if (!DRY_RUN) {
+ // SADD is idempotent — safe to call even if some members already exist.
+ const activeCmds = [['SADD', key, ...members]];
+ if (ttl > 0) {
+ const expireAt = Math.floor(Date.now() / 1000) + ttl;
+ activeCmds.push(['EXPIREAT', key, String(expireAt)]);
+ }
+ await pipeline(ACTIVE_URL, ACTIVE_TOKEN, activeCmds);
+ }
+ return { action: 'copy', type: 'set', count: members.length, ttl };
+}
+
+async function migrateString(key) {
+ const [val, ttl] = await pipeline(DEAD_URL, DEAD_TOKEN, [
+ ['GET', key],
+ ['TTL', key],
+ ]);
+ if (val === null || val === undefined) return { action: 'skip', reason: 'null value' };
+ if (ttl === -2) return { action: 'skip', reason: 'key expired in dead store' };
+
+ if (!DRY_RUN) {
+ // NX = only set if the key doesn't already exist, so newer post-incident
+ // data in the active store is never clobbered by stale dead-store values.
+ const serialized = typeof val === 'string' ? val : JSON.stringify(val);
+ const setCmd = ttl > 0
+ ? ['SET', key, serialized, 'NX', 'EX', String(ttl)]
+ : ['SET', key, serialized, 'NX'];
+ await cmd(ACTIVE_URL, ACTIVE_TOKEN, ...setCmd);
+ }
+ return { action: 'copy', type: 'string', ttl };
+}
+
+async function migrateList(key) {
+ const [items, ttl] = await pipeline(DEAD_URL, DEAD_TOKEN, [
+ ['LRANGE', key, '0', '-1'],
+ ['TTL', key],
+ ]);
+ if (!Array.isArray(items) || items.length === 0) return { action: 'skip', reason: 'empty list' };
+
+ if (!DRY_RUN) {
+ // Only write if the key doesn't exist in the active store — new events
+ // written after the incident are more current than the dead store's list.
+ const exists = await cmd(ACTIVE_URL, ACTIVE_TOKEN, 'EXISTS', key);
+ if (exists) return { action: 'skip', reason: 'already exists in active store' };
+
+ // RPUSH preserves LRANGE order (newest-first convention maintained).
+ await cmd(ACTIVE_URL, ACTIVE_TOKEN, 'RPUSH', key, ...items);
+ if (ttl > 0) {
+ const expireAt = Math.floor(Date.now() / 1000) + ttl;
+ await cmd(ACTIVE_URL, ACTIVE_TOKEN, 'EXPIREAT', key, String(expireAt));
+ }
+ }
+ return { action: 'copy', type: 'list', count: items.length, ttl };
+}
+
+async function migrateKey(key) {
+ if (shouldSkip(key)) return { action: 'skip', reason: 'ephemeral key pattern' };
+
+ const type = await cmd(DEAD_URL, DEAD_TOKEN, 'TYPE', key);
+
+ switch (type) {
+ case 'set': return migrateSet(key);
+ case 'string': return migrateString(key);
+ case 'list': return migrateList(key);
+ case 'none': return { action: 'skip', reason: 'key expired or missing in dead store' };
+ default: return { action: 'skip', reason: `unsupported type: ${type}` };
+ }
+}
+
+// ── Main ─────────────────────────────────────────────────────────────────────
+
+async function main() {
+ validateCredentials();
+
+ const mode = DRY_RUN ? ' [DRY RUN]' : '';
+ console.log(`\n── Redis migration${mode} ──────────────────────────────────────`);
+ console.log(` Dead store : ${DEAD_URL}`);
+ console.log(` Active store: ${ACTIVE_URL}`);
+ console.log('');
+
+ // Collect all durable keys from the dead store.
+ const allKeys = new Set();
+
+ process.stdout.write('Scanning dead store…');
+ for (const pattern of SCAN_PATTERNS) {
+ const found = await scanAll(DEAD_URL, DEAD_TOKEN, pattern);
+ for (const k of found) allKeys.add(k);
+ process.stdout.write(` ${found.length} ${pattern}`);
+ }
+
+ // Check single list keys individually.
+ for (const key of SINGLE_LIST_KEYS) {
+ const exists = await cmd(DEAD_URL, DEAD_TOKEN, 'EXISTS', key);
+ if (exists) allKeys.add(key);
+ }
+
+ console.log(`\n\nFound ${allKeys.size} durable keys in dead store.\n`);
+
+ if (allKeys.size === 0) {
+ console.log('Nothing to migrate — the dead store appears to have no durable keys.');
+ console.log('If this is unexpected, verify that DEAD_REDIS_URL/TOKEN point to the correct store.');
+ return;
+ }
+
+ // Migrate each key.
+ const stats = { total: allKeys.size, copied: 0, skipped: 0, errors: 0 };
+ const rows = [];
+
+ for (const key of allKeys) {
+ try {
+ const result = await migrateKey(key);
+ if (result.action === 'copy') {
+ stats.copied++;
+ const detail = result.count != null ? ` (${result.count} items)` : '';
+ const ttlNote = result.ttl > 0 ? ` TTL=${result.ttl}s` : result.ttl === -1 ? ' no-TTL' : '';
+ rows.push(` COPY ${key}${detail}${ttlNote}`);
+ } else {
+ stats.skipped++;
+ rows.push(` SKIP ${key} — ${result.reason}`);
+ }
+ } catch (err) {
+ stats.errors++;
+ rows.push(` ERROR ${key} — ${err.message}`);
+ }
+ }
+
+ for (const row of rows) console.log(row);
+
+ console.log('\n── Summary ──────────────────────────────────────────────────');
+ console.log(` Total scanned : ${stats.total}`);
+ console.log(` Copied : ${stats.copied}`);
+ console.log(` Skipped : ${stats.skipped}`);
+ console.log(` Errors : ${stats.errors}`);
+ if (DRY_RUN) {
+ console.log('\n (DRY RUN — nothing written to the active store)');
+ } else if (stats.errors > 0) {
+ console.log('\n Migration finished with errors. Re-run to retry failed keys.');
+ process.exit(1);
+ } else {
+ console.log('\n Migration complete. Verify with docs/ops/redis.md post-migration checks.');
+ }
+}
+
+main().catch(err => {
+ console.error('\nFatal error:', err.message);
+ process.exit(1);
+});
diff --git a/scripts/publish-packages.mjs b/scripts/publish-packages.mjs
new file mode 100644
index 000000000..2eeece8f4
--- /dev/null
+++ b/scripts/publish-packages.mjs
@@ -0,0 +1,86 @@
+#!/usr/bin/env node
+// Publish three.ws npm library packages (not MCP servers — see
+// publish-mcp-servers.mjs for those), idempotently.
+//
+// For each package below it:
+// 1. reads the local version from package.json;
+// 2. checks that version against npm — if already published, skips;
+// 3. otherwise runs the package build (prepublishOnly handles this too) and
+// `npm publish --access public`.
+//
+// Requires `npm whoami` to succeed (or NPM_TOKEN in the environment).
+//
+// Usage:
+// node scripts/publish-packages.mjs --dry-run # report only
+// node scripts/publish-packages.mjs # publish what's missing
+// node scripts/publish-packages.mjs --only react # one package by key
+
+import { execFileSync } from 'node:child_process';
+import { readFileSync } from 'node:fs';
+import { resolve, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+
+// Every publishable library package in this repo.
+const PACKAGES = [{ key: 'react', dir: 'packages/react' }];
+
+const args = process.argv.slice(2);
+const dryRun = args.includes('--dry-run');
+const onlyIdx = args.indexOf('--only');
+const only = onlyIdx >= 0 ? (args[onlyIdx + 1] || '').split(',').filter(Boolean) : null;
+
+function readPkg(dir) {
+ return JSON.parse(readFileSync(resolve(root, dir, 'package.json'), 'utf8'));
+}
+
+function publishedVersions(name) {
+ try {
+ const out = execFileSync('npm', ['view', name, 'versions', '--json'], {
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'ignore'],
+ });
+ const parsed = JSON.parse(out);
+ return Array.isArray(parsed) ? parsed : [parsed];
+ } catch {
+ return []; // 404 → never published
+ }
+}
+
+let published = 0;
+let skipped = 0;
+let failed = 0;
+
+for (const entry of PACKAGES) {
+ if (only && !only.includes(entry.key)) continue;
+ const pkg = readPkg(entry.dir);
+ const { name, version } = pkg;
+ const existing = publishedVersions(name);
+
+ if (existing.includes(version)) {
+ console.log(`• ${name}@${version} — already on npm, skipping`);
+ skipped++;
+ continue;
+ }
+
+ if (dryRun) {
+ console.log(`• ${name}@${version} — would publish (dry run)`);
+ continue;
+ }
+
+ console.log(`• ${name}@${version} — publishing…`);
+ try {
+ execFileSync('npm', ['publish', '--access', 'public'], {
+ cwd: resolve(root, entry.dir),
+ stdio: 'inherit',
+ });
+ console.log(` ✓ published ${name}@${version}`);
+ published++;
+ } catch (err) {
+ console.error(` ✗ failed to publish ${name}@${version}: ${err.message}`);
+ failed++;
+ }
+}
+
+console.log(`\nDone — ${published} published, ${skipped} skipped, ${failed} failed.`);
+process.exit(failed ? 1 : 0);
diff --git a/scripts/smoke-mcp-remotes.mjs b/scripts/smoke-mcp-remotes.mjs
index c55a893ed..28f73019b 100644
--- a/scripts/smoke-mcp-remotes.mjs
+++ b/scripts/smoke-mcp-remotes.mjs
@@ -26,6 +26,9 @@ const ENDPOINTS = [
name: 'get_token_details',
args: { mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump' },
},
+ // Indexer-backed probe, run only when pumpfun_bot_status reports the bot is
+ // configured AND healthy. Skipped (not failed) when the indexer is absent.
+ indexerProbe: { name: 'get_new_tokens', args: { limit: 3 } },
},
{ path: '/api/mcp', type: 'paid' },
{ path: '/api/mcp-3d', type: 'paid' },
@@ -131,6 +134,56 @@ async function checkFree(ep) {
!isErr,
isErr ? call.body.error.message?.slice(0, 60) : 'ok',
]);
+
+ // Indexer-backed tools are conditionally available: pumpfun_bot_status reports
+ // whether PUMPFUN_BOT_URL is wired and the bot answers. Probe an indexer tool
+ // only when configured AND healthy; an unconfigured backend skips, a
+ // configured-but-down backend is degraded (live endpoint, indexer offline) —
+ // neither is a hard failure of the endpoint itself.
+ if (ep.indexerProbe) {
+ const status = await post(ep.path, rpc('tools/call', { name: 'pumpfun_bot_status' }, 4));
+ const s = status.body?.result?.structuredContent;
+ const statusOk = !status.body?.error && typeof s?.configured === 'boolean';
+ checks.push([
+ 'pumpfun_bot_status',
+ statusOk,
+ statusOk
+ ? `configured=${s.configured} healthy=${s.healthy}`
+ : status.body?.error?.message?.slice(0, 60) || 'malformed status',
+ ]);
+
+ // Confirm tools/list honours the same capability gate: indexer tools appear
+ // iff the backend is configured.
+ if (statusOk) {
+ const listed = (tools || []).some((t) => t.name === ep.indexerProbe.name);
+ checks.push([
+ `tools/list gating ${ep.indexerProbe.name}`,
+ listed === s.configured,
+ `listed=${listed} configured=${s.configured}`,
+ ]);
+ }
+
+ if (statusOk && s.configured && !s.healthy) {
+ checks.push([
+ 'indexer health',
+ true,
+ `degraded: bot configured but unhealthy (${s.error || 'no detail'})`,
+ ]);
+ } else if (statusOk && s.configured && s.healthy) {
+ const ix = await post(
+ ep.path,
+ rpc('tools/call', { name: ep.indexerProbe.name, arguments: ep.indexerProbe.args }, 5),
+ );
+ const ixErr = !!ix.body?.error;
+ checks.push([
+ `call ${ep.indexerProbe.name}`,
+ !ixErr,
+ ixErr ? ix.body.error.message?.slice(0, 60) : 'ok',
+ ]);
+ } else if (statusOk && !s.configured) {
+ console.log(' skip indexer not configured — skipping indexer tool probes');
+ }
+ }
return checks;
}
diff --git a/scripts/world-health.mjs b/scripts/world-health.mjs
index 4cca9ff57..e4017c2b7 100755
--- a/scripts/world-health.mjs
+++ b/scripts/world-health.mjs
@@ -7,8 +7,13 @@
// vanished from the GCS bucket, the scene app crashed on every client, the
// ground unloaded, and every player fell into the void.
//
-// Usage: node scripts/world-health.mjs
+// Usage: node scripts/world-health.mjs [--assert-protected]
// Exit 0 = healthy, 1 = problems found (suitable for cron/uptime alerting).
+//
+// --assert-protected treat an unprotected world (no ADMIN_CODE) as a hard
+// failure, not just a warning. Use it as a post-deploy gate
+// after deploy/world/apply-hardening.sh:
+// node scripts/world-health.mjs --assert-protected
import { execSync } from 'node:child_process'
import { createRequire } from 'node:module'
@@ -17,6 +22,7 @@ import os from 'node:os'
import path from 'node:path'
const WORLD = process.env.WORLD_URL || 'https://world.three.ws'
+const ASSERT_PROTECTED = process.argv.includes('--assert-protected')
// msgpackr is only needed by this script; provision it in a cache dir so the
// shared package.json/lockfile stay untouched.
@@ -33,7 +39,11 @@ const problems = []
const status = await (await fetch(`${WORLD}/status`)).json()
console.log(`/status: uptime=${status.uptime}s protected=${status.protected}`)
if (!status.protected) {
- problems.push('world is UNPROTECTED — no ADMIN_CODE set, every visitor has build rights (run deploy/world/apply-hardening.sh)')
+ const msg = 'world is UNPROTECTED — no ADMIN_CODE set, every visitor has build rights (run deploy/world/apply-hardening.sh)'
+ // --assert-protected makes this a hard failure (post-deploy gate); otherwise
+ // it is a warning so an asset-only health run still reports cleanly.
+ if (ASSERT_PROTECTED) problems.push(msg)
+ else console.warn(`WARNING: ${msg}`)
}
const snapshot = await new Promise((resolve, reject) => {
diff --git a/src/create-review-features.js b/src/create-review-features.js
index 524bf20c6..9976ed7b4 100644
--- a/src/create-review-features.js
+++ b/src/create-review-features.js
@@ -353,10 +353,9 @@ export function openPaidSkillsModal(ctx = {}) {
const snippets = {
fetch: `import { withX402 } from '@three-ws/x402-fetch';
-const fetchPaid = withX402(fetch, {
- wallet,
- network: 'solana',
-});
+// wallet: window.ethereum, a viem account, or privateKeyToWallet(pk).
+// On a 402 the wrapper pays in USDC and retries — no extra code.
+const fetchPaid = withX402(fetch, { wallet });
const res = await fetchPaid('${endpoint}', {
method: 'POST',
@@ -530,7 +529,7 @@ export function openEmbedModal(ctx = {}) {
react: `import { Agent3D } from '@three-ws/react';
export default function Page() {
- return <Agent3D agent="${handle}" mode="full" />;
+ return <Agent3D agentId="${handle}" controls="joystick" />;
}`,
iframe: `<iframe
src="https://three.ws/widget#widget=${handle}&kiosk=true"
diff --git a/src/marketplace.js b/src/marketplace.js
index f300238e0..a1c0f882f 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -2255,8 +2255,8 @@ function renderSkillX402(skill, paid) {
const codeEl = $('skill-detail-x402-code');
if (codeEl) {
codeEl.textContent =
- `import { wrapFetchWithPayment } from 'x402-fetch';\n\n` +
- `// wallet = a viem/ethers account funded with USDC on Base or Solana\n` +
+ `import { wrapFetchWithPayment } from '@three-ws/x402-fetch';\n\n` +
+ `// wallet = a viem/ethers account funded with USDC on Base\n` +
`const fetchWithPay = wrapFetchWithPayment(fetch, wallet);\n` +
`const res = await fetchWithPay('${url}');\n` +
`const { skill, tools, content } = await res.json();\n` +
diff --git a/src/pump/mcp-tools.js b/src/pump/mcp-tools.js
index 46626ce76..18b443d81 100644
--- a/src/pump/mcp-tools.js
+++ b/src/pump/mcp-tools.js
@@ -96,6 +96,7 @@ export const TOOL_ANNOTATIONS = Object.freeze({
kol_leaderboard: { title: 'KOL Leaderboard', ...LIVE_READ },
pumpfun_quote_swap: { title: 'Swap Quote (Read-Only)', ...LIVE_READ },
social_x_post_impact: { title: 'X Post Price Impact', ...LIVE_READ },
+ pumpfun_bot_status: { title: 'Indexer Status', ...LIVE_READ },
});
// outputSchema policy: only tools whose response shape is code-controlled and
@@ -481,6 +482,39 @@ export const TOOLS = [
required: ['postUrl', 'mint'],
},
},
+ {
+ name: 'pumpfun_bot_status',
+ description:
+ 'Returns the configuration and health status of the pump.fun indexer backend. Always available — does not require PUMPFUN_BOT_URL.',
+ inputSchema: { type: 'object', properties: {}, required: [] },
+ outputSchema: {
+ type: 'object',
+ properties: {
+ configured: {
+ type: 'boolean',
+ description: 'true when PUMPFUN_BOT_URL is set on the server',
+ },
+ healthy: {
+ type: 'boolean',
+ description: 'true when the indexer answered the health ping',
+ },
+ latencyMs: {
+ type: 'number',
+ description: 'Round-trip ms of the health ping (configured backends only)',
+ },
+ error: {
+ type: 'string',
+ description: 'Failure reason when healthy is false',
+ },
+ message: {
+ type: 'string',
+ description: 'Human-readable note when the indexer is unconfigured',
+ },
+ },
+ required: ['configured', 'healthy'],
+ additionalProperties: true,
+ },
+ },
];
// Stamp title + annotations onto every tool from the map above. A tool added
diff --git a/tasks/devnet-smoke-trade.md b/tasks/devnet-smoke-trade.md
new file mode 100644
index 000000000..aa3080258
--- /dev/null
+++ b/tasks/devnet-smoke-trade.md
@@ -0,0 +1,8 @@
+# Devnet smoke trade → moved
+
+This task is now the canonical, fully-specified task at
+[tasks/pumpfun-launchpad-100/07-devnet-smoke-trade.md](pumpfun-launchpad-100/07-devnet-smoke-trade.md)
+— part of the **Pump.fun Launchpad → 100%** plan
+([tasks/pumpfun-launchpad-100/README.md](pumpfun-launchpad-100/README.md)).
+
+Run it after Tasks 01–03 (USDC trade recording + UI + custodial) land.
diff --git a/tasks/launchpad/01-launch-modal-post-launch-cta.md b/tasks/launchpad/01-launch-modal-post-launch-cta.md
new file mode 100644
index 000000000..6ebf40d85
--- /dev/null
+++ b/tasks/launchpad/01-launch-modal-post-launch-cta.md
@@ -0,0 +1,63 @@
+# 01 — Launch modal: post-launch CTA set
+
+## Problem
+
+After a user successfully launches a coin, the modal success screen (`_renderStep4` in [src/pump/launch-token-modal.js](../../src/pump/launch-token-modal.js), line ~806) shows:
+
+- A shareable canvas card
+- "Copy mint" button
+- "Download card" button
+- "Share on X" button
+- A bare `View on pump.fun →` text link
+
+There is no link to `/coin3d?mint=<X>` (the platform's own 3D token view), no link to `/pump-dashboard?agent=<Y>` (the management console), and the "Done" button just calls `location.reload()` with no navigation offer. A user who just launched a coin has nowhere obvious to go next within three.ws.
+
+This is the highest-visibility moment in the entire launch flow and it currently dead-ends.
+
+## Target files
+
+- [src/pump/launch-token-modal.js](../../src/pump/launch-token-modal.js) — `_renderStep4` method and its CSS companion
+- [src/pump/launch-token-modal.css](../../src/pump/launch-token-modal.css) — button/link styling
+
+## Outcome
+
+The step-4 success screen adds a styled CTA row beneath the share actions:
+
+```
+[ View in 3D ] [ Manage on Dashboard ] [ View on pump.fun ↗ ]
+```
+
+Behavior:
+- **View in 3D** → opens `/coin3d?mint=<mint>` in a new tab. Always shown (mainnet launches only; skip on devnet).
+- **Manage on Dashboard** → opens `/pump-dashboard?agent=<agentId>` in the same tab, then closes the modal. `agentId` is already threaded through `this._agentId` from the call site (`openLaunchTokenModal({ agentId, … })`). If `agentId` is not available (direct embed callers), link to `/pump-dashboard` without the query param.
+- **View on pump.fun ↗** — keep this, but style it as a tertiary button matching the others. Remove the bare `<a>` text link.
+- The "Done" button remains but changes label to "Close" and just closes the modal (`this._close()`). Remove `location.reload()` — the page already listens for the `agent-token-launched` CustomEvent and can refresh itself; a hard reload breaks callers that handle the event.
+
+Style:
+- CTA row uses `display: flex; gap: 8px; flex-wrap: wrap; justify-content: center; margin-top: 16px;`.
+- Primary button (`ltm-btn ltm-btn-primary`) for "View in 3D".
+- Secondary button (`ltm-btn`) for "Manage on Dashboard".
+- Tertiary with `target="_blank"` for "View on pump.fun".
+
+## Implementation notes
+
+1. `_renderStep4(mint, pumpUrl, agentId)` — add `agentId` as a third parameter. Callers pass it from `this._agentId` which is already set when `open({ agentId })` is called.
+2. Build the dashboard URL: `agentId ? \`/pump-dashboard?agent=\${encodeURIComponent(agentId)}\` : '/pump-dashboard'`.
+3. Build the coin3d URL: `/coin3d?mint=\${encodeURIComponent(mint)}`.
+4. Only add the coin3d and pump.fun buttons when `this._network !== 'devnet'`.
+5. "Manage on Dashboard" click handler: `this._close(); window.location.href = dashboardUrl;`.
+6. Remove `location.reload()` from the "Done" handler; replace with `this._close()`.
+7. The `agent-token-launched` CustomEvent already fires (line ~857 of launch-token-modal.js) — do not remove it; callers rely on it to refresh their state.
+
+## Definition of done
+
+- Launch a coin on devnet via the modal (agent-detail page → "Launch Token").
+- Step 4 shows: canvas card, copy/download/share row, then a CTA row with correct buttons.
+- On devnet: only "Close" appears in the CTA row (no coin3d or pump.fun links since devnet).
+- On mainnet (or mocked): "View in 3D", "Manage on Dashboard", "View on pump.fun" all appear with correct hrefs.
+- "View in 3D" opens `/coin3d?mint=<mint>` in a new tab.
+- "Manage on Dashboard" navigates to `/pump-dashboard?agent=<agentId>` and the modal closes.
+- "Close" closes the modal without a hard reload; the page reflects the new coin state via the `agent-token-launched` event.
+- No console errors.
+- `npm test` green.
+- Completionist subagent run on changed files.
diff --git a/tasks/launchpad/02-launches-feed-coin3d-action.md b/tasks/launchpad/02-launches-feed-coin3d-action.md
new file mode 100644
index 000000000..21927d651
--- /dev/null
+++ b/tasks/launchpad/02-launches-feed-coin3d-action.md
@@ -0,0 +1,87 @@
+# 02 — /launches feed: add "View in 3D" action to every coin card
+
+## Problem
+
+Every launch card in [src/launches.js](../../src/launches.js) (`launchCard` function, lines ~398–470) has two action buttons:
+
+1. `pump.fun ↗` — external link to the pump.fun trading page
+2. `3D world` — links to `/communities/<mint>` (the social multiplayer world)
+
+There is no link to `/coin3d?mint=<mint>` — the platform's own 3D token visualization page. `/coin3d` renders a spinning coin medallion with the token's logo, a top-holder galaxy sized by balance, and a graduation ring tracking bonding-curve progress. It is one of the most visually compelling pages on the platform and it is invisible from the primary launch discovery surface.
+
+These are three distinct experiences:
+- `/coin3d?mint=X` — data-driven 3D token snapshot (what this task adds)
+- `/communities/<mint>` — social world for the coin's community
+- `pump.fun/<mint>` — external trading
+
+## Target files
+
+- [src/launches.js](../../src/launches.js) — `launchCard` function, `actions` array construction
+- [src/launches.css](../../src/launches.css) — `.lx-action` styling
+
+## Outcome
+
+Each mainnet launch card gains a third action button:
+
+```
+[ pump.fun ↗ ] [ 3D view ] [ 3D world ]
+```
+
+"3D view" is the new button:
+- `href: /coin3d?mint=<mint>`
+- `text: '3D view'`
+- `aria-label: \`View ${launch.symbol || launch.name} in 3D\``
+- Same `lx-action` class as the existing buttons
+- Opens in a new tab (`target="_blank"`)
+- Only rendered for mainnet launches (`!isDevnet`)
+
+On devnet, keep only "Explorer ↗" (no coin3d or pump.fun links since the mint doesn't exist on mainnet).
+
+## Implementation notes
+
+In `launchCard` (src/launches.js), the `actions` array is built just before the card element is assembled. Currently:
+
+```js
+const actions = [
+ el('a', { class: 'lx-action', href: tradeHref, target: '_blank', … }),
+];
+if (!isDevnet) {
+ actions.push(el('a', { class: 'lx-action', href: `/communities/${launch.mint}`, … }));
+}
+```
+
+Change to:
+
+```js
+const actions = [
+ el('a', { class: 'lx-action', href: tradeHref, target: '_blank', … }),
+];
+if (!isDevnet) {
+ actions.push(
+ el('a', {
+ class: 'lx-action',
+ href: `/coin3d?mint=${encodeURIComponent(launch.mint)}`,
+ target: '_blank',
+ rel: 'noopener noreferrer',
+ text: '3D view',
+ 'aria-label': `View ${launch.symbol || launch.name || 'coin'} in 3D`,
+ }),
+ );
+ actions.push(el('a', { class: 'lx-action', href: `/communities/${launch.mint}`, … }));
+}
+```
+
+Order: pump.fun ↗ | 3D view | 3D world — left to right from external to platform surfaces.
+
+Check if `.lx-action` styling wraps cleanly at three items on a card; if not, add `flex-wrap: wrap` to the `.lx-actions` container in `launches.css`.
+
+## Definition of done
+
+- Start `npm run dev`, visit `/launches`.
+- Every mainnet card shows three action buttons: "pump.fun ↗", "3D view", "3D world".
+- "3D view" opens `/coin3d?mint=<correct mint>` in a new tab.
+- On devnet cards, only "Explorer ↗" appears.
+- Cards display without overflow or layout shift at 320px, 768px, and 1440px viewport widths.
+- No console errors.
+- `npm test` green.
+- Completionist subagent run on changed files.
diff --git a/tasks/launchpad/03-pump-live-e2e-verify.md b/tasks/launchpad/03-pump-live-e2e-verify.md
new file mode 100644
index 000000000..e1df7a15a
--- /dev/null
+++ b/tasks/launchpad/03-pump-live-e2e-verify.md
@@ -0,0 +1,51 @@
+# 03 — /pump-live: verify and fix end-to-end rendering
+
+## Problem
+
+[pages/pump-live.html](../../pages/pump-live.html) is the real-time showcase of new pump.fun launches — a 3D agent viewer on the left reacts to token events while a live feed streams on the right. The page has all the scaffolding (WebSocket to `wss://pumpportal.fun/api/data`, token list rendering, stat counters) but has never been formally verified end-to-end. Specific risks:
+
+1. **3D agent viewer** — the `<agent-3d>` web component embedded in `#viewer-container` may not load its avatar correctly without a valid `agent-id` or fallback avatar URL wired to a real three.ws agent. If the component silently fails, the left panel is blank.
+2. **WebSocket reconnection** — the 5-second reconnect timer (`setTimeout(connect, 5000)`) does not implement exponential backoff; on a production page with many concurrent users, all clients reconnect simultaneously after a PumpPortal outage.
+3. **Token card rendering** — new token events (received as `onmessage`) must be parsed from PumpPortal's JSON envelope, mapped to the card template, prepended to `#token-list`, and the overflow capped. Verify this pipeline renders real names/symbols/images and does not leave `undefined` in card text.
+4. **Stats bar** — the "Tokens Launched", "Volume", and "Age" counters must update in real time from incoming events. Verify they are wired to the WebSocket `onmessage` handler and not just initialized to zero.
+5. **Mobile layout** — the flex row (`#main-container`) must stack on mobile. Verify the CSS breakpoint.
+6. **PumpPortal envelope format** — PumpPortal's `subscribeNewToken` response format should be verified against the live feed; if the field names changed (e.g. `marketCap` → `usdMarketCap`), the card renderer is silently broken.
+
+## Target files
+
+- [pages/pump-live.html](../../pages/pump-live.html) — all logic is inline in a `<script>` block
+
+## Verification steps
+
+1. `npm run dev`. Open `http://localhost:3000/pump-live` in a browser.
+2. Open the browser console and network tab.
+3. Confirm the `wss://pumpportal.fun/api/data` connection opens and stays open (no immediate close/error).
+4. Wait 30 seconds for real tokens to arrive (pump.fun launches ~1–3 tokens per minute). Confirm:
+ - Token cards appear in `#token-list` with real name, symbol, and image (or a placeholder if no image).
+ - The launch counter increments.
+ - No `undefined`, `null`, or `[object Object]` text in any card field.
+5. Open DevTools → Network → WS → inspect incoming frames. Map field names to what the renderer expects. Fix any field name mismatches.
+6. Resize to 375px width. Confirm the layout stacks vertically (viewer above feed).
+7. Simulate a WebSocket drop: `ws.close()` in the console. Confirm reconnect fires after 5s.
+
+## Fixes to apply
+
+- **Avatar loading**: in `#viewer-container`, the `<agent-3d>` tag (or its equivalent) must have a valid `avatar-url` pointing to a real three.ws platform avatar GLB from [public/avatars/](../../public/avatars/). Use the same default agent avatar used on [pages/home.html](../../pages/home.html) as the fallback. If `<agent-3d>` requires an `agent-id`, use the platform's demo agent ID (locate it via `grep -r 'demo.*agent\|agent.*demo' pages/ public/` or check [public/nav-data.js](../../public/nav-data.js)).
+- **Field mapping**: read the actual PumpPortal `subscribeNewToken` response envelope from the live stream (or from [docs/pumpfun-program/](../../docs/pumpfun-program/) if documented there). Update the card renderer's field references to match.
+- **Reconnect backoff**: replace the fixed 5s `setTimeout` with a capped exponential backoff: 2s → 4s → 8s → 16s → 32s → cap at 60s. Reset on successful open.
+- **Stats wiring**: if any stat counter is not updating from `onmessage`, wire it now — no fake increments, no `setInterval` tickers. Real counts from real events only.
+- **Empty state**: if the WebSocket hasn't delivered any tokens yet (first 5s), `#token-list` should show a skeleton row, not a blank void.
+- **Error state**: if the connection fails permanently (e.g. PumpPortal is down), show a styled error message in the feed panel with a "Retry" button that calls `connect()`.
+
+## Definition of done
+
+- Open `/pump-live` with no console errors.
+- Within 60 seconds, at least one real token card appears with correct name, symbol, and image (or placeholder). No `undefined` text anywhere.
+- The stat counters increment for every new token event.
+- Resizing to 375px width stacks the panels vertically.
+- Closing and reopening the WebSocket (`ws.close()` → wait) triggers reconnect with the new backoff.
+- The empty state (first 5 seconds) shows a skeleton or "Waiting for new launches…" message.
+- The error state (force-kill connection and disable reconnect) shows a styled error + retry button.
+- No console errors during normal operation.
+- `npm test` green.
+- Completionist subagent run on changed files.
diff --git a/tasks/launchpad/04-pump-visualizer-data-wire.md b/tasks/launchpad/04-pump-visualizer-data-wire.md
new file mode 100644
index 000000000..12607f470
--- /dev/null
+++ b/tasks/launchpad/04-pump-visualizer-data-wire.md
@@ -0,0 +1,58 @@
+# 04 — /pump-visualizer: verify and fix data pipeline + 3D interactivity
+
+## Problem
+
+[pages/pump-visualizer.html](../../pages/pump-visualizer.html) is a Three.js scene where trending pump.fun tokens appear as interactive spheres sized by market cap. The page has full Three.js setup (scene, camera, bloom post-processing, OrbitControls) and fetch calls to three data sources:
+
+- `TRENDING_API = '/api/pump/trending?limit=50'` — `/api/pump/helius-stats` → not the trending endpoint
+- `STATS_API = '/api/pump/helius-stats'` — Helius blockchain stats (TPS, slot, block time)
+- `LIVE_FEED_API = '/api/agents/pumpfun-feed?kind=mint'` — SSE stream of new launches (EventSource)
+- `MIGRATIONS_BACKFILL_API = '/api/pump/recent-graduations?limit=20'` — graduated coins
+
+However, it has never been formally verified. Specific risks:
+
+1. **Three.js sphere rendering** — the code that maps `/api/pump/trending` response tokens to `THREE.Mesh` sphere objects may have field name mismatches (e.g. `marketCap` vs `usdMarketCap` vs `market_cap`) resulting in all spheres being the same (minimum) size.
+2. **Texture loading** — coin logos are loaded as textures onto sphere faces. If the image URL field name is wrong or the image is blocked by CORS, every sphere shows as untextured (plain grey).
+3. **Click-to-navigate** — clicking a sphere should navigate to `/coin3d?mint=<mint>`. Verify the raycaster event is wired and the mint address is correctly threaded through to the navigation.
+4. **Live feed mode** — when mode switches to "feed", the page opens an `EventSource` to `/api/agents/pumpfun-feed?kind=mint`. Verify the SSE endpoint exists and returns the correct event format, that each new-mint event creates a new sphere, and that the sphere count caps to avoid scene overload.
+5. **Stats bar** — `STATS_API` populates TPS, slot, and block time. Verify `/api/pump/helius-stats` returns these fields and the DOM updates.
+6. **Mode switching** — the three modes (trending / feed / migrations) each have different data sources. Verify switching between modes cleans up the previous data source (closes EventSource, cancels timers) and initializes the new one correctly.
+
+## Target files
+
+- [pages/pump-visualizer.html](../../pages/pump-visualizer.html) — all Three.js and fetch logic is inline
+
+## Verification steps
+
+1. `npm run dev`. Open `http://localhost:3000/pump-visualizer`.
+2. Default mode is "trending". Open Network tab. Confirm:
+ - `GET /api/pump/trending?limit=50` fires and returns a non-empty JSON array.
+ - Each array item has the fields the renderer expects. If not, update the field references.
+3. Confirm spheres appear in the 3D scene with varying sizes.
+4. Click a sphere. Confirm navigation to `/coin3d?mint=<correct_mint>` (check the URL in the address bar or console).
+5. Switch to "feed" mode. Confirm:
+ - `GET /api/agents/pumpfun-feed?kind=mint` opens as an EventSource.
+ - New spheres appear when events arrive (may take up to 60s on mainnet).
+6. Switch to "migrations" mode. Confirm `GET /api/pump/recent-graduations?limit=20` fires.
+7. Verify the stats bar (`#vz-stat-tps`, `#vz-stat-slot`) updates from `/api/pump/helius-stats`.
+
+## Fixes to apply
+
+- **Field mapping**: read the actual `/api/pump/trending` response shape in [api/pump/[action].js](../../api/pump/[action].js) (`handleTrending` function). Align all field references in the sphere-creation code.
+- **Click navigation**: in the `pointerup`/`click` event handler, after raycasting, navigate via `window.location.href = \`/coin3d?mint=\${encodeURIComponent(intersect.object.userData.mint)}\``. If the handler already does this but uses `window.open`, keep `window.location.href` (same tab) as the default; opening a new tab for every click is jarring.
+- **Texture CORS**: coin logo URLs come from pump.fun metadata. If loading as `THREE.TextureLoader` fails due to CORS, use `crossOrigin = 'anonymous'` on the loader. For tokens with no image or failed image loads, use a generated SVG placeholder (use the same `mintIdenticon` approach from [src/launches.js](../../src/launches.js) or a simple colored sphere based on the mint's first byte).
+- **Live feed sphere cap**: cap the scene to 200 live-mode spheres. When the cap is hit, remove the oldest sphere before adding the new one (FIFO).
+- **Mode teardown**: each mode switch must call `eventSource?.close()`, `clearInterval(refreshTimer)`, and `clearTimeout(pendingFetch)` before initializing the new mode.
+- **Empty/loading states**: the `vz-status` element has `data-state="loading"` on init. When data arrives and spheres are placed, set `data-state="ready"`. On fetch error, set `data-state="error"` and update the status text to "Could not load data — retry?"
+
+## Definition of done
+
+- Open `/pump-visualizer`, wait 3 seconds. Spheres of varying sizes appear in 3D.
+- Clicking a sphere opens `/coin3d?mint=<correct mint>` in the same tab.
+- Switching to "feed" mode opens an SSE connection; new spheres appear when pump.fun events arrive.
+- Switching modes tears down the previous data source (no duplicate EventSource connections).
+- Stats bar populates with real TPS, slot, block time from `/api/pump/helius-stats`.
+- On load failure, `data-state="error"` shows with an actionable message.
+- No console errors during normal operation.
+- `npm test` green.
+- Completionist subagent run on changed files.
diff --git a/tasks/launchpad/05-launchpad-builder-avatar-picker.md b/tasks/launchpad/05-launchpad-builder-avatar-picker.md
new file mode 100644
index 000000000..fd13277d1
--- /dev/null
+++ b/tasks/launchpad/05-launchpad-builder-avatar-picker.md
@@ -0,0 +1,68 @@
+# 05 — Launchpad Studio: wire the avatar picker to real platform avatars
+
+## Problem
+
+[src/editor/launchpad-studio.js](../../src/editor/launchpad-studio.js) is the no-code builder for white-label launchpads. Step 2 of the wizard ("Identity") asks the user to provide an avatar for their launchpad page. The current picker accepts a URL field as free-form text input. This puts the burden on the user to know and copy a valid GLB URL.
+
+Professional result: the picker should show the user's own three.ws avatars and the platform's gallery — with URL entry as a fallback for power users. This is the same pattern already implemented in the agent-edit and character-studio flows.
+
+## Target files
+
+- [src/editor/launchpad-studio.js](../../src/editor/launchpad-studio.js) — the wizard's identity step
+- [pages/launchpad.html](../../pages/launchpad.html) — the host page (no changes expected, but verify the module is correctly imported)
+
+## Data sources
+
+**User's own avatars** (if logged in):
+```
+GET /api/agents?owner=me&limit=20
+```
+Returns `{ agents: [{ id, name, avatar_url, meta: { avatar: { url } } }] }`.
+Use `agent.meta?.avatar?.url || agent.avatar_url` for the GLB URL.
+
+**Platform gallery avatars**:
+```
+GET /api/avatars?limit=24&sort=popular
+```
+Returns `{ avatars: [{ id, name, thumbnail_url, glb_url }] }`.
+
+Both endpoints already exist. Use `credentials: 'include'` on the fetch. If the user is not logged in, the `/api/agents?owner=me` call returns 401 or an empty list — skip it gracefully.
+
+## Outcome
+
+Replace the bare URL `<input>` in the identity step with a three-section picker:
+
+### Section 1 — My Agents (shown only when logged in, hidden if empty)
+A horizontal scroll strip of avatar thumbnails. Each card shows:
+- Thumbnail image (use `agent.meta?.avatar?.thumbnail_url` if available, else the GLB URL rendered via `<img>` with the platform viewer as a fallback icon)
+- Agent name
+
+On click: select this avatar, populate the hidden `avatar_url` field, highlight the selected card.
+
+### Section 2 — Platform Gallery
+Same card strip but from `/api/avatars`. Show 8 cards, with a "Show more" button that loads the next page.
+
+### Section 3 — Custom URL (collapsed by default, expandable with "Or enter a URL →")
+The existing URL `<input>`. Keep this for power users but de-emphasize it visually.
+
+## Implementation notes
+
+1. In `launchpad-studio.js`, find where the identity form is rendered (search for `avatar` or `url` field in the wizard step). Wrap the new picker in a `div.lsp-avatar-picker` container.
+2. Fetch both data sources in parallel (`Promise.allSettled`) when the identity step renders. Show a skeleton row while loading.
+3. Store the selected avatar URL in the same `formData.avatar_url` field the rest of the studio already uses. No new state shape.
+4. Selected state: `lsp-avatar-card.is-selected` CSS class + `aria-pressed="true"`. Only one card can be selected at a time. Clicking a different card deselects the previous.
+5. Thumbnail images: use `loading="lazy"`. Gracefully handle broken images with an `onerror` that shows a generic avatar icon (use `/public/avatars/default.png` or the site's existing fallback).
+6. Mobile: cards are `64px × 64px` with a `4px` selection ring. The strip is `overflow-x: auto` with `-webkit-overflow-scrolling: touch`.
+
+## Definition of done
+
+- `npm run dev`. Visit `/launchpad`. Proceed to the identity step.
+- If logged in: "My Agents" section appears with real agent thumbnails. Clicking one selects it and the preview renders that avatar.
+- "Platform Gallery" section shows real avatars from `/api/avatars`.
+- Clicking any gallery card selects it; the preview updates.
+- "Or enter a URL" expands and accepts a custom GLB URL as before.
+- If not logged in: "My Agents" section is hidden; Gallery and URL fallback still work.
+- The published launchpad config (`POST /api/launchpad/publish`) includes the selected `avatar_url`.
+- No console errors.
+- `npm test` green.
+- Completionist subagent run on changed files.
diff --git a/tasks/launchpad/06-agent-coin-shared-widget.md b/tasks/launchpad/06-agent-coin-shared-widget.md
new file mode 100644
index 000000000..b6a9882db
--- /dev/null
+++ b/tasks/launchpad/06-agent-coin-shared-widget.md
@@ -0,0 +1,74 @@
+# 06 — Shared coin-status widget: extract and unify across pages
+
+## Problem
+
+Live coin status logic (price, market cap, % to graduation, 24h volume, quick buy/sell links) is independently implemented in at least three places:
+
+| File | What it does |
+|------|-------------|
+| [src/agent-detail.js](../../src/agent-detail.js) | `renderTokenSection` — displays the agent's current token chip + launch history rows with streamed market caps |
+| [src/agent-home-pumpfun.js](../../src/agent-home-pumpfun.js) | `mountPumpFunCard` — inline trade panel, live quote, graduation progress |
+| [src/launches.js](../../src/launches.js) | `launchCard` market cap enrichment — streams `/api/pump/coin` per card |
+
+Each implementation fetches `/api/pump/coin?mint=<mint>` independently, formats numbers independently, and handles loading/error states independently. When the API response shape changes, all three need to be updated. Adding a new field (e.g. holder count or recent trade sparkline) requires three edits.
+
+## Target files
+
+**New file to create**:
+- `src/pump/coin-status-card.js` — shared ES module
+
+**Files to refactor**:
+- [src/agent-detail.js](../../src/agent-detail.js) — replace inline market cap enrichment with the shared module
+- [src/agent-home-pumpfun.js](../../src/agent-home-pumpfun.js) — replace inline coin data fetch with the shared module
+- [src/launches.js](../../src/launches.js) — replace per-card `/api/pump/coin` fetch with the shared module
+
+## Outcome
+
+`src/pump/coin-status-card.js` exports a single function:
+
+```js
+/**
+ * Mounts a live coin-status display into `container`.
+ *
+ * @param {HTMLElement} container — where to render
+ * @param {string} mint — Solana mint address (base58)
+ * @param {object} [opts]
+ * @param {string} [opts.variant] — 'chip' | 'row' | 'card' (default: 'chip')
+ * @param {number} [opts.refreshMs] — live-refresh interval (default: 30_000, 0 to disable)
+ * @param {boolean} [opts.showBuy] — show "Buy" link (default: false)
+ * @returns {{ destroy: () => void }} — cleanup handle
+ */
+export function mountCoinStatus(container, mint, opts = {}) { … }
+```
+
+**Variants:**
+- `chip` (default) — compact inline chip: symbol, price, mcap, graduation %. Used in agent-detail token section.
+- `row` — table-row-style layout with mint address, volume, and time. Used in agent-detail launch history.
+- `card` — full card with name, price, mcap bar, volume, buy link, time-since-launch. Used in launches feed enrichment.
+
+**Data source**: single `GET /api/pump/coin?mint=<mint>`. Map response fields once in this module; all three consumers benefit.
+
+**Live refresh**: the module owns its own `setInterval` (default 30s). Call `destroy()` to stop it. Callers do not manage refresh timers.
+
+**States**: loading skeleton → populated → error (with "Retry" button that re-fetches).
+
+## Implementation notes
+
+1. Create `src/pump/coin-status-card.js`. It imports nothing from outside the `src/pump/` directory except shared utils from `src/shared/` if they exist.
+2. Internal helper: `formatMcap(n)` → `$1.2M`, `formatPrice(n)` → `$0.00012`, `formatPct(n)` → `34%`. Copy these verbatim from the existing implementations; do not invent new formatting.
+3. Graduation ring: the `card` variant renders a small SVG arc (same as `/coin3d` graduation ring concept) from 0 to `graduation_pct`. Use a `stroke-dasharray` trick on a `<circle>` element — no canvas.
+4. "Buy" link (when `showBuy: true`): `<a href="https://pump.fun/<mint>" target="_blank" rel="noopener noreferrer" class="csc-buy">Buy →</a>`. Plain external link; no trade modal in this widget.
+5. Refactoring the three callers: replace their inline fetch + render code with `mountCoinStatus(el, mint, { variant: '...', … })`. Each caller still owns the containing `HTMLElement` — the module only populates it.
+6. Accessibility: loading state has `aria-busy="true"` on the container. Error state has `role="alert"`. Price and mcap have `aria-label` with plain-language values ("Market cap: 1.2 million dollars").
+
+## Definition of done
+
+- `src/pump/coin-status-card.js` exists and exports `mountCoinStatus`.
+- Visit `/launches` — market cap enrichment on cards is powered by the shared module (verify by adding a `console.log` in the module and seeing it fire per card, then removing the log).
+- Visit an agent detail page with a coin — the token chip and launch history rows use the shared module.
+- Visit the agent home panel for an agent with a coin — coin data is fetched via the shared module (no duplicate fetch to `/api/pump/coin` from the old inline code).
+- All three variants render correctly at their target sites.
+- A single field-name change in `mountCoinStatus` (e.g. rename `market_cap` → `mcap`) propagates to all three surfaces without touching any other file.
+- No console errors.
+- `npm test` green (add at least one unit test for `formatMcap` and `formatPct` in a `coin-status-card.test.js` alongside the module).
+- Completionist subagent run on changed files.
diff --git a/tasks/launchpad/07-tokenized-agents-skill-gate.md b/tasks/launchpad/07-tokenized-agents-skill-gate.md
new file mode 100644
index 000000000..dc76faaa4
--- /dev/null
+++ b/tasks/launchpad/07-tokenized-agents-skill-gate.md
@@ -0,0 +1,96 @@
+# 07 — Tokenized agents: wire $THREE holder gate into skill execution
+
+## Problem
+
+[pump-fun-skills/tokenized-agents/](../../pump-fun-skills/tokenized-agents/) documents the "Tokenized Agent Payments" skill: agents accept USDC or SOL payments on-chain and verify invoices. The payment infrastructure (prep + confirm) works. What does not exist is the **holder gate**: an agent can be configured to require that the calling wallet holds a minimum amount of $THREE tokens to access the agent's skills at all — the equivalent of a token-gated service.
+
+This is a core part of the three.ws value proposition: $THREE utility beyond speculation. Without this, there is no reason for users to hold $THREE to interact with agents.
+
+**$THREE contract address**: `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`
+
+## Target files
+
+**New API endpoint** (create):
+- `api/pump/check-three-balance.js` — returns whether a wallet meets a $THREE threshold
+
+**Modified files**:
+- [api/pump/[action].js](../../api/pump/[action].js) — add `check-three-balance` case to the dispatcher
+- [api/agents/](../../api/agents/) — identify the agent skill execution handler (find `handleSkillCall` or similar) and add gate check before skill invocation
+- [pump-fun-skills/tokenized-agents/SKILL.md](../../pump-fun-skills/tokenized-agents/SKILL.md) — document the gate config
+
+## How the gate works
+
+### Agent configuration
+
+An agent opts into the gate by setting in their `meta` JSON (stored in `agents.meta`):
+```json
+{
+ "three_gate": {
+ "enabled": true,
+ "min_balance": 1000
+ }
+}
+```
+`min_balance` is the minimum $THREE tokens (raw, no decimals — $THREE has 6 decimals, so 1000 raw = 0.001 $THREE). This is intentionally low to make gate-testing easy. Real agents might set 10_000_000 (= 10 $THREE).
+
+### Balance check endpoint
+
+```
+GET /api/pump/check-three-balance?wallet=<base58>&min=<raw_amount>
+```
+
+Response:
+```json
+{
+ "wallet": "…",
+ "balance": 12345678,
+ "min": 1000,
+ "eligible": true
+}
+```
+
+Implementation in `api/pump/check-three-balance.js`:
+1. Import `Connection` from `@solana/web3.js` using the `SOLANA_RPC_URL` env var (already used throughout `api/_lib/`).
+2. Fetch all token accounts for the wallet via `connection.getParsedTokenAccountsByOwner(pubkey, { mint: THREE_CA_PUBKEY })`.
+3. Sum `tokenAmount.amount` across all matching accounts.
+4. Compare to `min`. Return the result JSON.
+5. Cache the response in Upstash Redis for 30 seconds (same pattern as `/api/pump/coin` — see [api/_lib/redis.js](../../api/_lib/redis.js)). The cache key is `three-gate:<wallet>:<min>`.
+6. Return 400 if `wallet` is not a valid base58 public key (use `PublicKey` constructor in a try-catch).
+7. Return 200 in all other cases (including balance = 0, eligible = false).
+
+### Gate enforcement in skill execution
+
+Find the API handler that processes agent skill calls (search for `skill` or `handleSkill` in `api/agents/`). Before executing the skill:
+
+1. Check if `agent.meta?.three_gate?.enabled` is `true`.
+2. If yes, extract the caller's wallet from the request (it should already be present as part of the payment/auth flow — find where `caller_wallet` or `payer` is validated in existing handlers).
+3. Call the balance check (`fetch('/api/pump/check-three-balance?wallet=<wallet>&min=<min_balance>')` internally, or call the database directly).
+4. If `eligible: false`, return HTTP 402 with body:
+```json
+{
+ "error": "insufficient_three_balance",
+ "message": "This agent requires a minimum $THREE balance. Acquire $THREE to use this skill.",
+ "required": 10000000,
+ "held": 5000,
+ "buy_url": "https://pump.fun/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump"
+}
+```
+5. If `eligible: true`, proceed with skill execution as normal.
+
+### Agent settings UI
+
+In [pages/agent-edit.html](../../pages/agent-edit.html) or [pages/agent-home.html](../../pages/agent-home.html) (whichever contains the agent settings panel), add a "$THREE Gate" toggle:
+- A checkbox "Require $THREE to use this agent's skills"
+- A number input "Minimum $THREE balance" (shown when checked, default 10_000_000 = 10 $THREE)
+- Save writes to `agent.meta.three_gate` via `PATCH /api/agents/<id>` (already exists)
+
+## Definition of done
+
+- Create an agent, enable the $THREE gate with min=10_000_000.
+- Send a skill call from a wallet with 0 $THREE → receive 402 with `insufficient_three_balance` error and `buy_url`.
+- Send the same skill call from a wallet with ≥ 10_000_000 $THREE (test with a real mainnet wallet that holds $THREE, or stub the balance check in test) → skill executes normally.
+- `GET /api/pump/check-three-balance?wallet=<valid>&min=1000` returns correct `balance` and `eligible` fields.
+- `GET /api/pump/check-three-balance?wallet=invalid` returns 400.
+- The agent settings panel shows the gate toggle and min-balance field. Saving persists.
+- `npm test` green.
+- Completionist subagent run on changed files.
diff --git a/tasks/launchpad/08-nav-and-crosslinks.md b/tasks/launchpad/08-nav-and-crosslinks.md
new file mode 100644
index 000000000..7830dab83
--- /dev/null
+++ b/tasks/launchpad/08-nav-and-crosslinks.md
@@ -0,0 +1,89 @@
+# 08 — Launchpad: audit and fix all cross-links and nav entries
+
+## Problem
+
+The token launchpad has seven distinct surfaces:
+
+| Surface | URL | Purpose |
+|---------|-----|---------|
+| Launchpad Studio | `/launchpad` | White-label launchpad builder |
+| Launches Feed | `/launches` | Public feed of every agent-launched coin |
+| Pump Dashboard | `/pump-dashboard` | Per-agent coin management console |
+| Pump Live | `/pump-live` | Real-time new launch stream |
+| Pump Visualizer | `/pump-visualizer` | 3D trending token scene |
+| Token in 3D | `/coin3d` | 3D snapshot of any individual token |
+| Coin/community world | `/communities/<mint>` | Social 3D world per coin |
+
+These surfaces are not consistently cross-linked. A user who discovers `/launches` has no way to get to `/pump-live` or `/pump-visualizer`. A user on `/coin3d` cannot navigate to the launch feed filtered for that token's agent. The main nav has no "Token" or "Launch" section linking these surfaces together.
+
+This task audits every surface and adds the missing links so the launchpad feels like a cohesive product, not seven isolated pages.
+
+## Target files
+
+- [public/nav-data.js](../../public/nav-data.js) — single source of truth for nav menus (see memory: Nav single source of truth)
+- [pages/launches.html](../../pages/launches.html) — page-level links
+- [src/launches.js](../../src/launches.js) — card actions (see Task 02 for coin3d link — if 02 is done, skip that part)
+- [pages/pump-live.html](../../pages/pump-live.html) — page-level links
+- [pages/pump-visualizer.html](../../pages/pump-visualizer.html) — page-level links
+- [pages/coin3d.html](../../pages/coin3d.html) — page-level links
+- [pages/launchpad.html](../../pages/launchpad.html) — page-level links
+
+## Nav changes (nav-data.js)
+
+Check whether a "Token" or "Launch" dropdown exists in the main nav. If not, add one (or extend the existing "Platform" / "Tools" dropdown — match the existing grouping convention already in nav-data.js). The new dropdown must include:
+
+| Label | URL | Description |
+|-------|-----|-------------|
+| Launch a Coin | `/launchpad` | Create a token for your agent |
+| All Launches | `/launches` | Public feed of every agent coin |
+| Live Stream | `/pump-live` | Real-time new launches |
+| 3D Visualizer | `/pump-visualizer` | Trending tokens in 3D |
+| Token in 3D | `/coin3d` | View any token as a 3D scene |
+
+Keep the existing nav structure — do not restructure menus that already work. Only add what is missing.
+
+## Per-page cross-link additions
+
+### /launches page
+
+In the page header or below the filters row, add a compact "explore" link row:
+```
+Live stream → | 3D Visualizer → | Launchpad Studio →
+```
+
+Each link must be plain `<a>` tags with `class="lx-explore-link"` and correct `href`. No JS required.
+
+### /pump-live page
+
+In the `#header` bar (already has the page title and stats), add an "All launches →" link to `/launches` and a "Visualizer →" link to `/pump-visualizer`.
+
+### /pump-visualizer page
+
+In the `.vz-controls` overlay, add a "Feed →" link to `/pump-live` and "All launches →" to `/launches`.
+
+### /coin3d page
+
+Below the HUD or in the page header, add:
+- "All launches →" link to `/launches`
+- "3D world →" link to `/communities/<current mint>` (the mint is already in `window.location.search` — read `new URLSearchParams(location.search).get('mint')` to build the link; render it only when a mint is present)
+
+### /launchpad page
+
+On the launchpad page, in the intro or hero section, add a "See all launched coins →" link to `/launches`.
+
+## Verification steps
+
+1. `npm run dev`. Open the main nav. Confirm the new dropdown exists and all links resolve (curl-verify each).
+2. Visit each of the 5 pages above. Confirm the added links appear, have correct hrefs, and do not break existing layout.
+3. On `/coin3d?mint=<valid_mint>`, confirm the "3D world" link resolves to `/communities/<that_mint>`.
+4. Confirm no existing nav links were removed or moved.
+
+## Definition of done
+
+- Main nav has a dropdown (or expanded existing dropdown) linking all 5 launchpad surfaces.
+- Each page listed above has the specified cross-links rendered with correct hrefs.
+- `/coin3d?mint=<X>` shows a "3D world →" link to `/communities/<X>`.
+- All new links return HTTP 200 when curl'd on the dev server.
+- No layout regressions on any changed page at 375px, 768px, 1440px.
+- `npm test` green.
+- Completionist subagent run on changed files.
diff --git a/tasks/launchpad/README.md b/tasks/launchpad/README.md
new file mode 100644
index 000000000..3bf1872c2
--- /dev/null
+++ b/tasks/launchpad/README.md
@@ -0,0 +1,28 @@
+# Token Launchpad — completeness tasks
+
+Every task in this folder targets the token launchpad for 3D AI Agents as a unified product surface. The goal is a launch experience that is complete, wired, and professional — no mocks, no dead links, no missing states.
+
+Each file is independent. Pick any one and ship it end-to-end.
+
+**Operating rules (same as all tasks in this repo):**
+- No mocks. No fake data. No placeholders. No `Math.random()` standing in for real cryptography.
+- If credentials are missing, locate them in `.env`, `vercel env ls`, or ask once — then proceed.
+- Start `npm run dev`, exercise the feature in a real browser, no console errors, network tab shows real calls.
+- Run the **completionist** subagent on changed files before claiming done.
+
+## Task list
+
+| # | File | Surface | Status |
+|---|------|---------|--------|
+| 01 | [01-launch-modal-post-launch-cta.md](01-launch-modal-post-launch-cta.md) | Launch modal success state | Open |
+| 02 | [02-launches-feed-coin3d-action.md](02-launches-feed-coin3d-action.md) | /launches card actions | Open |
+| 03 | [03-pump-live-e2e-verify.md](03-pump-live-e2e-verify.md) | /pump-live WS + rendering | Open |
+| 04 | [04-pump-visualizer-data-wire.md](04-pump-visualizer-data-wire.md) | /pump-visualizer Three.js + data | Open |
+| 05 | [05-launchpad-builder-avatar-picker.md](05-launchpad-builder-avatar-picker.md) | Launchpad studio avatar picker | Open |
+| 06 | [06-agent-coin-shared-widget.md](06-agent-coin-shared-widget.md) | Shared coin-status widget | Open |
+| 07 | [07-tokenized-agents-skill-gate.md](07-tokenized-agents-skill-gate.md) | $THREE holder gate on skills | Open |
+| 08 | [08-nav-and-crosslinks.md](08-nav-and-crosslinks.md) | Cross-links between all launchpad surfaces | Open |
+
+## Already tracked elsewhere
+
+The 12 pump-dashboard panel tasks are in [../pump-dashboard-real-apis/](../pump-dashboard-real-apis/). Those are independent of this folder — ship either set in any order.
diff --git a/tasks/onchain-deployment/00-PLAN.md b/tasks/onchain-deployment/00-PLAN.md
new file mode 100644
index 000000000..981f42c35
--- /dev/null
+++ b/tasks/onchain-deployment/00-PLAN.md
@@ -0,0 +1,66 @@
+# On-Chain Deployment Completion Plan
+
+Goal: make the three.ws on-chain layer for 3D AI Agents **complete, correct, and
+production-professional** — every contract deployed, every address verified,
+every registration flow wired end-to-end, and a smoke harness that proves it.
+
+This is the index. Each task below is a self-contained `.md` brief that an agent
+can execute independently. They are ordered by dependency; the **Wave** column
+shows what can run in parallel.
+
+## Current state (verified 2026-06-14)
+
+Solid:
+- ERC-8004 contracts (`contracts/src/{Identity,Reputation,Validation}Registry.sol`),
+ 25 passing Foundry tests.
+- IdentityRegistry + ReputationRegistry deployed deterministically (CREATE2) on
+ 15 mainnet + 7 testnet chains.
+- Pump.fun launch / trade / agent-payments fully built (`api/pump/`, `agent-payments-sdk/`).
+- x402 rails live on Solana + Base (`api/x402/`, `api/_lib/x402-*.js`).
+- SNS `*.threews.sol` subdomain minting (`src/solana/sns-subdomain.js`).
+- Specs published: avatar schema v1, agent-manifest v0.2, 3D Agent Card v1.
+
+Gaps (what these tasks close):
+1. Mainnet ValidationRegistry never deployed → mainnet `recordValidation()` throws.
+2. ThreeWSPayments on Base mined-but-no-bytecode → treat as not deployed.
+3. Solana `agent_invocation` program uses a placeholder ID, never deployed.
+4. three.ws self-registration record is empty.
+5. DEPLOYMENTS.md tx-hash provenance is all `TODO`; no address-parity guard.
+6. No "bind an existing agent to an on-chain identity" product flow.
+7. ValidationRegistry attestation not auto-wired into registration.
+8. ReputationRegistry data never surfaced in the UI.
+9. Solana relayer/buyback/distribution signers unfunded; devnet smoke unrun.
+10. No end-to-end on-chain smoke harness.
+
+## Task list
+
+| # | Task | Wave | Blocks |
+|---|------|------|--------|
+| 01 | Deploy mainnet ValidationRegistry (15 chains) + wire addresses | 1 | 06, 07 |
+| 02 | Re-deploy ThreeWSPayments on Base + verify bytecode | 1 | 10 |
+| 03 | Deploy Solana `agent_invocation` program + replace placeholder ID | 1 | 10 |
+| 04 | Register three.ws itself (ERC-8004) + fill `.well-known` record | 2 | — |
+| 05 | Backfill DEPLOYMENTS.md provenance + address-parity guard script | 1 | — |
+| 06 | "Bind existing agent → on-chain" flow + auto-populate manifest | 2 | 10 |
+| 07 | Wire ValidationRegistry attestation into registration + allowlist | 2 | — |
+| 08 | Surface ReputationRegistry in agent profiles + `/agents` directory | 2 | — |
+| 09 | Fund Solana relayers, verify buyback/distribution crons + devnet smoke | 1 | 10 |
+| 10 | On-chain end-to-end smoke harness (CI-runnable) | 3 | — |
+
+## Definition of done (whole plan)
+
+- No client code path throws "no registry deployed" on any supported mainnet chain.
+- Every address in `src/erc8004/abi.js`, `sdk/src/erc8004/abi.js`, and
+ `api/_lib/erc8004-chains.js` is identical and matches an on-chain contract with code.
+- DEPLOYMENTS.md has a real explorer tx link for every deployed contract.
+- A user can create an agent, bind it on-chain, and see it resolve, validate, and
+ carry reputation — all from the product UI, no manual scripts.
+- `node scripts/onchain-smoke.mjs` (task 10) passes against testnet/devnet in CI.
+
+## Hard rules (inherited from CLAUDE.md)
+
+- The only coin is `$THREE` (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Never
+ reference any other mint in code, fixtures, or docs. Use synthetic placeholders.
+- No mocks, no stubs, no `throw new Error("not implemented")`. Real RPC, real APIs.
+- Stage explicit paths before committing (concurrent agents share this worktree).
+- `npx vercel build` clobbers `api/*.js` — never commit esbuild bundles.
diff --git a/tasks/onchain-deployment/01-deploy-mainnet-validation-registry.md b/tasks/onchain-deployment/01-deploy-mainnet-validation-registry.md
new file mode 100644
index 000000000..aeddd547a
--- /dev/null
+++ b/tasks/onchain-deployment/01-deploy-mainnet-validation-registry.md
@@ -0,0 +1,87 @@
+# Task: Deploy Mainnet ValidationRegistry + Wire Addresses
+
+## Context
+
+three.ws ships ERC-8004 on-chain agent identity. IdentityRegistry and
+ReputationRegistry are deployed deterministically (CREATE2) across all 15 mainnet
+chains, but **ValidationRegistry is only on testnet**. Mainnet clients currently
+break:
+
+- `src/erc8004/abi.js` — mainnet `validationRegistry: ''` (empty string)
+- `sdk/src/erc8004/abi.js` — mainnet `validationRegistry: null`
+- `src/erc8004/validation-recorder.js` lines 63–65 — throws "No Validation
+ Registry deployed" when the address is falsy.
+
+So any user trying to record a glTF/schema validation attestation on Base mainnet
+hits a hard error. This task deploys the contract deterministically and wires the
+address everywhere.
+
+## Goal
+
+ValidationRegistry live at one deterministic address across all 15 mainnet chains,
+with that address present and identical in all three address sources, and
+`recordValidation()` working on mainnet.
+
+## Files to Read First
+
+- `contracts/script/DeployValidationMainnet.s.sol` — CREATE2 deploy script;
+ hardcodes IdentityRegistry `0x8004A169…`, Arachnid factory, salt
+ `keccak256("ValidationRegistry", 1)`, includes `computeAddress()` dry-run helper
+- `contracts/script/deploy-validation-registry.sh` — 15-chain orchestration
+- `contracts/DEPLOYMENTS.md` — deployment record (mainnet ValidationRegistry row is TODO)
+- `contracts/foundry.toml` — only Base is configured; you'll add RPC/Etherscan vars
+- `src/erc8004/abi.js`, `sdk/src/erc8004/abi.js`, `api/_lib/erc8004-chains.js` — the
+ three address sources that must agree
+
+## What to Build / Do
+
+1. **Predict the address.** Run the script in dry-run mode (`computeAddress(DEPLOYER)`)
+ to get the deterministic ValidationRegistry address. Confirm it carries the
+ `0x8004C…` vanity prefix consistent with the testnet deployment. If the salt
+ does not produce a `0x8004…` address, stop and surface — do not deploy to a
+ non-vanity address that breaks the family convention.
+
+2. **Fund the deployer.** The deployer EOA `0x4022de2D…C0564f402` needs gas on each
+ of the 15 chains. Confirm balances before broadcasting; report any underfunded
+ chain rather than partially deploying.
+
+3. **Deploy** via `deploy-validation-registry.sh` (or chain-by-chain `forge script
+ … --broadcast --verify`). Verify source on each explorer.
+
+4. **Confirm bytecode** on every chain: `cast code <addr> --rpc-url <chain>` must
+ return non-empty. A mined tx is not proof of deployment (see the Base
+ ThreeWSPayments incident in DEPLOYMENTS.md — tx succeeded, no code).
+
+5. **Wire the address** into all three sources, identically:
+ - `src/erc8004/abi.js` → mainnet `validationRegistry`
+ - `sdk/src/erc8004/abi.js` → mainnet `validationRegistry`
+ - `api/_lib/erc8004-chains.js` → each mainnet chain's registry block
+
+6. **Allow-list the platform validator** on each chain (`addValidator(<validator
+ addr>)` via `cast send`). This is owner-gated; the deployer is the owner. The
+ validator address is the key the platform uses to sign glTF attestations
+ (coordinate with task 07).
+
+7. **Update DEPLOYMENTS.md** — fill the mainnet ValidationRegistry address and one
+ tx hash per chain with explorer links (feeds task 05).
+
+## Constraints
+
+- All 15 chains or none for the address field — if a chain can't be funded, deploy
+ the rest, but mark the missing chain explicitly in DEPLOYMENTS.md and leave its
+ `erc8004-chains.js` entry pointing at the deterministic address only once code is
+ confirmed there. Never list an address that has no code.
+- Do not change the salt or factory — address parity with testnet/other contracts
+ depends on it.
+- zkSync Era uses a different EVM; verify its address separately (the script notes
+ this).
+
+## Success Criteria
+
+- `cast code <validationRegistry> --rpc-url <each mainnet chain>` returns non-empty.
+- `src/erc8004/abi.js`, `sdk/src/erc8004/abi.js`, `api/_lib/erc8004-chains.js` all
+ carry the same mainnet ValidationRegistry address (task 05's parity script passes).
+- A mainnet `recordValidation()` call from `validation-recorder.js` succeeds instead
+ of throwing.
+- DEPLOYMENTS.md mainnet ValidationRegistry row has a real address + per-chain tx links.
+- Changelog entry added (`data/changelog.json`, tag: infra/security).
diff --git a/tasks/onchain-deployment/02-redeploy-base-threews-payments.md b/tasks/onchain-deployment/02-redeploy-base-threews-payments.md
new file mode 100644
index 000000000..9e0fab2c6
--- /dev/null
+++ b/tasks/onchain-deployment/02-redeploy-base-threews-payments.md
@@ -0,0 +1,65 @@
+# Task: Re-deploy ThreeWSPayments on Base + Verify Bytecode
+
+## Context
+
+`ThreeWSPayments` is the x402 pay-per-call receiver contract. Per
+`contracts/DEPLOYMENTS.md`, it is live on BSC (`0x00000000381f…`) and Arbitrum
+(`0xed369648…`), but on **Base the deploy tx mined successfully yet the predicted
+address `0x31B13cDe…` has no code** — explicitly marked "treat as **not deployed**,
+must re-run." Base is the platform's primary EVM payment chain, so this is the most
+important x402 receiver and it's currently dead.
+
+## Goal
+
+ThreeWSPayments live on Base with confirmed bytecode, the real deployed address
+recorded, and every config/env reference pointing at it.
+
+## Files to Read First
+
+- `contracts/DEPLOYMENTS.md` — "ThreeWSPayments" section; Base row + the deploy
+ command at the bottom (`scripts/deploy-multichain.mjs` lives in the 3D-Agent repo)
+- `contracts/vanity/payments-bsc-deployed.json` — grind artifact, salt, init-code hashes
+- `api/_lib/x402-spec.js`, `api/_lib/x402-paid-endpoint.js` — where the receiver /
+ `X402_PAY_TO_BASE` is consumed (currently `0x4022de2d…`, the deployer EOA — confirm
+ whether payments should route to the contract or the EOA)
+
+## What to Build / Do
+
+1. **Diagnose the failed deploy.** The Base tx mined but produced no code — usually a
+ CREATE2 collision, an out-of-gas constructor, or a salt/init-code mismatch.
+ Re-derive the predicted address locally from the salt + Base USDC
+ (`0x833589fCD6…`) init code and compare to `0x31B13cDe…`. Decide: re-use the
+ vanity salt (accepting a non-zero-prefix address, as the doc notes Base never
+ landed the prefix) or grind a fresh Base-specific salt.
+
+2. **Fund + deploy.** Deployer EOA needs ETH on Base. Run the multichain deploy
+ (Base only) with the chosen salt.
+
+3. **Confirm bytecode** — `cast code <addr> --rpc-url $BASE_RPC_URL` must be
+ non-empty. Do not record the address until this passes.
+
+4. **Verify source** on Basescan.
+
+5. **Decide payment routing.** If x402 on Base is meant to settle into this contract
+ rather than the EOA, update `X402_PAY_TO_BASE` (Vercel env via REST API — the CLI
+ writes empty secrets) and any hardcoded reference. If the EOA is intentional
+ (simple receiver), document that and leave it, but still record the contract.
+
+6. **Update DEPLOYMENTS.md** — replace the Base "not deployed" warning with the real
+ address + tx link, and note bytecode confirmed.
+
+## Constraints
+
+- A mined tx is NOT proof of deployment — bytecode check is mandatory.
+- Do not touch the BSC/Arbitrum rows; they're live.
+- Never force config to an address with no code.
+- Env writes go through the Vercel REST API, not `vercel env add` (writes empty
+ secrets under the plugin wrapper).
+
+## Success Criteria
+
+- `cast code <base ThreeWSPayments> --rpc-url $BASE_RPC_URL` returns non-empty.
+- Contract verified on Basescan.
+- DEPLOYMENTS.md Base row shows the real address + tx link, no warning.
+- x402 Base payment routing is correct and documented.
+- An x402 paid call on Base settles to the intended recipient (verify with task 10).
diff --git a/tasks/onchain-deployment/03-deploy-solana-agent-invocation.md b/tasks/onchain-deployment/03-deploy-solana-agent-invocation.md
new file mode 100644
index 000000000..70e5e0f61
--- /dev/null
+++ b/tasks/onchain-deployment/03-deploy-solana-agent-invocation.md
@@ -0,0 +1,72 @@
+# Task: Deploy Solana `agent_invocation` Program + Replace Placeholder ID
+
+## Context
+
+`agent-protocol-sdk/` is a typed client for an Anchor program (`contracts/agent-invocation/`)
+that records verifiable agent-to-agent skill invocations on Solana. It is **not
+production-ready**: the program ID is the Anchor placeholder
+`Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS`, the program is not deployed to any
+live cluster, and the SDK README warns callers to "deploy the program yourself and
+pass your own programId." This is the one Solana-side on-chain primitive that is
+spec'd but not live.
+
+## Goal
+
+`agent_invocation` deployed to devnet and mainnet, the real program ID baked into
+the program (`declare_id!`), the SDK default, and the IDL, with at least one
+confirmed on-chain `invoke_skill` call.
+
+## Files to Read First
+
+- `contracts/agent-invocation/src/lib.rs` — Anchor program; `declare_id!`,
+ `invoke_skill(skill_name, parameters)`, PDA seeds `[b"agent", authority]`,
+ `SkillInvoked` event, `MAX_SKILL_NAME_LEN=64`, `MAX_PARAMETERS_LEN=512`
+- `contracts/idl/` — committed IDL (must be regenerated after deploy)
+- `agent-protocol-sdk/src/index.ts` — `AGENT_INVOCATION_PROGRAM_ID`, `invokeSkill()`
+- `agent-protocol-sdk/README.md` — current "not deployed" warnings to update
+- `api/_lib/pump.js` — RPC selection (`SOLANA_RPC_URL`, `SOLANA_RPC_URL_DEVNET`)
+
+## What to Build / Do
+
+1. **Generate a program keypair** (`solana-keygen new -o agent-invocation-keypair.json`,
+ kept OUT of the repo — store in Vercel/secret manager, document the env var name).
+ Optionally grind a vanity prefix to match house style, but don't block on it.
+
+2. **Set `declare_id!`** to the new pubkey in `lib.rs` and in `Anchor.toml`.
+
+3. **Build + deploy to devnet** first (`anchor build && anchor deploy --provider.cluster devnet`).
+ Fund the deploy authority with devnet SOL.
+
+4. **Smoke test on devnet** — run `invokeSkill()` from the SDK against the deployed
+ program with two synthetic agent authorities; confirm the `SkillInvoked` event
+ parses and the tx confirms. Add this as a script under `scripts/`.
+
+5. **Deploy to mainnet** once devnet passes. Fund the mainnet deploy authority.
+ Record the deploy signature.
+
+6. **Wire the real ID everywhere:**
+ - `agent-protocol-sdk/src/index.ts` → `AGENT_INVOCATION_PROGRAM_ID`
+ - regenerate + commit `contracts/idl/agent_invocation.json`
+ - remove "not deployed / placeholder" warnings from the SDK README; replace with
+ the live program ID + cluster note
+ - add a `contracts/agent-invocation/DEPLOYMENT.md` with both cluster addresses + sigs
+
+7. **Set the program upgrade authority** deliberately — either a known platform key
+ (document it) or make it immutable. Do not leave it as an ephemeral local key.
+
+## Constraints
+
+- Never commit the program keypair or deploy-authority secret.
+- Use synthetic agent authorities in tests — never a real third-party wallet.
+- The SDK must default to the live mainnet ID but still accept a `programId` override
+ (keep that param).
+- Devnet must pass before mainnet deploy.
+
+## Success Criteria
+
+- `solana program show <programId>` returns the program on both devnet and mainnet.
+- `agent-protocol-sdk` default ID is the live program; IDL regenerated and committed.
+- A confirmed `invoke_skill` tx exists on devnet (script under `scripts/`, re-runnable).
+- README no longer says "not deployed"; `DEPLOYMENT.md` records both clusters.
+- Upgrade authority is intentional and documented.
+- Changelog entry (tag: sdk/infra).
diff --git a/tasks/onchain-deployment/04-register-threews-self-erc8004.md b/tasks/onchain-deployment/04-register-threews-self-erc8004.md
new file mode 100644
index 000000000..4178025f9
--- /dev/null
+++ b/tasks/onchain-deployment/04-register-threews-self-erc8004.md
@@ -0,0 +1,69 @@
+# Task: Register three.ws Itself On-Chain (ERC-8004)
+
+## Context
+
+`public/.well-known/agent-registration.json` is three.ws's own ERC-8004 v1
+registration record — the discovery document that other agents and indexers read to
+verify three.ws is a real on-chain agent platform. It currently has
+`registrations: []` (empty). The platform tells users to register their agents
+on-chain but has not registered itself, which is the kind of detail a discerning
+integrator notices immediately. Eating our own dog food here is both correct and a
+credibility signal.
+
+## Goal
+
+three.ws registered as agent #N in the IdentityRegistry (Base mainnet, with a Base
+Sepolia testnet record too), its `tokenURI` pointing at a real 3D Agent Card v1
+manifest, and the `.well-known` document populated with the resulting registration(s).
+
+## Files to Read First
+
+- `public/.well-known/agent-registration.json` — the record to populate
+- `public/.well-known/3d-agent-card.schema.json` — the Card v1 schema
+- `specs/3D_AGENT_CARD.md` — required fields (type[], name, image, model{uri,sha256},
+ registrations[], supportedTrust)
+- `src/erc8004/agent-registry.js` — `registerAgent()` reference flow
+- `src/erc8004/registration-json.js` — `buildRegistrationJSON()` (importable server-side)
+- `src/erc8004/abi.js` — registry addresses
+
+## What to Build / Do
+
+1. **Pick three.ws's canonical avatar/GLB** for the platform agent (a real asset
+ from `public/avatars/` — not a placeholder). Compute its sha256.
+
+2. **Build the 3D Agent Card v1** for three.ws: name "three.ws", description, image
+ (poster), `model.{uri,format,sha256,polygonCount,boundingBox,license}`, `type`
+ array including both the ERC-8004 and `https://three.ws/specs/3d-agent-card-v1`
+ URIs, `supportedTrust: ["reputation","validation"]`, and the platform's A2A/MCP
+ service endpoints (mirror what's already in the `.well-known` record's services).
+
+3. **Pin the GLB + card** to IPFS (or R2 via `/api/erc8004/pin`). Verify the bytes at
+ `model.uri` hash to `model.sha256` (the spec's mandatory verification point 3).
+
+4. **Mint** on Base Sepolia first (cheap dry-run of the whole flow), then Base
+ mainnet: `register(seedURI)` → extract `agentId` from the `Registered` event →
+ `setAgentURI(agentId, cardURL)`.
+
+5. **Populate `agent-registration.json`** `registrations[]` with the real entries:
+ `{ agentId, agentRegistry: "eip155:8453:0x8004A169…" }` for mainnet and the
+ Sepolia equivalent. Keep the existing services/x402 fields.
+
+6. **Confirm resolution** — `api/_lib/onchain.js` `tokenURI(agentId)` returns the card
+ URL, and the card validates against the schema.
+
+## Constraints
+
+- Real asset, real IPFS/R2 pin, real mint. No placeholder CIDs.
+- The signer is the platform deployer key — handle it via env, never commit it.
+- `model.sha256` MUST match the pinned bytes or the card is "unverified" per spec.
+- Only `$THREE` may be referenced if a token is mentioned anywhere in the card.
+
+## Success Criteria
+
+- three.ws appears as a registered agent in IdentityRegistry on Base (+ Sepolia).
+- `public/.well-known/agent-registration.json` `registrations[]` is non-empty with
+ real agentIds.
+- The card at `tokenURI` validates against `3d-agent-card.schema.json` and its
+ `model.sha256` matches the pinned GLB.
+- Visiting the platform agent profile renders the on-chain badge.
+- Changelog entry (tag: feature/infra).
diff --git a/tasks/onchain-deployment/05-backfill-provenance-and-parity-guard.md b/tasks/onchain-deployment/05-backfill-provenance-and-parity-guard.md
new file mode 100644
index 000000000..3799163b3
--- /dev/null
+++ b/tasks/onchain-deployment/05-backfill-provenance-and-parity-guard.md
@@ -0,0 +1,71 @@
+# Task: Backfill Deployment Provenance + Address-Parity Guard
+
+## Context
+
+`contracts/DEPLOYMENTS.md` is the authoritative deployment record, but every
+deployed contract's **Tx Hash column says `TODO: fill after deployment`** — even for
+contracts that are demonstrably live (IdentityRegistry, ReputationRegistry on 15
+chains). There's no verifiable on-chain provenance, and no committed Foundry
+broadcast logs. Separately, the same registry addresses are duplicated by hand
+across **three** files that can silently drift:
+
+- `src/erc8004/abi.js` (`REGISTRY_DEPLOYMENTS`)
+- `sdk/src/erc8004/abi.js`
+- `api/_lib/erc8004-chains.js`
+
+A professional on-chain deployment has reproducible provenance and a guard that
+fails the build if these drift. This task adds both.
+
+## Goal
+
+Every live contract in DEPLOYMENTS.md has a real explorer tx link, and a committed
+script verifies that all three address sources agree with each other and with
+on-chain bytecode.
+
+## Files to Read First
+
+- `contracts/DEPLOYMENTS.md` — the record to backfill
+- `src/erc8004/abi.js`, `sdk/src/erc8004/abi.js`, `api/_lib/erc8004-chains.js`
+- `scripts/audit-deploy-artifacts.mjs` — existing build-gate audit (follow its style;
+ this is where the parity check should hook in or sit beside)
+- `package.json` — how audit scripts are wired into the build
+
+## What to Build / Do
+
+1. **Recover deploy tx hashes.** For each deployed registry on each chain, query the
+ chain (or the deployer EOA's history / CREATE2 factory events) for the deployment
+ tx and fill DEPLOYMENTS.md with explorer-linked hashes. Where a tx genuinely
+ cannot be recovered, write `verified by bytecode (tx unrecoverable)` with the
+ `cast code` confirmation date rather than leaving `TODO`.
+
+2. **Write `scripts/verify-onchain-parity.mjs`** that:
+ - Loads `REGISTRY_DEPLOYMENTS` from all three sources.
+ - Asserts every chainId present in one is present in all, with byte-identical
+ addresses per (chain, contract).
+ - For a configurable subset (at least Base mainnet + Base Sepolia), does a live
+ `eth_getCode` and asserts non-empty bytecode at each non-null address.
+ - Asserts no address is a non-empty string while another source has it null/empty
+ for the same slot (the ValidationRegistry drift trap).
+ - Exits non-zero with a precise diff on any mismatch.
+
+3. **Wire it into the build gate** alongside `audit-deploy-artifacts.mjs` so a drift
+ fails CI/the Vercel build.
+
+4. **Add `npm run verify:onchain`** to package.json.
+
+## Constraints
+
+- The live-bytecode portion must degrade gracefully when RPC is unreachable in CI
+ (warn, don't hard-fail on network error) but MUST hard-fail on an actual address
+ mismatch (that's a config bug, always real).
+- Do not auto-edit the abi files from the script — it verifies, humans fix.
+- Don't commit Foundry `broadcast/` bundles wholesale; link explorer tx hashes instead.
+
+## Success Criteria
+
+- DEPLOYMENTS.md has a real tx link (or explicit bytecode-verified note) for every
+ deployed contract — no remaining `TODO` for live contracts.
+- `node scripts/verify-onchain-parity.mjs` passes when the three sources agree and
+ fails with a clear diff when they don't (test by temporarily editing one address).
+- The check runs in the build gate.
+- `npm run verify:onchain` exists.
diff --git a/tasks/onchain-deployment/06-bind-existing-agent-onchain.md b/tasks/onchain-deployment/06-bind-existing-agent-onchain.md
new file mode 100644
index 000000000..ace4a6b19
--- /dev/null
+++ b/tasks/onchain-deployment/06-bind-existing-agent-onchain.md
@@ -0,0 +1,79 @@
+# Task: "Bind Existing Agent → On-Chain" Flow + Auto-Populate Manifest
+
+## Context
+
+Today, on-chain registration (`src/erc8004/agent-registry.js` `registerAgent()`)
+runs in isolation: it takes a GLB + metadata and mints fresh. There is **no product
+path to take an agent that already exists in `agent_identities` and bind it to an
+on-chain identity** — the user must re-enter everything. Two concrete gaps from the
+audit:
+
+1. No "Register this agent on-chain" action on an existing agent profile that reuses
+ the agent's stored GLB/metadata and writes the result back to
+ `agent_identities.meta.onchain`.
+2. The 3D Agent Card v1 has an optional `manifest` field (pointer to the rich
+ Claude-shaped agent-manifest bundle) that is **never auto-populated** during
+ registration, so on-chain agents lose their instructions/skills/memory linkage.
+
+## Goal
+
+From an existing agent's profile, a user can bind it on-chain in one flow that reuses
+stored assets, auto-builds + pins the agent-manifest, sets it as the card's
+`manifest` field, and persists the on-chain identity back to the DB.
+
+## Files to Read First
+
+- `src/erc8004/agent-registry.js` — `registerAgent()`, `ensureWallet()`,
+ `buildRegistrationJSON()`, pin helpers
+- `src/erc8004/registration-json.js` — Card v1 builder (add `manifest` support if missing)
+- `specs/AGENT_MANIFEST.md` — the manifest bundle shape (manifest.json + instructions
+ + skills + memory + body.glb)
+- `api/_lib/migrations/2026-04-29-onchain-unified.sql` — `agent_identities.meta.onchain` shape
+- `api/erc8004/[action].js` + `api/erc8004/register-confirm.js` — pin + index endpoints
+- `src/agent-home.js` (or wherever the agent profile/edit UI lives) — where the
+ "Bind on-chain" entry point goes
+
+## What to Build / Do
+
+1. **Add a `buildAgentManifest(agent)` helper** that assembles the agent-manifest/0.2
+ bundle from the agent's stored data: `manifest.json` (body, brain, voice, skills,
+ memory mode, tools, permissions), `instructions.md`, the GLB, and any installed
+ skills. Pin the bundle, return its URI.
+
+2. **Add `bindExistingAgentOnchain(agentId, chainId)`** in `agent-registry.js` that:
+ - Loads the agent's stored GLB + metadata (no re-entry).
+ - Builds + pins the manifest (step 1), captures its URI.
+ - Builds the Card v1 with `manifest` set to that URI.
+ - Pins the card, mints `register(seedURI)`, sets `setAgentURI`.
+ - POSTs to `register-confirm` so `meta.onchain` is written
+ (chain, family:"evm", tx_hash, onchain_id, contract_or_mint, wallet,
+ metadata_uri, confirmed_at).
+
+3. **Surface a "Register on-chain" action** on the agent profile UI, with all designed
+ states: not-registered (CTA), pending (tx in flight), registered (badge + chain +
+ agentId + explorer link), error (actionable). Idempotent — if already bound on that
+ chain, show the existing identity, don't double-mint.
+
+4. **Make `registration-json.js` accept + emit the `manifest` field** if it doesn't
+ already.
+
+## Constraints
+
+- Reuse the agent's existing pinned GLB if one exists — don't re-pin identical bytes.
+- Last-write-wins is fine for re-binding metadata, but never mint a second token on a
+ chain the agent is already registered on.
+- Best-effort manifest: if a skill asset fails to pin, surface which one — don't
+ silently ship a partial manifest.
+- Wallet connect must reuse an existing authorized connection (no forced popup).
+
+## Success Criteria
+
+- From an existing agent profile, "Register on-chain" completes without re-entering
+ GLB/metadata.
+- The resulting Card v1 has a populated `manifest` URI that resolves to a valid
+ agent-manifest/0.2 bundle.
+- `agent_identities.meta.onchain` is written; the profile shows the on-chain badge +
+ explorer link on reload.
+- Re-running on the same chain is a no-op (idempotent), not a second mint.
+- Every UI state (none/pending/done/error) is designed. No console errors.
+- Changelog entry (tag: feature).
diff --git a/tasks/onchain-deployment/07-wire-validation-attestation.md b/tasks/onchain-deployment/07-wire-validation-attestation.md
new file mode 100644
index 000000000..5fda8043d
--- /dev/null
+++ b/tasks/onchain-deployment/07-wire-validation-attestation.md
@@ -0,0 +1,73 @@
+# Task: Wire ValidationRegistry Attestation Into Registration
+
+## Context
+
+ValidationRegistry stores hashes of off-chain proofs (glTF validation, schema
+checks) signed by an allow-listed validator. The contract, the recorder
+(`src/erc8004/validation-recorder.js`), and the panel UI exist, but nothing
+**automatically validates an agent's GLB and records an on-chain attestation when
+the agent is registered**. The validator allow-list is also maintained by hand.
+Result: `supportedTrust: ["validation"]` is advertised in the 3D Agent Card but no
+agent actually carries a validation attestation. Depends on task 01 (mainnet
+ValidationRegistry must exist).
+
+## Goal
+
+When an agent is registered (or bound) on-chain, its GLB is automatically run through
+glTF validation and a signed attestation is recorded on-chain, surfaced as a
+"validated" badge on the profile.
+
+## Files to Read First
+
+- `src/erc8004/validation-recorder.js` — `reportPassed()`, `hashReport()`,
+ `recordValidation()`; throws if ValidationRegistry not deployed (fixed by task 01)
+- `contracts/src/ValidationRegistry.sol` — `recordValidation()`, `getLatestByKind()`,
+ validator allowlist, `kind` strings ("glb-schema", "a2a-card")
+- `src/erc8004/agent-registry.js` — registration flow to hook into (post-`setAgentURI`)
+- `api/_lib/onchain.js` — server resolver (add a "read latest validation" path)
+- `api/model-check.js` / `api/x402/model-check.js` — existing glTF validation endpoint
+ (reuse it — do NOT write a second validator)
+
+## What to Build / Do
+
+1. **Provision the platform validator key.** A dedicated Solana/EVM key that signs
+ attestations; allow-list it on each ValidationRegistry chain (coordinate with task
+ 01 step 6). Store via env, never commit.
+
+2. **After a successful registration/bind**, kick a best-effort validation:
+ - Run the agent's GLB through the existing glTF validator (`api/model-check`).
+ - Build the report, `hashReport()` it, pin the full report to IPFS/R2.
+ - Call `recordValidation(agentId, passed, proofHash, proofURI, kind:"glb-schema")`
+ signed by the platform validator key.
+
+3. **Add a server read path** in `api/_lib/onchain.js` (or a small `api/v1/agents`
+ addition) that returns the latest validation for an agent via `getLatestByKind`,
+ so the frontend doesn't need a wallet to display the badge.
+
+4. **Render a "Validated" badge** on the agent profile when a passing attestation
+ exists (with link to the proof report + the on-chain record). Designed states:
+ validated, validation-failed (show what failed), not-yet-validated, pending.
+
+5. **Make validation re-runnable** — re-validating after a GLB update records a fresh
+ attestation; the badge reflects the latest.
+
+## Constraints
+
+- Reuse the existing glTF validator endpoint — one source of truth for "is this GLB valid."
+- Validation is best-effort and async: a validation failure must NOT block or revert
+ the registration itself (the agent is still registered; it's just unvalidated).
+- Per spec: a passing validation report does NOT override the sha256 byte-check — both
+ matter; surface them independently.
+- Only allow-listed keys can record; handle the "not allow-listed on this chain" case
+ with a clear ops error, not a silent skip.
+
+## Success Criteria
+
+- Registering/binding an agent results in an on-chain validation attestation within
+ a short window (verify via `getLatestByKind`).
+- The agent profile shows a "Validated" badge backed by a real on-chain record + a
+ resolvable proof report.
+- A failing GLB records a failing attestation and shows the failure reason — the
+ agent is still registered.
+- No second glTF validator was introduced.
+- Changelog entry (tag: feature/security).
diff --git a/tasks/onchain-deployment/08-surface-reputation-onchain.md b/tasks/onchain-deployment/08-surface-reputation-onchain.md
new file mode 100644
index 000000000..b58576f51
--- /dev/null
+++ b/tasks/onchain-deployment/08-surface-reputation-onchain.md
@@ -0,0 +1,65 @@
+# Task: Surface ReputationRegistry in Agent Profiles + Directory
+
+## Context
+
+ReputationRegistry is deployed on 15 mainnet + 7 testnet chains and the submission
+panel (`src/erc8004/reputation-panel.js`) exists, but the data is **dormant** — no
+aggregation into agent profiles, no badge in the `/agents` directory, no read path.
+The 3D Agent Card advertises `supportedTrust: ["reputation"]` while the product shows
+none of it. This is a half-built feature in the CLAUDE.md sense: the capability
+exists but isn't wired so users can see or use it.
+
+## Goal
+
+On-chain reputation (average score + feedback count + stake) is read, aggregated, and
+displayed on every on-chain agent's profile and in the directory, and any user can
+submit feedback from the profile.
+
+## Files to Read First
+
+- `contracts/src/ReputationRegistry.sol` — `getReputation()` returns `(avgX100, count)`,
+ `getFeedbackCount()`, `getTotalStake()`, `submitFeedback()`, `stakeReputation()`
+- `src/erc8004/reputation-panel.js` — existing submit UI
+- `api/_lib/onchain.js` — server resolver (add reputation read)
+- `src/launches.js` and the `/agents` directory renderer — where badges render
+- `api/v1/agents/[caip].js` (if present) — agent read API
+
+## What to Build / Do
+
+1. **Add a server read path** in `api/_lib/onchain.js`: given an agent's
+ chain + registry + agentId, call `getReputation()` and `getFeedbackCount()` (and
+ optionally `getTotalStake()`), divide `avgX100` by 100 client-safe, cache briefly.
+ Expose via the existing agent read API so no wallet is needed to display.
+
+2. **Render a reputation badge** on the agent profile: average score (e.g. ★ 4.2),
+ feedback count, and stake total if non-zero. Designed states: has-reputation,
+ no-feedback-yet ("Be the first to review"), unsupported-chain.
+
+3. **Add reputation to the `/agents` directory cards** and enable **sort by reputation**
+ (the CLAUDE.md innovation standard: if the list lacks sorting, add it).
+
+4. **Wire the submit flow** from the profile: the existing `reputation-panel.js`
+ `submitFeedback()` → on success, optimistically update the badge and refresh from
+ chain. Enforce the contract's rules client-side too (no self-review, score
+ -100..+100, one review per reviewer) with clear messaging.
+
+5. **Optional staking entry point** — surface `stakeReputation()` for users who want
+ to back an agent, showing the min stake (0.001 ETH) and current total.
+
+## Constraints
+
+- Read path must work without a connected wallet (public RPC read).
+- Respect the contract's precision contract: it returns `avgX100`; never round on-chain
+ — divide for display only.
+- Cache reads (reputation changes slowly) but invalidate after a user submits.
+- Handle agents on chains where reputation is unsupported gracefully (hide, don't error).
+
+## Success Criteria
+
+- Every on-chain agent profile shows its real on-chain reputation (or a designed
+ empty state).
+- The `/agents` directory shows reputation and can sort by it.
+- Submitting feedback from a profile writes on-chain and the badge updates.
+- Self-review / out-of-range / double-review are blocked with clear UX before the tx.
+- No console errors; works without a wallet for read-only viewing.
+- Changelog entry (tag: feature).
diff --git a/tasks/onchain-deployment/09-fund-solana-relayers-verify-crons.md b/tasks/onchain-deployment/09-fund-solana-relayers-verify-crons.md
new file mode 100644
index 000000000..2c8b8e38e
--- /dev/null
+++ b/tasks/onchain-deployment/09-fund-solana-relayers-verify-crons.md
@@ -0,0 +1,82 @@
+# Task: Fund Solana Relayers + Verify Buyback/Distribution Crons + Devnet Smoke
+
+## Context
+
+The pump.fun agent-payments machinery is fully built but several on-chain execution
+paths are **conditionally wired and currently unfunded/unverified**:
+
+- Buyback + distribution crons require `PUMP_CRON_RELAYER_SECRET_KEY_B64` — a funded
+ Solana keypair — to pay tx fees and swap gas (`api/pump/[action].js` distribute /
+ buyback handlers, `pump_distribute_runs` / `pump_buyback_runs` audit tables).
+- The devnet smoke trade for `pump buy-prep` "awaits a funded signer" (per ops memory).
+- SNS subdomain minting needs `THREEWS_SOL_PARENT_SECRET_BASE58`; returns 503 when unset.
+- Agent authority keypairs and the collection authority need SOL for fees.
+
+Without funded signers + a verification pass, these flows are "deployed" but not
+provably working — exactly the gap this plan closes.
+
+## Goal
+
+Every Solana execution signer the platform relies on is funded and verified, the
+buyback/distribution crons demonstrably run a real on-chain tx on devnet, and the
+pump buy-prep devnet smoke trade passes.
+
+## Files to Read First
+
+- `api/pump/[action].js` — buyback (`buyback-*`), distribute (`distribute-creator-fees-*`),
+ `launch-agent`, `buy-prep`/`buy-confirm` handlers
+- `api/cron/pump-agent-stats.js` and any pump distribute/buyback cron entry
+- `api/_lib/pump.js` — RPC selection, signer loading, network handling
+- `api/_lib/migrations/2026-04-30-pump-fun.sql` — `pump_distribute_runs`, `pump_buyback_runs`
+- `vercel.json` — cron schedule registrations
+- Ops memory: `tasks/` may hold a prior `devnet-smoke-trade.md`; reconcile with it
+
+## What to Build / Do
+
+1. **Inventory every Solana signer env var** the platform reads (relayer, parent SNS
+ secret, agent authority, collection authority) and document each: var name,
+ purpose, required SOL balance, network. Put this in
+ `tasks/onchain-deployment/SOLANA-SIGNERS.md`.
+
+2. **Fund the devnet signers** (airdrop) and at least the relayer on mainnet to a
+ documented minimum. Report exact balances; flag anything the user must fund that
+ requires real SOL.
+
+3. **Devnet smoke trade**: run `buy-prep` → `buy-confirm` for a synthetic mint (or
+ `$THREE` on a devnet fork — never a real third-party mint) with the funded signer.
+ Capture the confirmed signature. Make it a re-runnable `scripts/` script.
+
+4. **Verify the distribution cron**: trigger `distribute-creator-fees` against a test
+ agent mint on devnet, confirm a row lands in `pump_distribute_runs` with before/after
+ balances and a real signature.
+
+5. **Verify the buyback cron**: trigger a buyback on devnet, confirm `pump_buyback_runs`
+ logs a real swap attempt + signature.
+
+6. **Verify SNS minting** end-to-end: with `THREEWS_SOL_PARENT_SECRET_BASE58` set,
+ mint a synthetic test subdomain on `threews.sol`, confirm the URL record + the
+ `user_subdomains` row, then note cleanup.
+
+7. **Add a low-balance alert**: if any relayer drops below its documented minimum, fire
+ a Telegram ops alert (reuse the existing observability/alerts pipeline) so signers
+ never silently run dry.
+
+## Constraints
+
+- Never commit any secret key. Document env var NAMES only.
+- Use synthetic mints or `$THREE` on devnet — never a real third-party token.
+- Devnet first for every flow; only fund mainnet relayers to the documented minimum.
+- Crons must write their audit rows — a run with no audit row is a failure, not a pass.
+- Mind the Redis quota incident: don't add high-frequency polling that burns the
+ Upstash quota; reuse existing crons.
+
+## Success Criteria
+
+- `tasks/onchain-deployment/SOLANA-SIGNERS.md` lists every signer, its purpose, env
+ var, network, and funded balance.
+- A confirmed devnet `buy` signature exists (re-runnable script).
+- `pump_distribute_runs` and `pump_buyback_runs` each gain a real row from a verified
+ devnet run.
+- A synthetic SNS subdomain mints + resolves end-to-end.
+- Low-balance alerting fires when a relayer is under-funded.
+- No secrets committed.
diff --git a/tasks/onchain-deployment/10-onchain-e2e-smoke-harness.md b/tasks/onchain-deployment/10-onchain-e2e-smoke-harness.md
new file mode 100644
index 000000000..e33246388
--- /dev/null
+++ b/tasks/onchain-deployment/10-onchain-e2e-smoke-harness.md
@@ -0,0 +1,73 @@
+# Task: On-Chain End-to-End Smoke Harness
+
+## Context
+
+The on-chain stack spans EVM (ERC-8004 identity/reputation/validation, x402 on Base)
+and Solana (pump.fun launch/trade, agent-payments, SNS, agent_invocation). Each piece
+is tested in isolation, but **nothing exercises the whole path in one pass**, so a
+regression in the seam between two systems (e.g. a registry address drift, a broken
+pin endpoint, an unfunded relayer) is only discovered in production. This is the
+verification net that makes "100% wired" provable and keeps it that way.
+
+This is the capstone — it depends on tasks 01, 02, 03, 06, 09 being done (or it will
+report exactly which are not).
+
+## Goal
+
+A single CI-runnable script, `scripts/onchain-smoke.mjs`, that exercises the full
+on-chain agent lifecycle against testnet/devnet and exits non-zero on any break, with
+a clear per-step report.
+
+## Files to Read First
+
+- `src/erc8004/agent-registry.js`, `src/erc8004/registration-json.js` — register flow
+- `src/erc8004/validation-recorder.js` — validation record
+- `contracts/src/ReputationRegistry.sol` — reputation read
+- `api/pump/[action].js` — launch-prep/confirm, buy-prep/confirm
+- `api/x402/pay-by-name.js` — x402 resolve + pay
+- `scripts/verify-onchain-parity.mjs` (from task 05) — reuse for the address check
+- `scripts/onchain-smoke.mjs` — does not exist yet; you create it
+
+## What to Build / Do
+
+Write `scripts/onchain-smoke.mjs` that runs these steps in order, each reporting
+PASS/FAIL/SKIP with timing, and a final summary:
+
+1. **Address parity** — invoke the task-05 parity check; fail fast on drift.
+2. **EVM register (Base Sepolia)** — pin a synthetic GLB, `register()`,
+ `setAgentURI()`, confirm `tokenURI()` round-trips and the card validates against
+ `3d-agent-card.schema.json` with a matching `model.sha256`.
+3. **EVM validation** — record a validation attestation for the test agent, read it
+ back via `getLatestByKind`.
+4. **EVM reputation** — submit feedback from a second synthetic signer, read
+ `getReputation()` and assert the count incremented.
+5. **Solana launch (devnet)** — `launch-prep` → `launch-confirm` for a synthetic mint,
+ assert a `pump_agent_mints` row.
+6. **Solana trade (devnet)** — `buy-prep` → `buy-confirm`, assert a confirmed signature.
+7. **x402 pay-by-name (devnet/testnet)** — resolve a synthetic `@user`/`.sol` name and
+ run a `mode=prep` payment build (don't broadcast real value unless funded).
+8. **Solana agent_invocation (devnet)** — `invokeSkill()` between two synthetic agent
+ authorities, assert the `SkillInvoked` event.
+
+Each step is independently `--only=<step>` runnable and skippable via env so CI can
+run the read-only subset without funded signers. Print a final table.
+
+## Constraints
+
+- Testnet/devnet only by default; a `--mainnet-readonly` mode may do read-only checks
+ (parity, bytecode, tokenURI resolve) but must never broadcast value on mainnet.
+- Synthetic signers/mints only — never a real third-party wallet or token; `$THREE`
+ or `THREEsynthetic1111…` placeholders only.
+- A missing-funded-signer step SKIPs with a clear reason (not FAIL) so the read-only
+ subset stays green in CI; funded runs turn SKIP into PASS/FAIL.
+- Reuse existing endpoints/SDKs — do not reimplement registration or trading logic.
+- Self-cleanup where cheap (release test SNS claims, etc.); document what it leaves behind.
+
+## Success Criteria
+
+- `node scripts/onchain-smoke.mjs` runs all 8 steps and prints a clear PASS/FAIL/SKIP table.
+- With funded testnet/devnet signers, all steps PASS end-to-end.
+- Without funded signers, read-only steps PASS and value steps SKIP (CI stays green).
+- It catches an injected regression (e.g. temporarily wrong registry address → step 1 FAIL).
+- Wired into CI as a non-blocking-but-reported job (or blocking for the read-only subset).
+- Documented in `tasks/onchain-deployment/00-PLAN.md` as the standing verification net.
diff --git a/tasks/pumpfun-launchpad-100/01-usdc-trade-recording.md b/tasks/pumpfun-launchpad-100/01-usdc-trade-recording.md
new file mode 100644
index 000000000..33ca33116
--- /dev/null
+++ b/tasks/pumpfun-launchpad-100/01-usdc-trade-recording.md
@@ -0,0 +1,68 @@
+# Task 01 — Quote-aware trade recording + portfolio subtotals
+
+**Priority:** HIGH — blocks 02, 03. **Type:** backend + schema.
+
+## Goal
+
+Make `pump_agent_trades` and the portfolio API correct for **USDC-paired** agent coins.
+Today the table only models SOL: a `sol_amount` lamports column and nothing that says which
+quote asset the trade actually used. Pump.fun launched USDC-paired coins (post 2026-05-21,
+`buy_v2`/`sell_v2` with explicit `quote_mint`), and our launch + curve code already supports
+them — but every trade we record for a USDC coin lands in `sol_amount` as if it were lamports,
+so prices, volumes, and portfolio subtotals are wrong for those coins.
+
+## Why this matters
+
+A trader on a USDC-paired agent coin sees nonsense P&L and the agent-profile token widget
+reports a fake market cap. This is a data-integrity bug, not cosmetics. The v2 audit
+(`docs/pumpfun-program/AUDIT-2026-06-11.md`, "remaining productization") explicitly listed
+`quote_amount`/`quote_mint` columns and portfolio per-quote subtotals as the unfinished work.
+
+## Context — read first
+
+- `api/_lib/migrations/2026-04-29-pump-trades.sql` — current schema (SOL-only).
+- `api/_lib/pumpfun-ws-feed.js:207-275` — `classifyQuote()` already returns
+ `{ quote_mint, quote_symbol, is_usdc_pair }`. Reuse it; do not reinvent.
+- `api/_lib/pump-quote.js` — quote-mint classification (SOL vs USDC) used by the trade path.
+- INSERT sites that must be updated:
+ - `api/pump/helius-webhook.js:47`
+ - `api/agents/pumpfun/[action].js:211` and `:1003`
+ - any buy-confirm / sell-confirm path in `api/pump/[action].js` that writes a trade
+- Consumers that must read the new columns:
+ - `api/pump/[action].js` → `portfolio`, `coin-trades`, `dashboard`
+ - `src/pump/dashboard.js`, `src/pump/agent-token-widget.js` (display)
+
+## Scope
+
+1. **Migration.** New file `api/_lib/migrations/2026-06-14-pump-trades-quote.sql`:
+ - `quote_mint text` — the quote SPL mint (WSOL or USDC mint string).
+ - `quote_symbol text` — `'SOL' | 'USDC' | 'OTHER'`.
+ - `quote_amount numeric(40,0)` — atomic units of the quote asset spent (buy) / received (sell).
+ - Backfill: set `quote_mint = <WSOL mint>`, `quote_symbol = 'SOL'`,
+ `quote_amount = sol_amount` for all existing rows (every legacy row is SOL-paired).
+ - Keep `sol_amount` (don't drop) for backward compat; new code reads `quote_amount`.
+ - Idempotent: `add column if not exists`, wrapped in a transaction, follows the existing
+ migration file conventions in that directory.
+2. **Wire every INSERT site** to populate the three new columns using `classifyQuote()` /
+ the resolved quote mint from `pump-quote.js`. For SOL trades, `quote_amount === sol_amount`.
+3. **Portfolio per-quote subtotals.** `portfolio` action returns holdings grouped/subtotaled by
+ quote asset (SOL subtotal, USDC subtotal) instead of summing lamports across mismatched units.
+4. **Display.** `coin-trades` / `dashboard` responses expose `quote_symbol` + a correctly-scaled
+ amount; the dashboard and token widget render `"X USDC"` vs `"Y SOL"` rather than assuming SOL.
+
+## Definition of done
+
+- [ ] Migration runs cleanly on a fresh DB and on the existing DB (idempotent, backfill correct).
+- [ ] Every trade INSERT writes `quote_mint`, `quote_symbol`, `quote_amount`; no path left on
+ the SOL-only assumption (grep the codebase to prove it).
+- [ ] A recorded USDC-paired trade shows the right amount + symbol in `coin-trades`, `dashboard`,
+ and the agent-profile widget. SOL trades unchanged.
+- [ ] `portfolio` returns separate SOL and USDC subtotals; no cross-unit summing.
+- [ ] `npm test` passes; add/extend a test that records a USDC trade and asserts the columns.
+- [ ] Changelog entry (tag: `fix` + `feature`): "USDC-paired agent coins now record and display
+ correct trade amounts."
+
+## Out of scope
+
+Buy/sell **UI** denomination (Task 02) and custodial USDC signing (Task 03). This task is the
+data layer they both depend on.
diff --git a/tasks/pumpfun-launchpad-100/02-usdc-buy-sell-ui.md b/tasks/pumpfun-launchpad-100/02-usdc-buy-sell-ui.md
new file mode 100644
index 000000000..e38e3cf31
--- /dev/null
+++ b/tasks/pumpfun-launchpad-100/02-usdc-buy-sell-ui.md
@@ -0,0 +1,58 @@
+# Task 02 — USDC denomination in the buy/sell widget
+
+**Priority:** HIGH. **Depends on:** Task 01 (quote-aware trade recording). **Type:** frontend.
+
+## Goal
+
+Let a user buy and sell a **USDC-paired** agent coin in USDC from the trade widget, end to end:
+input denominated in the coin's quote asset, a real quote, a signed `buy_v2`/`sell_v2`
+transaction, broadcast, confirm. Today the widget is hardwired to SOL — `src/game/coin-buy.js`
+has zero USDC references — so USDC coins are untradeable from our UI even though the backend
+(`pump-swap-ix.js`, `pump-quote.js`, `agent-payments` fork) already supports them.
+
+## Why this matters
+
+A user lands on a USDC-paired agent coin's page, hits Buy, and the widget asks for SOL — wrong
+asset, broken trade. The launchpad can launch USDC coins it then can't trade. That's a dead path,
+and CLAUDE.md forbids dead paths.
+
+## Context — read first
+
+- `src/game/coin-buy.js` — current SOL-only buy widget.
+- `src/pump/pump-modals.js` — buy/sell/governance/withdraw modal pipeline
+ (prep → sign → broadcast → confirm) already wired for SOL.
+- `src/pump/pump-swap-quote.js` — quote logic.
+- Backend already done: `api/pump/[action].js` `buy-prep`/`sell-prep`/`quote`,
+ `api/_lib/pump-swap-ix.js`, `api/_lib/pump-quote.js` accept/return the quote mint.
+- The coin's quote asset is known from `api/pump/coin` / `curve` (`quote_mint`/`is_usdc_pair`)
+ and now also from Task 01's recorded trades.
+
+## Scope
+
+1. **Detect the coin's quote asset** when the widget mounts (from `coin`/`curve`). Drive all
+ labels, the input suffix, balance display, and slippage off that — don't hardcode "SOL".
+2. **USDC input + balance.** For USDC coins: show the user's USDC balance, denominate the amount
+ input in USDC, fetch the quote against the USDC quote mint, render the USDC→token preview.
+3. **Idempotent quote-ATA create.** USDC sells need the quote ATA created if absent — the prep
+ endpoint already prepends this (audit GAP-5); make sure the client signs/broadcasts the full
+ returned transaction unchanged and doesn't strip instructions.
+4. **Every state designed:** insufficient USDC balance (actionable — link to fund), no quote,
+ slippage exceeded, user-rejected signature, broadcast failure. SOL coins must behave exactly
+ as before (no regression).
+5. **Bonding-curve vs AMM.** Respect the existing route selection (`bonding_curve` vs `amm`
+ post-graduation) for USDC coins the same way it works for SOL.
+
+## Definition of done
+
+- [ ] On a USDC-paired coin, Buy and Sell complete a real signed transaction in a browser
+ against a real RPC; the trade lands in `pump_agent_trades` with correct quote columns (Task 01).
+- [ ] On a SOL-paired coin, behavior is byte-for-byte the same as before (verified, not assumed).
+- [ ] Insufficient-balance, rejected-signature, and quote-failure states are all designed and tested.
+- [ ] No console errors/warnings from this code; network tab shows real prep/confirm calls.
+- [ ] `npm test` passes.
+- [ ] Changelog entry (tag: `feature`): "Buy and sell USDC-paired agent coins directly from the
+ trade widget."
+
+## Out of scope
+
+Server-signed/custodial USDC trades (Task 03). This task is the **user-wallet** flow only.
diff --git a/tasks/pumpfun-launchpad-100/03-custodial-usdc-trading.md b/tasks/pumpfun-launchpad-100/03-custodial-usdc-trading.md
new file mode 100644
index 000000000..23a3d3546
--- /dev/null
+++ b/tasks/pumpfun-launchpad-100/03-custodial-usdc-trading.md
@@ -0,0 +1,50 @@
+# Task 03 — Custodial (agent-signed) USDC trading
+
+**Priority:** MEDIUM. **Depends on:** Task 01. **Type:** backend.
+
+## Goal
+
+Let an agent's **custodial** wallet (server-signed, via the recovered encrypted keypair) buy and
+sell USDC-paired coins, not just SOL. The wallet-signed path is handled by Task 02; this is the
+autonomous/server path used by strategies, buyback, and the `launch-agent` family. The v2 audit
+flagged a "custodial USDC trading flag" as deferred.
+
+## Why this matters
+
+Autonomous lanes (buyback, strategy-run, distribute) currently assume SOL. On a USDC-paired
+agent coin they would build a SOL trade against a USDC curve — wrong asset, failed or mispriced
+transaction. The autonomous economy must work for both quote assets or it silently breaks for
+every USDC coin an agent launches.
+
+## Context — read first
+
+- `api/_lib/agent-pumpfun.js` — `loadAgentForSigning`, recovers encrypted Solana keypair.
+- `api/pump/[action].js` — `launch-agent`, `collect-creator-fee-agent`,
+ `distribute-creator-fees-agent`, `strategy-*`, server-signed trade paths.
+- `api/_lib/pump-swap-ix.js`, `api/_lib/pump-quote.js`, `api/_lib/pump-trade-args.js`.
+- `api/cron/pump-agent-stats.js` and the buyback/distribute cron paths
+ (`pump_buyback_runs`, `pump_distribute_runs`).
+- Task 01's quote columns — record custodial USDC trades correctly too.
+
+## Scope
+
+1. **Resolve the coin's quote asset server-side** before building any custodial trade; thread the
+ quote mint through the instruction builder exactly as the wallet path does.
+2. **Custodial USDC buy/sell** — server signs a `buy_v2`/`sell_v2` against the correct quote ATA;
+ create the agent's quote ATA idempotently if missing.
+3. **Buyback / distribute** lanes respect the quote asset (a USDC coin buys back with USDC, etc.).
+ If a lane genuinely can't operate in a given quote, it must fail loudly with a clear reason
+ and record the error in `pump_buyback_runs`/`pump_distribute_runs` — never silently no-op.
+4. **Record** custodial trades with the Task 01 quote columns.
+
+## Definition of done
+
+- [ ] A custodial buy and sell on a USDC-paired coin succeed on devnet (coordinate with Task 07).
+- [ ] Buyback/distribute lanes operate in the coin's quote asset, or fail with a recorded reason.
+- [ ] SOL custodial paths unchanged (no regression).
+- [ ] `npm test` passes; add a unit test covering quote-asset resolution in the custodial builder.
+- [ ] Changelog entry (tag: `feature`): "Agents can autonomously trade USDC-paired coins."
+
+## Out of scope
+
+The user-wallet UI (Task 02).
diff --git a/tasks/pumpfun-launchpad-100/04-alerts-server-persistence.md b/tasks/pumpfun-launchpad-100/04-alerts-server-persistence.md
new file mode 100644
index 000000000..3d2c073a8
--- /dev/null
+++ b/tasks/pumpfun-launchpad-100/04-alerts-server-persistence.md
@@ -0,0 +1,56 @@
+# Task 04 — Alert rules: server persistence + real delivery
+
+**Priority:** MEDIUM. **Type:** backend + frontend. **Supersedes:**
+`tasks/pump-dashboard-real-apis/12-alerts-server-persist.md` (carry over its intent, then mark it done).
+
+## Goal
+
+Move pump-dashboard alert rules from browser `localStorage` to server-side Postgres, evaluate
+them against the live pump.fun event stream on the server, and deliver matches over real channels
+(in-app notification + webhook + optional Telegram). Today alerts only exist in the tab that
+created them: close the tab and they stop; open another device and they're gone.
+
+## Why this matters
+
+An alert that only fires while a specific browser tab is open is not an alert. Traders expect a
+graduation/price/whale alert to fire whether or not they're looking. This is the difference
+between a toy and a tool.
+
+## Context — read first
+
+- `tasks/pump-dashboard-real-apis/12-alerts-server-persist.md` — original task statement.
+- `pages/pump-dashboard.html` — current localStorage alert UI.
+- Existing server-side infra to reuse (do NOT build parallel systems):
+ - `api/cron/pumpfun-monitor.js` — already evaluates `graduation_alerts` per user with cooldown
+ and webhook delivery. Extend this pattern; don't fork it.
+ - `pumpfun_signals`, `graduation_alerts`, `user_notifications` tables.
+ - `api/_lib/pumpfun-ws-feed.js` — the live mint/trade/graduation source.
+ - Telegram delivery: `api/pump/[action].js` `deliver-telegram`.
+ - Observability/alerts: `TELEGRAM_ALERTS_CHAT_ID` (per memory, still unset — handle absence).
+
+## Scope
+
+1. **Schema.** A `pump_alert_rules` table (or extend `graduation_alerts` if it cleanly
+ generalizes): `user_id`, `kind` (graduation | price_above | price_below | whale_buy | new_mint
+ by_agent), `target` (mint or agent_id, nullable for global), threshold params, delivery config
+ (in_app | webhook_url | telegram_chat), `cooldown_seconds`, `enabled`, timestamps.
+2. **CRUD API** — authenticated endpoints to create/list/update/delete a user's rules.
+3. **Server-side evaluation** — fold rule matching into the existing `pumpfun-monitor` cron (or a
+ companion) consuming the WS feed / signals table; respect cooldowns; dedupe.
+4. **Delivery** — write `user_notifications`, POST the webhook (with signature/secret), and send
+ Telegram when configured. Each delivery channel handles its own failure without blocking others.
+5. **Frontend** — dashboard alert UI reads/writes the server; `localStorage` becomes a render
+ cache only. Cross-device: rules created on one device appear on another after refresh.
+
+## Definition of done
+
+- [ ] Rules persist server-side and survive tab close; visible on a second device.
+- [ ] A real graduation/price/whale event fires the matching rule via the cron, delivering an
+ in-app notification and a webhook POST (verify with a request-bin style endpoint).
+- [ ] Cooldown + dedupe prevent alert storms.
+- [ ] Telegram delivery works when configured, no-ops cleanly when creds absent.
+- [ ] Every alert-UI state designed (no rules yet → helpful empty state; delivery-failed surfaced).
+- [ ] `npm test` passes; rule-evaluation logic has unit coverage.
+- [ ] Mark `tasks/pump-dashboard-real-apis/12-alerts-server-persist.md` done with a pointer here.
+- [ ] Changelog entry (tag: `feature`): "Pump dashboard alerts now run server-side — fire across
+ devices even with the tab closed, with webhook and Telegram delivery."
diff --git a/tasks/pumpfun-launchpad-100/05-pumpfun-signals-cron.md b/tasks/pumpfun-launchpad-100/05-pumpfun-signals-cron.md
new file mode 100644
index 000000000..29a98c8aa
--- /dev/null
+++ b/tasks/pumpfun-launchpad-100/05-pumpfun-signals-cron.md
@@ -0,0 +1,46 @@
+# Task 05 — Finish the `pumpfun-signals` cron
+
+**Priority:** MEDIUM. **Type:** backend.
+
+## Goal
+
+Complete the `pumpfun-signals` cron, which the backend inventory flagged as a skeleton: it
+ingests pump.fun events but its rule evaluation / signal-emission is unfinished. Bring it to the
+same completeness as `pumpfun-monitor` and `pump-agent-stats`.
+
+## Why this matters
+
+Signals power agent reputation, the reactive avatar, and the channel feed. A half-finished signal
+processor means agents react to a partial or empty event stream — the "live" feel of the
+launchpad degrades to stale. Either finish it or, if it's fully superseded by `pumpfun-monitor`,
+delete it and re-point consumers (CLAUDE.md: eliminate dead paths).
+
+## Context — read first
+
+- `api/cron/pumpfun-signals.js` (or wherever the signals cron lives — confirm path) and its
+ registration in `vercel.json` crons.
+- `pumpfun_signals` table — what rows it expects, who writes/reads them.
+- `api/_lib/pumpfun-ws-feed.js` — `getMints()` / `getWhales()` / `getClaims()` sources.
+- `api/pump/channel-feed.js` — a consumer of signals.
+- `api/cron/pumpfun-monitor.js` — the reference for a complete cron (cursor, cooldown, delivery).
+- `docs/solana-pumpfun.md` — documents the intended `pumpfun-signals` crawler design.
+
+## Scope
+
+1. **Determine the true state** — read the cron and decide: finish, or fold into `pumpfun-monitor`
+ and delete. Document the decision in the PR/commit.
+2. **If finishing:** complete rule evaluation (mints/whales/graduations → `pumpfun_signals`
+ rows with `weight`/`payload`), maintain a cursor so it doesn't reprocess, respect rate limits
+ and the Redis quota (see `tasks/redis-burn-rate-reduction.md` — minimize Redis writes).
+3. **Wire consumers** — channel-feed, reputation signals, reactive avatar read real signal rows.
+4. **Circuit-breaker / timeout** parity with the other crons (no runaway RPC under 429s).
+
+## Definition of done
+
+- [ ] Cron runs to completion within its time budget, emits real signal rows from live events.
+- [ ] Consumers (channel-feed at minimum) display data sourced from those rows.
+- [ ] No reprocessing of already-seen events (cursor verified).
+- [ ] If deleted instead: all consumers re-pointed, cron removed from `vercel.json`, no dead refs.
+- [ ] Redis write volume measured and within burn-rate budget.
+- [ ] `npm test` passes.
+- [ ] Changelog entry only if user-visible (e.g. channel feed gets livelier) — else internal-only.
diff --git a/tasks/pumpfun-launchpad-100/06-strategy-validate-semantic.md b/tasks/pumpfun-launchpad-100/06-strategy-validate-semantic.md
new file mode 100644
index 000000000..a5c2eafc1
--- /dev/null
+++ b/tasks/pumpfun-launchpad-100/06-strategy-validate-semantic.md
@@ -0,0 +1,43 @@
+# Task 06 — Real strategy validation
+
+**Priority:** LOW–MEDIUM. **Type:** backend.
+
+## Goal
+
+Upgrade the `strategy-validate` action from syntax-only checking to genuine semantic validation,
+so a user can't save or run a trading strategy that is structurally valid but operationally
+broken (references a missing mint, impossible thresholds, conflicting rules, unsupported quote
+asset).
+
+## Why this matters
+
+`strategy-run` executes real on-chain trades via the custodial wallet. A strategy that passes
+"validation" but then fails or misbehaves at runtime burns real SOL/USDC and erodes trust.
+Validation that only checks syntax gives false confidence.
+
+## Context — read first
+
+- `api/pump/[action].js` — `strategy-validate`, `strategy-run` (SSE), `strategy-backtest`,
+ `strategy-close-all`.
+- `PUMP_DEFAULT_AGENT_MINT` env fallback used by `strategy-run`.
+- Task 01/03 — quote-asset awareness (a strategy on a USDC coin must validate against USDC).
+
+## Scope
+
+1. **Define the strategy schema** explicitly (the set of valid rule types, operators, params) if
+ not already centralized; validate structure against it.
+2. **Semantic checks:** referenced mint exists and is an agent coin; quote asset matches the
+ strategy's denominated thresholds; numeric bounds sane (slippage, sizes, intervals); no
+ contradictory/unreachable rules; custodial wallet has the capability the strategy assumes.
+3. **Return actionable errors** — field-level messages the UI can show, not a single opaque fail.
+4. **Reuse, don't duplicate** the backtest's interpretation of the strategy so validate and run
+ agree on semantics.
+
+## Definition of done
+
+- [ ] A strategy referencing a nonexistent mint, an impossible threshold, or a quote-asset
+ mismatch is rejected with a specific, field-level reason.
+- [ ] A valid strategy validates and then runs/backtests consistently (validate and run agree).
+- [ ] No false positives on currently-working strategies.
+- [ ] `npm test` passes; add cases for each rejection class.
+- [ ] Changelog entry (tag: `improvement`) if the strategy UI surfaces the new errors.
diff --git a/tasks/pumpfun-launchpad-100/07-devnet-smoke-trade.md b/tasks/pumpfun-launchpad-100/07-devnet-smoke-trade.md
new file mode 100644
index 000000000..332cfa2d2
--- /dev/null
+++ b/tasks/pumpfun-launchpad-100/07-devnet-smoke-trade.md
@@ -0,0 +1,55 @@
+# Task 07 — End-to-end devnet smoke: launch → buy → sell
+
+**Priority:** HIGH (run LAST). **Depends on:** 01, 02, 03. **Type:** integration proof.
+**Supersedes:** the empty `tasks/devnet-smoke-trade.md` stub.
+
+## Goal
+
+Prove the entire launchpad loop works against real on-chain state on **devnet**, with a funded
+signer, for **both** a SOL-paired and a USDC-paired coin: launch a coin, buy it, sell it, confirm
+each transaction on-chain, and verify every row lands in Postgres with correct quote columns.
+This is the acceptance gate for Tasks 01–03 — nothing is "done" until this passes.
+
+## Why this matters
+
+Every other task touches the trade path. A unit test mocks the chain; this proves the real
+prep → sign → broadcast → confirm pipeline against a real RPC, real pump SDK, real PDAs. Memory
+notes the devnet smoke "awaits a funded signer" — getting one funded is part of this task.
+
+## Context — read first
+
+- `api/pump/[action].js` — `launch-prep`/`launch-confirm`, `buy-prep`/`buy-confirm`,
+ `sell-prep`/`sell-confirm`, `launch-agent` (custodial).
+- `api/_lib/pump.js`, `pump-launch.js`, `pump-swap-ix.js`, `pump-quote.js`.
+- `SOLANA_RPC_URL_DEVNET`; devnet SOL faucet for the signer; devnet USDC for the USDC leg.
+- `A2A_PAYER_PRIVATE_KEY` / existing demo wallets in `~/.config/x402-test-wallets/` (per memory)
+ — reuse a funded signer rather than minting a new one if possible.
+- Mints in fixtures: only `$THREE` CA or a synthetic `THREEsynthetic1111…` placeholder.
+
+## Scope
+
+1. **Funded signer.** Establish a devnet signer with SOL (faucet) and devnet USDC. Document how
+ it's funded and where the key lives (never commit the key).
+2. **Smoke script** under `scripts/` (not repo root — repo-hygiene rule), e.g.
+ `scripts/pump-devnet-smoke.mjs`, that:
+ - launches a SOL-paired coin via the real prep/confirm endpoints, signing locally;
+ - buys then sells it; asserts on-chain confirmation and correct `pump_agent_trades` rows;
+ - repeats for a USDC-paired coin (exercises Task 01 columns + Task 02/03 paths);
+ - runs one custodial (agent-signed) buy/sell to cover Task 03;
+ - prints a clear PASS/FAIL summary with tx signatures (explorer links).
+3. **Idempotent / re-runnable** — no leftover state that breaks a second run.
+
+## Definition of done
+
+- [ ] Script runs against devnet and reports PASS for: SOL launch+buy+sell, USDC launch+buy+sell,
+ custodial buy+sell. Real tx signatures shown.
+- [ ] `pump_agent_trades` rows for the USDC legs carry correct `quote_mint`/`quote_symbol`/
+ `quote_amount` (Task 01).
+- [ ] Failures produce actionable output (which step, which signature, the RPC error).
+- [ ] Script documented in `tasks/pumpfun-launchpad-100/` or a short `docs/` note: how to fund
+ the signer and run it.
+- [ ] No secret committed; signer key referenced from env / local config only.
+
+## Out of scope
+
+Mainnet execution. This is a devnet correctness proof.
diff --git a/tasks/pumpfun-launchpad-100/08-wire-pumpfun-bot-url.md b/tasks/pumpfun-launchpad-100/08-wire-pumpfun-bot-url.md
new file mode 100644
index 000000000..1460948bb
--- /dev/null
+++ b/tasks/pumpfun-launchpad-100/08-wire-pumpfun-bot-url.md
@@ -0,0 +1,55 @@
+# Task 08 — Deploy + wire `PUMPFUN_BOT_URL` (graduations feed)
+
+**Priority:** MEDIUM. **Type:** infra + backend. **Supersedes:** the empty
+`tasks/wire-pumpfun-bot-url.md` stub.
+
+## Goal
+
+Stand up and wire the pump.fun MCP bot so the launchpad's graduation / token-intelligence data
+comes from a live source in production, instead of silently falling back to the `pf:graduations`
+Redis list (which nothing currently populates reliably). `PUMPFUN_BOT_URL` / `PUMPFUN_BOT_TOKEN`
+are read throughout the code but not configured in prod.
+
+## Why this matters
+
+`recent-graduations`, the channel feed, and graduation alerts (Task 04) degrade to stale or empty
+when the bot URL is unset. The Cloudflare worker mirror (`workers/pump-fun-mcp/worker.js`) and the
+`@three-ws/pumpfun-mcp` package already exist — this is wiring + deploy, not new construction.
+
+## Context — read first
+
+- `api/_lib/pumpfun-mcp.js:95` — MCP client for `PUMPFUN_BOT_URL` (JSON-RPC), with the
+ `pf:graduations` Redis fallback.
+- `workers/pump-fun-mcp/worker.js` — the deployable Cloudflare Workers MCP mirror (on-chain only,
+ reads `SOLANA_RPC_URL`, `PUMPFUN_BOT_URL`, `PUMPFUN_BOT_TOKEN`).
+- `packages/pumpfun-mcp/` — the published MCP server package.
+- `api/pump/[action].js` → `recent-graduations`; `pumpfun_graduations` table; the WS feed
+ (`api/_lib/pumpfun-ws-feed.js`) that already writes graduations.
+- Per memory: `vercel env pull` returns empty for sensitive vars — set vars via the Vercel REST
+ API, not the CLI wrapper (which writes empty secrets under the plugin).
+
+## Scope
+
+1. **Decide the bot source.** Either (a) deploy `workers/pump-fun-mcp/worker.js` to Cloudflare and
+ point `PUMPFUN_BOT_URL` at it, or (b) confirm the WS feed already populates
+ `pumpfun_graduations` sufficiently and make `pf:graduations`/bot a true optional enrichment.
+ Document the choice.
+2. **Deploy** (if 1a): publish the worker, set its env (`SOLANA_RPC_URL`, optional token), verify
+ its MCP endpoints respond.
+3. **Configure prod** — set `PUMPFUN_BOT_URL` (+ `PUMPFUN_BOT_TOKEN` if used) in Vercel prod +
+ preview via the REST API. Verify `pumpfun-mcp.js` hits the live bot, not the fallback.
+4. **Verify the data path** — `recent-graduations` and the channel feed return live graduation
+ data; Task 04 alerts can fire on it.
+
+## Definition of done
+
+- [ ] `PUMPFUN_BOT_URL` resolves to a live endpoint in prod; `pumpfun-mcp.js` uses it (logs/probe
+ confirm it's not on the Redis fallback).
+- [ ] `recent-graduations` returns real, fresh graduations in prod.
+- [ ] If the worker was deployed: its URL, env, and redeploy steps documented.
+- [ ] Secrets set via REST API and verified non-empty (per the known CLI trap).
+- [ ] Changelog entry (tag: `infra`) only if users see fresher graduation data.
+
+## Out of scope
+
+Building new MCP tools — use what `pumpfun-mcp` / the worker already expose.
diff --git a/tasks/pumpfun-launchpad-100/09-launch-flow-e2e.md b/tasks/pumpfun-launchpad-100/09-launch-flow-e2e.md
new file mode 100644
index 000000000..04c97afc1
--- /dev/null
+++ b/tasks/pumpfun-launchpad-100/09-launch-flow-e2e.md
@@ -0,0 +1,50 @@
+# Task 09 — Browser E2E coverage of the launch flow
+
+**Priority:** MEDIUM. **Depends on:** Task 02 (USDC UI). **Type:** test + frontend hardening.
+
+## Goal
+
+Add real browser E2E coverage (Playwright) for the launch modal's four steps and the trade
+widget, and fix the UX gaps the frontend inventory flagged along the way: generic error copy and
+the untraced graduation visual state transition. Today there is zero E2E coverage of the most
+important conversion path in the product.
+
+## Why this matters
+
+The launch flow (`src/pump/launch-token-modal.js`, ~1000 lines, 4 steps, wallet signing, canvas
+share card) is where users convert. A silent regression here is invisible until a user can't
+launch. Manual testing doesn't scale; this is the one flow that must never break.
+
+## Context — read first
+
+- `src/pump/launch-token-modal.js` — steps 1 (form) → 2 (quote+curve chart) → 3 (connect) →
+ 4 (sign/broadcast/confirm + success share card).
+- `src/pump/pump-modals.js`, `src/game/coin-buy.js` — trade widget (post Task 02).
+- `src/pump/bonding-curve-chart.js` — graduation progress; trace the graduated visual state.
+- Per memory (`page-audit-tooling`, `vitest-cold-import-contention`): use a **dedicated-port
+ Vite** dev server pre-started for Playwright; mock the wallet's `signTransaction` at the
+ `window.solana` boundary (the only acceptable mock — it's an external browser extension, not
+ our code or a real API) so the test drives the real prep/confirm endpoints.
+- `scripts/page-audit.mjs` — existing browser-check harness to model the setup on.
+
+## Scope
+
+1. **E2E spec** (Playwright, in `tests/` or `scripts/` per existing convention) covering:
+ form validation (bad symbol rejected), quote step renders breakdown + curve chart, wallet
+ connect, sign+broadcast (wallet signing stubbed at the extension boundary), success card +
+ mint chip + share link. Assert real `launch-prep`/`launch-confirm` calls fire.
+2. **Trade widget E2E** — buy and sell happy paths for a SOL coin and a USDC coin (Task 02).
+3. **Fix error copy** — replace generic "Connection error, please try again" with messages mapped
+ to the actual failure (insufficient SOL, RPC down, user rejected, slippage exceeded).
+4. **Graduation visual state** — verify and, if missing, implement the curve→graduated visual
+ transition in the chart/widget so a graduated coin is visually unmistakable.
+
+## Definition of done
+
+- [ ] Playwright spec runs green locally against a dedicated dev server; covers all 4 launch steps
+ + buy + sell.
+- [ ] Error states show specific, actionable copy (no generic catch-all).
+- [ ] Graduated coins render a distinct visual state; verified in a browser.
+- [ ] Spec documented (how to run); pre-started dev server pattern followed (no flaky networkidle).
+- [ ] `npm test` still passes.
+- [ ] Changelog entry (tag: `improvement`) for the clearer error messages + graduation state.
diff --git a/tasks/pumpfun-launchpad-100/10-definition-of-done-sweep.md b/tasks/pumpfun-launchpad-100/10-definition-of-done-sweep.md
new file mode 100644
index 000000000..cfa189baa
--- /dev/null
+++ b/tasks/pumpfun-launchpad-100/10-definition-of-done-sweep.md
@@ -0,0 +1,53 @@
+# Task 10 — Launchpad Definition-of-Done sweep (final audit gate)
+
+**Priority:** HIGH (run LAST). **Depends on:** 01–09. **Type:** audit + polish.
+
+## Goal
+
+Run the entire pump.fun launchpad surface through the CLAUDE.md Definition of Done as a single
+deliberate pass, fix everything that falls short, and produce a short audit report proving the
+launchpad is genuinely 100% — every path reachable, every state designed, no dead links, no
+mocks, no console noise.
+
+## Why this matters
+
+Tasks 01–09 each close a specific gap. This task guarantees the *whole* surface holds together:
+the accumulation of small quality decisions that separates a great product from an adequate one.
+This is the "would I demo this to a room of senior engineers" gate.
+
+## Surfaces to audit (every one)
+
+- Pages: `/launches`, `/pump-live`, `/pump-dashboard`, `/pump-visualizer`, `/pumpfun`,
+ `/launchpad` (Studio), agent-detail launch history.
+- Modals/widgets: launch-token-modal, pump-modals (buy/sell/governance/withdraw),
+ agent-token-widget, homepage-launcher, bonding-curve-chart.
+- The Launchpad Studio publish flow (`/api/launchpad/publish` → `/p/<slug>` → `/api/launchpad/invoke`).
+
+## Checklist — apply to each surface
+
+1. **Reachable + navigable.** Every surface is in `public/nav-data.js` and reachable; every
+ button/link goes somewhere real; no dead paths (CLAUDE.md). Verify `/pumpfun` (served from
+ `public/pumpfun.html`) actually renders the intended stream UI, not a stale stub.
+2. **Every state designed:** loading (skeleton), empty (tells the user what to do — not a blank
+ void), error (actionable + recovery), populated, overflow (long names, 0 / 1 / 1000 items).
+3. **No mocks/fake data in prod paths.** Grep for sample arrays, `DEMO_*`, hardcoded mints
+ (only `$THREE` CA or synthetic placeholders allowed), `setTimeout` fake loading, TODO,
+ `not implemented`. Remove or implement.
+4. **No console errors/warnings** from our code on any surface (open each in a browser).
+5. **Network tab:** real `/api/pump/*` calls succeeding with real data on every surface.
+6. **Microinteractions + a11y:** hover/active/focus states on every interactive element;
+ semantic HTML; ARIA labels; keyboard nav; focus rings; sufficient contrast. The launch modal
+ and dashboard must be keyboard-operable.
+7. **Responsive** at 320 / 768 / 1440.
+8. **Cross-links wired:** launches feed ↔ agent profiles ↔ token widget ↔ dashboard ↔ pump.fun.
+ A coin card links to its agent; an agent links to its launches. The platform should feel linked.
+
+## Definition of done
+
+- [ ] Every surface passes the checklist; each fix committed with a justified diff.
+- [ ] A short report `tasks/pumpfun-launchpad-100/AUDIT-REPORT.md` listing each surface, its
+ verified states, and what was fixed.
+- [ ] Run the `completionist` subagent over the launchpad changes; address its findings.
+- [ ] `npm test` passes; no console errors on any surface.
+- [ ] Changelog entry (tag: `improvement`) summarizing the polish pass.
+- [ ] You would be proud to demo every one of these surfaces to senior engineers.
diff --git a/tasks/pumpfun-launchpad-100/README.md b/tasks/pumpfun-launchpad-100/README.md
new file mode 100644
index 000000000..0907559f0
--- /dev/null
+++ b/tasks/pumpfun-launchpad-100/README.md
@@ -0,0 +1,87 @@
+# Pump.fun Launchpad → 100% — Completion Plan
+
+**Goal:** Take the three.ws pump.fun launchpad for 3D AI agents from ~88% complete to
+genuinely production-complete: every path wired, every state designed, USDC fully
+first-class, autonomous lanes finished, and the whole launch→trade→graduate→earn
+loop proven end-to-end on devnet against real on-chain state.
+
+This is not a rewrite. The launchpad is already large and mostly real:
+
+- **Backend:** `api/pump/[action].js` (47 actions), `api/pump/*.js`, `api/_lib/pump*.js`,
+ PumpPortal WS feed, Helius webhook, 3 crons, 12 Postgres tables. Launch / buy / sell /
+ accept-payment / fee-sharing / buyback / distribute are all implemented and signed
+ end-to-end (custodial + wallet).
+- **Frontend:** launch modal (4 steps, vanity grind, share card), `/launches` feed,
+ `/pump-live`, `/pump-dashboard`, `/pump-visualizer`, `/pumpfun`, Launchpad Studio,
+ agent-profile token widget, buy/sell/governance/withdraw modals.
+- **SDKs/skills:** forked `@three-ws/agent-payments`, `pumpfun-mcp`, five pump-fun skills,
+ vendored program docs + IDLs, v2 trade-instruction audit (7 gaps found and fixed 2026-06-11).
+
+## What is actually missing (verified, not speculative)
+
+The 2026-06-11 v2 audit (`docs/pumpfun-program/AUDIT-2026-06-11.md`) closed the correctness
+gaps but explicitly deferred **productization of USDC-paired coins**. That, plus a few
+unfinished autonomous lanes and the absence of an end-to-end proof, is the real gap list:
+
+| # | Gap | Evidence |
+|---|-----|----------|
+| 01 | `pump_agent_trades` is SOL-only (`sol_amount` lamports, no `quote_mint`/`quote_amount`); USDC trades record garbage | `api/_lib/migrations/2026-04-29-pump-trades.sql:17`; audit "remaining productization" |
+| 02 | Buy/sell widget is SOL-only — no USDC denomination UI | `src/game/coin-buy.js` (0 USDC refs); audit |
+| 03 | Custodial (agent-signed) trading has no USDC flag | audit "custodial USDC trading flag" |
+| 04 | Alert rules live in browser `localStorage`, no server persistence / cross-device / real webhook delivery | `tasks/pump-dashboard-real-apis/12-alerts-server-persist.md` (OPEN) |
+| 05 | `pumpfun-signals` cron is a skeleton — rule evaluation incomplete | backend inventory |
+| 06 | `strategy-validate` is syntax-only; no semantic validation | backend inventory |
+| 07 | No automated end-to-end launch→buy→sell proof on devnet | `tasks/devnet-smoke-trade.md` empty; memory note "awaits funded signer" |
+| 08 | `PUMPFUN_BOT_URL` graduations feed not deployed/wired in prod | `tasks/wire-pumpfun-bot-url.md` empty; falls back to `pf:graduations` Redis |
+| 09 | No browser E2E coverage of the launch flow; generic error copy; graduation visual transition untraced | frontend inventory "Gaps" |
+| 10 | Launchpad-wide Definition-of-Done sweep (empty/error/loading states, a11y, dead paths) never run as one pass | CLAUDE.md DoD |
+
+## Execution order
+
+These are written to run **independently and in parallel** where possible (concurrent agents
+share one worktree — stage explicit paths, never `git add -A`). Hard dependencies:
+
+```
+01 (trades schema + quote columns) ──┬─→ 02 (USDC buy/sell UI)
+ ├─→ 03 (custodial USDC)
+ └─→ portfolio subtotals (folded into 01)
+
+04 (alerts persistence) ── independent
+05 (signals cron) ── independent
+06 (strategy-validate) ── independent
+08 (pumpfun bot url) ── independent, unblocks richer graduation data
+07 (devnet smoke) ── run LAST; proves 01–03 + launch flow on-chain
+09 (browser E2E) ── run after 02 lands the USDC UI
+10 (DoD sweep) ── run LAST, after 01–09, as the final audit gate
+```
+
+**Recommended sequence:** 01 → (02, 03, 04, 05, 06, 08 in parallel) → 07 → 09 → 10.
+
+## Task files
+
+- [01-usdc-trade-recording.md](01-usdc-trade-recording.md) — quote-aware trade schema + portfolio subtotals
+- [02-usdc-buy-sell-ui.md](02-usdc-buy-sell-ui.md) — USDC denomination in the trade widget
+- [03-custodial-usdc-trading.md](03-custodial-usdc-trading.md) — agent-signed USDC buys/sells
+- [04-alerts-server-persistence.md](04-alerts-server-persistence.md) — server-side alert rules + webhook delivery
+- [05-pumpfun-signals-cron.md](05-pumpfun-signals-cron.md) — finish signal rule evaluation
+- [06-strategy-validate-semantic.md](06-strategy-validate-semantic.md) — real strategy validation
+- [07-devnet-smoke-trade.md](07-devnet-smoke-trade.md) — end-to-end launch→buy→sell proof
+- [08-wire-pumpfun-bot-url.md](08-wire-pumpfun-bot-url.md) — deploy + wire the graduations feed
+- [09-launch-flow-e2e.md](09-launch-flow-e2e.md) — Playwright coverage of the launch flow
+- [10-definition-of-done-sweep.md](10-definition-of-done-sweep.md) — final launchpad DoD audit
+
+## Global rules for every task
+
+1. **No mocks, no fake data, no placeholders.** Real Solana RPC, real pump SDKs, real DB.
+ `$THREE` (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) or a clearly-synthetic
+ `THREEsynthetic1111…` placeholder are the **only** mints allowed in code/tests/fixtures.
+2. **End-to-end or not at all.** A column added must be written by every INSERT site and read
+ by every consumer. A UI toggle must reach a signed, broadcast, confirmed transaction.
+3. **Every state designed:** loading (skeleton), empty (tells user what to do), error
+ (actionable), populated, overflow.
+4. **Changelog:** any user-visible change appends to `data/changelog.json` (tags: feature /
+ improvement / fix / sdk / infra / security), then `npm run build:pages`.
+5. **Verify before done:** run `npm test`, exercise the surface in a real browser / against a
+ real RPC, review `git diff` line-by-line. State explicitly what you verified.
+6. **Watch the traps:** `npx vercel build` clobbers `api/*.js` (check `head -1` for `__defProp`);
+ stage explicit paths; pull only from `threews`, never `threeD`.
diff --git a/tasks/wire-pumpfun-bot-url.md b/tasks/wire-pumpfun-bot-url.md
new file mode 100644
index 000000000..f822f1733
--- /dev/null
+++ b/tasks/wire-pumpfun-bot-url.md
@@ -0,0 +1,6 @@
+# Wire PUMPFUN_BOT_URL → moved
+
+This task is now the canonical, fully-specified task at
+[tasks/pumpfun-launchpad-100/08-wire-pumpfun-bot-url.md](pumpfun-launchpad-100/08-wire-pumpfun-bot-url.md)
+— part of the **Pump.fun Launchpad → 100%** plan
+([tasks/pumpfun-launchpad-100/README.md](pumpfun-launchpad-100/README.md)).
diff --git a/tests/api/forge-health.test.js b/tests/api/forge-health.test.js
index 4467725d8..025a70442 100644
--- a/tests/api/forge-health.test.js
+++ b/tests/api/forge-health.test.js
@@ -28,8 +28,13 @@ const savedEnv = {};
let savedFetch;
// One mock upstream per probe URL; anything unrouted fails the test loudly.
+// world.three.ws is probed unconditionally (no credential gates it), so it is
+// always routed healthy here — per-backend tests stay focused on their upstream.
function mockUpstreams(routes) {
global.fetch = vi.fn(async (url) => {
+ if (String(url).includes('world.three.ws')) {
+ return new Response(JSON.stringify({ protected: true, blueprints: [] }), { status: 200 });
+ }
for (const [match, status] of routes) {
if (String(url).includes(match)) return new Response('{}', { status });
}
@@ -37,6 +42,11 @@ function mockUpstreams(routes) {
});
}
+// The world is the only always-on probe; these helpers assert that no
+// credentialed *backend* upstream was hit when nothing is configured.
+const backendProbes = () =>
+ global.fetch.mock.calls.map((c) => String(c[0])).filter((u) => !u.includes('world.three.ws'));
+
beforeEach(() => {
for (const v of ENV_VARS) {
savedEnv[v] = process.env[v];
@@ -64,8 +74,8 @@ describe('forge-health — per-backend verdicts', () => {
expect(Object.keys(health.backends).sort()).toEqual(Object.keys(BACKENDS).sort());
expect(health.backends.meshy.status).toBe('byok');
expect(health.backends.tripo.status).toBe('byok');
- // No platform env at all → nothing probed, nothing fetched.
- expect(global.fetch).not.toHaveBeenCalled();
+ // No platform env at all → no credentialed backend probe fired.
+ expect(backendProbes()).toEqual([]);
});
it('marks unset platform lanes unconfigured', async () => {
@@ -82,7 +92,7 @@ describe('forge-health — per-backend verdicts', () => {
mockUpstreams([]);
const health = await probeForgeHealth();
expect(health.backends.hunyuan3d.status).toBe('unconfigured');
- expect(global.fetch).not.toHaveBeenCalled();
+ expect(backendProbes()).toEqual([]);
});
it('passes Replicate when the invalid-version probe is rejected after auth (422)', async () => {
@@ -201,6 +211,54 @@ describe('forge-health — rate-limiter store', () => {
});
});
+describe('forge-health — world.three.ws', () => {
+ const HASH = 'a'.repeat(64);
+ const ASSET = `https://world.three.ws/assets/${HASH}.glb`;
+
+ function mockWorld(statusBody, { assetStatus = 200 } = {}) {
+ global.fetch = vi.fn(async (url, opts = {}) => {
+ if (String(url).includes('/status')) {
+ return new Response(JSON.stringify(statusBody), { status: 200 });
+ }
+ if (opts.method === 'HEAD') return new Response(null, { status: assetStatus });
+ throw new Error(`unrouted probe fetch: ${url}`);
+ });
+ }
+
+ it('reports ok when the world is protected and every asset resolves', async () => {
+ mockWorld({ protected: true, blueprints: [{ id: '$scene', assetUrl: ASSET }] });
+ const health = await probeForgeHealth();
+ expect(health.world.status).toBe('ok');
+ expect(health.world.protected).toBe(true);
+ expect(health.world.blueprint_count).toBe(1);
+ });
+
+ it('reports degraded (and degrades overall) when the world is unprotected', async () => {
+ mockWorld({ protected: false, blueprints: [] });
+ const health = await probeForgeHealth();
+ expect(health.world.status).toBe('degraded');
+ expect(health.world.message).toMatch(/unprotected/i);
+ expect(health.status).toBe('degraded');
+ });
+
+ it('reports down when a blueprint asset 404s — the scene would crash on join', async () => {
+ mockWorld({ protected: true, blueprints: [{ id: '$scene', assetUrl: ASSET }] }, { assetStatus: 404 });
+ const health = await probeForgeHealth();
+ expect(health.world.status).toBe('down');
+ expect(health.world.message).toMatch(/missing/i);
+ // A down world degrades overall — never escalates it past 'degraded'.
+ expect(health.status).toBe('degraded');
+ });
+
+ it('reports down when /status is unreachable instead of throwing', async () => {
+ global.fetch = vi.fn(async () => {
+ throw new Error('network down');
+ });
+ const health = await probeForgeHealth();
+ expect(health.world.status).toBe('down');
+ });
+});
+
describe('forge-health — caching', () => {
it('serves the cached payload within the TTL and re-probes on force', async () => {
process.env.REPLICATE_API_TOKEN = 'r8_test';
diff --git a/tests/api/pump-fun-mcp.test.js b/tests/api/pump-fun-mcp.test.js
index 41df99304..d63fed2be 100644
--- a/tests/api/pump-fun-mcp.test.js
+++ b/tests/api/pump-fun-mcp.test.js
@@ -43,7 +43,10 @@ vi.mock('../../src/pump/vanity-keygen.js', () => ({
generateVanityKey: vi.fn(async () => ({ publicKey: 'mocked', secretKey: 'mocked' })),
}));
-vi.setConfig({ testTimeout: 15_000, hookTimeout: 60_000 });
+// hookTimeout matches the global 120s calibration in vitest.config.js: the
+// beforeAll cold-imports api/pump-fun-mcp.js, which pulls the heavy Solana SDK
+// graph and has been measured past 60s under full-suite fork contention.
+vi.setConfig({ testTimeout: 15_000, hookTimeout: 120_000 });
// Mock rate-limit + clientIp so the route never blocks on Upstash.
vi.mock('../../api/_lib/rate-limit.js', () => ({
@@ -70,11 +73,14 @@ vi.mock('../../api/_lib/pump.js', () => ({
}),
}));
-// Mock the upstream pumpfun-claims-bot client.
+// Mock the upstream pumpfun-claims-bot client. pumpfunBotEnabled defaults to
+// false (no indexer); individual tests toggle it to exercise the configured
+// path — the route calls it fresh per request, so toggling between calls works.
vi.mock('../../api/_lib/pumpfun-mcp.js', () => ({
pumpfunBotEnabled: vi.fn(() => false),
pumpfunMcp: { creatorIntel: vi.fn(), recentClaims: vi.fn(), graduations: vi.fn() },
}));
+import { pumpfunBotEnabled } from '../../api/_lib/pumpfun-mcp.js';
// ── helpers ────────────────────────────────────────────────────────────────
function makeReq(body) {
@@ -120,53 +126,65 @@ beforeEach(() => {
sdkMock.fetchBondingCurve.mockReset();
connectionMock.getAccountInfo.mockReset();
connectionMock.getTokenLargestAccounts.mockReset();
+ // Default to the unconfigured-indexer state; tests that exercise the
+ // configured path opt in explicitly. Reset here so a toggle can't leak across
+ // tests (the route reads pumpfunBotEnabled() fresh on every request).
+ pumpfunBotEnabled.mockReturnValue(false);
});
// ── Tests ──────────────────────────────────────────────────────────────────
+// The six discovery tools that require the external indexer (PUMPFUN_BOT_URL).
+const INDEXER_TOOL_NAMES = [
+ 'search_tokens',
+ 'get_trending_tokens',
+ 'get_new_tokens',
+ 'get_graduated_tokens',
+ 'get_king_of_the_hill',
+ 'get_creator_profile',
+];
+
describe('initialize', () => {
- it('returns server info and protocol version', async () => {
+ it('returns server info, protocol version, and indexerEnabled flag', async () => {
+ pumpfunBotEnabled.mockReturnValue(false);
const { res, json } = await call({ jsonrpc: '2.0', id: 1, method: 'initialize' });
expect(res.statusCode).toBe(200);
expect(json.result.protocolVersion).toBeDefined();
expect(json.result.serverInfo.name).toBe('three.ws-pumpfun-mcp');
+ // indexerEnabled tracks PUMPFUN_BOT_URL presence — false when unconfigured.
+ expect(json.result.serverInfo.indexerEnabled).toBe(false);
+ });
+
+ it('reports indexerEnabled true when the bot is configured', async () => {
+ pumpfunBotEnabled.mockReturnValue(true);
+ const { json } = await call({ jsonrpc: '2.0', id: 1, method: 'initialize' });
+ expect(json.result.serverInfo.indexerEnabled).toBe(true);
});
});
describe('tools/list', () => {
- it('returns all 22 declared tools with schemas', async () => {
+ it('excludes the six indexer tools (keeps pumpfun_bot_status) when unconfigured', async () => {
+ pumpfunBotEnabled.mockReturnValue(false);
const { json } = await call({ jsonrpc: '2.0', id: 1, method: 'tools/list' });
expect(Array.isArray(json.result.tools)).toBe(true);
- expect(json.result.tools).toHaveLength(22);
- const names = json.result.tools.map((t) => t.name).sort();
- expect(names).toEqual(
- [
- 'getBondingCurve',
- 'getCreatorProfile',
- 'getGraduatedTokens',
- 'getKingOfTheHill',
- 'getNewTokens',
- 'getTokenDetails',
- 'getTokenHolders',
- 'getTokenTrades',
- 'getTrendingTokens',
- 'kol_leaderboard',
- 'kol_radar',
- 'pumpfun_first_claims',
- 'pumpfun_list_claims',
- 'pumpfun_quote_swap',
- 'pumpfun_vanity_mint',
- 'pumpfun_watch_claims',
- 'pumpfun_watch_whales',
- 'searchTokens',
- 'sns_resolve',
- 'sns_reverseLookup',
- 'social_cashtag_sentiment',
- 'social_x_post_impact',
- ].sort(),
- );
+ const names = json.result.tools.map((t) => t.name);
+ // None of the indexer-backed discovery tools are advertised…
+ for (const n of INDEXER_TOOL_NAMES) expect(names).not.toContain(n);
+ // …but the always-on metadata tool is.
+ expect(names).toContain('pumpfun_bot_status');
+ // 23 total declared − 6 indexer tools = 17 advertised.
+ expect(json.result.tools).toHaveLength(17);
for (const t of json.result.tools) expect(t.inputSchema.type).toBe('object');
});
+
+ it('advertises all 23 tools (incl. indexer tools) when the bot is configured', async () => {
+ pumpfunBotEnabled.mockReturnValue(true);
+ const { json } = await call({ jsonrpc: '2.0', id: 1, method: 'tools/list' });
+ expect(json.result.tools).toHaveLength(23);
+ const names = json.result.tools.map((t) => t.name);
+ for (const n of INDEXER_TOOL_NAMES) expect(names).toContain(n);
+ expect(names).toContain('pumpfun_bot_status');
+ });
});
describe('tools/call getBondingCurve', () => {
@@ -240,6 +258,31 @@ describe('tools/call indexer-required tools', () => {
});
});
+describe('tools/call pumpfun_bot_status', () => {
+ it('reports unconfigured + unhealthy with a message when the bot is unset', async () => {
+ pumpfunBotEnabled.mockReturnValue(false);
+ const { res, json } = await call({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'pumpfun_bot_status', arguments: {} },
+ });
+ // Always available — never gated, never an error envelope.
+ expect(res.statusCode).toBe(200);
+ expect(json.error).toBeUndefined();
+ const data = json.result.structuredContent;
+ expect(data.configured).toBe(false);
+ expect(data.healthy).toBe(false);
+ expect(data.message).toMatch(/PUMPFUN_BOT_URL/);
+ });
+
+ it('stays listed even when indexer tools are filtered out', async () => {
+ pumpfunBotEnabled.mockReturnValue(false);
+ const { json } = await call({ jsonrpc: '2.0', id: 1, method: 'tools/list' });
+ expect(json.result.tools.map((t) => t.name)).toContain('pumpfun_bot_status');
+ });
+});
+
describe('auth gate on expensive/sensitive tools', () => {
it('pumpfun_vanity_mint without a bearer or X-PAYMENT is rejected (does NOT return a secret key)', async () => {
const { res, json } = await call({
diff --git a/tests/api/redis-usage.test.js b/tests/api/redis-usage.test.js
new file mode 100644
index 000000000..08ac75d96
--- /dev/null
+++ b/tests/api/redis-usage.test.js
@@ -0,0 +1,133 @@
+// Redis quota-burn visibility (api/_lib/redis-usage.js).
+//
+// The free Upstash plan ceils at 500k commands/month; exceeding it fails every
+// critical limiter closed and 503s the whole paid surface (June 2026). These
+// tests pin the burn classifier and the ops-alert threshold so a runaway burn
+// rate can never page late — or fabricate a number when usage is unreadable.
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import {
+ evaluateRedisBurn,
+ redisBurnAlert,
+ fetchRedisDailyCommands,
+ REDIS_MONTHLY_BUDGET,
+} from '../../api/_lib/redis-usage.js';
+
+describe('evaluateRedisBurn — classification', () => {
+ it('reports ok well under the daily budget', () => {
+ const burn = evaluateRedisBurn(5_000); // ~30% of the daily budget
+ expect(burn.status).toBe('ok');
+ expect(burn.monthlyBudget).toBe(REDIS_MONTHLY_BUDGET);
+ expect(burn.projectedMonthly).toBe(150_000);
+ expect(burn.percentUsed).toBeCloseTo(30, 0);
+ });
+
+ it('warns above 70% of the daily budget', () => {
+ const burn = evaluateRedisBurn(13_000); // ~78% → projects ~390k
+ expect(burn.status).toBe('warning');
+ expect(burn.projectedMonthly).toBe(390_000);
+ });
+
+ it('goes critical above 90% of the daily budget', () => {
+ const burn = evaluateRedisBurn(16_000); // ~96% → projects 480k
+ expect(burn.status).toBe('critical');
+ expect(burn.projectedMonthly).toBe(480_000);
+ });
+
+ it('reports unknown (never a fabricated number) when usage is unreadable', () => {
+ for (const v of [null, undefined, NaN, -1]) {
+ const burn = evaluateRedisBurn(v);
+ expect(burn.status).toBe('unknown');
+ expect(burn.dailyCommands).toBeNull();
+ expect(burn.projectedMonthly).toBeNull();
+ expect(burn.percentUsed).toBeNull();
+ }
+ });
+});
+
+describe('redisBurnAlert — ops paging thresholds', () => {
+ it('does not alert below the 400k projection', () => {
+ expect(redisBurnAlert(evaluateRedisBurn(10_000))).toBeNull(); // projects 300k
+ });
+
+ it('fires a warning once the projection crosses 400k', () => {
+ const alert = redisBurnAlert(evaluateRedisBurn(14_000)); // projects 420k
+ expect(alert).not.toBeNull();
+ expect(alert.level).toBe('warning');
+ expect(alert.message).toMatch(/420k\/500k/);
+ expect(alert.message).toMatch(/upgrade/i);
+ });
+
+ it('escalates to critical once the projection crosses 450k', () => {
+ const alert = redisBurnAlert(evaluateRedisBurn(16_000)); // projects 480k
+ expect(alert).not.toBeNull();
+ expect(alert.level).toBe('critical');
+ expect(alert.message).toMatch(/480k\/500k/);
+ expect(alert.title).toMatch(/outage/i);
+ });
+
+ it('never alerts on unknown usage', () => {
+ expect(redisBurnAlert(evaluateRedisBurn(null))).toBeNull();
+ });
+});
+
+describe('fetchRedisDailyCommands — real source, honest fallback', () => {
+ const ENV = [
+ 'UPSTASH_EMAIL',
+ 'UPSTASH_MANAGEMENT_API_KEY',
+ 'UPSTASH_API_KEY',
+ 'UPSTASH_REDIS_STORE_ID',
+ 'UPSTASH_REDIS_REST_URL',
+ 'UPSTASH_REDIS_REST_TOKEN',
+ ];
+ const saved = {};
+ let savedFetch;
+ beforeEach(() => {
+ for (const v of ENV) {
+ saved[v] = process.env[v];
+ delete process.env[v];
+ }
+ savedFetch = global.fetch;
+ });
+ afterEach(() => {
+ for (const v of ENV) {
+ if (saved[v] === undefined) delete process.env[v];
+ else process.env[v] = saved[v];
+ }
+ global.fetch = savedFetch;
+ });
+
+ it('returns null without any credentials (no fetch, no fabrication)', async () => {
+ global.fetch = vi.fn();
+ expect(await fetchRedisDailyCommands()).toBeNull();
+ expect(global.fetch).not.toHaveBeenCalled();
+ });
+
+ it('reads the daily count from the Upstash Management API', async () => {
+ process.env.UPSTASH_EMAIL = '[email protected]';
+ process.env.UPSTASH_MANAGEMENT_API_KEY = 'mgmt-key';
+ process.env.UPSTASH_REDIS_STORE_ID = 'store_test';
+ global.fetch = vi.fn(async (url) => {
+ expect(String(url)).toContain('api.upstash.com/v2/redis/stats/store_test');
+ return new Response(JSON.stringify({ dailyrequests: [{ x: 1, y: 12_345 }] }), { status: 200 });
+ });
+ expect(await fetchRedisDailyCommands()).toBe(12_345);
+ });
+
+ it('falls back to the REST /stats/daily summary when management creds are absent', async () => {
+ process.env.UPSTASH_REDIS_REST_URL = 'https://probe.upstash.io';
+ process.env.UPSTASH_REDIS_REST_TOKEN = 'rest-token';
+ global.fetch = vi.fn(async (url) => {
+ expect(String(url)).toBe('https://probe.upstash.io/stats/daily');
+ return new Response(JSON.stringify({ totalCommands: 9_876 }), { status: 200 });
+ });
+ expect(await fetchRedisDailyCommands()).toBe(9_876);
+ });
+
+ it('returns null (not a guess) when the stats endpoint errors', async () => {
+ process.env.UPSTASH_REDIS_REST_URL = 'https://probe.upstash.io';
+ process.env.UPSTASH_REDIS_REST_TOKEN = 'rest-token';
+ global.fetch = vi.fn(async () => new Response('nope', { status: 500 }));
+ expect(await fetchRedisDailyCommands()).toBeNull();
+ });
+});
diff --git a/tests/pump-mcp-tools.test.js b/tests/pump-mcp-tools.test.js
index c87bbecd5..495a7c292 100644
--- a/tests/pump-mcp-tools.test.js
+++ b/tests/pump-mcp-tools.test.js
@@ -3,17 +3,20 @@ import { TOOLS, TOOL_ANNOTATIONS, rpcError, rpcEnvelope } from '../src/pump/mcp-
// Tool names that must be present in both the Vercel and Worker runtimes.
// Both import TOOLS from the same shared module, so parity is structural.
+// Canonical names are snake_case; the legacy camelCase forms are accepted on
+// tools/call via TOOL_NAME_ALIASES but never advertised in TOOLS.
const EXPECTED_TOOL_NAMES = [
- 'searchTokens',
- 'getTokenDetails',
- 'getBondingCurve',
- 'getTokenTrades',
- 'getTrendingTokens',
- 'getNewTokens',
- 'getGraduatedTokens',
- 'getKingOfTheHill',
- 'getCreatorProfile',
- 'getTokenHolders',
+ 'search_tokens',
+ 'get_token_details',
+ 'get_bonding_curve',
+ 'get_token_trades',
+ 'get_trending_tokens',
+ 'get_new_tokens',
+ 'get_graduated_tokens',
+ 'get_king_of_the_hill',
+ 'get_creator_profile',
+ 'get_token_holders',
+ 'pumpfun_bot_status',
];
describe('src/pump/mcp-tools — shared tool registry', () => {
diff --git a/vercel.json b/vercel.json
index e5604922d..aabe2182a 100644
--- a/vercel.json
+++ b/vercel.json
@@ -39,6 +39,10 @@
"includeFiles": "data/pages.json",
"maxDuration": 30
},
+ "api/cron/world-health.js": {
+ "includeFiles": "data/pages.json",
+ "maxDuration": 30
+ },
"api/cron/quota-check.js": {
"includeFiles": "data/pages.json",
"maxDuration": 30
@@ -3093,10 +3097,18 @@
"path": "/api/cron/uptime-check",
"schedule": "*/5 * * * *"
},
+ {
+ "path": "/api/cron/world-health",
+ "schedule": "*/15 * * * *"
+ },
{
"path": "/api/cron/forge-smoke",
"schedule": "30 9 * * *"
},
+ {
+ "path": "/api/llm/health",
+ "schedule": "0 * * * *"
+ },
{
"path": "/api/cron/cleanup-csrf-tokens",
"schedule": "17 * * * *"
diff --git a/workers/pump-fun-mcp/worker.js b/workers/pump-fun-mcp/worker.js
index de0e9d45e..3aab0207d 100644
--- a/workers/pump-fun-mcp/worker.js
+++ b/workers/pump-fun-mcp/worker.js
@@ -29,8 +29,9 @@ const INSTRUCTIONS =
'https://three.ws/api/pump-fun-mcp). Token discovery (search_tokens, ' +
'get_trending_tokens, get_new_tokens, get_graduated_tokens, get_king_of_the_hill), ' +
'on-chain analysis (get_bonding_curve, get_token_holders, get_token_details, ' +
- 'get_token_trades), and creator intelligence (get_creator_profile). All data is ' +
- 'live and on-chain; no API keys required.';
+ 'get_token_trades), and creator intelligence (get_creator_profile). Indexer-backed ' +
+ 'tools are listed only when the backend is configured — call pumpfun_bot_status ' +
+ '(always available) to check. All data is live and on-chain; no API keys required.';
const MAX_BATCH = 16;
const CORS_HEADERS = {
@@ -268,6 +269,55 @@ function indexerHandler(name, env) {
};
}
+// ── pumpfun_bot_status (metadata, always available) ──────────────────────────
+
+// Reports whether the indexer is configured and, when it is, whether it's
+// answering. Always available (never filtered) so MCP clients can discover
+// backend capability without parsing tools/list. Mirrors the Vercel handler.
+async function handlePumpfunBotStatus(_args, env) {
+ if (!env.PUMPFUN_BOT_URL) {
+ return {
+ configured: false,
+ healthy: false,
+ message:
+ 'PUMPFUN_BOT_URL is not configured. On-chain tools are available; indexer-backed discovery tools are disabled.',
+ };
+ }
+ const url = env.PUMPFUN_BOT_URL.replace(/\/$/, '');
+ const headers = { 'content-type': 'application/json', accept: 'application/json' };
+ if (env.PUMPFUN_BOT_TOKEN) headers.authorization = `Bearer ${env.PUMPFUN_BOT_TOKEN}`;
+ const ctrl = new AbortController();
+ const timer = setTimeout(() => ctrl.abort(), 3000);
+ const startedAt = Date.now();
+ try {
+ const r = await fetch(url, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'getNewTokens', arguments: { limit: 1 } },
+ }),
+ signal: ctrl.signal,
+ });
+ const latencyMs = Date.now() - startedAt;
+ if (!r.ok) return { configured: true, healthy: false, latencyMs, error: `bot ${r.status}` };
+ const j = await r.json().catch(() => null);
+ if (j?.error)
+ return { configured: true, healthy: false, latencyMs, error: j.error.message || 'rpc error' };
+ return { configured: true, healthy: true, latencyMs };
+ } catch (err) {
+ return {
+ configured: true,
+ healthy: false,
+ error: err?.name === 'AbortError' ? 'timeout after 3000ms' : err?.message || 'fetch failed',
+ };
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
// ── Dispatch ─────────────────────────────────────────────────────────────────
// Keyed by CANONICAL (snake_case) names. tools/call resolves legacy camelCase
@@ -284,6 +334,7 @@ function buildHandlers(env) {
get_graduated_tokens: indexerHandler('get_graduated_tokens', env),
get_king_of_the_hill: indexerHandler('get_king_of_the_hill', env),
get_creator_profile: indexerHandler('get_creator_profile', env),
+ pumpfun_bot_status: (a) => handlePumpfunBotStatus(a, env),
};
}
@@ -304,9 +355,26 @@ const WORKER_TOOL_NAMES = new Set([
'get_graduated_tokens',
'get_king_of_the_hill',
'get_creator_profile',
+ 'pumpfun_bot_status',
]);
const WORKER_TOOLS = TOOLS.filter((t) => WORKER_TOOL_NAMES.has(t.name));
+// Tools whose data comes only from the external indexer (PUMPFUN_BOT_URL).
+// Filtered out of tools/list when the bot is unconfigured so clients never see
+// a tool that would just return -32004. get_token_trades IS here: unlike the
+// Vercel handler (which has an on-chain trade-history fallback), this worker's
+// get_token_trades is indexer-only, so it can't be served without the bot.
+// pumpfun_bot_status is never filtered — it reports this very capability.
+const WORKER_INDEXER_TOOLS = new Set([
+ 'search_tokens',
+ 'get_token_trades',
+ 'get_trending_tokens',
+ 'get_new_tokens',
+ 'get_graduated_tokens',
+ 'get_king_of_the_hill',
+ 'get_creator_profile',
+]);
+
// ── JSON-RPC dispatch ────────────────────────────────────────────────────────
// Dispatch ONE JSON-RPC message; returns the response envelope or null for
@@ -320,13 +388,23 @@ async function dispatchRpc(msg, env) {
return rpcEnvelope(id, {
protocolVersion: PROTOCOL_VERSION,
capabilities: { tools: { listChanged: false } },
- serverInfo: SERVER_INFO,
+ // indexerEnabled lets client authors check indexer capability without a
+ // tools/list round-trip — it tracks the same env presence as the filter.
+ serverInfo: { ...SERVER_INFO, indexerEnabled: !!env.PUMPFUN_BOT_URL },
instructions: INSTRUCTIONS,
});
}
if (method === 'ping') return rpcEnvelope(id, {});
if (method === 'notifications/initialized') return null;
- if (method === 'tools/list') return rpcEnvelope(id, { tools: WORKER_TOOLS });
+ if (method === 'tools/list') {
+ // Advertise indexer-backed tools only when the bot is configured, so clients
+ // never see a tool that would just return -32004. pumpfun_bot_status (always
+ // listed, not in WORKER_INDEXER_TOOLS) reports capability.
+ const tools = env.PUMPFUN_BOT_URL
+ ? WORKER_TOOLS
+ : WORKER_TOOLS.filter((t) => !WORKER_INDEXER_TOOLS.has(t.name));
+ return rpcEnvelope(id, { tools });
+ }
if (method === 'resources/list') return rpcEnvelope(id, { resources: [] });
if (method === 'resources/templates/list') return rpcEnvelope(id, { resourceTemplates: [] });
if (method === 'prompts/list') return rpcEnvelope(id, { prompts: [] });