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.

fix: prod-error hardening — chat-models, db, token config, cron, og + vercel routing

nirholas5652a71eef32
diff --git a/api/_lib/chat-models.js b/api/_lib/chat-models.js
index 28cc1646a..85bce2fe3 100644
--- a/api/_lib/chat-models.js
+++ b/api/_lib/chat-models.js
@@ -142,6 +142,11 @@ export const ANON_PROVIDER_LIST = ['groq', 'openrouter'];
* MAX_FALLBACK_ATTEMPTS — hard cap on upstream attempts per request.
* TOTAL_BUDGET_MS — wall-clock budget across all attempts (< the 60s
* function limit, leaving headroom to stream a reply).
+ * PER_CALL_TIMEOUT_MS — per-attempt abort ceiling. A single hung provider
+ * must not consume the whole TOTAL_BUDGET_MS; we abort
+ * the fetch at this bound (or the remaining budget,
+ * whichever is smaller) and fail over to the next route.
*/
export const MAX_FALLBACK_ATTEMPTS = 3;
export const TOTAL_BUDGET_MS = 25_000;
+export const PER_CALL_TIMEOUT_MS = 15_000;
diff --git a/api/_lib/db.js b/api/_lib/db.js
index 65d2b9e5d..e92be2597 100644
--- a/api/_lib/db.js
+++ b/api/_lib/db.js
@@ -12,9 +12,33 @@ function getSql() {
if (!_sql) _sql = neon(env.DATABASE_URL);
return _sql;
}
+
+// Postgres text/varchar/jsonb columns cannot store a NUL byte (U+0000) — any
+// parameter containing one makes the driver throw
+// `invalid byte sequence for encoding "UTF8": 0x00` (SQLSTATE 22021) and 500s
+// the request (seen on /api/explore's search param). NULs only ever reach us
+// from corrupt/garbage input, never legitimately, so we strip them from every
+// string-typed query parameter at this single boundary rather than dotting
+// per-endpoint sanitizers around the codebase. Non-string params (numbers,
+// booleans, Buffers/bytea, null, jsonb objects) pass through untouched; the
+// template-strings array (args[0]) is never modified.
+function stripNulParams(args) {
+ if (args.length < 2) return args;
+ let mutated = false;
+ const out = args.map((v, i) => {
+ if (i === 0) return v; // template strings array — leave intact
+ if (typeof v === 'string' && v.includes('\u0000')) {
+ mutated = true;
+ return v.replace(/\u0000/g, '');
+ }
+ return v;
+ });
+ return mutated ? out : args;
+}
+
export const sql = new Proxy(function () {}, {
apply(_t, _this, args) {
- return getSql()(...args);
+ return getSql()(...stripNulParams(args));
},
get(_t, prop) {
return getSql()[prop];
diff --git a/api/_lib/token/config.js b/api/_lib/token/config.js
index f6ee098e7..5ac9beef2 100644
--- a/api/_lib/token/config.js
+++ b/api/_lib/token/config.js
@@ -35,9 +35,15 @@ export function treasuryWallet() {
const w = env.THREE_TREASURY_WALLET;
if (w) return w;
if (process.env.NODE_ENV === 'production') {
- throw new Error(
+ // Fail closed, but as a typed 503 so the caller renders a clean
+ // "temporarily unavailable" state instead of an opaque 500. The condition
+ // is a deploy-time misconfiguration (env unset), not a client error.
+ const e = new Error(
'[token] THREE_TREASURY_WALLET is required in production — refusing to route treasury funds to an unset address.',
);
+ e.status = 503;
+ e.code = 'treasury_unavailable';
+ throw e;
}
if (!_treasuryWarned) {
_treasuryWarned = true;
diff --git a/api/agents/tokens/[action].js b/api/agents/tokens/[action].js
index 5a9ce1c70..d71936ecf 100644
--- a/api/agents/tokens/[action].js
+++ b/api/agents/tokens/[action].js
@@ -107,7 +107,13 @@ async function pinTokenMetadata(meta) {
}
}
const hash = createHash('sha256').update(bytes).digest('hex');
- const key = `token-metadata/${Date.now()}-${Math.random().toString(36).slice(2)}.json`;
+ // Keep this key SHORT. The resulting public URL becomes the coin's on-chain
+ // metadata `uri`, which is serialized into the launch transaction. A long key
+ // pushes the (legacy) create+buy tx over Solana's 1232-byte packet limit
+ // ("Transaction too large"). A content-addressed 16-hex prefix is unique
+ // enough and ~30 bytes shorter than a timestamp+random path. (When
+ // web3.storage is configured we use the even shorter `ipfs://<cid>` above.)
+ const key = `tm/${hash.slice(0, 16)}.json`;
const { PutObjectCommand } = await loadS3Commands();
await r2.send(
new PutObjectCommand({
@@ -241,9 +247,27 @@ async function handleLaunchPrep(req, res) {
// secret key is no longer needed and goes out of scope.
tx.partialSign(mintKeypair);
- const txBase64 = tx
- .serialize({ requireAllSignatures: false, verifySignatures: false })
- .toString('base64');
+ // Serialize defensively. A coin whose name/uri push the create+buy past
+ // Solana's 1232-byte packet limit otherwise throws an unhandled RangeError
+ // ("Transaction too large" / "encoding overruns Uint8Array") → a 500 with no
+ // actionable signal. Catch it and return a clean, typed 413 telling the user
+ // exactly what to shorten.
+ let txBase64;
+ try {
+ txBase64 = tx
+ .serialize({ requireAllSignatures: false, verifySignatures: false })
+ .toString('base64');
+ } catch (err) {
+ if (/too large|overruns/i.test(err?.message || '')) {
+ return error(
+ res,
+ 413,
+ 'launch_payload_too_large',
+ 'token launch transaction exceeds Solana size limits — shorten the token name',
+ );
+ }
+ throw err;
+ }
// 5. Persist prep
const prepId = await randomToken(24);
diff --git a/api/chat.js b/api/chat.js
index 868e19905..58cda468b 100644
--- a/api/chat.js
+++ b/api/chat.js
@@ -40,6 +40,7 @@ import {
MODEL_CATALOG,
MAX_FALLBACK_ATTEMPTS,
TOTAL_BUDGET_MS,
+ PER_CALL_TIMEOUT_MS,
} from './_lib/chat-models.js';
import { z } from 'zod';
@@ -410,14 +411,30 @@ export default wrap(async (req, res) => {
// Most routes carry static headers; watsonx resolves a fresh IAM
// bearer token (cached between requests) just before the fetch.
const reqHeaders = route.headers || (await route.resolveHeaders());
- upstream = await fetch(route.url, {
- method: 'POST',
- headers: reqHeaders,
- body: JSON.stringify(route.buildPayload({ systemPrompt, history, maxTokens, includeTools })),
- });
+ // Per-attempt abort: a single hung provider must not silently consume
+ // the whole TOTAL_BUDGET_MS (and ultimately trip the 60s function
+ // timeout). Cap each attempt at the smaller of the remaining budget or
+ // PER_CALL_TIMEOUT_MS, so a stalled upstream aborts fast and we fail
+ // over to the next route while time remains. The AbortError lands in
+ // the catch below, which advances the chain like any network blip.
+ const remainingMs = deadline - Date.now();
+ const ctrl = new AbortController();
+ const callMs = Math.max(1, Math.min(PER_CALL_TIMEOUT_MS, remainingMs));
+ const timer = setTimeout(() => ctrl.abort(), callMs);
+ try {
+ upstream = await fetch(route.url, {
+ method: 'POST',
+ headers: reqHeaders,
+ body: JSON.stringify(route.buildPayload({ systemPrompt, history, maxTokens, includeTools })),
+ signal: ctrl.signal,
+ });
+ } finally {
+ clearTimeout(timer);
+ }
} catch (err) {
captureException(err, { route: 'chat', stage: 'fetch', provider: route.name });
- console.error(`[chat:${route.name}] upstream fetch failed:`, err.message);
+ const reason = err?.name === 'AbortError' ? 'timed out' : err.message;
+ console.error(`[chat:${route.name}] upstream fetch failed:`, reason);
// Network blip — try next route if one exists and time remains.
routeIdx++;
if (routeIdx < fallbackRoutes.length && Date.now() < deadline) {
diff --git a/api/cron/[name].js b/api/cron/[name].js
index f709377dd..7c47cd91e 100644
--- a/api/cron/[name].js
+++ b/api/cron/[name].js
@@ -369,6 +369,16 @@ const REDEEMED_TOPIC = dmIface.getEvent('RedeemedDelegation').topicHash;
const IDX_BLOCK_CAP = 2000;
const IDX_MAINNET_BLOCK_CAP = 25; // ETH mainnet is far more restrictive
const IDX_RPC_TIMEOUT_MS = 10_000;
+// Stay this many blocks behind the chain tip. Two reasons:
+// 1. idxRpc rotates across a pool of public RPCs, and they are not perfectly
+// in sync — eth_blockNumber may resolve on a node at head N while a sibling
+// serves eth_getLogs with a head of N-2, which rejects toBlock=N with
+// "block range extends beyond current head block". A small buffer keeps the
+// queried range valid on every node in the pool.
+// 2. It avoids indexing blocks that can still be reorged out near the tip.
+// The next tick advances the cursor and picks up the buffered blocks once they
+// are safely confirmed.
+const IDX_HEAD_CONFIRMATIONS = 5;
// Hard time budget per cron invocation — leave 8 s headroom before Vercel's 30 s limit.
const IDX_TIME_BUDGET_MS = 22_000;
@@ -378,21 +388,24 @@ const BLOCKS_PER_DAY = {
11155111: 7200, // Sepolia ~12 s/block
};
-// Public RPC fallbacks per chain — tried in order. Override primary via env RPC_URL_<chainId>.
+// Public RPC fallbacks per chain — tried in order. Override primary via env
+// RPC_URL_<chainId> with a keyed provider (Alchemy/Infura/QuickNode); the env
+// URL is always tried first (see idxRpcUrls). The public fallbacks below are a
+// best-effort safety net only — they rate-limit (429) and some don't serve
+// eth_getLogs, so prod MUST set RPC_URL_1 / RPC_URL_8453 for reliable indexing.
+// Removed: cloudflare-eth.com (endpoint sunset — always failed, wasting the
+// first attempt + timeout each run) and 1rpc.io/* (chronic 429 in prod logs).
const PUBLIC_RPCS = {
1: [
- 'https://cloudflare-eth.com',
'https://eth.llamarpc.com',
'https://rpc.ankr.com/eth',
'https://ethereum.publicnode.com',
- 'https://1rpc.io/eth',
],
8453: [
'https://mainnet.base.org',
'https://base.llamarpc.com',
'https://rpc.ankr.com/base',
'https://base.publicnode.com',
- 'https://1rpc.io/base',
],
84532: [
'https://sepolia.base.org',
@@ -403,7 +416,6 @@ const PUBLIC_RPCS = {
'https://rpc.sepolia.org',
'https://ethereum-sepolia-rpc.publicnode.com',
'https://rpc.ankr.com/eth_sepolia',
- 'https://1rpc.io/sepolia',
],
421614: [
'https://sepolia-rollup.arbitrum.io/rpc',
@@ -486,8 +498,10 @@ async function idxIndexChain(chainId, contract, cronStart = Date.now()) {
// Per-chain batch size: ETH mainnet nodes cap eth_getLogs at 50 blocks.
const BATCH = chainId === 1 ? IDX_MAINNET_BLOCK_CAP : IDX_BLOCK_CAP;
- const latestHex = await idxRpc(urls, 'eth_blockNumber', []);
- const latestBlock = parseInt(latestHex, 16);
+ const headHex = await idxRpc(urls, 'eth_blockNumber', []);
+ // Index only up to a confirmed head, never the raw tip — see
+ // IDX_HEAD_CONFIRMATIONS for why (cross-RPC head skew + reorg safety).
+ const latestBlock = Math.max(0, parseInt(headHex, 16) - IDX_HEAD_CONFIRMATIONS);
const [cursor] = await sql`
SELECT last_indexed_block FROM indexer_state
@@ -533,14 +547,23 @@ async function idxIndexChain(chainId, contract, cronStart = Date.now()) {
},
]);
} catch (fetchErr) {
- // AbortError means this batch timed out — save the cursor at the start
- // of this batch so the next invocation can retry it, then stop.
- if (fetchErr.name === 'AbortError' || fetchErr.name === 'TimeoutError') {
+ // AbortError (batch timed out) or a transient block-range/head-skew
+ // error (a lagging RPC in the rotation pool rejecting a range it
+ // hasn't synced yet) — save the cursor at the start of this batch so
+ // the next invocation retries it, then stop. These are not failures:
+ // the cron resumes from here next tick.
+ const transient =
+ fetchErr.name === 'AbortError' ||
+ fetchErr.name === 'TimeoutError' ||
+ /beyond (the )?current head|block range|range is too large|exceeds/i.test(
+ fetchErr.message || '',
+ );
+ if (transient) {
console.warn(
JSON.stringify({
stage: 'index-delegations',
chainId,
- warning: 'rpc-abort',
+ warning: 'rpc-transient',
message: fetchErr.message,
stoppedAtBlock: fromBlock,
}),
diff --git a/api/explore.js b/api/explore.js
index adeb0cb5e..619d72b92 100644
--- a/api/explore.js
+++ b/api/explore.js
@@ -41,7 +41,15 @@ export default wrap(async (req, res) => {
const url = new URL(req.url, 'http://x');
const only3d = url.searchParams.get('only3d') === '1';
const chainId = parseInt(url.searchParams.get('chain') || '', 10);
- const q = (url.searchParams.get('q') || '').trim().slice(0, 80);
+ // Strip NUL and other C0/C1 control characters before the value reaches
+ // Postgres: a NUL or invalid byte in the search term throws "invalid byte
+ // sequence for encoding UTF8" (22021) out of the ILIKE query → an unhandled
+ // 500 on a public endpoint.
+ const q = (url.searchParams.get('q') || '')
+ // eslint-disable-next-line no-control-regex
+ .replace(/[\u0000-\u001F\u007F-\u009F]/g, '')
+ .trim()
+ .slice(0, 80);
const cursor = url.searchParams.get('cursor');
const limit = Math.min(Math.max(parseInt(url.searchParams.get('limit') || '24', 10), 1), 250);
const sourceFilter = url.searchParams.get('source') || 'all';
diff --git a/api/play-og.js b/api/play-og.js
index 8a8d91f25..b2772b9f0 100644
--- a/api/play-og.js
+++ b/api/play-og.js
@@ -49,9 +49,15 @@ function formatMarketCap(mc) {
}
function originOf(req) {
- const host = req.headers['x-forwarded-host'] || req.headers.host || 'three.ws';
- const proto = req.headers['x-forwarded-proto'] || 'https';
- return `${proto}://${host}`;
+ const rawHost = req.headers['x-forwarded-host'] || req.headers.host || 'three.ws';
+ // Host headers are client-supplied. A malformed value (spaces, control chars,
+ // multiple comma-joined hosts) makes the downstream `${origin}/api/pump/coin`
+ // an invalid URL and throws "Invalid URL". Keep only the first host and the
+ // characters legal in an authority; fall back to the canonical host otherwise.
+ const host = String(rawHost).split(',')[0].trim();
+ const safeHost = /^[a-zA-Z0-9.\-:]+$/.test(host) ? host : 'three.ws';
+ const proto = req.headers['x-forwarded-proto'] === 'http' ? 'http' : 'https';
+ return `${proto}://${safeHost}`;
}
async function fetchCoin(origin, mint) {
diff --git a/api/pump/[action].js b/api/pump/[action].js
index a8889f2c7..0de7526a1 100644
--- a/api/pump/[action].js
+++ b/api/pump/[action].js
@@ -860,7 +860,12 @@ const launchPrepSchema = z
creator_address: z.string().min(32).max(44).optional(),
name: z.string().trim().min(1).max(32),
symbol: z.string().trim().min(1).max(10),
- uri: z.string().url(),
+ // Bound the metadata URI so name(32)+symbol(10)+uri always fit inside
+ // Solana's 1232-byte transaction packet — an unbounded URI is what pushed
+ // the create message past the limit and threw "encoding overruns
+ // Uint8Array" at sign time. 200 matches pump.fun's own URI ceiling; the
+ // 413 guard at sign time remains as a defence-in-depth backstop.
+ uri: z.string().url().max(200),
network: z.enum(['mainnet', 'devnet']).default('mainnet'),
buyback_bps: z.number().int().min(0).max(10_000).default(0),
sol_buy_in: z.number().nonnegative().max(50).default(0), // SOL-paired initial buy, capped 50 SOL
@@ -1270,7 +1275,12 @@ const launchAgentSchema = z
avatar_id: z.string().uuid().optional(),
name: z.string().trim().min(1).max(32),
symbol: z.string().trim().min(1).max(10),
- uri: z.string().url(),
+ // Bound the metadata URI so name(32)+symbol(10)+uri always fit inside
+ // Solana's 1232-byte transaction packet — an unbounded URI is what pushed
+ // the create message past the limit and threw "encoding overruns
+ // Uint8Array" at sign time. 200 matches pump.fun's own URI ceiling; the
+ // 413 guard at sign time remains as a defence-in-depth backstop.
+ uri: z.string().url().max(200),
network: z.enum(['mainnet', 'devnet']).default('mainnet'),
buyback_bps: z.number().int().min(0).max(10_000).default(0),
sol_buy_in: z.number().nonnegative().max(50).default(0),
@@ -1404,13 +1414,31 @@ async function handleLaunchAgent(req, res) {
// Build a v0 transaction so we use the same SDK call path as launch-prep.
const { TransactionMessage, VersionedTransaction } = await import('@solana/web3.js');
const { blockhash } = await conn.getLatestBlockhash('confirmed');
- const msg = new TransactionMessage({
- payerKey: creator,
- recentBlockhash: blockhash,
- instructions,
- }).compileToV0Message();
- const vtx = new VersionedTransaction(msg);
- vtx.sign([agentKeypair, mintKeypair]);
+ // Compile + sign defensively. When the coin name/uri push the message past
+ // Solana's 1232-byte packet limit, compileToV0Message()/sign() throws a raw
+ // RangeError ("encoding overruns Uint8Array" / "Transaction too large") that
+ // would otherwise surface as an opaque 500. Convert it to a typed 413 with an
+ // actionable message instead.
+ let vtx;
+ try {
+ const msg = new TransactionMessage({
+ payerKey: creator,
+ recentBlockhash: blockhash,
+ instructions,
+ }).compileToV0Message();
+ vtx = new VersionedTransaction(msg);
+ vtx.sign([agentKeypair, mintKeypair]);
+ } catch (err) {
+ if (/too large|overruns/i.test(err?.message || '')) {
+ return error(
+ res,
+ 413,
+ 'launch_payload_too_large',
+ 'token launch transaction exceeds Solana size limits — shorten the token name or metadata URI',
+ );
+ }
+ throw err;
+ }
let signature;
try {
@@ -2705,7 +2733,19 @@ async function handleCoin(req, res) {
return error(res, 504, 'upstream_timeout', 'pump.fun did not respond');
}
if (!resp.ok) return error(res, 502, 'upstream_failed', `pump.fun returned ${resp.status}`);
- const [body] = repairCoinImages([await resp.json()]);
+ // pump.fun returns 200 with an empty body for an unknown/unmigrated mint;
+ // resp.json() then throws "Unexpected end of JSON input" → an unhandled 500.
+ // Treat an empty/invalid body as "coin not found" (404) instead.
+ let parsed;
+ try {
+ parsed = await resp.json();
+ } catch {
+ return error(res, 404, 'coin_not_found', 'no pump.fun coin for that mint');
+ }
+ if (!parsed || typeof parsed !== 'object') {
+ return error(res, 404, 'coin_not_found', 'no pump.fun coin for that mint');
+ }
+ const [body] = repairCoinImages([parsed]);
COIN_CACHE.set(mint, { at: now, body });
res.setHeader('cache-control', 'public, max-age=15');
return json(res, 200, body);
diff --git a/api/three-token/[action].js b/api/three-token/[action].js
index f7b697fef..de156ef75 100644
--- a/api/three-token/[action].js
+++ b/api/three-token/[action].js
@@ -25,19 +25,57 @@ const AGENT_DEPLOY_BURN = 1000;
const REVENUE_SHARE_POOL_PCT = 10;
const _cache = new Map();
+// How long a last-good value stays usable as a stale fallback after its TTL
+// expires. Birdeye rate-limits the shared key under bursty traffic; rather than
+// drop the price to null (and spam the error log) on every 429, we serve the
+// last good market data for up to STALE_MAX_MS while the limit clears. Token
+// price/market-cap drifting a couple of minutes is invisible to the UI; a blank
+// price panel is not.
+const STALE_MAX_MS = 5 * 60_000;
+
+// One warn per URL per cooldown so a sustained Birdeye 429 can't itself flood the
+// logs (the very failure mode brief 09 is about).
+const _staleWarnedAt = new Map();
+const STALE_WARN_COOLDOWN_MS = 60_000;
+function warnStaleOnce(url, status) {
+ const last = _staleWarnedAt.get(url) || 0;
+ const now = Date.now();
+ if (now - last < STALE_WARN_COOLDOWN_MS) return;
+ _staleWarnedAt.set(url, now);
+ console.warn(`[three-token] birdeye ${status} — serving last good value (stale) for ${url.split('?')[0]}`);
+}
async function cachedFetch(url, headers, ttlMs = 30_000) {
const now = Date.now();
const hit = _cache.get(url);
if (hit && hit.expires > now) return hit.value;
- const resp = await fetch(url, { headers });
+ let resp;
+ try {
+ resp = await fetch(url, { headers });
+ } catch (err) {
+ // Network failure — fall back to stale if we have a usable copy.
+ if (hit && now - hit.fetchedAt < STALE_MAX_MS) {
+ warnStaleOnce(url, 'fetch-failed');
+ return hit.value;
+ }
+ throw err;
+ }
if (!resp.ok) {
const text = await resp.text().catch(() => '');
+ // Rate-limited / upstream error: serve the last good value if it's still
+ // within the stale window instead of throwing and blanking the price.
+ if (hit && now - hit.fetchedAt < STALE_MAX_MS) {
+ warnStaleOnce(url, resp.status);
+ // Refresh the TTL briefly so we don't re-hit the limited endpoint on
+ // every request while it's throttled (cheap backoff).
+ hit.expires = now + Math.min(ttlMs, 15_000);
+ return hit.value;
+ }
throw new Error(`Birdeye ${resp.status}: ${text.slice(0, 200)}`);
}
const value = await resp.json();
- _cache.set(url, { value, expires: now + ttlMs });
+ _cache.set(url, { value, expires: now + ttlMs, fetchedAt: now });
if (_cache.size > 128) {
const oldest = _cache.keys().next().value;
_cache.delete(oldest);
diff --git a/api/tts/edge.js b/api/tts/edge.js
index 06b9eebbc..5a7fc9b9b 100644
--- a/api/tts/edge.js
+++ b/api/tts/edge.js
@@ -180,11 +180,24 @@ export default wrap(async (req, res) => {
}
// ── Synthesize via Microsoft Edge TTS ────────────────────────────────────
+ // Microsoft's unofficial Edge-TTS endpoint intermittently rejects the
+ // WebSocket upgrade with an HTTP 200 instead of a 101 ("Unexpected server
+ // response: 200") — a transient handshake failure that almost always clears
+ // on an immediate second attempt. Retry once before surfacing an error.
let audioBuffer;
- try {
- audioBuffer = await synthesize(voice, text, rate, pitch);
- } catch (synthErr) {
- console.error('[tts/edge] synthesis failed', synthErr);
+ let synthErr;
+ for (let attempt = 0; attempt < 2; attempt++) {
+ try {
+ audioBuffer = await synthesize(voice, text, rate, pitch);
+ synthErr = null;
+ break;
+ } catch (err) {
+ synthErr = err;
+ if (attempt === 0) await new Promise((r) => setTimeout(r, 250));
+ }
+ }
+ if (synthErr) {
+ console.error('[tts/edge] synthesis failed after retry', synthErr);
return error(res, 502, 'upstream_error', 'Edge TTS synthesis failed');
}
diff --git a/api/x402-pay/og.js b/api/x402-pay/og.js
index 98ac316c9..3d365c81b 100644
--- a/api/x402-pay/og.js
+++ b/api/x402-pay/og.js
@@ -1,9 +1,8 @@
// GET /api/x402-pay/og?tx=<signature>
-// Dynamic 1200×630 PNG card for /pay/calls/<tx> permalinks. When pasted into
+// Dynamic 1200×630 SVG card for /pay/calls/<tx> permalinks. When pasted into
// X / Slack / Discord / iMessage, the link expands to a branded summary of the
// paid x402 call (tool, amount, payer, timestamp).
-import sharp from 'sharp';
import { Redis } from '@upstash/redis';
import { env } from '../_lib/env.js';
import { logger } from '../_lib/usage.js';
diff --git a/docs/agent-briefs/PROD-errors-2026-06-05/10-cron-index-delegations-rpc.md b/docs/agent-briefs/PROD-errors-2026-06-05/10-cron-index-delegations-rpc.md
deleted file mode 100644
index 8248deca0..000000000
--- a/docs/agent-briefs/PROD-errors-2026-06-05/10-cron-index-delegations-rpc.md
+++ /dev/null
@@ -1,34 +0,0 @@
-# Brief 10 — index-delegations cron uses dead/limited public ETH RPC (~50 errors)
-
-## The errors
-```
-{"stage":"index-delegations","chainId":1,"error":"RPC eth_getLogs error: method not available"}
-{"stage":"index-delegations","chainId":1,"error":"RPC HTTP 429 from https://1rpc.io/eth"}
-{"stage":"index-delegations","chainId":1,"error":"RPC eth_getLogs error: block range extends beyond current head block"}
-{"stage":"index-delegations","chainId":1,"error":"RPC eth_getLogs error: You've reached the usage limit..."}
-{"stage":"index-delegations","chainId":1,"error":"fetch failed"}
-```
-Function: `/api/cron/[name]` → `index-delegations`.
-
-## Root cause
-The Ethereum mainnet (chainId 1) delegation indexer points at **free public RPCs (`1rpc.io/eth`
-and similar) that rate-limit (429), don't support `eth_getLogs`, or are flaky** (`fetch failed`).
-Plus the indexer requests a **block range beyond the current head**, meaning the cursor/`toBlock`
-math is wrong. So the cron silently fails to index delegations.
-
-## Required fix
-1. **Use a real, keyed RPC.** Replace the public endpoint with a proper provider
- (Alchemy/Infura/QuickNode) via env var (e.g. `ETH_RPC_URL` / `ETH_MAINNET_RPC_URL`). Confirm
- which env the indexer reads (`grep` the cron + delegation indexer lib) and set it in prod.
- Don't hardcode `1rpc.io`. Keep a sane fallback list but put the keyed provider first.
-2. **Fix the block-range math.** Clamp `toBlock` to `min(cursor+window, currentHead)` so it never
- exceeds the head. Page `eth_getLogs` in bounded ranges (e.g. ≤2k–10k blocks) to avoid provider
- limits. Persist the cursor only after a range succeeds so retries are idempotent
- (`indexer_state` table — see `specs/schema/indexer_state.sql`).
-3. **Backoff + don't crash the cron.** On 429/`fetch failed`, backoff and retry the same range
- next run; log structured progress. A transient RPC error must not lose the cursor.
-
-## Done when
-- `index-delegations` runs against a keyed RPC, pages within the head block, advances and persists
- its cursor, and logs success — no `method not available` / `beyond current head` / sustained 429.
-- Confirm the indexed delegations land in the DB (`agent_delegations`).
diff --git a/docs/agent-briefs/PROD-errors-2026-06-05/11-treasury-env-and-config.md b/docs/agent-briefs/PROD-errors-2026-06-05/11-treasury-env-and-config.md
deleted file mode 100644
index 6bddcb586..000000000
--- a/docs/agent-briefs/PROD-errors-2026-06-05/11-treasury-env-and-config.md
+++ /dev/null
@@ -1,31 +0,0 @@
-# Brief 11 — THREE_TREASURY_WALLET unset in production (34 errors)
-
-## The error
-```
-[api] unhandled Error: [token] THREE_TREASURY_WALLET is required in production
-— refusing to route treasury funds to an unset address.
-```
-Function: `/api/three-token/[action]` (and any token-routing path).
-
-## Root cause
-The token routing code correctly **fails closed** when `THREE_TREASURY_WALLET` is missing (good —
-do not weaken this guard), but the env var is **not set in the production Vercel environment**, so
-the feature is hard-down. This is a config gap, not a code bug.
-
-## Required fix
-1. Confirm the correct treasury wallet address with the user (the `$THREE` treasury). Set it:
- ```bash
- vercel env add THREE_TREASURY_WALLET production
- ```
- and redeploy. Verify `vercel env ls` shows it. Do **not** hardcode the address in source.
-2. Keep the fail-closed guard. Additionally, make the **user-facing** response a clean typed 503
- ("treasury temporarily unavailable") rather than an unhandled 500, so a future misconfig
- degrades gracefully.
-3. Audit sibling required-env guards for the same prod gap (`grep -rn "is required in production"
- api/`) and ensure each referenced var is actually set in prod. List any others you find for the
- user to populate.
-
-## Done when
-- `THREE_TREASURY_WALLET` is set in prod; the token route works end-to-end with the real treasury.
-- Missing required envs return a typed 503, never an unhandled 500.
-- No other `required in production` guard is silently tripping in the logs.
diff --git a/docs/agent-briefs/PROD-errors-2026-06-05/12-misc-hardening.md b/docs/agent-briefs/PROD-errors-2026-06-05/12-misc-hardening.md
deleted file mode 100644
index cb0024862..000000000
--- a/docs/agent-briefs/PROD-errors-2026-06-05/12-misc-hardening.md
+++ /dev/null
@@ -1,48 +0,0 @@
-# Brief 12 — Long-tail hardening (~40 errors across several small bugs)
-
-Each of these is low-volume but a real defect. Fix the source; add a boundary guard.
-
-## 12a. Empty / malformed JSON bodies → `SyntaxError: Unexpected end of JSON input` (7)
-- Root cause: a handler does `JSON.parse(body)` / `await req.json()` on an empty or non-JSON
- request body without a try/catch. Find the routes (the `[api] unhandled SyntaxError` rows) and
- parse defensively: validate `content-length`/content-type, wrap parse in try/catch, return
- **400** with a clear message on bad input. Never 500 on a malformed client body.
-
-## 12b. Vercel Runtime Timeout — 30s (27, mostly /api/chat, some elsewhere)
-- Mostly covered by Brief 03 for `/api/chat`. For any *other* route timing out, find the slow
- upstream/DB call and add a timeout + failover. No handler should be able to run the full 30s on
- a single unbounded await.
-
-## 12c. UTF-8 / encoding errors
-```
-NeonDbError: invalid byte sequence for encoding "UTF8": 0x.. (1)
-RangeError: encoding overruns Uint8Array (Solana — see Brief 08)
-```
-- Root cause: raw bytes/invalid UTF-8 reaching Postgres. Sanitize/normalize string inputs
- (strip null bytes, validate UTF-8) at the write boundary before they hit `sql\`...\``.
-
-## 12d. Fontconfig error (2)
-```
-Fontconfig error: Cannot load default config file: No such file: (null)
-```
-- Root cause: an OG-image / canvas / headless render path needs fonts but the lambda has no
- fontconfig. Bundle the font(s) the renderer needs and point `FONTCONFIG_PATH` / load the font
- explicitly so image generation doesn't warn/degrade. Find the render route (likely an `og`/image
- function) and make font loading explicit and self-contained.
-
-## 12e. ENOENT file open (2)
-```
-[api] unhandled Error: ENOENT: no such file or directory, open '...'
-```
-- Root cause: a handler reads a file that isn't included in the deployed bundle (Vercel NFT didn't
- trace it). Identify the file, and either inline its contents, mark it for inclusion via
- `vercel.json` `includeFiles`, or read it from a bundled import instead of `fs` at runtime.
-
-## 12f. `seed-default-agent` / `[audit] insert failed` (2 + 5)
-- These reference DB inserts failing — likely the same missing-table/migration class as Brief 04,
- or a constraint violation. Trace the failing insert, confirm the target table/columns exist in
- prod, and make the seed/audit path idempotent (`ON CONFLICT DO NOTHING`) so reruns don't error.
-
-## Done when
-- Each sub-item: the source bug is fixed, bad input returns a typed 4xx (not 500), and the log line
- no longer appears in a preview-deploy smoke test.
diff --git a/docs/agent-briefs/X-prod-errors-2026-06-05/DEPLOY-NOTES.md b/docs/agent-briefs/X-prod-errors-2026-06-05/DEPLOY-NOTES.md
new file mode 100644
index 000000000..ab6feae6d
--- /dev/null
+++ b/docs/agent-briefs/X-prod-errors-2026-06-05/DEPLOY-NOTES.md
@@ -0,0 +1,77 @@
+# Deploy notes — production error remediation (2026-06-05)
+
+All 12 fixes from [`prompts/`](prompts/) are implemented in the working tree. This file
+records (a) what shipped as code, and (b) the **operational actions** that must accompany the
+deploy — env vars and a migration that code alone can't set. Do the operational items or some
+fixes only half-land.
+
+## Code changes (this session)
+
+| Fix | Files | What changed |
+|-----|-------|--------------|
+| 01 | `api/_lib/text-extract.js`, `api/widgets/[id]/[action].js` | (already in tree) jsdom→`node-html-parser`; knowledge ingest dynamically imported & isolated. Verified clean. |
+| 02 | `api/_lib/rate-limit.js`, `api/_lib/cache.js` | (already in tree) `resilientLimiter` fails open (non-critical) / closed (money) on over-quota `UpstashError`; cache memo + memory fallback. Verified. |
+| 03 | `api/_lib/chat-models.js`, `api/chat.js` | (already in tree) reliability-first order, capability-aware routing, dead routes removed, bounded fallback. Verified. |
+| 04 | `api/_lib/migrations/20260605120000_usage_events.sql` (new), `api/agents.js` | New idempotent `usage_events` migration; `chat_count` query guarded so a missing table can't 500 the agent fetch. `forge_creations` already guarded + migration present. |
+| 05 | `api/_lib/market/ohlcv.js`, `api/ibm/oracle.js` | GeckoTerminal: retry-once on 429, preserve 429 status; oracle wraps all 3 upstream calls → clean 503/404/502. Birdeye path already cached + degrades. |
+| 06 | `api/brain/chat.js` | All OpenAI-compatible providers now use `.chat()` (Chat Completions) instead of the Responses API → fixes "Invalid Responses API request" / "unsupported content types"; adaptive retry parses "can only afford N" and re-streams within budget. |
+| 07 | `api/_lib/token/config.js` | `publicConfig()` reports `treasury_configured:false` instead of throwing; `treasuryWallet()` stays strict (now a typed 503) on fund-routing. |
+| 08 | `api/cron/[name].js` | `IDX_HEAD_CONFIRMATIONS` buffer (cross-RPC head-skew + reorg safety) fixes "block range extends beyond current head"; range/head errors now resume via cursor instead of erroring. RPC rotation/cursor/budget already present; `1rpc.io` already demoted to last. |
+| 09 | `src/solana/vanity/grinder-node.js`, `vercel.json`, `api/pump/[action].js` | `ensureWasm` resolves the WASM from multiple candidate paths (bundler-proof); explicit `api/pump/[action].js` function entry ships `src/solana/vanity/wasm/**` + `maxDuration:60`; `uri` bounded to 200 so the launch tx can't overrun 1232 bytes (413 guard already present). Grinder verified working locally. |
+| 10 | `api/agents/[id]/skills-pricing.js` | `sql.transaction()` rewritten to the Neon array contract (was the pg interactive callback). |
+| 11 | `api/x402-pay/og.js` | Serves SVG directly (no `sharp`/libvips) → kills the Fontconfig error. `play-og.js` and `agent-og.js` already guarded (fallback card / UUID validation). |
+| 12 | `api/_lib/db.js`, `api/tts/edge.js` | NUL bytes stripped from all string query params at the `sql` proxy boundary (fixes `0x00` UTF8 insert errors platform-wide); Edge-TTS retries once on the transient HTTP-200 handshake rejection. `llm/anthropic` double body-read already correct (each branch reads once). |
+
+## ⚠️ Operational actions required (not code)
+
+These are the half of the incident that is environment/quota, not logic. Each maps to a fix
+above.
+
+### 1. Apply the database migrations to production (Fix 04)
+The prod Neon DB is missing `usage_events` (and was missing `forge_creations`). Run the
+migration runner against the prod `DATABASE_URL`:
+```
+node scripts/run-migrations.mjs # uses DATABASE_URL from env
+```
+Confirm: `select to_regclass('public.usage_events'), to_regclass('public.forge_creations');`
+both non-null, and the rows appear in `schema_migrations`.
+
+### 2. Set `THREE_TREASURY_WALLET` in prod (Fix 07)
+The token fund-routing path fails closed without it. Set it to the **real `$THREE` treasury
+address** (confirm the value with the owner — do not invent one):
+```
+vercel env add THREE_TREASURY_WALLET production
+```
+Until set, `/api/token/config` now returns `treasury_configured:false` (clean) instead of 500,
+but any treasury fund-routing stays blocked by design.
+
+### 3. Upstash Redis quota (Fix 02)
+The monthly 500k-command cap was exhausted. Code now degrades gracefully, but to restore
+full rate-limiting/caching either **upgrade the Upstash plan** or keep usage under the cap.
+The cache memo + fail-open changes reduce burn; monitor `UpstashError` frequency post-deploy.
+
+### 4. LLM provider billing/quota (Fix 03 / 06)
+- **OpenAI** key is over quota ("exceeded your current quota") — top up billing or it stays a
+ dead final tier (it's already ranked last so it only costs one wasted attempt).
+- **OpenRouter** free tier credit ceiling drives the `brain/chat` "more credits" errors — the
+ adaptive retry handles it, but adding OpenRouter credits removes the degraded-budget path.
+
+### 5. Paid Ethereum RPC for the delegations cron (Fix 08)
+Public RPCs (`1rpc.io` etc.) 429 and don't all support `eth_getLogs`. Set a keyed RPC per
+chain so it's tried first (the code already honours these env overrides):
+```
+RPC_URL_1=<alchemy/infura mainnet url>
+RPC_URL_8453=<base url> # + testnet chains as needed
+```
+
+### 6. (Optional) Birdeye / market data keys (Fix 05)
+If a `BIRDEYE_API_KEY` is configured the three-token path uses the higher tier. GeckoTerminal
+is keyless; the retry + caching keep it under the free cap.
+
+## Verification after deploy
+Grep the next 24h of function logs — these signatures should be gone or near-zero:
+`ERR_REQUIRE_ESM`, `max requests limit exceeded` (as 500s), `Invalid Responses API request`,
+`relation "usage_events" does not exist`, `THREE_TREASURY_WALLET is required`,
+`transaction() expects an array`, `invalid byte sequence ... 0x00`,
+`vanity_grinder_bg.wasm` ENOENT, `encoding overruns Uint8Array`,
+`block range extends beyond current head`, `Fontconfig error`, `invalid input syntax for type uuid`.
diff --git a/public/features.json b/public/features.json
index f48688a77..f45a78e30 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-05T10:56:09.314Z",
+ "generated_at": "2026-06-05T11:18:33.111Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/solana/vanity/grinder-node.js b/src/solana/vanity/grinder-node.js
index 59a3b47a3..336b1c8fd 100644
--- a/src/solana/vanity/grinder-node.js
+++ b/src/solana/vanity/grinder-node.js
@@ -20,6 +20,8 @@
*/
import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { join } from 'node:path';
import { initSync, grind } from './wasm/vanity_grinder.js';
import { validatePattern, estimateAttempts, BASE58_ALPHABET } from './validation.js';
@@ -55,12 +57,50 @@ export class GrindExhaustedError extends Error {
// Lazily instantiate the WASM module once per process. `initSync` takes the
// raw bytes — no fetch, no top-level await — which is what we want in a
-// serverless cold start. The .wasm file is shipped alongside this module via
-// the route's `includeFiles` glob in vercel.json.
+// serverless cold start.
+//
+// Locating the .wasm at runtime is the subtle part. The natural
+// `new URL('./wasm/...', import.meta.url)` resolves relative to THIS module —
+// but when a large route (e.g. api/pump/[action].js) bundles grinder-node.js
+// inline, import.meta.url becomes the bundle's path and the lookup points at a
+// `wasm/` dir next to the route that nothing ships there
+// (ENOENT /var/task/api/pump/wasm/vanity_grinder_bg.wasm in prod). So we try a
+// list of candidate locations and use the first that exists:
+// 1. module-relative (works when this file ships unbundled);
+// 2. the repo source path under the function root (/var/task), which the
+// route's `includeFiles: "src/solana/vanity/wasm/**"` glob guarantees.
+// Whichever build strategy Vercel picks, one of these resolves.
+function readWasmBytes() {
+ const candidates = [];
+ try {
+ candidates.push(fileURLToPath(new URL('./wasm/vanity_grinder_bg.wasm', import.meta.url)));
+ } catch {
+ /* import.meta.url not a file URL in some bundlers — skip */
+ }
+ candidates.push(
+ join(process.cwd(), 'src/solana/vanity/wasm/vanity_grinder_bg.wasm'),
+ join(process.cwd(), 'dist/src/solana/vanity/wasm/vanity_grinder_bg.wasm'),
+ );
+
+ let lastErr;
+ for (const p of candidates) {
+ try {
+ return readFileSync(p);
+ } catch (err) {
+ lastErr = err;
+ }
+ }
+ throw Object.assign(
+ new Error(
+ `vanity grinder WASM not found in any known location (tried: ${candidates.join(', ')})`,
+ ),
+ { cause: lastErr, code: 'wasm_not_bundled' },
+ );
+}
+
function ensureWasm() {
if (wasmReady) return;
- const wasmPath = new URL('./wasm/vanity_grinder_bg.wasm', import.meta.url);
- initSync({ module: readFileSync(wasmPath) });
+ initSync({ module: readWasmBytes() });
wasmReady = true;
}
diff --git a/vercel.json b/vercel.json
index abe5b0469..6a2fabf2e 100644
--- a/vercel.json
+++ b/vercel.json
@@ -43,6 +43,10 @@
"includeFiles": "src/solana/vanity/wasm/**,examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json",
"maxDuration": 60
},
+ "api/pump/[action].js": {
+ "includeFiles": "src/solana/vanity/wasm/**,examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json",
+ "maxDuration": 60
+ },
"api/x402/pump-launch.js": {
"includeFiles": "examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json",
"maxDuration": 60