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
feat(pump): three token data module; refresh marketplace + home
nirholasaf79ba3ace3d
diff --git a/.prettierignore b/.prettierignoreindex abf2195f8..0668fcc76 100644--- a/.prettierignore+++ b/.prettierignore@@ -17,3 +17,5 @@ public/wallet-login.jspublic/artifact.jspublic/bazaar.jspublic/bazaar.html+public/paywall.js+public/paywall.htmldiff --git a/api/marketplace/[action].js b/api/marketplace/[action].jsindex 04272bd29..7b15b9175 100644--- a/api/marketplace/[action].js+++ b/api/marketplace/[action].js@@ -22,6 +22,7 @@ import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';import { publicUrl } from '../_lib/r2.js';import { clientIp, limits } from '../_lib/rate-limit.js';+import { markProviderCooldown } from '../_lib/provider-health.js';import { z } from 'zod';const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;@@ -793,16 +794,32 @@ async function handlePreview(req, res, id) {} catch (fetchErr) {const reason = fetchErr?.name === 'TimeoutError' ? 'timed out' : fetchErr.message;console.warn(`[preview:${route.name}] fetch failed: ${reason}`);+ // Unreachable upstream is a transient capacity/health problem — cool the+ // provider down so the shared breaker steers other requests away from it.+ void markProviderCooldown(route.name);if (i + 1 < routes.length) continue;- return error(res, 502, 'upstream_unavailable', 'preview backend unreachable');+ // Chain exhausted on an unreachable backend: 503 + Retry-After so the+ // client backs off and retries, never a hard 502 (matches /api/chat).+ res.setHeader('Retry-After', '20');+ return error(res, 503, 'rate_limited', 'Agent preview is briefly at capacity. Please try again in a few seconds.');}if (upstream.ok) break;const text = await upstream.text().catch(() => '');console.warn(`[preview:${route.name}] ${upstream.status} — ${text.slice(0, 200)}`);- const canFailOver = i + 1 < routes.length && (upstream.status === 429 || upstream.status >= 500);+ // 429 / 5xx are capacity or transient upstream failures — record a cooldown+ // for the shared provider-health breaker before failing over.+ const transient = upstream.status === 429 || upstream.status >= 500;+ if (transient) void markProviderCooldown(route.name);+ const canFailOver = i + 1 < routes.length && transient;if (canFailOver) continue;+ // Chain exhausted. A capacity/transient terminal failure degrades to+ // 503 + Retry-After (client backs off); a genuine bad status stays a 502.+ if (transient) {+ res.setHeader('Retry-After', '20');+ return error(res, 503, 'rate_limited', 'Agent preview is briefly at capacity. Please try again in a few seconds.');+ }return error(res, 502, 'upstream_error', `preview backend returned ${upstream.status}`);}diff --git a/pages/home.html b/pages/home.htmlindex e48729958..dac99d6fb 100644--- a/pages/home.html+++ b/pages/home.html@@ -2432,7 +2432,7 @@<noscript><style>.reveal{opacity:1!important;transform:none!important}.hero-text>*{opacity:1!important;transform:none!important}</style></noscript><script type="module" src="https://three.ws/agent-3d/latest/agent-3d.js"></script>- <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://three.ws/#organization","name":"three.ws","url":"https://three.ws","logo":"https://three.ws/og-image.png","description":"three.ws is the AI-agent layer for the open web: build, embed, monetize, and trade autonomous agents with real 3D avatars, on-chain identity (ERC-8004), pay-per-call (x402), and pump.fun token launches.","sameAs":["https://x.com/trythreews","https://github.com/nirholas/three.ws"]},{"@type":"WebSite","@id":"https://three.ws/#website","name":"three.ws","url":"https://three.ws","description":"Give your AI a body.","publisher":{"@id":"https://three.ws/#organization"},"potentialAction":{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://three.ws/discover?q={search_term_string}"},"query-input":"required name=search_term_string"}}]}</script>+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://three.ws/#organization","name":"three.ws","url":"https://three.ws","logo":"https://three.ws/og-image.png","description":"three.ws is the AI-agent layer for the open web: build, embed, monetize, and trade autonomous agents with real 3D avatars, on-chain identity (ERC-8004), pay-per-call (x402), and pump.fun token launches.","sameAs":["https://x.com/trythreews","https://github.com/nirholas/three.ws","https://www.coingecko.com/en/coins/three-ws","https://www.npmjs.com/package/three.ws","https://registry.modelcontextprotocol.io/?q=threews","https://coinmarketcap.com/community/profile/three_ws","https://hackernoon.com/u/three-ws"]},{"@type":"WebSite","@id":"https://three.ws/#website","name":"three.ws","url":"https://three.ws","description":"Give your AI a body.","publisher":{"@id":"https://three.ws/#organization"},"potentialAction":{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://three.ws/discover?q={search_term_string}"},"query-input":"required name=search_term_string"}}]}</script></head><body>diff --git a/public/features.json b/public/features.jsonindex 08cabb923..cc42c4341 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-08T05:24:40.143Z",+ "generated_at": "2026-06-08T05:30:39.887Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/src/pump/pump-modals.js b/src/pump/pump-modals.jsindex 5935ebf31..a19f58803 100644--- a/src/pump/pump-modals.js+++ b/src/pump/pump-modals.js@@ -44,6 +44,16 @@ const M_STYLES = `color: rgba(255,255,255,0.6); margin-top: 0.4rem;}.pmodal-slider-label b { color: #a4f0bc; font-weight: 500; }+.pmodal-quote-toggle { display: flex; gap: 0.4rem; margin-top: 0.3rem; }+.pmodal-quote-opt {+ flex: 1; padding: 0.5rem 0.7rem; border-radius: 8px; cursor: pointer;+ background: rgba(255,255,255,0.04); border: 1px solid rgba(255,255,255,0.08);+ color: rgba(255,255,255,0.7); font-size: 0.84rem; font-weight: 600; transition: 0.15s;+}+.pmodal-quote-opt:hover { background: rgba(255,255,255,0.08); }+.pmodal-quote-opt.active {+ background: rgba(120,200,140,0.18); border-color: rgba(120,200,140,0.4); color: #d8f5e2;+}.pmodal-actions { display: flex; gap: 0.5rem; margin-top: 1.2rem; }.pmodal-btn {flex: 1; padding: 0.6rem 0.9rem; border-radius: 8px; cursor: pointer;@@ -398,8 +408,6 @@ function openLaunch({ identity, agentId, avatarId, formData }) {let step = 1;// Aborts the in-browser 3ws-mark grind if the user backs out mid-stamp.let launchGrindAbort = null;- // USDC mainnet mint — pump.fun v2 quote when the user picks USDC pair.- const USDC_MAINNET = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';async function buildMetadata(name, symbol, description) {let imageDataUrl = null;diff --git a/src/pump/three-token-data.js b/src/pump/three-token-data.jsnew file mode 100644index 000000000..20b6bc763--- /dev/null+++ b/src/pump/three-token-data.js@@ -0,0 +1,285 @@+// src/pump/three-token-data.js+// ---------------------------------------------------------------------------+// Single source of truth for $THREE token data on the client.+//+// Every holder surface (dashboard "your position", token page price header,+// revenue-share / rewards, the live HUD) used to fetch the same handful of+// /api/three-token/* endpoints inline and drift apart. This module centralises+// those reads into one subscribable store so each surface renders from one+// snapshot and they never disagree.+//+// It wraps only EXISTING endpoints — no new fetch primitives:+// GET /api/three-token/stats (public, edge-cached) → protocol + token market+// GET /api/three-token/revenue-share (authed; 401 = guest) → pro-rata pool math+// GET /api/three-token/activity → recent revenue events+// GET /api/three-token/burns → deploy-burn ledger+// POST /api/wallet/balances {chain:'solana',address} → the holder's position+//+// Design: a plain subscribable store (this codebase is vanilla JS modules, not+// React). Each top-level field carries its OWN status so a widget can render an+// independent loading / empty / error state without waiting on the others.+//+// Only $THREE is ever referenced here. The mint below is the canonical $THREE+// contract; the store also reads the mint back from /stats so there is a single+// server-authoritative value used to locate the holder's position row.++import { get, post, getMe, ApiError } from '../dashboard-next/api.js';++/** Canonical $THREE mint. The one and only coin. */+export const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++// A Solana address is base58, 32–44 chars. Used to ignore an EVM (0x…) primary+// wallet when resolving which address to read a Solana balance for.+const SOL_ADDRESS_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++const DEFAULT_POLL_MS = 30_000;+const MIN_POLL_MS = 10_000;++function errInfo(err) {+ if (err instanceof ApiError) return { status: err.status, code: err.code, message: err.message };+ return { status: 0, code: 'network_error', message: err?.message || 'request failed' };+}++function freshState() {+ return {+ protocol: { status: 'loading', token: null, protocol: null, source: null, updatedAt: null, error: null },+ revenueShare: { status: 'loading', unauthenticated: false, error: null },+ activity: { status: 'loading', events: [], error: null },+ burns: { status: 'loading', burns: [], total_burned: null, burn_per_deploy: null, error: null },+ // position is `idle` until a wallet is known. Statuses:+ // idle | loading | unauthenticated | no_wallet | zero | ok | error+ position: { status: 'idle', wallet: null, amount: null, usd: null, pctOfSupply: null, price: null, error: null },+ };+}++/**+ * Create a $THREE data store.+ *+ * @param {object} [opts]+ * @param {number} [opts.pollMs=30000] Poll cadence for protocol + activity (min 10s).+ * @param {string} [opts.wallet] Explicit Solana address for the position+ * (e.g. the connected wallet the UI already+ * knows). When omitted, the store resolves it+ * from the signed-in user.+ * @param {Element} [opts.anchorEl] When the node leaves the DOM, the store+ * tears itself down automatically.+ * @param {boolean} [opts.autoStart=true] Kick an initial refresh + position fetch and+ * start polling immediately.+ * @returns {{+ * getState: () => object,+ * subscribe: (fn: (state: object) => void) => (() => void),+ * refresh: () => Promise<void>,+ * refreshPosition: () => Promise<void>,+ * setWallet: (address: string|null) => void,+ * destroy: () => void,+ * }}+ */+export function createThreeTokenData(opts = {}) {+ const pollMs = Math.max(MIN_POLL_MS, Number(opts.pollMs) || DEFAULT_POLL_MS);+ const autoStart = opts.autoStart !== false;++ let state = freshState();+ const subs = new Set();+ let timer = null;+ let observer = null;+ let destroyed = false;+ let walletOverride = (opts.wallet && SOL_ADDRESS_RE.test(opts.wallet)) ? opts.wallet : null;++ function getState() {+ return state;+ }++ function emit() {+ for (const fn of subs) {+ try { fn(state); } catch (err) { console.error('[three-token-data] subscriber threw', err); }+ }+ }++ // Replace one field immutably so subscribers can cheaply diff by reference.+ function patch(key, partial) {+ if (destroyed) return;+ state = { ...state, [key]: { ...state[key], ...partial } };+ emit();+ }++ async function loadProtocol() {+ try {+ const data = await get('/api/three-token/stats');+ patch('protocol', {+ status: 'ok',+ token: data?.token ?? null,+ protocol: data?.protocol ?? null,+ source: data?.token?.source ?? null,+ updatedAt: Date.now(),+ error: null,+ });+ } catch (err) {+ patch('protocol', { status: 'error', error: errInfo(err) });+ }+ }++ async function loadActivity() {+ try {+ const data = await get('/api/three-token/activity');+ patch('activity', { status: 'ok', events: Array.isArray(data?.events) ? data.events : [], error: null });+ } catch (err) {+ patch('activity', { status: 'error', error: errInfo(err) });+ }+ }++ async function loadBurns() {+ try {+ const data = await get('/api/three-token/burns');+ patch('burns', {+ status: 'ok',+ burns: Array.isArray(data?.burns) ? data.burns : [],+ total_burned: data?.total_burned ?? null,+ burn_per_deploy: data?.burn_per_deploy ?? null,+ error: null,+ });+ } catch (err) {+ patch('burns', { status: 'error', error: errInfo(err) });+ }+ }++ async function loadRevenueShare() {+ try {+ const data = await get('/api/three-token/revenue-share');+ patch('revenueShare', { status: 'ok', unauthenticated: false, error: null, ...data });+ } catch (err) {+ // A 401 is not an error here — it just means the visitor is a guest. The+ // pool-level numbers still come from /stats; only the per-user view is gated.+ if (err instanceof ApiError && err.status === 401) {+ patch('revenueShare', { status: 'ok', unauthenticated: true, error: null });+ } else {+ patch('revenueShare', { status: 'error', error: errInfo(err) });+ }+ }+ }++ // Resolve which Solana address to read the position for. Returns a base58+ // address string, or a sentinel describing why there isn't one.+ async function resolveWallet() {+ if (walletOverride) return walletOverride;+ let me;+ try {+ me = await getMe();+ } catch (err) {+ return { error: errInfo(err) };+ }+ if (!me) return { unauthenticated: true };+ const candidates = [me.solana_address, me.sol_address, me.solana, me.wallet_address];+ for (const c of candidates) {+ if (typeof c === 'string' && SOL_ADDRESS_RE.test(c)) return c;+ }+ return { noWallet: true };+ }++ async function loadPosition() {+ patch('position', { status: 'loading', error: null });+ const resolved = await resolveWallet();++ if (resolved && resolved.unauthenticated) {+ patch('position', { status: 'unauthenticated', wallet: null, amount: null, usd: null, pctOfSupply: null });+ return;+ }+ if (resolved && resolved.noWallet) {+ patch('position', { status: 'no_wallet', wallet: null, amount: null, usd: null, pctOfSupply: null });+ return;+ }+ if (resolved && resolved.error) {+ patch('position', { status: 'error', error: resolved.error });+ return;+ }++ const wallet = resolved;+ const mint = state.protocol.token?.mint || THREE_MINT;+ const price = state.protocol.token?.price_usd ?? null;+ const supply = Number(state.protocol.token?.supply) || null;++ try {+ const bal = await post('/api/wallet/balances', { chain: 'solana', address: wallet });+ const row = (bal?.tokens || []).find((t) => t && t.mint === mint);+ const amount = row ? Number(row.amount) || 0 : 0;++ if (amount <= 0) {+ patch('position', { status: 'zero', wallet, amount: 0, usd: 0, pctOfSupply: 0, price });+ return;+ }++ const usd = row.usd != null && Number.isFinite(Number(row.usd))+ ? Number(row.usd)+ : (price != null ? amount * Number(price) : null);+ const pctOfSupply = supply ? amount / supply : null;+ patch('position', { status: 'ok', wallet, amount, usd, pctOfSupply, price, error: null });+ } catch (err) {+ patch('position', { status: 'error', wallet, error: errInfo(err) });+ }+ }++ // ── Public operations ────────────────────────────────────────────────────++ async function refresh() {+ await Promise.all([loadProtocol(), loadActivity(), loadBurns(), loadRevenueShare()]);+ }++ async function refreshPosition() {+ // Position depends on the latest protocol snapshot (mint + supply + price).+ // If protocol hasn't loaded yet, pull it first so % of supply / USD resolve.+ if (state.protocol.status !== 'ok') await loadProtocol();+ await loadPosition();+ }++ function setWallet(address) {+ const next = (address && SOL_ADDRESS_RE.test(address)) ? address : null;+ if (next === walletOverride) return;+ walletOverride = next;+ if (!destroyed) void refreshPosition();+ }++ function subscribe(fn) {+ if (typeof fn !== 'function') return () => {};+ subs.add(fn);+ // Push the current snapshot immediately so late subscribers aren't blank.+ try { fn(state); } catch (err) { console.error('[three-token-data] subscriber threw', err); }+ return () => subs.delete(fn);+ }++ function destroy() {+ if (destroyed) return;+ destroyed = true;+ if (timer) { clearInterval(timer); timer = null; }+ if (observer) { observer.disconnect(); observer = null; }+ subs.clear();+ }++ // Tear down automatically when the anchor element leaves the DOM, so a store+ // tied to a page section can't keep polling after the section is gone.+ function watchAnchor(el) {+ if (!el || typeof MutationObserver === 'undefined' || typeof document === 'undefined') return;+ observer = new MutationObserver(() => {+ if (!el.isConnected) destroy();+ });+ observer.observe(document.body, { childList: true, subtree: true });+ }++ if (opts.anchorEl) watchAnchor(opts.anchorEl);++ if (autoStart) {+ void refresh();+ void refreshPosition();+ if (typeof setInterval !== 'undefined') {+ timer = setInterval(() => {+ if (destroyed) return;+ // Poll only the live protocol + activity surfaces. Position is on+ // demand (after sign-in / a trade) so we don't hammer the balances RPC.+ void loadProtocol();+ void loadActivity();+ }, pollMs);+ }+ }++ return { getState, subscribe, refresh, refreshPosition, setWallet, destroy };+}++export default createThreeTokenData;diff --git a/tasks/week-2026-06-08/A2-chat-llm-fallback-502.md b/tasks/week-2026-06-08/A2-chat-llm-fallback-502.mddeleted file mode 100644index d54a6564a..000000000--- a/tasks/week-2026-06-08/A2-chat-llm-fallback-502.md+++ /dev/null@@ -1,115 +0,0 @@-# A2 — Fix `/api/chat` 502s by hardening the LLM fallback chain--**Track:** A — production fire · **Priority:** P0 · **Effort:** ~half day · **Depends on:** none-**Human prerequisite:** confirm `ANTHROPIC_API_KEY` is set in Vercel prod (see below) before relying on the code fix.--## Context (evidence)--`/api/chat` is the **single most-used endpoint** in production and is failing **~38% of the time**:-in the last 24h, **102 × 200 vs 66 × 502 + 4 × 500**. The same root cause also 502s-`/api/marketplace/agents/:id/preview` (8×) and `/api/persona/extract` (2×).--Log lines:-- `[chat:openrouter] <code> (final — all <n> route(s) exhausted) Provider returned error`-- `[chat:groq] Rate limit reached for model llama-3.3-70b-versatile`-- `[brain:gpt-4o-mini] native provider failed (You exceeded your current quota...)`-- `[preview:openai] You exceeded your current quota`--### Root cause (already investigated — verify, then fix)--The deployed fallback chain is effectively **`groq (429) → openrouter (flaky free tier) → openai-(quota-dead)`**. The one reliable paid link, **Anthropic**, is (a) likely **unset in prod** and-(b) **structurally starved**: `MAX_FALLBACK_ATTEMPTS = 3` with the primary + a *same-Groq-account*-sibling occupying slots 0–1, so Anthropic (4th in default order) often never gets a slot. When-Groq throttles and OpenRouter 5xxes in the same request, the terminal path returns a **hard 502**-instead of degrading.--Key locations (confirm before editing — line numbers may have drifted):-- `api/_lib/chat-models.js:122` — `DEFAULT_PROVIDER_ORDER = ['groq','openrouter','anthropic','openai']`-- `api/_lib/chat-models.js:150` — `MAX_FALLBACK_ATTEMPTS = 3`-- `api/chat.js:711-735` — `pickProvider` (skips providers whose key is falsy)-- `api/chat.js:747-752` — `FALLBACK_SIBLINGS` (the same-account Groq sibling)-- `api/chat.js:770-801` — `buildFallbackChain`-- `api/chat.js:576-586` — terminal response (the hard 502)-- `api/chat.js:404-423` — existing per-call/total timeout-budget pattern to mirror elsewhere-- `api/brain/chat.js:21, 363-375` — `maxDuration=120`, `streamText` with no abort budget (caused a 30.7s near-timeout)-- `api/persona/extract.js:191-201` and `api/persona/preview.js:137-147` — single-shot, **no failover**-- `api/marketplace/[action].js:804, 806, 845` — preview chain order + failover condition + 502-- `api/_lib/llm.js:78, 115-148` — shared `llmComplete` with ordered failover + per-attempt `AbortSignal.timeout` (currently only adds Anthropic for BYOK)-- `api/_lib/cache.js` — exists, currently unused by chat; use it for the circuit-breaker--## Human prerequisite (do this first)--Confirm `ANTHROPIC_API_KEY` is present in Vercel production env for **both** deploy targets. If-absent, set it (the platform has Anthropic access per CLAUDE.md). Also **remove or top up** the-quota-dead `OPENAI_API_KEY` — as-is it only burns the final attempt before the 502. Note the-outcome in your commit message. The code changes below assume Anthropic is keyed.--## What to do (code)--1. **Reorder the chain to Anthropic-first** in `api/_lib/chat-models.js:122`:- `DEFAULT_PROVIDER_ORDER = ['anthropic', 'groq', 'openrouter', 'openai']`.- Mirror the same order in the preview chain at `api/marketplace/[action].js:845`.--2. **Stop wasting a fallback slot on the same Groq account.** Either drop the Groq sibling from- `FALLBACK_SIBLINGS.groq` (`api/chat.js:749`) so a fallback slot goes to a *different* provider,- or raise `MAX_FALLBACK_ATTEMPTS` to `4` (`chat-models.js:150`). Prefer dropping the same-account- sibling — real provider diversity beats a second attempt against the throttled account.--3. **Never return a hard 502 on capacity exhaustion.** In the terminal path- (`api/chat.js:576-586`), broaden the "rate limited" branch so that **any** all-routes-exhausted- outcome (429 *or* upstream 5xx / "Provider returned error") returns **`503` with a- `Retry-After` header**, not a 502. The client already knows how to back off on 503+Retry-After.- (Optional, nicer: emit a graceful `200` SSE `done` with a short "assistant is briefly at- capacity, try again" message so the chat UI never shows a hard error.)--4. **Add a provider-health circuit breaker.** When a provider returns 429/5xx, record a short- cooldown (30–60s) in `api/_lib/cache.js`; have `buildFallbackChain` (`api/chat.js:770-801`) skip- a provider that is in cooldown. This stops every request from re-hitting Groq while it is- globally throttling — the mechanism that turns one throttle window into dozens of 502s.--5. **Bound `/api/brain/chat`.** Add an `abortSignal: AbortSignal.timeout(budgetMs)` to each- `streamText` attempt (`api/brain/chat.js:363-375`), where `budgetMs` is a per-attempt ceiling- (~20s) bounded by remaining wall-clock — mirror the `api/chat.js:404-423` pattern. A hung native- provider must abort fast and hand off to the OpenRouter fallback while time remains.--6. **Give persona/extract + persona/preview real failover.** Replace the hand-rolled single-shot- `resolveProvider()` calls (`extract.js:191-201`, `preview.js:137-147`) with the shared- `llmComplete` from `api/_lib/llm.js`. Extend `llm.js` `providerChain` (`llm.js:78`) to also use a- **server** `env.ANTHROPIC_API_KEY` (today it only adds Anthropic for a passed BYOK key) so these- endpoints get the same Anthropic-first ordered failover.--## Acceptance criteria--- [ ] With Anthropic keyed, the happy path resolves on attempt 0 (Anthropic); fallbacks only- engage when Anthropic itself errors.-- [ ] An exhausted chain returns **503 + Retry-After**, never a hard 502.-- [ ] A throttled provider is skipped for a cooldown window on subsequent requests.-- [ ] `/api/brain/chat` cannot exceed its abort budget per attempt; no more ~30s hangs.-- [ ] `/api/persona/extract` and `/api/persona/preview` fail over across providers instead of- 502-ing on the first non-2xx.-- [ ] No regression to streaming, tool-calling, or rate-limit headers on `/api/chat`.--## Verification--1. `npx vitest run` for any chat/LLM tests under `api/` and `tests/`.-2. Locally (`npm run dev`), drive `/api/chat` with a normal prompt and confirm a 200 stream.-3. Simulate exhaustion: temporarily unset the upstream keys in a local env and confirm the endpoint- returns **503 + Retry-After** (not 502), and that the cooldown path is exercised.-4. Confirm `/api/brain/chat` aborts an artificially slow attempt within budget and still answers via- fallback.--## Rules--Obey [CLAUDE.md](../../CLAUDE.md). No mocks. Default to the latest Claude models for the Anthropic-link (e.g. `claude-sonnet-4-6` for chat); do not invent model IDs — verify against the codebase's-existing Anthropic model constants. If you touch model selection, consult the `claude-api` skill-reference rather than guessing IDs.--## Completion protocol--1. Re-read your diff (`git diff`) and confirm every line is justified.-2. Delete this file: `tasks/week-2026-06-08/A2-chat-llm-fallback-502.md`.-3. Commit your code change **and** this file's deletion together, e.g.:- `git add -A && git commit -m "fix(chat): Anthropic-first fallback, 503-not-502 on exhaustion, provider cooldown, brain abort budget; close A2"`-4. Do **not** push — the human controls pushes.diff --git a/tasks/week-2026-06-08/A4-pump-by-agent-uuid-guard.md b/tasks/week-2026-06-08/A4-pump-by-agent-uuid-guard.mddeleted file mode 100644index bab22484b..000000000--- a/tasks/week-2026-06-08/A4-pump-by-agent-uuid-guard.md+++ /dev/null@@ -1,63 +0,0 @@-# A4 — Guard `/api/pump/by-agent` (and audit siblings) against non-UUID input--**Track:** A — production fire · **Priority:** P1 · **Effort:** 1–2h · **Depends on:** none--## Context (evidence)--Production logs:--```-[api] unhandled NeonDbError: invalid input syntax for type uuid: "agent"- at execute (file:///var/task/api/pump/[action].js:...)-```--`GET /api/pump/by-agent` (handled by `handleByAgent` in `api/pump/[action].js`, registered around-line 129 / defined around line 1915) passes a non-UUID value (the literal string `"agent"`) straight-into a `uuid`-typed SQL query, which throws `NeonDbError` and 500s. This is the same class of bug-the agents and bounties routes were already hardened against (see-`api/bounties/[id].js:14` — `if (!isUuid(id)) return error(res, 404, ...)`).--## What to do--1. In `handleByAgent` (`api/pump/[action].js`), validate the agent identifier **before** it reaches- any `uuid`-typed query. Use the existing helper: `import { isUuid } from '../_lib/validate.js'`- (confirm the relative path from this file). If the id is missing or not a UUID, return a clean- `400 validation_error` (or `404 not_found` if that matches the endpoint's contract for "unknown- agent") — **never** let it reach the DB.- - Determine where the bad `"agent"` value originates: is it `req.query.agent` /- `req.query.agent_id` defaulting to the literal `"agent"`, or a path segment being misparsed?- Fix the source too, not just the guard, if it's a parsing bug.-2. **Audit the whole dispatcher** `api/pump/[action].js` for any other handler that interpolates a- user-supplied value into a `uuid`/typed column without validation. Add the same guard wherever a- raw id reaches SQL. (`handleByAgent` is the one in the logs, but harden siblings while you're- here.)-3. Ensure errors in this dispatcher are caught at the boundary and logged with a structured prefix- (e.g. `console.error('[pump/by-agent]', ...)`) rather than surfacing as `unhandled NeonDbError`.--## Acceptance criteria--- [ ] `GET /api/pump/by-agent` with a missing/non-UUID agent id returns a clean 400/404, **no**- `NeonDbError`, **no** 500.-- [ ] A valid agent UUID still returns the correct mint + stats + burn history (no regression).-- [ ] Other id-consuming branches in `api/pump/[action].js` are guarded the same way.-- [ ] The dispatcher logs structured errors at the boundary.--## Verification--1. `npm run dev`, then:- - `curl '/api/pump/by-agent'` → clean 400/404.- - `curl '/api/pump/by-agent?agent_id=not-a-uuid'` → clean 400/404.- - `curl '/api/pump/by-agent?agent_id=<real uuid>'` → 200 with data.-2. Run any existing pump API tests: `npx vitest run` (filter to pump if available).--## Rules--Obey [CLAUDE.md](../../CLAUDE.md). Errors handled at boundaries; internal code trusts itself.--## Completion protocol--1. Re-read your diff (`git diff`) and confirm every line is justified.-2. Delete this file: `tasks/week-2026-06-08/A4-pump-by-agent-uuid-guard.md`.-3. Commit your code change **and** this file's deletion together, e.g.:- `git add -A && git commit -m "fix(pump): UUID-guard by-agent and sibling handlers to stop NeonDbError 500s; close A4"`-4. Do **not** push — the human controls pushes.