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.

x402 idempotency + payment-identifier hardening, pumpfun handler + agent boot fixes

nirholasc75fd50075a7
diff --git a/api/_lib/x402/idempotency-cache.js b/api/_lib/x402/idempotency-cache.js
index 268f769de..841b0ab80 100644
--- a/api/_lib/x402/idempotency-cache.js
+++ b/api/_lib/x402/idempotency-cache.js
@@ -128,6 +128,58 @@ export async function set(route, paymentId, entry, ttlSec) {
}
}
+// Sentinel stored while a paid request is mid-flight (verify→handler→settle).
+// A concurrent request carrying the same payment that observes this marker knows
+// the original is still running and must not re-execute the paid work.
+export const INFLIGHT = { __x402_inflight__: true };
+
+// Atomically claim the slot for `key`: SET NX so exactly one concurrent request
+// wins. Returns true for the winner, false if a value (in-flight marker OR a
+// stored response) already exists. The TTL is a crash backstop — the winner is
+// expected to overwrite (set) on success or release() on failure well before it.
+export async function reserve(route, paymentId, ttlSec) {
+ const key = fullKey(route, paymentId);
+ const ttl = ttlSec > 0 ? ttlSec : 120;
+ if (!redis) {
+ // Single-process fallback: the JS event loop makes get+set atomic here.
+ if (memoryGet(key) != null) return false;
+ memorySet(key, INFLIGHT, ttl);
+ return true;
+ }
+ try {
+ const ok = await redis.set(key, JSON.stringify(INFLIGHT), { nx: true, ex: ttl });
+ // Upstash returns 'OK' on success, null when the key already existed.
+ return ok === 'OK' || ok === true;
+ } catch (err) {
+ // On a Redis error, fail OPEN (allow the request) rather than wedging a
+ // legitimate payment — the always-on proof-hash dedup still bounds replay.
+ console.error('[idempotency-cache] reserve failed:', err?.message || err);
+ return true;
+ }
+}
+
+// Release a slot claimed by reserve() when the request failed before storing a
+// real response (verify/handler/settle error). Only ever called on failure paths
+// where no real entry was written, so an unconditional delete is safe and keeps a
+// transient failure from locking the payer out of retrying.
+export async function release(route, paymentId) {
+ const key = fullKey(route, paymentId);
+ if (!redis) {
+ memoryStore.delete(key);
+ return;
+ }
+ try {
+ await redis.del(key);
+ } catch (err) {
+ console.error('[idempotency-cache] release failed:', err?.message || err);
+ }
+}
+
+// True when a cached entry is the in-flight marker rather than a real response.
+export function isInflight(entry) {
+ return !!(entry && entry.__x402_inflight__ === true);
+}
+
// Test-only hook to drop the in-memory store between tests.
export function _resetMemoryStore() {
memoryStore.clear();
diff --git a/api/_lib/x402/payment-identifier-server.js b/api/_lib/x402/payment-identifier-server.js
index 2254b0c9b..59192960f 100644
--- a/api/_lib/x402/payment-identifier-server.js
+++ b/api/_lib/x402/payment-identifier-server.js
@@ -103,6 +103,10 @@ export async function checkCache({ route, paymentId, payloadHash, paymentHash })
if (!paymentId) return { kind: 'miss' };
const entry = await cache.get(route, paymentId);
if (!entry) return { kind: 'miss' };
+ // A concurrent request with the same payment is still executing the paid work.
+ // Signal the caller to back off rather than re-run it (closes the verify→settle
+ // double-execution window).
+ if (cache.isInflight(entry)) return { kind: 'inflight' };
// Payment-proof binding: a stored entry written with a paymentHash only
// replays to a caller presenting the same signed proof. A mismatch (or a
// caller that omits the proof against a proof-bound entry) is a conflict —
@@ -162,6 +166,21 @@ export async function storeResponse({
);
}
+// Atomically claim the in-flight slot for a payment before doing the paid work.
+// Returns true for the single winner; false when another request already holds
+// the slot or a response is already cached. Pair with releaseSlot() on any
+// failure path so a transient error doesn't lock the payer out of retrying.
+export async function reserveSlot({ route, paymentId, ttlSeconds }) {
+ if (!paymentId) return true;
+ const ttl = Number.isFinite(ttlSeconds) && ttlSeconds > 0 ? ttlSeconds : envTtl();
+ return cache.reserve(route, paymentId, ttl);
+}
+
+export async function releaseSlot({ route, paymentId }) {
+ if (!paymentId) return;
+ await cache.release(route, paymentId);
+}
+
// Flush a cached entry back onto the wire. Mirrors the headers the live path
// would have set (cache-control: no-store, x-payment-response, etc.) and
// tags the response with `x-x402-idempotent: replay` so the caller can tell
diff --git a/api/agents/[id]/skills-pricing.js b/api/agents/[id]/skills-pricing.js
index 30a2b8ca3..b2fbc2199 100644
--- a/api/agents/[id]/skills-pricing.js
+++ b/api/agents/[id]/skills-pricing.js
@@ -1,5 +1,5 @@
import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
+import { cors, json, method, readJson, wrap, error, respondError } from '../../_lib/http.js';
import { requireCsrf } from '../../_lib/csrf.js';
import { MonetizationService } from '../../_lib/services/MonetizationService.js';
import { z } from 'zod';
@@ -37,7 +37,8 @@ export default wrap(async (req, res) => {
try {
await service.assertOwnership(id);
} catch (e) {
- return error(res, e.status || 500, e.code || 'error', e.message);
+ console.error('[agents/skills-pricing] ownership check failed', e?.message);
+ return respondError(res, e.status || 500, e.code || 'error', e);
}
if (req.method === 'GET') return handleGet(req, res, service, id);
diff --git a/api/agents/pumpfun/[action].js b/api/agents/pumpfun/[action].js
index 8e3ca17fc..f4033b8b5 100644
--- a/api/agents/pumpfun/[action].js
+++ b/api/agents/pumpfun/[action].js
@@ -240,12 +240,7 @@ async function handleBuy(req, res, id) {
}
} catch (err) {
console.error('[pumpfun/buy] build failed', err);
- return error(
- res,
- err.status || 422,
- err.code || 'build_failed',
- err.message || 'could not build buy ix',
- );
+ return respondError(res, err.status || 422, err.code || 'build_failed', err);
}
// Reserve against the daily SOL cap for SOL spends only — atomically, BEFORE
@@ -428,7 +423,8 @@ async function handleLaunch(req, res, id) {
vanityIterations = ground.iterations;
vanityDurationMs = ground.durationMs;
} catch (err) {
- return error(res, err.status || 500, err.code || 'internal', err.message);
+ console.error('[pumpfun/launch] vanity grind failed', err?.message);
+ return respondError(res, err.status || 500, err.code || 'internal', err);
}
}
const solLamports = new BN(Math.floor((body.solAmount || 0) * 1e9));
@@ -1117,12 +1113,7 @@ async function handleSell(req, res, id) {
instructions = ixs;
} catch (err) {
console.error('[pumpfun/sell] build failed', err);
- return error(
- res,
- err.status || 422,
- err.code || 'build_failed',
- err.message || 'could not build sell ix',
- );
+ return respondError(res, err.status || 422, err.code || 'build_failed', err);
}
const tx = new Transaction().add(...instructions);
diff --git a/api/pump-fun-mcp.js b/api/pump-fun-mcp.js
index bffe937b1..ee5fed7b9 100644
--- a/api/pump-fun-mcp.js
+++ b/api/pump-fun-mcp.js
@@ -1654,9 +1654,33 @@ export default wrap(async (req, res) => {
);
}
+ // A single X-PAYMENT settles exactly once for the whole request, so a batch
+ // carrying more than one gated (paid) tool would run them all for one payment
+ // (pay-once-run-many). Reject that up front. Bearer-authed batches are exempt —
+ // they don't settle a payment and are bounded by the per-principal limiter.
+ if (req.headers['x-payment'] && !extractBearer(req)) {
+ const gatedCount = messages.reduce((n, m) => {
+ if (m?.method !== 'tools/call') return n;
+ const nm = resolveToolName(m?.params?.name);
+ return n + (typeof nm === 'string' && AUTH_REQUIRED_TOOLS.has(nm) ? 1 : 0);
+ }, 0);
+ if (gatedCount > 1) {
+ return json(
+ res,
+ 400,
+ rpcEnvelope(null, null, {
+ code: -32600,
+ message: 'one X-PAYMENT settles a single gated call — send at most one paid tool per request',
+ }),
+ { 'mcp-protocol-version': PROTOCOL_VERSION },
+ );
+ }
+ }
+
// Per-request dispatch context. Gate credentials resolve at most once.
let gateAuthPromise = null;
const ctx = {
+ req,
res,
batch: isBatch,
x402Ctx: null,
diff --git a/public/agents/boot.js b/public/agents/boot.js
index 1cb124d74..313c0f89e 100644
--- a/public/agents/boot.js
+++ b/public/agents/boot.js
@@ -30,6 +30,12 @@ const filterChips = document.querySelectorAll('.filter-chip');
const sortSelect = document.getElementById('sort');
const agentsContainer = document.getElementById('agents');
const emptyState = document.getElementById('empty-state');
+// Default empty-state copy, captured before any error path rewrites it so the
+// "no results" message can be restored after a failed load is retried.
+const emptyDefaults = {
+ title: emptyState?.querySelector('h2')?.textContent || 'No agents found',
+ body: emptyState?.querySelector('p')?.textContent || 'Try a different filter or search.',
+};
const loadingEl = document.getElementById('loading');
const paginationEl = document.getElementById('pagination');
const pageInfo = document.getElementById('page-info');
@@ -73,7 +79,10 @@ async function render() {
page: currentPage,
});
+ hideRetry();
if (result.agents.length === 0) {
+ emptyState.querySelector('h2').textContent = emptyDefaults.title;
+ emptyState.querySelector('p').textContent = emptyDefaults.body;
emptyState.style.display = 'block';
loadingEl.style.display = 'none';
return;
@@ -98,9 +107,33 @@ async function render() {
emptyState.style.display = 'block';
emptyState.querySelector('h2').textContent = 'Error loading agents';
emptyState.querySelector('p').textContent = err.message || 'Please try again later.';
+ showRetry();
}
}
+// Actionable error recovery: a Retry button inside the empty-state that re-runs
+// the load. Created once and reused; hidden on any successful render so it never
+// lingers over real results.
+function showRetry() {
+ let btn = document.getElementById('empty-retry');
+ if (!btn) {
+ btn = document.createElement('button');
+ btn.id = 'empty-retry';
+ btn.type = 'button';
+ btn.className = 'btn-primary';
+ btn.textContent = 'Retry';
+ btn.style.marginTop = '16px';
+ btn.addEventListener('click', () => { render(); });
+ emptyState.appendChild(btn);
+ }
+ btn.style.display = 'inline-flex';
+}
+
+function hideRetry() {
+ const btn = document.getElementById('empty-retry');
+ if (btn) btn.style.display = 'none';
+}
+
/**
* Handle card clicks.
*/
diff --git a/src/collection.js b/src/collection.js
index 3b583fbce..b9945b9d2 100644
--- a/src/collection.js
+++ b/src/collection.js
@@ -127,6 +127,26 @@ function emptyState(panel) {
</div>`;
}
+// Render a retryable load error into the shared error element and clear the
+// loading skeletons so they never linger. Wires a Retry button to re-run load().
+function renderLoadError(errorEl, skillsGrid, subsGrid, detail) {
+ errorEl.innerHTML = '';
+ const msg = document.createElement('span');
+ msg.textContent = detail
+ ? `Couldn't load your collection — ${detail}.`
+ : 'Failed to load your collection. Please try again.';
+ const retry = document.createElement('button');
+ retry.type = 'button';
+ retry.className = 'col-retry-btn';
+ retry.textContent = 'Retry';
+ retry.style.marginLeft = '10px';
+ retry.addEventListener('click', () => { load(); });
+ errorEl.append(msg, retry);
+ errorEl.hidden = false;
+ skillsGrid.innerHTML = '';
+ subsGrid.innerHTML = '';
+}
+
async function load() {
const authWall = document.getElementById('col-auth-wall');
const errorEl = document.getElementById('col-error');
@@ -136,13 +156,23 @@ async function load() {
const subsGrid = document.getElementById('subs-grid');
// Show skeleton while loading
+ errorEl.hidden = true;
skillsGrid.innerHTML = skeletonGrid(6);
subsGrid.innerHTML = skeletonGrid(3);
- const [skillsRes, subsRes] = await Promise.all([
- fetch('/api/users/me/purchased-skills', { credentials: 'include' }),
- fetch('/api/subscriptions', { credentials: 'include' }),
- ]);
+ let skillsRes, subsRes;
+ try {
+ [skillsRes, subsRes] = await Promise.all([
+ fetch('/api/users/me/purchased-skills', { credentials: 'include' }),
+ fetch('/api/subscriptions', { credentials: 'include' }),
+ ]);
+ } catch (err) {
+ // Network-level failure (offline, DNS, aborted): without this the awaited
+ // Promise.all rejects and the skeletons render forever. Surface a retryable
+ // error instead.
+ renderLoadError(errorEl, skillsGrid, subsGrid, err?.message);
+ return;
+ }
if (skillsRes.status === 401 || subsRes.status === 401) {
authWall.hidden = false;
@@ -152,16 +182,18 @@ async function load() {
}
if (!skillsRes.ok || !subsRes.ok) {
- const msg = 'Failed to load collection. Please refresh and try again.';
- errorEl.textContent = msg;
- errorEl.hidden = false;
- skillsGrid.innerHTML = '';
- subsGrid.innerHTML = '';
+ renderLoadError(errorEl, skillsGrid, subsGrid);
return;
}
- const { data: skillsData } = await skillsRes.json();
- const { data: subsData } = await subsRes.json();
+ let skillsData, subsData;
+ try {
+ ({ data: skillsData } = await skillsRes.json());
+ ({ data: subsData } = await subsRes.json());
+ } catch (err) {
+ renderLoadError(errorEl, skillsGrid, subsGrid, err?.message);
+ return;
+ }
const purchases = skillsData?.purchases ?? [];
const subs = subsData ?? [];