Skip to content

ac12644/RevPilot

Repository files navigation

RevAgent

Autonomous Revenue Operations for B2B SaaS
Replace a RevOps analyst. Prevent 20% of deal slippage.


RevAgent is an AI-powered revenue operations platform that monitors your sales pipeline, identifies at-risk deals, generates forecasts, and takes corrective action — autonomously or with human approval. Built for mid-market B2B SaaS teams (50–500 employees).

Key Features

  • AI Risk Detection — Continuously scores deal health using signals from CRM activity, email sentiment, stakeholder engagement, deal complexity, and pipeline velocity. Surfaces at-risk deals before they slip, with calibration-aware confidence intervals and explainable signal breakdowns.
  • Deep Email Intelligence — Full thread analysis with competitor mention detection, ghosting detection, tone shift tracking, unanswered question extraction, and per-contact engagement metrics. Configurable competitor list via EXTRA_COMPETITORS env var.
  • Autonomous Actions — Suggests hygiene fixes (close dates, stages, next steps), drafts personalized follow-up emails, and escalates high-risk deals to leadership. Run fully autonomous or human-in-the-loop with safety scoring and rollback support.
  • AI-Adjusted Forecasting — Combines CRM pipeline data with historical win rates, rep bias calibration, and seasonality to produce forecasts with confidence intervals. Includes pipeline health scoring and revenue confidence indexing.
  • Weekly CRO Briefs — Auto-generated executive summaries with pipeline health, slipping deals, hidden risks, and recommended interventions. Export as Markdown or board-ready JSON.
  • Chat Agent — Natural language interface to query pipeline data, ask about deals, and get instant insights backed by real database queries with safe LIKE-pattern escaping.
  • Stripe Billing — 5-tier pricing with 7-day free trials, plan-gated features, and customer portal integration.
  • Multi-Tenant & RBAC — Full tenant isolation with role-based access control (admin/member/viewer), multi-level approval chains, and field-level safe-write allowlists.
  • Enterprise Security — SAML SSO, SCIM provisioning, immutable audit log, data retention policies (with chunked batch deletion), action rate limits, and safety scoring.
  • Self-Improving Intelligence — Continuous learning loop with outcome-calibrated risk weights, Brier score tracking, per-rep bias derivation, drift detection, and stage win rate time decay.
  • 10-Layer Intelligence System — Prediction verdicts with feedback loop, Thompson Sampling action bandit, Bayesian per-tenant personalization, automated feature discovery (point-biserial correlation + mutual information), temporal pattern learning, counterfactual A/B holdout testing, adversarial self-testing, multi-dimensional rep behavior modeling, ensemble scoring with disagreement detection, and meta-learning for automatic recalibration.
  • Intelligence Dashboard — Admin panel surfacing model health: Brier score trends, ensemble disagreement rates, adversarial robustness metrics, and top risk factor rankings. Deal detail pages show ensemble score breakdowns, stage win rates, temporal pattern matches, and rep behavior insights.
  • Internationalization — Full i18n support for English, French, German, and Italian with SEO hreflang and locale routing.

Architecture

apps/
├── web/          Next.js 16 (App Router) + shadcn/ui + Tailwind CSS
└── api/          Hono REST API on Node.js

packages/
├── db/           Drizzle ORM — schema, migrations, seeds
├── schemas/      Zod validation schemas + shared TypeScript types
└── agents/       AI agents (LangGraph + OpenAI, rule-based fallback)
┌──────────────┐     ┌──────────────┐     ┌──────────────┐
│   Next.js    │────▶│   Hono API   │────▶│  Supabase    │
│   Frontend   │     │   /v1/*      │     │  Postgres    │
└──────┬───────┘     └──────┬───────┘     └──────────────┘
       │                    │
   Supabase Auth     ┌──────┴───────┐     ┌──────────────┐
   (session-based)   │ CRM Connectors│    │ AI Agents    │
                     ├── HubSpot    │     │ (LangGraph)  │
                     ├── Salesforce │     │ ┌─ Risk      │
                     ├── Zoho CRM   │     │ ├─ Forecast  │
                     └── Gmail OAuth│     │ ├─ Hygiene   │
                                    │     │ ├─ Follow-up │
                                    │     │ ├─ Escalation│
                                    │     │ ├─ CRO Brief │
                                    │     │ └─ Chat      │
                                    │     └──────────────┘
                     ┌──────────────┐
                     │ Notifications│
                     ├── Slack      │
                     └── Email      │
                     └──────────────┘

AI Agents

Agent Purpose Trigger
Risk Score deal health (0–1), identify risk factors, explain signals Daily scan, webhooks, manual
Escalation Determine urgency level and notify leadership Auto-triggered when risk >= 0.7
Hygiene Suggest CRM field corrections (close date, next step, stage) After risk evaluation
Follow-up Draft personalized follow-up emails After risk evaluation
Forecast AI-adjusted pipeline forecast with confidence intervals Dashboard load, API call
CRO Brief Weekly executive summary with narrative and interventions Scheduled job (Monday 8am)
Chat Natural language pipeline queries with 7 DB-backed tools User chat interface

All agents use a hybrid architecture: LangGraph + OpenAI GPT-4o-mini (configurable via AGENT_MODEL) when OPENAI_API_KEY is set; otherwise they fall back to deterministic rule-based logic. A process-wide circuit breaker (3 consecutive failures, 60s cooldown) protects against cascading LLM failures, with optional multi-model fallback via AGENT_FALLBACK_MODEL.

Intelligence System

Module What It Does
Prediction Verdicts Snapshots full state at prediction time; backfills with actual outcomes for calibration
Action Bandit Thompson Sampling (Beta distribution) selects optimal agent actions per deal context
Tenant Personalization Bayesian Beta-Binomial conjugate updating of per-tenant stage win rates
Feature Discovery Point-biserial correlation + mutual information ranks risk factors automatically
Temporal Patterns Classifies deal trajectories (spike, gradual, plateau, recovery) and matches historical patterns
Counterfactual Holdout A/B testing with z-test for proportions to measure causal impact of agent interventions
Adversarial Testing Replays historical failures + synthetic edge cases through current model to detect regressions
Rep Profiles Multi-dimensional rep behavior: stage velocity, close rate by segment, CRM latency, suggestion response
Ensemble Scoring Parallel rule + logistic + LLM scoring with weighted merge; flags disagreement > 0.25 for human review
Meta-Learning Tracks Brier score trends, drift precision, calibration health; auto-adjusts hyperparameters

API Routes

22 route modules under /v1: actions, audit, auth, billing, briefs, chat, crm, deals, forecast, gmail, jobs, pipeline, plans, reports, scim, settings, signup, teams, roles, webhooks, admin, super-admin.

Orchestration

After every risk evaluation, orchestratePostRisk() chains downstream agents with tracked status via the orchestration_runs table. Downstream agents (Hygiene, Follow-up) can signal re-evaluation needs, which the daily risk scan picks up automatically.

Database

33+ tables managed by Drizzle ORM including tenants, users, plans, deals, deal_outcomes, risk_signals, agent_actions, agent_metrics, agent_accuracy, orchestration_runs, forecast_history, forecast_accuracy, rep_calibration, risk_calibration_samples, risk_calibration_metrics, risk_model_config, deal_sentiment_snapshots, stage_history, stage_win_rate_prior, drift_alerts, feature_importance, gmail_tokens, slack_tokens, audit_log, prediction_verdicts, action_rewards, action_arms, tenant_stage_win_rates, continuous_feature_importance, temporal_patterns, adversarial_test_results, rep_behavior_profiles, ensemble_scores, logistic_model_weights, meta_learning_metrics, and more.

Tech Stack

Layer Technology
Frontend Next.js 16, React, Tailwind CSS, shadcn/ui
API Hono, Node.js
Database PostgreSQL (Supabase)
ORM Drizzle
Validation Zod
AI LangGraph, OpenAI GPT-4o-mini
Auth Supabase Auth + SAML SSO
Billing Stripe (Checkout + Customer Portal)
CRM HubSpot, Salesforce, Zoho CRM
Email Gmail OAuth
Notifications Slack (per-tenant bot token), Email
Deployment Vercel (web), Vercel Serverless / Cloud Run (API)
Monorepo pnpm workspaces

Prerequisites

  • Node.js 20+
  • pnpm (this repo requires pnpm — do not use npm or yarn)
    corepack enable && corepack prepare pnpm@latest --activate
  • PostgreSQL — Supabase (recommended) or local

Getting Started

1. Install dependencies

pnpm install

2. Configure environment

cp .env.example .env

Edit .env with your credentials. Key variables:

Variable Required Description
DATABASE_URL Yes Supabase connection string or local Postgres
NEXT_PUBLIC_SUPABASE_URL Yes Supabase project URL
NEXT_PUBLIC_SUPABASE_ANON_KEY Yes Supabase anon/public key
NEXT_PUBLIC_API_URL Yes API URL (default: http://localhost:3001)
STRIPE_SECRET_KEY For billing Stripe secret key
OPENAI_API_KEY For AI agents OpenAI API key
AGENT_MODEL No LLM model name (default: gpt-4o-mini)
AGENT_FALLBACK_MODEL No Fallback LLM model (e.g. claude-3-5-haiku-20241022)
HUBSPOT_ACCESS_TOKEN For HubSpot HubSpot private app token
GOOGLE_CLIENT_ID For Gmail Google OAuth client ID
EXTRA_COMPETITORS No Comma-separated additional competitor names for email analysis

See .env.example for the full list.

3. Set up the database

pnpm db:create    # Create database (local only)
pnpm db:migrate   # Run migrations
pnpm db:seed      # Seed demo data (optional)
pnpm db:seed:plans  # Seed pricing plans

4. Run locally

# Terminal 1 — Web (http://localhost:3000)
pnpm dev

# Terminal 2 — API (http://localhost:3001)
pnpm dev:api

# Terminal 3 — Stripe webhooks (if testing billing)
stripe listen --forward-to localhost:3001/v1/billing/webhook

Deployment

Web (Vercel)

  1. Connect the repo to Vercel
  2. Set Root Directory to apps/web
  3. Set environment variables: NEXT_PUBLIC_API_URL, NEXT_PUBLIC_SUPABASE_URL, NEXT_PUBLIC_SUPABASE_ANON_KEY

API (Vercel Serverless / Cloud Run)

  1. Deploy apps/api to Vercel Serverless, Cloud Run, or any Node.js host
  2. Set DATABASE_URL and integration credentials (CRM, Gmail, Stripe)
  3. Point NEXT_PUBLIC_API_URL in the web app to the deployed API URL

Scheduled Jobs (Supabase pg_cron)

Configure pg_cron + pg_net extensions in Supabase. Add rows to public.cron_config table:

Job Schedule Endpoint
Daily risk scan 0 9 * * * (9am UTC) POST /v1/jobs/daily-risk-scan
Weekly brief 0 8 * * 1 (Mon 8am) POST /v1/jobs/deliver-weekly-brief
Data retention 0 2 * * * (2am UTC) POST /v1/jobs/apply-data-retention
Learning loop 0 3 * * 0 (Sun 3am) POST /v1/jobs/learning-loop
CRM sync 0 6 * * * (6am UTC) POST /v1/jobs/sync-deals-from-crm
Orphan retry */15 * * * * (every 15m) POST /v1/jobs/retry-orphaned-orchestrations

The learning loop now runs 17 steps: risk calibration → rep bias → forecast accuracy → drift detection → feature importance → verdict backfill → tenant win rates → rep profiles → continuous features → temporal patterns → logistic model training → adversarial testing → meta-learning.

Pricing Tiers

Plan Price Features
Pilot Free Core risk detection, 5 deals
Starter $49/mo Full pipeline, 50 deals
Growth $149/mo Forecast agent, weekly briefs
Enterprise $399/mo Chat agent, SAML SSO, SCIM
Enterprise+ $799/mo Dedicated support, custom integrations

All paid plans include a 7-day free trial.

CRM Integration

HubSpot

  • OAuth or Private App Token for deal sync and CRM writes
  • Webhooks: Subscribe to deal property changes → POST /v1/webhooks/hubspot
  • Webhook signature verified via HUBSPOT_CLIENT_SECRET

Salesforce

  • REST API with SALESFORCE_ACCESS_TOKEN + SALESFORCE_INSTANCE_URL
  • Webhooks: Platform Events / Change Data Capture → POST /v1/webhooks/salesforce
  • Signature verified via SALESFORCE_WEBHOOK_SECRET

Zoho CRM

  • REST API with ZOHO_ACCESS_TOKEN + ZOHO_API_DOMAIN
  • Supports deal sync, account name extraction, and owner mapping

Multi-Tenant Webhooks

For multiple tenants sharing one CRM org, append ?tenant_id=<uuid> to the webhook URL.

Security & Compliance

  • SAML SSO — Supabase SAML integration (docs/saml-sso.md)
  • SCIM — User provisioning API (docs/scim.md)
  • Audit Log — Immutable, append-only log of all sensitive operations
  • RBAC — Admin / Member / Viewer roles with field-level enforcement
  • Data Retention — Configurable per-tenant retention policies with automated pruning
  • Token Encryption — AES-256-GCM encryption for OAuth tokens at rest
  • Safety Scoring — 0–1 safety score per action; blocks auto-execution below threshold
  • Action Rate Limits — Per-tenant/deal rate limiting with 429 + Retry-After
  • SOC 2 / ISO — Compliance documentation (docs/soc2-overview.md)

Project Scripts

pnpm dev            # Start web app (Next.js)
pnpm dev:api        # Start API server (Hono)
pnpm build          # Build all packages and apps
pnpm db:migrate     # Run database migrations
pnpm db:generate    # Generate migrations from schema changes
pnpm db:seed        # Seed demo data
pnpm db:seed:plans  # Seed pricing plans with Stripe IDs
pnpm test           # Run API tests
pnpm test:all       # Run all tests

License

Proprietary. All rights reserved.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages