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.

feat: payment session sweep, pulse tick, bounties, and db/usage updates

nirholase4e70249abc5
diff --git a/api/_lib/db.js b/api/_lib/db.js
index 715e8071f..90ddc303b 100644
--- a/api/_lib/db.js
+++ b/api/_lib/db.js
@@ -143,7 +143,11 @@ export function sqlValues(rows) {
// DB-unavailable alert per hour is enough.
export function isDbUnavailableError(err) {
if (!err) return false;
- const name = err.constructor?.name ?? '';
+ // esbuild minifies class names (e.g. NeonDbError → Pt in the bundle), so
+ // err.constructor.name is unreliable in production. Use err.name instead —
+ // NeonDbError explicitly sets `this.name = 'NeonDbError'` via a class field,
+ // which survives minification. Fall back to constructor.name for dev builds.
+ const name = String(err.name || err.constructor?.name || '');
const msg = String(err.message ?? '');
if (name === 'NeonDbError' || name === 'DatabaseError') {
return (
@@ -160,6 +164,12 @@ export function isDbUnavailableError(err) {
if (name === 'FetchError' || name === 'TypeError') {
return msg.includes('ECONNREFUSED') || msg.includes('fetch failed');
}
+ // Upstash Redis auth failure — WRONGPASS means the token is wrong or rotated.
+ // Same "infra misconfigured" class as a DB auth failure: a single bad env var
+ // would otherwise produce an unhandled-500 storm on every cron tick.
+ if (name === 'UpstashError') {
+ return msg.includes('WRONGPASS') || msg.includes('invalid or missing auth token') || msg.includes('Unauthorized');
+ }
return false;
}
diff --git a/api/_lib/usage.js b/api/_lib/usage.js
index 83e3b7ae6..436b62fc2 100644
--- a/api/_lib/usage.js
+++ b/api/_lib/usage.js
@@ -138,7 +138,13 @@ export async function flushUsageBuffer({ limit = 500, deadlineMs = 45_000 } = {}
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);
+ let raw;
+ try {
+ raw = await r.lrange(BUFFER_KEY, 0, take - 1);
+ } catch (err) {
+ console.warn('[usage-flush] redis unavailable on lrange:', err?.message);
+ return { flushed, remaining: -1, errors, skipped: 'redis_unavailable' };
+ }
if (!raw || raw.length === 0) break;
const events = raw.map((item) => {
diff --git a/api/cron/payment-session-sweep.js b/api/cron/payment-session-sweep.js
index 6feb57427..3ef28f0b7 100644
--- a/api/cron/payment-session-sweep.js
+++ b/api/cron/payment-session-sweep.js
@@ -43,14 +43,24 @@ export default wrapCron(async (req, res) => {
const t0 = Date.now();
- // Find expired sessions in one query, limiting the batch
+ // PostgreSQL does not allow LIMIT directly in UPDATE. Use a CTE to select
+ // the batch first (FOR UPDATE SKIP LOCKED prevents double-processing when
+ // multiple cron invocations race), then join back to update.
const expiredRows = await sql`
+ WITH batch AS (
+ SELECT id FROM payment_sessions
+ WHERE status = 'active'
+ AND expires_at < now()
+ ORDER BY expires_at
+ LIMIT ${BATCH_LIMIT}
+ FOR UPDATE SKIP LOCKED
+ )
UPDATE payment_sessions
SET status = 'expired', updated_at = now()
- WHERE status = 'active'
- AND expires_at < now()
- RETURNING id, user_id, budget_usdc, spent_usdc
- LIMIT ${BATCH_LIMIT}
+ FROM batch
+ WHERE payment_sessions.id = batch.id
+ RETURNING payment_sessions.id, payment_sessions.user_id,
+ payment_sessions.budget_usdc, payment_sessions.spent_usdc
`;
let refunded = 0;
diff --git a/api/cron/pulse-tick.js b/api/cron/pulse-tick.js
index 898e702a5..12f29f10a 100644
--- a/api/cron/pulse-tick.js
+++ b/api/cron/pulse-tick.js
@@ -5,7 +5,7 @@
// agent pool and has those agents transact with one another on-chain, so the live
// money feed reflects real wallet activity.
-import { json, method, wrapCron } from '../_lib/http.js';
+import { json, error, method, wrapCron } from '../_lib/http.js';
import { env } from '../_lib/env.js';
import { constantTimeEquals } from '../_lib/crypto.js';
import { runCirculationTick } from '../_lib/circulation.js';
@@ -13,13 +13,13 @@ import { runCirculationTick } from '../_lib/circulation.js';
function requireCron(req, res) {
const secret = process.env.CRON_SECRET || env.CRON_SECRET;
if (!secret) {
- res.status(503).json({ error: 'not_configured', message: 'CRON_SECRET unset' });
+ 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)) {
- res.status(401).json({ error: 'unauthorized' });
+ error(res, 401, 'unauthorized', 'invalid cron secret');
return false;
}
return true;
diff --git a/api/vanity/bounties.js b/api/vanity/bounties.js
index 083b1e700..8a2d552dd 100644
--- a/api/vanity/bounties.js
+++ b/api/vanity/bounties.js
@@ -263,6 +263,7 @@ async function handleGet(req, res, url) {
const view = (url.searchParams.get('view') || 'board').toLowerCase();
+ // quote and config are pure computation — no Redis, no try-catch needed.
if (view === 'quote') {
const pattern = normalizeBountyPattern({
prefix: url.searchParams.get('prefix') || '',
@@ -290,38 +291,50 @@ async function handleGet(req, res, url) {
}, { 'cache-control': READ_CACHE });
}
- if (view === 'get') {
- const id = (url.searchParams.get('id') || '').trim();
- if (!/^[0-9a-f]{8,32}$/.test(id)) return error(res, 400, 'validation_error', 'id must be a hex bounty id');
- const bounty = await getBounty(id);
- if (!bounty) return error(res, 404, 'not_found', 'no bounty with that id');
- return json(res, 200, { bounty }, { 'cache-control': READ_CACHE });
- }
+ // All remaining views hit the Redis-backed store. A single try-catch converts
+ // an Upstash auth failure (WRONGPASS) into a 503 rather than an unhandled 500.
+ try {
+ if (view === 'get') {
+ const id = (url.searchParams.get('id') || '').trim();
+ if (!/^[0-9a-f]{8,32}$/.test(id)) return error(res, 400, 'validation_error', 'id must be a hex bounty id');
+ const bounty = await getBounty(id);
+ if (!bounty) return error(res, 404, 'not_found', 'no bounty with that id');
+ return json(res, 200, { bounty }, { 'cache-control': READ_CACHE });
+ }
- if (view === 'open') {
- const limit = Number(url.searchParams.get('limit')) || 30;
- const bounties = await listClaimable(limit);
- return json(res, 200, { bounties, count: bounties.length }, { 'cache-control': 'no-store' });
- }
+ if (view === 'open') {
+ const limit = Number(url.searchParams.get('limit')) || 30;
+ const bounties = await listClaimable(limit);
+ return json(res, 200, { bounties, count: bounties.length }, { 'cache-control': 'no-store' });
+ }
- if (view === 'stats') {
- const stats = await bountyStats();
- return json(res, 200, stats, { 'cache-control': READ_CACHE });
- }
+ if (view === 'stats') {
+ const stats = await bountyStats();
+ return json(res, 200, stats, { 'cache-control': READ_CACHE });
+ }
- if (view === 'leaderboard') {
- const limit = Number(url.searchParams.get('limit')) || 10;
- const grinders = await topGrinders(limit);
- return json(res, 200, { grinders, count: grinders.length }, { 'cache-control': READ_CACHE });
- }
+ if (view === 'leaderboard') {
+ const limit = Number(url.searchParams.get('limit')) || 10;
+ const grinders = await topGrinders(limit);
+ return json(res, 200, { grinders, count: grinders.length }, { 'cache-control': READ_CACHE });
+ }
- // Default: paginated board.
- const status = (url.searchParams.get('status') || 'open').toLowerCase();
- const sort = (url.searchParams.get('sort') || 'recency').toLowerCase();
- const limit = Number(url.searchParams.get('limit')) || 24;
- const offset = Number(url.searchParams.get('offset')) || 0;
- const result = await queryBounties({ status, sort, limit, offset });
- return json(res, 200, { ...result, status, sort }, { 'cache-control': READ_CACHE });
+ // Default: paginated board.
+ const status = (url.searchParams.get('status') || 'open').toLowerCase();
+ const sort = (url.searchParams.get('sort') || 'recency').toLowerCase();
+ const limit = Number(url.searchParams.get('limit')) || 24;
+ const offset = Number(url.searchParams.get('offset')) || 0;
+ const result = await queryBounties({ status, sort, limit, offset });
+ return json(res, 200, { ...result, status, sort }, { 'cache-control': READ_CACHE });
+ } catch (err) {
+ const isRedisAuth = err?.constructor?.name === 'UpstashError' &&
+ (err.message?.includes('WRONGPASS') || err.message?.includes('invalid or missing auth token'));
+ if (isRedisAuth) {
+ console.warn('[vanity/bounties] redis unavailable:', err.message);
+ return error(res, 503, 'store_unavailable', 'the bounty store is temporarily unavailable');
+ }
+ throw err;
+ }
}
function escrowNetworks() {
diff --git a/data/changelog.json b/data/changelog.json
index 9e26f31db..863da1fc8 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,12 @@
{
"$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-27",
+ "title": "Production stability fixes — payment sessions, Redis error handling, infra resilience",
+ "summary": "Fixed a SQL syntax error that blocked payment session expiry and refunds (PostgreSQL does not allow LIMIT directly in UPDATE — now uses a CTE with FOR UPDATE SKIP LOCKED). Fixed esbuild class-name minification breaking NeonDB error detection in production — infrastructure errors (wrong DB credentials, Redis auth) now correctly return 503 and suppress alert storms instead of crashing every endpoint with 500. Added graceful Redis-unavailable handling to the usage flush buffer and the bounty board API. Fixed Express-style response methods in pulse-tick cron.",
+ "tags": ["fix", "infra"]
+ },
{
"date": "2026-06-27",
"title": "60 live x402 payments per minute",