Skip to content

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

fix: harden cache, reputation, usage logging, forge, and x402 payment paths

nirholas9d59916579dc
diff --git a/api/_lib/cache.js b/api/_lib/cache.js
index 900752278..7b6cf6669 100644
--- a/api/_lib/cache.js
+++ b/api/_lib/cache.js
@@ -74,6 +74,15 @@ function redisConfigured() {
return Boolean(env.UPSTASH_REDIS_REST_URL && env.UPSTASH_REDIS_REST_TOKEN);
}
+// A cache round-trip must be fast or not happen at all. Without a timeout a
+// Upstash TCP stall (as opposed to a clean 5xx, which rejects promptly) would hang
+// the fetch until the caller's function hits its hard maxDuration → a 504 on an
+// endpoint whose whole point in calling us was to be fast. Cap every command so a
+// degraded Redis fails fast into the in-memory fallback instead of stalling the
+// request. 3s is far longer than a healthy REST GET/SET yet well under any caller's
+// budget.
+const REDIS_CMD_TIMEOUT_MS = 3_000;
+
async function redisCmd(args) {
const r = await fetch(env.UPSTASH_REDIS_REST_URL, {
method: 'POST',
@@ -82,6 +91,7 @@ async function redisCmd(args) {
'content-type': 'application/json',
},
body: JSON.stringify(args),
+ signal: AbortSignal.timeout(REDIS_CMD_TIMEOUT_MS),
});
if (!r.ok) throw new Error(`upstash ${r.status}: ${await r.text().catch(() => '')}`);
const json = await r.json();
diff --git a/api/_lib/trust/reputation-store.js b/api/_lib/trust/reputation-store.js
index a5e6c021f..056876f95 100644
--- a/api/_lib/trust/reputation-store.js
+++ b/api/_lib/trust/reputation-store.js
@@ -187,13 +187,22 @@ export async function listStaleAgents(limit = 40) {
*
* @param {string[]} agentIds
* @param {object} [opts]
- * @returns {Promise<{ scored: number, failed: number }>}
+ * @param {number} [opts.concurrency]
+ * @param {number} [opts.deadlineMs] stop dispatching new chunks once this much
+ * wall-clock has elapsed, so a per-agent RPC/DB latency spike can't run the
+ * batch past the cron's function timeout. Unscored agents simply roll over to
+ * the next tick (they sort as stalest-first), so coverage is never lost.
+ * @returns {Promise<{ scored: number, failed: number, remaining: number, timedOut: boolean }>}
*/
-export async function recomputeAgents(agentIds = [], { concurrency = 4 } = {}) {
+export async function recomputeAgents(agentIds = [], { concurrency = 4, deadlineMs = Infinity } = {}) {
let scored = 0;
let failed = 0;
+ let timedOut = false;
const ids = [...new Set(agentIds.filter(Boolean))];
- for (let i = 0; i < ids.length; i += concurrency) {
+ const startedAt = Date.now();
+ let i = 0;
+ for (; i < ids.length; i += concurrency) {
+ if (Date.now() - startedAt > deadlineMs) { timedOut = true; break; }
const chunk = ids.slice(i, i + concurrency);
const results = await Promise.allSettled(chunk.map((id) => getAgentReputation(id)));
for (const r of results) {
@@ -205,5 +214,5 @@ export async function recomputeAgents(agentIds = [], { concurrency = 4 } = {}) {
}
}
}
- return { scored, failed };
+ return { scored, failed, remaining: Math.max(0, ids.length - i), timedOut };
}
diff --git a/api/_lib/usage.js b/api/_lib/usage.js
index 2684381ef..83e3b7ae6 100644
--- a/api/_lib/usage.js
+++ b/api/_lib/usage.js
@@ -115,19 +115,27 @@ export function recordEvent(evt) {
}
/**
- * Drain up to `limit` events from the Redis buffer and insert them into Neon.
- * Returns { flushed, remaining, errors }.
+ * Drain up to `limit` events from the Redis buffer and insert them into Neon,
+ * stopping after `deadlineMs` so a slow Neon spell can't push the caller past its
+ * function timeout. Returns { flushed, remaining, errors, timedOut }.
* Called by api/cron/flush-usage-events.js and api/jobs/flush-usage-events.js.
*/
-export async function flushUsageBuffer({ limit = 500 } = {}) {
+export async function flushUsageBuffer({ limit = 500, deadlineMs = 45_000 } = {}) {
const r = getRedis();
if (!r) return { flushed: 0, remaining: 0, errors: 0, skipped: 'redis_unavailable' };
const BATCH = 200;
let flushed = 0;
let errors = 0;
+ let timedOut = false;
+ // Stop cleanly before the function's maxDuration: a slow Neon write spell across
+ // several batches could otherwise run past the limit and 504 the cron, dropping
+ // the entire flush. Bailing early returns what we managed — the safety-net cron
+ // runs again next minute and clears the rest (`remaining` is also alerted on).
+ const startedAt = Date.now();
while (flushed < limit) {
+ if (Date.now() - startedAt > deadlineMs) { timedOut = true; break; }
const take = Math.min(BATCH, limit - flushed);
// Read the front of the list, then atomically trim those entries.
const raw = await r.lrange(BUFFER_KEY, 0, take - 1);
@@ -156,7 +164,7 @@ export async function flushUsageBuffer({ limit = 500 } = {}) {
}
const remaining = await r.llen(BUFFER_KEY).catch(() => -1);
- return { flushed, remaining, errors };
+ return { flushed, remaining, errors, timedOut };
}
export function logger(name) {
diff --git a/api/cron/forge-seed-cron.js b/api/cron/forge-seed-cron.js
index aaadaa1f4..0c64bbc39 100644
--- a/api/cron/forge-seed-cron.js
+++ b/api/cron/forge-seed-cron.js
@@ -31,7 +31,15 @@ const ORIGIN = () => env.APP_ORIGIN || 'https://three.ws';
// fires its own DOMException[TimeoutError]. When the timeout fires, fetchJson returns
// { timedOut: true } — startNextJob treats that as a soft failure and rolls back
// the pending user so the next tick can retry cleanly.
-const FETCH_TIMEOUT_MS = 48_000;
+//
+// poll + submit run in parallel and each can hold a fetch for this long, with the
+// per-job DB work (avatar insert, job upserts, user rollback) stacked on top inside
+// the same 70 s window. At 48 s a worst-case fetch left too little headroom for that
+// tail and the cron occasionally tipped past 70 s → a hard 504. The free NVIDIA
+// draft lane returns inline in ~13–22 s, so 35 s still covers a healthy generation
+// with wide margin while keeping the whole tick comfortably under the ceiling; a
+// genuinely degraded lane simply rolls back and retries next minute.
+const FETCH_TIMEOUT_MS = 35_000;
const MAX_CONCURRENT_PENDING = 3;
const MIN_JOB_AGE_SECONDS = 20;
diff --git a/api/cron/recompute-reputation.js b/api/cron/recompute-reputation.js
index d8946ec79..1fbdedbd7 100644
--- a/api/cron/recompute-reputation.js
+++ b/api/cron/recompute-reputation.js
@@ -50,9 +50,13 @@ export default wrap(async (req, res) => {
if (!ids.length) {
return json(res, 200, { ok: true, scored: 0, failed: 0, reason: 'no agents to score' });
}
- const { scored, failed } = await recomputeAgents(ids);
- console.log(`[recompute-reputation] scored ${scored}/${ids.length} (failed ${failed}) in ${Date.now() - started}ms`);
- return json(res, 200, { ok: true, scored, failed, batch: ids.length, elapsed_ms: Date.now() - started });
+ // Stop well before Vercel's 300s hard kill: a single agent's slow RPC/DB read
+ // must not drag the whole batch past the limit and 504 the cron (which would
+ // drop every score this tick). Unfinished agents are the stalest, so they're
+ // first in line next run — continuous rollover, never lost coverage.
+ const { scored, failed, remaining, timedOut } = await recomputeAgents(ids, { deadlineMs: 250_000 });
+ console.log(`[recompute-reputation] scored ${scored}/${ids.length} (failed ${failed}, remaining ${remaining}${timedOut ? ', hit time budget' : ''}) in ${Date.now() - started}ms`);
+ return json(res, 200, { ok: true, scored, failed, remaining, timed_out: timedOut, batch: ids.length, elapsed_ms: Date.now() - started });
} catch (err) {
// Never throw: a failed run leaves the prior stored scores intact.
console.error('[recompute-reputation] failed:', err?.message || err);
diff --git a/api/explore.js b/api/explore.js
index 6b162325c..2725a2405 100644
--- a/api/explore.js
+++ b/api/explore.js
@@ -95,8 +95,13 @@ export default wrap(async (req, res) => {
// Filter construction via template fragments kept inline because Neon's
// tagged-template driver doesn't compose them the way pg.Client does; a
// single query with optional predicates guarded by nulls is clearer.
- const onchainRows = includeOnchain
- ? await sql`
+ // The three source feeds are independent — run them concurrently so the
+ // endpoint's DB time is the slowest single query, not the sum of all three.
+ // A leading-wildcard ILIKE scan on one source no longer serializes in front of
+ // the others, which is what pushed slow searches past the function budget → 504.
+ const [onchainRows, avatarRows, solanaRows] = await Promise.all([
+ includeOnchain
+ ? sql`
SELECT chain_id, agent_id, owner, name, description, image, glb_url,
has_3d, x402_support, registered_at, registered_tx,
services, agent_uri
@@ -112,10 +117,9 @@ export default wrap(async (req, res) => {
ORDER BY registered_at DESC NULLS LAST
LIMIT ${limit + 1}
`
- : [];
-
- const avatarRows = includeAvatars
- ? await sql`
+ : [],
+ includeAvatars
+ ? sql`
SELECT a.id, a.slug, a.name, a.description, a.storage_key, a.thumbnail_key,
a.tags, a.created_at, a.source, a.model_category,
coalesce(a.featured, false) AS featured,
@@ -142,10 +146,9 @@ export default wrap(async (req, res) => {
ORDER BY coalesce(a.featured, false) DESC, a.created_at DESC
LIMIT ${(limit + 1) * 3}
`
- : [];
-
- const solanaRows = includeSolana
- ? await sql`
+ : [],
+ includeSolana
+ ? sql`
SELECT ai.id, ai.name, ai.description, ai.wallet_address, ai.skills,
ai.meta, ai.created_at,
a.thumbnail_key AS avatar_thumb
@@ -162,7 +165,8 @@ export default wrap(async (req, res) => {
ORDER BY ai.created_at DESC NULLS LAST
LIMIT ${limit + 1}
`
- : [];
+ : [],
+ ]);
const onchainItems = onchainRows.map((r) => {
const chain = CHAIN_BY_ID[r.chain_id];
diff --git a/api/forge.js b/api/forge.js
index 8ef582286..e61d16386 100644
--- a/api/forge.js
+++ b/api/forge.js
@@ -352,6 +352,10 @@ async function runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path }) {
// this returns status:'done' synchronously like the NVIDIA sync branch — no
// poll handle to route. Returns true once a 200 is written, false when the lane
// is unavailable so the caller can surface its own error.
+// One-shot guard so the "HuggingFace lane not configured" notice is logged once
+// per process instead of on every forge request (a static env condition).
+let _hfUnconfiguredWarned = false;
+
async function runHfImageLane({
req,
res,
@@ -376,7 +380,18 @@ async function runHfImageLane({
} catch (err) {
// HF_TOKEN absent or the Space chain is empty — the lane isn't available
// on this deployment; fall through so the caller surfaces the real error.
- console.warn(`[forge] free HuggingFace image lane unavailable: ${err?.message || err}`);
+ // A missing token is a STATIC deployment condition, not a per-request fault:
+ // logging it on every forge call floods the function logs (it was the
+ // single noisiest line). Warn once per process for the unconfigured case;
+ // keep logging genuine transient init failures each time.
+ if (err?.code === 'provider_unconfigured') {
+ if (!_hfUnconfiguredWarned) {
+ _hfUnconfiguredWarned = true;
+ console.warn(`[forge] free HuggingFace image lane disabled (not configured): ${err?.message || err}`);
+ }
+ } else {
+ console.warn(`[forge] free HuggingFace image lane unavailable: ${err?.message || err}`);
+ }
return false;
}
diff --git a/api/x402-pay.js b/api/x402-pay.js
index 2c3142f0e..f80692f10 100644
--- a/api/x402-pay.js
+++ b/api/x402-pay.js
@@ -397,7 +397,13 @@ async function buildSolanaPaymentPayload({ accept, buyer, conn, resourceUrl }) {
// resource server, and that server — not us — verifies + settles. We only build
// and sign the SPL transfer with the agent key and present it as X-PAYMENT.
-const EXTERNAL_FETCH_TIMEOUT_MS = 30_000;
+// A paid flow makes TWO sequential calls to the external resource server (the 402
+// probe, then the X-PAYMENT settle) plus on-chain blockhash + settlement work, all
+// inside the function's 60s ceiling. At the old 30s-per-fetch budget two slow
+// probes alone consumed the entire window, leaving nothing for settlement and
+// surfacing a 504 instead of a clean, retryable timeout. 20s still tolerates a
+// genuinely slow-but-alive server while leaving room for the second call + Solana.
+const EXTERNAL_FETCH_TIMEOUT_MS = 20_000;
// SSRF-guarded one-shot fetch of an untrusted URL: https-only (http in dev),
// DNS resolved + checked against the private-range blocklist, the socket pinned
diff --git a/data/changelog.json b/data/changelog.json
index 337488fac..1c30a423d 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$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-25",
+ "title": "Stability sweep: live page, dashboards, and the galaxy feed never hard-fail",
+ "summary": "A second pass on the day's production logs, this time on resilience. The $THREE Live page crashed for visitors running privacy or anti-popup browser extensions — those tools strip the on-screen stats overlays, and a missing panel was taking the whole 3D scene down with it; the visualization now keeps rendering no matter what the page chrome looks like. Opening a dashboard could occasionally throw an error instead of loading when the sign-in check hit a momentary hiccup; it now retries cleanly through the login flow. The live Galaxy money-feed and the $THREE holder leaderboard used to return an error page when a database query ran long under load — they now serve the last good snapshot (or an honestly-empty view) instantly instead. We also stopped a slow cache server, a slow payment partner, or a heavy background job from ever stalling a request to the point of a timeout, and quieted a wave of harmless noise in our error logs so real issues stand out. No action needed.",
+ "tags": [
+ "fix",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-25",
"title": "Production error sweep: tier page, image understanding, and on-chain indexing",