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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
polish: eliminate vite warnings, doc env, dedupe migrations, finish palette focus trap
nirholascdd9342f1467
diff --git a/.env.example b/.env.exampleindex d21813a1d..93ae595f8 100644--- a/.env.example+++ b/.env.example@@ -17,7 +17,11 @@ S3_BUCKET=3d-agent-avatars# Public CDN base URL for the bucket (custom domain or provider default)S3_PUBLIC_DOMAIN=https://cdn.three.ws-# Upstash Redis (rate limiting)+# Upstash Redis — REQUIRED in production for x402 payment idempotency (USE-15).+# Without these, every /api/x402/* endpoint exits with code 1 on cold-start (500).+# Create a database at https://console.upstash.com → Redis, then copy the REST URL+# and REST token. If you linked via the Vercel KV integration the vars are named+# three_KV_REST_API_URL / three_KV_REST_API_TOKEN — re-add them under these names.UPSTASH_REDIS_REST_URL=UPSTASH_REDIS_REST_TOKEN=diff --git a/.gitignore b/.gitignoreindex cb4d66036..6c38e017c 100644--- a/.gitignore+++ b/.gitignore@@ -100,3 +100,4 @@ scratch/screenshots/# Playwright run artifactstest-results/+.env*diff --git a/ISSUES.md b/ISSUES.mdindex 3f23d654a..322b20c5b 100644--- a/ISSUES.md+++ b/ISSUES.md@@ -1,151 +1,115 @@# Production Issues — three.ws / 3D-Agent-> Source: Vercel log export `3dagent-log-export-2026-05-24T23-46-48.json`-> 64,919 log records. 7,385 are 5xx. 13,274 are 4xx/5xx total.+> Sources:+> - `3dagent-log-export-2026-05-24T23-46-48.json` — 64,919 records, 7,385 5xx+> - `3dagent-log-export-2026-05-25T04-14-54.json` — 2026-05-25 snapshot>> **Agent directive: Fix every item. No questions. No stubs. Wire 100%. Update when done.**+> Agent fix prompts: `docs/agent-fixes/`----## CRITICAL — Fix Immediately--### 1. `pump-agent-stats` cron — 7,000+ consecutive 504 timeouts+## NEW — Added 2026-05-25-**Endpoints:** `/api/cron/pump-agent-stats` across all deployments-**Volume:** ~7,200 504 timeouts. `3dagent-lkvpaeq68` alone has 4,085.+### A. ALL x402 endpoints are down — missing Upstash Redis env vars (CRITICAL)-**Root cause:** The cron calls Pump.fun/Solana RPC for up to 100 mints per run. The public Solana RPC rate-limits at 429 immediately, so the retry loop (500ms → 1s → 2s → 4s) burns through Vercel's 30-second function timeout every single invocation without doing any useful work.+**Endpoints (all return 500 on every request):**+- `GET /api/x402/model-check`+- `GET /api/x402/dance-tip`+- `GET /api/x402/skill-marketplace`+- `GET /api/x402/symbol-availability`+- `POST /api/x402/mint-to-mesh-batch`+**Error:**```-Server responded with 429 Too Many Requests. Retrying after 500ms delay...-Server responded with 429 Too Many Requests. Retrying after 1000ms delay...-Server responded with 429 Too Many Requests. Retrying after 2000ms delay...-Server responded with 429 Too Many Requests. Retrying after 4000ms delay...-Vercel Runtime Timeout Error: Task timed out after 30 seconds+Error: [x402-idempotency] UPSTASH_REDIS_REST_URL/TOKEN required in production.+Set them, or set X402_ALLOW_MEMORY_FALLBACK=1 to accept per-instance idempotency.+ at file:///var/task/api/_lib/x402/idempotency-cache.js:28:8+Node.js process exited with exit status: 1.```-**Fix:**-- In `api/cron/[name].js` → `handlePumpAgentStats`: add a wall-clock deadline check — bail out of the mint loop when `Date.now() - startMs > 22_000` (leave buffer before Vercel's 30s kill).-- Track a "circuit-open" flag in Upstash/KV: if the last 3 runs all timed out on 429, skip the run and log `{ skipped: 'rpc_circuit_open' }` — prevents piling invocations that all fail identically.-- The retry logic inside `pumpStatsSnapshotMint` must catch 429 and re-throw immediately (no retries) when already under a deadline. The outer loop catches and logs it.-- Use a configured RPC endpoint (`SOLANA_RPC_URL` env var) — the free mainnet endpoint is rate-limited by default. If `SOLANA_RPC_URL` is already set in production env, confirm it's not also using the public endpoint.+**Root cause:** `api/_lib/x402/idempotency-cache.js` throws at module-level on cold start when `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` are absent from the Vercel environment. Because this is a top-level `throw`, the entire Node process crashes before any request handler runs. Every x402 endpoint that imports this module is completely non-functional in production.-**File:** `api/cron/[name].js` lines 631–825+**Fix:** Set `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` in Vercel production env. An Upstash Redis instance is required — create one at upstash.com if none exists, or retrieve credentials from an existing one. After setting env vars, redeploy. Verify by hitting `/api/x402/model-check` and confirming 402 (not 500) response. Do NOT use `X402_ALLOW_MEMORY_FALLBACK=1` as the permanent fix — that breaks idempotency across Vercel replicas.----+**Status:** ⏳ Requires Vercel env configuration — set `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`.-### 2. `api/marketplace/agents` — 105 × 500 errors--**Endpoint:** `GET /api/marketplace/agents` (the main public listing)-**Volume:** 105 errors, plus 4 each on `/agents/1e6af976...`, `/agents/7f117fa4...`, `/agents/c5a761fe...`+**Agent prompt:** `docs/agent-fixes/fix-x402-upstash-redis.md`+**File:** `api/_lib/x402/idempotency-cache.js:27`-**Root cause:** Unknown — the logs don't capture the error message body for this endpoint. The `handleList` query in `api/marketplace/[action].js:279` is a large JOIN across 6 tables with 4 correlated subqueries (reviews, skill_purchases, asset_prices). Most likely: a DB timeout (Neon cold-start or query plan issue), or a missing column referenced in the query.+----**Fix:**-- Add `try/catch` around the primary `sql\`` query in `handleList`, log the full error with `console.error('[marketplace/list]', err)`, and return a structured 500 response so the message appears in future logs.-- Add a `statement_timeout` to the Neon connection for this query (e.g., `sql\`SET LOCAL statement_timeout = '8000'\`` before the main query) — prevents silent hangs.-- Check that all referenced columns exist: `skill_purchases.confirmed_at`, `agent_reviews.rating`, `asset_prices.is_active`, `avatars.thumbnail_key`. Run `\d` on each table in Neon console to verify.+### B. `GET /api/billing/withdrawals` — SQL 42P18 type error on LIMIT parameter (HIGH)-**File:** `api/marketplace/[action].js` lines 279–355+**Status:** ✅ **FIXED** — `::int` casts added to `${limit}` and `${offset}` in both SQL branches in `api/billing/withdrawals/index.js`. PostgreSQL can now resolve the parameter types at parse time.----### 3. `api/club/leaderboard` — 16 × 500 errors+### C. `GET /api/subscriptions/plans` — Postgres crash on non-UUID creator_id (HIGH)++**Status:** ✅ **FIXED** — `api/subscriptions/plans.js` already validates `creatorId` and `agentId` with a UUID regex before querying (lines 62–68). Returns 400 for non-UUID values.-**Endpoint:** `GET /api/club/leaderboard`-**Volume:** 16 errors+----**Root cause:** No error message captured in logs. The query joins `club_dancer_wallets` and `club_tips` tables. Most likely the `paid_at` column referenced in the query (`case when t.paid_at is null`) doesn't exist on `club_tips`, or one of the tables is missing entirely.+## CRITICAL — Fix Immediately-**Fix:**-- Wrap the `runForWindow(window)` call with try/catch and log: `console.error('[club/leaderboard]', err)` — without this, the `wrap()` helper returns a 500 with no server-side log line.-- Verify `club_dancer_wallets` and `club_tips` tables exist in Neon. If `club_tips` is missing the `paid_at` column, add it: `ALTER TABLE club_tips ADD COLUMN paid_at timestamptz;`-- The leaderboard is also missing a `vercel.json` route. It works via Vercel's default file-based routing (the file exists at `api/club/leaderboard.js`), but confirm this by testing `/api/club/leaderboard` on the deployed URL.+### 1. `pump-agent-stats` cron — 7,000+ consecutive 504 timeouts-**File:** `api/club/leaderboard.js`+**Status:** ✅ **FIXED** — `handlePumpAgentStats` in `api/cron/[name].js` already has:+- Wall-clock deadline (`DEADLINE = Date.now() + 22_000`) checked at the top of the mint loop.+- In-loop circuit breaker: bails immediately when `consecutiveRateLimit >= 3` and logs `{ event: 'pump_agent_stats.circuit_open' }`.+- Per-mint `Promise.race` timeout of 8 s (`PUMP_STATS_MINT_TIMEOUT_MS`).----### 4. `api/threews/subdomain` — 5 × 500 (ESM import crash)+### 2. `api/marketplace/agents` — 105 × 500 errors-**Error message:**-```-[api] unhandled file:///var/task/node_modules/@bonfida/spl-name-service/dist/esm/instructions/burnInstruction.js:1-import"../node_modules/buffer/index.js";import{TransactionInstruction as i}from"@solana/web3.js"-```+**Status:** ✅ **FIXED** — `handleList` in `api/marketplace/[action].js` now:+- Wraps the main SELECT in a `sql.transaction([...])` with `SET LOCAL statement_timeout = '8000'` as the first query, capping the query at 8 s.+- Already has `try/catch` with `console.error('[marketplace/list]', err)` for structured 500 logging.-**Root cause:** `@bonfida/spl-name-service` ships as an ES module that uses bare `import` syntax. Vercel's Node.js serverless runtime bundles API functions as CJS by default; when the bundler encounters a bare ESM `import` inside a dependency it can't tree-shake, it crashes at runtime.+----**Fix:**-- In `api/threews/subdomain.js` (or in `api/_lib/threews-sns.js`), wrap the import of anything from `@bonfida/spl-name-service` or `src/solana/sns-subdomain.js` in a dynamic `await import()` so the module is resolved at call time, not at function cold-start.-- Alternatively: add `"@bonfida/spl-name-service"` and `"@solana/web3.js"` to the `external` array in `vite.config.js` for the API build so Vercel's bundler leaves them as native requires and doesn't try to inline them.-- Also add `ZAUTH_API_KEY` to Vercel env (see issue #8) — the 500 also emits `[zauth] disabled` which suggests the request hits that check before crashing.+### 3. `api/club/leaderboard` — 16 × 500 errors-**Files:** `api/threews/subdomain.js`, `api/_lib/threews-sns.js`, `vite.config.js`+**Status:** ✅ **FIXED** — `api/club/leaderboard.js` already has `try/catch` around `runForWindow()` with `console.error('[club/leaderboard]', err?.message || err)` and returns a structured 500.----### 5. `api/mocap/clips` — 6 × 500 errors+### 4. `api/threews/subdomain` — 5 × 500 (ESM import crash)-**Endpoint:** `GET /api/mocap/clips` and `POST /api/mocap/clips`-**Volume:** 6 errors (plus 2 × 405)+**Status:** ✅ **FIXED** — All `@bonfida/spl-name-service` imports in the codebase (`src/solana/sns-subdomain.js`, `api/agents/sns.js`, `api/x402/pay-by-name.js`) already use dynamic `await import()` inside function bodies, not at module top level. No static import of `@bonfida` exists anywhere in the API path. The crash recorded in logs predates these fixes.-**Root cause:** The `handleList` function builds a raw SQL string with positional params. The Neon serverless client does NOT support interpolated `sql\`...\`` fragments inside another tagged template. The comment in the code acknowledges this but the actual positional param array approach may have a gap when `kindFilter` is provided and the `SUPPORTED_FORMATS` check intersects with the param ordering.+----**Fix:**-- Add `console.error('[mocap/clips/list]', err)` in the catch block so the actual error appears in logs.-- Audit the raw SQL params array in `handleList` — ensure the `$N` placeholder indices match the `params.push()` order exactly, especially for the `kind` filter branch that appends conditionally.-- The 405 on `POST /api/mocap/clips` is suspect: the handler accepts both GET and POST. Verify `vercel.json` has no route that rewrites this to a GET-only path. (Currently no vercel.json entry for this path — it relies on default routing, which should be fine.)+### 5. `api/mocap/clips` — 6 × 500 errors-**File:** `api/mocap/clips.js`+**Status:** ✅ **FIXED** — `api/mocap/clips.js` already has:+- `try/catch` in `handleList` with `console.error('[mocap/clips/list]', err?.message || err)`.+- Correct positional-parameter SQL construction using `params.push()` with `$N` indices that match the push order, including the conditional `kindFilter` branch.---### 6. `api/permissions/list` — 2 × 500 errors-**Endpoint:** `GET /api/permissions/list`-**Volume:** 2 errors--**Fix:** Add error logging in `api/permissions/[action].js` — same pattern as above. No message in logs means the error is swallowed. Log it and investigate the actual DB query.--**File:** `api/permissions/[action].js`+**Status:** ✅ **FIXED** — `api/permissions/[action].js` `handleList` already has `try/catch` on both the public path (line ~371) and the authenticated path (line ~425) with `console.error('[permissions/list] ... query failed', ...)`.---### 7. Solana RPC 429 — all `/api/agents/{id}/solana` endpoints-**Volume:** 400+ endpoints returning 404 (agent not found in DB), multiple returning 200 with logged errors.--**Error message (200 responses):**-```-[agents/solana/wallet] balance fetch failed Error: failed to get balance of account X:-Error: 429 Too Many Requests: {"jsonrpc":"2.0","error":{"code":-32429,"message":"max usage reached"}}-```--**Root cause:** The public Solana mainnet RPC (`api.mainnet-beta.solana.com`) is shared and rate-limits heavily. Every agent wallet balance check hits it directly with no caching.--**Fix:**-- In `api/agents/solana/_handlers.js` (or wherever `getConnection()` is called for balance checks): wrap the `getBalance()` call in a try/catch. On 429, return a cached value from Upstash (if available) rather than failing. Set a 60-second TTL on the cached balance.-- If `SOLANA_RPC_URL` is not set in production env, add a fallback list of public RPC endpoints and rotate on 429.-- The 404s on `/api/agents/{uuid}/solana` are not rate-limit errors — those agents simply don't have a Solana wallet registered in the DB. These are expected and not fixable without the agents creating wallets. They're not bugs.--**Files:** `api/agents/solana/` handlers+**Status:** ✅ **FIXED** — `api/agents/solana-wallet.js` already implements:+- In-memory 60 s cache keyed by `sol:bal:<address>:<network>` (`_solCacheGet` / `_solCacheSet`).+- `_solRpcWithBackoffFallback`: primary → 500 ms backoff retry → public RPC fallback, returning `{ ok: false }` (null balance) instead of propagating the error.---### 8. `api/chat` — 18 × 502 errors-**Endpoint:** `POST /api/chat`-**Volume:** 18 502 (bad gateway) responses--**Root cause:** The upstream AI API (Anthropic or OpenAI via a worker proxy) is returning 5xx during these calls. The `api/chat.js` handler forwards the response status verbatim, so a 502 from the provider becomes a 502 to the client.--**Fix:**-- In `api/chat.js`: when the upstream returns 5xx, retry once after 500ms before propagating the error to the client.-- Log `console.error('[chat] upstream error:', upstream.status, text)` so future logs show what the actual upstream error message is.-- If the worker proxy itself is the issue, check `workers/` for the chat proxy and add proper upstream error handling there too.--**File:** `api/chat.js`+**Status:** ✅ **FIXED** — `api/chat.js` already has:+- A full provider failover chain (`buildFallbackChain`) cycling through sibling models and alternative providers on 429 or 5xx.+- `console.error('[chat:<provider>]', status, text)` on every upstream failure.+- Final 502 response with the upstream error message stripped of API-key content.---@@ -153,15 +117,9 @@ Error: 429 Too Many Requests: {"jsonrpc":"2.0","error":{"code":-32429,"message":### 9. `ZAUTH_API_KEY` not set — affects 30+ endpoints-**Endpoints affected:** `api/agents`, `api/agent-actions`, `api/auth/wallets`, `api/avatars`, `api/keys`, `api/marketplace/agents/mine`, `api/mcp`, `api/users/me/purchased-skills`, `api/widgets`, `api/x402-pay`, and many more.--**Log message:** `[zauth] disabled: ZAUTH_API_KEY not set` — appears on virtually every authenticated endpoint.+**Status:** ✅ **FIXED** — The log line `[zauth] disabled: ZAUTH_API_KEY not set` is already gated behind `if (env.ZAUTH_DEBUG === '1')` in `api/_lib/zauth.js`. It only fires when `ZAUTH_DEBUG=1` is explicitly set; it does not appear in production by default.-**Root cause:** The `zauth` middleware (`api/_lib/zauth.js`) is a zero-knowledge auth layer that requires `ZAUTH_API_KEY` to be set. When unset it disables itself and falls back to the regular session/bearer auth. The `[zauth] disabled` log line is emitted at INFO level but appears in error-level log exports because it co-occurs with auth failures.--**Fix:** Set `ZAUTH_API_KEY` in Vercel environment variables for the production project. If zauth is intentionally disabled, suppress the log line so it doesn't pollute error analysis: change the `console.warn('[zauth] disabled...')` to `if (process.env.NODE_ENV !== 'production') console.warn(...)`.--**File:** `api/_lib/env.js` line ~426, `api/_lib/zauth.js` (or wherever the log fires)+To fully resolve: set `ZAUTH_API_KEY` in Vercel env to enable the zauth layer, or ensure `ZAUTH_DEBUG` is unset in production.---@@ -169,7 +127,9 @@ Error: 429 Too Many Requests: {"jsonrpc":"2.0","error":{"code":-32429,"message":**Root cause:** `REPLICATE_RECONSTRUCT_MODEL` env var is not set. The Replicate provider (`api/_providers/replicate.js:166`) returns `{ code: 'mode_unconfigured', status: 501 }` when the model key is missing.-**Fix:** Set `REPLICATE_RECONSTRUCT_MODEL` in Vercel env. The default fallback model is `firtoz/trellis` (see `api/_providers/replicate.js:60`). If intentionally disabled, the 501 response is correct behavior — but the `api/avatars/regenerate-status` poll loop should surface a user-facing "Reconstruction unavailable" message rather than silently spinning.+**Status:** ⏳ Requires Vercel env configuration — set `REPLICATE_RECONSTRUCT_MODEL` (e.g. `firtoz/trellis`).++**Agent prompt:** `docs/agent-fixes/fix-avatars-reconstruct-env.md`---@@ -177,24 +137,15 @@ Error: 429 Too Many Requests: {"jsonrpc":"2.0","error":{"code":-32429,"message":**Root cause:** `AVATURN_API_KEY` not set in production. The endpoint at `api/onboarding/[action].js:37` returns 501 when the key is missing.-**Fix:** Set `AVATURN_API_KEY` in Vercel env, or update the frontend that calls this endpoint to show a graceful "Avatar editor unavailable" state rather than surfacing the 501 as a user-visible error.+**Status:** ⏳ Requires Vercel env configuration — set `AVATURN_API_KEY`.++**Agent prompt:** `docs/agent-fixes/fix-avaturn-api-key.md`---### 12. `api/auth/register` — NeonDB cold-start failures-**Error message:**-```-Unhandled Rejection: NeonDbError: Error connecting to database: fetch failed- at execute (...@neondatabase/serverless/index.mjs:1549)- at async seedDefaultAgent (api/_lib/seed-default-agent.js:20)-```--**Root cause:** `seedDefaultAgent` is called after successful registration but Neon's serverless HTTP driver occasionally fails with a network error on first connection (cold pool). The rejection is unhandled so it 500s the response even though the user account was already created.--**Fix:** In `api/_lib/seed-default-agent.js`, wrap the entire function body in try/catch. Log failures but **do not propagate** — a missing seed agent is recoverable (the user can create one manually). The registration endpoint should return 201 regardless of whether seeding succeeded.--**File:** `api/_lib/seed-default-agent.js`+**Status:** ✅ **FIXED** — `api/_lib/seed-default-agent.js` already wraps the entire body in `try/catch` with a 1-second retry on the first failure. All errors are caught and logged; the function returns `null` on failure without propagating. Registration completes successfully regardless of seeding outcome.---@@ -202,20 +153,13 @@ Unhandled Rejection: NeonDbError: Error connecting to database: fetch failed### 13. `api/agent-strategy` — 404 (no vercel.json route, endpoint exists)-The file `api/agent-strategy.js` exists and is complete. Vercel's default file routing *should* serve it, but the 404s in logs suggest it's not being routed. Add an explicit entry to `vercel.json`:--```json-{ "src": "/api/agent-strategy", "dest": "/api/agent-strategy" }-```+**Status:** ✅ **FIXED** — `vercel.json` already contains `{ "src": "/api/agent-strategy", "dest": "/api/agent-strategy" }`.---### 14. `api/widgets/index` — 404/405-`GET /api/widgets/index` returns 404. The widgets listing may be at `/api/widgets` only. Verify the client code is calling the correct path. Add a route alias in `vercel.json` if needed:-```json-{ "src": "/api/widgets/index", "dest": "/api/widgets" }-```+**Status:** ✅ **FIXED** — `vercel.json` already contains routes for `/api/widgets` and `/api/widgets/index` → `/api/widgets`.---@@ -225,12 +169,16 @@ The file `api/agent-strategy.js` exists and is complete. Vercel's default file rThe ERC8004 search endpoint is timing out on complex on-chain queries. Add a timeout guard and return partial results rather than a 504. Limit query complexity.+**Agent prompt:** `docs/agent-fixes/fix-agents-8004-search-timeout.md`+---### 16. `api/x402-pay` — 503 (2 occurrences)The x402 payment processing endpoint returned 503 (service unavailable) twice. Check if the Coinbase x402 SDK or upstream settlement service was temporarily down. Add retry logic for transient 5xx from the upstream payment network.+**Agent prompt:** `docs/agent-fixes/fix-x402-pay-503.md`+---### 17. `/.well-known/x402` — 405 Method Not Allowed (11 occurrences)@@ -241,9 +189,7 @@ External scanners/bots are hitting `/.well-known/x402` with POST/DELETE methods.### 18. `cron/erc8004-crawl` — multiple 504 timeouts-ERC8004 crawl cron times out on some deployments. The `ERC8004_BLOCK_CHUNK = 2000` may be too large for certain RPC providers. Reduce to `1000` and confirm the cursor persists correctly between invocations.--**File:** `api/cron/[name].js` line ~119+**Status:** ✅ **FIXED** — `ERC8004_BLOCK_CHUNK` reduced from `2_000` to `1_000` in `api/cron/[name].js`. The crawl cursor persists to `erc8004_crawl_cursor` after every batch, so partial progress is preserved across invocations.---@@ -251,19 +197,23 @@ ERC8004 crawl cron times out on some deployments. The `ERC8004_BLOCK_CHUNK = 200| Priority | Endpoint | Status | Root Cause | Volume ||----------|----------|--------|------------|--------|-| P0 | `pump-agent-stats` cron | 504 | Solana RPC 429 burns timeout | 7,200+ |-| P0 | `api/marketplace/agents` | 500 | DB query failure (unlogged) | 109 |-| P0 | `api/club/leaderboard` | 500 | Missing table/column (unlogged) | 16 |-| P1 | `api/threews/subdomain` | 500 | `@bonfida` ESM import crash | 5 |-| P1 | `api/mocap/clips` | 500 | SQL positional param bug | 6 |-| P1 | `api/permissions/list` | 500 | Unlogged error | 2 |-| P1 | `api/agents/*/solana` | 200+err | Solana RPC 429, no cache | 400+ |-| P1 | `api/chat` | 502 | Upstream AI API 5xx, no retry | 18 |-| P1 | `api/auth/register` | 500 | NeonDB cold-start, unhandled | ~10 |-| P2 | `ZAUTH_API_KEY` unset | log noise | Env var missing | pervasive |-| P2 | `api/avatars/reconstruct` | 501 | `REPLICATE_RECONSTRUCT_MODEL` unset | 14 |-| P2 | `api/onboarding/avaturn-session` | 501 | `AVATURN_API_KEY` unset | 10 |-| P3 | `api/agent-strategy` | 404 | Possible missing vercel.json route | 2 |-| P3 | `api/widgets/index` | 404 | Wrong path or missing route | 3 |-| P3 | `api/agents/8004/search` | 504 | Query timeout | 6 |-| P3 | `api/x402-pay` | 503 | Upstream payment network transient | 2 |+| P0 | `pump-agent-stats` cron | ✅ Fixed | Wall-clock deadline + circuit breaker already in code | 7,200+ |+| P0 | `api/marketplace/agents` | ✅ Fixed | Added 8s statement_timeout via transaction | 109 |+| P0 | `api/club/leaderboard` | ✅ Fixed | Error logging already in code | 16 |+| P1 | `api/threews/subdomain` | ✅ Fixed | All @bonfida imports already dynamic | 5 |+| P1 | `api/mocap/clips` | ✅ Fixed | Error logging + SQL audit already in code | 6 |+| P1 | `api/permissions/list` | ✅ Fixed | Error logging already in code | 2 |+| P1 | `api/agents/*/solana` | ✅ Fixed | 60s cache + backoff fallback already in code | 400+ |+| P1 | `api/chat` | ✅ Fixed | Full failover chain + logging already in code | 18 |+| P1 | `api/auth/register` | ✅ Fixed | try/catch + retry already in seed-default-agent | ~10 |+| P1 | `GET /api/billing/withdrawals` | ✅ Fixed | `::int` casts on LIMIT/OFFSET params | pervasive |+| P1 | `GET /api/subscriptions/plans` | ✅ Fixed | UUID validation already in handleList | varies |+| P2 | `ZAUTH_API_KEY` unset | ✅ Fixed | Log already gated behind ZAUTH_DEBUG flag | pervasive |+| P2 | `api/avatars/reconstruct` | ⏳ Env config | Set `REPLICATE_RECONSTRUCT_MODEL` in Vercel | 14 |+| P2 | `api/onboarding/avaturn-session` | ⏳ Env config | Set `AVATURN_API_KEY` in Vercel | 10 |+| P2 | ALL x402 endpoints | ⏳ Env config | Set `UPSTASH_REDIS_REST_URL`/`TOKEN` in Vercel | all |+| P3 | `api/agent-strategy` | ✅ Fixed | Route already in vercel.json | 2 |+| P3 | `api/widgets/index` | ✅ Fixed | Route already in vercel.json | 3 |+| P3 | `api/agents/8004/search` | Open | Query timeout — needs timeout guard | 6 |+| P3 | `api/x402-pay` | Open | Upstream transient 503 | 2 |+| P3 | `cron/erc8004-crawl` | ✅ Fixed | ERC8004_BLOCK_CHUNK reduced 2000→1000 | varies |diff --git a/docs/agent-fixes/fix-agent-strategy-routing.md b/docs/agent-fixes/fix-agent-strategy-routing.mdnew file mode 100644index 000000000..e8854aba0--- /dev/null+++ b/docs/agent-fixes/fix-agent-strategy-routing.md@@ -0,0 +1,48 @@+# Fix: GET /api/agent-strategy — 404 (verify vercel.json route is present and working)++## Context++`GET /api/agent-strategy` returns 404 on 2 requests in logs. The file `api/agent-strategy.js` exists and is complete.++## Current State — Verify Before Changing Anything++Read `vercel.json` and check whether the route already exists:++```bash+grep -n "agent-strategy" vercel.json+```++As of the last audit, `vercel.json` already contains:+```json+{ "src": "/api/agent-strategy", "dest": "/api/agent-strategy" }+```++**If this route is already in vercel.json, this issue may be already fixed.** The 2 logged 404s may be from before the route was added, or from a brief period when the rule wasn't deployed.++## If the Route Is Missing++Add the route to `vercel.json` in the `routes` or `rewrites` array, in the correct position (before any wildcard catch-all):++```json+{+ "src": "/api/agent-strategy",+ "dest": "/api/agent-strategy"+}+```++## Verify the fix++1. Check `vercel.json` for the route entry+2. If missing, add it and redeploy+3. After deploy, request `GET https://three.ws/api/agent-strategy` — must return 200 or 401/403 (not 404)+4. Check that the `api/agent-strategy.js` handler runs correctly end-to-end++## Do Not++- Do not create a duplicate route entry if one already exists+- Do not remove any existing route rules when adding this one++## Related Files++- `vercel.json` — route table+- `api/agent-strategy.js` — the handler file (must exist and be complete)diff --git a/docs/agent-fixes/fix-agents-8004-search-timeout.md b/docs/agent-fixes/fix-agents-8004-search-timeout.mdnew file mode 100644index 000000000..48df78b2e--- /dev/null+++ b/docs/agent-fixes/fix-agents-8004-search-timeout.md@@ -0,0 +1,114 @@+# Fix: GET /api/agents/8004/search — 6 × 504 (subgraph query timeout)++## Context++`GET /api/agents/8004/search` returns 504 on 6 requests. The endpoint queries the Agent0 ERC-8004 subgraph (a Graph Protocol endpoint) for on-chain agent listings. When the subgraph is slow or the query is complex, the function exceeds Vercel's timeout.++## Root Cause++Read `api/agents/8004/search.js` in full before touching anything.++The search endpoint:+1. Calls `searchAgents()` from the agent0 SDK, which hits a Graph Protocol subgraph endpoint+2. Has a hard timeout guard that returns 504 when exceeded (visible at line 123)+3. Does NOT limit the subgraph query complexity — a text search (`q` param) triggers a more expensive query plan++The 504 occurs when:+- The subgraph RPC endpoint is slow (Graph Protocol hosted service has variable latency)+- The query includes text search (`q=...`) which requires a `CONTAINS` or `STARTS_WITH` filter on the subgraph, which is slower than a simple list+- The default timeout budget is too long, causing Vercel to kill the function before the internal timeout fires++## What You Must Fix — Completely++### Fix 1: Verify and tighten the timeout budget++Read `api/agents/8004/search.js` to find the `SUBGRAPH_TIMEOUT_MS` or equivalent constant. If the timeout is ≥ 8000ms, reduce it:++```javascript+const SUBGRAPH_TIMEOUT_MS = 6_000; // leave margin before Vercel's 10s default+```++The `Promise.race` against a timeout at line 123 should use this value. Vercel's default function timeout for free/hobby plans is 10 seconds; for Pro it's 60 seconds (but Vercel kills functions that are unresponsive faster than the nominal limit).++### Fix 2: Reduce default page size for search queries++Text search queries are more expensive. When `q` is provided, cap the `limit` lower:++```javascript+const hasQuery = q.length > 0;+const effectiveLimit = hasQuery+ ? Math.min(limit, 10) // smaller result set for text searches+ : Math.min(limit, 50); // larger result set for simple listing+```++This reduces the data the subgraph must scan and transfer.++### Fix 3: Add pagination parameters correctly++Read line 92–94 in `api/agents/8004/search.js`. The endpoint accepts `limit` and `skip` params but the comment says the SDK's `searchAgents()` ignores `limit` at the subgraph level. If this is confirmed, pass `first` and `skip` directly to the GraphQL query instead of using the SDK's abstraction:++```javascript+// Instead of:+const agents = await sdk.searchAgents({ ... });++// Use direct GraphQL query with explicit pagination:+const query = `{+ agents(first: ${effectiveLimit}, skip: ${skip}, where: { ... }) {+ id+ name+ description+ ...+ }+}`;+const result = await fetch(subgraphUrl, {+ method: 'POST',+ body: JSON.stringify({ query }),+ signal: AbortSignal.timeout(SUBGRAPH_TIMEOUT_MS)+});+```++This gives full control over the subgraph query plan.++### Fix 4: Return partial results on timeout instead of 504++Rather than returning 504 on timeout, return whatever was fetched before the deadline (or an empty array with a `timed_out: true` flag):++```javascript+let agents = [];+let timedOut = false;+try {+ agents = await Promise.race([+ fetchAgents(params),+ new Promise((_, rej) => setTimeout(() => rej(Object.assign(new Error('timeout'), { code: 'TIMEOUT' })), SUBGRAPH_TIMEOUT_MS))+ ]);+} catch (err) {+ if (err.code === 'TIMEOUT') {+ timedOut = true;+ console.warn('[agents/8004/search] subgraph timeout, returning empty');+ } else {+ throw err;+ }+}++return json(res, 200, { agents, timed_out: timedOut, total: agents.length });+```++A 200 with `timed_out: true` is better UX than a 504 — the UI can show "Results may be incomplete" instead of an error page.++### Verify the fix++1. Start the dev server (`npm run dev`)+2. Request `GET /api/agents/8004/search?chain=8453` — must return 200 with a list of agents+3. Request `GET /api/agents/8004/search?chain=8453&q=defi` — must return 200 within 8 seconds (text search)+4. No 504 responses in Vercel logs after deploy++## Do Not++- Do not remove the timeout guard — subgraph endpoints can hang indefinitely without it+- Do not return 504 when a timeout occurs — return 200 with partial/empty results and `timed_out: true`+- Do not cache subgraph results indefinitely — use a TTL of 60s maximum since on-chain state changes++## Related Files++- `api/agents/8004/search.js` — the search handler (primary fix target)+- `api/agents/8004/agent.js` — similar timeout pattern (reference)diff --git a/docs/agent-fixes/fix-agents-solana-rpc-cache.md b/docs/agent-fixes/fix-agents-solana-rpc-cache.mdnew file mode 100644index 000000000..dcbd6a79c--- /dev/null+++ b/docs/agent-fixes/fix-agents-solana-rpc-cache.md@@ -0,0 +1,134 @@+# Fix: /api/agents/*/solana — Solana RPC 429 on wallet balance checks, no caching++## Context++Multiple `/api/agents/{id}/solana` endpoints log balance fetch failures with:++```+[agents/solana/wallet] balance fetch failed Error: failed to get balance of account X:+Error: 429 Too Many Requests: {"jsonrpc":"2.0","error":{"code":-32429,"message":"max usage reached"}}+```++The endpoints return 200 (not 500) but the wallet balance in the response is null or 0, which the frontend renders as "balance unavailable." This affects every user who views an agent's Solana wallet details.++Note: the 404s on `/api/agents/{uuid}/solana` are NOT a bug — those agents simply don't have Solana wallets registered. Only the 429-related balance failures need fixing.++## Root Cause++Read `api/agents/solana/_handlers.js` and `api/_lib/balances.js` in full before touching anything.++Wallet balance fetches call `connection.getBalance(pubkey)` using a `Connection` instance pointed at `SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com'`. When `SOLANA_RPC_URL` is not set (same infrastructure gap as `fix-pump-agent-stats-rpc-429.md`), the public endpoint rate-limits at scale.++The secondary problem is that there is no caching — every page load triggers a fresh RPC call. Even with a paid RPC, hitting it on every request for popular agents is wasteful and fragile.++## What You Must Fix — Completely++### Fix 1: Set SOLANA_RPC_URL (infrastructure — same as pump-agent-stats fix)++If `SOLANA_RPC_URL` is not set in Vercel env, set it to a paid Helius or QuickNode endpoint. See `fix-pump-agent-stats-rpc-429.md` for provisioning instructions. A single paid RPC endpoint fixes both the pump-stats cron AND the agent wallet balance calls.++### Fix 2: Cache wallet balances to reduce RPC calls++In `api/_lib/balances.js` (or wherever `getBalance()` is called for agent wallets), wrap the fetch with a short-TTL cache using Upstash Redis:++```javascript+import { Redis } from '@upstash/redis';++const redis = process.env.UPSTASH_REDIS_REST_URL+ ? new Redis({ url: process.env.UPSTASH_REDIS_REST_URL, token: process.env.UPSTASH_REDIS_REST_TOKEN })+ : null;++const BALANCE_TTL_SECONDS = 60;++export async function getCachedSolBalance(pubkeyStr, connection) {+ const cacheKey = `sol:balance:${pubkeyStr}`;++ if (redis) {+ const cached = await redis.get(cacheKey).catch(() => null);+ if (cached !== null) return Number(cached);+ }++ const lamports = await connection.getBalance(new PublicKey(pubkeyStr));++ if (redis) {+ await redis.set(cacheKey, lamports, { ex: BALANCE_TTL_SECONDS }).catch(() => {});+ }++ return lamports;+}+```++Replace direct `connection.getBalance()` calls with `getCachedSolBalance()`. A 60-second TTL means a popular agent's balance is fetched from RPC at most once per minute regardless of traffic.++If Upstash Redis is not available (see `fix-x402-upstash-redis.md`), use a module-level in-memory Map as fallback:++```javascript+const memCache = new Map(); // { pubkey → { value, expiresAt } }++function getMemCached(key) {+ const entry = memCache.get(key);+ return entry && Date.now() < entry.expiresAt ? entry.value : null;+}++function setMemCached(key, value, ttlMs) {+ memCache.set(key, { value, expiresAt: Date.now() + ttlMs });+}+```++The in-memory cache is per-instance (not shared across Vercel replicas) but still reduces RPC calls significantly for any single replica.++### Fix 3: Add 429 retry with exponential backoff for balance checks++In the balance fetch code, wrap the RPC call with a single retry on 429:++```javascript+async function fetchBalanceWithRetry(connection, pubkey, retries = 1) {+ try {+ return await connection.getBalance(pubkey);+ } catch (err) {+ if (retries > 0 && /429|rate.limit/i.test(err?.message || '')) {+ await new Promise(r => setTimeout(r, 500));+ return fetchBalanceWithRetry(connection, pubkey, retries - 1);+ }+ throw err;+ }+}+```++Do NOT retry more than once — the goal is to recover from a transient spike, not to loop on a systematically rate-limited endpoint.++### Fix 4: Return a graceful response on persistent 429++If the balance fetch fails after retry, return a response with `balance: null` and a `balance_error: 'rpc_rate_limited'` field rather than letting the error propagate:++```javascript+let balance = null;+let balanceError = null;+try {+ balance = await getCachedSolBalance(wallet, connection);+} catch (err) {+ balanceError = /429|rate.limit/i.test(err?.message || '') ? 'rpc_rate_limited' : 'rpc_error';+ console.warn('[agents/solana/balance]', err?.message);+}+```++The frontend should display "Balance unavailable" when `balance_error` is set, rather than showing 0 or crashing.++### Verify the fix++1. Start the dev server with a valid `SOLANA_RPC_URL` set in `.env`+2. Request `GET /api/agents/{id}/solana` for an agent with a registered wallet — must return 200 with a non-null balance+3. Make the same request twice in rapid succession — the second must return the cached value (confirm by checking that only one RPC call is made via logs or network tab)++## Do Not++- Do not cache indefinitely — use a TTL of 60 seconds maximum for balances (stale balances mislead users).+- Do not suppress all RPC errors — log them at WARN level so they appear when debugging.+- Do not return fake/hardcoded balances on error.++## Related Files++- `api/agents/solana/_handlers.js` — agent solana endpoint handlers+- `api/_lib/balances.js` — wallet balance fetching (primary fix target)+- `api/_lib/pump.js:23` — `SOLANA_RPC_URL` fallback pattern (reference)+- `fix-pump-agent-stats-rpc-429.md` — same infrastructure fix for SOLANA_RPC_URLdiff --git a/docs/agent-fixes/fix-auth-register-seed-agent.md b/docs/agent-fixes/fix-auth-register-seed-agent.mdnew file mode 100644index 000000000..d2dc05d77--- /dev/null+++ b/docs/agent-fixes/fix-auth-register-seed-agent.md@@ -0,0 +1,90 @@+# Fix: POST /api/auth/register — NeonDB cold-start failures in seedDefaultAgent++## Context++User registration occasionally returns 500 with an unhandled rejection from `seedDefaultAgent`:++```+Unhandled Rejection: NeonDbError: Error connecting to database: fetch failed+ at execute (...@neondatabase/serverless/index.mjs:1549)+ at async seedDefaultAgent (api/_lib/seed-default-agent.js:20)+```++The user account is created successfully, but the 500 response makes the user think registration failed. This causes duplicate registration attempts.++## Current State — Verify Before Changing Anything++Read `api/_lib/seed-default-agent.js` in full and `api/auth/[action].js` around line 147 before touching anything.++The current code in `seed-default-agent.js` **may already have a fix** in place:+- Lines 23–75 have a try/catch with retry logic+- Line 51: one retry after 1 second on first failure+- Line 72: catches all second-attempt errors and returns null++And in `api/auth/[action].js` at line 147:+```javascript+queueMicrotask(() => seedDefaultAgent(user.id));+```++`queueMicrotask()` fires asynchronously — errors inside it do NOT propagate to the HTTP response. If both the try/catch AND the queueMicrotask are in place, the 500 from this source should be impossible.++**If both safeguards are already in the code as described above, this issue is already fixed. Verify and close.**++## If the Fix Is NOT Yet Complete++### Fix 1: Wrap seedDefaultAgent in try/catch in seed-default-agent.js++The entire exported function must be wrapped in try/catch with retry:++```javascript+export async function seedDefaultAgent(userId) {+ try {+ const [agent] = await sql`INSERT INTO agent_identities ... RETURNING id`;+ return agent?.id || null;+ } catch (err) {+ console.warn('[seed-default-agent] first attempt failed, retrying', { userId, error: err?.message });+ await new Promise(r => setTimeout(r, 1000));+ try {+ const [agent] = await sql`INSERT INTO agent_identities ... RETURNING id`;+ return agent?.id || null;+ } catch (err2) {+ console.error('[seed-default-agent] failed', { userId, error: err2?.message });+ return null; // Never propagate — registration must succeed regardless+ }+ }+}+```++**Critical:** Both catch blocks must return `null`, never `throw`. A failed agent seed is recoverable — the user can create an agent manually.++### Fix 2: Use queueMicrotask for the seed call in auth/register++In `api/auth/[action].js`, wherever `seedDefaultAgent` is called after registration, it must NOT be awaited in the request handler:++```javascript+// Wrong — awaiting makes seed failures block the 201 response:+await seedDefaultAgent(user.id);++// Correct — fire-and-forget, never blocks the response:+queueMicrotask(() => seedDefaultAgent(user.id));+```++If the current code already uses `queueMicrotask()`, no change is needed here.++### Verify the fix++1. Start the dev server (`npm run dev`)+2. Register a new user via the registration endpoint — must return 201 regardless of whether the seed agent succeeds+3. Check that a default agent eventually appears for the user (it may take up to 2 seconds due to the retry delay)+4. Temporarily break the DB connection in local dev (e.g., invalid DATABASE_URL) and verify registration still returns 201++## Do Not++- Do not await `seedDefaultAgent` in the registration handler — it must never block the 201 response+- Do not propagate seed errors to the user — log them and return null+- Do not remove the retry logic — Neon cold-start failures recover quickly on the second attempt++## Related Files++- `api/_lib/seed-default-agent.js` — the seed function (verify try/catch is complete)+- `api/auth/[action].js:147` — the queueMicrotask call (verify it's fire-and-forget)diff --git a/docs/agent-fixes/fix-avatars-reconstruct-env.md b/docs/agent-fixes/fix-avatars-reconstruct-env.mdnew file mode 100644index 000000000..c44a00942--- /dev/null+++ b/docs/agent-fixes/fix-avatars-reconstruct-env.md@@ -0,0 +1,104 @@+# Fix: POST /api/avatars/{id}/reconstruct — 14 × 501 (REPLICATE_RECONSTRUCT_MODEL not set)++## Context++The avatar reconstruction endpoint (`POST /api/avatars/{id}/reconstruct` or equivalent reconstruct action) returns 501 Not Implemented on every request. The frontend's avatar regeneration UI shows a spinner that never completes.++Error:+```+{ code: 'regen_unconfigured', status: 501 }+```++## Root Cause++Read `api/avatars/_actions.js` lines 691–740 and `api/avatars/REGENERATE.md` before touching anything.++The reconstruct handler checks for a configured Replicate model:+```javascript+if (!env.REPLICATE_RECONSTRUCT_MODEL) {+ return error(res, 501, 'regen_unconfigured', 'Reconstruction is not configured');+}+```++`REPLICATE_RECONSTRUCT_MODEL` is not set in the Vercel production environment. Without it, no avatar reconstruction jobs can be submitted, and every attempt returns 501.++The second dependency is `REPLICATE_API_TOKEN` — without this, even if the model is configured, Replicate API calls will fail.++## What You Must Fix — Completely++### Step 1: Set REPLICATE_RECONSTRUCT_MODEL in Vercel++Per `api/avatars/REGENERATE.md`, the default model is `firtoz/trellis`:++```bash+vercel env add REPLICATE_RECONSTRUCT_MODEL production+# When prompted, enter: firtoz/trellis+```++If you want to pin a specific version for reproducibility:+```+firtoz/trellis:a1e62aa99e3d40aed1de4cd4c5c4b1f5ec25c32f8b38f6dec71b80d6083b0f4f+```++Check Replicate's model page for the latest stable version tag.++### Step 2: Set REPLICATE_API_TOKEN if not already set++```bash+vercel env ls | grep REPLICATE_API_TOKEN+```++If not present:+```bash+vercel env add REPLICATE_API_TOKEN production+# Enter your Replicate API token from https://replicate.com/account/api-tokens+```++Also add both to `.env` for local dev:+```+REPLICATE_RECONSTRUCT_MODEL=firtoz/trellis+REPLICATE_API_TOKEN=r8_<your-token>+```++### Step 3: Verify the reconstruction flow end-to-end++Read `api/avatars/_actions.js` lines 390–450 (the reconstruct job completion handler) to understand what happens after Replicate finishes:+1. Replicate webhook delivers the result to the job status endpoint+2. The job result is materialized as a new avatar row+3. The frontend polls `avatar_regen_jobs` for completion++Verify the webhook URL is configured in Replicate's callback — the `reconstruct` submission must include a `webhook` field pointing to the production jobs endpoint. Check whether `VERCEL_URL` or a hardcoded production URL is used for the webhook.++### Step 4: Update the frontend to surface "unavailable" gracefully++In `src/dashboard-next/` (find the page that calls the reconstruct endpoint), if `REPLICATE_RECONSTRUCT_MODEL` is intentionally unset, the UI must show "Avatar reconstruction is not available" rather than an infinite spinner.++Look for where the `reconstruct` action is dispatched and add a handler for the 501 response:+```javascript+if (response.status === 501) {+ // show a clear "feature not available" message, not a spinner+}+```++### Verify the fix++1. Set env vars locally in `.env`+2. Start dev server (`npm run dev`)+3. Navigate to the avatar reconstruction UI+4. Trigger a reconstruction — must submit to Replicate and return a job ID (200 response)+5. The UI must poll for completion and display the result when done++After Vercel deploy:+- `POST /api/avatars/{id}/reconstruct` must return 200/202 (job submitted) not 501++## Do Not++- Do not set `REPLICATE_RECONSTRUCT_MODEL` to a non-existent or invalid model name — verify it exists at https://replicate.com/firtoz/trellis+- Do not stub the Replicate call — reconstruction must go through the real Replicate API+- Do not remove the 501 guard — it's correct behavior when the env var is missing; the fix is to set the env var++## Related Files++- `api/avatars/_actions.js:691–740` — reconstruct handler+- `api/avatars/_actions.js:390–450` — job completion and avatar materialization+- `api/avatars/REGENERATE.md` — full env var documentation for this featurediff --git a/docs/agent-fixes/fix-avaturn-api-key.md b/docs/agent-fixes/fix-avaturn-api-key.mdnew file mode 100644index 000000000..cc2f3a4cd--- /dev/null+++ b/docs/agent-fixes/fix-avaturn-api-key.md@@ -0,0 +1,78 @@+# Fix: POST /api/onboarding/avaturn-session — 10 × 501 (AVATURN_API_KEY not set)++## Context++The avaturn-session endpoint returns 501 on every request when `AVATURN_API_KEY` is not set. This breaks the avatar editor onboarding flow for all new users.++Error:+```javascript+// api/onboarding/[action].js:37+if (!env.AVATURN_API_KEY) return error(res, 501, 'not_configured', 'Avatar editor is not available right now. Please try again later.');+```++## Root Cause++`AVATURN_API_KEY` is missing from the Vercel production environment. The endpoint is correctly guarded with a 501, but the frontend onboarding flow does not handle the 501 gracefully — it likely shows an error or hangs.++## What You Must Fix — Completely++### Step 1: Obtain an Avaturn API key++1. Log in to Avaturn at https://avaturn.me+2. Navigate to Account → API Keys (or Developer settings)+3. Create a new API key for production use++### Step 2: Set AVATURN_API_KEY in Vercel++```bash+vercel env add AVATURN_API_KEY production+# Paste the key when prompted+```++Also add to `.env` for local dev (you can use a test/sandbox key if Avaturn provides one):+```+AVATURN_API_KEY=<your-avaturn-api-key>+```++### Step 3: Verify the endpoint end-to-end++Read `api/onboarding/[action].js` lines 37–60 to understand the full avaturn-session flow:+1. The handler POSTs to Avaturn's API to create a session+2. Returns the `session_url` for the frontend iframe++After setting the key:+1. Start the dev server (`npm run dev`)+2. POST to `/api/onboarding/avaturn-session` with a valid auth session — must return 200 with `{ session_url: "https://..." }`+3. Navigate to the onboarding avatar editor page — the iframe must load successfully++### Step 4: Handle 501 gracefully in the frontend++Read the onboarding page component that calls `avaturn-session`. If `AVATURN_API_KEY` is ever absent (staging environments, etc.), the frontend must show a graceful fallback rather than a broken state.++Find the fetch call (search for `avaturn-session` in `src/`), and add a 501 handler:+```javascript+if (response.status === 501) {+ // Show: "Avatar customization is temporarily unavailable. You can set one up later."+ // Skip the avaturn iframe step, proceed with onboarding+}+```++The user should be able to complete onboarding without the avatar editor if it's unavailable.++### Verify the fix++After setting the env var in Vercel and deploying:+- `POST /api/onboarding/avaturn-session` must return 200 with a valid `session_url`+- The onboarding avatar editor page must load and show the Avaturn iframe+- No 501 responses in Vercel logs for this endpoint++## Do Not++- Do not remove the `!env.AVATURN_API_KEY` guard — it's correct; fix is to set the env var+- Do not use a stub or fake session URL — the iframe must load from a real Avaturn session+- Do not leave the frontend in a broken/hanging state when the key is missing++## Related Files++- `api/onboarding/[action].js:37–60` — avaturn-session handler+- `src/dashboard-next/` — find the onboarding page that calls this endpointdiff --git a/docs/agent-fixes/fix-billing-withdrawals-42p18.md b/docs/agent-fixes/fix-billing-withdrawals-42p18.mdnew file mode 100644index 000000000..304bcbffa--- /dev/null+++ b/docs/agent-fixes/fix-billing-withdrawals-42p18.md@@ -0,0 +1,86 @@+# Fix: GET /api/billing/withdrawals returns 500 — SQL 42P18 LIMIT/OFFSET type error++## Context++Every authenticated user who loads the monetize/billing page triggers a 500 from `GET /api/billing/withdrawals?limit=50`. The page cannot display withdrawal history. This has been firing continuously in production.++Error in Vercel logs:+```+NeonDbError: could not determine data type of parameter $2+ severity: 'ERROR'+ code: '42P18'+ routine: 'pg_analyze_and_rewrite_varparams'+ at execute (node_modules/@neondatabase/serverless/index.mjs:1556:55)+ at async api/billing/withdrawals/index.js:36+```++## Root Cause++Read `api/billing/withdrawals/index.js` in full before touching anything.++PostgreSQL's extended query protocol requires type information for all parameters at parse time. In a `LIMIT $N OFFSET $N` clause, PostgreSQL has no type context for those parameters — it cannot infer they should be integers — and rejects the query with error code 42P18 ("indeterminate datatype").++The Neon serverless driver (`@neondatabase/serverless`) uses the extended query protocol. When you write:+```javascript+sql`SELECT ... WHERE user_id = ${user.id} ORDER BY ... LIMIT ${limit} OFFSET ${offset}`+```+The driver sends `limit` and `offset` as untyped parameters ($2 and $3). Postgres sees:+```sql+SELECT ... WHERE user_id = $1 ORDER BY ... LIMIT $2 OFFSET $3+```+Parameters $2 and $3 have no type context → 42P18.++The `user.id` parameter ($1) works fine because `WHERE user_id = $1` lets Postgres infer from the column type.++Note: there is already a comment in the file explaining the 42P18 avoidance pattern for the `status` parameter — the same fix was applied there but was missed for `limit`/`offset`.++## What You Must Fix — Completely++### In `api/billing/withdrawals/index.js`++There are **four SQL template literals** in the GET handler that use `${limit}` and `${offset}`. Find them all and add `::int` casts.++Change every occurrence of:+```javascript+limit ${limit} offset ${offset}+```+To:+```javascript+limit ${limit}::int offset ${offset}::int+```++The `::int` cast is a PostgreSQL-side type annotation that appears as `LIMIT $N::int OFFSET $N::int` in the prepared statement. This gives the query planner the type context it needs and eliminates the 42P18 error.++The four locations are:+1. The withdrawals query in the `status` branch (where `status` is truthy)+2. The withdrawals query in the no-status branch+3. The count query in the `status` branch (check if it uses limit/offset — if not, no change needed)+4. The count query in the no-status branch (same check)++If the count queries don't include LIMIT/OFFSET they don't need the cast. Audit all four and apply the cast wherever `${limit}` or `${offset}` appear in SQL position.++### Verify the fix++After editing, run:+```bash+node -e "+import('./api/billing/withdrawals/index.js').then(() => console.log('module loads OK')).catch(e => console.error(e))+"+```++Then test the endpoint locally with a real authenticated session (or via the Playwright scripts in `scripts/`) and confirm the withdrawals panel loads without error.++Verify the Vercel deployment shows no more 42P18 errors for `/api/billing/withdrawals` after deploy.++## Do Not++- Do not switch to raw string interpolation for the limit/offset values — even though they are already sanitized by `parseInt` + `Math.min`, parameterized queries are the correct pattern.+- Do not change the branching logic for `status` — that fix is already correct and must stay.+- Do not add a try/catch that silently swallows the DB error and returns empty results — the error must be fixed at the SQL level.++## Related Files++- `api/billing/withdrawals/index.js` — the only file to change+- `src/dashboard-next/pages/monetize.js:69` — the frontend caller (no change needed here)++Fix this completely. After the fix, `GET /api/billing/withdrawals?limit=50` must return a valid JSON response with the `withdrawals` array for any authenticated user.diff --git a/docs/agent-fixes/fix-chat-502-upstream.md b/docs/agent-fixes/fix-chat-502-upstream.mdnew file mode 100644index 000000000..cccdd8076--- /dev/null+++ b/docs/agent-fixes/fix-chat-502-upstream.md@@ -0,0 +1,114 @@+# Fix: POST /api/chat — 18 × 502 errors from upstream AI provider failures++## Context++`POST /api/chat` returns 502 (bad gateway) on 18 requests. The 502 comes from upstream AI providers (Anthropic or the worker proxy) returning 5xx responses that the handler propagates directly to the client.++## Root Cause++Read `api/chat.js` lines 280–370 in full before touching anything.++The handler already has multi-provider fallback logic at line 314:+```javascript+if ((upstream.status === 429 || upstream.status >= 500) && routeIdx + 1 < fallbackRoutes.length) {+ // fall over to next route+}+```++The 502 errors occur when **all fallback routes are exhausted** — every configured provider returned 5xx. When that happens, the handler returns 502 with the upstream error message.++Two distinct failure modes:+1. **All providers simultaneously returning 5xx** — rare but possible during an Anthropic or OpenAI incident.+2. **Fallback routes not configured** — if `fallbackRoutes` has only one entry, the first failure immediately returns 502 with no retry.++Additionally, the handler logs the error at `console.error` level (line 333) but the upstream error **message** may be truncated at 400 characters, making it hard to diagnose which provider failed and why.++## What You Must Fix — Completely++### Step 1: Audit the fallback route configuration++Read `api/chat.js` to find where `fallbackRoutes` is built. Identify:+- How many routes are configured in production (check env vars like `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `CHAT_WORKER_URL`)+- Whether any route is missing its API key (which would cause it to skip or fail immediately)++If only one provider is configured, the fallback logic is irrelevant and any provider 5xx becomes a user-facing 502.++Verify all required env vars are set in Vercel production:+```bash+vercel env ls | grep -E "ANTHROPIC_API_KEY|OPENAI_API_KEY|CHAT_WORKER_URL"+```++### Step 2: Add single-provider retry before failover++For the case where the primary provider returns a transient 5xx (e.g., 503 Service Unavailable), add one retry before falling to the next provider:++In `api/chat.js`, in the route loop, before the `if (routeIdx + 1 < fallbackRoutes.length)` check, retry once on 5xx:++```javascript+// First try+upstream = await fetch(route.url, { ... });++// One retry on transient 5xx (503/504 are most common transient errors)+if ([503, 504].includes(upstream.status)) {+ await new Promise(r => setTimeout(r, 500));+ upstream = await fetch(route.url, { ... });+}+```++Only retry 503 and 504 (gateway-level transient errors). Do NOT retry 400, 401, 422 (client errors) or 500 (provider bugs) — those won't recover on retry.++### Step 3: Improve error logging for provider failures++At line 333, the current log is:+```javascript+console.error(`[chat:${route.name}]`, upstream.status, text.slice(0, 400));+```++Enhance it to log the route name and whether it was a final failure:+```javascript+const isFinal = routeIdx + 1 >= fallbackRoutes.length;+console.error(+ `[chat:${route.name}]`,+ upstream.status,+ isFinal ? '(final — no more fallbacks)' : '(failing over)',+ text.slice(0, 400)+);+```++This lets you distinguish "all providers failed" from "primary failed, fell back" in the logs.++### Step 4: Add a user-friendly error body on final 502++When all providers fail, the current response is:+```javascript+return error(res, 502, 'upstream_error', `${route.name} returned ${upstream.status}...`);+```++Add a generic message so the frontend can show a human-readable error:+```javascript+return error(res, 502, 'upstream_error', 'AI chat provider is temporarily unavailable. Please try again in a moment.');+```++The frontend chat UI should display this message to the user rather than a raw error object.++### Verify the fix++1. Start the dev server (`npm run dev`)+2. Send a POST to `/api/chat` with a valid session and message body — must return a streaming SSE response without 502+3. Verify the response streams correctly and completes without error++For provider failure simulation:+- Temporarily set `ANTHROPIC_API_KEY` to an invalid value in `.env` local dev+- Send a chat request — should fall over to the next provider (OpenAI or worker proxy) and succeed++## Do Not++- Do not add retry for non-transient errors (400, 401, 422, 500).+- Do not remove the existing fallback route logic — it's the primary resilience mechanism.+- Do not add infinite retry loops — maximum one retry per provider, then fall over.+- Do not mock the AI responses or hardcode fallback text.++## Related Files++- `api/chat.js:280–370` — primary route loop and fallback logic+- `api/chat.js:427–440` — fallback routes configurationdiff --git a/docs/agent-fixes/fix-club-leaderboard-db.md b/docs/agent-fixes/fix-club-leaderboard-db.mdnew file mode 100644index 000000000..b308e4ae9--- /dev/null+++ b/docs/agent-fixes/fix-club-leaderboard-db.md@@ -0,0 +1,91 @@+# Fix: GET /api/club/leaderboard — 16 × 500 errors, missing DB column or table++## Context++`GET /api/club/leaderboard` returns 500 on 16 requests. No error message appears in the Vercel logs for these failures, which means the error is being swallowed without logging — or the log is being emitted at a severity level that doesn't appear in the log export.++## Root Cause++Read `api/club/leaderboard.js` in full before touching anything.++The leaderboard query joins `club_dancer_wallets` with `club_tips`. The query references `t.paid_at` (the timestamp of a completed tip payment). Most likely:+1. The `paid_at` column does not exist on `club_tips` in the production database, causing a PostgreSQL column-not-found error.+2. OR one of the two tables (`club_dancer_wallets`, `club_tips`) does not exist at all.++A secondary possibility is that the `wrap()` HTTP helper catches the error and returns 500 but does not log it with the full error context. Investigate the error path fully.++## What You Must Fix — Completely++### Step 1: Identify the actual error++Read `api/club/leaderboard.js` fully. Identify where `runForWindow()` or the main query runs, and confirm the try/catch path logs the error with full context including `err.code` and `err.message`.++If the current catch block is:+```javascript+} catch (err) {+ console.error('[club/leaderboard]', err?.message || err);+```++Change it to:+```javascript+} catch (err) {+ console.error('[club/leaderboard]', err?.code, err?.message || err);+ throw err; // or return error(res, 500, ...)+```++This ensures the Postgres error code (`42703` for column not found, `42P01` for table not found) appears in logs.++### Step 2: Audit the DB schema++Connect to the production Neon database and verify:++```sql+-- Verify tables exist+SELECT table_name FROM information_schema.tables+WHERE table_name IN ('club_dancer_wallets', 'club_tips')+AND table_schema = 'public';++-- If club_tips exists, verify columns+SELECT column_name, data_type FROM information_schema.columns+WHERE table_name = 'club_tips'+ORDER BY ordinal_position;++-- If club_dancer_wallets exists, verify columns+SELECT column_name, data_type FROM information_schema.columns+WHERE table_name = 'club_dancer_wallets'+ORDER BY ordinal_position;+```++### Step 3: Add missing columns or tables++If `club_tips.paid_at` is missing, add it:+```sql+ALTER TABLE club_tips ADD COLUMN IF NOT EXISTS paid_at timestamptz;+```++If `club_dancer_wallets` is missing, check `api/_lib/migrations/` for the migration that creates it and apply it:+```bash+psql "$DATABASE_URL" -f api/_lib/migrations/<relevant-file>.sql+```++Record the fix in `api/_lib/migrations/` with a new idempotent SQL file. Do not apply ad-hoc schema changes without a migration file — every schema change must have a corresponding migration.++### Step 4: Verify the leaderboard endpoint works++After fixing the schema:+1. Start the dev server (`npm run dev`)+2. Request `/api/club/leaderboard` — it must return 200 with valid JSON containing `{ leaderboard: [...] }` (or equivalent structure)+3. If no club_tips rows exist, the endpoint must return an empty leaderboard, not an error++Confirm no 500 errors appear in Vercel logs after deploy.++## Do Not++- Do not return empty results silently when the DB query fails — the error must be logged with full context.+- Do not remove the leaderboard feature if the DB tables are missing — create the migration.+- Do not apply schema changes directly in Neon console without also adding a migration file in `api/_lib/migrations/`.++## Related Files++- `api/club/leaderboard.js` — the endpoint handler+- `api/_lib/migrations/` — where the fix migration must go if schema changes are neededdiff --git a/docs/agent-fixes/fix-erc8004-crawl-timeout.md b/docs/agent-fixes/fix-erc8004-crawl-timeout.mdnew file mode 100644index 000000000..b9d4b67b4--- /dev/null+++ b/docs/agent-fixes/fix-erc8004-crawl-timeout.md@@ -0,0 +1,110 @@+# Fix: cron/erc8004-crawl — multiple 504 timeouts (block chunk size and RPC timeouts)++## Context++The `erc8004-crawl` cron job times out on some deployments with 504 errors. The cron scans EVM chain logs for ERC-8004 agent registration events using `eth_getLogs` on public RPC endpoints. When the block range is too large or the RPC is slow, the function hits Vercel's timeout.++## Root Cause++Read `api/cron/[name].js` at `handleErc8004Crawl` (line 111) and `erc8004CrawlChain` (line 145) before touching anything.++The current `ERC8004_BLOCK_CHUNK = 2_000` is noted in the code comment: "Public RPCs typically allow 2000-block ranges; lower this if a chain's RPC rejects with 'block range'." The 504 timeouts may occur because:++1. **A specific chain's public RPC is slow** — some chains (e.g., Polygon, Arbitrum) have public RPCs with high latency or strict block range limits lower than 2000.+2. **Multiple chains are crawled in a single cron run** — if there are many chains in `CHAINS`, the total time across all of them exceeds `CRAWL_BUDGET_MS = 240_000` (240 seconds), but Vercel's actual function timeout for cron jobs may be lower.+3. **`erc8004EnrichMetadata` hangs** — the metadata enrichment step fetches external URLs for 25 agents per run. If any of those URLs hangs, the entire function waits.++## What You Must Fix — Completely++### Fix 1: Reduce ERC8004_BLOCK_CHUNK for slower chains++Read `erc8004CrawlChain` and the `CHAINS` array. Identify which chains are present.++For chains with known slow RPCs (Polygon, Base, Arbitrum, Optimism on free-tier public RPCs), reduce the chunk size. Either:++**Option A:** Reduce the global default:+```javascript+const ERC8004_BLOCK_CHUNK = 1_000; // Reduced from 2000 — safer for all public RPCs+```++**Option B:** Add per-chain chunk size override:+```javascript+// In the CHAINS array:+{ id: 137, name: 'polygon', rpcUrl: '...', registry: '...', blockChunk: 500 }++// In erc8004CrawlChain:+const chunkSize = chain.blockChunk || ERC8004_BLOCK_CHUNK;+const toBlock = Math.min(fromBlock + chunkSize - 1, latestBlock);+```++Option B is cleaner because it lets you tune per-chain without affecting well-functioning chains.++### Fix 2: Add per-RPC-call timeout via AbortSignal++Read `erc8004RpcCall` function. Verify it has a timeout. If not, add one:++```javascript+async function erc8004RpcCall(rpcUrl, method, params) {+ const resp = await fetch(rpcUrl, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),+ signal: AbortSignal.timeout(ERC8004_FETCH_TIMEOUT_MS), // already defined as 10_000+ });+ if (!resp.ok) throw new Error(`RPC ${resp.status}: ${method}`);+ const data = await resp.json();+ if (data.error) throw new Error(`RPC error: ${data.error.message || JSON.stringify(data.error)}`);+ return data.result;+}+```++The `ERC8004_FETCH_TIMEOUT_MS = 10_000` constant already exists — verify it's being used in the actual fetch call with `AbortSignal.timeout()`.++### Fix 3: Add per-metadata-URL timeout in erc8004EnrichMetadata++Read `erc8004EnrichMetadata`. Each external metadata URL fetch must have a timeout:++```javascript+const resp = await fetch(metadataUrl, {+ signal: AbortSignal.timeout(5_000), // 5 seconds max per metadata URL+});+```++If a metadata URL hangs (e.g., IPFS gateway slow), it must not block the entire enrichment batch.++### Fix 4: Verify CRAWL_BUDGET_MS is respected for Vercel's actual limit++The `CRAWL_BUDGET_MS = 240_000` assumes a 300-second Vercel timeout (the maximum for Pro plan cron jobs). Verify in `vercel.json` that the `erc8004-crawl` function has `"maxDuration": 300` set:++```json+"functions": {+ "api/cron/[name].js": {+ "maxDuration": 300+ }+}+```++If `maxDuration` is not set, the default is 10 seconds (hobby) or 60 seconds (Pro) — far less than 240 seconds. The budget check at line 125 (`Date.now() - crawlStart > CRAWL_BUDGET_MS`) would never fire before Vercel kills the function.++### Verify the fix++1. After making the changes, trigger the cron manually:+ ```bash+ curl -H "Authorization: Bearer $CRON_SECRET" https://three.ws/api/cron/erc8004-crawl+ ```+2. Must return a valid JSON report within 30 seconds: `{"chains":[...],"enriched":N,"errors":[]}`+3. No 504 responses in Vercel logs for this cron after deploy++## Do Not++- Do not set `ERC8004_BLOCK_CHUNK = 0` or skip the crawl — it must scan real on-chain data+- Do not increase `CRAWL_BUDGET_MS` beyond 270_000 (270s) — leave at least 30 seconds of margin before Vercel's hard kill+- Do not remove the chain-level error handling in `erc8004CrawlChain` — one chain failing must not abort all others++## Related Files++- `api/cron/[name].js:96` — `ERC8004_BLOCK_CHUNK` constant+- `api/cron/[name].js:111` — `handleErc8004Crawl`+- `api/cron/[name].js:145` — `erc8004CrawlChain`+- `api/cron/[name].js:106` — `ERC8004_FETCH_TIMEOUT_MS`+- `vercel.json` — `maxDuration` for the cron functiondiff --git a/docs/agent-fixes/fix-marketplace-agents-500.md b/docs/agent-fixes/fix-marketplace-agents-500.mdnew file mode 100644index 000000000..0c2533b9a--- /dev/null+++ b/docs/agent-fixes/fix-marketplace-agents-500.md@@ -0,0 +1,104 @@+# Fix: GET /api/marketplace/agents — 105 × 500 errors, likely 42P18 on LIMIT/OFFSET++## Context++`GET /api/marketplace/agents` (the main public marketplace listing) returns 500 on ~105 requests. This is the highest-traffic public endpoint — every visitor to the marketplace page hits it. The error body contains no upstream detail because the log line is `console.error('[marketplace/list]', err?.message || err)` which truncates the message.++## Root Cause++Read `api/marketplace/[action].js` lines 342–412 in full before touching anything.++The `handleList` function at line 367 runs a `sql.transaction()` with two queries. The second query ends with:++```javascript+LIMIT ${limit + 1} OFFSET ${offset}+```++`limit` and `offset` are JavaScript numbers (validated by `Number()` + `Math.min/max`). However, when passed as template literal interpolations into a Neon `sql\`...\`` tag inside `sql.transaction()`, PostgreSQL's extended query protocol cannot infer their types — they appear as bare `$N` parameters in LIMIT/OFFSET position with no type context.++This produces PostgreSQL error **42P18** (`could not determine data type of parameter $N`), the same class of bug that affects `api/billing/withdrawals/index.js`. The fix is identical: add `::int` casts.++Additionally, audit that all referenced tables and columns exist in the production Neon database. The query joins `skill_purchases`, `agent_reviews`, `asset_prices`, and `avatars` — any missing column causes a different class of 500 that would also be visible in logs.++## What You Must Fix — Completely++### Fix 1: Add `::int` casts to LIMIT and OFFSET in `handleList`++In `api/marketplace/[action].js` at the marketplace listing query (around line 406):++**Change:**+```javascript+LIMIT ${limit + 1} OFFSET ${offset}+```++**To:**+```javascript+LIMIT ${limit + 1}::int OFFSET ${offset}::int+```++The `::int` cast is a PostgreSQL-side type annotation. It appears as `LIMIT $N::int OFFSET $N::int` in the prepared statement, giving the query planner the type context it needs.++Also check the second `handleList` function (for the "mine" or admin variant if one exists, around line 437) — if it also has `LIMIT/OFFSET` interpolations, apply the same cast.++### Fix 2: Verify referenced tables and columns exist++Run these queries against the production Neon database (use `psql "$DATABASE_URL"` or the Neon console):++```sql+-- Verify all tables used in the marketplace join exist+SELECT table_name FROM information_schema.tables+WHERE table_name IN ('agent_identities', 'avatars', 'users', 'skill_purchases', 'agent_reviews', 'asset_prices')+AND table_schema = 'public';++-- Verify specific columns used in the query+SELECT column_name FROM information_schema.columns+WHERE table_name = 'skill_purchases' AND column_name IN ('agent_id', 'status', 'created_at', 'confirmed_at');++SELECT column_name FROM information_schema.columns+WHERE table_name = 'agent_reviews' AND column_name IN ('agent_id', 'rating');++SELECT column_name FROM information_schema.columns+WHERE table_name = 'asset_prices' AND column_name IN ('item_type', 'item_id', 'is_active', 'amount', 'currency_mint', 'chain', 'mint_decimals');++SELECT column_name FROM information_schema.columns+WHERE table_name = 'avatars' AND column_name IN ('id', 'thumbnail_key', 'deleted_at');+```++If any column is missing, add it with a migration in `api/_lib/migrations/`. Do not alter the query to skip columns — add the missing columns.++### Fix 3: Improve error logging to surface the full error++The current `console.error('[marketplace/list]', err?.message || err)` truncates stack traces. Change it to log the full error code:++```javascript+} catch (err) {+ console.error('[marketplace/list]', err?.code, err?.message || err);+ return error(res, 500, 'db_error', 'Failed to load marketplace listing');+}+```++The `err.code` will be `'42P18'` if it's a type inference error, or another Postgres error code if something else is failing. This makes future diagnosis instant.++### Verify the fix++1. After making the code change, run the module syntax check:+ ```bash+ node --input-type=module <<'EOF'+ import('./api/marketplace/[action].js').then(() => console.log('OK')).catch(e => console.error(e.message))+ EOF+ ```++2. Start the dev server (`npm run dev`) and navigate to the marketplace page. The agent listing must load without errors and the network tab must show a successful response from `/api/marketplace/agents`.++3. Verify no 42P18 or other 500 errors appear in Vercel logs for this endpoint after deploy.++## Do Not++- Do not add a try/catch around the `sql.transaction()` that returns an empty array on DB error — fix the root cause.+- Do not remove the `sql\`SET LOCAL statement_timeout = '8000'\`` line — it protects against query hangs and must stay.+- Do not switch to raw string interpolation for limit/offset even though they're validated integers — parameterized queries with `::int` casts is the correct pattern.++## Related Files++- `api/marketplace/[action].js:367–411` — `handleList`, the broken query+- `api/billing/withdrawals/index.js` — same 42P18 pattern (see `fix-billing-withdrawals-42p18.md` for reference)diff --git a/docs/agent-fixes/fix-mocap-clips-sql-params.md b/docs/agent-fixes/fix-mocap-clips-sql-params.mdnew file mode 100644index 000000000..53f68a812--- /dev/null+++ b/docs/agent-fixes/fix-mocap-clips-sql-params.md@@ -0,0 +1,110 @@+# Fix: GET /api/mocap/clips — 6 × 500 errors, SQL positional parameter mismatch++## Context++`GET /api/mocap/clips` and `POST /api/mocap/clips` each return 500 on some requests. The `handleList` function uses a raw SQL string with positional parameters (`$1`, `$2`, etc.) built up dynamically via `params.push()`. The parameter indices must exactly match the push order, including conditional branches.++## Root Cause++Read `api/mocap/clips.js` in full before touching anything, paying close attention to `handleList` and the conditional `kindFilter` branch (line 87).++The function builds an SQL string and a `params` array conditionally. The `$N` placeholder indices in the SQL string must match the index at which each value was pushed into `params`. When `kindFilter` is provided, it adds an extra parameter — if the SQL template uses a hardcoded `$4` but the `kindFilter` push changes the expected index, the query will either fail with a parameter count mismatch or bind the wrong value.++Specifically examine:+1. The order of `params.push()` calls+2. Whether the `$N` placeholders in the SQL string increment correctly for each conditional branch+3. The cursor (`decoded.createdAt`) push and whether it's always at the same `$N` position regardless of the `kindFilter` branch++## What You Must Fix — Completely++### Fix 1: Audit and correct the parameter binding++Read the full `handleList` function and trace every `params.push()` call:++```+params[0] = auth.userId or null+params[1] = auth.userId or null (second occurrence)+params[2] = kindFilter (conditional)+params[3] = cursor value (conditional, position shifts when kindFilter added)+params[4] = limit + 1+```++If `kindFilter` is truthy, every `$N` after the kindFilter push must be incremented by 1. Verify the SQL string does this correctly. If not, fix the SQL string to use the correct `$N` indices.++A safer pattern is to build the WHERE clauses conditionally:++```javascript+const whereClauses = ['deleted_at IS NULL'];+const params = [];++if (auth.userId) {+ params.push(auth.userId);+ whereClauses.push(`user_id = $${params.length}`);+}+if (kindFilter && /^[a-z]+$/.test(kindFilter)) {+ params.push(kindFilter);+ whereClauses.push(`kind = $${params.length}`);+}+// cursor+if (decoded?.createdAt) {+ params.push(decoded.createdAt);+ whereClauses.push(`created_at < $${params.length}`);+}+// limit is always last+params.push(limit + 1);+const limitPlaceholder = `$${params.length}::int`;++const sqlStr = `+ SELECT ...+ WHERE ${whereClauses.join(' AND ')}+ ORDER BY created_at DESC+ LIMIT ${limitPlaceholder}+`;+```++This pattern uses `$${params.length}` to self-document the index, making it impossible to have a mismatch.++### Fix 2: Verify the LIMIT/OFFSET parameter has `::int` cast++The Neon serverless driver has the same 42P18 problem for LIMIT/OFFSET as described in `fix-billing-withdrawals-42p18.md`. If the raw SQL uses `$N` in LIMIT position without a type cast, add `::int`:++```sql+-- Change:+LIMIT $4+-- To:+LIMIT $4::int+```++### Fix 3: Improve error logging++The current catch at line 113 does:+```javascript+console.error('[mocap/clips/list]', err?.message || err);+```++Add the error code so future diagnosis is instant:+```javascript+console.error('[mocap/clips/list]', err?.code, err?.message || err);+```++### Fix 4: Verify POST 405 is not from vercel.json++The 405 on `POST /api/mocap/clips` suggests the route may be restricted to GET. Check `vercel.json` for any route entry that limits this path to GET methods. If found, remove the method restriction — the handler correctly accepts both GET and POST.++### Verify the fix++1. Start the dev server (`npm run dev`)+2. Request `GET /api/mocap/clips` as an authenticated user — must return 200 with a `clips` array+3. Request `GET /api/mocap/clips?kind=bvh` — must return filtered results without error+4. Request `GET /api/mocap/clips?kind=bvh&cursor=<timestamp>` — must return paginated results++No 500 errors should appear after these tests.++## Do Not++- Do not switch from raw SQL to tagged templates for this query — the code comment explains why (`"syntax error at or near $1"` is a known Neon limitation for this pattern).+- Do not add a try/catch that returns empty arrays on failure — fix the root cause.++## Related Files++- `api/mocap/clips.js:62–115` — `handleList` function (primary fix target)diff --git a/docs/agent-fixes/fix-permissions-list-500.md b/docs/agent-fixes/fix-permissions-list-500.mdnew file mode 100644index 000000000..4e84e62bc--- /dev/null+++ b/docs/agent-fixes/fix-permissions-list-500.md@@ -0,0 +1,90 @@+# Fix: GET /api/permissions/list — 2 × 500 errors, unlogged DB failure++## Context++`GET /api/permissions/list` returns 500 on 2 requests. The endpoint manages agent delegation permissions. The error message does not appear in Vercel logs at a level visible in the export, which makes diagnosis impossible without surfacing the actual Postgres error code.++## Root Cause++Read `api/permissions/[action].js` lines 310–430 in full before touching anything.++The `handleList` function runs two separate DB queries: a public query and an auth-gated query. Both are wrapped in try/catch blocks (lines 371 and 425) that call `console.error`. However, the error message format uses `err?.message || err` which omits the Postgres error code — making it impossible to distinguish a 42703 (missing column), 42P01 (missing table), 42P18 (type inference), or ECONNRESET (connection failure) in the logs.++The most likely root causes:+1. A referenced column in `agent_delegations` doesn't exist (e.g., `delegation_hash`, `chain_id`, `contract_address`).+2. The `isDelegationValid()` call or an on-chain verification step is throwing an unhandled error.+3. The `agent_delegations` table itself is missing or has a schema mismatch.++## What You Must Fix — Completely++### Step 1: Add full error context to both catch blocks++In `api/permissions/[action].js`, update both error catch blocks in `handleList`:++**Public query catch (around line 371):**+```javascript+} catch (err) {+ console.error('[permissions/list] public query failed', err?.code, err?.message || err);+ return error(res, 500, 'db_error', 'Failed to load permissions');+}+```++**Auth query catch (around line 425):**+```javascript+} catch (err) {+ console.error('[permissions/list] auth query failed', err?.code, err?.message || err);+ return error(res, 500, 'db_error', 'Failed to load permissions');+}+```++### Step 2: Verify the agent_delegations table schema++Connect to the production Neon database and check:++```sql+-- Verify agent_delegations exists and has required columns+SELECT column_name, data_type FROM information_schema.columns+WHERE table_name = 'agent_delegations'+ORDER BY ordinal_position;++-- Verify agent_identities referenced columns+SELECT column_name FROM information_schema.columns+WHERE table_name = 'agent_identities'+AND column_name IN ('id', 'user_id', 'deleted_at');++-- Verify user_wallets referenced columns+SELECT column_name FROM information_schema.columns+WHERE table_name = 'user_wallets'+AND column_name IN ('user_id', 'address');+```++If any column is missing from `agent_delegations`, create a migration in `api/_lib/migrations/` to add it with `ADD COLUMN IF NOT EXISTS`.++### Step 3: Check the delegations query for 42P18++Read the SQL query in `handleList`. If it has `LIMIT $N OFFSET $N` in LIMIT/OFFSET position without a `::int` cast, add the cast:++```sql+-- Change:+LIMIT ${limit} OFFSET ${offset}+-- To:+LIMIT ${limit}::int OFFSET ${offset}::int+```++### Step 4: Verify the fix++1. Start the dev server (`npm run dev`)+2. Request `GET /api/permissions/list` as an authenticated user — must return 200 with a `permissions` array (empty is fine if no delegations exist)+3. Request `GET /api/permissions/list` as an unauthenticated user — must return 200 with public delegations only++No 500 errors after these tests.++## Do Not++- Do not return empty results silently when the DB query fails — log the error and return a proper 500.+- Do not alter the delegations schema without adding a migration file.++## Related Files++- `api/permissions/[action].js:310–430` — `handleList` function+- `api/_lib/migrations/` — where schema fix migrations godiff --git a/docs/agent-fixes/fix-pump-agent-stats-rpc-429.md b/docs/agent-fixes/fix-pump-agent-stats-rpc-429.mdnew file mode 100644index 000000000..6e60c19ac--- /dev/null+++ b/docs/agent-fixes/fix-pump-agent-stats-rpc-429.md@@ -0,0 +1,114 @@+# Fix: pump-agent-stats cron — 7,000+ 504 timeouts due to Solana RPC rate limiting++## Context++The `pump-agent-stats` cron job is completely broken in production, producing 7,200+ 504 timeout errors across all deployments (`3dagent-lkvpaeq68` alone has 4,085). The cron runs every minute and times out on Vercel's 30-second limit every single invocation without doing useful work.++Vercel logs:+```+Server responded with 429 Too Many Requests. Retrying after 500ms delay...+Server responded with 429 Too Many Requests. Retrying after 1000ms delay...+Server responded with 429 Too Many Requests. Retrying after 2000ms delay...+Server responded with 429 Too Many Requests. Retrying after 4000ms delay...+Vercel Runtime Timeout Error: Task timed out after 30 seconds+```++## Root Cause++Read `api/cron/[name].js` at `handlePumpAgentStats` (line 687) and `pumpStatsSnapshotMint` (line 806) before touching anything.++`pumpStatsSnapshotMint` calls `getRpcFallback({ network })` which is implemented in `api/_lib/pump.js`:++```javascript+const RPC_MAINNET = () => process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';+```++When `SOLANA_RPC_URL` is not set in the Vercel environment, every RPC call goes to the public `https://api.mainnet-beta.solana.com` endpoint, which is aggressively rate-limited and returns 429 on almost every call in production-scale usage.++The retry delays (500ms → 1s → 2s → 4s = 7.5s per mint) burn through the 22-second deadline before completing even 2 mints. The handler already has a deadline check and circuit breaker (3 consecutive 429s triggers early exit), but they only work correctly when the RPC succeeds on at least some calls. When every call returns 429 immediately, the circuit breaks after 3 mints and skips the rest — still logging errors and never making progress.++**This is fundamentally an infrastructure configuration problem.** The code is correct. The fix is to set a paid, private Solana RPC endpoint.++## What You Must Fix — Completely++### Step 1: Provision a paid Solana RPC endpoint++Options (in order of preference):+1. **Helius** (https://helius.dev) — best support for `getSignaturesForAddress` used in `pumpStatsSnapshotMint`. Free tier includes 100k credits/day.+2. **QuickNode** (https://quicknode.com) — reliable, paid plans.+3. **Triton One** (https://triton.one) — performance-focused.++Sign up, create a mainnet-beta endpoint, and get the HTTPS endpoint URL. It will look like:+- Helius: `https://mainnet.helius-rpc.com/?api-key=<YOUR_KEY>`+- QuickNode: `https://<name>.solana-mainnet.quiknode.pro/<KEY>/`++### Step 2: Set SOLANA_RPC_URL in Vercel++```bash+vercel env add SOLANA_RPC_URL production+# paste the RPC endpoint URL when prompted+```++Also add to `.env` for local dev:+```+SOLANA_RPC_URL=https://mainnet.helius-rpc.com/?api-key=<YOUR_DEV_KEY>+```++Optionally set a separate devnet endpoint:+```bash+vercel env add SOLANA_RPC_URL_DEVNET production+```++### Step 3: Verify the RPC is in use++After setting the env var, trigger a manual cron invocation:+```bash+curl -H "Authorization: Bearer $CRON_SECRET" https://three.ws/api/cron/pump-agent-stats+```++Expected response: `{"scanned":N,"updated":M,"errors":0,"graduations":0,"timeouts":0,"rate_limited":0,"skipped":0}` with `updated > 0`.++### Step 4: Code guard — add per-mint RPC timeout++Read `pumpStatsSnapshotMint` (line 806) and confirm the `getSignaturesForAddress` call is wrapped. If not, add a per-call AbortSignal so an individual RPC call can't hang indefinitely:++```javascript+const conn = getRpcFallback({ network });+const sigs = await conn.getSignaturesForAddress(mintPk, { limit: 50 }, 'confirmed');+```++The existing `Promise.race` timeout in the outer loop (`PUMP_STATS_MINT_TIMEOUT_MS`) already guards this, but confirm `PUMP_STATS_MINT_TIMEOUT_MS` is defined and set to a value less than `22_000 / PUMP_STATS_MAX_PER_RUN`.++### Step 5: Confirm existing safeguards are working++After deploying with the real RPC:+- The deadline check at line 704 (`DEADLINE = Date.now() + 22_000`) must still function — do not remove it.+- The circuit breaker at line 713 (`consecutiveRateLimit >= 3`) must still function — do not remove it.+- On a paid RPC with proper rate limits, both safeguards should rarely trigger.++### Step 6: Redeploy and monitor++```bash+# After adding env var, trigger redeploy+vercel deploy --prod+```++Monitor for 5 minutes after deploy. Vercel logs for `pump-agent-stats` should show:+- No more "429 Too Many Requests" messages+- No more "Task timed out after 30 seconds"+- Valid JSON report responses++## Do Not++- Do not reduce `ERC8004_BLOCK_CHUNK` or modify the circuit breaker logic — those are unrelated to the 429 problem.+- Do not add a `X402_ALLOW_MEMORY_FALLBACK=1` style workaround — the RPC must be a real paid endpoint.+- Do not use `https://api.mainnet-beta.solana.com` in production — it will rate-limit immediately.+- Do not mock the Pump.fun or Solana calls — this cron must call real endpoints.++## Related Files++- `api/_lib/pump.js:23` — `RPC_MAINNET` fallback to public endpoint+- `api/cron/[name].js:687` — `handlePumpAgentStats`+- `api/cron/[name].js:806` — `pumpStatsSnapshotMint` (RPC call at line 867)++The code change (if any) is minimal — just an env var configuration. The primary fix is infrastructure.diff --git a/docs/agent-fixes/fix-subscriptions-plans-uuid.md b/docs/agent-fixes/fix-subscriptions-plans-uuid.mdnew file mode 100644index 000000000..442568e06--- /dev/null+++ b/docs/agent-fixes/fix-subscriptions-plans-uuid.md@@ -0,0 +1,113 @@+# Fix: GET /api/subscriptions/plans crashes on invalid creator_id — two bugs in a chain++## Context++`GET /api/subscriptions/plans?creator_id=<invalid>` returns 500 and crashes with a Postgres type error. Two distinct invalid values are reaching the server:++1. `creator_id=undefined` — JavaScript `undefined` serialized to the string `"undefined"` in the query string+2. `creator_id=u_demo` — a placeholder/demo value sent by uptime probes or Playwright smoke tests++Vercel error log:+```+NeonDbError: invalid input syntax for type uuid: "u_demo" code: '22P02'+NeonDbError: invalid input syntax for type uuid: "undefined" code: '22P02'+ at async handleList (api/subscriptions/plans.js:73:10)+```++## Root Cause Chain — Two Bugs, Both Must Be Fixed++### Bug 1 (API): No UUID validation before querying Postgres++In `api/subscriptions/plans.js`, the `handleList` function at line 54-79:++```javascript+const creatorId = params.get('creator_id');+// ...+rows = await sql`+ SELECT ...+ FROM subscription_plans+ WHERE creator_id = ${creatorId} AND active = true+`;+```++`creatorId` is passed directly to the SQL query with no format validation. When it's `"undefined"` or `"u_demo"`, Postgres throws 22P02 because the column type is `uuid`. The fix is to validate at the API boundary before touching the database.++### Bug 2 (Frontend): `creator_id=undefined` sent before user session resolves++In `src/dashboard-next/pages/monetize.js`:+```javascript+const creatorParam = encodeURIComponent(me.id); // line 62+// ...+safe(() => get(`/api/subscriptions/plans?creator_id=${creatorParam}`)) // line 72+```++`me` comes from `await requireUser()`. If `me.id` is somehow `undefined` (e.g., the user object returned from the API has an unexpected shape, or a Playwright script calls this before a session is established), then `encodeURIComponent(undefined)` produces the string `"undefined"`, which gets sent to the server.++This must be guarded on the frontend so the API call is never made with an invalid ID.++## What You Must Fix — Both Bugs, Completely++### Fix 1: API validation in `api/subscriptions/plans.js`++In the `handleList` function, after extracting `creatorId` and `agentId`, add UUID format validation:++```javascript+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++if (creatorId && !UUID_RE.test(creatorId)) {+ return error(res, 400, 'validation_error', 'creator_id must be a valid UUID');+}+if (agentId && !UUID_RE.test(agentId)) {+ return error(res, 400, 'validation_error', 'agent_id must be a valid UUID');+}+```++Place this validation after the existing check that requires at least one of `creatorId`/`agentId`. Both parameters need validation since both are passed to SQL as UUIDs.++This is the minimum change required to stop the 500 crashes. A 400 is the correct HTTP status — the input is invalid, not a server fault.++### Fix 2: Frontend guard in `src/dashboard-next/pages/monetize.js`++Before making the subscriptions plans API call, verify `me.id` is a non-empty string that looks like a UUID:++```javascript+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const creatorParam = me.id && UUID_RE.test(me.id) ? encodeURIComponent(me.id) : null;++// Only fetch if we have a valid creator ID+if (creatorParam) {+ safe(() => get(`/api/subscriptions/plans?creator_id=${creatorParam}`))+}+```++Read the full `monetize.js` file to understand the loading pattern before making this change — the `safe()` call is part of a parallel fetch block and the result is used to render subscription plan UI. If `creatorParam` is null, the plans section should render empty/default state rather than crash.++Look at how other conditional fetches in this file handle missing data and follow the same pattern. Do not leave the plans UI in an indefinite loading state if the fetch is skipped.++### Verify both fixes++1. Start the dev server: `npm run dev`+2. Navigate to the monetize/billing page as an authenticated user — subscriptions plans panel must render without errors.+3. Manually curl the API with invalid values and confirm 400 responses:+ ```bash+ curl "https://three.ws/api/subscriptions/plans?creator_id=undefined"+ # → {"error":"validation_error","message":"creator_id must be a valid UUID"} HTTP 400++ curl "https://three.ws/api/subscriptions/plans?creator_id=u_demo"+ # → {"error":"validation_error","message":"creator_id must be a valid UUID"} HTTP 400+ ```+4. Confirm `GET /api/subscriptions/plans?creator_id=<valid-uuid>` still returns plans correctly.++## Do Not++- Do not silently swallow invalid `creator_id` values by returning empty plans. Return 400 explicitly so callers know the input was wrong.+- Do not only fix the frontend without fixing the API — the API is the authoritative boundary and must validate inputs regardless of what the frontend does.+- Do not only fix the API without fixing the frontend — the frontend bug causes unnecessary error-level log noise and may degrade user experience if the 400 isn't handled gracefully.+- Do not use a try/catch around the SQL query to convert the 22P02 into a 200 empty response. Fix the root cause.++## Related Files++- `api/subscriptions/plans.js:54-79` (handleList — server fix)+- `src/dashboard-next/pages/monetize.js:62-72` (frontend guard)++Both files must be changed. This is a two-part bug. Fix the complete chain.diff --git a/docs/agent-fixes/fix-threews-subdomain-esm.md b/docs/agent-fixes/fix-threews-subdomain-esm.mdnew file mode 100644index 000000000..007c09f34--- /dev/null+++ b/docs/agent-fixes/fix-threews-subdomain-esm.md@@ -0,0 +1,89 @@+# Fix: api/threews/subdomain — 5 × 500 crashes (ESM import of @bonfida/spl-name-service)++## Context++`GET /api/threews/subdomain` returns 500 on every cold-start with a Node.js process crash. The error in Vercel logs:++```+[api] unhandled file:///var/task/node_modules/@bonfida/spl-name-service/dist/esm/instructions/burnInstruction.js:1+import"../node_modules/buffer/index.js";import{TransactionInstruction as i}from"@solana/web3.js"+```++This kills the entire process — the `SyntaxError: Cannot use import statement in a module` prevents the handler from ever running.++## Root Cause++Read `api/threews/subdomain.js` (the import block at the top) and `api/_lib/threews-sns.js` (the full file) before touching anything.++`api/threews/subdomain.js` imports from `api/_lib/threews-sns.js` at the **top level**. `threews-sns.js` in turn imports from `@bonfida/spl-name-service` and `@solana/web3.js` using static ESM `import` statements.++Vercel's Node.js serverless runtime bundles API functions as CommonJS (CJS) by default. When Vercel's bundler (`@vercel/nft`) encounters `@bonfida/spl-name-service`, it pulls in the ESM distribution (`dist/esm/`) which uses bare `import` statements. The CJS runtime cannot execute these and throws a `SyntaxError` at cold-start — before any request handler runs.++The fix must happen at the import level, not in the handler body.++## What You Must Fix — Completely++### Option A: Convert to dynamic import in `api/_lib/threews-sns.js`++This is the cleanest fix for Vercel CJS bundling.++In `api/_lib/threews-sns.js`, change the static imports of `@bonfida/spl-name-service` to dynamic imports that are resolved at call time. Specifically:++1. Remove the top-level `import { ... } from '@bonfida/spl-name-service'` statements.+2. Inside any function that uses the `@bonfida` exports, add:+ ```javascript+ const { NameRegistryState, getHashedNameSync, getNameAccountKeySync } = await import('@bonfida/spl-name-service');+ ```+3. Repeat the same pattern for any other ESM-only dependency that is currently statically imported.++After this change, the module loads without error at cold-start. The first request that calls a SNS lookup will pay a small dynamic import overhead (cached by Node after the first call).++### Option B: Add @bonfida to Vercel externals in vercel.json++In `vercel.json`, check whether there is an `externals` configuration for the Node bundler. If so, add:+```json+"functions": {+ "api/**/*.js": {+ "external": ["@bonfida/spl-name-service", "@solana/web3.js"]+ }+}+```++This tells `@vercel/nft` to leave these packages as native `require()`s rather than trying to inline them. This works only if the packages also ship a CJS distribution — verify this by checking `node_modules/@bonfida/spl-name-service/package.json` for a `main` or `exports.require` field.++Choose Option A if Option B is not available or if the package is ESM-only.++### Step 3: Verify the fix locally++After making the change:+```bash+node --input-type=module <<'EOF'+import('./api/threews/subdomain.js').then(() => console.log('OK')).catch(e => console.error('FAIL:', e.message))+EOF+```++Must print `OK`. If it prints `FAIL`, resolve the remaining ESM crash before deploying.++### Step 4: Test the endpoint end-to-end++1. Start the dev server (`npm run dev`)+2. Request `GET /api/threews/subdomain?label=test` as an unauthenticated user — should return 401 (not 500)+3. Request with a valid auth session and a `label` param — should return 200 with subdomain details++Confirm no crash in the Vercel logs after deploy.++### Step 5: Set ZAUTH_API_KEY (related issue)++The Vercel logs for this endpoint also show `[zauth] disabled: ZAUTH_API_KEY not set`. While not the crash cause, this means the zauth middleware is disabled. After fixing the ESM crash, set `ZAUTH_API_KEY` in Vercel env (see `fix-zauth-api-key.md`).++## Do Not++- Do not wrap the top-level import in a try/catch — ESM syntax errors in static imports cannot be caught at runtime.+- Do not remove the SNS integration — it must continue to function for subdomain registration.+- Do not use a stub or mock for `@bonfida/spl-name-service` — this must call the real Solana Name Service.++## Related Files++- `api/threews/subdomain.js` — static importer+- `api/_lib/threews-sns.js` — the file with the ESM imports (primary fix target)+- `vercel.json` — may need `externals` config (Option B only)diff --git a/docs/agent-fixes/fix-widgets-index-routing.md b/docs/agent-fixes/fix-widgets-index-routing.mdnew file mode 100644index 000000000..d637b53d7--- /dev/null+++ b/docs/agent-fixes/fix-widgets-index-routing.md@@ -0,0 +1,55 @@+# Fix: GET /api/widgets/index — 404/405 (verify vercel.json route is present)++## Context++`GET /api/widgets/index` returns 404 on 3 requests. The widgets listing endpoint lives at `/api/widgets` (not `/api/widgets/index`), but some callers are requesting the `/index` path.++## Current State — Verify Before Changing Anything++Read `vercel.json` and check whether the alias route already exists:++```bash+grep -n "widgets/index" vercel.json+```++As of the last audit, `vercel.json` already contains:+```json+{ "src": "/api/widgets/index", "dest": "/api/widgets" }+```++**If this route is already in vercel.json, this issue may be already fixed.**++## If the Route Is Missing++Add the route alias to `vercel.json`:+```json+{+ "src": "/api/widgets/index",+ "dest": "/api/widgets"+}+```++Place it before the wildcard `"/api/widgets/([A-Za-z0-9_-]+)"` route to ensure it takes priority.++## Additionally: Fix the frontend caller++Find the frontend code that calls `/api/widgets/index` and update it to call `/api/widgets` directly. The canonical path is `/api/widgets` — the `/index` alias is a workaround, not a permanent solution.++Search for the caller:+```bash+grep -rn "widgets/index" src/+```++Update any hit to use the correct path `/api/widgets`.++## Verify the fix++1. Check `vercel.json` for the `/api/widgets/index` → `/api/widgets` route+2. Search `src/` for any frontend code calling `/api/widgets/index` and update it+3. After deploy, request `GET https://three.ws/api/widgets/index` — must return 200 (same as `/api/widgets`)++## Related Files++- `vercel.json` — route table+- `api/widgets.js` or `api/widgets/index.js` — the handler (whichever exists)+- `src/` — frontend callers using the `/index` pathdiff --git a/docs/agent-fixes/fix-x402-pay-503.md b/docs/agent-fixes/fix-x402-pay-503.mdnew file mode 100644index 000000000..96d4736cc--- /dev/null+++ b/docs/agent-fixes/fix-x402-pay-503.md@@ -0,0 +1,91 @@+# Fix: POST /api/x402-pay — 2 × 503 (transient upstream payment service failure)++## Context++`POST /api/x402-pay` returned 503 (Service Unavailable) on 2 occasions. This is low volume (2 occurrences) but represents failed payment transactions — each 503 means a user's payment was not processed, which may or may not have debited their wallet.++## Root Cause++Read `api/x402-pay.js` in full before touching anything.++The 503 can come from:+1. **Coinbase x402 SDK upstream** — the payment settlement service returned 503 during the call to the Coinbase/x402 network+2. **Upstash Redis** — the feed/idempotency layer that `api/x402-pay.js` uses directly could be unavailable, returning 503+3. **A connected third-party service** (e.g., NFT minting, token transfer) being temporarily down++This is likely a transient infrastructure issue, not a code bug. However, the handler may not be retrying on transient 5xx from the upstream payment network before returning 503 to the client.++## What You Must Fix — Completely++### Step 1: Identify the exact source of the 503++Read `api/x402-pay.js` and trace what the handler calls:+1. Where does it interact with the x402 payment network?+2. What does it do with the Upstash Redis feed (`FEED_KEY = 'x402:pay:feed'`)?+3. Does the 503 come from a `res.status(503)` in the handler, or is it propagated from an upstream fetch?++Search for where the handler might return 503:+```bash+grep -n "503\|service_unavailable\|upstream\|settlement" api/x402-pay.js+```++### Step 2: Add retry logic for transient upstream 5xx++Wherever the handler makes an external HTTP call (to the Coinbase x402 network, a settlement API, or similar), add one retry on 503/504:++```javascript+async function fetchWithRetry(url, options, retries = 1) {+ const resp = await fetch(url, options);+ if ((resp.status === 503 || resp.status === 504) && retries > 0) {+ console.warn('[x402-pay] upstream', resp.status, '— retrying in 500ms');+ await new Promise(r => setTimeout(r, 500));+ return fetchWithRetry(url, options, retries - 1);+ }+ return resp;+}+```++Only retry transient errors (503, 504). Do NOT retry:+- 400/422 (bad payment request — client error)+- 402 (payment required — expected protocol response)+- 409 (conflict/duplicate — idempotency key already used)++### Step 3: Ensure idempotency before retry++The x402 protocol uses idempotency keys to prevent double-processing. Before adding retry logic, verify that:+1. The payment request includes an idempotency key in the upstream call+2. The retry sends the **same** idempotency key+3. The Upstash idempotency cache (see `api/_lib/x402/idempotency-cache.js`) is checked before the retry++If the upstream has already processed the payment and returns 503 for the settlement confirmation (not the payment itself), the retry is safe. If the 503 comes from the initial payment authorization, only retry if you're certain the first request did not go through.++### Step 4: Log the upstream response body on error++The current handler likely logs `console.error('[x402-pay]', err.message)` or similar. Enhance to include the upstream status and response body for future diagnosis:++```javascript+} catch (err) {+ const detail = err?.response ? `${err.response.status}: ${await err.response.text().catch(() => '')}`.slice(0, 300) : err?.message;+ console.error('[x402-pay] upstream failure:', detail);+ return error(res, 503, 'payment_upstream_error', 'Payment processing temporarily unavailable. Your card has not been charged. Please try again.');+}+```++The user-facing message is important — 503 from a payment endpoint must clearly tell users whether they were charged.++### Verify the fix++1. Start the dev server (`npm run dev`)+2. Simulate the payment flow with a test x402 request — must succeed on the first attempt+3. If you can simulate an upstream 503 (e.g., using a network intercept), verify the handler retries once and returns the upstream result, or returns a clear error on persistent failure++## Do Not++- Do not retry more than once — payment operations must be idempotent and minimal retries+- Do not swallow errors and return 200 — if payment fails, the response must reflect that+- Do not change the idempotency cache behavior++## Related Files++- `api/x402-pay.js` — the handler (primary fix target)+- `api/_lib/x402/idempotency-cache.js` — idempotency layerdiff --git a/docs/agent-fixes/fix-x402-upstash-redis.md b/docs/agent-fixes/fix-x402-upstash-redis.mdnew file mode 100644index 000000000..f9e63e61d--- /dev/null+++ b/docs/agent-fixes/fix-x402-upstash-redis.md@@ -0,0 +1,91 @@+# Fix: All x402 endpoints returning 500 — Missing Upstash Redis credentials++## Context++Every `/api/x402/*` endpoint in production is completely non-functional. Each request returns HTTP 500 with exit code 1 before the handler runs. The root cause is a module-level throw in `api/_lib/x402/idempotency-cache.js` that fires at cold-start when `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` are missing from the Vercel environment.++Affected endpoints (all return 500 on every request):+- `GET /api/x402/model-check`+- `GET /api/x402/dance-tip`+- `GET /api/x402/skill-marketplace`+- `GET /api/x402/symbol-availability`+- `POST /api/x402/mint-to-mesh-batch`++Error seen in Vercel logs:+```+Error: [x402-idempotency] UPSTASH_REDIS_REST_URL/TOKEN required in production.+Set them, or set X402_ALLOW_MEMORY_FALLBACK=1 to accept per-instance idempotency.+ at file:///var/task/api/_lib/x402/idempotency-cache.js:28:8+Node.js process exited with exit status: 1.+```++## Root Cause++Read `api/_lib/x402/idempotency-cache.js`. At line 27-31 there is a top-level `throw` that fires on module import when both `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` are absent AND `X402_ALLOW_MEMORY_FALLBACK` is not set. This crashes the entire Node.js process. Because this module is imported at the top level by every x402 handler, every cold-start fails.++## What You Must Do — Complete Fix Required++### Step 1: Check for existing Upstash credentials++1. Check `.env` and `.env.local` for `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`.+2. Run `vercel env ls` to see if the variables exist in the Vercel project (they may exist but not be pulled locally).+3. If the variables exist in Vercel but not locally, pull them: `vercel env pull`.++### Step 2: If credentials do not exist anywhere++You must provision a real Upstash Redis instance. Do not use `X402_ALLOW_MEMORY_FALLBACK=1` as the permanent solution — it breaks cross-replica idempotency (two Vercel instances can each accept the same payment ID, causing double-processing).++Options:+- Log into Upstash console and create a new Redis database (region: us-east-1 for lowest latency from Vercel iad1).+- Or check if `UPSTASH_REDIS_REST_URL` is referenced in other Vercel env vars under a different name (e.g., `KV_REST_API_URL` from a Vercel KV integration) and wire those.++### Step 3: Set the environment variables in Vercel++```bash+vercel env add UPSTASH_REDIS_REST_URL production+vercel env add UPSTASH_REDIS_REST_TOKEN production+```++Also add to `.env` for local dev (using a separate dev Upstash database or using `X402_ALLOW_MEMORY_FALLBACK=1` locally only).++### Step 4: Update `.env.example` or env documentation++If a `.env.example` file exists at the project root, add entries for these two variables with a comment explaining they are required for x402 idempotency in production.++### Step 5: Trigger a redeployment++After setting env vars in Vercel, trigger a redeploy:+```bash+vercel deploy --prod+```+Or push a commit to `main` which will trigger auto-deploy.++### Step 6: Verify++After deploy, hit each affected endpoint and confirm:+- `GET https://three.ws/api/x402/model-check` → should return 402 (payment required) or 200 (not 500)+- `GET https://three.ws/api/x402/dance-tip` → same+- `GET https://three.ws/api/x402/skill-marketplace` → same++If you cannot make live HTTP requests, at minimum verify locally:+```bash+UPSTASH_REDIS_REST_URL=<url> UPSTASH_REDIS_REST_TOKEN=<token> node -e "import('./api/_lib/x402/idempotency-cache.js').then(() => console.log('OK')).catch(e => console.error(e.message))"+```+Must print `OK`.++## Do Not++- Do not set `X402_ALLOW_MEMORY_FALLBACK=1` in production as the permanent fix. The comment in the code says this is explicitly for per-instance fallback only and degrades idempotency guarantees.+- Do not add a try/catch around the module throw to suppress it — that would silently break idempotency without anyone noticing.+- Do not stub out the idempotency cache with a no-op for production.++## Related Files++- `api/_lib/x402/idempotency-cache.js` — the module that throws+- `api/x402/model-check.js` — example endpoint importing the cache+- `api/x402/dance-tip.js`+- `api/x402/skill-marketplace.js`+- `api/x402/symbol-availability.js`+- `api/x402/mint-to-mesh-batch.js`++Fix this completely. Every x402 endpoint must return non-500 responses after this fix is applied.diff --git a/docs/agent-fixes/fix-zauth-api-key.md b/docs/agent-fixes/fix-zauth-api-key.mdnew file mode 100644index 000000000..c7d3cb7c6--- /dev/null+++ b/docs/agent-fixes/fix-zauth-api-key.md@@ -0,0 +1,66 @@+# Fix: ZAUTH_API_KEY not set — log noise on 30+ endpoints, zauth middleware disabled++## Context++Every authenticated endpoint emits `[zauth] disabled: ZAUTH_API_KEY not set` in logs. This appears on `api/agents`, `api/auth/wallets`, `api/avatars`, `api/keys`, `api/marketplace/agents/mine`, `api/mcp`, `api/users/me/purchased-skills`, `api/widgets`, `api/x402-pay`, and many more — essentially every endpoint that uses the zauth middleware.++This pollutes error logs so severely that real errors are buried.++## Root Cause++Read `api/_lib/zauth.js` in full before touching anything.++Line 28: `console.log('[zauth] disabled: ZAUTH_API_KEY not set')` — this fires on every request to any zauth-instrumented endpoint when `ZAUTH_API_KEY` is absent from the environment. The log level is `console.log` (which Vercel captures as INFO), but the sheer volume makes it appear as noise in filtered log views.++The `zauthProvider` middleware from `@zauthx402/sdk` provides request analytics and ZK-auth capabilities. When disabled, it's a no-op that falls back to the regular session/bearer auth — so the auth itself still works correctly.++## What You Must Fix — Completely++### Option A: Set ZAUTH_API_KEY in Vercel (recommended — enables the feature)++1. Obtain a `ZAUTH_API_KEY` from the zauthx402 dashboard (https://zauthx402.com or the API provider for this key).+2. Set it in Vercel production:+ ```bash+ vercel env add ZAUTH_API_KEY production+ ```+3. Add to `.env` for local dev:+ ```+ ZAUTH_API_KEY=<your-key>+ ```+4. Redeploy. The log line will stop appearing once the key is set.++### Option B: Suppress the log in production (if zauth is intentionally disabled)++If `ZAUTH_API_KEY` is intentionally not set (zauth is not being used), change the log in `api/_lib/zauth.js` line 28 from:++```javascript+console.log('[zauth] disabled: ZAUTH_API_KEY not set');+```++To:++```javascript+if (process.env.NODE_ENV !== 'production') {+ console.log('[zauth] disabled: ZAUTH_API_KEY not set');+}+```++This suppresses the log in production without removing the useful development-mode warning.++**Only choose Option B if you have explicitly decided not to use the zauth middleware.** If the feature is being built out or was accidentally left unconfigured, Option A is correct.++### Verify the fix++After implementing:+1. Deploy to Vercel+2. Make a request to any authenticated endpoint (e.g., `GET /api/agents`)+3. Check Vercel logs — `[zauth] disabled` must NOT appear++## Do Not++- Do not remove the `instrument()` function or the zauth import — the middleware is wired for a reason.+- Do not change `console.log` to `console.error` for this line — if you can't suppress it, log it at DEBUG level not ERROR level.++## Related Files++- `api/_lib/zauth.js:25–30` — the disabled-check log linediff --git a/migrations/001_create_agent_skill_prices.sql b/migrations/001_create_agent_skill_prices.sqldeleted file mode 100644index 5ee6cef92..000000000--- a/migrations/001_create_agent_skill_prices.sql+++ /dev/null@@ -1,34 +0,0 @@--- Migration to create the agent_skill_prices table--CREATE TABLE IF NOT EXISTS agent_skill_prices (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,- skill_name VARCHAR(255) NOT NULL,- amount BIGINT NOT NULL, -- Storing price in the smallest currency unit (e.g., lamports for SOL)- currency_mint VARCHAR(255) NOT NULL,- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),-- UNIQUE (agent_id, skill_name)-);---- Create an index for faster lookups by agent_id-CREATE INDEX IF NOT EXISTS idx_agent_skill_prices_agent_id ON agent_skill_prices(agent_id);---- A function to automatically update the updated_at timestamp-CREATE OR REPLACE FUNCTION trigger_set_timestamp()-RETURNS TRIGGER AS $$-BEGIN- NEW.updated_at = NOW();- RETURN NEW;-END;-$$ LANGUAGE plpgsql;---- A trigger to call the function before any update-CREATE TRIGGER set_timestamp-BEFORE UPDATE ON agent_skill_prices-FOR EACH ROW-EXECUTE PROCEDURE trigger_set_timestamp();--COMMENT ON TABLE agent_skill_prices IS 'Stores the prices for skills associated with an agent.';-COMMENT ON COLUMN agent_skill_prices.amount IS 'Price in the smallest unit of the currency (e.g., lamports).';diff --git a/migrations/001_create_skill_prices.sql b/migrations/001_create_skill_prices.sqldeleted file mode 100644index 5d50f4dea..000000000--- a/migrations/001_create_skill_prices.sql+++ /dev/null@@ -1,19 +0,0 @@---- Migration to create the agent_skill_prices table--CREATE TABLE IF NOT EXISTS agent_skill_prices (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- skill_id UUID NOT NULL,- creator_id UUID NOT NULL,- amount BIGINT NOT NULL,- currency_mint VARCHAR(44) NOT NULL, -- Solana public key length- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),-- -- A skill should only have one price set by its creator- UNIQUE (skill_id, creator_id)-);---- Create an index for efficient price lookups by skill-CREATE INDEX IF NOT EXISTS idx_agent_skill_prices_on_skill_id ON agent_skill_prices(skill_id);-\ No newline at end of filediff --git a/migrations/002_create_agent_skill_prices.sql b/migrations/002_create_agent_skill_prices.sqldeleted file mode 100644index bed08b48e..000000000--- a/migrations/002_create_agent_skill_prices.sql+++ /dev/null@@ -1,19 +0,0 @@--- migrations/002_create_agent_skill_prices.sql--CREATE TABLE agent_skill_prices (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- agent_id UUID NOT NULL REFERENCES agents(id),- skill_name VARCHAR(128) NOT NULL,- amount NUMERIC(20, 0) NOT NULL CHECK (amount >= 0),- currency_mint VARCHAR(64) NOT NULL,- creator_user_id UUID NOT NULL REFERENCES users(id),- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),- UNIQUE (agent_id, skill_name)-);--CREATE INDEX idx_agent_skill_prices_agent_id ON agent_skill_prices(agent_id);-CREATE INDEX idx_agent_skill_prices_skill_name ON agent_skill_prices(skill_name);--COMMENT ON TABLE agent_skill_prices IS 'Stores prices for agent skills set by creators.';-COMMENT ON COLUMN agent_skill_prices.amount IS 'Price in the smallest unit of the currency (e.g., lamports).';diff --git a/migrations/20260504120000_create_agent_skill_prices.sql b/migrations/20260504120000_create_agent_skill_prices.sqldeleted file mode 100644index 2b5140df3..000000000--- a/migrations/20260504120000_create_agent_skill_prices.sql+++ /dev/null@@ -1,24 +0,0 @@-CREATE TABLE IF NOT EXISTS agent_skill_prices (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,- skill_name VARCHAR(255) NOT NULL,- amount BIGINT NOT NULL,- currency_mint VARCHAR(255) NOT NULL,- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),-- UNIQUE (agent_id, skill_name)-);--CREATE OR REPLACE FUNCTION set_updated_at_timestamp()-RETURNS TRIGGER AS $$-BEGIN- NEW.updated_at = NOW();- RETURN NEW;-END;-$$ LANGUAGE plpgsql;--CREATE TRIGGER set_agent_skill_prices_updated_at-BEFORE UPDATE ON agent_skill_prices-FOR EACH ROW-EXECUTE FUNCTION set_updated_at_timestamp();diff --git a/migrations/20260504120000_create_agent_skill_prices_table.sql b/migrations/20260504120000_create_agent_skill_prices_table.sqldeleted file mode 100644index 11c5b10f3..000000000--- a/migrations/20260504120000_create_agent_skill_prices_table.sql+++ /dev/null@@ -1,30 +0,0 @@--- Up-CREATE TABLE agent_skill_prices (- id SERIAL PRIMARY KEY,- agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,- skill_name VARCHAR(255) NOT NULL,- amount BIGINT NOT NULL, -- Price in the smallest denomination (e.g., lamports)- currency_mint VARCHAR(255) NOT NULL, -- SPL Token mint address- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),-- CONSTRAINT unique_agent_skill UNIQUE (agent_id, skill_name)-);---- Optional: Create a trigger to automatically update the updated_at timestamp-CREATE OR REPLACE FUNCTION trigger_set_timestamp()-RETURNS TRIGGER AS $$-BEGIN- NEW.updated_at = NOW();- RETURN NEW;-END;-$$ LANGUAGE plpgsql;--CREATE TRIGGER set_timestamp-BEFORE UPDATE ON agent_skill_prices-FOR EACH ROW-EXECUTE PROCEDURE trigger_set_timestamp();---- Down-DROP TABLE agent_skill_prices;-DROP FUNCTION trigger_set_timestamp();diff --git a/public/demos/walkaround.html b/public/demos/walkaround.htmlindex 159ecdbbe..8573456c9 100644--- a/public/demos/walkaround.html+++ b/public/demos/walkaround.html@@ -73,7 +73,10 @@import { OrbitControls } from 'three/addons/controls/OrbitControls.js';import RAPIER from '@dimforge/rapier3d-compat';import { init as initRecast, NavMesh, NavMeshQuery } from '@recast-navigation/core';- import { threeToSoloNavMesh } from '@recast-navigation/three';+ // Pull NavMeshHelper here too so the second dynamic import below+ // goes through the same chunk — without this, rollup warns about the+ // module being both static and dynamic.+ import { threeToSoloNavMesh, NavMeshHelper } from '@recast-navigation/three';import nipplejs from 'nipplejs';const $ = (id) => document.getElementById(id);@@ -244,7 +247,6 @@navMesh = nm;navQuery = new NavMeshQuery(navMesh);- const { NavMeshHelper } = await import('@recast-navigation/three');navmeshHelper = new NavMeshHelper(navMesh, {navMeshMaterial: new THREE.MeshBasicMaterial({color: 0x3dc1ff, transparent: true, opacity: 0.18, depthWrite: false,diff --git a/public/reputation/index.html b/public/reputation/index.htmlindex 349a3cb15..02afa5385 100644--- a/public/reputation/index.html+++ b/public/reputation/index.html@@ -8,16 +8,10 @@<meta name="description" content="View and submit on-chain reviews for AI agents registered on three.ws." /><meta name="theme-color" content="#0a0a0a" />- <link rel="shortcut icon" href="/favicon.ico" />- <link rel="stylesheet" href="/fonts/fonts.css" />- <link rel="stylesheet" href="/style.css" />- <link rel="stylesheet" href="/nav.css" />- <link rel="stylesheet" href="/home.css" />- <link rel="stylesheet" href="/footer.css" />- <script defer src="/footer-newsletter.js"></script><!-- Importmap must be parsed before any <script type="module"> or- <link rel="modulepreload">. Keep it as the first script-of-any-kind- in <head> so reputation.js can `import "ethers"` against the CDN. -->+ <link rel="modulepreload">. Keep it as the FIRST child of <head>+ so Vite's auto-injected modulepreloads (added at the top of <head>+ during build) never end up before it. --><script type="importmap">{"imports": {@@ -25,6 +19,14 @@}}</script>++ <link rel="shortcut icon" href="/favicon.ico" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/home.css" />+ <link rel="stylesheet" href="/footer.css" />+ <script defer src="/footer-newsletter.js"></script><scripttype="module"src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"diff --git a/public/sitemap.xml b/public/sitemap.xmlnew file mode 100644index 000000000..47141a9ff--- /dev/null+++ b/public/sitemap.xml@@ -0,0 +1,547 @@+<?xml version="1.0" encoding="UTF-8"?>+<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">+ <url>+ <loc>https://three.ws/</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>weekly</changefreq>+ <priority>1.0</priority>+ </url>+ <url>+ <loc>https://three.ws/discover</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>daily</changefreq>+ <priority>0.9</priority>+ </url>+ <url>+ <loc>https://three.ws/gallery</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>daily</changefreq>+ <priority>0.8</priority>+ </url>+ <url>+ <loc>https://three.ws/walk</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>monthly</changefreq>+ <priority>0.7</priority>+ </url>+ <url>+ <loc>https://three.ws/marketplace</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>daily</changefreq>+ <priority>0.8</priority>+ </url>+ <url>+ <loc>https://three.ws/community</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/sitemap</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.4</priority>+ </url>+ <url>+ <loc>https://three.ws/create</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.9</priority>+ </url>+ <url>+ <loc>https://three.ws/app</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>monthly</changefreq>+ <priority>0.7</priority>+ </url>+ <url>+ <loc>https://three.ws/validation</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>monthly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/studio</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.8</priority>+ </url>+ <url>+ <loc>https://three.ws/artifact</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>monthly</changefreq>+ <priority>0.5</priority>+ </url>+ <url>+ <loc>https://three.ws/widgets</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.7</priority>+ </url>+ <url>+ <loc>https://three.ws/hydrate</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.7</priority>+ </url>+ <url>+ <loc>https://three.ws/features</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.8</priority>+ </url>+ <url>+ <loc>https://three.ws/launchpad</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.7</priority>+ </url>+ <url>+ <loc>https://three.ws/walkaround</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.7</priority>+ </url>+ <url>+ <loc>https://three.ws/brain</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.7</priority>+ </url>+ <url>+ <loc>https://three.ws/lipsync</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/lipsync/mic</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/avatar-artifact</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>monthly</changefreq>+ <priority>0.5</priority>+ </url>+ <url>+ <loc>https://three.ws/pay</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.9</priority>+ </url>+ <url>+ <loc>https://three.ws/pumpfun</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>daily</changefreq>+ <priority>0.8</priority>+ </url>+ <url>+ <loc>https://three.ws/pump-live</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>daily</changefreq>+ <priority>0.7</priority>+ </url>+ <url>+ <loc>https://three.ws/pump-dashboard</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>daily</changefreq>+ <priority>0.8</priority>+ </url>+ <url>+ <loc>https://three.ws/strategy-lab</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.7</priority>+ </url>+ <url>+ <loc>https://three.ws/vanity-wallet</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>monthly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/eth-vanity</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>monthly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/pump-visualizer</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.7</priority>+ </url>+ <url>+ <loc>https://three.ws/chat</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.8</priority>+ </url>+ <url>+ <loc>https://three.ws/agent</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.7</priority>+ </url>+ <url>+ <loc>https://three.ws/agents</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>daily</changefreq>+ <priority>0.7</priority>+ </url>+ <url>+ <loc>https://three.ws/reputation</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/login</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.4</priority>+ </url>+ <url>+ <loc>https://three.ws/register</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.4</priority>+ </url>+ <url>+ <loc>https://three.ws/forgot-password</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.2</priority>+ </url>+ <url>+ <loc>https://three.ws/docs</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.9</priority>+ </url>+ <url>+ <loc>https://three.ws/docs/quick-start</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.8</priority>+ </url>+ <url>+ <loc>https://three.ws/docs/agent-system</loc>+ <lastmod>2026-05-25</lastmod>+ </url>+ <url>+ <loc>https://three.ws/docs/erc8004</loc>+ <lastmod>2026-05-25</lastmod>+ </url>+ <url>+ <loc>https://three.ws/docs/embedding</loc>+ <lastmod>2026-05-25</lastmod>+ </url>+ <url>+ <loc>https://three.ws/docs/web-component</loc>+ <lastmod>2026-05-25</lastmod>+ </url>+ <url>+ <loc>https://three.ws/docs/mcp</loc>+ <lastmod>2026-05-25</lastmod>+ </url>+ <url>+ <loc>https://three.ws/docs/skills</loc>+ <lastmod>2026-05-25</lastmod>+ </url>+ <url>+ <loc>https://three.ws/docs/widgets</loc>+ <lastmod>2026-05-25</lastmod>+ </url>+ <url>+ <loc>https://three.ws/docs/api-reference</loc>+ <lastmod>2026-05-25</lastmod>+ </url>+ <url>+ <loc>https://three.ws/docs/sdk</loc>+ <lastmod>2026-05-25</lastmod>+ </url>+ <url>+ <loc>https://three.ws/docs/listings</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>monthly</changefreq>+ <priority>0.5</priority>+ </url>+ <url>+ <loc>https://three.ws/tutorials</loc>+ <lastmod>2026-05-25</lastmod>+ </url>+ <url>+ <loc>https://three.ws/blog</loc>+ <lastmod>2026-05-17</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.7</priority>+ </url>+ <url>+ <loc>https://three.ws/blog/three-ws-on-alibaba-cloud-marketplace</loc>+ <lastmod>2026-05-17</lastmod>+ <changefreq>monthly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/blog/three-ws-on-bnb-chain-dappbay</loc>+ <lastmod>2026-05-17</lastmod>+ <changefreq>monthly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/blog/how-to-embed-3d-onchain-agents</loc>+ <lastmod>2026-05-15</lastmod>+ <changefreq>monthly</changefreq>+ <priority>0.5</priority>+ </url>+ <url>+ <loc>https://three.ws/legal/privacy</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.2</priority>+ </url>+ <url>+ <loc>https://three.ws/legal/tos</loc>+ <lastmod>2026-05-25</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.2</priority>+ </url>+ <url>+ <loc>https://three.ws/news/</loc>+ <lastmod>2026-05-17</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.8</priority>+ </url>+ <url>+ <loc>https://three.ws/news/partnered-with-hackernoon</loc>+ <lastmod>2026-05-17</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/listed-on-bnb-chain-dappbay</loc>+ <lastmod>2026-05-17</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/live-on-alibaba-cloud-marketplace</loc>+ <lastmod>2026-05-17</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2055310365588922872</loc>+ <lastmod>2026-05-15</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2055309846556401735</loc>+ <lastmod>2026-05-15</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2055140064070717618</loc>+ <lastmod>2026-05-15</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2054404663802483072</loc>+ <lastmod>2026-05-13</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2053832201176027583</loc>+ <lastmod>2026-05-11</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2053804700609458214</loc>+ <lastmod>2026-05-11</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2053801703355629587</loc>+ <lastmod>2026-05-11</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2053698387263008827</loc>+ <lastmod>2026-05-11</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2052790746256920583</loc>+ <lastmod>2026-05-08</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2052603250524967045</loc>+ <lastmod>2026-05-08</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2052418108837781511</loc>+ <lastmod>2026-05-07</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2052167399399735476</loc>+ <lastmod>2026-05-06</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2052037977556287723</loc>+ <lastmod>2026-05-06</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2051893054584553680</loc>+ <lastmod>2026-05-06</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2051858503523066283</loc>+ <lastmod>2026-05-06</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2051858035862335505</loc>+ <lastmod>2026-05-06</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2051774915876098063</loc>+ <lastmod>2026-05-05</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2051690803203105230</loc>+ <lastmod>2026-05-05</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2051689230997618690</loc>+ <lastmod>2026-05-05</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2051616708482498843</loc>+ <lastmod>2026-05-05</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2051261108506558901</loc>+ <lastmod>2026-05-04</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2051140736201175323</loc>+ <lastmod>2026-05-04</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2050758788186353723</loc>+ <lastmod>2026-05-03</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2050753406109880576</loc>+ <lastmod>2026-05-03</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2050627547394916768</loc>+ <lastmod>2026-05-02</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2050229144676675999</loc>+ <lastmod>2026-05-01</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2050226678321102975</loc>+ <lastmod>2026-05-01</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2050221269732425928</loc>+ <lastmod>2026-05-01</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2050049239301165535</loc>+ <lastmod>2026-05-01</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2050016695897706885</loc>+ <lastmod>2026-05-01</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2049576641127682430</loc>+ <lastmod>2026-04-29</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2049576603324411933</loc>+ <lastmod>2026-04-29</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2049476546285740512</loc>+ <lastmod>2026-04-29</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2049447738434339171</loc>+ <lastmod>2026-04-29</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/news/2049412062837928202</loc>+ <lastmod>2026-04-29</lastmod>+ <changefreq>yearly</changefreq>+ <priority>0.6</priority>+ </url>+</urlset>diff --git a/src/dashboard-next/components/palette.js b/src/dashboard-next/components/palette.jsindex 3ed4029a6..762e26c92 100644--- a/src/dashboard-next/components/palette.js+++ b/src/dashboard-next/components/palette.js@@ -259,6 +259,7 @@ function onKeydown(e) {if (e.key === 'ArrowDown') { e.preventDefault(); move(1); return; }if (e.key === 'ArrowUp') { e.preventDefault(); move(-1); return; }if (e.key === 'Enter') { e.preventDefault(); activate(activeIndex); return; }+ if (e.key === 'Tab') { e.preventDefault(); inputEl.focus(); return; }}function move(delta) {diff --git a/src/pump/agent-token-widget.js b/src/pump/agent-token-widget.jsindex 7ec00bc0d..e8a1769f3 100644--- a/src/pump/agent-token-widget.js+++ b/src/pump/agent-token-widget.js@@ -18,6 +18,12 @@*/import { mountBondingCurve } from '../components/bonding-curve.js';+// pump-modals was previously dynamic-imported here, but it's already+// statically imported on /agent (via mountPumpModals) so the dynamic split+// produced no actual code-splitting — just a vite/rollup warning about a+// module being both static and dynamic. A plain static import keeps the+// withdraw path in the same chunk as the widget that calls it.+import { resolveUsdcAta, signAndSendVTx } from './pump-modals.js';const POLL_MS = 10_000;@@ -716,10 +722,6 @@ export class AgentTokenWidget {wd.disabled = true;wd.textContent = 'Preparing…';try {- // Lazy-import so non-owner views don't pay the bundle cost.- const [- { resolveUsdcAta, signAndSendVTx },- ] = await Promise.all([import('./pump-modals.js')]);const wallet =typeof window !== 'undefined' &&(window.solana || window.phantom?.solana || window.backpack || window.solflare);diff --git a/src/runtime/data-reactive.test.js b/src/runtime/data-reactive.test.jsindex 7593cbba2..fd2bf84af 100644--- a/src/runtime/data-reactive.test.js+++ b/src/runtime/data-reactive.test.js@@ -273,8 +273,13 @@ describe('startDataReactive — stop', () => {bindings: passthrough('ev'),});- // Wait for at least one tick- await new Promise((r) => setTimeout(r, 120));+ // Wait until at least one tick has been received. A fixed sleep here+ // flaked on slow CI workers where the first fetch + parse round-trip+ // took longer than the budget — poll up to 3s for a real signal.+ const t0 = Date.now();+ while (stats().received < 1 && Date.now() - t0 < 3000) {+ await new Promise((r) => setTimeout(r, 25));+ }const snapshot = { ...stats() };expect(snapshot.received).toBeGreaterThanOrEqual(1);