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(payments): give recurring schedules a charge ledger and a way back from paused
nirholas9e7eae703c64
diff --git a/api/_lib/migrations/20260813191500_recurring_payment_lifecycle.sql b/api/_lib/migrations/20260813191500_recurring_payment_lifecycle.sqlnew file mode 100644index 000000000..0ce2f8340--- /dev/null+++ b/api/_lib/migrations/20260813191500_recurring_payment_lifecycle.sql@@ -0,0 +1,70 @@+-- Migration: recurring-payment lifecycle (pause/resume + a real charge ledger).+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260813191500_recurring_payment_lifecycle.sql+-- Idempotent.+--+-- Before this migration, `agent_subscriptions` recorded only `last_error`: one+-- overwritten string per schedule. A creator could not see what a schedule had+-- ever paid, and any failure (including a transient RPC blip) pinned the row to+-- status='paused' with no way back, because no endpoint could set it to+-- 'active' again. DCA schedules had the same one-way door plus a ledger+-- (`dca_executions`) that nothing surfaced.+--+-- This adds:+-- * subscription_charges — one row per charge attempt, the mirror of+-- dca_executions, so incoming revenue is queryable and every failure is+-- recorded with the classification the cron acted on.+-- * consecutive_failures / last_error_code / paused_at / resumed_at on both+-- schedule tables, so a retryable failure can be retried a bounded number+-- of times before the schedule is paused, and a resume is auditable.++begin;++-- ── subscription_charges — per-tick charge attempt log ──────────────────────+create table if not exists subscription_charges (+ id uuid primary key default gen_random_uuid(),+ subscription_id uuid not null references agent_subscriptions(id) on delete cascade,+ -- Denormalized so the creator-side incoming view can aggregate earnings+ -- without joining back through a subscription that may since be canceled.+ agent_id uuid not null references agent_identities(id) on delete cascade,+ payer_user_id uuid references users(id) on delete set null,+ chain_id integer,+ amount text not null,+ tx_hash text,+ status text not null default 'pending',+ -- The machine code the cron classified this outcome as. `outcome` is the+ -- classification bucket that drove what happened to the schedule.+ code text,+ outcome text,+ error text,+ period_start_at timestamptz,+ charged_at timestamptz not null default now(),++ constraint subscription_charges_status_check+ check (status in ('success', 'failed', 'aborted', 'unknown')),+ constraint subscription_charges_outcome_check+ check (outcome is null or outcome in ('charged', 'fatal', 'retryable', 'ambiguous'))+);++create index if not exists idx_subscription_charges_subscription+ on subscription_charges(subscription_id, charged_at desc);+create index if not exists idx_subscription_charges_agent+ on subscription_charges(agent_id, charged_at desc);+create unique index if not exists uq_subscription_charges_period+ on subscription_charges(subscription_id, period_start_at)+ where status = 'success' and period_start_at is not null;++-- ── agent_subscriptions — lifecycle columns ─────────────────────────────────+alter table agent_subscriptions add column if not exists consecutive_failures integer not null default 0;+alter table agent_subscriptions add column if not exists last_error_code text;+alter table agent_subscriptions add column if not exists last_tx_hash text;+alter table agent_subscriptions add column if not exists paused_at timestamptz;+alter table agent_subscriptions add column if not exists resumed_at timestamptz;++-- ── dca_strategies — lifecycle columns ──────────────────────────────────────+alter table dca_strategies add column if not exists consecutive_failures integer not null default 0;+alter table dca_strategies add column if not exists last_error text;+alter table dca_strategies add column if not exists last_error_code text;+alter table dca_strategies add column if not exists paused_at timestamptz;+alter table dca_strategies add column if not exists resumed_at timestamptz;++commit;diff --git a/api/_lib/recurring.js b/api/_lib/recurring.jsnew file mode 100644index 000000000..4fea510e6--- /dev/null+++ b/api/_lib/recurring.js@@ -0,0 +1,272 @@+/**+ * Shared lifecycle rules for recurring on-chain payments.+ *+ * Two schedule kinds ride the same rails:+ * - `agent_subscriptions` — a fixed USDC transfer per period, charged by the+ * run-subscriptions cron through /api/permissions/redeem.+ * - `dca_strategies` — a fixed USDC swap per period, executed by the run-dca+ * cron through the same relayer.+ *+ * Both used to treat every failure identically: pause the schedule and write a+ * raw error string. A one-off RPC blip therefore killed a schedule as+ * permanently as a revoked delegation, and nothing could set it back to+ * 'active'. This module is the single place that decides what a failure means,+ * so the crons, the API and the UI all agree on it.+ *+ * The three outcomes:+ * fatal the owner has to change something (revoked or expired+ * delegation, a scope that no longer covers the charge). Retrying+ * is guaranteed to fail, so the schedule pauses immediately.+ * retryable nothing about the schedule is wrong; the attempt did not land+ * (RPC down, relayer unreachable, wallet short of funds). The+ * schedule stays active and the next tick tries again, up to+ * MAX_CONSECUTIVE_FAILURES before it pauses.+ * ambiguous the request timed out, so the transfer may or may not be+ * on-chain. Never retried: the period is consumed and the schedule+ * pauses for the owner to look at, because a retry here is the one+ * failure mode that can double-charge.+ * skipped the schedule deliberately declined to act this period (a DCA+ * quote that moved too far between reads). Nothing is wrong, so+ * the period is simply given up and the next one runs on time.+ */++/** Consecutive retryable failures a schedule survives before it is paused. */+export const MAX_CONSECUTIVE_FAILURES = 3;++/** Charge attempt outcomes, mirrored by subscription_charges.outcome. */+export const OUTCOME = {+ CHARGED: 'charged',+ FATAL: 'fatal',+ RETRYABLE: 'retryable',+ AMBIGUOUS: 'ambiguous',+ SKIPPED: 'skipped',+};++// Codes that mean the schedule itself is no longer valid. Sourced from+// api/permissions/[action].js (the redeem handler) plus the cron's own guards.+const FATAL_CODES = new Set([+ 'chain_not_supported',+ 'delegation_expired',+ 'delegation_gone',+ 'delegation_not_found',+ 'delegation_revoked',+ 'feature_disabled',+ 'scope_exceeded',+ 'target_not_allowed',+ 'unauthorized',+ 'unsupported_chain',+ 'validation_error',+]);++// Codes that mean the attempt never landed and the next tick can try again.+const RETRYABLE_CODES = new Set([+ 'db_error',+ 'fetch_error',+ 'insufficient_balance',+ 'internal_error',+ 'no_tx_hash',+ 'relayer_error',+ 'rpc_error',+]);++// A reverted ERC-20 transfer surfaces through the relayer as a generic+// rpc_error. The wallet being short of USDC is the single most common cause and+// the only one the owner can fix by topping up, so it gets its own code rather+// than hiding inside "on-chain call failed".+const INSUFFICIENT_BALANCE_PATTERN =+ /insufficient (?:funds|balance|allowance)|transfer amount exceeds balance|ERC20InsufficientBalance|exceeds balance/i;++// What the owner should do about each code, in plain language. Rendered+// verbatim in the recurring-payments UI, so it never shows a raw revert string.+const REASONS = {+ chain_not_supported: 'This chain is no longer supported for recurring charges.',+ delegation_expired: 'The signed permission behind this schedule expired. Grant a new one to restart it.',+ 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.',+ 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.',+ quote_divergence: 'The swap price moved too far between quotes, so the swap was abandoned rather than filled at a bad rate.',+ relayer_error: 'The relayer rejected the charge. The next run will retry.',+ rpc_error: 'The network could not be reached. The next run will retry.',+ 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.',+ unsupported_chain: 'This chain is no longer supported for recurring charges.',+ validation_error: 'The charge was rejected as malformed. Nothing was charged.',+};++/**+ * Turn a raw relayer/skill failure into the code, outcome and owner-facing+ * reason the rest of the product uses.+ *+ * @param {{ code?: string|null, message?: string|null }} failure+ * @returns {{ code: string, outcome: string, reason: string }}+ */+export function classifyChargeFailure({ code, message } = {}) {+ const raw = String(code || '').trim();+ const text = String(message || '');++ if (raw === 'timeout' || /^timeout\b/i.test(text)) {+ return { code: 'timeout', outcome: OUTCOME.AMBIGUOUS, reason: REASONS.timeout };+ }++ // A quote that moved between reads is the market, not a broken schedule.+ // Give up this period only; the next one runs on time and the failure+ // counter is untouched.+ if (raw === 'quote_divergence') {+ return {+ code: 'quote_divergence',+ outcome: OUTCOME.SKIPPED,+ reason: REASONS.quote_divergence,+ };+ }++ // An HTTP status the skill could not name: 4xx is ours to fix, 5xx is theirs+ // and worth another tick.+ const httpMatch = /^http_(\d{3})$/.exec(raw);+ if (httpMatch) {+ const status = Number(httpMatch[1]);+ if (status >= 500) {+ return {+ code: 'relayer_error',+ outcome: OUTCOME.RETRYABLE,+ reason: REASONS.relayer_error,+ };+ }+ return {+ code: 'validation_error',+ outcome: OUTCOME.FATAL,+ reason: REASONS.validation_error,+ };+ }++ if (INSUFFICIENT_BALANCE_PATTERN.test(text)) {+ return {+ code: 'insufficient_balance',+ outcome: OUTCOME.RETRYABLE,+ reason: REASONS.insufficient_balance,+ };+ }++ if (FATAL_CODES.has(raw)) {+ return { code: raw, outcome: OUTCOME.FATAL, reason: REASONS[raw] };+ }+ if (RETRYABLE_CODES.has(raw)) {+ return { code: raw, outcome: OUTCOME.RETRYABLE, reason: REASONS[raw] };+ }++ // An unrecognised code is treated as retryable on purpose: the failure+ // counter bounds it to MAX_CONSECUTIVE_FAILURES attempts, so an unknown+ // transient recovers on its own while an unknown permanent still stops.+ return {+ code: raw || 'unknown',+ outcome: OUTCOME.RETRYABLE,+ reason: text ? `The charge failed: ${text}` : 'The charge failed. The next run will retry.',+ };+}++/**+ * Decide what a classified failure does to the schedule row.+ *+ * @param {{ outcome: string, consecutiveFailures: number }} opts+ * consecutiveFailures is the count BEFORE this failure.+ * @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 }) {+ const next = Number(consecutiveFailures) + 1;+ if (outcome === OUTCOME.FATAL) return { pause: true, retry: false, consecutiveFailures: next };+ if (outcome === OUTCOME.AMBIGUOUS) {+ return { pause: true, retry: false, consecutiveFailures: next };+ }+ const exhausted = next >= MAX_CONSECUTIVE_FAILURES;+ return { pause: exhausted, retry: !exhausted, consecutiveFailures: next };+}++/** The charge-row status that goes with an outcome. */+export function chargeStatusFor(outcome) {+ if (outcome === OUTCOME.CHARGED) return 'success';+ if (outcome === OUTCOME.FATAL) return 'aborted';+ if (outcome === OUTCOME.AMBIGUOUS) return 'unknown';+ return 'failed';+}++// ── Schedule state machine ──────────────────────────────────────────────────++/** Statuses an owner is allowed to move a schedule between. */+const TRANSITIONS = {+ pause: { from: ['active'], to: 'paused' },+ resume: { from: ['paused'], to: 'active' },+};++/**+ * Validate an owner-initiated pause/resume against the row's current status.+ *+ * Cancel is deliberately not here: it is terminal and each endpoint owns its+ * own column names for it (`canceled_at` vs `cancelled_at`).+ *+ * @param {'pause'|'resume'} action+ * @param {string} currentStatus+ * @returns {{ ok: true, status: string } | { ok: false, code: string, message: string }}+ */+export function planStatusChange(action, currentStatus) {+ const rule = TRANSITIONS[action];+ if (!rule) {+ return { ok: false, code: 'validation_error', message: `unknown action '${action}'` };+ }+ if (currentStatus === rule.to) {+ return {+ ok: false,+ code: 'conflict',+ message: `schedule is already ${rule.to}`,+ };+ }+ if (!rule.from.includes(currentStatus)) {+ return {+ ok: false,+ code: 'conflict',+ message: `cannot ${action} a schedule that is ${currentStatus}`,+ };+ }+ return { ok: true, status: rule.to };+}++// ── Formatting shared by the API responses and the page ─────────────────────++/** Human label for a period length in seconds. */+export function describePeriod(seconds) {+ const s = Number(seconds);+ if (!Number.isFinite(s) || s <= 0) return 'unknown';+ if (s === 86400) return 'daily';+ if (s === 604800) return 'weekly';+ if (s === 2592000) return 'monthly';+ if (s % 604800 === 0) return `every ${s / 604800} weeks`;+ if (s % 86400 === 0) return `every ${s / 86400} days`;+ if (s % 3600 === 0) return `every ${s / 3600} hours`;+ return `every ${Math.round(s / 60)} minutes`;+}++/**+ * Render a base-unit integer string as a decimal amount.+ * USDC is 6 decimals on every chain these schedules run on.+ */+export function formatUnits(baseUnits, decimals = 6) {+ const raw = String(baseUnits ?? '0');+ if (!/^\d+$/.test(raw)) return '0';+ const padded = raw.padStart(decimals + 1, '0');+ const whole = padded.slice(0, padded.length - decimals);+ const frac = padded.slice(padded.length - decimals).replace(/0+$/, '');+ return frac ? `${whole}.${frac}` : whole;+}++/** Sum an array of base-unit integer strings without losing precision. */+export function sumUnits(values) {+ return values+ .reduce((acc, v) => acc + (/^\d+$/.test(String(v ?? '')) ? BigInt(v) : 0n), 0n)+ .toString();+}diff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex 0066e3b85..1d3ea96cf 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -1164,6 +1164,49 @@ create index if not exists idx_subscriptions_due on agent_subscriptions(next_chacreate index if not exists idx_subscriptions_user on agent_subscriptions(user_id);create index if not exists idx_subscriptions_agent on agent_subscriptions(agent_id);+-- Lifecycle columns (migration 20260813191500_recurring_payment_lifecycle.sql).+-- A retryable failure bumps consecutive_failures and leaves the schedule active+-- so the next tick retries; the cron pauses it once the bound is hit. paused_at+-- / resumed_at make an owner's pause and resume auditable.+alter table agent_subscriptions add column if not exists consecutive_failures integer not null default 0;+alter table agent_subscriptions add column if not exists last_error_code text;+alter table agent_subscriptions add column if not exists last_tx_hash text;+alter table agent_subscriptions add column if not exists paused_at timestamptz;+alter table agent_subscriptions add column if not exists resumed_at timestamptz;++-- ── subscription_charges — per-tick charge attempt log ──────────────────────+-- The subscription mirror of dca_executions: one row per attempt, so a creator+-- can see what a schedule actually paid and every failure keeps the code the+-- cron classified it under.+create table if not exists subscription_charges (+ id uuid primary key default gen_random_uuid(),+ subscription_id uuid not null references agent_subscriptions(id) on delete cascade,+ agent_id uuid not null references agent_identities(id) on delete cascade,+ payer_user_id uuid references users(id) on delete set null,+ chain_id integer,+ amount text not null,+ tx_hash text,+ status text not null default 'pending',+ code text,+ outcome text,+ error text,+ period_start_at timestamptz,+ charged_at timestamptz not null default now(),++ constraint subscription_charges_status_check+ check (status in ('success', 'failed', 'aborted', 'unknown')),+ constraint subscription_charges_outcome_check+ check (outcome is null or outcome in ('charged', 'fatal', 'retryable', 'ambiguous'))+);++create index if not exists idx_subscription_charges_subscription+ on subscription_charges(subscription_id, charged_at desc);+create index if not exists idx_subscription_charges_agent+ on subscription_charges(agent_id, charged_at desc);+create unique index if not exists uq_subscription_charges_period+ on subscription_charges(subscription_id, period_start_at)+ where status = 'success' and period_start_at is not null;+-- ── indexer_state — block cursor for the index-delegations cron ──────────────create table if not exists indexer_state (contract text not null,@@ -1204,6 +1247,14 @@ create table if not exists dca_strategies (create index if not exists idx_dca_strategies_agent on dca_strategies(agent_id);create index if not exists idx_dca_strategies_next_exec on dca_strategies(next_execution_at) where status = 'active';+-- Lifecycle columns (migration 20260813191500_recurring_payment_lifecycle.sql):+-- same contract as agent_subscriptions above.+alter table dca_strategies add column if not exists consecutive_failures integer not null default 0;+alter table dca_strategies add column if not exists last_error text;+alter table dca_strategies add column if not exists last_error_code text;+alter table dca_strategies add column if not exists paused_at timestamptz;+alter table dca_strategies add column if not exists resumed_at timestamptz;+-- ── dca_executions — per-cron swap attempt log ───────────────────────────────create table if not exists dca_executions (id uuid primary key default gen_random_uuid(),diff --git a/api/_lib/services/MonetizationService.js b/api/_lib/services/MonetizationService.jsindex 0e4edb5e3..82b120aa9 100644--- a/api/_lib/services/MonetizationService.js+++ b/api/_lib/services/MonetizationService.js@@ -524,6 +524,14 @@ export class MonetizationService {* Creator sales overview for the current user: per-sale ledger entries (skill* royalties + asset sales) plus pending/settled USD totals.*+ * Both royalty lanes land here. Rows billed in-process by skill-runtime carry+ * an agent_id and settle later through the EIP-7710 redeem leg; rows accrued+ * on the platform's own x402 rail (/api/x402/skill-call) have NO agent_id at+ * all, because the caller is an anonymous paying wallet rather than a+ * registered agent. Both joins are therefore LEFT joins: an inner join on+ * agent_identities silently dropped every per-call x402 royalty from this+ * surface, so authors earning on the rail saw an empty ledger and a $0 total.+ ** @returns {Promise<{pending_usd:number, settled_usd:number, entries:Array}>}*/async getCreatorSalesData() {@@ -535,11 +543,17 @@ export class MonetizationService {rl.price_usd,rl.status,rl.created_at,+ rl.settled_at,+ rl.source,+ rl.network,+ rl.tx_hash,+ rl.platform_fee_usd,ms.name AS skill_name,+ ms.slug AS skill_slug,ai.name AS agent_nameFROM royalty_ledger rl- JOIN marketplace_skills ms ON ms.id = rl.skill_id- JOIN agent_identities ai ON ai.id = rl.agent_id+ LEFT JOIN marketplace_skills ms ON ms.id = rl.skill_id+ LEFT JOIN agent_identities ai ON ai.id = rl.agent_idWHERE rl.author_user_id = ${userId}ORDER BY rl.created_at DESCLIMIT 100@@ -574,31 +588,52 @@ export class MonetizationService {// asset_purchases migration hasn't run yet — leave list empty.}- const pending_usd = rows- .filter((r) => r.status === 'pending')+ const sumBy = (status) => rows+ .filter((r) => r.status === status).reduce((s, r) => s + Number(r.price_usd), 0);- const settled_usd = rows- .filter((r) => r.status === 'settled')- .reduce((s, r) => s + Number(r.price_usd), 0);+ const pending_usd = sumBy('pending');+ // Claimed by an in-flight settle pass: no longer 'pending', not yet in the+ // author's wallet. Reported separately so neither total overstates itself.+ const settling_usd = sumBy('settling');+ const settled_usd = sumBy('settled');++ // What the platform kept across these rows. Only the x402 rail records a+ // per-row cut; runtime rows leave it null and contribute 0.+ const platform_fee_usd = rows.reduce((s, r) => s + Number(r.platform_fee_usd ?? 0), 0);const asset_settled_usd = assetRows.reduce((s, r) => s + Number(r.amount) / 1_000_000, 0);const entries = rows.map((r) => ({skill_name: r.skill_name,+ skill_slug: r.skill_slug ?? null,agent_name: r.agent_name,price_usd: Number(r.price_usd),+ platform_fee_usd: r.platform_fee_usd == null ? null : Number(r.platform_fee_usd),status: r.status,created_at: r.created_at,+ settled_at: r.settled_at ?? null,+ // Which rail earned it: 'x402' (per-call, paid straight to the author's+ // wallet at settle) or 'skill-runtime' (in-process, settles via the+ // flag-gated EIP-7710 redeem leg).+ source: r.source ?? 'skill-runtime',+ network: r.network ?? null,+ tx_hash: r.tx_hash ?? null,kind: 'skill',}));for (const r of assetRows) {entries.push({skill_name: `${r.item_type[0].toUpperCase()}${r.item_type.slice(1)} sale`,+ skill_slug: null,agent_name: r.item_name || '(deleted)',price_usd: Number(r.amount) / 1_000_000,+ platform_fee_usd: null,status: 'settled',created_at: r.confirmed_at || r.created_at,+ settled_at: r.confirmed_at || null,+ source: 'asset-sale',+ network: null,+ tx_hash: null,kind: r.item_type,});}@@ -606,7 +641,9 @@ export class MonetizationService {return {pending_usd,+ settling_usd,settled_usd: settled_usd + asset_settled_usd,+ platform_fee_usd,entries,};}@@ -629,7 +666,8 @@ export class MonetizationService {* reconciled to the same revenue/withdrawal ledger buyers are billed from.** @returns {Promise<{- * pending_usd:number, settled_usd:number, entries:Array,+ * pending_usd:number, settling_usd:number, settled_usd:number,+ * platform_fee_usd:number, entries:Array,* splits:{ received_usd:number, distributions:Array },* onchain_licenses:{ minted:number, by_agent:Array },* withdrawable:{ available:number, earned:number, pending:number, withdrawn:number }diff --git a/api/agent-subscriptions.js b/api/agent-subscriptions.jsindex dc96fa5f8..395954e78 100644--- a/api/agent-subscriptions.js+++ b/api/agent-subscriptions.js@@ -1,13 +1,22 @@/**- * /api/agent-subscriptions: manage recurring agent-delegation subscription records.+ * /api/agent-subscriptions: the full lifecycle of a recurring on-chain payment.** Distinct from /api/subscriptions (creator plan subscriptions over* creator_subscriptions); this endpoint tracks delegation-backed recurring- * charges in agent_subscriptions, created by the subscription skill.+ * charges in agent_subscriptions, executed hourly by the run-subscriptions+ * cron in api/cron/[name].js.*- * POST: create a subscription (viewer has already granted a delegation)- * GET: list subscriptions for the authenticated user- * DELETE: soft-cancel a subscription (?id=<uuid>); does NOT revoke the delegation+ * POST create a schedule (the delegation is already signed)+ * GET list the schedules the caller pays for+ * GET ?view=incoming list the schedules paying INTO agents the caller owns+ * GET ?id=<uuid> one schedule plus its charge history+ * PATCH ?id=<uuid> {action} pause or resume a schedule+ * DELETE ?id=<uuid> cancel a schedule (does NOT revoke the delegation)+ *+ * Both sides of the payment can read a schedule: the payer (agent_subscriptions+ * .user_id) and the creator being paid (agent_identities.user_id). Only the+ * payer can pause, resume or cancel, because only their signed delegation funds+ * it.*/import { sql } from './_lib/db.js';@@ -17,6 +26,13 @@ import { requireCsrf } from './_lib/csrf.js';import { limits, clientIp } from './_lib/rate-limit.js';import { z } from 'zod';import { parse } from './_lib/validate.js';+import {+ MAX_CONSECUTIVE_FAILURES,+ describePeriod,+ formatUnits,+ planStatusChange,+ sumUnits,+} from './_lib/recurring.js';const postSchema = z.object({agentId: z.string().uuid(),@@ -27,9 +43,116 @@ const postSchema = z.object({.regex(/^\d+$/, 'amountPerPeriod must be a base-unit integer string'),});+const patchSchema = z.object({+ action: z.enum(['pause', 'resume']),+});++// How many charge attempts a detail view returns. Enough to show a month of+// daily charges without turning one row into an unbounded response.+const CHARGE_HISTORY_LIMIT = 40;++/**+ * Query params, whether the runtime pre-parsed them onto req.query (Vercel-style+ * handlers, the test harness) or left them on the URL (the Cloud Run server).+ */+function queryParam(req, name) {+ const fromQuery = req.query?.[name];+ if (fromQuery != null && fromQuery !== '') return String(fromQuery);+ try {+ return new URL(req.url, 'http://localhost').searchParams.get(name);+ } catch {+ return null;+ }+}++/** Shape one schedule row for the client, with everything the UI renders. */+function presentSchedule(row) {+ return {+ id: row.id,+ agent_id: row.agent_id,+ agent_name: row.agent_name ?? null,+ delegation_id: row.delegation_id,+ chain_id: row.chain_id ?? null,+ payer_address: row.payer_address ?? null,+ payee_address: row.payee_address ?? null,+ period_seconds: row.period_seconds,+ period_label: describePeriod(row.period_seconds),+ amount_per_period: row.amount_per_period,+ amount_display: formatUnits(row.amount_per_period),+ status: row.status,+ next_charge_at: row.next_charge_at,+ last_charge_at: row.last_charge_at,+ last_tx_hash: row.last_tx_hash ?? null,+ last_error: row.last_error ?? null,+ last_error_code: row.last_error_code ?? null,+ consecutive_failures: Number(row.consecutive_failures ?? 0),+ retries_left:+ row.status === 'active'+ ? Math.max(0, MAX_CONSECUTIVE_FAILURES - Number(row.consecutive_failures ?? 0))+ : 0,+ delegation_status: row.delegation_status ?? null,+ delegation_expires_at: row.delegation_expires_at ?? null,+ charges_total: Number(row.charges_total ?? 0),+ charged_total: row.charged_total ?? '0',+ charged_total_display: formatUnits(row.charged_total ?? '0'),+ paused_at: row.paused_at ?? null,+ resumed_at: row.resumed_at ?? null,+ created_at: row.created_at,+ canceled_at: row.canceled_at ?? null,+ };+}++function presentCharge(row) {+ return {+ id: row.id,+ subscription_id: row.subscription_id,+ amount: row.amount,+ amount_display: formatUnits(row.amount),+ chain_id: row.chain_id,+ tx_hash: row.tx_hash,+ status: row.status,+ code: row.code,+ outcome: row.outcome,+ error: row.error,+ charged_at: row.charged_at,+ };+}++// Every list/detail query selects the same columns so presentSchedule always+// has what it needs. Built per call rather than held in a module constant so+// importing this handler never touches the DB client.+const scheduleColumns = () => sql`+ s.id, s.user_id, s.agent_id, s.delegation_id, s.period_seconds, s.amount_per_period,+ s.next_charge_at, s.last_charge_at, s.status, s.last_error, s.last_error_code,+ s.last_tx_hash, s.consecutive_failures, s.paused_at, s.resumed_at,+ s.created_at, s.canceled_at,+ ai.name AS agent_name,+ ai.user_id AS creator_user_id,+ ai.wallet_address AS payee_address,+ d.chain_id AS chain_id,+ d.delegator_address AS payer_address,+ d.status AS delegation_status,+ d.expires_at AS delegation_expires_at,+ COALESCE(c.charges_total, 0) AS charges_total,+ COALESCE(c.charged_total, '0') AS charged_total+`;++// Successful-charge rollup per schedule. LEFT JOINed so a schedule that has+// never charged still lists, with zeroes rather than a missing row.+const chargeRollup = () => sql`+ LEFT JOIN (+ SELECT subscription_id,+ COUNT(*) AS charges_total,+ SUM(amount::numeric)::text AS charged_total+ FROM subscription_charges+ WHERE status = 'success'+ GROUP BY subscription_id+ ) c ON c.subscription_id = s.id+`;+export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;- if (!method(req, res, ['GET', 'POST', 'DELETE'])) return;+ if (cors(req, res, { methods: 'GET,POST,PATCH,DELETE,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST', 'PATCH', 'DELETE'])) return;const session = await getSessionUser(req);const bearer = session ? null : await authenticateBearer(extractBearer(req));@@ -41,10 +164,10 @@ export default wrap(async (req, res) => {// State-changing methods on a cookie session require a CSRF token (bearer// callers are exempt inside requireCsrf). Without this, a cross-origin script- // could cancel a victim's subscriptions on their behalf.+ // could pause or cancel a victim's schedules on their behalf.if (req.method !== 'GET' && !(await requireCsrf(req, res, userId))) return;- // ── POST: create subscription ─────────────────────────────────────────────+ // ── POST: create schedule ─────────────────────────────────────────────────if (req.method === 'POST') {let body;@@ -55,7 +178,10 @@ export default wrap(async (req, res) => {}const { agentId, delegationId, periodSeconds, amountPerPeriod } = body;- // Verify the agent belongs to this user.+ // Verify the agent belongs to this user. Delegations are owner-scoped+ // (api/permissions/grant refuses to record one for an agent you do not+ // own), so a schedule funded by a delegation you signed is always for+ // your own agent.const [agent] = await sql`SELECT id FROM agent_identitiesWHERE id = ${agentId} AND user_id = ${userId} AND deleted_at IS NULL@@ -64,11 +190,14 @@ export default wrap(async (req, res) => {// Verify the delegation is active and belongs to this agent.const [delegation] = await sql`- SELECT id FROM agent_delegations+ SELECT id, expires_at FROM agent_delegationsWHERE id = ${delegationId} AND agent_id = ${agentId} AND status = 'active'`;if (!delegation)return error(res, 400, 'validation_error', 'delegation not found or not active');+ if (delegation.expires_at && new Date(delegation.expires_at) <= new Date()) {+ return error(res, 409, 'delegation_expired', 'delegation has already expired');+ }// Idempotency: return existing active subscription rather than duplicating.const [existing] = await sql`@@ -89,37 +218,224 @@ export default wrap(async (req, res) => {return json(res, 201, { data: row });}- // ── GET: list subscriptions for authenticated user ────────────────────────+ // ── GET: detail, incoming view, or the caller's own schedules ─────────────if (req.method === 'GET') {- const agentId = req.query?.agentId ?? null;+ const id = queryParam(req, 'id');+ const view = queryParam(req, 'view');+ const agentId = queryParam(req, 'agentId');++ if (id) {+ if (!z.string().uuid().safeParse(id).success) {+ return error(res, 400, 'validation_error', 'id must be a uuid');+ }+ const [row] = await sql`+ SELECT ${scheduleColumns()}+ FROM agent_subscriptions s+ JOIN agent_identities ai ON ai.id = s.agent_id+ JOIN agent_delegations d ON d.id = s.delegation_id+ ${chargeRollup()}+ WHERE s.id = ${id}+ `;+ // Both sides of the payment may read it; nobody else may learn it exists.+ if (!row || (row.user_id !== userId && row.creator_user_id !== userId)) {+ return error(res, 404, 'not_found', 'subscription not found');+ }+ const charges = await sql`+ SELECT id, subscription_id, amount, chain_id, tx_hash, status, code, outcome,+ error, charged_at+ FROM subscription_charges+ WHERE subscription_id = ${id}+ ORDER BY charged_at DESC+ LIMIT ${CHARGE_HISTORY_LIMIT}+ `;+ return json(res, 200, {+ data: {+ ...presentSchedule(row),+ role: row.user_id === userId ? 'payer' : 'creator',+ charges: charges.map(presentCharge),+ },+ });+ }+if (agentId && !z.string().uuid().safeParse(agentId).success) {return error(res, 400, 'validation_error', 'agentId must be a uuid');}+ // ?view=incoming — what is being paid INTO the agents this user owns.+ // Scoped by agent_identities.user_id rather than agent_subscriptions+ // .user_id, so it stays correct the day a third party can fund an agent.+ if (view === 'incoming') {+ const rows = agentId+ ? await sql`+ SELECT ${scheduleColumns()}+ FROM agent_subscriptions s+ JOIN agent_identities ai ON ai.id = s.agent_id+ JOIN agent_delegations d ON d.id = s.delegation_id+ ${chargeRollup()}+ WHERE ai.user_id = ${userId} AND ai.deleted_at IS NULL AND s.agent_id = ${agentId}+ ORDER BY s.created_at DESC+ `+ : await sql`+ SELECT ${scheduleColumns()}+ FROM agent_subscriptions s+ JOIN agent_identities ai ON ai.id = s.agent_id+ JOIN agent_delegations d ON d.id = s.delegation_id+ ${chargeRollup()}+ WHERE ai.user_id = ${userId} AND ai.deleted_at IS NULL+ ORDER BY s.created_at DESC+ `;++ const schedules = rows.map(presentSchedule);+ const active = schedules.filter((s) => s.status === 'active');+ return json(res, 200, {+ data: schedules,+ summary: {+ schedules: schedules.length,+ active: active.length,+ needs_attention: schedules.filter((s) => s.status === 'paused').length,+ received_total: sumUnits(schedules.map((s) => s.charged_total)),+ received_total_display: formatUnits(+ sumUnits(schedules.map((s) => s.charged_total)),+ ),+ charges_total: schedules.reduce((n, s) => n + s.charges_total, 0),+ next_charge_at:+ active+ .map((s) => s.next_charge_at)+ .filter(Boolean)+ .sort()[0] ?? null,+ },+ });+ }+const rows = agentId? await sql`- SELECT id, agent_id, delegation_id, period_seconds, amount_per_period,- next_charge_at, last_charge_at, status, last_error, created_at, canceled_at- FROM agent_subscriptions- WHERE user_id = ${userId} AND agent_id = ${agentId}- ORDER BY created_at DESC+ SELECT ${scheduleColumns()}+ FROM agent_subscriptions s+ JOIN agent_identities ai ON ai.id = s.agent_id+ JOIN agent_delegations d ON d.id = s.delegation_id+ ${chargeRollup()}+ WHERE s.user_id = ${userId} AND s.agent_id = ${agentId}+ ORDER BY s.created_at DESC`: await sql`- SELECT id, agent_id, delegation_id, period_seconds, amount_per_period,- next_charge_at, last_charge_at, status, last_error, created_at, canceled_at- FROM agent_subscriptions- WHERE user_id = ${userId}- ORDER BY created_at DESC+ SELECT ${scheduleColumns()}+ FROM agent_subscriptions s+ JOIN agent_identities ai ON ai.id = s.agent_id+ JOIN agent_delegations d ON d.id = s.delegation_id+ ${chargeRollup()}+ WHERE s.user_id = ${userId}+ ORDER BY s.created_at DESC`;- return json(res, 200, { data: rows });+ const schedules = rows.map(presentSchedule);+ const active = schedules.filter((s) => s.status === 'active');+ return json(res, 200, {+ data: schedules,+ summary: {+ schedules: schedules.length,+ active: active.length,+ needs_attention: schedules.filter((s) => s.status === 'paused').length,+ paid_total: sumUnits(schedules.map((s) => s.charged_total)),+ paid_total_display: formatUnits(sumUnits(schedules.map((s) => s.charged_total))),+ charges_total: schedules.reduce((n, s) => n + s.charges_total, 0),+ next_charge_at:+ active+ .map((s) => s.next_charge_at)+ .filter(Boolean)+ .sort()[0] ?? null,+ },+ });+ }++ // ── PATCH: pause / resume ─────────────────────────────────────────────────++ if (req.method === 'PATCH') {+ const id = queryParam(req, 'id');+ if (!id) return error(res, 400, 'validation_error', 'id query param is required');+ if (!z.string().uuid().safeParse(id).success) {+ return error(res, 400, 'validation_error', 'id must be a uuid');+ }++ let body;+ try {+ body = parse(patchSchema, await readJson(req));+ } catch (err) {+ return error(res, err.status ?? 400, err.code ?? 'validation_error', err.message);+ }++ // Only the payer controls the schedule: it spends their delegation.+ const [current] = await sql`+ SELECT s.status, s.next_charge_at, s.period_seconds,+ d.status AS delegation_status, d.expires_at AS delegation_expires_at+ FROM agent_subscriptions s+ JOIN agent_delegations d ON d.id = s.delegation_id+ WHERE s.id = ${id} AND s.user_id = ${userId}+ `;+ if (!current) return error(res, 404, 'not_found', 'subscription not found');++ const plan = planStatusChange(body.action, current.status);+ if (!plan.ok) {+ return error(res, plan.code === 'conflict' ? 409 : 400, plan.code, plan.message);+ }++ if (body.action === 'resume') {+ // Resuming a schedule whose delegation is gone would just fail on the+ // next tick and re-pause it. Say so instead of pretending it worked.+ if (current.delegation_status !== 'active') {+ return error(+ res,+ 409,+ 'delegation_inactive',+ `the signed permission behind this schedule is ${current.delegation_status} — grant a new one to restart it`,+ );+ }+ if (+ current.delegation_expires_at &&+ new Date(current.delegation_expires_at) <= new Date()+ ) {+ return error(+ res,+ 409,+ 'delegation_expired',+ 'the signed permission behind this schedule has expired — grant a new one to restart it',+ );+ }++ // Charge from now on rather than back-filling every period missed while+ // paused: a resume must never fire a burst of catch-up charges.+ const nextChargeAt = new Date(+ Date.now() + Number(current.period_seconds) * 1000,+ ).toISOString();+ const [row] = await sql`+ UPDATE agent_subscriptions+ SET status = 'active',+ next_charge_at = ${nextChargeAt},+ consecutive_failures = 0,+ last_error = NULL,+ last_error_code = NULL,+ resumed_at = NOW()+ WHERE id = ${id} AND user_id = ${userId} AND status = 'paused'+ RETURNING id, status, next_charge_at, resumed_at+ `;+ if (!row) return error(res, 409, 'conflict', 'schedule changed while resuming');+ return json(res, 200, { data: row });+ }++ const [row] = await sql`+ UPDATE agent_subscriptions+ SET status = 'paused', paused_at = NOW()+ WHERE id = ${id} AND user_id = ${userId} AND status = 'active'+ RETURNING id, status, paused_at, next_charge_at+ `;+ if (!row) return error(res, 409, 'conflict', 'schedule changed while pausing');+ return json(res, 200, { data: row });}- // ── DELETE: soft-cancel ───────────────────────────────────────────────────+ // ── DELETE: cancel ────────────────────────────────────────────────────────if (req.method === 'DELETE') {- const id = req.query?.id;+ const id = queryParam(req, 'id');if (!id) return error(res, 400, 'validation_error', 'id query param is required');if (!z.string().uuid().safeParse(id).success) {return error(res, 400, 'validation_error', 'id must be a uuid');diff --git a/api/cron/[name].js b/api/cron/[name].jsindex e696737ad..79b06e19d 100644--- a/api/cron/[name].js+++ b/api/cron/[name].js@@ -71,6 +71,12 @@ import { runPumpAlertRules } from '../_lib/pump-alert-runner.js';import { publishUserEvent } from '../_lib/feed.js';import { confirmSkillPurchase } from '../_lib/purchase-confirm.js';import { requireCron } from '../_lib/cron-auth.js';+import {+ OUTCOME,+ applyChargeFailure,+ chargeStatusFor,+ classifyChargeFailure,+} from '../_lib/recurring.js';// ─── Dispatcher ──────────────────────────────────────────────────────────────@@ -2891,6 +2897,8 @@ async function handleRunSubscriptions(req, res) {charged: 0,skipped: 0,paused: 0,+ // Retryable failures that left the schedule active for the next tick.+ retrying: 0,claimLost: 0,errors: [],};@@ -2917,6 +2925,7 @@ async function handleRunSubscriptions(req, res) {s.amount_per_period,s.next_charge_at,s.last_charge_at,+ s.consecutive_failures,d.status AS delegation_status,d.expires_at AS delegation_expires_at,d.chain_id,@@ -2947,36 +2956,44 @@ async function handleRunSubscriptions(req, res) {const ctx = { runId, subscriptionId: row.id, agentId: row.agent_id };try {- // Guard: delegation must still be active.+ // Guard: delegation must still be active. Nothing is attempted+ // on-chain here, but the attempt is still recorded: a creator reading+ // the ledger has to see why a period produced no money.if (row.delegation_status !== 'active') {- await subPause(row.id, `delegation_${row.delegation_status}`);- report.paused++;- report.errors.push({ id: row.id, reason: `delegation_${row.delegation_status}` });- subLog('subscription_cron.paused', {- ...ctx,- reason: `delegation_${row.delegation_status}`,+ const applied = await subApplyFailure(row, ctx, {+ code:+ row.delegation_status === 'revoked'+ ? 'delegation_revoked'+ : 'delegation_expired',+ message: `delegation is ${row.delegation_status}`,});+ report.paused++;+ report.errors.push({ id: row.id, code: applied.code, reason: applied.reason });+ subLog('subscription_cron.paused', { ...ctx, code: applied.code });continue;}// Guard: delegation must not be expired.if (row.delegation_expires_at && new Date(row.delegation_expires_at) <= new Date()) {- await subPause(row.id, 'delegation_expired');+ const applied = await subApplyFailure(row, ctx, {+ code: 'delegation_expired',+ message: 'delegation expiry has passed',+ });report.paused++;- report.errors.push({ id: row.id, reason: 'delegation_expired' });- subLog('subscription_cron.paused', { ...ctx, reason: 'delegation_expired' });+ report.errors.push({ id: row.id, code: applied.code, reason: applied.reason });+ subLog('subscription_cron.paused', { ...ctx, code: applied.code });continue;}const usdcAddress = USDC_BY_CHAIN[row.chain_id];if (!usdcAddress) {- await subPause(row.id, `chain_${row.chain_id}_unsupported`);- report.skipped++;- report.errors.push({ id: row.id, reason: `chain_${row.chain_id}_unsupported` });- subLog('subscription_cron.skipped', {- ...ctx,- reason: `chain_${row.chain_id}_unsupported`,+ const applied = await subApplyFailure(row, ctx, {+ code: 'chain_not_supported',+ message: `chain ${row.chain_id} has no USDC address configured`,});+ report.skipped++;+ report.errors.push({ id: row.id, code: applied.code, reason: applied.reason });+ subLog('subscription_cron.skipped', { ...ctx, code: applied.code });continue;}@@ -3023,14 +3040,19 @@ async function handleRunSubscriptions(req, res) {'onPeriod',);} catch (err) {- const reason =- (err.code === 'timeout' ? 'timeout: ' : '') + (err.message ?? 'unknown');- await subSafePause(row.id, reason, ctx);- report.paused++;- report.errors.push({ id: row.id, reason });+ const applied = await subApplyFailure(row, ctx, {+ code: err.code ?? 'unknown',+ message: err.message ?? 'unknown',+ });+ if (applied.pause) report.paused++;+ else report.retrying++;+ report.errors.push({ id: row.id, code: applied.code, reason: applied.reason });subLogError('subscription_cron.onperiod_threw', {...ctx,- code: err.code ?? 'unknown',+ code: applied.code,+ outcome: applied.outcome,+ paused: applied.pause,+ willRetry: applied.retry,message: err.message ?? 'unknown',durationMs: Date.now() - rowStart,});@@ -3045,8 +3067,11 @@ async function handleRunSubscriptions(req, res) {try {await sql`UPDATE agent_subscriptions- SET next_charge_at = ${nextChargeAt.toISOString()},- last_error = NULL+ SET next_charge_at = ${nextChargeAt.toISOString()},+ last_error = NULL,+ last_error_code = NULL,+ consecutive_failures = 0,+ last_tx_hash = ${result.txHash ?? null}WHERE id = ${row.id}`;} catch (err) {@@ -3077,6 +3102,12 @@ async function handleRunSubscriptions(req, res) {}),);+ await recordSubscriptionCharge(row, ctx, {+ status: chargeStatusFor(OUTCOME.CHARGED),+ outcome: OUTCOME.CHARGED,+ txHash: result.txHash ?? null,+ });+report.charged++;subLog('subscription_cron.charged', {...ctx,@@ -3084,15 +3115,19 @@ async function handleRunSubscriptions(req, res) {durationMs: Date.now() - rowStart,});} else {- const code = result?.code ?? 'unknown';- const message = result?.message ?? '';- await subSafePause(row.id, `${code}: ${message}`.slice(0, 500), ctx);- report.paused++;- report.errors.push({ id: row.id, code, message });- subLog('subscription_cron.paused', {+ const applied = await subApplyFailure(row, ctx, {+ code: result?.code ?? 'unknown',+ message: result?.message ?? '',+ });+ if (applied.pause) report.paused++;+ else report.retrying++;+ report.errors.push({ id: row.id, code: applied.code, reason: applied.reason });+ subLog('subscription_cron.charge_failed', {...ctx,- code,- message,+ code: applied.code,+ outcome: applied.outcome,+ paused: applied.pause,+ willRetry: applied.retry,durationMs: Date.now() - rowStart,});}@@ -3120,6 +3155,7 @@ async function handleRunSubscriptions(req, res) {processed: report.processed,charged: report.charged,paused: report.paused,+ retrying: report.retrying,skipped: report.skipped,claimLost: report.claimLost,errorCount: report.errors.length,@@ -3131,11 +3167,88 @@ async function handleRunSubscriptions(req, res) {async function subPause(id, lastError) {await sql`UPDATE agent_subscriptions- SET status = 'paused', last_error = ${lastError}+ SET status = 'paused', last_error = ${lastError}, paused_at = NOW()WHERE id = ${id}`;}+/**+ * Append one row to the subscription charge ledger. Best-effort: a ledger write+ * must never turn a successful charge into a failed cron row, so failures are+ * logged and swallowed.+ */+async function recordSubscriptionCharge(row, ctx, { status, outcome, code, error, txHash }) {+ await sql`+ INSERT INTO subscription_charges+ (subscription_id, agent_id, payer_user_id, chain_id, amount, tx_hash,+ status, code, outcome, error, period_start_at)+ VALUES+ (${row.id}, ${row.agent_id}, ${row.user_id ?? null}, ${row.chain_id ?? null},+ ${row.amount_per_period}, ${txHash ?? null}, ${status}, ${code ?? null},+ ${outcome}, ${error ? String(error).slice(0, 500) : null},+ ${row.next_charge_at ?? null})+ ON CONFLICT DO NOTHING+ `.catch((err) =>+ subLogError('subscription_cron.charge_record_failed', { ...ctx, message: err.message }),+ );+}++/**+ * Apply a failed charge to the schedule: record it in the ledger, then either+ * leave the schedule active for another tick or pause it, per the shared rules+ * in api/_lib/recurring.js.+ *+ * Releasing the period claim means restoring last_charge_at to what it was+ * before this tick claimed the period. That is only safe because the retryable+ * bucket is exactly the set of failures where the transfer provably never+ * reached the chain; a timeout is classified ambiguous and never retried.+ */+async function subApplyFailure(row, ctx, failure) {+ const { code, outcome, reason } = classifyChargeFailure(failure);+ const applied = applyChargeFailure({+ outcome,+ consecutiveFailures: Number(row.consecutive_failures ?? 0),+ });++ await recordSubscriptionCharge(row, ctx, {+ status: chargeStatusFor(outcome),+ outcome,+ code,+ error: failure.message,+ });++ try {+ if (applied.pause) {+ await sql`+ UPDATE agent_subscriptions+ SET status = 'paused',+ paused_at = NOW(),+ last_error = ${reason.slice(0, 500)},+ last_error_code = ${code},+ consecutive_failures = ${applied.consecutiveFailures}+ WHERE id = ${row.id}+ `;+ } else {+ await sql`+ UPDATE agent_subscriptions+ SET last_charge_at = ${row.last_charge_at ?? null},+ last_error = ${reason.slice(0, 500)},+ last_error_code = ${code},+ consecutive_failures = ${applied.consecutiveFailures}+ WHERE id = ${row.id}+ `;+ }+ } catch (err) {+ subLogError('subscription_cron.apply_failure_failed', {+ ...ctx,+ code,+ message: err.message,+ });+ }++ return { ...applied, code, outcome, reason };+}+// Like subPause but swallows its own errors so a DB hiccup during pause doesn't// propagate out of the per-row handler. Logs the failure for ops visibility.async function subSafePause(id, lastError, ctx) {diff --git a/api/dca-strategies.js b/api/dca-strategies.jsindex ff7791c46..1f8d8995e 100644--- a/api/dca-strategies.js+++ b/api/dca-strategies.js@@ -1,5 +1,12 @@-// POST/GET/DELETE /api/dca-strategies-// Manages DCA strategy records. Strategies are executed by api/cron/run-dca.js.+// POST/GET/PATCH/DELETE /api/dca-strategies+// Manages DCA strategy records. Strategies are executed hourly by the run-dca+// cron in api/cron/[name].js.+//+// POST create a strategy (delegation already signed)+// GET ?agent_id=<uuid> list an agent's strategies+// GET /api/dca-strategies/<id> one strategy plus its execution history+// PATCH /api/dca-strategies/<id> pause or resume ({ "action": "pause" })+// DELETE /api/dca-strategies/<id> cancel (terminal; does NOT revoke the delegation)import { z } from 'zod';import { sql } from './_lib/db.js';@@ -8,6 +15,12 @@ import { cors, json, error, wrap, readJson, method, rateLimited } from './_lib/himport { requireCsrf } from './_lib/csrf.js';import { parse } from './_lib/validate.js';import { limits, clientIp } from './_lib/rate-limit.js';+import {+ MAX_CONSECUTIVE_FAILURES,+ describePeriod,+ formatUnits,+ planStatusChange,+} from './_lib/recurring.js';// Whitelisted token-out symbols — runtime operator config, never hardcoded// tickers. DCA_ALLOWED_TOKEN_OUT is a comma-separated symbol list; when unset@@ -53,23 +66,136 @@ const createSchema = z.object({slippage_bps: z.number().int().min(1).max(MAX_SLIPPAGE_BPS).default(50),});+const patchSchema = z.object({+ action: z.enum(['pause', 'resume']),+});++// How many execution attempts a detail view returns.+const EXECUTION_HISTORY_LIMIT = 40;++/**+ * The strategy id from `/api/dca-strategies/<id>`, or from `?id=` when a+ * runtime rewrote the path into a query param.+ */+function strategyIdFrom(url) {+ const fromPath = url.pathname.split('/').pop();+ if (fromPath && fromPath !== 'dca-strategies') return fromPath;+ return url.searchParams.get('id');+}++/** Shape one strategy row for the client, matching the subscription presenter. */+function presentStrategy(row) {+ return {+ ...row,+ period_label: describePeriod(row.period_seconds),+ amount_display: formatUnits(row.amount_per_execution),+ consecutive_failures: Number(row.consecutive_failures ?? 0),+ retries_left:+ row.status === 'active'+ ? Math.max(0, MAX_CONSECUTIVE_FAILURES - Number(row.consecutive_failures ?? 0))+ : 0,+ };+}+export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;+ if (cors(req, res, { methods: 'GET,POST,PATCH,DELETE,OPTIONS', credentials: true })) return;const session = await getSessionUser(req);if (!session) return error(res, 401, 'unauthorized', 'sign in required');// State-changing methods on a cookie session require a CSRF token. These- // strategies move real funds on a schedule, so a forged create/cancel is- // high-impact — gate every non-GET method.+ // strategies move real funds on a schedule, so a forged create/pause/cancel+ // is high-impact — gate every non-GET method.if (req.method !== 'GET' && !(await requireCsrf(req, res, session.id))) return;const url = new URL(req.url, 'http://x');+ // ── PATCH /api/dca-strategies/:id — pause / resume ────────────────────────+ if (req.method === 'PATCH') {+ const strategyId = strategyIdFrom(url);+ if (!strategyId) return error(res, 400, 'missing_param', 'strategy id required in path');+ if (!z.string().uuid().safeParse(strategyId).success) {+ return error(res, 400, 'validation_error', 'strategy id must be a uuid');+ }++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ let body;+ try {+ body = parse(patchSchema, await readJson(req));+ } catch (err) {+ return error(res, err.status || 400, err.code || 'validation_error', err.message);+ }++ const [row] = await sql`+ SELECT s.status, s.period_seconds, d.status AS delegation_status,+ d.expires_at AS delegation_expires_at+ FROM dca_strategies s+ JOIN agent_identities a ON a.id = s.agent_id+ JOIN agent_delegations d ON d.id = s.delegation_id+ WHERE s.id = ${strategyId} AND a.user_id = ${session.id}+ LIMIT 1+ `;+ if (!row) return error(res, 404, 'not_found', 'strategy not found');++ const plan = planStatusChange(body.action, row.status);+ if (!plan.ok) {+ return error(res, plan.code === 'conflict' ? 409 : 400, plan.code, plan.message);+ }++ if (body.action === 'pause') {+ const [paused] = await sql`+ UPDATE dca_strategies+ SET status = 'paused', paused_at = NOW()+ WHERE id = ${strategyId} AND status = 'active'+ RETURNING id, status, paused_at, next_execution_at+ `;+ if (!paused) return error(res, 409, 'conflict', 'strategy changed while pausing');+ return json(res, 200, { ok: true, data: paused });+ }++ // Resuming onto a dead delegation would only fail on the next tick and+ // re-pause the row, so refuse with the reason instead.+ if (row.delegation_status !== 'active') {+ return error(+ res,+ 409,+ 'delegation_inactive',+ `the signed permission behind this strategy is ${row.delegation_status} — grant a new one to restart it`,+ );+ }+ if (row.delegation_expires_at && new Date(row.delegation_expires_at) <= new Date()) {+ return error(+ res,+ 409,+ 'delegation_expired',+ 'the signed permission behind this strategy has expired — grant a new one to restart it',+ );+ }++ // Schedule the next swap a full period out rather than back-filling the+ // periods missed while paused: a resume must never fire a burst of swaps.+ const nextExecAt = new Date(Date.now() + Number(row.period_seconds) * 1000).toISOString();+ const [resumed] = await sql`+ UPDATE dca_strategies+ SET status = 'active',+ next_execution_at = ${nextExecAt},+ consecutive_failures = 0,+ last_error = NULL,+ last_error_code = NULL,+ resumed_at = NOW()+ WHERE id = ${strategyId} AND status = 'paused'+ RETURNING id, status, next_execution_at, resumed_at+ `;+ if (!resumed) return error(res, 409, 'conflict', 'strategy changed while resuming');+ return json(res, 200, { ok: true, data: resumed });+ }+// ── DELETE /api/dca-strategies/:id ─────────────────────────────────────────if (req.method === 'DELETE') {- const strategyId = url.pathname.split('/').pop();- if (!strategyId || strategyId === 'dca-strategies') {+ const strategyId = strategyIdFrom(url);+ if (!strategyId) {return error(res, 400, 'missing_param', 'strategy id required in path');}if (!z.string().uuid().safeParse(strategyId).success) {@@ -80,14 +206,15 @@ export default wrap(async (req, res) => {const rl = await limits.authIp(ip);if (!rl.success) return rateLimited(res, rl);- // Verify ownership via agent_id → user_id chain+ // Verify ownership via agent_id → user_id chain. A paused strategy is+ // cancellable too — cancel is the terminal state from anywhere but itself.const [row] = await sql`SELECT s.idFROM dca_strategies sJOIN agent_identities a ON a.id = s.agent_idWHERE s.id = ${strategyId}AND a.user_id = ${session.id}- AND s.status = 'active'+ AND s.status <> 'cancelled'LIMIT 1`;if (!row) return error(res, 404, 'not_found', 'strategy not found or already cancelled');@@ -100,18 +227,54 @@ export default wrap(async (req, res) => {return json(res, 200, { ok: true });}- // ── GET /api/dca-strategies?agent_id=… ────────────────────────────────────+ // ── GET — one strategy with history, or an agent's list ───────────────────if (req.method === 'GET') {+ const ip = clientIp(req);+ const rl = await limits.authedReadIp(ip);+ if (!rl.success) return rateLimited(res, rl);++ const detailId = strategyIdFrom(url);+ if (detailId) {+ if (!z.string().uuid().safeParse(detailId).success) {+ return error(res, 400, 'validation_error', 'strategy id must be a uuid');+ }+ const [strategy] = await sql`+ SELECT+ s.id, s.agent_id, s.delegation_id, s.chain_id, s.token_in, s.token_out,+ s.token_out_symbol, s.amount_per_execution, s.period_seconds, s.slippage_bps,+ s.status, s.next_execution_at, s.last_execution_at, s.created_at,+ s.cancelled_at, s.paused_at, s.resumed_at, s.consecutive_failures,+ s.last_error, s.last_error_code,+ a.name AS agent_name,+ d.status AS delegation_status, d.expires_at AS delegation_expires_at+ FROM dca_strategies s+ JOIN agent_identities a ON a.id = s.agent_id+ JOIN agent_delegations d ON d.id = s.delegation_id+ WHERE s.id = ${detailId} AND a.user_id = ${session.id}+ LIMIT 1+ `;+ if (!strategy) return error(res, 404, 'not_found', 'strategy not found');++ const executions = await sql`+ SELECT id, chain_id, tx_hash, amount_in, quote_amount_out, amount_out,+ slippage_bps_used, quote_divergence_bps, status, error, executed_at+ FROM dca_executions+ WHERE strategy_id = ${detailId}+ ORDER BY executed_at DESC+ LIMIT ${EXECUTION_HISTORY_LIMIT}+ `;+ return json(res, 200, {+ ok: true,+ data: { ...presentStrategy(strategy), executions },+ });+ }+const agentId = url.searchParams.get('agent_id');if (!agentId) return error(res, 400, 'missing_param', 'agent_id is required');if (!z.string().uuid().safeParse(agentId).success) {return error(res, 400, 'validation_error', 'agent_id must be a uuid');}- const ip = clientIp(req);- const rl = await limits.authedReadIp(ip);- if (!rl.success) return rateLimited(res, rl);-// Confirm session user owns this agentconst [agent] = await sql`SELECT id FROM agent_identities@@ -122,27 +285,34 @@ export default wrap(async (req, res) => {const strategies = await sql`SELECT- s.id, s.chain_id, s.token_in, s.token_out, s.token_out_symbol,- s.amount_per_execution, s.period_seconds, s.slippage_bps,+ s.id, s.agent_id, s.delegation_id, s.chain_id, s.token_in, s.token_out,+ s.token_out_symbol, s.amount_per_execution, s.period_seconds, s.slippage_bps,s.status, s.next_execution_at, s.last_execution_at, s.created_at,+ s.cancelled_at, s.paused_at, s.resumed_at, s.consecutive_failures,+ s.last_error, s.last_error_code,(SELECT json_build_object('tx_hash', e.tx_hash,'amount_in', e.amount_in,'amount_out', e.amount_out,'status', e.status,+ 'error', e.error,'executed_at', e.executed_at)FROM dca_executions eWHERE e.strategy_id = s.idORDER BY e.executed_at DESCLIMIT 1- ) AS last_execution+ ) AS last_execution,+ (+ SELECT COUNT(*) FROM dca_executions e+ WHERE e.strategy_id = s.id AND e.status = 'success'+ ) AS executions_totalFROM dca_strategies sWHERE s.agent_id = ${agentId}ORDER BY s.created_at DESC`;- return json(res, 200, { ok: true, data: strategies });+ return json(res, 200, { ok: true, data: strategies.map(presentStrategy) });}// ── POST /api/dca-strategies ───────────────────────────────────────────────@@ -212,12 +382,14 @@ export default wrap(async (req, res) => {}// Prevent duplicate active strategies for the same agent + token pair+ // A paused strategy still occupies the pair: resuming it would otherwise+ // leave two live schedules buying the same token from the same wallet.const [existing] = await sql`- SELECT id FROM dca_strategies+ SELECT id, status FROM dca_strategiesWHERE agent_id = ${body.agent_id}AND token_in = ${body.token_in}AND token_out = ${body.token_out}- AND status = 'active'+ AND status IN ('active', 'paused')LIMIT 1`;if (existing) {@@ -225,7 +397,7 @@ export default wrap(async (req, res) => {res,409,'conflict',- 'an active strategy already exists for this token pair — cancel it first',+ `a ${existing.status} strategy already exists for this token pair — cancel it first`,);}