Inspiration

Modern finance is split into two broken extremes: passive dashboards that only show you where your money went after it’s gone, and unguarded AI agents that nobody wants to trust with a real payment method.

Every day, founders, students, and small teams leave thousands of dollars on the table—paying full price for SaaS subscriptions when partner discounts exist, missing out on $300k+ in startup cloud credits, getting hit by silent post-trial renewal spikes, and spending hours categorizing multi-currency receipts for tax season.

We asked a simple question: What if you had an autonomous CFO that actively saves you money, claims your perks, and executes payments—while guaranteeing mathematically and at the database level that an AI model can never overspend, double-charge, or see your raw card details?

That question inspired Rico (ricoagent.tech), an open-source autonomous financial operations (FinOps) and agentic commerce platform.


What Rico Does

Rico turns natural-language financial rules ("mandates") into guarded, verifiable actions inside a unified workspace:

  • Partner Discount Marketplace & Startup Credits: Automatically matches founders, students, and developers to verified partner deals (1,000+ partners), student perks (such as GitHub Student Pack), and $300k+ in cloud and SaaS startup credits (AWS Activate, GCP, PostHog, Notion), including application essay drafting.
  • Live Headless Browser Price Verification: Launches real headless Chromium instances via Playwright CDP to inspect live merchant checkout pages, verify real-time DOM pricing, and stream a 30FPS viewport inside RICO-Browser.
  • Multi-Tier Financial Guardrails: Every payment must pass hard budget ceilings, price-spike anomaly detection, billing-period idempotency locks, and a two-step HMAC-signed confirmToken handshake.
  • 24/7 Price Sentinel & Omnichannel Approvals: Continuously audits recurring subscriptions for price hikes, expiring 24-hour free trials, and unused "zombie seats," sending interactive approval cards to Telegram, WhatsApp, and Slack (Approve One-Time, Pay with Backup Card, or 1-Click Cancel).
  • Bulk Invoice OCR & Tax Engine: Parses multi-currency receipts (USD, EUR, GBP), verifies line-item math integrity, reconciles them against active mandates, and classifies IRS Schedule C tax deductions automatically.

How We Built It

Rico is built as a full-stack Next.js 14 (App Router) + TypeScript monorepo (core platform + standalone marketing/docs app) backed by a dual SQLite / PostgreSQL 16 Drizzle ORM data layer.

1. Multi-Agent Reasoning & Generative UI

  • Model Orchestration: Combines Google Gemini (@google/genai) for interactive tool calling with DeepSeek for batch and deep reasoning, plus Bring-Your-Own-Key (BYOK) support for Claude, GPT, and Llama.
  • Google A2UI v1.0 + Split Workspace: Instead of walls of text, Rico composes interactive financial UI cards, live spreadsheets (RICO-Excel via FortuneSheet), audit grids (AG Grid), and document editors (RICO-DOC via BlockNote).
  • Modular SKILL.md Runtime Injector: Domain playbooks (cloud credit domino, SaaS renewal negotiation, invoice auditing, tax deduction OCR) are parsed from Markdown/YAML frontmatter and injected dynamically into agent prompts.

2. Deterministic Financial Guardrail Math

LLMs are probabilistic; moving money must be deterministic. In Rico, no AI tool can capture funds directly. Chat tools can only request a server-verified quote (/api/payments/quote), which issues a short-lived HMAC-signed confirmToken verified by /api/payments/execute.

Every live scraped merchant price \(p_{\text{live}}\) is evaluated against the mandate’s authorized budget ceiling \(B_{\max}\) and expected baseline \(p_{\text{base}}\):

$$ \Delta_{\text{cap}} = p_{\text{live}} - B_{\max} $$

If \(\Delta_{\text{cap}} > 0\) (rounded to 2 decimal places), execution is hard-blocked (BLOCKED) and logged to auditLogs and PostHog telemetry. Next, Rico computes the relative price jump \(\Delta p\):

$$ \Delta p = \frac{p_{\text{live}} - p_{\text{base}}}{p_{\text{base}}} \times 100 $$

Whenever \(\Delta p \ge \tau_{\text{anomaly}}\) (default \(\tau_{\text{anomaly}} = 20\%\)), the payment is placed on an Anomaly Hold (ANOMALY_HOLD) requiring explicit human confirmation via the web console, Telegram, WhatsApp, or Slack.

3. Concurrency, Idempotency & Fail-Closed Reconciliation

To eliminate duplicate charges across retries or concurrent workers, every mandate run derives a deterministic UTC billing-period idempotency key:

$$ K_{\text{period}}(m, t) = \text{period} : m_{\text{id}} : L(m_{\text{recurrence}}, t) $$

where \(L(\cdot)\) maps recurrence rules to canonical UTC period labels (YYYY-MM, YYYY-Www, YYYY-Qn, YYYY, or once).

Layer Enforcement Mechanism Guarantee
Tier 1: Budget Ceiling Deterministic cap check \(p_{\text{live}} \le B_{\max}\) Hard reject before payment rail call
Tier 2: Anomaly Sentinel Threshold check \(\Delta p \ge 20\%\) on live_browser price Places mandate on ANOMALY_HOLD
Tier 3: Quote Handshake Two-step HMAC-signed confirmToken AI tools cannot capture funds directly
Tier 4: DB Reservation PG SELECT ... FOR UPDATE + partial unique index At most one in-flight/completed charge per period

In PostgreSQL production mode, Rico uses a three-phase reserve-before-capture protocol:

  1. Reserve: Acquire a row lock (SELECT ... FOR UPDATE) on the mandate, enforce the partial unique index (transactions_mandate_pending_uq), and commit a PENDING reservation row.
  2. Execute Outside Lock: Call PayPal Orders v2 (with deterministic PayPal-Request-Id headers) or tokenized backup card rails (PayPal Vault v3 / Stripe adapter) with no DB transaction held open.
  3. Finalize or Fail-Closed: Finalize to COMPLETED on success. If a network timeout or ambiguous 5xx occurs, the row stays PENDING (NEEDS_RECONCILIATION)—blocking all retries until reconciled rather than risking a double-capture.

4. FinOps Tax & Watchdog Calculations

For uploaded invoices, Rico decomposes line items \(i \in {1, \dots, n}\) with pre-tax amount \(a_i\) and IRS Schedule C deduction rate \(r_i \in {0, 0.5, 1.0}\) (e.g., \(100\%\) for cloud/SaaS under Sec. 162/179 vs. \(50\%\) for business meals under Sec. 274):

$$ D_{\text{total}} = \sum_{i=1}^{n} a_i \cdot r_i $$

Simultaneously, the Contract Watchdog calculates annualized seat waste across parallel worker pools from licensed seats \(s_{\text{licensed}}\), active seats \(s_{\text{active}}\), and monthly per-seat cost \(c_{\text{seat}}\):

$$ W_{\text{annual}} = 12 \cdot (s_{\text{licensed}} - s_{\text{active}}) \cdot c_{\text{seat}} $$

5. Universal MCP Hub & Zero-Knowledge Security

  • Universal MCP Client (src/lib/mcp/): Connects to PayPal, GitHub, Slack, Notion, Stripe, and custom HTTP/SSE MCP servers with automatic token redaction.
  • Zero-Knowledge Vaulting & Sealed Auth: Raw card PANs and CVVs stay inside hosted/vaulted payment frames and never enter LLM prompts or logs. Supabase access and refresh tokens are sealed inside HMAC-SHA256 / AES-GCM HttpOnly; Secure; SameSite=Lax cookies.

Challenges We Faced

  1. Preventing Double-Charges Under Concurrency: Application-level duplicate checks fail when webhooks retry or two clicks race. Moving to a reserve-before-capture design with PostgreSQL SELECT ... FOR UPDATE row locks, partial unique indexes, and billing-period idempotency keys eliminated race conditions.
  2. Separating Live Browser Prices from Stale Cache Baselines: Running automated Price Sentinel audits without false-positive holds required strictly tagging every observation as live_browser (verified Playwright DOM extraction) versus cache_fallback, so unverified cache reads never block legitimate renewals.
  3. Preserving Dual SQLite + PostgreSQL Parity: We wanted instant zero-config local evaluation on SQLite (better-sqlite3 in WAL mode) alongside multi-tenant PostgreSQL 16. A single synchronous Drizzle call (.run(), .get(), .all()) silently breaks PostgreSQL. We wrote a static CI guardrail (scripts/ci-guardrails.mjs) that blocks merges if synchronous SQLite calls or @ts-ignore appear in critical paths.
  4. Hardening Browser & Webhook Attack Surfaces: Streaming live headless Chromium frames and accepting omnichannel webhook callbacks meant defending against ReDoS, SSRF/hostname spoofing, and cookie tampering—all audited via CodeQL SAST and a 32-case live GoTrue authentication E2E suite.

What We Learned

  • Decouple Intelligence from Authority: LLMs excel at discovering partner deals, drafting startup credit essays, and parsing messy multi-currency invoices—but authority to move money must stay in deterministic code and database locks, never inside a model prompt.
  • Fail-Closed Beats "Smart Retry" in Payments: When an external payment provider times out, retrying blindly causes double charges. Locking the reservation as NEEDS_RECONCILIATION protects users when networks misbehave.
  • Automated CI Guardrails Supercharge Velocity: Our 6-gate CI/CD pipeline (static guardrails, dual TypeScript/ESLint, 23 SQLite suites, 81 PostgreSQL concurrency/chaos cases, live Auth E2E build, and Playwright DOM tests—130+ tests total) lets us ship fast without breaking financial invariants.

What's Next for Rico

  • Early Access Launch at ricoagent.tech: Onboarding waitlist users with 1,000 free credits in month one and 250 free credits every month after (zero card required), plus full BYOK and API access.
  • Expanding the Partner & Startup Network: Growing our 1,000+ partner discount marketplace and automating end-to-end startup program applications.
  • Enterprise Governance: Multi-signature team approvals, dedicated browser clusters, and SOC 2 Type II readiness—while keeping Rico open-source under the MIT License.

Built With

Share this project:

Updates

Submission history