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: enhance Redis error handling and implement direct-insert timeout for usage events; add regression test for avatar API performance
zprv84c718ddbf98
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f342e788a..24a82ffce 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-06-28- **$THREE payments ride out brief price-feed blips instead of failing** — Paid actions priced in $THREE (Forge high tier, spins, marketplace) no longer fail when every live price feed happens to miss on the same request. The price layer now keeps a recent last-known-good price and serves it through a momentary simultaneous outage of Jupiter and the backup feeds, so a quote is never rejected over a transient blip. Prices older than five minutes are still refused — a payment is never priced off a stale number. And on the rare moment the payment rail genuinely is catching its breath, you now see a clear "briefly unavailable — try again" message instead of a raw "internal error" support code. (`/three-token`) `[fix]`+- **A free, no-login 3D Studio you can add to ChatGPT** — We shipped a brand-new connector that turns any chat into a 3D modeling studio — completely free, with no account, no payment, and nothing to install on your end. It exposes five tools: generate a textured 3D model from a text prompt, build a 3D avatar from text or a reference image, forge an art-directed mesh, auto-rig a static model so it's ready to animate, and do prompt-to-rigged-avatar in a single step. Every result comes back as a downloadable GLB plus an interactive viewer link you can rotate and inspect right in the conversation. It runs entirely on our own model infrastructure — we cover the generation cost — with built-in rate limits so it stays fast and available for everyone. This is a separate, self-contained server from our existing tools, purpose-built so anyone can add prompt-to-3D to their assistant in one click. `[feature]`- **A quiet Money Pulse now points you to the live feed instead of a dead end** — When the Money Pulse (/pulse) showed "No money moving — yet," it gave no hint that the silence was just the network you were on — or the filter you'd clicked. The feed has no time limit, so mainnet — where the real tips, launches, trades and payments flow — is effectively never empty; almost every empty view was the devnet test network, or a filter (like Trades or Marketplace) that happened to be quiet while the platform was busy with other money. The empty state now reads the situation honestly: a quiet filter says "No trades yet" instead of "all quiet" and offers a one-click "View all activity" that clears the filter, while a quiet network checks the other one in the background and offers "See live activity on mainnet" — either switch flips the whole page, feed and every stat panel, in lockstep. On devnet the copy now explains it's a test network and most money moves on mainnet, so a quiet feed reads as honest, not broken. (`/pulse`) `[improvement]`- **Agent mirror (copy-trading) panel loads again** — Opening an agent's mirror panel — the copy-trading social graph where your agent follows a proven leader within your spend policy — was failing with a 404. The endpoints that power it (your following list, a leader's public track record and follower count, the recent-fills feed, and the follow/unfollow/pause/sync controls) all live under /api/agents/:id/mirror, but our production routing only recognised single-segment agent paths, so every mirror request fell through to the not-found page. We widened the route so the agent dispatcher receives these sub-paths, restoring the mirror panel and its sibling agent endpoints. (`/mirror`) `[fix]`- **Agent Reputation Leaderboard — top agents promoted in marketplace by on-chain trust score** — The platform now autonomously ranks the top 10 three.ws agents by behavioral trust score every 30 minutes via a real x402 payment to the agent-reputation endpoint. Scores are synthesized from real on-chain pump.fun agent-payments activity, distribution/buyback success, and signed Solana attestations — not a subjective rating. The top 10 are promoted to the front of the marketplace recommended feed and marked with a ◈ Top Trust badge. The ranking is also stored as an oracle signal (topic: agent_reputation_leaderboard) for downstream systems to query. Full snapshot history is written to agent_reputation_leaderboard_snapshots so trust trends are auditable over time. (`/marketplace`) `[feature, improvement]`@@ -15,6 +16,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **API Key Validity Health — the platform verifies its own access keys every hour** — A lapsed or missing access key for the autonomous loop means every self-call in the pipeline hits the paywall cold — legitimate tool calls start failing, recovery is manual, and the outage is invisible until someone investigates why the spend log went quiet. The platform now detects this automatically. Every hour an autonomous agent makes a real on-chain payment to a new /api/x402/api-key-health endpoint with body { scope: "autonomous_loop" }. The endpoint checks whether any active subscription key covers the requested scope, falling back to the INTERNAL_API_KEY env var, and returns { valid, scopes, expires_at }. The extracted signal surfaces hours_until_expiry in x402_autonomous_log.signal_data. When expiry is within 24 hours the storeValue hook writes a Redis alert (x402:api-key-health:expiry-alert) so the ops surface can surface the warning before the key lapses. `[infra, feature]`- **AR avatars look right on iPhone, and AR tells you what to do on a desktop** — Two fixes to the "View in AR" experience. Avatars with position-only props or accessories were exported to iOS Quick Look without surface normals, so those parts showed up flat and mis-lit; every mesh now gets correct normals before the USDZ is built, so avatars are shaded properly in your room. And on a desktop or any device that can't do AR, the "Place in your space" button used to do nothing when clicked — it now copies the page link and tells you to open it on your iPhone or Android, where AR actually works. (`/features/ar`) `[fix, improvement]`- **Auth Session Lifecycle Health — the platform canaries its own JWT auth pipeline every 30 minutes** — A broken auth subsystem — a JWT signer that stops working, a verifier that accepts expired tokens, or a misconfigured issuer — can lock users out silently or, worse, leave a security hole open. The platform now detects both within 30 minutes. Every half-hour an autonomous agent makes a real on-chain payment to a new /api/x402/auth-health endpoint and runs a four-step session lifecycle canary: mint a canary access token, verify it with the full JWT verifier, issue a replacement token and re-verify it (the rotation path), and confirm that an already-expired token is rejected. Each step is timed independently; a failure names exactly which step broke and why. The result — all_pass, failed_step, and per-step latency — is recorded as an actionable signal so ops can read auth health off a single log row without a separate query. `[infra, security]`+- **Avatar API no longer stalls when usage logging hits a slow database** — Behind the scenes we record lightweight usage events for things like avatar fetches and uploads. When our fast in-memory buffer was unavailable, each event fell back to writing directly to the database — and a slow database spell could hold that write open for up to 15 seconds, dragging out avatar requests and filling the logs with deadline errors. Those background writes are now strictly time-boxed and fully detached from your request, so a sluggish database can never delay an avatar response. Telemetry stays best-effort; your request always comes first. `[fix, infra]`- **Avatar generation rides out engine outages by failing over between backends** — Describe-it-to-3D and Instant Agent Genesis no longer dead-end with "the avatar engine rejected this job" when one 3D backend has a hiccup. A request now tries every configured engine in turn — and your own Meshy or Tripo key as a backstop — before giving up, so a single provider's cold start, throttle, or outage is invisible to you. On the rare moment every engine is down at once, the error now points you straight to the selfie scanner and offers a one-tap retry instead of stranding the build. (`/create/prompt`) `[fix]`- **Back-an-Agent Vaults got a sharper, more visual redesign** — The vaults page (/vaults) now opens with a live at-a-glance strip — open vaults, total capital backed, backers, and the best return across the board — counting up the moment data lands. Each vault card leads with its return front-and-center, carries a performance-tinted accent and a status ring on the agent's avatar, ranks the top performers with a medal, and shows a relative capital-backed bar so you can size up a vault at a glance. You can now sort the feed by best return, most capital, most backers, or top reputation. Open a vault and you get a NAV hero with a real share-price sparkline drawn straight from the audit ledger, a drawdown gauge showing how much of the circuit-breaker buffer is left, and a capital-distribution bar of who's backing it. Same real on-chain data — just far easier to read. (`/vaults`) `[improvement]`- **Building a strategy is now a real page, not a cramped pop-up** — Creating or editing a Strategy Object on the Strategies page (/strategies) opened a small modal that squeezed a long, multi-section form — entry rules, sizing, take-profit, stop-loss, risk — into a scrolling box. It now opens as a full builder page with room to work: the rules on the left and a sticky "Your strategy" panel on the right that shows a plain-language summary of your plan as you type, the safety guarantees, and the Create button always in reach. The builder is shareable and reload-safe (it lives at /strategies?editor=new) and the browser back button returns you to the library. Editing a strategy in-context from an agent's profile still uses the quick inline editor. (`/strategies`) `[improvement]`@@ -23,6 +25,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Club Social Activity — the platform tracks its own nightlife economy on-chain** — The autonomous loop now pays /api/x402/analytics every 30 minutes with { report: "clubs", period: "24h" } for a live snapshot of the Pole Club's social economy. The report reads straight from the real ledgers — settled tips (club_tips), the stage roster (club_dancer_wallets) and settled door cover charges (x402_audit_log) — and returns how many stages are active, how many distinct patrons showed up, the tip count and USDC volume, the cover charges collected at the door, and a fastest-growing-stage leaderboard. Every snapshot is appended to a club_social_analytics time series so a dashboard can chart whether the nightlife is heating up or cooling down and spot which stages are on the rise. `[feature, infra]`- **Create an agent by describing it — the wizard now builds itself** — Spinning up an agent no longer means filling out five steps of fields. At the top of the Create flow there's now a single box: describe your agent in a sentence — "a witty crypto market analyst that explains charts in plain English" — and we generate the whole thing for you: name, description, tags, the right skills, a fitting 3D body, a marketplace category, a greeting, and its personality. No idea where to start? Tap an example or hit "Surprise me" and get a complete agent with zero typing. Everything lands on the Review step pre-filled, so you read it over, tweak anything you like, and ship. The by-hand form is still right there for anyone who wants it. (`/create-agent`) `[feature]`- **Five pages that were returning 404 are reachable again** — The Gaussian-splat viewer (/splat), the capture tool (/capture), the integrations directory (/integrations), partners (/partners), and the live-agents board (/agents-live) were all returning a 404 in production even though the pages existed and were linked from the nav. Our routing pins every clean URL explicitly, and these five were missing their entry, so the request fell through to the not-found page. We added the missing routes and tightened the route audit so a new page can no longer ship without one. (`/splat`) `[fix]`+- **Fixed strategy backtesting failing to find candidate coins** — Running a strategy backtest (and live strategy runs) could fail with a server error while scanning for candidate coins. The scan and trading steps rely on several bundled trading skills, but only one of them was being shipped to production — so the moment a backtest tried to pull trending or new coins, it hit a missing-module error. All of the required skills now deploy together, and backtests source their candidate coins and replay normally again. `[fix]`- **Fixed: "Generate API key" in the Agent Screen worker setup** — The Launch your browser agent wizard (/agent-screen) has a Generate button that mints the API key the worker uses to authenticate. The button was failing with a permission error because it wasn't attaching the security token the server requires, so you couldn't get past step 2. It now reads and sends that token correctly, so generating the key — and starting a live agent screen stream — works again. The same token-handling fix was applied to one-click agent wallet provisioning. (`/agent-screen`) `[fix]`- **Forge Content Health — the platform canaries its own generation engine every 10 minutes** — Every 3D generation the Forge produces begins by running a prompt through the platform's generative AI lane, so if that lane slows down or goes dark, creations stall before a mesh is ever built. The platform now watches for this automatically. Every ten minutes an autonomous agent makes a real on-chain payment to a new lightweight health_check mode on /api/x402/forge, which runs one fast text completion over the same free-first model chain Forge depends on — no expensive 3D reconstruction — and reports back whether content was generated, how long it took, and the token count. A completion slower than five seconds, or an outright generator outage, raises a Forge performance alert that an on-call dashboard reads in a single lookup and that clears itself once generation is healthy again. The new health_check mode is also available to any x402 agent on the bazaar for a fraction of a cent, far cheaper than a full generation, for callers that just want to confirm the engine is live. `[infra, feature]`- **Forge Image Generation Canary — the platform validates its own image pipeline every 5 minutes** — Every Forge job that reconstructs a 3D mesh starts with a text-to-image call. If the image provider chain is down or hung, every paid Forge generation silently fails — before users even hit the paywall. The platform now detects this automatically. Every five minutes an autonomous agent makes a real on-chain $0.001 USDC payment to /api/x402/forge with body { mode: "health_check", type: "image", prompt: "A simple blue circle." }. The endpoint runs one real text-to-image call through the free-first provider chain (NIM FLUX → Vertex Imagen → Replicate backstop) and uploads the result to R2 CDN — proving the full image generation and CDN upload path end-to-end. The extracted signal { generated, url, latency_ms } lands in x402_autonomous_log.signal_data. When generation fails or latency exceeds 30 seconds, a Redis alert (x402:forge-image-health:alert) is raised so ops can investigate before users see broken generations. The image alert key is separate from the existing text LLM canary alert so both lanes can degrade independently. `[infra, feature]`@@ -45,6 +48,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **The Live Agents wall now shows every agent, 24/7** — The Live Agents page (/agents-live) used to show only the handful of agents that happened to have a browser actively streaming — usually none, so the page sat empty. Now it shows every agent on the platform, each with a live screen, and a screen is never blank: when no live browser is attached, the card streams the agent's real activity as a live terminal straight from its on-chain and skill history. Scroll to load more, and watch the live/total counts update in real time. Open any agent any time — and when you're actually watching one, an on-demand caster spins a real browser feed up for it (and tears it down when you leave), so live pixels are available for any agent without anything running idle. The same activity feed now also powers the screens on the agent desks in the 3D world. (`/agents-live`) `[feature, improvement]`- **The main menu is now organized — no more walls of links** — The top navigation kept everything but had become hard to scan: the Launch menu alone listed 25 features in one long single-column drop-down, and nearly every item shouted a "New" badge, so the badge meant nothing. Each menu — Build, Discover, Launch, Learn — is now split into clearly labelled columns grouped by what you're trying to do (Launch, for example, splits into Launch / Terminal & trade / Intelligence / Compete & earn). Every feature is still one click away, on desktop and in the mobile drawer; nothing was removed or moved off-platform. The only badge left is the green "Live" dot, which now genuinely means the page is running right now. `[improvement]`- **The Money Pulse now sits on a pure-black canvas** — The Money Pulse page (/pulse) now renders on a true black background in every theme, so the live feed of tips, launches, trades and agent-to-agent payments reads as one calm, high-contrast field. Previously the page could pick up a lighter surface or near-black tone depending on your theme; it's now consistently black with the monochrome ink ramp pinned for readability. (`/pulse`) `[improvement]`+- **The multiplayer world now refuses to start unprotected** — The three.ws world (world.three.ws) is locked down so only admins can build, move, or delete scene content — everyone else explores freely. Previously, if a world deploy ever went out missing its admin secret, the underlying engine quietly handed every visitor full build rights, which is how the world could get wiped. We closed that gap at the source: a production world build now refuses to boot at all unless the admin secret is present, so a misconfigured deploy can never silently expose build rights — the last known-good, protected version keeps serving instead. Our automated world-health monitor continues to watch for this every 15 minutes. `[security, infra]`- **The shared 3D world stays in sync through server updates** — After we shipped an update to the multiplayer world, players who hadn't reloaded the page could land in a broken session — other people stopped appearing, movement froze, and the browser console filled with decode errors — until a hard refresh. The cause: the page read the world using its own bundled copy of the world's data layout, which fell out of step with the freshly updated server. The client now reads the layout the server itself describes when you join, so it always matches the live server. Joining the walk world and coin community worlds survives a server update without a forced refresh. `[fix]`- **Trending and the agent directory now actually show agents** — The Trending leaderboard (/trending) and the public agent directory were coming up empty no matter how busy the platform was — every list rendered "No trending agents yet." Both feeds ranked agents by chat activity using a column that doesn't exist in the database, so the query failed silently and returned nothing. They now count real chat activity (LLM usage events) the same way the rest of the site does, so the 24h, 7d, and all-time rankings — and the directory's "popular" sort — populate with the agents people are actually using. (`/trending`) `[fix]`- **User Activity Analytics — DAU, WAU, and top features now tracked every 6 hours via x402** — The platform now monitors its own engagement metrics automatically. Every six hours an autonomous agent pays the /api/x402/analytics endpoint for a live user_activity report — computing DAU, WAU, stickiness (DAU/WAU ratio), the top ten features by event volume, the platform error rate, and session-length distribution (average, median, and p90). All figures are read live from the real metered tables; an empty window returns zeros, never fabricated numbers. The extracted signal — dau, wau, top_feature — is recorded to x402_autonomous_log for the status surface to read, and every snapshot is persisted to a user_activity_snapshots time series for trend alerting and the engagement dashboard. The same report is available to any x402 agent on the bazaar for $0.005 per call. `[feature, infra]`diff --git a/api/_lib/cache.js b/api/_lib/cache.jsindex c0df98452..40f7045a6 100644--- a/api/_lib/cache.js+++ b/api/_lib/cache.js@@ -160,7 +160,7 @@ function circuitAllows() {}function circuitRecordSuccess() {- if (circuitOpenUntil !== 0) console.warn('[cache] redis recovered — circuit closed');+ if (circuitOpenUntil !== 0) warnThrottled('circuit', '[cache] redis recovered — circuit closed');circuitFailures = 0;circuitOpenUntil = 0;circuitTrialInFlight = false;@@ -176,7 +176,8 @@ function circuitRecordFailure() {circuitFailures++;if (circuitFailures >= CIRCUIT_FAIL_THRESHOLD) {circuitOpenUntil = Date.now() + CIRCUIT_COOLDOWN_MS;- console.warn(+ warnThrottled(+ 'circuit',`[cache] redis degraded — circuit opened for ${CIRCUIT_COOLDOWN_MS / 1000}s after ${circuitFailures} consecutive failures; serving from memory`,);}@@ -270,7 +271,7 @@ export async function cacheSet(key, value, ttlSeconds = 60) {try {const payload = JSON.stringify(value);await redisCmd(['SET', key, payload, 'EX', String(ttlSeconds)]);- if (setSuppressedUntil !== 0) console.warn('[cache] redis SET recovered — resuming cache writes');+ if (setSuppressedUntil !== 0) warnThrottled('set-gate', '[cache] redis SET recovered — resuming cache writes');setFailures = 0;setSuppressedUntil = 0;memoPut(key, value); // keep the memo coherent with what we just wrote@@ -286,7 +287,8 @@ export async function cacheSet(key, value, ttlSeconds = 60) {setFailures++;if (setFailures >= SET_FAIL_THRESHOLD) {setSuppressedUntil = now + SET_SUPPRESS_MS;- console.warn(+ warnThrottled(+ 'set-gate',`[cache] redis SET degraded — suppressing cache writes for ${SET_SUPPRESS_MS / 1000}s after ${setFailures} consecutive failures; serving from memory`,);} else {diff --git a/api/_lib/forge-scale.js b/api/_lib/forge-scale.jsindex 17c8e28b0..5e425281c 100644--- a/api/_lib/forge-scale.js+++ b/api/_lib/forge-scale.js@@ -153,6 +153,80 @@ export async function providerSubmitAllowed(provider, { limit, windowS }) {}}+// ── Per-provider rate slot (queue, not shed) ──────────────────────────────────+// A leaky-bucket / GCRA gate that PACES submissions to a hard upstream rate+// instead of shedding over-cap traffic. Where providerSubmitAllowed() drops a+// burst to a free lane, this reserves the next free slot and tells the caller how+// long to wait for it — so a lane with no free fallback (the paid Replicate+// text→image backstop) queues gracefully behind the rate rather than firing+// straight into a throttle 429. Replicate holds a reduced-rate account to "6+// requests per minute with a burst of 1"; under an influx every text→3D request+// that falls past the free NIM/Vertex lanes lands here, and without pacing they+// stampede that limit (106× "Request was throttled" in one window). The gate is+// account-wide per provider key, so concurrent serverless instances all reserve+// from the same bucket.+//+// GCRA: one emission every `interval` ms; a `burst`-deep allowance (τ) lets an+// idle bucket admit up to `burst` immediately. The reservation (advancing the+// theoretical-arrival-time) and the wait computation run as one Lua script so+// concurrent reservers can't both claim the same slot. A reservation is only+// taken when the wait fits the caller's budget — an over-budget request leaves+// the bucket untouched and is told to retry, so a rejected caller never steals a+// slot from one that will actually wait for it. Fail-OPEN without Redis (dev /+// outage): no bucket to coordinate, so every caller proceeds immediately.++const RATE_PREFIX = 'fc:rate:';++// KEYS[1] = bucket; ARGV = now, interval(ms), tau(ms), maxWait(ms). Returns+// {allowed(0|1), waitMs}. `base` is the time this request would be served: the+// later of the stored TAT and (now - tau) — the τ slack is what permits a burst+// out of an idle bucket. We reserve (push TAT to base+interval) only when the+// wait is within budget; the key's TTL tracks the live reservation horizon so an+// idle bucket self-clears.+const RATE_RESERVE_LUA = `local now = tonumber(ARGV[1])+local interval = tonumber(ARGV[2])+local tau = tonumber(ARGV[3])+local maxWait = tonumber(ARGV[4])+local tat = tonumber(redis.call('GET', KEYS[1]))+if not tat then tat = now end+local base = tat+if base < now - tau then base = now - tau end+local waitMs = base - now+if waitMs < 0 then waitMs = 0 end+if waitMs > maxWait then+ return {0, math.floor(waitMs)}+end+local newTat = base + interval+redis.call('SET', KEYS[1], tostring(newTat), 'PX', math.floor(newTat - now + 5000))+return {1, math.floor(waitMs)}`;++// Reserve the next submission slot for `provider`, pacing to `ratePerMin`+// (`burst`-deep). Returns { ok, waitMs }: when ok, the caller sleeps `waitMs`+// (0..maxWaitMs) then submits — the slot is reserved. When !ok the queue is+// deeper than maxWaitMs; no slot is taken and `waitMs` is the time until one+// would open, so the caller can surface a retry hint. Fail-open (ok, 0) on a+// missing or erroring Redis — pacing is a protective throttle, never a gate.+export async function reserveProviderRateSlot(+ provider,+ { ratePerMin, burst = 1, maxWaitMs, now = Date.now() },+) {+ if (!redis) return { ok: true, waitMs: 0 };+ const interval = Math.max(1, Math.floor(60_000 / Math.max(1, ratePerMin)));+ const tau = Math.max(0, (Math.max(1, burst) - 1) * interval);+ try {+ const r = await redis.eval(+ RATE_RESERVE_LUA,+ [`${RATE_PREFIX}${provider}`],+ [String(now), String(interval), String(tau), String(Math.max(0, Math.floor(maxWaitMs)))],+ );+ const ok = Array.isArray(r) && Number(r[0]) === 1;+ const waitMs = Array.isArray(r) ? Math.max(0, Number(r[1]) || 0) : 0;+ return { ok, waitMs };+ } catch {+ return { ok: true, waitMs: 0 };+ }+}+// Tunables, overridable per-deployment via env. Defaults are conservative ceilings// chosen to protect the worker pool / provider quota without throttling normal use.function intEnv(name, fallback) {@@ -169,6 +243,14 @@ export const SCALE_LIMITS = Object.freeze({// Platform Replicate submits per 10s window before we shed to the free lane.replicateSubmitLimit: intEnv('FORGE_REPLICATE_SUBMIT_LIMIT', 40),replicateSubmitWindowS: 10,+ // Account-wide rate the platform Replicate token is paced to by the text→image+ // backstop queue. Mirrors the reduced-rate state Replicate imposes when account+ // credit is low: 6 predictions/min, burst of 1 (no fallback lane to shed to, so+ // we queue instead — see reserveProviderRateSlot). A request whose slot is more+ // than replicateQueueMaxMs out is told to retry rather than blocking a worker.+ replicateRatePerMin: intEnv('FORGE_REPLICATE_RATE_PER_MIN', 6),+ replicateRateBurst: intEnv('FORGE_REPLICATE_RATE_BURST', 1),+ replicateQueueMaxMs: intEnv('FORGE_REPLICATE_QUEUE_MAX_MS', 15_000),// Max PLATFORM-keyed paid generations one identity (browser client) may run per// UTC day — the layer per-IP and the global hourly cap don't cover.paidDailyPerClient: intEnv('FORGE_PAID_DAILY_CAP', 60),diff --git a/api/_lib/market/token-market.js b/api/_lib/market/token-market.jsindex 53fa57801..005f09878 100644--- a/api/_lib/market/token-market.js+++ b/api/_lib/market/token-market.js@@ -12,7 +12,7 @@// they can and never crash on a single upstream blip. This is the market-data// analogue of the RPC failover layer.-import { cacheGet, cacheSet, cacheDel } from '../cache.js';+import { cacheGet, cacheSet, cacheDel, acquireLock, releaseLock } from '../cache.js';const BIRDEYE_BASE = 'https://public-api.birdeye.so';const DEXSCREENER_BASE = 'https://api.dexscreener.com/latest/dex/tokens';@@ -20,7 +20,12 @@ const GECKOTERMINAL_BASE = 'https://api.geckoterminal.com/api/v2/networks/solanaconst FETCH_TIMEOUT_MS = 6000;const DEFAULT_TTL_MS = 30_000;-const STALE_MAX_MS = 5 * 60_000;+// Last-good window served when EVERY source is simultaneously down. With the+// single-flight + background-refresh defenses below, the only path to stale is a+// total upstream outage (all three rate-limited at once — TASK-10), so we hold+// the last price far longer: a 25-minute-old price keeps the panel populated+// through a transient outage, which beats blanking it ("all sources failed").+const STALE_MAX_MS = 30 * 60_000;// L2 (shared, cross-instance) cache TTL. Scaling defense: Vercel runs many// stateless lambda instances; the per-instance L1 Map below is wiped on every@@ -28,10 +33,31 @@ const STALE_MAX_MS = 5 * 60_000;// fan out to all three upstreams. The L2 Upstash cache lets a cold lambda serve// a sibling's recent fetch instead, collapsing fleet-wide upstream load to ~1// call per key per window — the difference between "holds at 100x" and "every-// instance rate-limits Birdeye at once". Short window keeps a token price fresh.-const SHARED_TTL_S = 15;+// instance rate-limits Birdeye at once".+//+// 60s window (was 15s): the background refresh cron (api/cron/three-market-+// refresh) re-fetches $THREE once a minute, so this TTL is sized to outlive one+// cron cadence — on-demand reads serve the cron's warm write and almost never+// touch an upstream. 15s forced ~4× the necessary fan-out (a fresh cascade every+// time the window lapsed); 60s staleness is invisible on a token price panel and+// the cron keeps the real age ≤ one minute regardless.+const SHARED_TTL_S = 60;const sharedKey = (mint) => `mktdata:v1:${mint}`;+// Fleet-wide single-flight lock for the live upstream fetch. When L1+L2 both+// miss (cold start, or the brief gap between cron refreshes) a traffic spike+// would otherwise have every concurrent lambda run the full Birdeye→DexScreener→+// GeckoTerminal cascade at once — the exact pattern that exhausts all three free+// quotas simultaneously. One instance wins this lock and does the real fetch;+// the losers serve last-good or briefly await the winner's L2 write instead of+// piling onto the upstreams. TTL covers a worst-case full cascade (3 × timeout)+// so the lock never expires mid-fetch and lets a second instance double-fetch.+const lockKey = (mint) => `mktlock:v1:${mint}`;+const LOCK_TTL_S = 20;+const LOCK_WAIT_TRIES = 4;+const LOCK_WAIT_STEP_MS = 250;+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));+const _cache = new Map(); // mint → { value, expires, fetchedAt }const _warnedAt = new Map();const WARN_COOLDOWN_MS = 60_000;@@ -206,6 +232,32 @@ async function fromGeckoTerminal(mint) {const SOURCES = [fromBirdeye, fromDexScreener, fromGeckoTerminal];+// Store a value in the per-instance L1 cache (with the bounded-size eviction the+// fetch path uses) and return it. Shared by the live, L2-hit, and lock-loser+// paths so they all keep L1 coherent the same way.+function storeL1(mint, value, now, ttlMs) {+ _cache.set(mint, { value, expires: now + ttlMs, fetchedAt: now });+ if (_cache.size > 256) _cache.delete(_cache.keys().next().value);+ return value;+}++// Lock-loser path: another instance holds the single-flight lock and is fetching+// live right now. Poll the shared cache a few times for its write rather than+// firing our own redundant upstream cascade. Returns the freshly-published value+// or null if the winner hasn't landed within the short wait budget.+async function waitForSharedWrite(mint, ttlMs) {+ for (let i = 0; i < LOCK_WAIT_TRIES; i++) {+ await sleep(LOCK_WAIT_STEP_MS);+ try {+ const shared = await cacheGet(sharedKey(mint));+ if (shared && shared.price_usd > 0) return storeL1(mint, shared, Date.now(), ttlMs);+ } catch {+ /* keep waiting, then fall through */+ }+ }+ return null;+}+/*** Normalized market data for a mint, with multi-source failover and a stale* cache. Returns null only when every source fails and no recent value exists.@@ -235,32 +287,59 @@ export async function fetchTokenMarketData(mint, { fresh = false, ttlMs = DEFAUL}}+ // Single-flight the live fetch across the fleet. A cold/expired cache under a+ // traffic spike would otherwise have every concurrent lambda run the full+ // source cascade at once — the pattern that rate-limits all three upstreams+ // simultaneously (TASK-10). One instance wins the lock and fetches; the losers+ // serve last-good immediately, or briefly await the winner's L2 write, instead+ // of duplicating the upstream calls. fresh:true (the background cron, explicit+ // quote refreshes) deliberately bypasses this — those callers want live data+ // and don't fan out. When Redis is unconfigured acquireLock returns true, so+ // dev/tests keep the direct path.+ let locked = false;+ if (!fresh) {+ locked = await acquireLock(lockKey(mint), LOCK_TTL_S);+ if (!locked) {+ if (hit && now - hit.fetchedAt < STALE_MAX_MS) {+ hit.expires = now + Math.min(ttlMs, 5_000); // re-check soon for the winner's write+ return hit.value;+ }+ const shared = await waitForSharedWrite(mint, ttlMs);+ if (shared) return shared;+ // Winner never landed (its lambda may have died) — fall through and+ // fetch ourselves, trading one extra cascade for correctness in a rare+ // cold-and-contended corner.+ }+ }+// Live fetch ahead — inherit the fleet's circuit-breaker state so a cold// lambda skips a source another instance already found exhausted.await hydrateCooldowns(now);- for (const src of SOURCES) {- if ((_sourceCooldown.get(src.name) || 0) > now) continue;- try {- const result = await src(mint);- if (result && result.price_usd > 0) {- _cache.set(mint, { value: result, expires: now + ttlMs, fetchedAt: now });- if (_cache.size > 256) _cache.delete(_cache.keys().next().value);- // Publish to the shared cache for sibling instances (best-effort).- cacheSet(sharedKey(mint), result, SHARED_TTL_S).catch(() => {});- return result;- }- } catch (err) {- const cooldown = cooldownFor(err);- if (cooldown) {- _sourceCooldown.set(src.name, now + cooldown);- // Broadcast the verdict so sibling lambdas skip this dead source too.- publishCooldowns(now);- warnThrottled(`${src.name}:cooldown`, `[market] ${src.name} quota/rate-limited — skipping it for ${Math.round(cooldown / 60_000)}min: ${err?.message}`);- } else {- warnThrottled(`${mint}:${src.name}`, `[market] ${src.name} failed for ${mint.slice(0, 6)}…: ${err?.message}`);+ try {+ for (const src of SOURCES) {+ if ((_sourceCooldown.get(src.name) || 0) > now) continue;+ try {+ const result = await src(mint);+ if (result && result.price_usd > 0) {+ // Publish to the shared cache for sibling instances (best-effort).+ cacheSet(sharedKey(mint), result, SHARED_TTL_S).catch(() => {});+ return storeL1(mint, result, now, ttlMs);+ }+ } catch (err) {+ const cooldown = cooldownFor(err);+ if (cooldown) {+ _sourceCooldown.set(src.name, now + cooldown);+ // Broadcast the verdict so sibling lambdas skip this dead source too.+ publishCooldowns(now);+ warnThrottled(`${src.name}:cooldown`, `[market] ${src.name} quota/rate-limited — skipping it for ${Math.round(cooldown / 60_000)}min: ${err?.message}`);+ } else {+ warnThrottled(`${mint}:${src.name}`, `[market] ${src.name} failed for ${mint.slice(0, 6)}…: ${err?.message}`);+ }}}+ } finally {+ if (locked) releaseLock(lockKey(mint)); // best-effort; lock also auto-expires}// Every source failed — serve the last good value if it's still fresh enough.diff --git a/api/_lib/migrations/20260628140000_solana_agents_index.sql b/api/_lib/migrations/20260628140000_solana_agents_index.sqlnew file mode 100644index 000000000..00c60fcbc--- /dev/null+++ b/api/_lib/migrations/20260628140000_solana_agents_index.sql@@ -0,0 +1,51 @@+-- solana_agents_index — crawled directory of every on-chain Solana agent that+-- lives OUTSIDE three.ws's own agent_identities table. Two upstream registries+-- are folded into one table via the `source` column:+--+-- 'metaplex' → Metaplex Agent Registry (program 1DREGFgysWYxLnRnKQnwrxnJQeSMk2HmGaC6whw2B2p).+-- Each AgentIdentity account points at a Metaplex Core `asset`;+-- name/image/uri are enriched from that asset's DAS record.+-- 'agenc' → AgenC coordination protocol (Tetsuo Corp). Each agentRegistration+-- account carries authority, capabilities, endpoint and metadataUri;+-- name/image/description are enriched from metadataUri JSON.+--+-- Populated by api/cron/[name].js → handleSolanaAgentsCrawl (cron name+-- `solana-agents-crawl`). The /agents directory (via /api/explore?source=agents)+-- reads this alongside erc8004_agents_index (EVM) and agent_identities (ours) so+-- the index shows the whole ecosystem, not just three.ws-launched agents.+create table if not exists solana_agents_index (+ source text not null, -- 'metaplex' | 'agenc'+ ref text not null, -- on-chain account pubkey (PDA), base58 — unique within source+ network text not null default 'mainnet',+ owner text, -- authority / asset owner, base58+ asset text, -- Metaplex Core asset pubkey (metaplex source)+ agent_id text, -- AgenC 32-byte agent id, base58 (agenc source)+ name text,+ description text,+ image text, -- 2D thumbnail URL+ glb_url text, -- 3D model endpoint when the agent advertises one+ metadata_uri text, -- off-chain metadata pointer (asset json_uri / agenc metadataUri)+ endpoint text, -- AgenC service endpoint (URL or DID)+ capabilities text, -- AgenC capability bitmask, decimal string+ reputation integer, -- AgenC on-chain reputation score+ status text, -- registry-specific status label (e.g. 'active', 'suspended')+ has_3d boolean not null default false,+ x402_support boolean not null default false,+ active boolean not null default true, -- false once de-registered / suspended on-chain+ registered_at timestamptz,+ last_metadata_at timestamptz,+ metadata_error text,+ last_seen_at timestamptz not null default now(),+ primary key (source, ref)+);++create index if not exists solana_agents_active_time+ on solana_agents_index(registered_at desc) where active;+create index if not exists solana_agents_source_time+ on solana_agents_index(source, registered_at desc) where active;+create index if not exists solana_agents_owner+ on solana_agents_index(owner) where active;+create index if not exists solana_agents_asset+ on solana_agents_index(asset) where asset is not null;+create index if not exists solana_agents_metadata_stale+ on solana_agents_index(last_metadata_at nulls first);diff --git a/api/_lib/pumpfun-ws-feed.js b/api/_lib/pumpfun-ws-feed.jsindex cc23cee74..d93475af4 100644--- a/api/_lib/pumpfun-ws-feed.js+++ b/api/_lib/pumpfun-ws-feed.js@@ -109,11 +109,35 @@ export function connectPumpFunFeed({ onEvent, signal, kind = 'all', mints = [] }return true;}+ // WebSocket.CONNECTING. A socket torn down before its handshake completes is+ // the common serverless case here: collectLiveMints (and the request abort+ // signal) fire on a short timer, often before the upstream open lands.+ const WS_CONNECTING = 0;+function stop() {active = false;clearTimeout(reconnectTimer);clearInterval(fallbackTimer);- if (ws) try { ws.close(); } catch {}+ const sock = ws;+ ws = null;+ if (!sock) return;+ try {+ if (sock.readyState === WS_CONNECTING) {+ // Closing a socket mid-handshake makes `ws` emit a benign+ // "WebSocket was closed before the connection was established"+ // error. This teardown is intentional, so drop our listeners and+ // swallow that one error rather than logging it as a failure —+ // terminate() still aborts the pending request and frees the socket.+ sock.removeAllListeners?.('open');+ sock.removeAllListeners?.('message');+ sock.removeAllListeners?.('close');+ sock.removeAllListeners?.('error');+ sock.on?.('error', () => {});+ (sock.terminate ?? sock.close).call(sock);+ } else {+ sock.close();+ }+ } catch {}}signal?.addEventListener('abort', stop);@@ -208,7 +232,12 @@ export function connectPumpFunFeed({ onEvent, signal, kind = 'all', mints = [] }}});- ws.on('error', (err) => console.warn('[pumpportal-ws] error:', err?.message));+ ws.on('error', (err) => {+ // A handshake aborted during teardown is expected, not a failure — don't+ // surface it as an error (stop() already silences the common path).+ if (!active && /closed before the connection was established/i.test(err?.message || '')) return;+ console.warn('[pumpportal-ws] error:', err?.message);+ });ws.on('close', () => {if (!active || reconnects >= MAX_RECONNECTS) return;diff --git a/api/_mcp3d/text-to-image.js b/api/_mcp3d/text-to-image.jsindex dcb4908ce..3925e7d0e 100644--- a/api/_mcp3d/text-to-image.js+++ b/api/_mcp3d/text-to-image.js@@ -19,6 +19,7 @@// Replicate backstop: black-forest-labs/flux-schnell — same family, $0.003/run.import { markProviderCooldown, providersInCooldown } from '../_lib/provider-health.js';+import { reserveProviderRateSlot, SCALE_LIMITS } from '../_lib/forge-scale.js';const REPLICATE_BASE = 'https://api.replicate.com/v1';const DEFAULT_TXT2IMG_MODEL = 'black-forest-labs/flux-schnell';@@ -366,6 +367,26 @@ export async function textToImage(prompt, { aspectRatio = '1:1', skipNim = falsethrow new Error(`invalid REPLICATE_TXT2IMG_MODEL reference: ${modelRef}`);}+ // Pace creation to the platform account's rate before firing. On a reduced-rate+ // (low-credit) Replicate account this caps at 6/min, burst 1 — and this paid+ // backstop has no further free lane to shed to, so we QUEUE for the next slot+ // rather than stampede the limit into account-wide throttle 429s. Reserve the+ // slot; if it opens within the bounded wait, hold this worker until then; if the+ // queue is deeper than the budget, surface a retryable rate-limit the forge+ // boundary maps to a "queued — retry shortly" 429 (with an accurate Retry-After).+ const slot = await reserveProviderRateSlot('replicate', {+ ratePerMin: SCALE_LIMITS.replicateRatePerMin,+ burst: SCALE_LIMITS.replicateRateBurst,+ maxWaitMs: SCALE_LIMITS.replicateQueueMaxMs,+ });+ if (!slot.ok) {+ throw Object.assign(+ new Error('Image generation is queued behind other requests — please retry in a few seconds.'),+ { code: 'rate_limited', queued: true, retryAfter: Math.max(1, Math.ceil(slot.waitMs / 1000)) },+ );+ }+ if (slot.waitMs > 0) await sleep(slot.waitMs);+let res;try {res = await fetch(endpoint, {diff --git a/api/_providers/huggingface.js b/api/_providers/huggingface.jsindex 8eae64b39..4015264ca 100644--- a/api/_providers/huggingface.js+++ b/api/_providers/huggingface.js@@ -314,51 +314,68 @@ function r2Configured() {}// Pull the freshly-produced GLB and re-host it to durable storage, returning the-// public URL. Returns null on any failure (storage unconfigured, fetch error,-// oversize) so the caller falls back to the raw Space URL — the result is never-// worse than today, and on a configured deployment the ephemeral URL never-// escapes this provider. The HF bearer token is forwarded so private Spaces'-// file endpoints authorize the read; public Spaces ignore it.+// public URL. The HF bearer token is forwarded so private Spaces' file endpoints+// authorize the read; public Spaces ignore it.+//+// Two terminal outcomes, deliberately distinct:+// • Storage unconfigured → return null. There is nowhere durable to put the+// mesh, so the caller keeps the raw Space URL exactly as before. Nothing+// regresses on storage-less deployments.+// • Storage configured but the rehost can't complete (the temp file already+// 404'd, the fetch errored after retries, the body was empty/oversize, or+// the upload failed) → THROW. Returning the raw gradio /tmp URL here would+// be worse than failing: that URL is ephemeral and *will* 404 when a later+// consumer (the forge poll, materializeCreation, model-viewer's loader)+// fetches it — the exact "materializeCreation failed: ...glb 404" this+// function exists to prevent. Throwing lets the failover loop regenerate on+// the next Space, and if the chain is exhausted the caller surfaces a+// designed error instead of a doomed URL.async function rehostGlbToR2(glbUrl, token) {if (!r2Configured()) return null;let buf = null;+ let lastErr = null;for (let attempt = 1; attempt <= REHOST_MAX_ATTEMPTS; attempt++) {try {const resp = await fetch(glbUrl, { headers: { authorization: `Bearer ${token}` } });if (!resp.ok) {+ lastErr = Object.assign(new Error(`GLB fetch ${resp.status}`), { status: resp.status });// 404/410 = the temp file is already gone; retrying can't recover it.- if (resp.status === 404 || resp.status === 410) return null;- if (attempt >= REHOST_MAX_ATTEMPTS) return null;+ if (resp.status === 404 || resp.status === 410) break;} else {const bytes = Buffer.from(await resp.arrayBuffer());- if (bytes.length > REHOST_MAX_GLB_BYTES) return null;- if (bytes.length === 0) return null;+ if (bytes.length === 0) { lastErr = new Error('GLB body was empty'); break; }+ if (bytes.length > REHOST_MAX_GLB_BYTES) {+ lastErr = new Error(`GLB too large: ${bytes.length} bytes`);+ break;+ }buf = bytes;break;}- } catch (_) {- if (attempt >= REHOST_MAX_ATTEMPTS) return null;+ } catch (err) {+ lastErr = err;+ }+ if (attempt < REHOST_MAX_ATTEMPTS) {+ await new Promise((r) => setTimeout(r, REHOST_RETRY_BASE_MS * attempt));}- await new Promise((r) => setTimeout(r, REHOST_RETRY_BASE_MS * attempt));}- if (!buf) return null;-- try {- const { putObject, publicUrl } = await import('../_lib/r2.js');- const { randomUUID } = await import('node:crypto');- const key = `hf-recon/${randomUUID()}.glb`;- await putObject({- key,- body: buf,- contentType: 'model/gltf-binary',- metadata: { source: 'huggingface-reconstruct' },- });- return publicUrl(key);- } catch (err) {- console.warn(`[huggingface] GLB re-host to R2 failed: ${err?.message || err}`);- return null;+ if (!buf) {+ throw Object.assign(+ new Error(`GLB rehost failed: ${lastErr?.message || 'unknown error'}`),+ { code: 'rehost_failed', status: lastErr?.status, cause: lastErr },+ );}++ const { putObject, publicUrl } = await import('../_lib/r2.js');+ const { randomUUID } = await import('node:crypto');+ const key = `hf-recon/${randomUUID()}.glb`;+ await putObject({+ key,+ body: buf,+ contentType: 'model/gltf-binary',+ metadata: { source: 'huggingface-reconstruct' },+ });+ return publicUrl(key);}// Try one Space end-to-end: enqueue → consume SSE → extract GLB url.@@ -424,9 +441,21 @@ async function runOnSpace({ token, target, photos, params }) {else if (!/^https?:\/\//i.test(glbUrl)) glbUrl = `${spaceUrl}/file=${glbUrl}`;// Re-host the ephemeral gradio temp file to durable storage right now, while- // it's freshest. A successful re-host means no consumer ever sees the expiring- // Space URL; a miss leaves the raw URL untouched (fail-soft).- const durableUrl = await rehostGlbToR2(glbUrl, token);+ // it's freshest, so no consumer ever re-fetches the expiring Space URL. When+ // storage is configured this returns a durable URL or throws (the asset is+ // already gone / unwritable). A throw is tagged as this Space's failure so the+ // failover loop advances to the next Space and regenerates rather than handing+ // back a URL that will 404 downstream. When storage is unconfigured it returns+ // null and we keep the raw URL — the only option where there's nowhere durable.+ let durableUrl;+ try {+ durableUrl = await rehostGlbToR2(glbUrl, token);+ } catch (err) {+ throw tag(Object.assign(+ new Error(`GLB produced but not persistable: ${err?.message}`),+ { code: 'rehost_failed', status: err?.status || 502, cause: err },+ ));+ }return { resultGlbUrl: durableUrl || glbUrl, space, api };}diff --git a/api/_providers/nvidia.js b/api/_providers/nvidia.jsindex 8a46d4702..7b25a8324 100644--- a/api/_providers/nvidia.js+++ b/api/_providers/nvidia.js@@ -96,16 +96,33 @@ const POLL_TIMEOUT_MS = 60_000;// NVCF can answer a cold model — or a momentary capacity/routing blip at the// gateway — with a transient 502/503/504, or drop the socket before a worker is-// warm. None of these is terminal: a single short retry usually lands once the-// model spins up, which keeps the FREE lane from dead-ending straight to the-// (often equally throttled) paid Replicate lane and surfacing to the user as a-// hard 502. Bounded to one retry so a genuinely-down upstream still fails over-// fast rather than burning the whole serverless budget on a dead provider.+// warm. None of these is terminal: a short retry usually lands once the model+// spins up, which keeps the FREE lane from dead-ending straight to the (often+// equally throttled) paid Replicate lane and surfacing to the user as a hard 502.+// A hosted-preview 504 is the single most common blip (the gateway gives up on a+// slow worker), and it returns FAST — so retrying it a couple of times with+// spaced-out backoff is cheap and lands most of them on a warmed node, which is+// the main lever that stops a transient 504 from tripping the lane cooldown and+// dumping the request on the paid lane. Bounded to MAX_INVOKE_ATTEMPTS so a+// genuinely-down upstream still fails over fast rather than burning the whole+// serverless budget on a dead provider.const GATEWAY_RETRY_STATUSES = new Set([502, 503, 504]);-const MAX_INVOKE_ATTEMPTS = 2;-const INVOKE_RETRY_DELAY_MS = 1_500;+const MAX_INVOKE_ATTEMPTS = 3;+const INVOKE_RETRY_BASE_MS = 1_000;+const INVOKE_RETRY_MAX_MS = 6_000;const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));+// Backoff between invoke retries: exponential (base · 2^(n-1), capped) with full+// jitter so concurrent retries don't resynchronize into a thundering herd against+// a single warming node. When the gateway hands back a Retry-After we honour it+// (capped) instead of guessing.+function invokeRetryDelayMs(attempt, retryAfterSeconds) {+ const hinted = Number(retryAfterSeconds);+ if (Number.isFinite(hinted) && hinted > 0) return Math.min(hinted * 1000, INVOKE_RETRY_MAX_MS);+ const ceiling = Math.min(INVOKE_RETRY_BASE_MS * 2 ** (attempt - 1), INVOKE_RETRY_MAX_MS);+ return Math.floor(ceiling / 2 + Math.random() * (ceiling / 2));+}+// Sampling steps per quality tier. TRELLIS accepts 10–50, but the NVIDIA HOSTED// preview at this endpoint only returns within the gateway's synchronous window// at the low end: a 15-step draft completes in ~13 s, while 25 steps overruns the@@ -321,7 +338,7 @@ export function createNvidiaProvider() {// retry, so a single dropped connection doesn't fail the whole free lane.const timedOut = err?.name === 'TimeoutError' || err?.name === 'AbortError';if (!timedOut && attempt < MAX_INVOKE_ATTEMPTS) {- await sleep(INVOKE_RETRY_DELAY_MS);+ await sleep(invokeRetryDelayMs(attempt));continue;}throw lastErr;@@ -364,8 +381,9 @@ export function createNvidiaProvider() {// surfaced as a normalized provider error the forge layer routes around.if (GATEWAY_RETRY_STATUSES.has(res.status) && attempt < MAX_INVOKE_ATTEMPTS) {await res.text().catch(() => {});- lastErr = providerError(res.status, undefined, res.headers.get('retry-after'));- await sleep(INVOKE_RETRY_DELAY_MS);+ const retryAfter = res.headers.get('retry-after');+ lastErr = providerError(res.status, undefined, retryAfter);+ await sleep(invokeRetryDelayMs(attempt, retryAfter));continue;}diff --git a/api/cron/three-market-refresh.js b/api/cron/three-market-refresh.jsnew file mode 100644index 000000000..840654def--- /dev/null+++ b/api/cron/three-market-refresh.js@@ -0,0 +1,60 @@+// @ts-check+// GET /api/cron/three-market-refresh — keep the $THREE market-data cache warm.+//+// Why this exists (TASK-10): market reads — the price / market-cap / holders+// panels, the leaderboard supply percentages, OG badges — are traffic-driven.+// On a cold or expired cache, every concurrent request independently fans out to+// Birdeye → DexScreener → GeckoTerminal, and under load that exhausts all three+// free quotas at once ("all sources failed — serving stale").+//+// This cron turns the upstream polling into a single, constant-rate background+// job: once a minute we do ONE forced-fresh fetch and write it to the shared+// (L2) cache, sized to outlive a cron cadence. On-demand reads then serve that+// warm write and almost never touch an upstream — collapsing fleet-wide upstream+// load to ~1 cascade per minute regardless of traffic. The circuit breaker still+// applies: a quota-exhausted source stays skipped via the shared cooldown key,+// so a dead Birdeye isn't re-burned every tick.+//+// Kept as a concrete file (not [name].js) so this lightweight refresh never+// shares a cold start with the heavy SDK bundles.++import { error, json, method, wrapCron } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { constantTimeEquals } from '../_lib/crypto.js';+import { TOKEN_MINT as THREE_MINT } from '../_lib/token/config.js';+import { fetchTokenMarketData } from '../_lib/market/token-market.js';++function requireCron(req, res) {+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;+ if (!secret) {+ error(res, 503, 'not_configured', 'CRON_SECRET unset');+ return false;+ }+ const auth = req.headers['authorization'] || '';+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';+ if (!constantTimeEquals(presented, secret)) {+ error(res, 401, 'unauthorized', 'invalid cron secret');+ return false;+ }+ return true;+}++export default wrapCron(async (req, res) => {+ if (!method(req, res, ['GET'])) return;+ if (!requireCron(req, res)) return;++ // fresh:true bypasses the read caches and the single-flight lock (we WANT to+ // fetch) but still writes the result to L2 for everyone else to serve.+ const md = await fetchTokenMarketData(THREE_MINT, { fresh: true }).catch((err) => {+ console.warn('[three-market-refresh] fetch failed:', err?.message || err);+ return null;+ });++ return json(res, 200, {+ ok: !!md,+ mint: THREE_MINT,+ source: md?.source ?? null,+ price_usd: md?.price_usd ?? null,+ ts: Date.now(),+ });+});diff --git a/api/forge.js b/api/forge.jsindex 54aa59e59..052ea5bb7 100644--- a/api/forge.js+++ b/api/forge.js@@ -104,7 +104,39 @@ import { sanitizeJobError } from './_lib/provider-job-error.js';// working one; it expires on its own so a recovered lane is retried promptly.// Best-effort via the shared cache — a miss just means "not cooling".const NIM_TRELLIS_COOLDOWN_KEY = 'forge-nim-trellis';+// Sideline the free NIM lane after a failure. The cooldown exists to avoid+// re-paying the expensive submit-timeout HANG, so a socket timeout / unreachable+// host (no HTTP status came back) earns the full window. A fast gateway 5xx (a+// 504/503 the gateway returned promptly — a cold-start/capacity blip the+// in-provider retry already rode) only earns a short window, so a single transient+// 504 doesn't sideline the free lane for two minutes and dump every text prompt on+// the paid lane. See nimCooldownSeconds().const NIM_FORGE_COOLDOWN_SECONDS = 120;+const NIM_FORGE_GATEWAY_COOLDOWN_SECONDS = 30;++// The platform-keyed paid reconstruct lane (Replicate TRELLIS) recorded as down.+// Set only on an out-of-credit/billing failure — which won't self-heal until ops+// tops the account up, so the window is long (reason 'auth'). The NIM-cooldown+// router reads it to avoid skipping the free lane in favour of a dead paid lane.+const REPLICATE_PAID_COOLDOWN_KEY = 'forge-replicate-paid';+const REPLICATE_PAID_COOLDOWN_SECONDS = 300;++// Pick how long to cool the free NIM lane after a failure. A Retry-After hint+// (429) is honoured within bounds; an HTTP status that came back at all means the+// gateway answered (a fast fail) and earns the short window; no status means our+// socket timed out / the host was unreachable (the expensive hang) and earns the+// full window.+function nimCooldownSeconds(err) {+ const retryAfter = Number(err?.retryAfter);+ if (Number.isFinite(retryAfter) && retryAfter > 0) {+ return Math.min(+ Math.max(Math.ceil(retryAfter), NIM_FORGE_GATEWAY_COOLDOWN_SECONDS),+ NIM_FORGE_COOLDOWN_SECONDS,+ );+ }+ if (typeof err?.providerStatus === 'number') return NIM_FORGE_GATEWAY_COOLDOWN_SECONDS;+ return NIM_FORGE_COOLDOWN_SECONDS;+}// Holder perk (Lever 2): a presented, verified $THREE tier pass lifts the free// generation ceiling by that tier's multiplier. The pass is pure-HMAC verifiable@@ -260,7 +292,7 @@ async function runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path }) {// down so the next request skips the submit-timeout gamble and fails over// fast. A 4xx (bad input / key) is not a lane-health fault, so it never cools.if (isUpstreamUnavailable(err)) {- markProviderCooldown(NIM_TRELLIS_COOLDOWN_KEY, NIM_FORGE_COOLDOWN_SECONDS).catch(() => {});+ markProviderCooldown(NIM_TRELLIS_COOLDOWN_KEY, nimCooldownSeconds(err)).catch(() => {});}console.warn(`[forge] free NVIDIA NIM lane unavailable: ${err?.message || err}`);return false;@@ -1100,10 +1132,19 @@ async function startJob(req, res) {nvidiaTried = true;// Skip the submit-timeout gamble when the lane is in a recent-failure// cooldown — go straight to the reconstruct lane instead of re-hanging.- const trellisCooling = (await providersInCooldown([NIM_TRELLIS_COOLDOWN_KEY])).has(+ // BUT only when that reconstruct lane is a real destination: it free-firsts+ // to HuggingFace and then the paid Replicate account, so it's viable when HF+ // is configured OR the paid account isn't itself recorded out-of-credit. When+ // both are gone, skipping NIM would route straight into a dead paid lane and+ // 503 the user — so we ignore the cooldown and give the free lane a real shot.+ const cooldowns = await providersInCooldown([NIM_TRELLIS_COOLDOWN_KEY,- );- if (trellisCooling) {+ REPLICATE_PAID_COOLDOWN_KEY,+ ]);+ const trellisCooling = cooldowns.has(NIM_TRELLIS_COOLDOWN_KEY);+ const reconstructLaneViable =+ backendIsConfigured('huggingface') || !cooldowns.has(REPLICATE_PAID_COOLDOWN_KEY);+ if (trellisCooling && reconstructLaneViable) {console.warn('[forge] NVIDIA NIM TRELLIS lane in cooldown; routing to reconstruct lane');nimGatewayDegraded = true;backendId = 'trellis';@@ -1596,15 +1637,26 @@ async function startJob(req, res) {});}// Last-resort free fallback: when the paid image-intermediate TRELLIS lane- // (Replicate) is throttled, over-quota, or unreachable, a text prompt must- // never dead-end — degrade to the free NVIDIA NIM lane so the default- // "type a prompt → get a model" flow always returns something. Honors the- // free-first "AI must never fail" policy; provenance reports backend:nvidia- // so the downgrade is visible, not silent. Image uploads have no free- // reconstruct fallback (NVCF is text-only), so they fall through to the- // designed states below. `nvidiaTried` guards against re-running a lane that- // already failed this request (the draft nvidia→trellis→nvidia loop).- if (isUpstreamUnavailable(err) && !isImageMode && !nvidiaTried && prompt) {+ // (Replicate) is throttled, over-quota, unreachable, OR out of credit, a text+ // prompt must never dead-end — degrade to the free NVIDIA NIM lane so the+ // default "type a prompt → get a model" flow always returns something. The+ // credit-exhaustion case matters most here: the failure is the paid FLUX+ // synthesis step (textToImage throws code:'billing'/402, which is NOT+ // upstream-unavailable), but the NIM TRELLIS lane is native text→mesh and+ // needs no FLUX intermediate at all — so a dry Replicate account should hand+ // the prompt to the healthy free lane rather than skip straight to the 503.+ // Honors the free-first "AI must never fail" policy; provenance reports+ // backend:nvidia so the downgrade is visible, not silent. Image uploads have+ // no free reconstruct fallback here (NVCF is text-only — the HF lane already+ // absorbed them above), so they fall through to the designed states below.+ // `nvidiaTried` guards against re-running a lane that already failed this+ // request (the draft nvidia→trellis→nvidia loop).+ if (+ (isUpstreamUnavailable(err) || isPaidCreditFailure(err)) &&+ !isImageMode &&+ !nvidiaTried &&+ prompt+ ) {nvidiaTried = true;// Don't degrade to NIM when it's already in a recent-failure cooldown — that// would just re-pay the submit timeout on a lane we know is down right now.@@ -1628,9 +1680,16 @@ async function startJob(req, res) {if (err?.code === 'rate_limited' || err?.providerStatus === 429) {const retryAfter = typeof err?.retryAfter === 'number' ? err.retryAfter : 10;res.setHeader('retry-after', String(retryAfter));+ // A `queued` throttle is our own rate gate pacing the request to the+ // upstream limit (not an upstream rejection) — tell the user it's in line so+ // a retry reads as "your turn is coming up", not "the system is failing".+ const queued = Boolean(err?.queued);return json(res, 429, {error: 'rate_limited',- message: 'The 3D generator is busy right now. Try again in a few seconds.',+ queued,+ message: queued+ ? `Your generation is queued behind a few others — retry in ~${retryAfter}s to pick it up.`+ : 'The 3D generator is busy right now. Try again in a few seconds.',retry_after: retryAfter,});}@@ -1644,6 +1703,15 @@ async function startJob(req, res) {console.warn(`[forge] paid reconstruct lane out of credit and no free lane available: ${err?.message || err}${creditDetail}`,);+ // Record the paid lane as down (reason 'auth' — a billing fault that won't+ // self-heal until ops tops the account up). The NIM-cooldown router reads this+ // so the next text prompt keeps the free NIM lane in play instead of skipping+ // it to route into this now-known-dead paid lane.+ markProviderCooldown(+ REPLICATE_PAID_COOLDOWN_KEY,+ REPLICATE_PAID_COOLDOWN_SECONDS,+ 'auth',+ ).catch(() => {});res.setHeader('retry-after', '30');return json(res, 503, {error: 'generation_unavailable',diff --git a/data/changelog.json b/data/changelog.jsonindex 8b2eac753..0e3c3420d 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,32 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-28",+ "title": "The multiplayer world now refuses to start unprotected",+ "summary": "The three.ws world (world.three.ws) is locked down so only admins can build, move, or delete scene content — everyone else explores freely. Previously, if a world deploy ever went out missing its admin secret, the underlying engine quietly handed every visitor full build rights, which is how the world could get wiped. We closed that gap at the source: a production world build now refuses to boot at all unless the admin secret is present, so a misconfigured deploy can never silently expose build rights — the last known-good, protected version keeps serving instead. Our automated world-health monitor continues to watch for this every 15 minutes.",+ "tags": [+ "security",+ "infra"+ ]+ },+ {+ "date": "2026-06-28",+ "title": "Avatar API no longer stalls when usage logging hits a slow database",+ "summary": "Behind the scenes we record lightweight usage events for things like avatar fetches and uploads. When our fast in-memory buffer was unavailable, each event fell back to writing directly to the database — and a slow database spell could hold that write open for up to 15 seconds, dragging out avatar requests and filling the logs with deadline errors. Those background writes are now strictly time-boxed and fully detached from your request, so a sluggish database can never delay an avatar response. Telemetry stays best-effort; your request always comes first.",+ "tags": [+ "fix",+ "infra"+ ]+ },+ {+ "date": "2026-06-28",+ "title": "Fixed strategy backtesting failing to find candidate coins",+ "summary": "Running a strategy backtest (and live strategy runs) could fail with a server error while scanning for candidate coins. The scan and trading steps rely on several bundled trading skills, but only one of them was being shipped to production — so the moment a backtest tried to pull trending or new coins, it hit a missing-module error. All of the required skills now deploy together, and backtests source their candidate coins and replay normally again.",+ "tags": [+ "fix"+ ]+ },{"date": "2026-06-28","title": "A free, no-login 3D Studio you can add to ChatGPT",diff --git a/deploy/world/apply-hardening.sh b/deploy/world/apply-hardening.shindex 28d07db70..eff60e1d6 100755--- a/deploy/world/apply-hardening.sh+++ b/deploy/world/apply-hardening.sh@@ -44,12 +44,25 @@ gcloud builds submit --config deploy/world/cloudbuild.yaml deploy/world/# Apply the service config: ADMIN_CODE + PUBLIC_MAX_UPLOAD_SIZE=16.gcloud run services replace deploy/world/cloudrun.yaml --region="$REGION"-echo "Waiting for the new revision to serve..."-sleep 20-STATUS=$(curl -fsS https://world.three.ws/status)+echo "Waiting for the new revision to serve and report protected:true..."+# A min-instance service swaps traffic to the new revision only after it passes+# its startup probe, so poll rather than guessing with a fixed sleep. The+# fail-closed patch (patches/0003) makes a secret-less revision refuse to boot,+# so if protected never flips, the previous revision is still serving and the+# rollout needs a look — don't exit 0 on a silent failure.+STATUS=""+for attempt in $(seq 1 30); do+ STATUS=$(curl -fsS --max-time 10 https://world.three.ws/status 2>/dev/null || echo '{}')+ case "$STATUS" in+ *'"protected":true'*) break ;;+ esac+ sleep 5+doneecho "live /status: $STATUS"case "$STATUS" in*'"protected":true'*) echo "OK — world is protected. Visitors can no longer build." ;;- *) echo "WARNING — /status does not report protected:true yet. Check the revision rollout:"- echo " gcloud run revisions list --service=$SERVICE --region=$REGION" ;;+ *) echo "WARNING — /status does not report protected:true after ~150s. Check the rollout:"+ echo " gcloud run revisions list --service=$SERVICE --region=$REGION"+ echo " gcloud run services logs read $SERVICE --region=$REGION --limit=50"+ exit 1 ;;esacdiff --git a/deploy/world/patches/0003-fail-closed-without-admin-code.patch b/deploy/world/patches/0003-fail-closed-without-admin-code.patchnew file mode 100644index 000000000..0ff467973--- /dev/null+++ b/deploy/world/patches/0003-fail-closed-without-admin-code.patch@@ -0,0 +1,22 @@+diff --git a/src/server/index.js b/src/server/index.js+index 67d7345..b3c1f9a 100644+--- a/src/server/index.js++++ b/src/server/index.js+@@ -32,7 +32,16 @@ if (!process.env.JWT_SECRET) {+ throw new Error('[envs] JWT_SECRET not set')+ }+ if (!process.env.ADMIN_CODE) {+- console.warn('[envs] ADMIN_CODE not set - all users will have admin permissions!')++ // Fail closed in production: without ADMIN_CODE, Hyperfy's Settings.effectiveRank++ // falls back to Ranks.ADMIN, so EVERY visitor joins with admin/build rights and++ // can delete the ground or replace the scene. That fail-open default is how++ // world.three.ws was repeatedly left UNPROTECTED (the 2026-06-12 void-fall).++ // Refuse to boot so a secret-less revision fails its startup probe and Cloud Run++ // keeps serving the last protected revision instead of exposing build rights.++ if (process.env.NODE_ENV === 'production') {++ throw new Error('[envs] ADMIN_CODE not set - refusing to start an UNPROTECTED world in production')++ }++ console.warn('[envs] ADMIN_CODE not set - all users will have admin permissions!')+ }+ if (!process.env.SAVE_INTERVAL) {+ throw new Error('[envs] SAVE_INTERVAL not set')diff --git a/public/changelog.json b/public/changelog.jsonindex 81950225f..756bf6abf 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-28T19:49:27.976Z",+ "generated_at": "2026-06-28T20:53:56.395Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -16,6 +16,16 @@"fix"]},+ {+ "date": "2026-06-28",+ "type": "update",+ "title": "A free, no-login 3D Studio you can add to ChatGPT",+ "summary": "We shipped a brand-new connector that turns any chat into a 3D modeling studio — completely free, with no account, no payment, and nothing to install on your end. It exposes five tools: generate a textured 3D model from a text prompt, build a 3D avatar from text or a reference image, forge an art-directed mesh, auto-rig a static model so it's ready to animate, and do prompt-to-rigged-avatar in a single step. Every result comes back as a downloadable GLB plus an interactive viewer link you can rotate and inspect right in the conversation. It runs entirely on our own model infrastructure — we cover the generation cost — with built-in rate limits so it stays fast and available for everyone. This is a separate, self-contained server from our existing tools, purpose-built so anyone can add prompt-to-3D to their assistant in one click.",+ "link": null,+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-28","type": "update",@@ -100,6 +110,17 @@"security"]},+ {+ "date": "2026-06-28",+ "type": "update",+ "title": "Avatar API no longer stalls when usage logging hits a slow database",+ "summary": "Behind the scenes we record lightweight usage events for things like avatar fetches and uploads. When our fast in-memory buffer was unavailable, each event fell back to writing directly to the database — and a slow database spell could hold that write open for up to 15 seconds, dragging out avatar requests and filling the logs with deadline errors. Those background writes are now strictly time-boxed and fully detached from your request, so a sluggish database can never delay an avatar response. Telemetry stays best-effort; your request always comes first.",+ "link": null,+ "tags": [+ "fix",+ "infra"+ ]+ },{"date": "2026-06-28","type": "update",@@ -183,6 +204,16 @@"fix"]},+ {+ "date": "2026-06-28",+ "type": "update",+ "title": "Fixed strategy backtesting failing to find candidate coins",+ "summary": "Running a strategy backtest (and live strategy runs) could fail with a server error while scanning for candidate coins. The scan and trading steps rely on several bundled trading skills, but only one of them was being shipped to production — so the moment a backtest tried to pull trending or new coins, it hit a missing-module error. All of the required skills now deploy together, and backtests source their candidate coins and replay normally again.",+ "link": null,+ "tags": [+ "fix"+ ]+ },{"date": "2026-06-28","type": "update",@@ -416,6 +447,17 @@"improvement"]},+ {+ "date": "2026-06-28",+ "type": "update",+ "title": "The multiplayer world now refuses to start unprotected",+ "summary": "The three.ws world (world.three.ws) is locked down so only admins can build, move, or delete scene content — everyone else explores freely. Previously, if a world deploy ever went out missing its admin secret, the underlying engine quietly handed every visitor full build rights, which is how the world could get wiped. We closed that gap at the source: a production world build now refuses to boot at all unless the admin secret is present, so a misconfigured deploy can never silently expose build rights — the last known-good, protected version keeps serving instead. Our automated world-health monitor continues to watch for this every 15 minutes.",+ "link": null,+ "tags": [+ "security",+ "infra"+ ]+ },{"date": "2026-06-28","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex c314740e4..9f6726f84 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -14,6 +14,14 @@<category>fix</category><description>Paid actions priced in $THREE (Forge high tier, spins, marketplace) no longer fail when every live price feed happens to miss on the same request. The price layer now keeps a recent last-known-good price and serves it through a momentary simultaneous outage of Jupiter and the backup feeds, so a quote is never rejected over a transient blip. Prices older than five minutes are still refused — a payment is never priced off a stale number. And on the rare moment the payment rail genuinely is catching its breath, you now see a clear "briefly unavailable — try again" message instead of a raw "internal error" support code.</description></item>+ <item>+ <title>A free, no-login 3D Studio you can add to ChatGPT</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-28:A free, no-login 3D Studio you can add to ChatGPT</guid>+ <pubDate>Sun, 28 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>We shipped a brand-new connector that turns any chat into a 3D modeling studio — completely free, with no account, no payment, and nothing to install on your end. It exposes five tools: generate a textured 3D model from a text prompt, build a 3D avatar from text or a reference image, forge an art-directed mesh, auto-rig a static model so it's ready to animate, and do prompt-to-rigged-avatar in a single step. Every result comes back as a downloadable GLB plus an interactive viewer link you can rotate and inspect right in the conversation. It runs entirely on our own model infrastructure — we cover the generation cost — with built-in rate limits so it stays fast and available for everyone. This is a separate, self-contained server from our existing tools, purpose-built so anyone can add prompt-to-3D to their assistant in one click.</description>+ </item><item><title>A quiet Money Pulse now points you to the live feed instead of a dead end</title><link>https://three.ws/pulse</link>@@ -78,6 +86,14 @@<category>infra</category><description>A broken auth subsystem — a JWT signer that stops working, a verifier that accepts expired tokens, or a misconfigured issuer — can lock users out silently or, worse, leave a security hole open. The platform now detects both within 30 minutes. Every half-hour an autonomous agent makes a real on-chain payment to a new /api/x402/auth-health endpoint and runs a four-step session lifecycle canary: mint a canary access token, verify it with the full JWT verifier, issue a replacement token and re-verify it (the rotation path), and confirm that an already-expired token is rejected. Each step is timed independently; a failure names exactly which step broke and why. The result — all_pass, failed_step, and per-step latency — is recorded as an actionable signal so ops can read auth health off a single log row without a separate query.</description></item>+ <item>+ <title>Avatar API no longer stalls when usage logging hits a slow database</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-28:Avatar API no longer stalls when usage logging hits a slow database</guid>+ <pubDate>Sun, 28 Jun 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>Behind the scenes we record lightweight usage events for things like avatar fetches and uploads. When our fast in-memory buffer was unavailable, each event fell back to writing directly to the database — and a slow database spell could hold that write open for up to 15 seconds, dragging out avatar requests and filling the logs with deadline errors. Those background writes are now strictly time-boxed and fully detached from your request, so a sluggish database can never delay an avatar response. Telemetry stays best-effort; your request always comes first.</description>+ </item><item><title>Avatar generation rides out engine outages by failing over between backends</title><link>https://three.ws/create/prompt</link>@@ -142,6 +158,14 @@<category>fix</category><description>The Gaussian-splat viewer (/splat), the capture tool (/capture), the integrations directory (/integrations), partners (/partners), and the live-agents board (/agents-live) were all returning a 404 in production even though the pages existed and were linked from the nav. Our routing pins every clean URL explicitly, and these five were missing their entry, so the request fell through to the not-found page. We added the missing routes and tightened the route audit so a new page can no longer ship without one.</description></item>+ <item>+ <title>Fixed strategy backtesting failing to find candidate coins</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-28:Fixed strategy backtesting failing to find candidate coins</guid>+ <pubDate>Sun, 28 Jun 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>Running a strategy backtest (and live strategy runs) could fail with a server error while scanning for candidate coins. The scan and trading steps rely on several bundled trading skills, but only one of them was being shipped to production — so the moment a backtest tried to pull trending or new coins, it hit a missing-module error. All of the required skills now deploy together, and backtests source their candidate coins and replay normally again.</description>+ </item><item><title>Fixed: "Generate API key" in the Agent Screen worker setup</title><link>https://three.ws/agent-screen</link>@@ -318,6 +342,14 @@<category>improvement</category><description>The Money Pulse page (/pulse) now renders on a true black background in every theme, so the live feed of tips, launches, trades and agent-to-agent payments reads as one calm, high-contrast field. Previously the page could pick up a lighter surface or near-black tone depending on your theme; it's now consistently black with the monochrome ink ramp pinned for readability.</description></item>+ <item>+ <title>The multiplayer world now refuses to start unprotected</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-28:The multiplayer world now refuses to start unprotected</guid>+ <pubDate>Sun, 28 Jun 2026 12:00:00 GMT</pubDate>+ <category>security</category>+ <description>The three.ws world (world.three.ws) is locked down so only admins can build, move, or delete scene content — everyone else explores freely. Previously, if a world deploy ever went out missing its admin secret, the underlying engine quietly handed every visitor full build rights, which is how the world could get wiped. We closed that gap at the source: a production world build now refuses to boot at all unless the admin secret is present, so a misconfigured deploy can never silently expose build rights — the last known-good, protected version keeps serving instead. Our automated world-health monitor continues to watch for this every 15 minutes.</description>+ </item><item><title>The shared 3D world stays in sync through server updates</title><link>https://three.ws/changelog</link>diff --git a/public/features.json b/public/features.jsonindex c2a816d74..b3c39b5b5 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-28T19:49:27.816Z",+ "generated_at": "2026-06-28T20:53:56.303Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/tests/api/forge-credit-exhaustion-rescue.test.js b/tests/api/forge-credit-exhaustion-rescue.test.jsnew file mode 100644index 000000000..15425a5a3--- /dev/null+++ b/tests/api/forge-credit-exhaustion-rescue.test.js@@ -0,0 +1,173 @@+/**+ * Credit-exhaustion rescue + designed degradation for api/forge.js.+ *+ * The prod failure (TASK-4): the platform's paid Replicate account ran out of+ * credit, so the FLUX reference-image synthesis (textToImage) — the FIRST paid+ * step of a standard/high tier text→3D request — threw a billing/402 error.+ *+ * That billing error is NOT "upstream-unavailable" (it's a 402, not a 429/5xx),+ * so the last-resort free NIM TRELLIS text→mesh rescue used to be skipped and the+ * request dead-ended at the 503 — even though NIM TRELLIS is native text→mesh and+ * needs no FLUX intermediate at all, i.e. a perfectly healthy free lane was left+ * unused. These tests pin the corrected behavior:+ *+ * 1. FLUX synthesis out of credit + NIM TRELLIS healthy → the prompt is rescued+ * on the free NIM lane (200, backend:nvidia). The paid reconstruct is never+ * reached (the failure was at synthesis, before it).+ * 2. FLUX synthesis out of credit + NIM TRELLIS also down → a DESIGNED+ * "temporarily unavailable" 503 (never a 500, never the vendor billing leak).+ *+ * The HF reconstruct lane is deliberately irrelevant here: it reconstructs the+ * SYNTHESIZED view, and synthesis is exactly what's broke — only a native+ * text→mesh lane can rescue this, which is the whole point of the fix.+ */++import { describe, it, expect, vi, beforeAll } from 'vitest';++beforeAll(() => {+ Object.assign(process.env, {+ APP_ORIGIN: 'https://three.ws',+ REPLICATE_API_TOKEN: 'test-token',+ NVIDIA_API_KEY: 'test-nvidia-key',+ JWT_SECRET: 'test-jwt-secret-at-least-32-characters-long',+ });+ delete process.env.GCP_HUNYUAN3D_URL;+ delete process.env.GCP_RECONSTRUCTION_KEY;+ delete process.env.HF_TOKEN; // no free reconstruct lane — irrelevant to a synth failure+ delete process.env.FORGE_PREFER_FREE;+});++// Free NIM TRELLIS text→mesh lane. Default: HEALTHY, returns a finished GLB+// synchronously (no taskId) exactly like the real sync NVCF branch. A test can+// flip it to down to exercise the designed-503 path.+const nvidiaTextTo3d = vi.fn(async () => ({+ kind: 'trellis',+ taskId: null,+ resultGlbUrl: 'https://cdn.example/nim-rescue.glb',+}));+vi.mock('../../api/_providers/nvidia.js', () => ({+ createNvidiaProvider: () => ({ textTo3d: nvidiaTextTo3d }),+}));++// FLUX reference-image synthesis is OUT OF CREDIT — the exact prod symptom. This+// throws the billing envelope textToImage tags (code:'billing', providerStatus:402),+// which is NOT upstream-unavailable.+const textToImage = vi.fn(async () => {+ throw Object.assign(new Error('image provider billing error'), {+ code: 'billing',+ providerStatus: 402,+ providerDetail:+ 'You have insufficient credit to run this model. Go to https://replicate.com/account/billing to purchase credit.',+ });+});+vi.mock('../../api/_mcp3d/text-to-image.js', () => ({ textToImage }));++// Paid Replicate reconstruct. A module-level spy lets us assert it is NEVER+// reached — the failure is at synthesis, upstream of any reconstruct.+const replicateSubmit = vi.fn(async () => ({ extJobId: 'should-not-run' }));+vi.mock('../../api/_providers/replicate.js', () => ({+ createRegenProvider: () => ({ submit: replicateSubmit }),+}));++vi.mock('../../api/_lib/forge-store.js', () => ({+ hashClient: (v) => `client:${v || 'anon'}`,+ hashIp: (v) => `ip:${v}`,+ createCreation: vi.fn(async () => 'creation-1'),+ materializeCreation: vi.fn(async ({ glbUrl }) => ({ id: 'creation-1', glbUrl })),+ markFailed: vi.fn(async () => {}),+ findByJob: vi.fn(async () => null),+}));++vi.mock('../../api/_lib/forge-image-validate.js', () => ({+ validateForgeImage: vi.fn(async () => ({ ok: true })),+}));++vi.mock('../../api/_lib/rate-limit.js', async (importActual) => {+ const actual = await importActual();+ return {+ ...actual,+ limits: {+ ...actual.limits,+ mcp3dGenerate: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),+ mcp3dGenerateFree: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),+ mcp3dGenerateFreeTiered: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),+ },+ clientIp: () => '203.0.113.21',+ };+});++const { default: handler } = await import('../../api/forge.js');++function makeReq(body) {+ return {+ method: 'POST',+ url: '/api/forge',+ headers: { 'content-type': 'application/json', 'x-forge-client': 'tester' },+ on(event, cb) {+ if (event === 'data') cb(Buffer.from(JSON.stringify(body)));+ if (event === 'end') cb();+ },+ };+}++function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: null,+ setHeader(name, value) {+ this.headers[String(name).toLowerCase()] = value;+ },+ getHeader(name) {+ return this.headers[String(name).toLowerCase()];+ },+ end(body) {+ this.body = body ? JSON.parse(body) : null;+ },+ };+}++describe('forge credit-exhaustion rescue', () => {+ it('rescues a text prompt on the free NIM lane when paid FLUX synthesis is out of credit', async () => {+ nvidiaTextTo3d.mockClear();+ replicateSubmit.mockClear();+ textToImage.mockClear();++ // Standard tier text→3D: NIM is NOT the first-choice lane (draft-only), so the+ // request reaches the paid FLUX synthesis — which is dry — and must fail OVER+ // to the native free NIM text→mesh lane rather than dead-end.+ const req = makeReq({ prompt: 'a red ceramic mug', tier: 'standard', path: 'image' });+ const res = makeRes();+ await handler(req, res);++ expect(textToImage).toHaveBeenCalled(); // paid synthesis attempted (and broke)+ expect(res.statusCode).toBe(200);+ expect(res.body.status).toBe('done');+ expect(res.body.backend).toBe('nvidia'); // provenance shows the lane that actually ran+ expect(res.body.glb_url).toBe('https://cdn.example/nim-rescue.glb');+ expect(nvidiaTextTo3d).toHaveBeenCalled();+ // The reconstruct lane was never reached — the failure was upstream of it.+ expect(replicateSubmit).not.toHaveBeenCalled();+ });++ it('returns a DESIGNED unavailable state (not a 500) when synthesis is out of credit AND the free NIM lane is also down', async () => {+ textToImage.mockClear();+ nvidiaTextTo3d.mockClear();+ // NIM rescue is down too — every lane is exhausted.+ nvidiaTextTo3d.mockRejectedValueOnce(+ Object.assign(new Error('TRELLIS gateway 503'), { code: 'provider_unreachable' }),+ );++ const req = makeReq({ prompt: 'a red ceramic mug', tier: 'standard', path: 'image' });+ const res = makeRes();+ await handler(req, res);++ expect(textToImage).toHaveBeenCalled();+ expect(nvidiaTextTo3d).toHaveBeenCalled(); // the rescue WAS attempted+ expect(res.statusCode).toBe(503); // honest, designed — never a 500+ expect(res.body.error).toBe('generation_unavailable');+ // The vendor's raw billing copy is never leaked to the buyer.+ expect(res.body.message).not.toMatch(/credit|replicate|billing|insufficient/i);+ expect(res.headers['retry-after']).toBe('30');+ });+});diff --git a/tests/api/providers-huggingface-rehost.test.js b/tests/api/providers-huggingface-rehost.test.jsindex 6faef2554..b35b7874c 100644--- a/tests/api/providers-huggingface-rehost.test.js+++ b/tests/api/providers-huggingface-rehost.test.js@@ -8,8 +8,10 @@// Invariants under test:// • With object storage configured, the returned resultGlbUrl is the durable// R2 URL, not the raw Space URL, and the mesh was uploaded exactly once.-// • A 404 on the (already-expired) Space file fails soft to the raw URL — the-// result is never worse than handing back the Space URL.+// • With storage configured, a 404 on the (already-expired) Space file must NOT+// leak the ephemeral URL downstream: the provider fails over to the next+// Space and regenerates, and if none remain it throws a designed error+// instead of handing back a URL guaranteed to 404 in materializeCreation.// • Without storage configured, re-host is skipped entirely (no fetch of the// mesh, no upload) and the raw Space URL is returned, unchanged behavior.@@ -106,14 +108,26 @@ describe('huggingface provider — durable GLB re-host', () => {expect(putObject.mock.calls[0][0]).toMatchObject({ contentType: 'model/gltf-binary' });});- it('fails soft to the raw Space URL when the ephemeral file already 404s', async () => {+ it('regenerates on the next Space when the first Space\'s mesh already 404s, never leaking the ephemeral URL', async () => {setS3();- const fetchMock = vi.fn(async (url) => {+ // foo/A produces a GLB whose temp file is already gone (404 on rehost); bar/B+ // produces a live one. The doomed foo/A URL must never escape — we expect a+ // durable bar/B copy instead.+ process.env.HF_RECONSTRUCT_SPACES = 'foo/A,bar/B';+ const fetchMock = vi.fn(async (url, opts) => {if (url === `${spaceUrl('foo/A')}/call/generation_all`) return jsonResp({ event_id: 'evt-A' });if (url === `${spaceUrl('foo/A')}/call/generation_all/evt-A`) {return sseStream([{ url: 'https://files.hf/tmp/gradio/gone/model.glb' }]);}if (url === 'https://files.hf/tmp/gradio/gone/model.glb') return new Response('', { status: 404 });+ if (url === `${spaceUrl('bar/B')}/call/generation_all`) return jsonResp({ event_id: 'evt-B' });+ if (url === `${spaceUrl('bar/B')}/call/generation_all/evt-B`) {+ return sseStream([{ url: 'https://files.hf/tmp/gradio/live/model.glb' }]);+ }+ if (url === 'https://files.hf/tmp/gradio/live/model.glb') {+ expect(opts?.headers?.authorization).toBe('Bearer hf_test_token');+ return new Response(glbBytes(), { status: 200, headers: { 'content-type': 'model/gltf-binary' } });+ }throw new Error(`unexpected url ${url}`);});globalThis.fetch = fetchMock;@@ -125,7 +139,36 @@ describe('huggingface provider — durable GLB re-host', () => {});const decoded = JSON.parse(Buffer.from(out.extJobId, 'base64url').toString('utf8'));- expect(decoded.resultGlbUrl).toBe('https://files.hf/tmp/gradio/gone/model.glb');+ expect(decoded.resultGlbUrl).toMatch(/^https:\/\/cdn\.example\/hf-recon\/[0-9a-f-]+\.glb$/);+ expect(decoded.resultGlbUrl).not.toContain('files.hf');+ expect(decoded.space).toBe('bar/B');+ expect(decoded.fellBackFrom).toEqual(['foo/A']);+ expect(putObject).toHaveBeenCalledTimes(1);+ });++ it('throws a designed error rather than returning the ephemeral URL when every Space\'s mesh 404s', async () => {+ setS3();+ const fetchMock = vi.fn(async (url) => {+ if (url === `${spaceUrl('foo/A')}/call/generation_all`) return jsonResp({ event_id: 'evt-A' });+ if (url === `${spaceUrl('foo/A')}/call/generation_all/evt-A`) {+ return sseStream([{ url: 'https://files.hf/tmp/gradio/gone/model.glb' }]);+ }+ if (url === 'https://files.hf/tmp/gradio/gone/model.glb') return new Response('', { status: 404 });+ throw new Error(`unexpected url ${url}`);+ });+ globalThis.fetch = fetchMock;++ const { createRegenProvider } = await import('../../api/_providers/huggingface.js');+ await expect(+ createRegenProvider().submit({+ mode: 'reconstruct',+ params: { images: ['data:image/jpeg;base64,AAA'] },+ }),+ ).rejects.toMatchObject({+ code: 'all_providers_failed',+ message: expect.stringMatching(/not persistable/),+ });+ // The doomed ephemeral URL was never persisted.expect(putObject).not.toHaveBeenCalled();});diff --git a/tests/api/text-to-image.test.js b/tests/api/text-to-image.test.jsindex 1128f3733..a88c35145 100644--- a/tests/api/text-to-image.test.js+++ b/tests/api/text-to-image.test.js@@ -28,6 +28,16 @@ vi.mock('../../api/_lib/r2.js', () => ({publicUrl: (key) => `https://cdn.example/${key}`,}));+// The Replicate text→image submit is paced through forge-scale's rate gate. The+// gate itself fails open without Redis (its own unit tests cover that); here we+// drive it deterministically so we can assert the queue/shed behavior of the+// caller. Defaults to "slot granted, no wait" so every other test is unaffected.+const rateState = { result: { ok: true, waitMs: 0 } };+vi.mock('../../api/_lib/forge-scale.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, reserveProviderRateSlot: vi.fn(async () => rateState.result) };+});+const ORIGINAL_FETCH = globalThis.fetch;const ENV_KEYS = ['NVIDIA_API_KEY', 'GOOGLE_CLOUD_PROJECT', 'GCP_SERVICE_ACCOUNT_JSON', 'REPLICATE_API_TOKEN'];const ORIGINAL_ENV = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));@@ -79,6 +89,7 @@ beforeEach(async () => {vertexState.configured = false;vertexState.generate = null;r2State.puts.length = 0;+ rateState.result = { ok: true, waitMs: 0 };for (const k of ENV_KEYS) delete process.env[k];// The NIM FLUX circuit breaker persists a short cooldown in the shared in-memory// cache; clear it between tests so one test's induced NIM failure doesn't make a@@ -356,6 +367,54 @@ describe('textToImage — Vertex → Replicate fallback', () => {expect(caught.message).not.toMatch(/credit|\$5|throttl|rate limit/i);});+ it('queues against the Replicate rate gate and waits for the reserved slot before submitting', async () => {+ // Under the reduced-rate account state Replicate paces creation to 6/min; the+ // gate reserves the next slot and tells us to hold for it. We must wait out+ // that slot, THEN submit — never fire early into a throttle 429.+ process.env.REPLICATE_API_TOKEN = 'r8_test_token';+ rateState.result = { ok: true, waitMs: 5_000 };+ const calls = stubFetch([['api.replicate.com', () => replicateSuccessResponse()]]);++ vi.useFakeTimers();+ try {+ const textToImage = await freshTextToImage();+ const p = textToImage('a red teapot');+ // Mid-wait: the reserved slot has not opened, so no prediction is created yet.+ await vi.advanceTimersByTimeAsync(4_000);+ expect(calls.some((c) => c.url.includes('api.replicate.com'))).toBe(false);+ // Slot opens — the submit fires and resolves.+ await vi.advanceTimersByTimeAsync(2_000);+ const result = await p;+ expect(result.imageUrl).toBe('https://replicate.delivery/out.png');+ expect(calls.some((c) => c.url.includes('api.replicate.com'))).toBe(true);+ } finally {+ vi.useRealTimers();+ }+ });++ it('sheds to a queued rate-limit (no submit) when the queue is deeper than the wait budget', async () => {+ // The gate reports the next slot is further out than we will block a worker for.+ // We must NOT fire the prediction (that would just earn a throttle 429); instead+ // surface a retryable, queued rate-limit carrying the time until the slot opens.+ process.env.REPLICATE_API_TOKEN = 'r8_test_token';+ rateState.result = { ok: false, waitMs: 12_000 };+ const calls = stubFetch([['api.replicate.com', () => replicateSuccessResponse()]]);++ const textToImage = await freshTextToImage();+ const caught = await textToImage('a red teapot').then(+ () => null,+ (e) => e,+ );+ expect(caught).toBeTruthy();+ expect(caught.code).toBe('rate_limited');+ expect(caught.queued).toBe(true);+ expect(caught.retryAfter).toBe(12); // ceil(12000ms / 1000)+ // The Replicate prediction was never created — we shed before firing.+ expect(calls.some((c) => c.url.includes('api.replicate.com'))).toBe(false);+ // The buyer-facing message names the queue, not the account's rate state.+ expect(caught.message).not.toMatch(/credit|\$|throttl|rate limit/i);+ });+it('masks a Replicate 402 out-of-credit failure as a buyer-safe billing error', async () => {// The incident the user hit: the free NIM lane fell through to the paid// Replicate backstop, which had zero credit. Replicate returns the harddiff --git a/tests/forge-scale.test.js b/tests/forge-scale.test.jsindex 7e449cdd6..4156f9114 100644--- a/tests/forge-scale.test.js+++ b/tests/forge-scale.test.js@@ -6,6 +6,7 @@ import {registerInFlight,acquireBlockingSlot,providerSubmitAllowed,+ reserveProviderRateSlot,dailyPaidAllowed,circuitState,circuitRecordFailure,@@ -81,6 +82,16 @@ describe('fail-open behavior without Redis', () => {expect(await providerSubmitAllowed('replicate', { limit: 1, windowS: 10 })).toBe(true);});+ it('reserveProviderRateSlot grants an immediate, zero-wait slot', async () => {+ // No Redis → no shared bucket to pace against, so the gate must never queue or+ // reject: every caller proceeds instantly (a paced lane beats a blocked one).+ const a = await reserveProviderRateSlot('replicate', { ratePerMin: 6, burst: 1, maxWaitMs: 15_000 });+ expect(a).toEqual({ ok: true, waitMs: 0 });+ // A second back-to-back reserve also clears — there is no store to count against.+ const b = await reserveProviderRateSlot('replicate', { ratePerMin: 6, burst: 1, maxWaitMs: 15_000 });+ expect(b).toEqual({ ok: true, waitMs: 0 });+ });+it('dailyPaidAllowed allows and reports the limit', async () => {const r = await dailyPaidAllowed('client-abc', { limit: 60 });expect(r.ok).toBe(true);@@ -116,5 +127,9 @@ describe('SCALE_LIMITS', () => {expect(SCALE_LIMITS.hfSlotTtlMs).toBeGreaterThanOrEqual(300_000);expect(SCALE_LIMITS.replicateSubmitLimit).toBeGreaterThan(0);expect(SCALE_LIMITS.replicateSubmitWindowS).toBeGreaterThan(0);+ // The text→image queue paces to Replicate's reduced-rate ceiling: 6/min, burst 1.+ expect(SCALE_LIMITS.replicateRatePerMin).toBe(6);+ expect(SCALE_LIMITS.replicateRateBurst).toBe(1);+ expect(SCALE_LIMITS.replicateQueueMaxMs).toBeGreaterThan(0);});});diff --git a/tests/pumpfun-ws-premature-close.test.js b/tests/pumpfun-ws-premature-close.test.jsnew file mode 100644index 000000000..990c35e18--- /dev/null+++ b/tests/pumpfun-ws-premature-close.test.js@@ -0,0 +1,77 @@+// Regression: tearing down the PumpPortal WS before its handshake completes+// must not surface the benign "WebSocket was closed before the connection was+// established" error. This is the common serverless path — the alpha-candidates+// endpoint taps the feed on a short timer (collectLiveMints) and aborts it,+// frequently while the upstream socket is still CONNECTING.+//+// The fake `ws` mirrors the real library: close()/terminate() on a CONNECTING+// socket aborts the handshake and emits 'error' (premature-close) then 'close'+// asynchronously, to whatever listeners are registered at emit time.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++const PREMATURE = 'WebSocket was closed before the connection was established';++class FakeWS {+ constructor(url) {+ this.url = url;+ this.readyState = 0; // CONNECTING — never transitions to OPEN here+ this._h = {};+ FakeWS.instances.push(this);+ }+ on(ev, cb) { (this._h[ev] ||= []).push(cb); return this; }+ removeAllListeners(ev) { if (ev) delete this._h[ev]; else this._h = {}; return this; }+ emit(ev, ...a) { (this._h[ev] || []).forEach((cb) => cb(...a)); }+ send() {}+ terminate() { this._abortHandshake(); }+ close() { if (this.readyState === 0) this._abortHandshake(); else this.emit('close'); }+ _abortHandshake() {+ this.readyState = 2; // CLOSING+ // Real ws emits on process.nextTick — defer so listeners registered during+ // teardown (the no-op error swallow) are the ones that receive it.+ queueMicrotask(() => {+ this.emit('error', new Error(PREMATURE));+ this.emit('close');+ });+ }+}+FakeWS.instances = [];++vi.mock('ws', () => ({ default: FakeWS }));++// Keep the REST mint fallback inert (kind:'mint' kicks off a poll on connect).+globalThis.fetch = vi.fn(async () => ({ ok: true, json: async () => [] }));++const { connectPumpFunFeed } = await import('../api/_lib/pumpfun-ws-feed.js');++const settle = () => new Promise((r) => setTimeout(r, 10));++describe('connectPumpFunFeed — teardown mid-handshake', () => {+ let warnSpy;+ beforeEach(() => {+ FakeWS.instances.length = 0;+ warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});+ });+ afterEach(() => warnSpy.mockRestore());++ it('does not log a premature-close error when stopped while CONNECTING', async () => {+ const stop = connectPumpFunFeed({ kind: 'mint', mints: [], onEvent: () => {} });+ const ws = FakeWS.instances[0];+ expect(ws.readyState).toBe(0); // still connecting — no open() emitted+ stop();+ await settle();+ const logged = warnSpy.mock.calls.some((c) => String(c.join(' ')).includes(PREMATURE));+ expect(logged).toBe(false);+ });++ it('does not log a premature-close error when aborted via the signal', async () => {+ const ac = new AbortController();+ connectPumpFunFeed({ kind: 'mint', mints: [], signal: ac.signal, onEvent: () => {} });+ const ws = FakeWS.instances[0];+ expect(ws.readyState).toBe(0);+ ac.abort();+ await settle();+ const logged = warnSpy.mock.calls.some((c) => String(c.join(' ')).includes(PREMATURE));+ expect(logged).toBe(false);+ });+});diff --git a/tests/usage-direct-insert-timeout.test.js b/tests/usage-direct-insert-timeout.test.jsnew file mode 100644index 000000000..b9bfa8a21--- /dev/null+++ b/tests/usage-direct-insert-timeout.test.js@@ -0,0 +1,54 @@+// Regression for TASK-7: when the Redis usage buffer is down, every event takes+// the direct-insert fallback. A slow/wedged Neon must NOT hold that work open for+// the 15s default DB budget (the storm of `db query exceeded 15000ms deadline`+// errors that was stalling the avatar API). The fallback runs under a short,+// bounded per-event timeout and never throws back to the (detached) caller.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++// Redis buffer unavailable → recordEvent must fall through to direct insert.+vi.mock('../api/_lib/redis.js', () => ({ getRedis: () => null }));++// QStash disabled so no flush-job side effects fire during the test.+vi.mock('../api/_lib/qstash.js', () => ({+ qstashEnabled: () => false,+ publishJob: vi.fn(async () => {}),+}));++// A `sql` tagged template that never settles — models a wedged Neon connection+// (the failure mode db-retry's deadline exists to abandon).+vi.mock('../api/_lib/db.js', () => ({+ sql: () => new Promise(() => {}),+}));++import { recordEvent } from '../api/_lib/usage.js';++describe('recordEvent direct-insert fallback (buffer down)', () => {+ beforeEach(() => vi.restoreAllMocks());+ afterEach(() => vi.restoreAllMocks());++ it('does not block the caller and bounds a wedged insert well under the 15s budget', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ const startedAt = Date.now();+ // recordEvent is fire-and-forget: it must return synchronously (undefined),+ // never awaiting the DB write.+ const ret = recordEvent({ userId: 'u1', kind: 'avatar_fetch' });+ expect(ret).toBeUndefined();+ expect(Date.now() - startedAt).toBeLessThan(50);++ // Wait past the 2.5s fallback budget (plus retry backoff) but far under 15s.+ await new Promise((r) => setTimeout(r, 4_000));++ const elapsed = Date.now() - startedAt;+ expect(elapsed).toBeLessThan(10_000);++ // The bounded write times out and is swallowed with a deadline warning that+ // names the SHORT budget, not the 15s default.+ const msgs = warn.mock.calls.map((c) => `${c[0]} ${c[1] ?? ''}`);+ const deadlineWarn = msgs.find((m) => m.includes('[usage] write failed'));+ expect(deadlineWarn).toBeTruthy();+ expect(deadlineWarn).toContain('2500ms deadline');+ expect(deadlineWarn).not.toContain('15000ms');+ }, 15_000);+});diff --git a/vercel.json b/vercel.jsonindex d2bbdaa02..08cd3ac20 100644--- a/vercel.json+++ b/vercel.json@@ -86,6 +86,9 @@"api/cron/payment-session-sweep.js": {"maxDuration": 30},+ "api/cron/three-market-refresh.js": {+ "maxDuration": 30+ },"api/cron/oracle-score.js": {"includeFiles": "{examples/skills/**,data/pages.json,data/_generated/**,sdk/src/sas-config.json}","maxDuration": 120@@ -4518,6 +4521,10 @@"path": "/api/cron/payment-session-sweep","schedule": "*/5 * * * *"},+ {+ "path": "/api/cron/three-market-refresh",+ "schedule": "* * * * *"+ },{"path": "/api/cron/avaturn-seed-cron","schedule": "* * * * *"