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
fix(recurring): keep a schedule alive through our own outages and stop sub-millisecond claims from stalling it
nirholas7e7aa20f3dab
diff --git a/api/_lib/recurring.js b/api/_lib/recurring.jsindex ad919b183..aa0bd3717 100644--- a/api/_lib/recurring.js+++ b/api/_lib/recurring.js@@ -94,7 +94,8 @@ const REASONS = {delegation_gone: 'The signed permission behind this schedule is gone. Grant a new one to restart it.',delegation_not_found: 'The signed permission behind this schedule no longer exists. Grant a new one to restart it.',delegation_revoked: 'The signed permission was revoked. Grant a new one to restart this schedule.',- feature_disabled: 'On-chain relaying is switched off on this deployment. Nothing was charged.',+ feature_disabled:+ 'On-chain relaying is switched off on this deployment, so nothing was charged. The schedule stays active and keeps trying.',insufficient_balance: 'Your wallet did not hold enough USDC for this charge. Top it up and the next run will retry.',internal_error: 'The charge failed inside the relayer. The next run will retry.',no_tx_hash: 'The relayer accepted the charge but returned no transaction. The next run will retry.',@@ -104,7 +105,8 @@ const REASONS = {scope_exceeded: 'This charge is larger than the permission you signed allows for the period. Grant a wider permission to restart it.',target_not_allowed: 'The permission you signed does not cover this payment target.',timeout: 'The charge timed out, so we cannot tell whether it landed. The schedule is paused so it can never double-charge; check the transaction before resuming.',- unauthorized: 'The relayer rejected our credentials. Nothing was charged.',+ unauthorized:+ 'The relayer rejected our own credentials, so nothing was charged. The schedule stays active while we fix it.',unsupported_chain: 'This chain is no longer supported for recurring charges.',validation_error: 'The charge was rejected as malformed. Nothing was charged.',};@@ -190,19 +192,24 @@ export function classifyChargeFailure({ code, message } = {}) {/*** Decide what a classified failure does to the schedule row.*- * @param {{ outcome: string, consecutiveFailures: number }} opts- * consecutiveFailures is the count BEFORE this failure.+ * @param {{ outcome: string, consecutiveFailures: number, platform?: boolean }} opts+ * consecutiveFailures is the count BEFORE this failure; `platform` marks an+ * outage on our side rather than a problem with the schedule.* @returns {{ pause: boolean, retry: boolean, consecutiveFailures: number }}* `retry` means release the period claim so the next tick picks the row up* again; `pause` means stop scheduling it until the owner resumes.*/-export function applyChargeFailure({ outcome, consecutiveFailures = 0 }) {+export function applyChargeFailure({ outcome, consecutiveFailures = 0, platform = false }) {const current = Number(consecutiveFailures) || 0;// A deliberate skip is not a failure: the counter must not creep toward a// pause across a volatile week.if (outcome === OUTCOME.SKIPPED) {return { pause: false, retry: false, consecutiveFailures: current };}+ // A platform outage retries indefinitely and never counts against the owner.+ if (platform) {+ return { pause: false, retry: true, consecutiveFailures: current };+ }const next = current + 1;if (outcome === OUTCOME.FATAL) return { pause: true, retry: false, consecutiveFailures: next };if (outcome === OUTCOME.AMBIGUOUS) {diff --git a/api/cron/[name].js b/api/cron/[name].jsindex 7a76786b8..7526ebeac 100644--- a/api/cron/[name].js+++ b/api/cron/[name].js@@ -330,6 +330,11 @@ function rank(cursor) {return Math.min(ageMin, 1);}+// Concurrent eth_getBlockByNumber calls while stamping a range's event blocks.+// See the loop in erc8004CrawlChain for why this is bounded rather than a single+// Promise.all over every block in the window.+const ERC8004_BLOCKTIME_CONCURRENCY = 8;+// Ceiling for the adaptive window. Public RPCs commonly cap eth_getLogs at// 2,000 to 10,000 blocks; the crawl walks up toward this and backs off the// moment a provider says no, so no chain needs its limit hardcoded here.@@ -455,20 +460,29 @@ async function erc8004CrawlChain(chain) {const allLogs = [...logs, ...reputationLogs];if (allLogs.length > 0) {const uniqueBlockHexes = [...new Set(allLogs.map((l) => l.blockNumber))];- await Promise.all(- uniqueBlockHexes.map(async (bn) => {- try {- const block = await erc8004RpcCall(- chain.rpcUrls ?? chain.rpcUrl,- 'eth_getBlockByNumber',- [bn, false],- );- blockTimes[bn] = block ? Number.parseInt(block.timestamp, 16) : null;- } catch {- // registered_at will be null for this block- }- }),- );+ // Bounded fan-out, not one request per block all at once. The window this+ // crawl asks for grows while a chain is behind, so a catching-up chain can+ // return several hundred distinct event blocks in a single tick, and firing+ // that many concurrent eth_getBlockByNumber calls is the reliable way to+ // get rate-limited off every lane at once. A log whose timestamp cannot be+ // read is still applied to the agent row; it just does not enter the event+ // index, which refuses to invent a time.+ for (let i = 0; i < uniqueBlockHexes.length; i += ERC8004_BLOCKTIME_CONCURRENCY) {+ await Promise.all(+ uniqueBlockHexes.slice(i, i + ERC8004_BLOCKTIME_CONCURRENCY).map(async (bn) => {+ try {+ const block = await erc8004RpcCall(+ chain.rpcUrls ?? chain.rpcUrl,+ 'eth_getBlockByNumber',+ [bn, false],+ );+ blockTimes[bn] = block ? Number.parseInt(block.timestamp, 16) : null;+ } catch {+ // registered_at will be null for this block+ }+ }),+ );+ }}let inserted = 0;@@ -2809,12 +2823,13 @@ async function handleRunDca(req, res) {// One classifier decides what a failure means, shared with the// subscription cron and with the API that renders it to the owner// (api/_lib/recurring.js).- const { code, outcome, reason } = classifyChargeFailure({+ const { code, outcome, reason, platform } = classifyChargeFailure({code: err.code,message: err.message,});const applied = applyChargeFailure({outcome,+ platform,consecutiveFailures: Number(strategy.consecutive_failures ?? 0),});@@ -3205,16 +3220,25 @@ async function handleRunSubscriptions(req, res) {// Atomic claim: mark this period as being processed by writing// last_charge_at = NOW(). Matches only if:- // - next_charge_at hasn't moved (no racing writer),- // - status is still active,+ // - the schedule is still active and still due,// - last_charge_at is NULL OR < next_charge_at (not already claimed for this period).- // If 0 rows returned, another worker claimed this period — skip.+ // If 0 rows returned, another worker claimed this period, so skip.+ //+ // Dueness is re-tested server-side (`next_charge_at <= NOW()`) rather+ // than by comparing against the timestamp we selected. Postgres stores+ // timestamptz to the microsecond and the driver hands it back as a JS+ // Date, which truncates to the millisecond: an equality check against+ // the round-tripped value silently never matches for any row whose+ // next_charge_at carries sub-millisecond digits, and that schedule then+ // never charges again. The last_charge_at guard is what actually makes+ // the claim idempotent per period; the equality added nothing but that+ // failure mode.const claim = await sql`UPDATE agent_subscriptionsSET last_charge_at = NOW()WHERE id = ${row.id}AND status = 'active'- AND next_charge_at = ${row.next_charge_at}+ AND next_charge_at <= NOW()AND (last_charge_at IS NULL OR last_charge_at < next_charge_at)RETURNING id`;@@ -3410,9 +3434,10 @@ async function recordSubscriptionCharge(row, ctx, { status, outcome, code, error* reached the chain; a timeout is classified ambiguous and never retried.*/async function subApplyFailure(row, ctx, failure) {- const { code, outcome, reason } = classifyChargeFailure(failure);+ const { code, outcome, reason, platform } = classifyChargeFailure(failure);const applied = applyChargeFailure({outcome,+ platform,consecutiveFailures: Number(row.consecutive_failures ?? 0),});diff --git a/api/dca-strategies.js b/api/dca-strategies.jsindex 11c6bf10e..341777eaf 100644--- a/api/dca-strategies.js+++ b/api/dca-strategies.js@@ -305,7 +305,7 @@ export default wrap(async (req, res) => {LIMIT 1) AS last_execution,(- SELECT COUNT(*) FROM dca_executions e+ SELECT COUNT(*)::int FROM dca_executions eWHERE e.strategy_id = s.id AND e.status = 'success') AS executions_totalFROM dca_strategies s