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
Quick Links
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.
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
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
- POST
/auth/loginwith{ email, password } - Auth service validates credentials against Supabase
- Returns signed Bridge JWT — store in
localStorage.bridge_token
Flow 2: OAuth PKCE (Google / GitHub)
- Login page calls
supabase.auth.signInWithOAuth({ provider }) - Browser redirects to Supabase OAuth → provider → back to
/auth-callback - auth-callback.html parses the URL hash/fragment, extracts the Supabase session
- POSTs
access_tokento/auth/token-exchange - Receives Bridge JWT — stored in localStorage and as a 7-day cookie
if (!supabase.isConfigured) check before invocation to avoid silent failures when env vars are not loaded.JWT Payload
{
"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
}
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
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:
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
Auto-Split Endpoint
POST /api/treasury/auto-split Authorization: Bearer <token> Content-Type: application/json { "amount_zar": 1000, "source": "marketplace_sale" }
Response:
{ "success": true, "split": { "user": 800, "ops": 100, "platform": 50, "burn": 50 }, "currency": "ZAR", "transaction_id": "txn_abc123" }
Wallet Balance
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:
activeorexpired - 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_idis null or undefined (null guard added 2026-04-25)
Generate Mission
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:
{ "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) / TTCwhere 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
| Phase | Method | Path | Description |
|---|---|---|---|
| 1 | POST | /api/aic/classify | Classify input signal into entity type + intent |
| 1 | POST | /api/aic/process | Main agent process — routes to swarm |
| 2 | POST | /api/aic/score | Opportunity score: (EDV × CP × SVM) / TTC |
| 2 | POST | /api/aic/simulate | Monte Carlo simulation of outcomes |
| 2 | POST | /api/aic/process-v2 | Enhanced process with scoring + reinvestment |
| 2 | GET | /api/aic/state | Current AIC pipeline state and metrics |
| 2 | GET | /api/aic/queue | Job queue depth per agent type |
| 3 | POST | /api/aic/close | Autonomous deal closure loop |
| 3 | GET | /api/aic/autonomy | Autonomy Index (0–100) |
| 3 | GET | /api/aic/intelligence | Intelligence report — anomalies and recommendations |
| 3 | GET | /api/aic/system | System manifest — full AIC configuration |
| 3 | POST | /api/aic/detect | Anomaly 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.
Authorization: Bearer <token> header on all authenticated requests. The Content-Type: application/json header is required for POST/PUT bodies.Authentication
| Method | Path | Auth | Description |
|---|---|---|---|
| GET | /auth/me | Required | Returns current user profile decoded from JWT |
| POST | /auth/token-exchange | Public | Exchanges Supabase access_token for Bridge JWT. Body: { access_token } |
| POST | /api/auth/root-token | Secret | Issues root JWT. Requires X-Zero-Trust-Secret header |
| POST | /auth/register | Public | Email/password registration. Body: { email, password, name } |
| POST | /auth/login | Public | Email/password login. Body: { email, password } |
Economy & Treasury
| Method | Path | Auth | Description |
|---|---|---|---|
| GET | /api/economy/me | Required | Wallet balance: ZAR + BRDG, total earned |
| POST | /api/treasury/auto-split | Required | Apply 4-way AEOS split. Body: { amount_zar, source } |
| GET | /api/treasury/splits | Required | Split transaction history and current balances |
| GET | /api/system/overview | Required | Full system state summary |
Missions
| Method | Path | Auth | Description |
|---|---|---|---|
| POST | /api/mission/generate | Required | Generate mission statement for entity |
| GET | /api/mission | Required | List all missions for current entity |
| GET | /api/mission/:id | Required | Get mission by ID |
| PUT | /api/mission/:id | Required | Update mission status or rules |
Leads & CRM
| Method | Path | Auth | Description |
|---|---|---|---|
| GET | /api/leads | Required | Paginated leads with AIC score |
| POST | /api/leads | Required | Create lead. Body: { name, email, company, source } |
| POST | /api/leads/:id/convert | Required | Convert lead to deal, triggers closer agent |
| POST | /api/leads/ai-generate | Required | AI-generate leads from ICP. Body: { industry, title, count } |
Platform Utilities
| Method | Path | Auth | Description |
|---|---|---|---|
| GET | /health | Public | Gateway health check. Returns { status: "OK", uptime } |
| GET | /api/brain/status | Required | Brain service health, version, agent count |
| POST | /ask | Required | Freeform AI query. Body: { query, context? } |
| GET | /api/apps | Required | List registered apps |
| POST | /api/apps | Required | Register app, generates API key |
| GET | /api/brands | Required | List brand profiles |
| POST | /api/brands | Required | Create brand profile |
| GET | /api/affiliates/me | Required | Affiliate stats and referral earnings |
| POST | /api/usage/event | Required | Record 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:
Processing a Task
// 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
// 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:
- Detects
#access_token=in the URL fragment from Supabase - Calls
supabase.auth.getSession()to confirm the session - POSTs the
access_tokento/auth/token-exchange - Receives Bridge JWT and stores it
- Redirects based on user state (see routing logic below)
localStorage Keys
| Key | Value | Notes |
|---|---|---|
| bridge_token | JWT string | Primary auth token — include in all API calls |
| bridge_user | JSON string | Decoded user object { id, email, role, plan, tier, wallet_id } |
Auth Cookie
Alongside localStorage, the Bridge JWT is set as an HTTP cookie:
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:
role === 'superadmin'→/dashboarduser.wizard === 1(setup not complete) →/wizarduser.plan === null(no plan selected) →/checkout- Otherwise →
/profile
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'); }
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
# 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
# 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
| Variable | Service | Description |
|---|---|---|
| SUPABASE_URL | All | Supabase project URL |
| SUPABASE_SERVICE_KEY | Auth, Gateway | Service role key — full DB access, never expose client-side |
| SUPABASE_ANON_KEY | Frontend | Anon key for client-side Supabase calls |
| JWT_SECRET | Auth, Gateway | HMAC secret for Bridge JWT signing/verification |
| ZERO_TRUST_SECRET | Gateway | System-to-system root token secret |
| GOOGLE_CLIENT_ID | Auth | Google OAuth client ID for PKCE flow |
| GOOGLE_CLIENT_SECRET | Auth | Google OAuth client secret |
Health Check
# 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.
- 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/
- PKCE auth flow complete rewrite — auth-callback.html rebuilt from scratch
- supabase.js
isConfiguredguard added to prevent silent failures - nginx exchange-code routing fix — POST /auth/token-exchange now correctly proxied
/admin/dashboardredirect chain fixed — superadmins land on correct dashboard- Google OAuth client ID and secret added to env blob
- 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
missionsandtreasury_splitstables created and seeded
- 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