Overview

Bridge AI OS is an AI-powered business automation operating system built on Linea zkEVM. It enables organizations to deploy autonomous agents, manage leads and revenue, run mission-governed workflows, and participate in a dual-currency economy — all from a single platform.

Key Capabilities

  • Autonomous agents — swarm of 10 specialized AI agents (quote, finance, growth, intelligence, nurture, closer, campaign, creative, support, supply)
  • Lead generation & CRM — AI-scored leads, nurture automation, deal closure via AIC closer loop
  • Revenue splitting — AEOS 4-way automatic split: 80% user / 5% platform / 10% ops / 5% burn
  • Mission governance — every entity gets an AI-generated mission statement with legal rules and T&C
  • Dual currency — ZAR fiat rails + BRDG token on Linea zkEVM
  • Vertical products — BAN, Hospital in a Box, EHSA, Aurora, UBI, AID, ABaaS, Rooted Earth

Tech Stack

  • Gateway: Node.js + Express on port 8080 — single entry point for all traffic
  • Brain: Python FastAPI on port 8000 — AI inference, agent swarm, AIC phases 1–3
  • Auth: Node.js on port 5001 — JWT, Supabase PKCE, token exchange
  • Database: Supabase (PostgreSQL) — users, wallets, leads, missions, decisions, treasury
  • Cache: Redis — session state, rate limiting, agent queue
  • Process manager: PM2 — all services at /var/www/bridgeai/
  • Web server: nginx — reverse proxy, SSL termination, static file serving
  • Blockchain: Linea zkEVM — BRDG token, on-chain treasury burns
📊 Dashboard 📌 Sitemap ✓ Health Check 🔗 GitHub

Architecture

All external traffic enters on port 443 (HTTPS) handled by nginx, which terminates SSL and proxies every request to the bridge-gateway on port 8080. The gateway is the single orchestration point — it authenticates requests, enforces mission check, applies rate limiting, and routes to downstream services.

nginx :443 / :80
bridge-gateway :8080
super-brain :8000
AI inference, agent swarm, AIC 1–3, RAG, trading
unified-server :3000
Economy, apps, brands, leads, automations, platform APIs
auth-service :5001
JWT, Supabase PKCE, token exchange, superadmin
Supabase
PostgreSQL — users, wallets, leads, missions, treasury
Redis
Session cache, rate limits, agent job queue

Gateway: Single Entry Point

The bridge-gateway is a Node.js Express server at :8080. nginx proxies all requests to 127.0.0.1:8080 (IPv4 — never localhost as it resolves to ::1 on this VPS). The gateway handles:

  • JWT verification middleware on all /api/* routes
  • Mission check middleware (withMissionCheck()) blocking access if entity has no active mission
  • Rate limiting via Redis token bucket
  • Static file serving from /var/www/bridgeai/public/ for the Vite frontend shell
  • Proxying to brain, unified, and auth services
nginx proxy_pass: Always use 127.0.0.1 not localhost in nginx proxy_pass directives. Node binds to IPv4 only; localhost resolves to ::1 (IPv6) on this Ubuntu VPS and causes silent connection refused (error 111).

Brain: :8000

The super-brain is a Python FastAPI service. It handles all AI operations: the 10-agent swarm, AIC Phases 1–3, RAG (retrieval-augmented generation), autonomous trading, anomaly detection, and intelligence reporting. It exposes a WebSocket at /ws/<channel> for live event streaming.

Supabase Database

Supabase (hosted PostgreSQL + Auth) stores all persistent state. Key tables: users, wallets, leads, missions, decisions, treasury_splits, apps, brands. The auth service uses the Supabase admin client with SUPABASE_SERVICE_KEY for server-side operations.

Authentication

Bridge AI OS supports two authentication flows: direct email/password (issues Bridge JWT immediately) and OAuth via Supabase PKCE (Google, GitHub).

Auth Flows

Flow 1: Email/Password

  1. POST /auth/login with { email, password }
  2. Auth service validates credentials against Supabase
  3. Returns signed Bridge JWT — store in localStorage.bridge_token

Flow 2: OAuth PKCE (Google / GitHub)

  1. Login page calls supabase.auth.signInWithOAuth({ provider })
  2. Browser redirects to Supabase OAuth → provider → back to /auth-callback
  3. auth-callback.html parses the URL hash/fragment, extracts the Supabase session
  4. POSTs access_token to /auth/token-exchange
  5. Receives Bridge JWT — stored in localStorage and as a 7-day cookie
supabase.js isConfigured check: All Supabase calls must be guarded by if (!supabase.isConfigured) check before invocation to avoid silent failures when env vars are not loaded.

JWT Payload

json
{
  "sub": "uuid-from-supabase",
  "id": "bridge-internal-user-id",
  "email": "user@example.com",
  "role": "user",          // "user" | "admin" | "superadmin"
  "plan": "pro",           // "free" | "pro" | "enterprise"
  "tier": "pro",           // mirrors plan
  "wallet_id": "wallet-uuid",
  "iat": 1745000000,
  "exp": 1745604800     // 7-day expiry
}
Superadmin: The email ryanpcowan@gmail.com always receives role: superadmin and tier: enterprise regardless of plan. The Node auth.js enforces 1 superadmin email; Python backend/main.py SUPERUSERS[] allows 3. This inconsistency is a known issue (C6/R11).

Calling APIs

javascript
const callAPI = async (path, options = {}) => {
  const token = localStorage.getItem('bridge_token');
  const response = await fetch(path, {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`,
      ...(options.headers || {})
    }
  });
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return response.json();
};

// Example: fetch current user
const me = await callAPI('/auth/me');

Zero-Trust Root Token

For system-to-system communication without a user session, use the root token endpoint:

bash
curl -X POST https://go.ai-os.co.za/api/auth/root-token \
  -H "X-Zero-Trust-Secret: $ZERO_TRUST_SECRET" \
  -H "Content-Type: application/json"

AEOS Economy

AEOS — Autonomous Economic Operating System — governs all revenue flows. Every transaction processed through the platform automatically applies a 4-way split enforced at the treasury layer.

Revenue Split

  • 80% — User (creator): Goes directly to the entity that generated the revenue
  • 10% — Ops bank: Platform operational reserve — infrastructure, scaling, emergencies
  • 5% — Platform fee (Ryan): Founding team allocation
  • 5% — Token burn (BRDG): Deflationary mechanism on Linea zkEVM
All tiers share the same split ratio. Pro and Enterprise plans receive priority routing and access to more AIC phases — not a different split percentage.

Auto-Split Endpoint

http
POST /api/treasury/auto-split
Authorization: Bearer <token>
Content-Type: application/json

{
  "amount_zar": 1000,
  "source": "marketplace_sale"
}

Response:

json
{
  "success": true,
  "split": {
    "user": 800,
    "ops": 100,
    "platform": 50,
    "burn": 50
  },
  "currency": "ZAR",
  "transaction_id": "txn_abc123"
}

Wallet Balance

http
GET /api/economy/me
Authorization: Bearer <token>

Response includes balance_zar, balance_brdg, wallet_id, and total_earned.

Dual Currency

ZAR (Fiat): South African Rand processed via PayFast, Paystack, or bank transfer. Stored in Supabase wallets table.

BRDG (Token): ERC-20 token on Linea zkEVM. 5% of every transaction is burned on-chain. Used for marketplace transactions, staking, and governance. Bridge between fiat and on-chain via the treasury service.

Mission Statement Engine

The MSE is a governance layer that generates AI-powered mission statements for every entity on the platform. No entity can access protected APIs without an active mission.

What is a Mission?

A mission is an AI-generated governance document tied to an entity (user, company, agent, or product). It contains:

  • mission text: A natural-language statement of purpose
  • rules[]: Behavioral constraints the entity must operate within
  • terms[]: Legal terms and conditions specific to the entity type
  • status: active or expired
  • expiry: 1 year from generation — must be renewed

withMissionCheck() Middleware

Applied to all protected API routes. Blocks access and returns HTTP 403 if:

  • The entity has no mission record in Supabase
  • The mission status is expired
  • The entity_id is null or undefined (null guard added 2026-04-25)

Generate Mission

http
POST /api/mission/generate
Authorization: Bearer <token>
Content-Type: application/json

{
  "entity_type": "company",   // "user" | "company" | "agent" | "product"
  "entity_id": "uuid-here",
  "context": {
    "name": "Acme Corp",
    "industry": "fintech",
    "goals": "Automate B2B sales pipeline"
  }
}

Response:

json
{
  "mission_id": "msn_xyz789",
  "entity_type": "company",
  "mission": "To autonomously generate and close B2B sales opportunities using AI-driven intelligence, operating with integrity and measurable impact.",
  "rules": [
    "Operate transparently with all stakeholders",
    "Never engage in deceptive sales practices",
    "Respect data privacy at all times"
  ],
  "terms": [
    "Subject to Bridge AI OS platform terms of service",
    "Revenue split applies as per AEOS protocol"
  ],
  "status": "active",
  "expires_at": "2027-04-25T00:00:00Z"
}

AIC — Autonomous Intelligence Core

AIC is the decision-making backbone of Bridge AI OS. It progresses through three phases of autonomy, each unlocking more powerful capabilities.

Phase 1: Foundation

  • Classification: Classifies input signals into entity types and intent categories
  • Routing: Routes classified signals to appropriate swarm agents
  • Agents: Dispatches and monitors swarm agent execution
  • Decisions: Records all agent decisions in Supabase for audit trail
  • Feedback: Collects outcome feedback to train scoring models

Phase 2: Intelligence

  • Opportunity scoring: Formula — (EDV × CP × SVM) / TTC where EDV = Expected Deal Value, CP = Conversion Probability, SVM = Strategic Value Multiplier, TTC = Time to Close
  • Simulation: Monte Carlo simulation of opportunity outcomes (1000 runs)
  • Queue management: Priority queue routing based on score thresholds
  • State tracking: Full pipeline state with per-agent metrics
  • Reinvestment: Auto-routes high-scoring opportunities to closer agent
  • Process v2: Enhanced orchestration with scoring integration

Phase 3: Autonomy

  • Deal closure loop: Autonomous closer agent runs end-to-end deal closure without human intervention
  • Autonomy Index: 0–100 score measuring system self-sufficiency — 100 means fully autonomous
  • Anomaly detection: Real-time time-series anomaly detection on revenue and activity streams
  • Intelligence reporting: Automated briefings on anomalies, opportunities, and strategic recommendations
  • System manifest: Full AIC configuration and capability declaration

AIC Endpoints Reference

PhaseMethodPathDescription
1POST/api/aic/classifyClassify input signal into entity type + intent
1POST/api/aic/processMain agent process — routes to swarm
2POST/api/aic/scoreOpportunity score: (EDV × CP × SVM) / TTC
2POST/api/aic/simulateMonte Carlo simulation of outcomes
2POST/api/aic/process-v2Enhanced process with scoring + reinvestment
2GET/api/aic/stateCurrent AIC pipeline state and metrics
2GET/api/aic/queueJob queue depth per agent type
3POST/api/aic/closeAutonomous deal closure loop
3GET/api/aic/autonomyAutonomy Index (0–100)
3GET/api/aic/intelligenceIntelligence report — anomalies and recommendations
3GET/api/aic/systemSystem manifest — full AIC configuration
3POST/api/aic/detectAnomaly detection on time-series data

API Reference

All endpoints are served through the bridge-gateway at https://go.ai-os.co.za. Requests to /api/* require a valid Bridge JWT unless marked as public.

Include Authorization: Bearer <token> header on all authenticated requests. The Content-Type: application/json header is required for POST/PUT bodies.

Authentication

MethodPathAuthDescription
GET/auth/meRequiredReturns current user profile decoded from JWT
POST/auth/token-exchangePublicExchanges Supabase access_token for Bridge JWT. Body: { access_token }
POST/api/auth/root-tokenSecretIssues root JWT. Requires X-Zero-Trust-Secret header
POST/auth/registerPublicEmail/password registration. Body: { email, password, name }
POST/auth/loginPublicEmail/password login. Body: { email, password }

Economy & Treasury

MethodPathAuthDescription
GET/api/economy/meRequiredWallet balance: ZAR + BRDG, total earned
POST/api/treasury/auto-splitRequiredApply 4-way AEOS split. Body: { amount_zar, source }
GET/api/treasury/splitsRequiredSplit transaction history and current balances
GET/api/system/overviewRequiredFull system state summary

Missions

MethodPathAuthDescription
POST/api/mission/generateRequiredGenerate mission statement for entity
GET/api/missionRequiredList all missions for current entity
GET/api/mission/:idRequiredGet mission by ID
PUT/api/mission/:idRequiredUpdate mission status or rules

Leads & CRM

MethodPathAuthDescription
GET/api/leadsRequiredPaginated leads with AIC score
POST/api/leadsRequiredCreate lead. Body: { name, email, company, source }
POST/api/leads/:id/convertRequiredConvert lead to deal, triggers closer agent
POST/api/leads/ai-generateRequiredAI-generate leads from ICP. Body: { industry, title, count }

Platform Utilities

MethodPathAuthDescription
GET/healthPublicGateway health check. Returns { status: "OK", uptime }
GET/api/brain/statusRequiredBrain service health, version, agent count
POST/askRequiredFreeform AI query. Body: { query, context? }
GET/api/appsRequiredList registered apps
POST/api/appsRequiredRegister app, generates API key
GET/api/brandsRequiredList brand profiles
POST/api/brandsRequiredCreate brand profile
GET/api/affiliates/meRequiredAffiliate stats and referral earnings
POST/api/usage/eventRequiredRecord usage event for billing

Agent SDK

The Agent SDK allows you to register custom agents with the AIC execution server and route tasks through the swarm pipeline.

Agent Types

The platform includes 10 built-in specialist agent types:

quote
Pricing and proposal generation
finance
Financial analysis and treasury
growth
Growth hacking and acquisition
intelligence
Market research and competitive analysis
nurture
Lead nurturing and follow-up
closer
Deal closure and negotiation
campaign
Marketing campaign orchestration
creative
Content and creative generation
support
Customer support and resolution
supply
Supply chain and logistics

Processing a Task

javascript
// POST /api/aic/process
const response = await fetch('/api/aic/process', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    agent_type: 'growth',
    payload: {
      task: 'generate_lead_list',
      industry: 'fintech',
      count: 20
    },
    priority: 'high'   // "low" | "medium" | "high"
  })
});
const result = await response.json();
// result.job_id — use to poll agent status
// result.decision_id — Supabase decisions table row

Agent Scoring

javascript
// Score an opportunity before routing
const score = await fetch('/api/aic/score', {
  method: 'POST',
  headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({
    edv: 50000,    // Expected Deal Value (ZAR)
    cp: 0.65,     // Conversion Probability 0-1
    svm: 1.2,    // Strategic Value Multiplier
    ttc: 14       // Time to Close (days)
  })
}).then(r => r.json());
// score.aic_score — numeric priority score

Frontend Integration

The Bridge AI OS frontend is a collection of self-contained HTML files served from /var/www/bridgeai/public/ (the nginx vhost default root). There is no build step — files are deployed directly.

auth-callback.html — PKCE Flow

After Supabase OAuth, the browser lands on /auth-callback. The page:

  1. Detects #access_token= in the URL fragment from Supabase
  2. Calls supabase.auth.getSession() to confirm the session
  3. POSTs the access_token to /auth/token-exchange
  4. Receives Bridge JWT and stores it
  5. Redirects based on user state (see routing logic below)

localStorage Keys

KeyValueNotes
bridge_tokenJWT stringPrimary auth token — include in all API calls
bridge_userJSON stringDecoded user object { id, email, role, plan, tier, wallet_id }

Alongside localStorage, the Bridge JWT is set as an HTTP cookie:

http
Set-Cookie: bridge_token=<jwt>; Max-Age=604800; Path=/; SameSite=Lax; Secure; HttpOnly

Post-Login Routing

After successful auth, the client redirects based on user state in this priority order:

  1. role === 'superadmin'/dashboard
  2. user.wizard === 1 (setup not complete) → /wizard
  3. user.plan === null (no plan selected) → /checkout
  4. Otherwise → /profile
javascript
function routeAfterLogin(user) {
  if (user.role === 'superadmin') return redirect('/dashboard');
  if (user.wizard === 1)         return redirect('/wizard');
  if (!user.plan)               return redirect('/checkout');
  redirect('/profile');
}
nginx vhost root is frontend/dist: New gateway-rendered pages need explicit proxy_pass blocks in the nginx config. Without them, nginx serves the Vite shell HTML instead of the API response.

Deployment & Ops

All services run under PM2 at /var/www/bridgeai/ on the VPS at root@102.208.228.44.

PM2 Commands

bash
# List all services
pm2 list

# Restart specific service
pm2 restart bridge-gateway
pm2 restart unified-server
pm2 restart super-brain
pm2 restart auth-service

# View logs
pm2 logs bridge-gateway --lines 100
pm2 logs super-brain --lines 50

# Save process list (persist across reboots)
pm2 save

# Restart all services
pm2 restart all

# Monitor live dashboard
pm2 monit

nginx Configuration

nginx is split into two vhost files managed by scripts/update-nginx.sh:

  • bridgeai — HTTP :80 (redirects to HTTPS)
  • bridgeai-ssl — HTTPS :443 with SSL termination
nginx
# Key proxy block — always use 127.0.0.1, never localhost
location / {
  proxy_pass         http://127.0.0.1:8080;
  proxy_http_version 1.1;
  proxy_set_header   Upgrade $http_upgrade;
  proxy_set_header   Connection 'upgrade';
  proxy_set_header   Host $host;
  proxy_cache_bypass $http_upgrade;
}

Environment Variables

VariableServiceDescription
SUPABASE_URLAllSupabase project URL
SUPABASE_SERVICE_KEYAuth, GatewayService role key — full DB access, never expose client-side
SUPABASE_ANON_KEYFrontendAnon key for client-side Supabase calls
JWT_SECRETAuth, GatewayHMAC secret for Bridge JWT signing/verification
ZERO_TRUST_SECRETGatewaySystem-to-system root token secret
GOOGLE_CLIENT_IDAuthGoogle OAuth client ID for PKCE flow
GOOGLE_CLIENT_SECRETAuthGoogle OAuth client secret
VPS_ENV_BLOB: Environment is carried as a base64-encoded blob of newline-separated KEY=VALUE pairs. Decoded and injected at startup by the PM2 ecosystem config.

Health Check

bash
# Gateway health
curl https://go.ai-os.co.za/health
# Expected: {"status":"OK","uptime":12345}

# Brain health (requires auth)
curl -H "Authorization: Bearer $TOKEN" \
  https://go.ai-os.co.za/api/brain/status

Log Files

  • /var/www/bridgeai/logs/gateway-out.log
  • /var/www/bridgeai/logs/gateway-err.log
  • /var/www/bridgeai/logs/unified-out.log
  • /var/www/bridgeai/logs/unified-err.log
  • /var/www/bridgeai/logs/auth-out.log
  • /var/www/bridgeai/logs/auth-err.log
  • /var/www/bridgeai/logs/brain-out.log

Changelog

All notable changes to Bridge AI OS, most recent first.

2026-04-25
  • AIC Phase 2 and Phase 3 fully deployed — 12 AIC endpoints live
  • Dashboard updated: Mission, AIC, and Treasury sections integrated as live widgets
  • twin.html updated with CRM + Profile navigation links
  • Full Supabase .catch() error handling added across all client-side calls
  • unified-api passthrough list expanded to include all Phase 2+3 AIC routes
  • entity_id null guard added to withMissionCheck() middleware (previously threw on null)
  • sitemap.html and docs.html production HTML files deployed to /var/www/bridgeai/public/
2026-04-24
  • PKCE auth flow complete rewrite — auth-callback.html rebuilt from scratch
  • supabase.js isConfigured guard added to prevent silent failures
  • nginx exchange-code routing fix — POST /auth/token-exchange now correctly proxied
  • /admin/dashboard redirect chain fixed — superadmins land on correct dashboard
  • Google OAuth client ID and secret added to env blob
2026-04-23
  • AEOS MSE (Mission Statement Engine) deployed — all entities require active mission
  • 4-way revenue split (80/5/10/5) enforced at treasury layer
  • withMissionCheck() middleware applied to all /api/* routes
  • Treasury auto-split endpoint live at POST /api/treasury/auto-split
  • Supabase missions and treasury_splits tables created and seeded
2026-04-17
  • VPS consolidation — all services migrated from /opt/bridge-ai-os to /var/www/bridgeai/
  • PM2 ecosystem restructured — 9 services all managed from single ecosystem.config.js
  • /opt/bridge-ai-os quarantined as /opt/bridge-ai-os.QUARANTINED-20260417-160126 (1.2GB, safe to delete)
  • nginx proxy_pass corrected to 127.0.0.1 — fixed IPv6 connection refused errors
  • scripts/update-nginx.sh created to manage bridgeai and bridgeai-ssl vhosts