Skip to content

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

feat: add three.ws 3D Forge plugin submission documentation

nirholas828834eecb42
diff --git a/.claude-plugin/README.md b/.claude-plugin/README.md
index 461478bd7..738bc2ca9 100644
--- a/.claude-plugin/README.md
+++ b/.claude-plugin/README.md
@@ -14,6 +14,7 @@ The official Claude Code plugin marketplace for [three.ws](https://three.ws) —
/plugin install three-ws-core@three-ws # wallet + x402 payment skills
/plugin install three-ws-developer@three-ws # agent scaffolding + MCP tooling
/plugin install three-ws-pump-fun@three-ws # pump.fun on-chain trading
+/plugin install three-ws-3d@three-ws # text/image → 3D models + rigged avatars
```
Run `/reload-plugins` (or restart Claude Code) after installing.
@@ -25,6 +26,7 @@ Run `/reload-plugins` (or restart Claude Code) after installing.
| `three-ws-core` | 9 skills | Authenticate, fund, send, trade, search the bazaar, pay for and monetize services, query onchain data. | [README](../.agents/README.md) |
| `three-ws-developer` | 3 commands + MCP server | Scaffold agents, configure `@three-ws/mcp-server`, get runnable tool code. | [README](../marketplace/plugins/three-ws-developer/README.md) |
| `three-ws-pump-fun` | 5 skills | Create coins, swap tokens, manage creator fees, tokenize agents, live feed reactions. | [README](../pump-fun-skills/README.md) |
+| `three-ws-3d` | 4 skills + 3 MCP servers | Text/image → textured 3D models and rigged, animation-ready avatars; scene composition; live avatar embeds. | [README](../marketplace/plugins/three-ws-3d/README.md) |
## Configuration at a glance
@@ -33,6 +35,7 @@ Run `/reload-plugins` (or restart Claude Code) after installing.
| `three-ws-core` | `THREE_WS_API`, `THREE_WS_TOKEN` |
| `three-ws-developer` | `MCP_EVM_PAYMENT_ADDRESS`, `MCP_SVM_PAYMENT_ADDRESS` |
| `three-ws-pump-fun` | `SOLANA_PRIVATE_KEY`, `SOLANA_RPC_URL` |
+| `three-ws-3d` | `MCP_SVM_PAYMENT_ADDRESS` (paid lanes only) |
See each plugin's README for details. Skills that move funds always confirm before executing, and transactions are irreversible.
diff --git a/.env.example b/.env.example
index 59348bf1e..e7986a528 100644
--- a/.env.example
+++ b/.env.example
@@ -356,6 +356,14 @@ X402_IDEMPOTENCY_TTL_SECONDS=3600
# X402_FACILITATOR_URL_BASE at it for production.
X402_FACILITATOR_URL_SOLANA=https://facilitator.payai.network
X402_FACILITATOR_URL_BASE=https://facilitator.payai.network
+# Advertise the Base (eip155:8453) payment rail WITHOUT CDP credentials. OFF by
+# default: setting X402_FACILITATOR_URL_BASE alone is NOT treated as proof the
+# facilitator settles — a stale/decommissioned host answers /verify with 404 and
+# every Base-preferring buyer would pay, fail verification, and get a 502. Set to
+# true ONLY after confirming your non-CDP Base facilitator actually verifies+settles.
+# With CDP creds set (CDP_API_KEY_ID + CDP_API_KEY_SECRET), Base routes to Coinbase
+# and this flag is unnecessary. Solana (self-hosted facilitator) is always-on.
+X402_ADVERTISE_BASE=false
# Optional bearer tokens for self-hosted/private facilitators.
X402_FACILITATOR_TOKEN_SOLANA=
X402_FACILITATOR_TOKEN_BASE=
@@ -710,6 +718,27 @@ APP_ORIGIN=https://three.ws
# Generate: openssl rand -base64 32
CRON_SECRET=
+# ── Database retention (/api/cron/db-retention) ──────────────────────────────
+# Keeps the Neon branch under its project-size cap. The pump.fun intel firehose
+# (pump_coin_intel + its mint-keyed satellites) ingests tens of thousands of rows
+# a day; the retention cron prunes anything older than the window below and
+# self-tunes under storage pressure. Docs: docs/ops/db-retention.md
+#
+# Normal retention window for the coin-intel firehose, in days. Clamped [2,365].
+# Default 14 matches the smart-money engine's judge horizon. A 512 MB Neon free
+# tier cannot physically hold 14 days of the firehose — the pressure valve below
+# will hold a shorter effective window until the branch is upgraded. Raise this
+# after moving to a larger Neon plan.
+PUMP_INTEL_RETENTION_DAYS=14
+# Hard floor the pressure valve tightens to when the branch is over the high-water
+# mark. Clamped [1, PUMP_INTEL_RETENTION_DAYS]. Coins are judged within a day or
+# two of launch, so 3 keeps everything load-bearing while shedding the oldest data.
+PUMP_INTEL_MIN_RETENTION_DAYS=3
+# Storage high-water mark in MB. At/above this the retention cron switches to the
+# min window so the hard cap (512 MB on the free tier) is never actually reached.
+# Clamped [128, 100000]. Lower it for more headroom; raise it after a plan upgrade.
+DB_RETENTION_HIGH_WATER_MB=470
+
# ── Agent activity engine (api/_lib/circulation.js, /api/cron/pulse-tick) ─────
# Operates a pool of platform-owned agents that transact with one another on-chain
# (tips, payments, trades, launches, on-chain registration) so the live money feed
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3ec696b3c..d22800a5f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,8 +19,10 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Diorama is live — speak a little 3D world into being** — Diorama is now a real, reachable page at three.ws/diorama. Type one sentence — "a cozy autumn campsite by a lake at dusk" — and Claude composes the scene, each object is forged into a real 3D model, and the little world assembles in front of you, explorable in 3D and viewable in AR. Save it and you get a permalink and a slot on the public gallery wall, where every saved world shows a live rotating 3D thumbnail you can open and explore. Share it as a 3D postcard: copy the link, post to X, or grab an embed snippet. Nothing is a screenshot — it's all real geometry forged from your words. (`/diorama`) `[feature]`
- **Labs — a home for the hidden gems most people never find** — There's a new Labs page at three.ws/labs (now linked from the Discover menu and the footer) that gathers the platform's experimental and advanced surfaces in one beautiful, filterable gallery — the kind of things you'd only reach before if you knew the exact URL. Speak a 3D world into being with Diorama, drive an avatar with your webcam in Mocap Studio, run a coin hands-off with Autopilot, watch autonomous agents coordinate on-chain, and more. Each card shows a live status check and a preview, and you can filter by category. Everything featured is real and live. (`/labs`) `[feature]`
- **Launch Studio, redesigned — and rewards can now go to anyone** — The Launch Studio got a full makeover and a big new power. New look: instant search across all 50 recipes, colour-themed category tabs, a Reward/Theme filter, savable favourites, a Surprise-me button, and keyboard shortcuts. Clicking a recipe now slides open a live preview drawer with real candidate coins — avatars, signal-strength bars, a dev-buy slider that flows into the launch, and a network toggle. The big addition is the reward planner: route a coin's creator fees to anyone, not just GitHub — a GitHub or X (Twitter) account, any Solana wallet or .sol name, back to holders as cashback, or into an auto buy-back-and-burn. The same generalisation reaches the post-launch fees panel, whose recipient box now accepts a GitHub @user, an X handle (x:@handle), a raw wallet, or an owner/repo to split contributors. (`/launch-studio`) `[improvement, feature]`
+- **Live data keeps flowing — automatic database housekeeping** — A handful of behind-the-scenes jobs — the smart-money radar, the coin-intel feeds, and usage metering — had started intermittently failing because the database had grown to its storage ceiling. We reclaimed the space, added a scheduled housekeeping job that trims the high-volume coin-intel history and stale avatar-generation payloads so the database self-manages its size, and made every write path degrade gracefully (a brief 'retry shortly' instead of a hard error) if storage ever runs tight again. The radar, feeds, and metering now keep updating reliably. `[fix, infra]`
- **Long-running agent endpoints no longer time out mid-task** — Fixed a deployment-config gap where fifteen API endpoints asked for more time than they were actually granted, so the platform's 30-second catch-all limit silently overrode them. Team tasks (an agent hiring and coordinating a crew), the ask-an-agent endpoint, multi-image and single-image avatar generation, portfolio and autopilot proposals, vision and voice-face processing all now get the full budget they were designed for instead of being cut off at 30 seconds with a gateway timeout. Separately, the live portfolio stream now closes itself cleanly just before the platform's window and lets your browser reconnect, instead of being hard-killed with a timeout error mid-update. `[fix, infra]`
- **Money Pulse & Viability now render in the brand type** — Fixed the typography on the Money Pulse and Viability pages. Both surfaces were missing a base font, so any text without its own styling — the subtitle, network toggle, filter labels and live-feed rows — fell back to the browser's default serif and read as unstyled. They now use the platform's Inter/Space Grotesk/JetBrains Mono set, so each page reads as one clean, consistent monochrome surface. (`/pulse`) `[fix]`
+- **Pay-per-call APIs now settle reliably — no more dead payment rails** — Our x402 pay-per-call endpoints advertise which networks they accept before you pay. A secondary settlement network had been advertised even while its external verifier was offline, so a payment on that rail could be built and submitted only to fail at the last step. Endpoints now advertise a network only when it can actually settle — Solana (our in-house facilitator) always leads, and the secondary EVM rail appears only when a working verifier is configured. Buyers settle on the healthy rail instead of hitting a dead one. We also hardened the reputation-scoring job so a single slow wallet read can never stall the whole refresh. `[fix, improvement]`
- **Pricing your agent's skills is now one tap** — The Pricing section of Agent Studio's Money tab now opens with a storefront summary — how many of your sellable skills carry a price, the average per-call price, and how many are still free — computed live from your real pricing. Each skill gets one-tap price chips ($0.01, $0.10, $1, or Free): tap one and it sets and saves the price instantly, with the active price highlighted, so you can price your whole agent in seconds instead of typing into every field. Editing a price by hand still works exactly as before; the summary and highlights update the moment a price lands, without disturbing anything you're mid-editing. (`/agent-studio`) `[improvement]`
- **The Agent Labor Market, reimagined** — The labor market got a top-to-bottom redesign built for watching the machine economy work. A live hero with settlement sparklines, a real-time $THREE-flow ticker, and a sticky toolbar with instant search, sorting (reward, most bids, newest), a "Mine" filter, and skill/reward filters. Open any bounty into a richer drawer: a lifecycle stepper from Posted → Settled, a bid-distribution chart, transparent bid scores, and every on-chain receipt one tap away. Bounties are now shareable by link, the whole surface is keyboard-driven (press ? for shortcuts), and clean toast notifications replace jarring pop-ups. Moderators get an in-drawer override to release or refund a stuck bounty — without ever touching the escrow key. (`/labor-market`) `[improvement, feature]`
- **The Arena gets a full design pass — and its tournament pages work again** — The Arena's live tournament view was silently broken: opening any competition showed a stuck loading screen because the page relied on four pieces that were never finished. They're now built and live — a window-progress timeline that ticks down to the open and close, a prize ladder showing exactly how the $THREE pool splits across the podium and who currently holds each place, a rules-and-eligibility panel spelling out scoring, bracket and the trade gates, and a summary strip totalling entrants, in-window trades and net P&L across the field. The whole surface also got a cohesion pass to match the rest of three.ws: the correct Space Grotesk / Inter typefaces (it was rendering in the browser's default serif), the shared color tokens so it flips cleanly between dark and light themes, and tighter, fully responsive layouts on phone and desktop. The list page now opens with a live snapshot of what's on — how many tournaments are live, upcoming and finished, plus total $THREE at stake and agents competing. (`/arena`) `[fix, improvement]`
@@ -31,6 +33,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **The Trading Brain is redesigned — presets, a live risk meter, and a real backtest breakdown** — Building your agent's sniper is now a minute, not a manual. Four one-tap presets — Guardian, Balanced, Hunter, Moonshot — fill the whole rule with a coherent risk posture you can then tune; the active preset stays highlighted and un-highlights the moment you change anything. A live Risk Profile meter scores your rule from its own parameters (position size, stop depth, slippage, how fresh a coin it chases, concurrent exposure) and slides from calm green to hot red as you push it, so you can feel the aggressiveness before you arm. The backtest no longer stops at headline numbers: it now shows a segmented bar of how the matching launches actually resolved — graduated, pumped, flat, rugged — plus a few real best- and worst-case sample trades, so the projection is honest about its shape. Power users get keyboard shortcuts (⌘/Ctrl+S save, ⌘/Ctrl+B backtest, ⌘/Ctrl+↵ run). And on the wallet, balances now count up and flash green or red when money moves instead of hard-swapping. Every animation respects reduced-motion. (`/agent-studio`) `[improvement, feature]`
- **The x402 page is now a live, searchable storefront** — three.ws/x402 is rebuilt as a live catalog. Every paid endpoint the platform offers now renders automatically from the OpenAPI discovery doc with its real price, description, and category — no more hand-maintained cards. Search or press ⌘K to jump to any endpoint, filter by category, and sort by most-used or price. Click an endpoint to open a detail panel that reads its input schema into a fill-in form, shows ready-to-copy JavaScript, cURL, and Python snippets, and runs it end-to-end with a real on-chain USDC payment — the response, settlement network, and transaction link stream back inline. A live stats bar surfaces 24-hour settlement volume, success rate, and unique payers, and the page now has a full light theme. (`/x402`) `[feature, improvement]`
- **The x402 toolkit is now on npm and the VS Code Marketplace** — The x402 buyer, seller, browser-modal and MCP libraries are published as standalone, provider-neutral npm packages you can use in any project without a three.ws account: @three-ws/x402-fetch (drop-in fetch that auto-pays a 402 in USDC), @three-ws/x402-server (build paid endpoints), @three-ws/x402-modal and @three-ws/x402-payment-modal (drop-in browser checkout), and @three-ws/x402-mcp and @three-ws/ibm-x402-mcp (pay or sell from any MCP client). There's also a new x402 extension for VS Code — inspect, pay, and scaffold paid endpoints from the editor — on both the VS Code Marketplace and Open VSX. The docs now carry install commands, one-line summaries, repo links, and a Node code sample in the pay-for-a-service tutorial. (`/x402`) `[sdk, docs]`
+- **three.ws 3D Forge is now a one-command Claude Code plugin** — You can add three.ws 3D generation straight into Claude Code as a one-line plugin. three.ws 3D Forge bundles four skills — a free text→3D draft lane plus the paid avatar, high-fidelity mesh, and auto-rig lanes — and wires the three.ws generation, scene, and avatar servers with no extra setup. Add it with `/plugin marketplace add nirholas/three.ws`, then `/plugin install three-ws-3d@three-ws`; every result hands back a downloadable GLB and a live viewer link. The plugin is now packaged to Anthropic's plugin spec — manifest, license, and changelog — and prepared for submission to the public Claude plugin directory. (`/forge`) `[feature, sdk]`
- **three.ws now self-hosts its Solana payment settlement** — The platform's Solana x402 payments no longer depend on an outside settlement service — three.ws runs its own facilitator, so it holds its own keys, uses its own RPC, and keeps every settled payment inside the platform. Alongside it, a closed-loop internal settlement engine continuously proves every paid endpoint actually works end-to-end by cycling a small amount of the platform's own USDC between platform-controlled wallets. This is clearly labeled internal dogfooding — never counted as outside demand — and it's engineered to cost only network fees: fewer, larger payments instead of millions of tiny ones, with a hard SOL floor that pauses the loop before it can spend down the fee wallet. It ships off by default. `[infra, security]`
- **Treasury Autopilot screen matches the brand** — Polished the agent's live Treasury Autopilot dashboard so it reads as one product with the rest of the site. The on-screen render — the balance, runway gauge, income/burn/net stats and policy rules that show on /agents-live and the agent screen — now draws in the platform's own Space Grotesk and Inter type instead of the browser's default font, with the runway label no longer clipping. The interactive cockpit's status colours (armed/killed, healthy/warning/critical runway, buyback and distribution states) now come from the shared design tokens, so green/amber/red match everywhere. The Market Anchor lower-third dropped its off-brand blue and orange for the site's monochrome palette, and the whole cockpit reflows cleanly on phones. (`/agent-screen`) `[improvement]`
diff --git a/api/_lib/db.js b/api/_lib/db.js
index ff656624e..0dc254e2b 100644
--- a/api/_lib/db.js
+++ b/api/_lib/db.js
@@ -247,6 +247,31 @@ export function isDbUnavailableError(err) {
return false;
}
+// Returns true when the error is a storage-capacity failure: Postgres SQLSTATE
+// 53100 (disk_full), which Neon raises as "could not extend file because project
+// size limit (… MB) has been exceeded" once a branch reaches its storage cap.
+//
+// This is a distinct condition from isDbUnavailableError's connectivity failures:
+// the database is reachable and READS still succeed — only WRITES that need to
+// grow a relation fail (INSERT/UPDATE/index extension). It is not a code bug, and
+// it clears the moment retention frees space (see api/cron/db-retention.js). Left
+// unclassified it 500s every write path and, on the ~70 cron ticks/5-min, fires an
+// unhandled-5xx Sentry event + ops alert per request — the exact NeonDbError
+// storm seen in production. Classified, write paths degrade gracefully: wrapCron
+// skips the tick (200 + reason), API writes return a bounded 503 + Retry-After,
+// and a single deduped 'db:capacity' alert tells ops to reclaim space.
+//
+// Matched on BOTH the SQLSTATE code and the message text: the native driver sets
+// err.code = '53100', but the esbuild-minified production bundle can surface only
+// the wrapped message, so we also regex the message chain (message + sourceError +
+// cause) the same way isDbUnavailableError folds in nested transport errors.
+export function isDbCapacityError(err) {
+ if (!err) return false;
+ if (String(err.code) === '53100') return true;
+ const msg = `${err.message ?? ''} ${err.sourceError?.message ?? ''} ${err.cause?.message ?? ''}`;
+ return /could not extend file because|project size limit|max_cluster_size|throttle_or_fail_extension/i.test(msg);
+}
+
export const sql = new Proxy(function () {}, {
apply(_t, _this, args) {
// Neon dispatches on the first argument: a string is the ordinary
diff --git a/api/_lib/env.js b/api/_lib/env.js
index 4ad4527c6..f6edd831b 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -755,6 +755,17 @@ export const env = {
),
);
},
+ // Explicit opt-in to advertise the Base (eip155:8453) payment rail WITHOUT CDP
+ // credentials. Off by default: a bare X402_FACILITATOR_URL_BASE being set is NOT
+ // proof the facilitator settles — prod had it pointed at decommissioned hosts
+ // (x402.sperax.io, facilitator.payai.network) that 404 every /verify, so every
+ // Base-preferring buyer paid, failed verification, and got a 502. Turn this on
+ // only after confirming your non-CDP Base facilitator actually verifies+settles.
+ // With CDP creds set, Base routes to CDP and this flag is unnecessary. Solana
+ // (self-hosted facilitator) is always-on regardless. See baseSettleable().
+ get X402_ADVERTISE_BASE() {
+ return opt('X402_ADVERTISE_BASE', 'false') === 'true';
+ },
get X402_FACILITATOR_TOKEN_SOLANA() {
return opt('X402_FACILITATOR_TOKEN_SOLANA', opt('X402_FACILITATOR_TOKEN'));
},
diff --git a/api/_lib/http.js b/api/_lib/http.js
index fcb9d14fd..226471831 100644
--- a/api/_lib/http.js
+++ b/api/_lib/http.js
@@ -6,7 +6,7 @@ import { env } from './env.js';
import { captureException } from './sentry.js';
import { sendOpsAlert } from './alerts.js';
import { instrument as zauthInstrument, drain as zauthDrain } from './zauth.js';
-import { isDbUnavailableError } from './db.js';
+import { isDbUnavailableError, isDbCapacityError } from './db.js';
// Secure-by-default caching: emit `no-store` UNLESS the handler already set a
// Cache-Control header (e.g. `res.setHeader('cache-control', 'public, s-maxage=…')`
@@ -196,10 +196,13 @@ export function reportServerError(err, { code = 'internal_error', status = 500,
// A DB outage is infrastructure, not a code fault: throttle the log, skip the
// Sentry capture, and collapse to the single shared `db:unavailable` alert so a
// missing DATABASE_URL degrades quietly instead of flooding error tracking.
- if (isDbUnavailableError(err)) {
+ const dbFull = isDbCapacityError(err);
+ if (isDbUnavailableError(err) || dbFull) {
logDbUnavailableOnce(code, detail);
try {
- sendOpsAlert('database unavailable', `${detail}\nref ${ref}`, { signature: 'db:unavailable' });
+ sendOpsAlert(dbFull ? 'database at storage cap — retention needed' : 'database unavailable', `${detail}\nref ${ref}`, {
+ signature: dbFull ? 'db:capacity' : 'db:unavailable',
+ });
} catch { /* alerts best-effort */ }
return ref;
}
@@ -222,10 +225,11 @@ export function reportServerError(err, { code = 'internal_error', status = 500,
// is logged + captured server-side under a correlation id the caller can quote
// to support; the client only sees a generic description + the ref.
export function serverError(res, status, code, err, extra = {}) {
- // Coerce a DB outage to 503 + Retry-After regardless of the caller's status, so
- // boundaries that catch internally (sitemap, deployments) advertise "retry
- // shortly" to clients and CDNs exactly like wrap() does, instead of a hard 500.
- if (isDbUnavailableError(err)) {
+ // Coerce a DB outage OR a storage-cap failure to 503 + Retry-After regardless of
+ // the caller's status, so boundaries that catch internally (sitemap, deployments)
+ // advertise "retry shortly" to clients and CDNs exactly like wrap() does, instead
+ // of a hard 500.
+ if (isDbUnavailableError(err) || isDbCapacityError(err)) {
const ref = reportServerError(err, { code, status: 503 });
if (typeof res.setHeader === 'function') res.setHeader('retry-after', '30');
return json(res, 503, {
@@ -421,18 +425,25 @@ export function wrap(handler) {
await handler(req, res, ...rest);
} catch (err) {
const dbDown = isDbUnavailableError(err);
- const status = dbDown ? 503 : (err.status || 500);
+ // Storage-cap failures (SQLSTATE 53100) are, like a connectivity outage, an
+ // infrastructure condition rather than a code bug — reads still work, writes
+ // fail until retention frees space — so they take the same graceful, throttled,
+ // no-Sentry path, just with a distinct alert so ops knows to reclaim space
+ // (api/cron/db-retention.js) rather than chase a phantom bug.
+ const dbFull = !dbDown && isDbCapacityError(err);
+ const dbDegraded = dbDown || dbFull;
+ const status = dbDegraded ? 503 : (err.status || 500);
if (status >= 500) {
const ref = correlationId();
- if (dbDown) {
- // During a DB outage EVERY endpoint that doesn't catch internally lands
- // here. A missing/rotated DATABASE_URL would otherwise emit one
- // `[api] unhandled` error line + one Sentry event per request — thousands
+ if (dbDegraded) {
+ // During a DB outage/cap EVERY endpoint that doesn't catch internally lands
+ // here. A missing/rotated DATABASE_URL or a full branch would otherwise emit
+ // one `[api] unhandled` error line + one Sentry event per request — thousands
// in minutes. It's infrastructure, not a code bug: throttle the log, skip
// the Sentry capture, and fire only the single shared deduped alert.
logDbUnavailableOnce(`${req.method} ${redactUrl(req.url)}`, err?.message || String(err));
- sendOpsAlert('database unavailable', `${err?.message || String(err)}\nref ${ref}`, {
- signature: 'db:unavailable',
+ sendOpsAlert(dbFull ? 'database at storage cap — retention needed' : 'database unavailable', `${err?.message || String(err)}\nref ${ref}`, {
+ signature: dbFull ? 'db:capacity' : 'db:unavailable',
});
} else {
// Redact coordinates / device tokens so a 5xx on a geolocated read never
@@ -448,7 +459,7 @@ export function wrap(handler) {
// so err.message would leak HELIUS_API_KEY to the client. Hand back a
// sanitized envelope keyed to the same ref we just logged.
if (!res.headersSent && !res.writableEnded) {
- if (dbDown) {
+ if (dbDegraded) {
// 503 with Retry-After so clients and CDNs know to back off.
res.setHeader('retry-after', '30');
}
@@ -459,8 +470,8 @@ export function wrap(handler) {
redirect(res, serverErrorPageLocation(ref, req), 303);
} else {
json(res, status, {
- error: dbDown ? 'service_unavailable' : (err.code || 'internal_error'),
- error_description: dbDown
+ error: dbDegraded ? 'service_unavailable' : (err.code || 'internal_error'),
+ error_description: dbDegraded
? 'database temporarily unavailable — retry shortly'
: `internal error — quote ref ${ref} to support`,
ref,
@@ -507,10 +518,11 @@ export function wrapCron(handler) {
import('./cache.js').then(({ cacheSet }) => {
cacheSet(`cron:heartbeat:${cronName}`, { ok: false, t: t0, ms: Date.now() - t0, err: err?.message?.slice(0, 200) }, 7 * 24 * 60 * 60).catch(() => {});
}).catch(() => {});
- if (isDbUnavailableError(err)) {
- console.warn('[cron] db unavailable — skipping tick:', err.message);
+ if (isDbUnavailableError(err) || isDbCapacityError(err)) {
+ const full = isDbCapacityError(err);
+ console.warn(`[cron] db ${full ? 'at storage cap' : 'unavailable'} — skipping tick:`, err.message);
if (!res.headersSent && !res.writableEnded) {
- json(res, 200, { ok: false, reason: 'db_unavailable' });
+ json(res, 200, { ok: false, reason: full ? 'db_full' : 'db_unavailable' });
}
return;
}
diff --git a/api/_lib/launcher-engine.js b/api/_lib/launcher-engine.js
index 06a351b8d..fa75432ac 100644
--- a/api/_lib/launcher-engine.js
+++ b/api/_lib/launcher-engine.js
@@ -25,7 +25,7 @@
// circuit breaker bound the blast radius. Never throws — every failure is contained
// and recorded.
-import { sql } from './db.js';
+import { sql, isDbCapacityError, isDbUnavailableError } from './db.js';
import { env } from './env.js';
import { createSession } from './auth.js';
import { pickSource } from './launcher-sources.js';
@@ -499,7 +499,12 @@ export async function runLauncherTick() {
if (e instanceof Skip) {
results.push({ ok: false, scope: cfg.scope, skipped: e.message });
} else {
- console.error('[launcher] scope tick failed', cfg.scope, e?.message);
+ // A full/unavailable DB is infrastructure, not a launcher bug — the tick is
+ // already caught and the next one retries, so log it at warn (not error) so
+ // a storage-cap blip doesn't read as a code fault in the error stream.
+ const infra = isDbCapacityError(e) || isDbUnavailableError(e);
+ const log = infra ? console.warn : console.error;
+ log('[launcher] scope tick failed', cfg.scope, e?.message);
results.push({ ok: false, scope: cfg.scope, error: String(e?.message || e).slice(0, 300) });
}
}
diff --git a/api/_lib/trust/reputation-store.js b/api/_lib/trust/reputation-store.js
index 9def32401..43a83e86b 100644
--- a/api/_lib/trust/reputation-store.js
+++ b/api/_lib/trust/reputation-store.js
@@ -195,7 +195,10 @@ export async function listStaleAgents(limit = 40) {
* the next tick (they sort as stalest-first), so coverage is never lost.
* @returns {Promise<{ scored: number, failed: number, remaining: number, timedOut: boolean }>}
*/
-export async function recomputeAgents(agentIds = [], { concurrency = 4, deadlineMs = Infinity } = {}) {
+export async function recomputeAgents(
+ agentIds = [],
+ { concurrency = 4, deadlineMs = Infinity, perAgentTimeoutMs = 20_000 } = {},
+) {
let scored = 0;
let failed = 0;
let timedOut = false;
@@ -203,17 +206,50 @@ export async function recomputeAgents(agentIds = [], { concurrency = 4, deadline
const startedAt = Date.now();
let i = 0;
for (; i < ids.length; i += concurrency) {
- if (Date.now() - startedAt > deadlineMs) { timedOut = true; break; }
+ const elapsed = Date.now() - startedAt;
+ // Cap each agent's compute so ONE hung upstream (a stalled Solana RPC, a slow
+ // DB read) can't block the whole chunk — and thus the cron — past Vercel's
+ // hard function timeout. Checking the deadline only BETWEEN chunks is not
+ // enough: an un-timed getAgentReputation() inside Promise.allSettled awaits
+ // forever, so the 250s deadline never gets a turn and the run 504s at 300s.
+ const remainingBudget = Number.isFinite(deadlineMs) ? deadlineMs - elapsed : Infinity;
+ if (remainingBudget <= 0) { timedOut = true; break; }
+ // The per-agent ceiling is the smaller of a fixed budget and the wall-clock
+ // remaining before the deadline, so even the final chunk can't overrun it.
+ // A tiny remaining sliver just means slow agents on the last chunk time out
+ // and roll over to the next tick — never lost, since they sort stalest-first.
+ const budget = Math.min(perAgentTimeoutMs, remainingBudget);
const chunk = ids.slice(i, i + concurrency);
- const results = await Promise.allSettled(chunk.map((id) => getAgentReputation(id)));
+ const results = await Promise.allSettled(
+ chunk.map((id) => withTimeout(getAgentReputation(id), budget, id)),
+ );
for (const r of results) {
if (r.status === 'fulfilled' && r.value) {
const ok = await saveReputation(r.value);
ok ? scored++ : failed++;
} else {
+ // A timed-out or failed agent rolls over to the next tick — it sorts
+ // stalest-first — so bounding it here never loses coverage.
failed++;
}
}
}
return { scored, failed, remaining: Math.max(0, ids.length - i), timedOut };
}
+
+// Race a per-agent recompute against a timeout. A hung upstream can leave the
+// original promise pending forever; Promise.race settles on the timeout, and the
+// loser's late rejection is swallowed so it never surfaces as an unhandled
+// rejection after the race resolved. The timer is always cleared so a fast agent
+// doesn't leave a dangling handle keeping the function warm.
+function withTimeout(promise, ms, id) {
+ promise.catch(() => {}); // swallow a late rejection from the losing promise
+ let timer;
+ const timeout = new Promise((_, reject) => {
+ timer = setTimeout(
+ () => reject(new Error(`reputation recompute timed out for ${id} after ${ms}ms`)),
+ ms,
+ );
+ });
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
+}
diff --git a/api/_lib/x402-paid-endpoint.js b/api/_lib/x402-paid-endpoint.js
index 1fbc23ad6..f20c823ed 100644
--- a/api/_lib/x402-paid-endpoint.js
+++ b/api/_lib/x402-paid-endpoint.js
@@ -160,11 +160,11 @@ function buildRequirements({ priceAtomics, networks, resourceUrl, payToOverride
// 402-failing only when NONE are payable. The asset is checked here too —
// without it the accept would be advertised and then rejected by the
// facilitator at settle, which is the same broken experience as a 500.
- // Base also needs a WORKING facilitator to settle against — CDP creds or an
- // explicit facilitator URL. Without one it routes to the decommissioned
- // PayAI default that 404s every /verify, so advertising Base would hand
- // buyers a first-choice accept that always fails at settle (a 502, not a
- // clean 402). Drop Base instead; the Solana accept still settles in-house.
+ // Base also needs a WORKING facilitator to settle against — CDP creds or the
+ // X402_ADVERTISE_BASE opt-in. A bare facilitator URL is not enough: the prod
+ // host was decommissioned and 404s every /verify, so advertising Base would
+ // hand buyers an accept that always fails at settle (a 502, not a clean 402).
+ // Drop Base instead; the Solana accept still settles in-house.
if (
net === NETWORK_BASE_MAINNET &&
(!baseTo || !env.X402_ASSET_ADDRESS_BASE || !baseSettleable())
diff --git a/api/_lib/x402-spec.js b/api/_lib/x402-spec.js
index 7e261ca1f..837bf6273 100644
--- a/api/_lib/x402-spec.js
+++ b/api/_lib/x402-spec.js
@@ -278,19 +278,71 @@ function facilitatorFor(network) {
}
// Is Base (eip155:8453) actually settleable right now? Base routes to CDP when
-// CDP creds are set, otherwise to X402_FACILITATOR_URL_BASE. The historical bare
-// default for that URL — facilitator.payai.network — was decommissioned and now
-// answers every /verify with `404 Application not found`, so a Base accept that
-// falls through to it gets advertised (buyers pick it first), then fails at
-// verify with a 502. Treat Base as settleable ONLY when the operator has
-// committed to a working facilitator: CDP credentials, an explicit per-network
-// Base URL, or an explicit generic facilitator URL. A pure fall-through to the
-// hardcoded default is NOT a working Base facilitator. Self-heals: the moment
-// CDP keys or an explicit URL are configured, Base is advertised again. Solana
+// CDP creds are set, otherwise to X402_FACILITATOR_URL_BASE. Treat Base as
+// settleable ONLY when we can trust it will verify+settle:
+//
+// 1. CDP credentials are configured — Base routes to Coinbase's facilitator, a
+// known-good, platform-trusted path.
+// 2. The operator has EXPLICITLY opted in via X402_ADVERTISE_BASE=true.
+//
+// A bare X402_FACILITATOR_URL_BASE being SET is deliberately NOT enough. Prod had
+// it pointed at decommissioned hosts (x402.sperax.io, then facilitator.payai.network)
+// that answer every /verify with `404 Application not found` — so a Base accept was
+// advertised (buyers pick it first), the buyer paid, verification 404'd, and they got
+// a 502. A URL string is not proof the endpoint behind it works; only CDP or a
+// deliberate operator opt-in is. Self-heals the moment either is set. Solana
// (self-hosted facilitator) is unaffected and stays the always-on settle path.
export function baseSettleable() {
if (env.CDP_API_KEY_ID && env.CDP_API_KEY_SECRET) return true;
- return Boolean(process.env.X402_FACILITATOR_URL_BASE || process.env.X402_FACILITATOR_URL);
+ return env.X402_ADVERTISE_BASE === true;
+}
+
+// Shared exact-scheme requirements builder for the hand-rolled x402 endpoints that
+// call send402()/verifyPayment() directly instead of going through paidEndpoint().
+// Emits the platform-standard accept set for a USDC price:
+//
+// 1. Solana first — the always-on, self-hosted settle rail (first-accept clients
+// and wallet modals settle here).
+// 2. Base second, but ONLY when baseSettleable() (CDP creds or explicit opt-in)
+// AND the Base pay-to/asset are configured. A dead or unconfigured Base
+// facilitator is never advertised as a rail that 402s the buyer and then 502s
+// at /verify. With CDP set, permit2VariantOf appends the gasless Permit2
+// sibling right after the Base accept.
+//
+// Replaces five byte-for-byte copies of this logic (model-check, mint-to-mesh,
+// vanity, vanity-verifiable, revenue-vision) and matches the Solana-first ordering
+// the discovery catalog (wk.js) already advertises, so live 402 and catalog agree.
+export function buildExactRequirements(resourceUrl, amount = env.X402_MAX_AMOUNT_REQUIRED) {
+ const amt = String(amount);
+ const out = [];
+ if (env.X402_PAY_TO_SOLANA && env.X402_ASSET_MINT_SOLANA && env.X402_FEE_PAYER_SOLANA) {
+ out.push({
+ scheme: 'exact',
+ network: NETWORK_SOLANA_MAINNET,
+ amount: amt,
+ payTo: env.X402_PAY_TO_SOLANA,
+ asset: env.X402_ASSET_MINT_SOLANA,
+ maxTimeoutSeconds: 60,
+ resource: resourceUrl,
+ extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },
+ });
+ }
+ if (baseSettleable() && env.X402_PAY_TO_BASE && env.X402_ASSET_ADDRESS_BASE) {
+ const eip3009 = {
+ scheme: 'exact',
+ network: NETWORK_BASE_MAINNET,
+ amount: amt,
+ payTo: env.X402_PAY_TO_BASE,
+ asset: env.X402_ASSET_ADDRESS_BASE,
+ maxTimeoutSeconds: 60,
+ resource: resourceUrl,
+ extra: { name: 'USD Coin', version: '2', decimals: 6 },
+ };
+ out.push(eip3009);
+ const permit2 = permit2VariantOf(eip3009);
+ if (permit2) out.push(permit2);
+ }
+ return out;
}
// Operations the CDP SDK pre-builds headers for; map our internal path to the SDK key.
diff --git a/api/client-errors.js b/api/client-errors.js
index 908486237..d54999b94 100644
--- a/api/client-errors.js
+++ b/api/client-errors.js
@@ -77,6 +77,18 @@ const PROP_ACCESS_TYPEERROR =
export function isNonActionableNoise(event) {
if (event.type !== 'error' && event.type !== 'unhandledrejection') return false;
const msg = event.message || '';
+ // Safari-masked injected-script frames. Safari rewrites the URL of scripts it
+ // deems privacy-sensitive — content-blocker/extension-injected scripts, and some
+ // blob:/eval contexts — to the synthetic `webkit-masked-url://hidden/` scheme.
+ // Our own same-origin modules are served from normal https URLs and never masked,
+ // so an error whose only frame is a masked URL comes from an injected third-party
+ // script (e.g. a cashback/shopping extension's `onResponse` handler throwing
+ // "undefined is not an object (evaluating 'response.cashbackReminder')") — unfixable
+ // from our deploy. Mirrors public/error-reporter.js; catches clients still holding
+ // an older cached reporter that lacks the client-side filter.
+ if (/webkit-masked-url:\/\//.test(event.stack || '') || /webkit-masked-url:\/\//.test(event.source || '')) {
+ return true;
+ }
// Cross-origin "Script error." — the browser strips every detail (stack,
// file, line) from an exception thrown by a script served without CORS
// headers, leaving nothing to act on.
diff --git a/api/cron/db-retention.js b/api/cron/db-retention.js
new file mode 100644
index 000000000..0ced34301
--- /dev/null
+++ b/api/cron/db-retention.js
@@ -0,0 +1,266 @@
+// @ts-check
+// GET /api/cron/db-retention — keep the database under its storage cap.
+//
+// Why this exists
+// ---------------
+// The platform runs on a Neon branch with a hard project-size cap (512 MB on the
+// free tier). Two families of tables grow without bound and, left alone, march the
+// branch straight into that cap — at which point Postgres raises SQLSTATE 53100
+// ("could not extend file because project size limit … exceeded") and every WRITE
+// path starts failing (the production incident this cron closes out):
+//
+// 1. The pump.fun intel firehose. `pump_coin_intel` ingests ~15–20k new mints a
+// day (≈30 MB/day), and its mint-keyed satellites (`pump_coin_wallets`,
+// `coin_smart_money`, `smart_money_scored`, `pump_coin_outcomes`,
+// `oracle_conviction`, `oracle_conviction_history`) grow in lockstep — ~60 MB
+// a day across the family. Nothing pruned it, so it accreted until the branch
+// was full.
+// 2. `avatar_regen_jobs`. Each reconstruct job's `params` carries the multi-MB
+// base64 SOURCE images. The live path drops them once a job leaves
+// reconstruction (reconstruct-finalize.js), but terminal (done/failed) jobs
+// that took another route kept them — 346 rows were holding 43 MB.
+//
+// What it does
+// ------------
+// Runs on a schedule and, idempotently + bounded so a single tick can never run
+// away past the function's maxDuration:
+//
+// A. FIREHOSE RETENTION. Deletes every mint (and its satellite rows) older than
+// the retention window. The window self-tunes: normally PUMP_INTEL_RETENTION_
+// DAYS, but when the branch is over the high-water mark it tightens to
+// PUMP_INTEL_MIN_RETENTION_DAYS so the cap is never actually hit. This is the
+// self-healing valve — it sheds the oldest firehose data under storage
+// pressure and relaxes again once space is reclaimed. The engine's own judge
+// window (smart-money-rollup.js) resolves coins within a day or two of launch,
+// so a multi-day window keeps everything load-bearing; wallet reputation
+// (`wallet_reputation`, wallet-keyed, the durable output) and the win/loss
+// ground truth (`pumpfun_graduations`) are never touched.
+// B. AVATAR JOB HYGIENE. Strips the base64 source images from terminal jobs past
+// a day old, and deletes terminal jobs past 30 days.
+// C. VACUUM. Plain VACUUM on the tables it pruned so the freed pages become
+// reusable and Neon's storage GC can return them.
+//
+// DELETE (not UPDATE) is used for the firehose because DELETE settles xmax in place
+// and does NOT extend a relation file — it therefore succeeds even AT the cap,
+// where an UPDATE (which writes a new tuple version, needing a fresh page) would
+// itself fail with 53100. The image-strip UPDATE is guarded for the same reason.
+//
+// Everything here operates on the platform's OWN runtime launch/intel records at
+// runtime and hardcodes no specific mint — generic retention plumbing, not an
+// endorsement of any coin.
+
+import { error, json, method, wrapCron } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+import { sql, isDbCapacityError } from '../_lib/db.js';
+import { sendOpsAlert } from '../_lib/alerts.js';
+
+// Mint-keyed satellites of pump_coin_intel, deleted before the master so no run
+// orphans a satellite row. Every name here is a fixed constant (never user input),
+// so splicing it into the DELETE text below is safe. Verified to carry a `mint`
+// column. Deliberately EXCLUDES: wallet_reputation / smart_wallet_reputation
+// (wallet-keyed accumulated output — the durable product value), and
+// pumpfun_graduations (small, slow-growing win/loss ground truth the judge reads).
+const FIREHOSE_SATELLITES = [
+ 'pump_coin_wallets',
+ 'coin_smart_money',
+ 'smart_money_scored',
+ 'pump_coin_outcomes',
+ 'oracle_conviction',
+ 'oracle_conviction_history',
+];
+
+// Bounds so a single tick stays well under the function's maxDuration. The cron
+// re-runs on its schedule, so a large backlog (the first prune once data crosses
+// the window, or a pressure-valve catch-up) is chewed through over several ticks.
+const MINT_BATCH = 2000; // mints per cascade batch
+const MAX_MINTS_PER_RUN = 40_000; // ceiling per tick across all batches
+const REGEN_STRIP_BATCH = 200;
+const REGEN_DELETE_BATCH = 500;
+const REGEN_MAX_ITERS = 40;
+
+function clampInt(raw, min, max, dflt) {
+ const n = Number.parseInt(String(raw ?? ''), 10);
+ if (!Number.isFinite(n)) return dflt;
+ return Math.min(max, Math.max(min, n));
+}
+
+function requireCron(req, res) {
+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;
+ if (!secret) {
+ error(res, 503, 'not_configured', 'CRON_SECRET unset');
+ return false;
+ }
+ const auth = req.headers['authorization'] || '';
+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';
+ if (!constantTimeEquals(presented, secret)) {
+ error(res, 401, 'unauthorized', 'invalid cron secret');
+ return false;
+ }
+ return true;
+}
+
+async function dbSizeMb() {
+ const [{ mb }] = await sql`SELECT (pg_database_size(current_database()) / 1048576.0)::int AS mb`;
+ return Number(mb) || 0;
+}
+
+async function tableExists(name) {
+ const [{ reg }] = await sql`SELECT to_regclass(${'public.' + name}) AS reg`;
+ return reg != null;
+}
+
+// ── A. Firehose retention (cascade prune older than cutoffDays) ───────────────
+async function pruneFirehose(cutoffDays) {
+ if (!(await tableExists('pump_coin_intel'))) return { mints: 0, perTable: {} };
+
+ // Resolve satellite existence once (a fresh deploy may not have every table).
+ const liveSatellites = [];
+ for (const t of FIREHOSE_SATELLITES) {
+ if (await tableExists(t)) liveSatellites.push(t);
+ }
+
+ const perTable = {};
+ let totalMints = 0;
+ const maxBatches = Math.ceil(MAX_MINTS_PER_RUN / MINT_BATCH);
+ for (let i = 0; i < maxBatches; i++) {
+ const olds = await sql`
+ SELECT mint FROM pump_coin_intel
+ WHERE first_seen_at < now() - ${cutoffDays} * interval '1 day'
+ LIMIT ${MINT_BATCH}
+ `;
+ if (!olds.length) break;
+ const mints = olds.map((r) => r.mint);
+
+ for (const t of liveSatellites) {
+ // t is a fixed constant from FIREHOSE_SATELLITES — safe to splice; the
+ // mint list is bound as $1. DELETE settles xmax in place (no file
+ // extension), so it works even at the cap.
+ const del = await sql(`DELETE FROM ${t} WHERE mint = ANY($1) RETURNING mint`, [mints]);
+ perTable[t] = (perTable[t] || 0) + del.length;
+ }
+ const delIntel = await sql`DELETE FROM pump_coin_intel WHERE mint = ANY(${mints}) RETURNING mint`;
+ perTable['pump_coin_intel'] = (perTable['pump_coin_intel'] || 0) + delIntel.length;
+
+ totalMints += mints.length;
+ if (olds.length < MINT_BATCH) break;
+ }
+ return { mints: totalMints, perTable };
+}
+
+// ── B. avatar_regen_jobs hygiene ──────────────────────────────────────────────
+async function pruneRegenJobs() {
+ if (!(await tableExists('avatar_regen_jobs'))) return { stripped: 0, deleted: 0 };
+
+ // Delete terminal jobs past 30 days first (DELETE frees space without
+ // extending a file, so it is safe even under storage pressure).
+ let deleted = 0;
+ for (let i = 0; i < REGEN_MAX_ITERS; i++) {
+ const del = await sql`
+ DELETE FROM avatar_regen_jobs
+ WHERE job_id IN (
+ SELECT job_id FROM avatar_regen_jobs
+ WHERE status IN ('done', 'failed') AND created_at < now() - interval '30 days'
+ LIMIT ${REGEN_DELETE_BATCH}
+ ) RETURNING job_id
+ `;
+ deleted += del.length;
+ if (del.length < REGEN_DELETE_BATCH) break;
+ }
+
+ // Strip the multi-MB base64 source images from terminal jobs older than a day —
+ // never read for a finished job. This is an UPDATE (rewrites the row), so it can
+ // need to extend a file; if the branch is at the cap the DELETE prune above will
+ // have freed space, but guard anyway so a capacity blip degrades to "skip the
+ // strip this tick" rather than failing the whole cron.
+ let stripped = 0;
+ try {
+ for (let i = 0; i < REGEN_MAX_ITERS; i++) {
+ const upd = await sql`
+ UPDATE avatar_regen_jobs
+ SET params = (params - 'images') - 'image', updated_at = now()
+ WHERE job_id IN (
+ SELECT job_id FROM avatar_regen_jobs
+ WHERE status IN ('done', 'failed')
+ AND created_at < now() - interval '1 day'
+ AND (params ? 'images' OR params ? 'image')
+ LIMIT ${REGEN_STRIP_BATCH}
+ ) RETURNING job_id
+ `;
+ stripped += upd.length;
+ if (upd.length < REGEN_STRIP_BATCH) break;
+ }
+ } catch (err) {
+ if (!isDbCapacityError(err)) throw err;
+ }
+ return { stripped, deleted };
+}
+
+// ── C. Best-effort VACUUM of the tables we pruned ─────────────────────────────
+async function vacuumTables(names) {
+ for (const t of names) {
+ try {
+ // Plain VACUUM (never FULL): FULL rewrites the whole table into a fresh
+ // file, needing free space ≈ the table's live size — the one thing we lack
+ // near the cap. Plain VACUUM marks dead tuples reusable and lets Neon's
+ // storage GC return the space. Single-statement over the HTTP driver runs
+ // in autocommit, so VACUUM's no-transaction rule is satisfied.
+ await sql(`VACUUM ${t}`);
+ } catch {
+ /* best-effort — reclaim happens on the next autovacuum regardless */
+ }
+ }
+}
+
+export default wrapCron(async (req, res) => {
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (!requireCron(req, res)) return;
+
+ const started = Date.now();
+ const retentionDays = clampInt(process.env.PUMP_INTEL_RETENTION_DAYS, 2, 365, 14);
+ const minDays = clampInt(process.env.PUMP_INTEL_MIN_RETENTION_DAYS, 1, retentionDays, 3);
+ const highWaterMb = clampInt(process.env.DB_RETENTION_HIGH_WATER_MB, 128, 100_000, 470);
+
+ const sizeBeforeMb = await dbSizeMb();
+ const underPressure = sizeBeforeMb >= highWaterMb;
+ // Self-healing valve: tighten the window to the floor while the branch is over
+ // the high-water mark, so the cap is never actually reached; relax to the full
+ // window once GC has returned the freed space and size drops back under it.
+ const cutoffDays = underPressure ? minDays : retentionDays;
+
+ const firehose = await pruneFirehose(cutoffDays);
+ const regen = await pruneRegenJobs();
+
+ // VACUUM only tables we actually deleted from this tick.
+ const touched = Object.keys(firehose.perTable).filter((t) => firehose.perTable[t] > 0);
+ if (regen.deleted > 0 || regen.stripped > 0) touched.push('avatar_regen_jobs');
+ await vacuumTables(touched);
+
+ const sizeAfterMb = await dbSizeMb();
+
+ // One deduped signal when the valve engages so ops knows storage is tight and a
+ // Neon plan bump (for a longer history window) is worth considering. Neon's GC
+ // is not instant, so sizeAfter may still read high right after a prune — that's
+ // expected; the space returns within the branch's history-retention window.
+ if (underPressure) {
+ sendOpsAlert(
+ 'db retention pressure valve engaged',
+ `db ${sizeBeforeMb}MB ≥ high-water ${highWaterMb}MB — tightened firehose retention to ${minDays}d; pruned ${firehose.mints} mints. Raise the Neon storage plan (or DB_RETENTION_HIGH_WATER_MB / PUMP_INTEL_RETENTION_DAYS) for a longer window.`,
+ { signature: 'db:retention-pressure' },
+ );
+ }
+
+ return json(res, 200, {
+ ok: true,
+ size_before_mb: sizeBeforeMb,
+ size_after_mb: sizeAfterMb,
+ high_water_mb: highWaterMb,
+ under_pressure: underPressure,
+ retention_days: retentionDays,
+ cutoff_days: cutoffDays,
+ firehose,
+ regen,
+ vacuumed: touched,
+ took_ms: Date.now() - started,
+ });
+});
diff --git a/api/insights/revenue-vision.js b/api/insights/revenue-vision.js
index 2c40b6cfd..6de062f48 100644
--- a/api/insights/revenue-vision.js
+++ b/api/insights/revenue-vision.js
@@ -14,13 +14,11 @@
import { wrap, cors, error } from '../_lib/http.js';
import {
- NETWORK_BASE_MAINNET,
- NETWORK_SOLANA_MAINNET,
send402,
verifyPayment,
settlePayment,
encodePaymentResponseHeader,
- permit2VariantOf,
+ buildExactRequirements,
resolveResourceUrl,
buildBazaarSchema,
} from '../_lib/x402-spec.js';
@@ -129,32 +127,8 @@ const ROUTE_BAZAAR = {
};
function buildRequirements(resourceUrl) {
- const eip3009 = {
- scheme: 'exact',
- network: NETWORK_BASE_MAINNET,
- amount: env.X402_MAX_AMOUNT_REQUIRED,
- payTo: env.X402_PAY_TO_BASE,
- asset: env.X402_ASSET_ADDRESS_BASE,
- maxTimeoutSeconds: 60,
- resource: resourceUrl,
- extra: { name: 'USD Coin', version: '2', decimals: 6 },
- };
- const out = [eip3009];
- const permit2 = permit2VariantOf(eip3009);
- if (permit2) out.push(permit2);
- if (env.X402_PAY_TO_SOLANA) {
- out.push({
- scheme: 'exact',
- network: NETWORK_SOLANA_MAINNET,
- amount: env.X402_MAX_AMOUNT_REQUIRED,
- payTo: env.X402_PAY_TO_SOLANA,
- asset: env.X402_ASSET_MINT_SOLANA,
- maxTimeoutSeconds: 60,
- resource: resourceUrl,
- extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },
- });
- }
- return out;
+ // Solana-first accepts, Base gated on baseSettleable() — see buildExactRequirements.
+ return buildExactRequirements(resourceUrl);
}
const SYSTEM_PROMPT =
diff --git a/api/wk.js b/api/wk.js
index bae0f6bbe..d5c86022f 100644
--- a/api/wk.js
+++ b/api/wk.js
@@ -12,6 +12,7 @@ import {
declareEip2612GasSponsoringExtension,
declareErc20ApprovalGasSponsoringExtension,
permit2VariantOf,
+ baseSettleable,
NETWORK_BASE_MAINNET,
NETWORK_SOLANA_MAINNET,
} from './_lib/x402-spec.js';
@@ -311,7 +312,12 @@ function acceptsForPrice(amountAtomics, resourceUrl) {
extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },
});
}
- if (env.X402_PAY_TO_BASE) {
+ // Base only when a WORKING facilitator will settle it (CDP creds or the
+ // X402_ADVERTISE_BASE opt-in). A bare facilitator URL is not enough — the prod
+ // host was decommissioned and 404s /verify, so an unsettleable Base accept would
+ // drift from the live 402 (which now drops Base) and hand buyers a catalog rail
+ // that 502s at verify. See baseSettleable().
+ if (env.X402_PAY_TO_BASE && baseSettleable()) {
pushAcceptWithPermit2Sibling(out, {
scheme: 'exact',
network: NETWORK_BASE_MAINNET,
@@ -418,7 +424,7 @@ async function buildAgentServiceItems(origin) {
const url = serviceResourceUrl(row.slug);
const price = RAW_AMOUNT_TO_USDC(row.price_atomics);
const accepts = [];
- if (row.network === 'base' && row.payout_address && env.X402_ASSET_ADDRESS_BASE) {
+ if (row.network === 'base' && row.payout_address && env.X402_ASSET_ADDRESS_BASE && baseSettleable()) {
pushAcceptWithPermit2Sibling(accepts, {
scheme: 'exact',
network: NETWORK_BASE_MAINNET,
@@ -1273,7 +1279,9 @@ async function handleX402Discovery(req, res) {
extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },
});
}
- if (env.X402_PAY_TO_BASE) {
+ // Base only when settleable (CDP creds or the X402_ADVERTISE_BASE opt-in) —
+ // else the catalog would advertise a rail the live 402 now drops. See baseSettleable().
+ if (env.X402_PAY_TO_BASE && baseSettleable()) {
pushAcceptWithPermit2Sibling(out, {
scheme: 'exact',
network: NETWORK_BASE_MAINNET,
@@ -1317,7 +1325,11 @@ async function handleX402Discovery(req, res) {
extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },
});
}
- if (env.X402_PAY_TO_BASE) {
+ // Base + Arbitrum are CDP-settled EVM rails; advertise them only when a
+ // working facilitator is configured (CDP creds or the X402_ADVERTISE_BASE
+ // opt-in). Without one the live 402 drops Base, so an ungated catalog entry
+ // would drift and 502.
+ if (env.X402_PAY_TO_BASE && baseSettleable()) {
pushAcceptWithPermit2Sibling(out, {
scheme: 'exact',
network: NETWORK_BASE_MAINNET,
@@ -1332,7 +1344,7 @@ async function handleX402Discovery(req, res) {
extra: { name: 'USDC', version: '2', decimals: 6 },
});
}
- if (env.X402_PAY_TO_BASE && ARB_USDC) {
+ if (env.X402_PAY_TO_BASE && ARB_USDC && baseSettleable()) {
pushAcceptWithPermit2Sibling(out, {
scheme: 'exact',
network: 'eip155:42161',
diff --git a/api/x402/mint-to-mesh.js b/api/x402/mint-to-mesh.js
index f8362531a..fc4a185a2 100644
--- a/api/x402/mint-to-mesh.js
+++ b/api/x402/mint-to-mesh.js
@@ -19,13 +19,11 @@
import { wrap, cors, error } from '../_lib/http.js';
import {
- NETWORK_BASE_MAINNET,
- NETWORK_SOLANA_MAINNET,
send402,
verifyPayment,
settlePayment,
encodePaymentResponseHeader,
- permit2VariantOf,
+ buildExactRequirements,
resolveResourceUrl,
buildBazaarSchema,
} from '../_lib/x402-spec.js';
@@ -159,32 +157,9 @@ const ROUTE_BAZAAR = {
};
function buildRequirements(resourceUrl) {
- const eip3009 = {
- scheme: 'exact',
- network: NETWORK_BASE_MAINNET,
- amount: env.X402_MAX_AMOUNT_REQUIRED,
- payTo: env.X402_PAY_TO_BASE,
- asset: env.X402_ASSET_ADDRESS_BASE,
- maxTimeoutSeconds: 60,
- resource: resourceUrl,
- extra: { name: 'USD Coin', version: '2', decimals: 6 },
- };
- const out = [eip3009];
- const permit2 = permit2VariantOf(eip3009);
- if (permit2) out.push(permit2);
- if (env.X402_PAY_TO_SOLANA) {
- out.push({
- scheme: 'exact',
- network: NETWORK_SOLANA_MAINNET,
- amount: env.X402_MAX_AMOUNT_REQUIRED,
- payTo: env.X402_PAY_TO_SOLANA,
- asset: env.X402_ASSET_MINT_SOLANA,
- maxTimeoutSeconds: 60,
- resource: resourceUrl,
- extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },
- });
- }
- return out;
+ // Solana-first accepts, Base gated on baseSettleable() (CDP or opt-in) plus its
+ // gasless Permit2 sibling under CDP — see buildExactRequirements.
+ return buildExactRequirements(resourceUrl);
}
// Loose Solana base58 sanity check. Real validation happens in solanaPubkey()
diff --git a/api/x402/model-check.js b/api/x402/model-check.js
index a803043c3..0eb47508a 100644
--- a/api/x402/model-check.js
+++ b/api/x402/model-check.js
@@ -16,13 +16,11 @@
import { wrap, cors, error } from '../_lib/http.js';
import {
- NETWORK_BASE_MAINNET,
- NETWORK_SOLANA_MAINNET,
send402,
verifyPayment,
settlePayment,
encodePaymentResponseHeader,
- permit2VariantOf,
+ buildExactRequirements,
resolveResourceUrl,
buildBazaarSchema,
} from '../_lib/x402-spec.js';
@@ -176,36 +174,9 @@ const ROUTE_BAZAAR = {
};
function buildRequirements(resourceUrl) {
- const eip3009 = {
- scheme: 'exact',
- network: NETWORK_BASE_MAINNET,
- amount: env.X402_MAX_AMOUNT_REQUIRED,
- payTo: env.X402_PAY_TO_BASE,
- asset: env.X402_ASSET_ADDRESS_BASE,
- maxTimeoutSeconds: 60,
- resource: resourceUrl,
- extra: { name: 'USD Coin', version: '2', decimals: 6 },
- };
- const out = [eip3009];
- // permit2VariantOf returns null without CDP credentials (PayAI doesn't
- // settle Permit2). When CDP is configured, append a sibling so SDK clients
- // can take the gasless EIP-2612 path; build402Body will auto-declare the
- // matching gas-sponsoring extensions in response.extensions.
- const permit2 = permit2VariantOf(eip3009);
- if (permit2) out.push(permit2);
- if (env.X402_PAY_TO_SOLANA) {
- out.push({
- scheme: 'exact',
- network: NETWORK_SOLANA_MAINNET,
- amount: env.X402_MAX_AMOUNT_REQUIRED,
- payTo: env.X402_PAY_TO_SOLANA,
- asset: env.X402_ASSET_MINT_SOLANA,
- maxTimeoutSeconds: 60,
- resource: resourceUrl,
- extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },
- });
- }
- return out;
+ // Solana-first accepts, Base gated on baseSettleable() (CDP or opt-in) plus its
+ // gasless Permit2 sibling under CDP — see buildExactRequirements.
+ return buildExactRequirements(resourceUrl);
}
async function fetchAndInspect(targetUrl) {
diff --git a/api/x402/vanity-verifiable.js b/api/x402/vanity-verifiable.js
index 9cd6bde55..db02e7267 100644
--- a/api/x402/vanity-verifiable.js
+++ b/api/x402/vanity-verifiable.js
@@ -31,13 +31,11 @@
import { wrap, cors, error, rateLimited } from '../_lib/http.js';
import {
- NETWORK_BASE_MAINNET,
- NETWORK_SOLANA_MAINNET,
send402,
verifyPayment,
settlePayment,
encodePaymentResponseHeader,
- permit2VariantOf,
+ buildExactRequirements,
resolveResourceUrl,
buildBazaarSchema,
} from '../_lib/x402-spec.js';
@@ -231,33 +229,9 @@ const ROUTE_BAZAAR = {
};
function buildRequirements(resourceUrl, priceAtomics) {
- const amount = String(priceAtomics);
- const eip3009 = {
- scheme: 'exact',
- network: NETWORK_BASE_MAINNET,
- amount,
- payTo: env.X402_PAY_TO_BASE,
- asset: env.X402_ASSET_ADDRESS_BASE,
- maxTimeoutSeconds: 60,
- resource: resourceUrl,
- extra: { name: 'USD Coin', version: '2', decimals: 6 },
- };
- const out = [eip3009];
- const permit2 = permit2VariantOf(eip3009);
- if (permit2) out.push(permit2);
- if (env.X402_PAY_TO_SOLANA) {
- out.push({
- scheme: 'exact',
- network: NETWORK_SOLANA_MAINNET,
- amount,
- payTo: env.X402_PAY_TO_SOLANA,
- asset: env.X402_ASSET_MINT_SOLANA,
- maxTimeoutSeconds: 60,
- resource: resourceUrl,
- extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },
- });
- }
- return out;
+ // Solana-first accepts, Base gated on baseSettleable() (CDP or opt-in) plus its
+ // gasless Permit2 sibling under CDP — see buildExactRequirements.
+ return buildExactRequirements(resourceUrl, priceAtomics);
}
// Parse a client-supplied seed (hex or Base58) into bytes, or generate a fresh
diff --git a/api/x402/vanity.js b/api/x402/vanity.js
index 23c77573c..420994b18 100644
--- a/api/x402/vanity.js
+++ b/api/x402/vanity.js
@@ -24,13 +24,11 @@
import { wrap, cors, error, rateLimited } from '../_lib/http.js';
import {
- NETWORK_BASE_MAINNET,
- NETWORK_SOLANA_MAINNET,
send402,
verifyPayment,
settlePayment,
encodePaymentResponseHeader,
- permit2VariantOf,
+ buildExactRequirements,
resolveResourceUrl,
buildBazaarSchema,
} from '../_lib/x402-spec.js';
@@ -292,33 +290,9 @@ const ROUTE_BAZAAR = {
};
function buildRequirements(resourceUrl, priceAtomics) {
- const amount = String(priceAtomics);
- const eip3009 = {
- scheme: 'exact',
- network: NETWORK_BASE_MAINNET,
- amount,
- payTo: env.X402_PAY_TO_BASE,
- asset: env.X402_ASSET_ADDRESS_BASE,
- maxTimeoutSeconds: 60,
- resource: resourceUrl,
- extra: { name: 'USD Coin', version: '2', decimals: 6 },
- };
- const out = [eip3009];
- const permit2 = permit2VariantOf(eip3009);
- if (permit2) out.push(permit2);
- if (env.X402_PAY_TO_SOLANA) {
- out.push({
- scheme: 'exact',
- network: NETWORK_SOLANA_MAINNET,
- amount,
- payTo: env.X402_PAY_TO_SOLANA,
- asset: env.X402_ASSET_MINT_SOLANA,
- maxTimeoutSeconds: 60,
- resource: resourceUrl,
- extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },
- });
- }
- return out;
+ // Solana-first accepts, Base gated on baseSettleable() (CDP or opt-in) plus its
+ // gasless Permit2 sibling under CDP — see buildExactRequirements.
+ return buildExactRequirements(resourceUrl, priceAtomics);
}
// Parse + validate the requested pattern. Returns { prefix, suffix, ignoreCase,
diff --git a/data/changelog.json b/data/changelog.json
index 1bc5b9906..cc443d1ba 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,34 @@
{
"$comment": "Curated changelog entries for three.ws \u2014 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-07-01",
+ "title": "Pay-per-call APIs now settle reliably — no more dead payment rails",
+ "summary": "Our x402 pay-per-call endpoints advertise which networks they accept before you pay. A secondary settlement network had been advertised even while its external verifier was offline, so a payment on that rail could be built and submitted only to fail at the last step. Endpoints now advertise a network only when it can actually settle — Solana (our in-house facilitator) always leads, and the secondary EVM rail appears only when a working verifier is configured. Buyers settle on the healthy rail instead of hitting a dead one. We also hardened the reputation-scoring job so a single slow wallet read can never stall the whole refresh.",
+ "tags": [
+ "fix",
+ "improvement"
+ ]
+ },
+ {
+ "date": "2026-07-01",
+ "title": "Live data keeps flowing — automatic database housekeeping",
+ "summary": "A handful of behind-the-scenes jobs — the smart-money radar, the coin-intel feeds, and usage metering — had started intermittently failing because the database had grown to its storage ceiling. We reclaimed the space, added a scheduled housekeeping job that trims the high-volume coin-intel history and stale avatar-generation payloads so the database self-manages its size, and made every write path degrade gracefully (a brief 'retry shortly' instead of a hard error) if storage ever runs tight again. The radar, feeds, and metering now keep updating reliably.",
+ "tags": [
+ "fix",
+ "infra"
+ ]
+ },
+ {
+ "date": "2026-07-01",
+ "title": "three.ws 3D Forge is now a one-command Claude Code plugin",
+ "summary": "You can add three.ws 3D generation straight into Claude Code as a one-line plugin. three.ws 3D Forge bundles four skills — a free text→3D draft lane plus the paid avatar, high-fidelity mesh, and auto-rig lanes — and wires the three.ws generation, scene, and avatar servers with no extra setup. Add it with `/plugin marketplace add nirholas/three.ws`, then `/plugin install three-ws-3d@three-ws`; every result hands back a downloadable GLB and a live viewer link. The plugin is now packaged to Anthropic's plugin spec — manifest, license, and changelog — and prepared for submission to the public Claude plugin directory.",
+ "tags": [
+ "feature",
+ "sdk"
+ ],
+ "link": "/forge"
+ },
{
"date": "2026-07-01",
"title": "Agent profile pages read tighter and clearer",
diff --git a/docs/ops/db-retention.md b/docs/ops/db-retention.md
new file mode 100644
index 000000000..29c202a11
--- /dev/null
+++ b/docs/ops/db-retention.md
@@ -0,0 +1,102 @@
+# Database retention — keeping the Neon branch under its storage cap
+
+The platform runs on a Neon Postgres branch with a hard **project-size cap**
+(512 MB on the free tier). When a branch reaches that cap Postgres raises
+SQLSTATE **53100** — `could not extend file because project size limit … exceeded`
+— and every **write** path starts failing (reads still work). In production this
+surfaced as a storm of 500s on `/api/cron/smart-money-rollup` plus caught write
+failures across `coin-intel-observe`, `launcher-tick`, `flush-usage-events`, and
+usage metering.
+
+This doc is the playbook: what fills the branch, what keeps it bounded, and when
+to upgrade.
+
+## What fills the branch
+
+Two families grow without bound:
+
+1. **The coin-intel firehose.** `pump_coin_intel` ingests **~15–20k new mints a
+ day** (≈30 MB/day), and its mint-keyed satellites grow in lockstep —
+ `pump_coin_wallets`, `coin_smart_money`, `smart_money_scored`,
+ `pump_coin_outcomes`, `oracle_conviction`, `oracle_conviction_history`. All
+ told the family adds **~60 MB/day**.
+2. **`avatar_regen_jobs`.** Each reconstruct job's `params` carries the multi-MB
+ base64 **source** images. The live path drops them once a job leaves
+ reconstruction, but terminal jobs that took another route kept them — 346 rows
+ were holding 43 MB.
+
+At ~60 MB/day the firehose alone cannot fit a 14-day window inside 512 MB. That
+is a plan-capacity fact, not a bug: **a longer guaranteed history window requires
+a larger Neon plan.**
+
+## The two mechanisms
+
+### 1. Graceful degradation (always on)
+
+`isDbCapacityError()` (`api/_lib/db.js`) classifies SQLSTATE 53100. Once
+classified, write paths degrade instead of 500-storming:
+
+- **API writes** return a bounded **503 + `Retry-After: 30`** (`wrap` /
+ `serverError` in `api/_lib/http.js`), with a single deduped `db:capacity` ops
+ alert — no per-request Sentry flood.
+- **Crons** skip the tick and return `200 { ok: false, reason: "db_full" }`
+ (`wrapCron`), so a full branch never produces a 5xx alert storm.
+
+### 2. `/api/cron/db-retention` (scheduled every 15 min)
+
+Bounded + idempotent. Each tick:
+
+- **Firehose retention** — deletes every mint older than the window (and cascades
+ its satellite rows) via `DELETE`, which settles `xmax` in place and therefore
+ works **even at the cap**, where an `UPDATE` would itself fail with 53100.
+ `wallet_reputation` (the durable, wallet-keyed output) and `pumpfun_graduations`
+ (win/loss ground truth) are **never** touched.
+- **Avatar job hygiene** — deletes terminal jobs past 30 days and strips base64
+ source images from terminal jobs past a day.
+- **VACUUM** (plain, never `FULL`) of the pruned tables so freed pages become
+ reusable and Neon's storage GC can return the space.
+
+**The self-healing valve.** The retention window self-tunes: normally
+`PUMP_INTEL_RETENTION_DAYS`, but whenever the branch is at/above
+`DB_RETENTION_HIGH_WATER_MB` it tightens to `PUMP_INTEL_MIN_RETENTION_DAYS`, so
+the hard cap is **never actually reached**. It relaxes again once GC returns the
+freed space and the branch drops back under the mark. When the valve engages it
+fires one deduped `db:retention-pressure` alert.
+
+## Tunables
+
+| Env | Default | Meaning |
+| --- | --- | --- |
+| `PUMP_INTEL_RETENTION_DAYS` | `14` | Normal firehose window (days). Clamped `[2, 365]`. Raise after a Neon plan upgrade. |
+| `PUMP_INTEL_MIN_RETENTION_DAYS` | `3` | Floor the valve tightens to under pressure. Clamped `[1, retention]`. |
+| `DB_RETENTION_HIGH_WATER_MB` | `470` | Engage the valve at/above this size. Clamped `[128, 100000]`. |
+
+## Upgrade trigger
+
+The valve keeps the branch **healthy** on the free tier, but at the cost of a
+**shorter effective history window** (roughly `PUMP_INTEL_MIN_RETENTION_DAYS`)
+whenever storage is tight. If `db:retention-pressure` alerts are frequent and you
+want a longer guaranteed window (e.g. the full 14-day judge horizon), **upgrade
+the Neon plan** for more storage, then raise `DB_RETENTION_HIGH_WATER_MB` and
+`PUMP_INTEL_RETENTION_DAYS` to match.
+
+## Manual reclaim (one-off, at the cap)
+
+`DELETE` frees space without extending a file, so it works at the cap; `UPDATE`
+does not. To reclaim immediately, delete the oldest rows in batches, then
+`VACUUM` (or `VACUUM FULL <table>` only when that table's **live** data is small
+enough that the rewrite fits the remaining headroom). Measure with:
+
+```sql
+SELECT pg_size_pretty(pg_database_size(current_database()));
+SELECT relname, pg_size_pretty(pg_total_relation_size(c.oid))
+FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
+WHERE c.relkind = 'r' AND n.nspname = 'public'
+ORDER BY pg_total_relation_size(c.oid) DESC LIMIT 20;
+```
+
+## See also
+
+- `api/cron/db-retention.js` — the cron
+- `api/_lib/db.js` — `isDbCapacityError` / `isDbUnavailableError`
+- [docs/ops/redis.md](redis.md) — the Upstash cache/limiter quota playbook
diff --git a/docs/x402-endpoints.md b/docs/x402-endpoints.md
index 6e81c164b..779b2e612 100644
--- a/docs/x402-endpoints.md
+++ b/docs/x402-endpoints.md
@@ -33,16 +33,28 @@ should tune them to real unit economics.
## Networks and settlement
Endpoints advertise the networks they accept in the 402 challenge. The platform
-settles **USDC on Solana** (primary) and **USDC on Base** (EVM), via the
-configured facilitators. The relevant config (see [Configuration](configuration.md)):
+settles **USDC on Solana** (primary, always-on via the self-hosted facilitator)
+and, when configured, **USDC on Base** (EVM). The relevant config (see
+[Configuration](configuration.md)):
| Key | Meaning |
| ---------------------------------------------------- | ------------------------------------ |
| `X402_PAY_TO_SOLANA` / `X402_PAY_TO_BASE` | Receiving address per network. |
| `X402_ASSET_MINT_SOLANA` / `X402_ASSET_ADDRESS_BASE` | USDC mint / contract. |
| `X402_FACILITATOR_URL_SOLANA` / `_BASE` | Facilitator that verifies + settles. |
+| `X402_ADVERTISE_BASE` | Opt-in to advertise Base without CDP (see below). |
| `X402_RECEIPT_SIGNING_KEY`, `OFFER_RECEIPT_*` | Signed receipt issuance. |
+**Base is gated on a settleable facilitator.** Solana always leads the 402
+challenge. Base is advertised only when it can actually settle — either CDP
+credentials are set (`CDP_API_KEY_ID` + `CDP_API_KEY_SECRET`, routing Base to
+Coinbase) **or** the operator opts in with `X402_ADVERTISE_BASE=true`. A bare
+`X402_FACILITATOR_URL_BASE` being set is deliberately *not* enough: a
+decommissioned facilitator answers `/verify` with `404 Application not found`, so
+an ungated Base accept would let a buyer pay and then fail settlement with a 502.
+The gate (`baseSettleable()` in `x402-spec.js`) keeps such a rail out of both the
+live 402 and the discovery catalog until it is provably settleable.
+
The shared handler in `x402-paid-endpoint.js` builds the challenge
(`buildRequirements()`), verifies the submitted payment, settles it, runs the
endpoint logic, and issues a signed receipt.
diff --git a/marketplace/plugins/three-ws-3d/.claude-plugin/plugin.json b/marketplace/plugins/three-ws-3d/.claude-plugin/plugin.json
index bafec913b..22a04b8b2 100644
--- a/marketplace/plugins/three-ws-3d/.claude-plugin/plugin.json
+++ b/marketplace/plugins/three-ws-3d/.claude-plugin/plugin.json
@@ -1,9 +1,11 @@
{
"name": "three-ws-3d",
+ "displayName": "three.ws 3D Forge",
"description": "three.ws 3D Forge — generate textured 3D models and rigged, animation-ready avatars from text or images. Free text→3D (NVIDIA NIM / TRELLIS) plus the paid mesh, avatar, and auto-rig lanes, scene composition, and live avatar embeds, all wired over the three.ws MCP servers.",
"version": "1.0.0",
"author": {
- "name": "nirholas"
+ "name": "nirholas",
+ "url": "https://three.ws"
},
"homepage": "https://three.ws/forge",
"license": "Apache-2.0",
diff --git a/marketplace/plugins/three-ws-3d/CHANGELOG.md b/marketplace/plugins/three-ws-3d/CHANGELOG.md
new file mode 100644
index 000000000..2a8d60e26
--- /dev/null
+++ b/marketplace/plugins/three-ws-3d/CHANGELOG.md
@@ -0,0 +1,21 @@
+# Changelog — three.ws 3D Forge (Claude Code plugin)
+
+All notable changes to this plugin are documented here. Versions follow [semver](https://semver.org).
+
+## 1.0.0 — 2026-07-01
+
+Initial release. Generate textured 3D models and rigged, animation-ready avatars
+from text or images, directly inside Claude Code.
+
+### Skills
+- `three-ws-3d:forge-3d` — free text → 3D GLB (NVIDIA NIM / TRELLIS); no key or wallet.
+- `three-ws-3d:text-to-avatar` — text or 1–4 reference images → textured 3D avatar (paid, $0.15 USDC via x402).
+- `three-ws-3d:mesh-forge` — directed text / single-image / multi-view → high-fidelity mesh (paid, $0.25 USDC via x402).
+- `three-ws-3d:auto-rig` — add a humanoid skeleton + skin weights to an existing GLB, or go prompt → rigged avatar in one call (paid, $0.20 / $0.45 USDC via x402).
+
+### Bundled MCP servers
+- `@three-ws/mcp-server` — the full generation surface: `forge_free`, `text_to_avatar`, `mesh_forge`, `rig_mesh`, `forge_avatar`. Paid tools settle over x402; set `MCP_SVM_PAYMENT_ADDRESS` to enable them.
+- `@three-ws/scene-mcp` — `compose_scene` / `get_scene` / `list_scenes` (free, no key).
+- `@three-ws/avatar-mcp` — live avatar render, paste-anywhere embed iframe, and avatar metadata (free, no key).
+
+Every result returns a downloadable `glbUrl` plus a `https://three.ws/viewer?src=…` preview link.
diff --git a/marketplace/plugins/three-ws-3d/LICENSE b/marketplace/plugins/three-ws-3d/LICENSE
new file mode 100644
index 000000000..8e2251ab4
--- /dev/null
+++ b/marketplace/plugins/three-ws-3d/LICENSE
@@ -0,0 +1,180 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship made available under
+ the License, as indicated by a copyright notice that is included in
+ or attached to the work (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other transformations
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
+ in the Work by the copyright owner or by an individual or Legal Entity
+ authorized to submit on behalf of the copyright owner. For the purposes
+ of this definition, "submitted" means any form of electronic, verbal,
+ or written communication sent to the Licensor or its representatives,
+ including but not limited to communication on electronic mailing lists,
+ source code control systems, and issue tracking systems that are managed
+ by, or on behalf of, the Licensor for the purpose of discussing and
+ improving the Work, but excluding communication that is conspicuously
+ marked or designated in writing by the copyright owner as "Not a
+ Contribution."
+
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
+ whom a Contribution has been received by the Licensor and included
+ within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by the combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a cross-claim
+ or counterclaim in a lawsuit) alleging that the Work or any
+ Contribution embodied within the Work constitutes direct or contributory
+ patent infringement, then any patent licenses granted to You under
+ this License for that Work shall terminate as of the date such
+ litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or Derivative
+ Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, You must include a readable copy of the
+ attribution notices contained within such NOTICE file, in
+ at least one of the following places: within a NOTICE text
+ file distributed as part of the Derivative Works; within
+ the Source form or documentation, if provided along with the
+ Derivative Works; or, within a display generated by the
+ Derivative Works, if and wherever such third-party notices
+ normally appear. The contents of the NOTICE file are for
+ informational purposes only and do not modify the License.
+ You may add Your own attribution notices within Derivative
+ Works that You distribute, alongside or in addition to the
+ NOTICE text from the Work, provided that such additional
+ attribution notices cannot be construed as modifying the License.
+
+ You may add Your own license statement for Your modifications and
+ may provide additional grant of rights to use, copy, modify, merge,
+ publish, distribute, sublicense, and/or sell copies of the
+ Derivative Works, and to permit persons to whom the Derivative Works
+ are furnished to do so.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or reproducing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or exemplary damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or all other
+ commercial damages or losses), even if such Contributor has been
+ advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may offer only
+ conditions consistent with this License.
+
+ END OF TERMS AND CONDITIONS
+
+ Copyright 2026 nirholas
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/marketplace/plugins/three-ws-3d/SUBMISSION.md b/marketplace/plugins/three-ws-3d/SUBMISSION.md
new file mode 100644
index 000000000..e3c78b6a2
--- /dev/null
+++ b/marketplace/plugins/three-ws-3d/SUBMISSION.md
@@ -0,0 +1,72 @@
+# Submitting three.ws 3D Forge to the Claude plugin marketplace
+
+This plugin is packaged for submission to Anthropic's **community** plugin marketplace
+(`anthropics/claude-plugins-community`). Anthropic runs automated validation + safety
+screening, pins the approved commit to a specific SHA in the community catalog, and the
+plugin becomes installable to everyone as `/plugin install three-ws-3d@claude-community`
+(the public catalog syncs nightly, so expect ~24h between approval and appearance).
+
+> The official, Anthropic-curated marketplace (`claude-plugins-official`) has **no public
+> submission** — Anthropic reaches out directly to feature a plugin. The community route
+> below is the one you submit to.
+
+## 1. Pre-flight — already done in this repo
+
+- `.claude-plugin/plugin.json` is spec-valid: kebab-case `name`, `displayName`, Apache-2.0 `license`, `mcpServers` block.
+- Four skills under `skills/` (`forge-3d`, `text-to-avatar`, `mesh-forge`, `auto-rig`), each with valid YAML frontmatter.
+- `README.md`, `CHANGELOG.md`, and `LICENSE` are present in the plugin root.
+- All three bundled MCP servers are published to npm and resolve via `npx`: `@three-ws/mcp-server`, `@three-ws/scene-mcp`, `@three-ws/avatar-mcp`.
+
+## 2. Validate locally (recommended)
+
+Requires the Claude Code CLI:
+
+```bash
+claude plugin validate ./marketplace/plugins/three-ws-3d --strict
+```
+
+Fix anything it reports before submitting. The validator checks `plugin.json` JSON,
+skill/agent/command frontmatter, required fields, and path rules.
+
+## 3. Test the install end-to-end
+
+```bash
+# From the repo root, add this marketplace by local path and install:
+/plugin marketplace add ./
+/plugin install three-ws-3d@three-ws
+/reload-plugins
+```
+
+Confirm the `three-ws-3d:` skills appear (`/help` or `/plugin list`) and the bundled MCP
+tools list. A `forge-3d` call should return a `glbUrl` + viewer link.
+
+## 4. Submit to the community marketplace
+
+Make sure the plugin is pushed to the public repo (`github.com/nirholas/three.ws`), then
+submit via **one** of:
+
+- **Console** (individual authors): <https://platform.claude.com/plugins/submit>
+- **claude.ai admin** (Team / Enterprise with directory access): <https://claude.ai/admin-settings/directory/submissions/plugins/new>
+
+Provide:
+
+| Field | Value |
+| --- | --- |
+| Marketplace / source repo | `https://github.com/nirholas/three.ws` |
+| Plugin name | `three-ws-3d` |
+| Plugin path in repo | `marketplace/plugins/three-ws-3d` |
+
+## 5. After approval
+
+Anthropic pins the approved commit SHA; their CI bumps it when you push new commits.
+Users then install with:
+
+```bash
+/plugin marketplace add anthropics/claude-plugins-community
+/plugin install three-ws-3d@claude-community
+```
+
+## Updating later
+
+Bump `version` in `.claude-plugin/plugin.json` (and add a `CHANGELOG.md` entry) so
+existing installs receive the update.
diff --git a/public/changelog.json b/public/changelog.json
index a2f5b43fa..ef9cb5d88 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-01T17:00:46.937Z",
+ "generated_at": "2026-07-01T18:36:51.450Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -138,6 +138,17 @@
"feature"
]
},
+ {
+ "date": "2026-07-01",
+ "type": "update",
+ "title": "Live data keeps flowing — automatic database housekeeping",
+ "summary": "A handful of behind-the-scenes jobs — the smart-money radar, the coin-intel feeds, and usage metering — had started intermittently failing because the database had grown to its storage ceiling. We reclaimed the space, added a scheduled housekeeping job that trims the high-volume coin-intel history and stale avatar-generation payloads so the database self-manages its size, and made every write path degrade gracefully (a brief 'retry shortly' instead of a hard error) if storage ever runs tight again. The radar, feeds, and metering now keep updating reliably.",
+ "link": null,
+ "tags": [
+ "fix",
+ "infra"
+ ]
+ },
{
"date": "2026-07-01",
"type": "update",
@@ -159,6 +170,17 @@
"fix"
]
},
+ {
+ "date": "2026-07-01",
+ "type": "update",
+ "title": "Pay-per-call APIs now settle reliably — no more dead payment rails",
+ "summary": "Our x402 pay-per-call endpoints advertise which networks they accept before you pay. A secondary settlement network had been advertised even while its external verifier was offline, so a payment on that rail could be built and submitted only to fail at the last step. Endpoints now advertise a network only when it can actually settle — Solana (our in-house facilitator) always leads, and the secondary EVM rail appears only when a working verifier is configured. Buyers settle on the healthy rail instead of hitting a dead one. We also hardened the reputation-scoring job so a single slow wallet read can never stall the whole refresh.",
+ "link": null,
+ "tags": [
+ "fix",
+ "improvement"
+ ]
+ },
{
"date": "2026-07-01",
"type": "update",
@@ -267,6 +289,17 @@
"docs"
]
},
+ {
+ "date": "2026-07-01",
+ "type": "update",
+ "title": "three.ws 3D Forge is now a one-command Claude Code plugin",
+ "summary": "You can add three.ws 3D generation straight into Claude Code as a one-line plugin. three.ws 3D Forge bundles four skills — a free text→3D draft lane plus the paid avatar, high-fidelity mesh, and auto-rig lanes — and wires the three.ws generation, scene, and avatar servers with no extra setup. Add it with `/plugin marketplace add nirholas/three.ws`, then `/plugin install three-ws-3d@three-ws`; every result hands back a downloadable GLB and a live viewer link. The plugin is now packaged to Anthropic's plugin spec — manifest, license, and changelog — and prepared for submission to the public Claude plugin directory.",
+ "link": "/forge",
+ "tags": [
+ "feature",
+ "sdk"
+ ]
+ },
{
"date": "2026-07-01",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 41b2eaf87..652a8ac06 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -110,6 +110,14 @@
<category>improvement</category>
<description>The Launch Studio got a full makeover and a big new power. New look: instant search across all 50 recipes, colour-themed category tabs, a Reward/Theme filter, savable favourites, a Surprise-me button, and keyboard shortcuts. Clicking a recipe now slides open a live preview drawer with real candidate coins — avatars, signal-strength bars, a dev-buy slider that flows into the launch, and a network toggle. The big addition is the reward planner: route a coin's creator fees to anyone, not just GitHub — a GitHub or X (Twitter) account, any Solana wallet or .sol name, back to holders as cashback, or into an auto buy-back-and-burn. The same generalisation reaches the post-launch fees panel, whose recipient box now accepts a GitHub @user, an X handle (x:@handle), a raw wallet, or an owner/repo to split contributors.</description>
</item>
+ <item>
+ <title>Live data keeps flowing — automatic database housekeeping</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-07-01:Live data keeps flowing — automatic database housekeeping</guid>
+ <pubDate>Wed, 01 Jul 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>A handful of behind-the-scenes jobs — the smart-money radar, the coin-intel feeds, and usage metering — had started intermittently failing because the database had grown to its storage ceiling. We reclaimed the space, added a scheduled housekeeping job that trims the high-volume coin-intel history and stale avatar-generation payloads so the database self-manages its size, and made every write path degrade gracefully (a brief 'retry shortly' instead of a hard error) if storage ever runs tight again. The radar, feeds, and metering now keep updating reliably.</description>
+ </item>
<item>
<title>Long-running agent endpoints no longer time out mid-task</title>
<link>https://three.ws/changelog</link>
@@ -126,6 +134,14 @@
<category>fix</category>
<description>Fixed the typography on the Money Pulse and Viability pages. Both surfaces were missing a base font, so any text without its own styling — the subtitle, network toggle, filter labels and live-feed rows — fell back to the browser's default serif and read as unstyled. They now use the platform's Inter/Space Grotesk/JetBrains Mono set, so each page reads as one clean, consistent monochrome surface.</description>
</item>
+ <item>
+ <title>Pay-per-call APIs now settle reliably — no more dead payment rails</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-07-01:Pay-per-call APIs now settle reliably — no more dead payment rails</guid>
+ <pubDate>Wed, 01 Jul 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Our x402 pay-per-call endpoints advertise which networks they accept before you pay. A secondary settlement network had been advertised even while its external verifier was offline, so a payment on that rail could be built and submitted only to fail at the last step. Endpoints now advertise a network only when it can actually settle — Solana (our in-house facilitator) always leads, and the secondary EVM rail appears only when a working verifier is configured. Buyers settle on the healthy rail instead of hitting a dead one. We also hardened the reputation-scoring job so a single slow wallet read can never stall the whole refresh.</description>
+ </item>
<item>
<title>Pricing your agent's skills is now one tap</title>
<link>https://three.ws/agent-studio</link>
@@ -206,6 +222,14 @@
<category>sdk</category>
<description>The x402 buyer, seller, browser-modal and MCP libraries are published as standalone, provider-neutral npm packages you can use in any project without a three.ws account: @three-ws/x402-fetch (drop-in fetch that auto-pays a 402 in USDC), @three-ws/x402-server (build paid endpoints), @three-ws/x402-modal and @three-ws/x402-payment-modal (drop-in browser checkout), and @three-ws/x402-mcp and @three-ws/ibm-x402-mcp (pay or sell from any MCP client). There's also a new x402 extension for VS Code — inspect, pay, and scaffold paid endpoints from the editor — on both the VS Code Marketplace and Open VSX. The docs now carry install commands, one-line summaries, repo links, and a Node code sample in the pay-for-a-service tutorial.</description>
</item>
+ <item>
+ <title>three.ws 3D Forge is now a one-command Claude Code plugin</title>
+ <link>https://three.ws/forge</link>
+ <guid isPermaLink="false">2026-07-01:three.ws 3D Forge is now a one-command Claude Code plugin</guid>
+ <pubDate>Wed, 01 Jul 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>You can add three.ws 3D generation straight into Claude Code as a one-line plugin. three.ws 3D Forge bundles four skills — a free text→3D draft lane plus the paid avatar, high-fidelity mesh, and auto-rig lanes — and wires the three.ws generation, scene, and avatar servers with no extra setup. Add it with `/plugin marketplace add nirholas/three.ws`, then `/plugin install three-ws-3d@three-ws`; every result hands back a downloadable GLB and a live viewer link. The plugin is now packaged to Anthropic's plugin spec — manifest, license, and changelog — and prepared for submission to the public Claude plugin directory.</description>
+ </item>
<item>
<title>three.ws now self-hosts its Solana payment settlement</title>
<link>https://three.ws/changelog</link>
diff --git a/public/error-reporter.js b/public/error-reporter.js
index a35b4075d..aae34bc80 100644
--- a/public/error-reporter.js
+++ b/public/error-reporter.js
@@ -56,6 +56,15 @@
// ResizeObserver messages are spec-mandated, thrown by the browser itself,
// and not actionable — every error pipeline ignores them.
const IGNORED_SOURCES = /^(chrome|moz|safari|safari-web)-extension:/;
+ // Safari masks the URL of scripts it deems privacy-sensitive — content-blocker
+ // and browser-extension injected scripts, and some blob:/eval contexts — behind
+ // the synthetic `webkit-masked-url://hidden/` scheme. Our own same-origin modules
+ // are served from normal https URLs and are never masked, so an error whose only
+ // attributable frame is a masked URL comes from an injected third-party script,
+ // not three.ws (e.g. a cashback/shopping extension's `onResponse` handler throwing
+ // "undefined is not an object (evaluating 'response.cashbackReminder')"). Unfixable
+ // from our deploy and pure log noise — drop it. Matched on the stack in shouldIgnore.
+ const IGNORED_MASKED_URL = /webkit-masked-url:\/\//;
const IGNORED_MESSAGES = [
'ResizeObserver loop limit exceeded',
'ResizeObserver loop completed with undelivered notifications.',
@@ -314,6 +323,15 @@
if (report.stack && /\b(chrome|moz|safari|safari-web)-extension:\/\//.test(report.stack)) {
return true;
}
+ // Safari-masked injected-script frames (extension/content-blocker/blob) — never
+ // our same-origin code. Check both stack and source (a masked URL can surface
+ // as either), so a cashback/shopping-extension throw stops flooding [client-error].
+ if (
+ IGNORED_MASKED_URL.test(report.stack || '') ||
+ IGNORED_MASKED_URL.test(report.source || '')
+ ) {
+ return true;
+ }
if (report.message && IGNORED_MESSAGES.includes(report.message)) return true;
// WebGL could not start on this device — no GPU, a blocklisted driver, a
// headless/automation UA, or (mobile Safari) the per-tab live-context budget
diff --git a/public/features.json b/public/features.json
index b77c01efa..45f5e9d20 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-01T17:00:46.923Z",
+ "generated_at": "2026-07-01T18:36:51.429Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/tests/api/reputation-store-recompute.test.js b/tests/api/reputation-store-recompute.test.js
new file mode 100644
index 000000000..90031f3f9
--- /dev/null
+++ b/tests/api/reputation-store-recompute.test.js
@@ -0,0 +1,95 @@
+// Regression test for the recompute-reputation cron 504.
+//
+// The cron 504'd at Vercel's 300s hard kill even though it passed a 250s deadline:
+// the deadline was only checked BETWEEN chunks, so one un-timed getAgentReputation()
+// (a stalled Solana RPC / slow DB read) inside Promise.allSettled blocked the whole
+// batch past the timeout. recomputeAgents now bounds each agent with a per-agent
+// timeout capped at the wall-clock remaining before the deadline, so a hung upstream
+// can never run the batch past its budget. These tests lock that in with a fake
+// getAgentReputation that hangs forever.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// sql is used as a tagged template; a plain async fn resolving to [] satisfies
+// ensureTable() (returns true) and saveReputation()'s upsert (no throw → true).
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async () => []),
+ isDbUnavailableError: () => false,
+}));
+
+const getAgentReputation = vi.fn();
+vi.mock('../../api/_lib/trust/wallet-reputation.js', () => ({
+ getAgentReputation: (...args) => getAgentReputation(...args),
+ REPUTATION_VERSION: 3,
+}));
+
+const { recomputeAgents } = await import('../../api/_lib/trust/reputation-store.js');
+
+const okResult = (id) => ({
+ agent_id: id,
+ score: 50,
+ tier: 'silver',
+ isNew: false,
+ version: 3,
+ partial: false,
+});
+
+beforeEach(() => {
+ getAgentReputation.mockReset();
+});
+
+describe('recomputeAgents — per-agent timeout guards the cron budget', () => {
+ it('does not block on a single hung agent; bounds it and scores the rest', async () => {
+ getAgentReputation.mockImplementation((id) =>
+ id === 'hang' ? new Promise(() => {}) : Promise.resolve(okResult(id)),
+ );
+ const started = Date.now();
+ const res = await recomputeAgents(['a', 'hang', 'b'], {
+ concurrency: 1,
+ deadlineMs: 5_000,
+ perAgentTimeoutMs: 50,
+ });
+ const elapsed = Date.now() - started;
+ // The hung agent alone would have run past any timeout; a bounded run returns
+ // in well under a second, proving the per-agent cap fired.
+ expect(elapsed).toBeLessThan(1_000);
+ expect(res.scored).toBe(2); // a + b
+ expect(res.failed).toBe(1); // hung agent → timed out → failed
+ expect(res.remaining).toBe(0);
+ });
+
+ it('stops within the deadline when every agent hangs (never 504s)', async () => {
+ getAgentReputation.mockImplementation(() => new Promise(() => {}));
+ const ids = Array.from({ length: 20 }, (_, i) => `agent-${i}`);
+ const started = Date.now();
+ const res = await recomputeAgents(ids, {
+ concurrency: 2,
+ deadlineMs: 120,
+ perAgentTimeoutMs: 40,
+ });
+ const elapsed = Date.now() - started;
+ // Bounded by the deadline (+ at most one perAgentTimeoutMs), not infinite.
+ expect(elapsed).toBeLessThan(1_500);
+ expect(res.timedOut).toBe(true);
+ expect(res.scored).toBe(0);
+ expect(res.remaining).toBeGreaterThan(0); // unfinished agents roll over
+ });
+
+ it('never overruns the deadline by more than one per-agent budget', async () => {
+ // A slow-but-finite agent (200ms) with a 40ms cap must be cut off at ~40ms,
+ // not waited out — otherwise 20 of them would blow a 120ms deadline wide open.
+ getAgentReputation.mockImplementation(
+ (id) => new Promise((resolve) => setTimeout(() => resolve(okResult(id)), 200)),
+ );
+ const ids = Array.from({ length: 20 }, (_, i) => `slow-${i}`);
+ const started = Date.now();
+ const res = await recomputeAgents(ids, {
+ concurrency: 4,
+ deadlineMs: 150,
+ perAgentTimeoutMs: 40,
+ });
+ const elapsed = Date.now() - started;
+ expect(elapsed).toBeLessThan(150 + 200); // deadline + one over-budget chunk max
+ expect(res.timedOut).toBe(true);
+ });
+});
diff --git a/tests/api/x402-discovery-parity.test.js b/tests/api/x402-discovery-parity.test.js
index d3be51430..1a61efa93 100644
--- a/tests/api/x402-discovery-parity.test.js
+++ b/tests/api/x402-discovery-parity.test.js
@@ -34,6 +34,14 @@ const EXCLUSIONS = new Map([
'concrete listing is cataloged dynamically from agent_paid_services by ' +
"handleX402Discovery's buildAgentServiceItems(), not as a static entry.",
],
+ [
+ '/api/x402/ring-settle',
+ 'Internal closed-loop settlement primitive (discoverable:false in the ' +
+ 'endpoint itself): platform-controlled ring wallets pay it to cycle the ' +
+ 'agent economy. Deliberately NOT on the public bazaar/agentic.market ' +
+ 'catalog — ring volume is dogfooding, not organic third-party demand, and ' +
+ 'must not masquerade as such.',
+ ],
]);
function paidRoutesFromFiles() {
diff --git a/tests/api/x402-spec.test.js b/tests/api/x402-spec.test.js
index a465b2d1a..5f896f352 100644
--- a/tests/api/x402-spec.test.js
+++ b/tests/api/x402-spec.test.js
@@ -512,3 +512,99 @@ describe('send402 PAYMENT-REQUIRED header', () => {
expect(JSON.stringify(decoded)).toBe(JSON.stringify(body));
});
});
+
+describe('baseSettleable', () => {
+ // Base is settleable ONLY via CDP or a deliberate operator opt-in. A bare
+ // facilitator URL being set is NOT enough — prod pointed it at decommissioned
+ // hosts (x402.sperax.io, facilitator.payai.network) that 404 every /verify, so a
+ // URL string is no proof the endpoint works. baseSettleable() is the gate that
+ // keeps an unsettleable Base accept out of both the live 402 (buildRequirements)
+ // and the discovery catalog (wk.js), so buyers never pick a Base rail that 502s.
+ beforeEach(() => {
+ delete process.env.CDP_API_KEY_ID;
+ delete process.env.CDP_API_KEY_SECRET;
+ delete process.env.X402_FACILITATOR_URL_BASE;
+ delete process.env.X402_FACILITATOR_URL;
+ delete process.env.X402_ADVERTISE_BASE;
+ });
+
+ it('is false with no CDP creds and no opt-in (default)', async () => {
+ const { baseSettleable } = await loadSpec();
+ expect(baseSettleable()).toBe(false);
+ });
+
+ it('is FALSE even when a facilitator URL is set but not opted in (the dead-host trap)', async () => {
+ process.env.X402_FACILITATOR_URL_BASE = 'https://x402.sperax.io';
+ const { baseSettleable } = await loadSpec();
+ expect(baseSettleable()).toBe(false);
+ });
+
+ it('is true when CDP credentials are configured (Base settles via CDP)', async () => {
+ process.env.CDP_API_KEY_ID = 'x';
+ process.env.CDP_API_KEY_SECRET = 'y';
+ const { baseSettleable } = await loadSpec();
+ expect(baseSettleable()).toBe(true);
+ });
+
+ it('is true when the operator explicitly opts in via X402_ADVERTISE_BASE=true', async () => {
+ process.env.X402_ADVERTISE_BASE = 'true';
+ const { baseSettleable } = await loadSpec();
+ expect(baseSettleable()).toBe(true);
+ });
+
+ it('treats any non-"true" opt-in value as off', async () => {
+ process.env.X402_ADVERTISE_BASE = '1';
+ const { baseSettleable } = await loadSpec();
+ expect(baseSettleable()).toBe(false);
+ });
+
+ it('requires BOTH CDP keys — one alone is not enough', async () => {
+ process.env.CDP_API_KEY_ID = 'x';
+ const { baseSettleable } = await loadSpec();
+ expect(baseSettleable()).toBe(false);
+ });
+});
+
+describe('buildExactRequirements', () => {
+ // Shared accept builder for the hand-rolled endpoints (model-check, mint-to-mesh,
+ // vanity, vanity-verifiable, revenue-vision). Solana always leads; Base only rides
+ // along when settleable, so a dead Base facilitator is never advertised.
+ const SOLANA = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';
+ const BASE = 'eip155:8453';
+
+ beforeEach(() => {
+ delete process.env.CDP_API_KEY_ID;
+ delete process.env.CDP_API_KEY_SECRET;
+ delete process.env.X402_ADVERTISE_BASE;
+ });
+
+ it('is Solana-only when Base is not settleable (default)', async () => {
+ const { buildExactRequirements } = await loadSpec();
+ const reqs = buildExactRequirements('https://three.ws/api/x402/x');
+ expect(reqs.map((r) => r.network)).toEqual([SOLANA]);
+ expect(reqs[0].amount).toBe(process.env.X402_MAX_AMOUNT_REQUIRED);
+ });
+
+ it('lists Solana first, then Base, when opted in (no CDP → no Permit2 sibling)', async () => {
+ process.env.X402_ADVERTISE_BASE = 'true';
+ const { buildExactRequirements } = await loadSpec();
+ const reqs = buildExactRequirements('https://three.ws/api/x402/x');
+ expect(reqs.map((r) => r.network)).toEqual([SOLANA, BASE]);
+ });
+
+ it('appends the Permit2 sibling after Base when CDP is configured', async () => {
+ process.env.CDP_API_KEY_ID = 'x';
+ process.env.CDP_API_KEY_SECRET = 'y';
+ const { buildExactRequirements } = await loadSpec();
+ const reqs = buildExactRequirements('https://three.ws/api/x402/x');
+ expect(reqs.map((r) => r.network)).toEqual([SOLANA, BASE, BASE]);
+ expect(reqs[2].extra.assetTransferMethod).toBe('permit2');
+ });
+
+ it('honors an explicit amount override on every accept', async () => {
+ process.env.X402_ADVERTISE_BASE = 'true';
+ const { buildExactRequirements } = await loadSpec();
+ const reqs = buildExactRequirements('https://three.ws/api/x402/x', '250000');
+ expect(reqs.every((r) => r.amount === '250000')).toBe(true);
+ });
+});
diff --git a/tests/client-errors-noise.test.js b/tests/client-errors-noise.test.js
index 2e3075e3b..2d9ba8cb5 100644
--- a/tests/client-errors-noise.test.js
+++ b/tests/client-errors-noise.test.js
@@ -41,3 +41,38 @@ describe('isNonActionableNoise — injected wallet-provider RPC noise', () => {
expect(isNonActionableNoise(ev({ type: 'csp', message: 'Internal JSON-RPC error.' }))).toBe(false);
});
});
+
+describe('isNonActionableNoise — Safari webkit-masked-url injected scripts', () => {
+ // The exact signature seen in production: a cashback/shopping browser extension's
+ // `onResponse` handler throws inside a Safari-masked injected script, surfacing as
+ // an unhandledrejection three.ws can never fix.
+ it('drops an extension error whose stack is a webkit-masked-url frame', () => {
+ expect(
+ isNonActionableNoise(
+ ev({
+ name: 'TypeError',
+ message: "undefined is not an object (evaluating 'response.cashbackReminder')",
+ stack: 'onResponse@webkit-masked-url://hidden/:99:15',
+ }),
+ ),
+ ).toBe(true);
+ });
+
+ it('drops it when the masked URL is only on the source field', () => {
+ expect(
+ isNonActionableNoise(ev({ type: 'error', message: 'boom', source: 'webkit-masked-url://hidden/' })),
+ ).toBe(true);
+ });
+
+ it('keeps a genuine first-party fault with a normal same-origin stack', () => {
+ expect(
+ isNonActionableNoise(
+ ev({
+ name: 'TypeError',
+ message: "undefined is not an object (evaluating 'response.cashbackReminder')",
+ stack: 'onResponse@https://three.ws/assets/index-abc.js:99:15',
+ }),
+ ),
+ ).toBe(false);
+ });
+});
diff --git a/tests/db-capacity-error.test.js b/tests/db-capacity-error.test.js
new file mode 100644
index 000000000..ec0226927
--- /dev/null
+++ b/tests/db-capacity-error.test.js
@@ -0,0 +1,45 @@
+/**
+ * isDbCapacityError — classify the Neon storage-cap failure (SQLSTATE 53100).
+ *
+ * When a branch hits its project-size limit, Postgres raises 53100 ("could not
+ * extend file because project size limit … exceeded"). It must be recognized so
+ * write paths degrade gracefully instead of 500-storming — whether the driver
+ * surfaces err.code (native) or only the wrapped message (minified prod bundle).
+ */
+
+import { describe, it, expect } from 'vitest';
+import { isDbCapacityError, isDbUnavailableError } from '../api/_lib/db.js';
+
+describe('isDbCapacityError', () => {
+ it('matches on SQLSTATE code 53100', () => {
+ const e = new Error('anything');
+ e.code = '53100';
+ expect(isDbCapacityError(e)).toBe(true);
+ });
+
+ it('matches on the Neon message text when the code is stripped (minified bundle)', () => {
+ const e = new Error('could not extend file because project size limit (512 MB) has been exceeded');
+ e.name = 'NeonDbError';
+ expect(isDbCapacityError(e)).toBe(true);
+ });
+
+ it('matches the wrapped cause chain', () => {
+ const e = new Error('Error connecting to database');
+ e.cause = new Error('neon.max_cluster_size exceeded');
+ expect(isDbCapacityError(e)).toBe(true);
+ });
+
+ it('does not misfire on unrelated errors', () => {
+ expect(isDbCapacityError(new Error('syntax error at or near "$3"'))).toBe(false);
+ expect(isDbCapacityError(new Error('password authentication failed'))).toBe(false);
+ expect(isDbCapacityError(null)).toBe(false);
+ expect(isDbCapacityError(undefined)).toBe(false);
+ });
+
+ it('is distinct from a connectivity outage (a full DB is reachable)', () => {
+ const full = new Error('could not extend file because project size limit exceeded');
+ full.code = '53100';
+ expect(isDbCapacityError(full)).toBe(true);
+ expect(isDbUnavailableError(full)).toBe(false);
+ });
+});
diff --git a/tests/http-db-unavailable-boundary.test.js b/tests/http-db-unavailable-boundary.test.js
index daffd4a2b..3de117670 100644
--- a/tests/http-db-unavailable-boundary.test.js
+++ b/tests/http-db-unavailable-boundary.test.js
@@ -33,6 +33,16 @@ function dbDownError() {
return new Error('Missing required env var: DATABASE_URL');
}
+function dbFullError() {
+ // The exact NeonDbError shape when the branch hits its project-size cap
+ // (SQLSTATE 53100). esbuild minifies the class name, so production matches on
+ // err.code / message — mirror both here.
+ const e = new Error('could not extend file because project size limit (512 MB) has been exceeded');
+ e.name = 'NeonDbError';
+ e.code = '53100';
+ return e;
+}
+
let errSpy, warnSpy;
beforeEach(() => {
errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
@@ -58,6 +68,20 @@ describe('wrap() under a DB outage', () => {
expect(unhandled).toBe(false);
});
+ it('degrades a storage-cap failure (SQLSTATE 53100) to 503 + Retry-After, not a 500 storm', async () => {
+ const handler = wrap(async () => { throw dbFullError(); });
+ const res = fakeRes();
+ await handler({ method: 'GET', url: '/api/cron/smart-money-rollup', headers: {} }, res);
+
+ expect(res.statusCode).toBe(503);
+ expect(res.getHeader('retry-after')).toBe('30');
+ expect(JSON.parse(res.body).error).toBe('service_unavailable');
+
+ // No `[api] unhandled` error line / Sentry capture — throttled to a warn.
+ const unhandled = errSpy.mock.calls.some((c) => String(c[0]).includes('[api] unhandled'));
+ expect(unhandled).toBe(false);
+ });
+
it('still logs and 500s a genuine (non-DB) handler bug', async () => {
const handler = wrap(async () => { throw new Error('boom'); });
const res = fakeRes();
diff --git a/vercel.json b/vercel.json
index d3a14cb1f..523230c96 100644
--- a/vercel.json
+++ b/vercel.json
@@ -99,6 +99,9 @@
"api/cron/{recompute-reputation,smart-money-graph}.js": {
"maxDuration": 300
},
+ "api/cron/db-retention.js": {
+ "maxDuration": 120
+ },
"api/cron/[name].js": {
"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
"maxDuration": 300
@@ -4711,6 +4714,10 @@
"path": "/api/cron/smart-money-rollup",
"schedule": "*/5 * * * *"
},
+ {
+ "path": "/api/cron/db-retention",
+ "schedule": "*/15 * * * *"
+ },
{
"path": "/api/cron/smart-money-graph",
"schedule": "*/10 * * * *"
diff --git a/x402-launch-media/x402-article-extended.md b/x402-launch-media/x402-article-extended.md
new file mode 100644
index 000000000..693e2f9fd
--- /dev/null
+++ b/x402-launch-media/x402-article-extended.md
@@ -0,0 +1,254 @@
+# For 25 years, HTTP 402 did nothing. three.ws just switched it on inside VS Code.
+
+> The web's forgotten payment code is finally live, right where developers work. With the three.ws x402 extension you can discover, inspect, pay, and *publish* paid APIs by the call, in $THREE or USDC on Solana (and USDC on Base), without ever leaving the editor. This is the long version: the history, the protocol, the cryptography, the security model, and the ambitious platform it all grew out of.
+
+---
+
+## A status code that waited 25 years
+
+Open the HTTP specification and walk the 4xx range. `400 Bad Request`, used constantly. `401 Unauthorized`, `403 Forbidden`, `404 Not Found`, `429 Too Many Requests`: every one of them has a job, a library, a middleware, a muscle-memory reflex in every developer alive.
+
+Then there's `402 Payment Required`. It shipped in the earliest HTTP drafts and was immediately marked *"reserved for future use."* And there it sat. For twenty-five years the web had a status code that said, in plain language, *"you have to pay for this,"* and no standard way to actually do it.
+
+It's not that nobody tried. The web has attempted micropayments roughly once a decade since the 1990s: W3C working groups, browser wallets, tipping widgets, metered paywalls. They all broke on the same rock: the web had no native money. Every attempt bolted payments on from the outside, which meant an account, a credit-card form, a merchant relationship, a $0.30-plus card minimum that made a one-cent API call absurd, and a login wall between you and the thing you wanted. You can't build per-call settlement on rails whose smallest viable unit is thirty cents and whose "hello" is a signup form.
+
+Three things changed at once. Stablecoins gave the internet a unit of account that clears in seconds for fractions of a cent. On-chain settlement gave it finality without a merchant account. And AI agents (programs that call APIs on your behalf, thousands of times, with no human at the keyboard to type a card number) gave it a *reason*. An agent can't sign up for your SaaS tier. It can't remember your API key. But it can hold a wallet and pay for exactly what it uses, the instant it uses it.
+
+That's the opening `402` was reserved for. The protocol that finally fills it is called **x402**, and three.ws brought the whole thing into the one place developers actually wire up, test, and ship paid endpoints: **VS Code.** This is the kind of thing three.ws does: take a piece of the agent economy that was theoretical and ship it as a tool you can install today.
+
+---
+
+## What x402 actually is
+
+x402 is a payment protocol for developers and agents. Strip away the branding and it is four moves:
+
+1. **You request a resource.** A plain HTTP request, `GET` or `POST`, to an endpoint that happens to cost money.
+2. **The server answers `402 Payment Required`** with a machine-readable challenge. Not a paywall page for a human to squint at, but a structured envelope your code can parse: which networks it accepts, which asset, the exact price in atomic units, the payment scheme, and the address to pay.
+3. **Your client signs a payment authorization** in the requested token (USDC or $THREE) and retries the *same request* with the proof attached in an `X-PAYMENT` header.
+4. **The server verifies, does the work, and returns the result** plus an on-chain settlement receipt in an `x-payment-response` header.
+
+No accounts. No API keys. No subscriptions. No "contact sales." Just per-call settlement, on-chain, in the time it takes to retry a request.
+
+The challenge itself is a small JSON envelope (x402 version 2). Its heart is an `accepts[]` array: one entry per way you're allowed to pay. Each entry names a network in CAIP-2 form (`solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp` for Solana mainnet, `eip155:8453` for Base), an asset, an amount in atomic units, a scheme (`exact`, pay exactly this), and a `payTo` recipient. A single endpoint can advertise several at once: pay in USDC on Solana, *or* $THREE on Solana, *or* USDC on Base. Your client picks the rail it can satisfy and signs for that one.
+
+This is the part that matters and the part that's easy to miss: **the price and the payment instructions are data, not a webpage.** That's what makes 402 finally usable. A human never has to read it. A `fetch` wrapper reads it, a wallet signs it, and the call goes through, or an autonomous agent does the same thing at three in the morning with no one watching.
+
+---
+
+## Why the editor is the right place
+
+Here's the workflow the tooling forgot.
+
+You find a paid endpoint. To understand what it costs, you `curl` it and read a raw 402 blob by eye. To pay it, you copy an amount and an address into a separate wallet app, sign, wait, copy the transaction hash back. To confirm it settled, you open a block explorer in a browser tab. To *publish* your own paid endpoint, you clone a starter repo, wire up a facilitator, and hope you got the challenge format right. Four tools, three context switches, and a wallet holding real money one alt-tab away from the code you're writing.
+
+Every one of those steps is something a developer does **in the editor**, or would, if the editor could do it. Discovering an API, reading its contract, calling it with a test body, checking the response, scaffolding a new one: that's the inner loop of building against any API. Payments were the one part exiled to other windows, which is exactly why paid APIs felt heavier than free ones even when the payment itself takes a second.
+
+So we collapsed it. The **x402 Pay-per-call APIs** extension puts the entire loop (discover, inspect, pay, receive, publish) inside VS Code. The wallet lives in your OS keychain, the receipt renders next to the response, and the endpoint you scaffold is a file in your workspace. Nothing leaves the editor. That's not a convenience feature; it's the difference between paid APIs being a first-class thing you build with and a chore you avoid.
+
+---
+
+## What the extension does
+
+The extension ships as `three-ws.vscode-x402` (v0.2.0, Apache-2.0, VS Code 1.85+). Its own description is blunt about the scope:
+
+> *"Browse the x402 bazaar, decode 402 payment challenges, and pay per call for paid APIs and MCP tools in USDC or $THREE on Solana and Base, without leaving VS Code."*
+
+Four moves, all in the editor.
+
+### 1. Inspect any endpoint: free, read-only, no wallet
+
+Run **`x402: Inspect Endpoint (decode 402 challenge)`**, paste a URL, and the extension makes an unpaid request and decodes whatever 402 comes back. It reads the challenge from the `payment-required` / `x-payment-required` header (base64 JSON) or the response body, then lays out every accepted requirement in plain terms: network, asset, payment scheme, price converted to USD, and the `payTo` address. The one requirement *your* wallet can actually satisfy is flagged, and each entry is tagged with its rail: Solana or EVM.
+
+No wallet. No signing. No configuration. Inspecting is a pure read: you can point it at any x402 endpoint on the internet and see exactly what it would cost before you decide to spend a cent. Free endpoints just return their result; there's nothing to decode.
+
+### 2. Pay & call: the real thing, with guardrails
+
+Run **`x402: Pay & Call Endpoint`** (or hit "Pay & call" on a service in the sidebar) and you make a genuine paid request from a panel. You get a method selector and a JSON body field; the panel shows the price, and then three things happen before any key touches the request:
+
+- **The rail is chosen automatically.** The extension inspects the 402 and routes to the right chain based on your preferences: an explicit CAIP-2 `network`, then your `preferToken` choice (`auto`, `usdc`, or `three`), then a sensible auto-order: Solana USDC first, then any Solana asset, then Base USDC, then the first payable requirement. You don't hand-pick a chain; it picks the one you can pay on.
+- **The spending cap is enforced.** `threewsX402.maxPaymentUsd` defaults to **$0.10**. Anything above your cap is refused *before signing*, with a "raise cap & pay" escape hatch if you meant it.
+- **You confirm the exact spend.** With `confirmEachPayment` on (the default), a dialog shows the precise USD amount, the token, the network, and the paying address. Nothing is signed until you click through it.
+
+Then the response body and the on-chain receipt render inline: status, amount paid, paying address, token, network, and the transaction signature. The whole round trip (challenge, sign, retry, settle, receipt) happens in the panel, and you never leave the file you were in.
+
+### 3. Browse a bazaar: discovery in the sidebar
+
+The **x402 Bazaar** view lives in the activity bar. Point it at a discovery origin (`threewsX402.origin`, default `https://three.ws`) and it lists paid HTTP APIs and MCP tools pulled live from the bazaar's discovery API, which itself merges multiple facilitator feeds (PayAI and Coinbase CDP) into one normalized list. Filter by type (`http` / `mcp`), price, network, and tag; run a full-text search with **`x402: Search Bazaar`**; click any service to open its detail panel and pay it. Discovery and payment are the same surface: find a tool, read its contract, call it, all in the sidebar.
+
+### 4. Scaffold your own: publisher in about a minute
+
+Run **`x402: Scaffold a Paid Endpoint`**, answer three prompts (URL slug, price in USD, description), and the extension generates a self-contained handler at `api/x402/<slug>.js`. It follows the canonical `paidEndpoint()` pattern from the platform's own server library: it advertises a 402 challenge on an unpaid request, and runs your handler **only after payment verifies and settles on-chain.** The generated handler echoes the request as proof the whole thing is wired end to end: you replace that body with your real logic and you're a paid-API publisher. The scaffold prices in USDC on Base out of the box; adding the Solana / $THREE rail is one option flag on the server side (below).
+
+---
+
+## Under the hood
+
+The extension sends your request unpaid (free endpoints just work), parses the 402, and picks a payable requirement across both rails, honoring your network and token preferences. Then, depending on the rail, one of two payment paths runs.
+
+### The EVM rail: EIP-3009 on Base
+
+For Base and other EVM chains, the extension uses the vendored **`@three-ws/x402-fetch`** client to sign a USDC `transferWithAuthorization` (**EIP-3009**), structured and signed as **EIP-712** typed data. EIP-3009 is the right primitive here: it lets you authorize a transfer by signature without a separate on-chain `approve`, so a single locally-produced signature *is* the payment. The message carries `from`, `to`, `value`, a `validAfter` / `validBefore` window, and a random `nonce`: signed once, submitted once, never replayable.
+
+What's notable is that `@three-ws/x402-fetch` is **genuinely zero-dependency** (`"dependencies": {}`, verified). The entire cryptographic stack is inlined:
+
+- **secp256k1 ECDSA**: deterministic nonces via RFC-6979 (HMAC-SHA256), low-S normalization to kill signature malleability, recoverable 65-byte signatures. Ethereum addresses are derived the canonical way: public key → keccak256 → last 20 bytes → checksum.
+- **keccak256**: a pure-JavaScript Keccak-f[1600] over BigInt lanes, verified against the canonical test vectors.
+- **EIP-712**: typed-data hashing that produces the 32-byte digest `eth_signTypedData_v4` would, implementing exactly the value types the payment needs (address, uintN, bytes32, bytes, string) and no more.
+
+The only outside primitives are HMAC-SHA256 and SHA-256, taken from **Web Crypto** (`globalThis.crypto.subtle`), present in Node 18+ and every modern browser. Nothing exotic, nothing to audit but the code in front of you, and no payment SDK pulled at runtime.
+
+### The Solana rail: the real `@x402/svm` exact scheme
+
+For Solana, the extension does **not** use `x402-fetch` (which is EVM-only by design). It uses the real **`@x402/svm`** `ExactSvmScheme`, the same buyer that powers `@three-ws/x402-mcp` in production. It loads your Solana key (base58 or JSON byte array), builds a signer with `@solana/kit`, registers the scheme against `solana:*`, filters the challenge's accepts down to your preferred token, and signs a real SPL transfer of the selected asset:
+
+- **USDC on Solana**, mint `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`
+- **$THREE**, mint `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump` (SPL, 6 decimals, Solana-native, the platform's own token)
+
+No mocking, no stub: the same settlement path a headless agent would use.
+
+### The common tail
+
+Either way, the extension retries the request with an `X-PAYMENT` header carrying the base64-encoded payment payload. The merchant verifies it, does the work, settles on-chain through a facilitator, and returns the result plus a receipt in the `x-payment-response` header. The extension decodes that receipt and renders it inline (token, network, transaction signature) right under the response body.
+
+The default facilitator that actually settles both Solana and Base is **PayAI** (`facilitator.payai.network`); Coinbase CDP shows up as one of the *discovery* feeds the bazaar merges, not as the settler. Any route can override the facilitator, so nothing is bolted to a single provider.
+
+---
+
+## Security you can reason about
+
+The threat model here is simple to state: there's a private key on a developer's machine that can spend real money, and the editor is asking it to sign things. Every design choice follows from taking that seriously.
+
+- **Keys live in the OS keychain, never on disk in plaintext.** Both the EVM key (`threewsX402.walletPrivateKey`) and the Solana key (`threewsX402.solanaSecretKey`) are stored in VS Code **SecretStorage**: Keychain on macOS, Credential Manager on Windows, libsecret on Linux. Never in `settings.json`, never in workspace config, never logged. They're entered through a masked input and only loaded into memory at the moment of payment. The status bar shows the derived addresses (◎ for Solana, ⟠ for EVM); the keys themselves never surface.
+- **Two keys, two rails, independent.** The Solana and EVM wallets are separate. You can fund one and leave the other empty, and an endpoint is only payable on the rail where a key exists; if it isn't, the extension offers to set the missing one rather than failing silently.
+- **The spending cap is checked before signing, not after.** `maxPaymentUsd` (default $0.10) rejects any payment over your limit *before* the key is touched. A runaway loop or a mispriced endpoint can't drain a wallet a cent at a time.
+- **Every payment is confirmed with the real numbers.** With `confirmEachPayment` on, you see the exact USD amount, token, network, and payer before anything is signed. No signature happens without an explicit click.
+- **Signatures can't be replayed.** EIP-3009 authorizations carry a random nonce and a validity window; Solana transfers are signed per-call. There's no reusable blanket approval sitting on-chain.
+
+The guidance the extension itself gives is deliberately blunt: **use a dedicated, low-balance wallet.** Treat it like the petty-cash drawer, not the vault. The point of per-call micropayments is that the amounts are tiny, so the wallet backing them should be too.
+
+---
+
+## Two tokens, one challenge
+
+A detail worth pulling out: on the merchant side, **`@three-ws/x402-server`** can advertise **both USDC and $THREE in a single 402 challenge**. Turn on `acceptThree` and a Solana endpoint emits two accepts (USDC first, then $THREE) inside the same envelope. The buyer picks. That's the whole point of the `accepts[]` array being plural: a publisher doesn't have to choose their audience's currency in advance. A USDC-holding agent and a $THREE-holding agent hit the same URL and each pays in what it carries. `$THREE` is the platform's native token and the one it promotes; USDC is the neutral stablecoin rail. The protocol lets both ride in one response, and the extension routes to whichever you told it to prefer.
+
+---
+
+## No lock-in
+
+The extension has no dependency on any specific provider. Point it at *any* compliant x402 endpoint, or *any* bazaar that serves the discovery API. It's the open protocol all the way down. Discovery is optional: inspecting and paying a single URL needs zero configuration, no origin, no account. The vendored client means there's no payment SDK fetched at runtime and no service you're implicitly trusting beyond the merchant you chose to pay. That openness is a point of pride: three.ws built the extension to serve the whole x402 ecosystem, not to fence it in. It works with any compliant endpoint or bazaar, three.ws's own or anyone else's, which is exactly how a tool from one team becomes infrastructure for everyone.
+
+---
+
+## Build a paid API in 60 seconds
+
+The scaffold command is the fast path, but here's the shape of what it produces, because it's the same server library any publisher uses. `@three-ws/x402-server`'s `paid()` wrapper gates a handler behind payment:
+
+```js
+import { paid } from '@three-ws/x402-server';
+
+export default paid(
+ {
+ price: '10000', // 0.01 USDC, in atomic units (6 decimals)
+ asset: 'usdc',
+ acceptThree: true, // also advertise $THREE in the same 402
+ payTo: { solana: '<your-sol-addr>', base: '0x<your-base-addr>' },
+ },
+ async (req, res) => {
+ // Runs ONLY after payment verifies and settles on-chain.
+ const body = await readJson(req);
+ return { ok: true, result: doTheWork(body) };
+ },
+);
+```
+
+An unpaid request gets a 402 with your price on both rails. A paid request gets verified against the facilitator, runs your handler, settles, and returns the work with a receipt. The library also gives you `buildChallenge`, `verifyPayment`, `settlePayment`, and a `feeSplit` helper that carves a platform fee out of the price without ever marking it up to the buyer. The whole thing is zero-dependency and ESM, and it defaults to the PayAI facilitator for Solana + Base; override per route if you want your own.
+
+That's the symmetry the extension is built around: **`x402-fetch` / `@x402/svm` on the buyer side, `x402-server` on the seller side, and one editor that speaks both.** You can inspect someone's endpoint and scaffold your own in the same window, minutes apart.
+
+---
+
+## Where x402 fits: the three.ws ecosystem
+
+This extension is one surface of **three.ws**, an open-source, browser-native platform for 3D AI agents that can *earn, pay, and coordinate.* The same team that wired 402 into your editor is building the whole loop around it: give an AI a body, a brain, an on-chain identity, and a wallet, then let agents transact with each other in real time. It ships from a single npm-workspaces monorepo, published under the **`@three-ws`** scope. `$THREE` (Solana: `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) is the native token.
+
+### What we're building
+
+Type a prompt and **Forge** turns text, an image, or a sketch into a textured, rig-ready 3D model: free draft tier, no account. Rig it, animate it, give it an LLM brain, embed it anywhere with `<agent-3d>`, register it on-chain (ERC-8004), and let it pay for tools and get paid for skills over x402. The extension you just installed is the *payments edge* of that platform, pulled out so any developer can use it standalone. You don't need a single 3D asset to get value from it.
+
+### The x402 stack
+
+- **`@three-ws/x402-fetch`**: the zero-dependency payment client the extension vendors for the EVM rail. `withX402(wallet)` wraps any `fetch` so it transparently pays USDC/EIP-3009 challenges on Base and retries. All crypto inlined, `dependencies: {}`.
+- **`@three-ws/x402-server`**: the merchant side. Turn any endpoint paid; advertise USDC *and* $THREE in one challenge; verify and settle on Solana + Base; split a platform fee.
+- **`@three-ws/x402-mcp`**: a self-custodial x402 buyer as an MCP server. Four tools (`x402_wallet`, `find_services`, `inspect_endpoint`, `pay_and_call`) that let any AI client search the bazaar, price an endpoint without paying, and pay-and-call any service in USDC or $THREE from its own Solana key, bounded by spend caps, no custodial account.
+- **Native x402 endpoints on Solana and Base**, settled through the PayAI facilitator (Coinbase CDP is a bazaar discovery feed). The sibling **`@three-ws/naming-mcp`** resolves `@username`, `*.sol`, and `*.threews.sol` to addresses when you'd rather point at a name than paste a base58 string.
+
+### 40+ MCP servers
+
+Everything the platform can do is exposed over the Model Context Protocol, listed in the [official MCP registry](https://registry.modelcontextprotocol.io/?q=io.github.nirholas): **32 install-and-run servers on npm** (stdio) under `@three-ws`, two more top-level npm servers (`@three-ws/mcp-server`, the full 3D + agent toolkit; `@three-ws/mcp-bridge`, an x402 HTTP→stdio bridge that auto-pays endpoints), and **7 hosted remote endpoints** (Streamable HTTP, nothing to install). A sampling of the fleet:
+
+- **3D & avatars:** `scene-mcp` (speak a diorama into being), `avatar-agent-mcp`, `threews-avatar-mcp`, `loom-mcp` (the creation gallery), plus the hosted `/api/mcp` (35+ avatar/agent tools) and `/api/mcp-3d` (text→3D).
+- **Payments & economy:** `x402-mcp`, `three-token-mcp`, `mcp-bridge`, `autopilot-mcp` (scopes + spend caps + propose/execute/undo), `agentcore-payments-mcp`, `billing-mcp`, `portfolio-mcp`, `provenance-mcp`.
+- **Market intel:** `intel-mcp`, `pumpfun-mcp`, `signals-mcp`, `kol-mcp`, `vanity-mcp`, `marketplace-mcp`, `activity-mcp`, `alerts-mcp`.
+- **Coordination:** `agenc-mcp` (on-chain task marketplace), `agora-mcp`, `naming-mcp`, `notifications-mcp`, `tutor-mcp`, `copy-mcp`, `clash-mcp`.
+- **AI providers:** `ibm-watsonx-mcp`, `ibm-x402-mcp`, `alibaba-cloud-mcp` (Qwen / DashScope), `brain-mcp` (multi-provider router), `vision-mcp`, `audio-mcp`.
+
+### 70+ SDKs & packages (all `@three-ws`, all published)
+
+The `@three-ws` scope holds **more than 70 published packages**: zero-dependency, pure-ESM, typed, and tested (**216 green tests** across the SDK suite, per the repo's own `STRUCTURE.md`). Each wraps a live platform capability into a single import:
+
+- **Create:** `forge`, `pose`, `mocap`, `voice`, `glb-tools`, `avatar`, `avatar-cli`, `page-agent`, `walk`, `avatar-schema`, `viewer-presets`.
+- **Earn / trade:** `x402-server`, `x402-fetch`, `strategies`, `pumpfun-skills`, `agent-guards`, `skill-license`.
+- **Coordinate:** `agenc` (task marketplace), `agent-memory`, `reputation` (ERC-8004), `guardian` (content safety), `names`, `intel`, `vanity`, `irl`.
+- **Cross-chain:** `@three-ws/sdk`, `@three-ws/solana-agent`, `@three-ws/agent-protocol-sdk`, `@three-ws/agent-payments`.
+
+### In your editor
+
+- **VS Code:** the *x402 Pay-per-call APIs* extension, this one.
+- **Claude Code plugin marketplace:** add `three-ws` once and install wallet, payments, pump.fun trading, agent scaffolding, and the 3D Forge as namespaced skills + MCP tools. Works across Claude Code, Claude Desktop, and Cursor over MCP.
+
+### Partners & platforms
+
+three.ws builds in the open and earns its integrations. The reach is real and growing:
+
+- **IBM:** three.ws is an IBM Business Partner, with the agent runtime running on **IBM Granite** models via **watsonx.ai**. *(Our public `/ibm/*` demos and the `@three-ws/ibm-watsonx-mcp` / `@three-ws/ibm-x402-mcp` connectors are community-built explorations of Granite, made by the three.ws team.)*
+- **AWS:** AWS Partner on the APN Software Path, with a Marketplace SaaS listing in review and production running on `us-east-1`.
+- **Alibaba Cloud:** a live product listing on Alibaba Cloud Marketplace.
+- **Solana Mobile (Seeker):** MWA wallet wired straight into the app, with a dApp Store release pipeline ready to ship.
+- **Built on / integrated with:** Anthropic Claude, PayAI (the default x402 facilitator) and Coinbase CDP (a bazaar discovery feed), pump.fun, ENS + SNS, Meshy & Tripo (bring-your-own-key 3D), and FLUX → TRELLIS (the free text→3D lane).
+
+### Under the hood
+
+Stateless Vercel serverless functions, Neon Postgres, Cloudflare R2, Upstash Redis, a full OAuth 2.1 authorization server, and an MCP endpoint. Payments span **15+ EVM chains and Solana** (Metaplex Core).
+
+---
+
+## Get it
+
+Open the Extensions view, search **x402**, and install `threews.vscode-x402`, or run `ext install nirholas.vscode-x402`. Requires VS Code 1.85+. You only need a funded wallet to *pay*: a Solana wallet holding $THREE or USDC, or a Base USDC wallet. Inspecting endpoints and browsing the bazaar are free and need no wallet at all.
+
+It's **free**, on the VS Code Marketplace now → https://marketplace.visualstudio.com/items?itemName=threews.vscode-x402
+
+**Explore it:** [three.ws](https://three.ws) · [MCP registry](https://registry.modelcontextprotocol.io/?q=io.github.nirholas) · [github.com/nirholas/three.ws](https://github.com/nirholas/three.ws) · `$THREE` on Solana `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`
+
+The extension is the easiest door into a much bigger build. three.ws is giving AI agents a body, a brain, an identity, and a wallet, and wiring them into an economy where they can actually pay each other. Payments an agent can make on its own, identity it can carry, skills it can sell: three.ws is turning each of those from a whitepaper idea into something you can install and use today, all in the open, all under `@three-ws`. This is just the first piece you can hold.
+
+Twenty-five years is long enough. Let's use the code.
+
+---
+
+## FAQ
+
+**Do I need crypto to use it?** Not for inspecting or browsing: decoding a 402 challenge and searching the bazaar are pure reads with no wallet. You only need a funded wallet to actually pay a call.
+
+**Which chains and tokens?** USDC or $THREE on Solana (via the real `@x402/svm` exact scheme), and USDC on Base (via `@three-ws/x402-fetch`, EIP-3009). The extension auto-routes to whichever rail your challenge and preferences point at.
+
+**Where does my private key go?** Into your OS keychain via VS Code SecretStorage: never `settings.json`, never disk plaintext, never a log. It's loaded only at the moment of payment.
+
+**What stops an accidental overspend?** A per-call spending cap (default $0.10) checked *before* signing, plus a per-payment confirmation showing the exact amount, token, network, and payer. Use a dedicated low-balance wallet.
+
+**Is there vendor lock-in?** No. It speaks the open x402 protocol to any compliant endpoint and any compliant bazaar. The payment client is vendored and zero-dependency: no SDK fetched at runtime, no service trusted beyond the merchant you chose to pay.
+
+**Can I publish my own paid API?** Yes: one command scaffolds `api/x402/<slug>.js` around `@three-ws/x402-server`'s `paid()` wrapper. Your handler runs only after payment settles on-chain. You're a publisher in about a minute.
+
+**Is this only for the three.ws platform?** No. It's the payments edge of three.ws pulled out to stand alone. You never need a 3D asset, an account, or the rest of the platform to inspect, pay, and publish x402 endpoints from your editor.