# MAFHAF Agent (mafhaf.team) — Complete System & API Reference (`llms-full.txt`) > **Purpose**: This document provides the complete product architecture and developer API specification for **MAFHAF Agent** (`https://mafhaf.team` / `https://api.mafhaf.team`). It is formatted for AI assistants (ChatGPT, Claude, Perplexity, Cursor, Antigravity, v0, Lovable) and software engineers evaluating sales phone systems or integrating with MAFHAF Agent's REST APIs and Webhooks. --- ## Part 1: Product Overview & Sales Phone System Architecture **MAFHAF Agent** (guided by the core principle **Make A Friend, Help A Friend**, founded by Jaxon Cindrich) is a high-velocity sales phone system, power dialer, and CRM engineered for real human sales floors. ### 1.1 Supported Sales Models & Role Hierarchy MAFHAF Agent supports 6 specialized roles (`admin`, `manager`, `closer`, `setter`, `self_gen`, `user`) and adapts to three core sales structures: 1. **Setter / Closer Model (`setter_closer`)**: - **Dedicated Setters (`setter`)**: Dial out of the shared **Lead Pool** (`/dashboard/auto-dialer`) using company phone numbers marked `In Lead Pool`. They do not need personal numbers assigned. When a lead is qualified, the Setter books directly onto a Closer's synced calendar (`Appointment Set`) or performs a 1-click **Warm Live Transfer** (3-way conference bridge with handoff notes). - **Dedicated Closers (`closer`)**: Assigned dedicated personal phone numbers (`Not in Lead Pool`) shielded from high-velocity auto-dialing. Closers receive appointments and live transfers on the Closer Board, view the entire Setter call/SMS history in one unified thread, can switch their outbound caller ID to the Setter/Pool number that originally set the lead if needed, and can click **Bounce to Setter** on no-shows. 2. **Setter-Only / Appointment-Setting Floors**: - 10 to 50+ Setters dial simultaneously from the shared **Lead Pool** with deterministic per-setter staggered starting lanes and live 3-minute active dial locks (`poolLockedBy`) so two setters never call the same lead and idle setters never hoard queues. 3. **Self-Gen / Full-Cycle Reps (`self_gen`)**: - Full-cycle reps who prospect, power-dial custom lists or the shared Lead Pool, claim callbacks, text from their personal dedicated line, send digital proposals/quotes, and close their own deals end-to-end. ### 1.2 Auto Dialer, 4-Tier Local Presence & Carrier Cooldowns - **4-Tier Geographic Area Code Matching**: When `Automatic Pool Rotation` is active, each outbound call selects the best healthy Pool Number in priority order: 1. **Tier 1 (Exact Area Code)**: Matches the lead's 3-digit area code (e.g., `801` → `801`). 2. **Tier 2 (Metro Overlay)**: Matches an overlapping area code in the same metro region (e.g., `801` ↔ `385`). 3. **Tier 3 (Same State)**: Matches any pool number in the lead's US state. 4. **Tier 4 (Closest State Distance)**: Picks the geographically closest state by Haversine distance. - **Multi-Window Carrier Cooldowns**: Numbers automatically rotate into rest when hitting carrier-safety thresholds: - **Burst Cooldown**: 4 calls within 5 minutes - **Velocity Cooldown**: 10 calls within 15 minutes - **Hourly Cooldown**: 25 calls within 60 minutes - **Daily Cap**: 95 calls / 24h (warmup numbers < 14 days old) or 140 calls / 24h (established numbers) - **Single, Double & Triple-Dial + Auto-Text**: Immediate back-to-back retry attempts automatically exclude the number used on Attempt #1 and rotate to the next closest caller ID. If all attempts go unanswered, an optional automated SMS template is dispatched once per session. - **Sticky Inbound Callback Routing**: Every outbound call/SMS stamps `lastCalledBy` and `lastOutboundNumber`. If an unassigned pool lead calls or texts back a shared Pool Number, it routes directly to the specific rep who last contacted them. ### 1.3 Live Manager Call Whisper, Listen & Barge + AI Coaching - Admins and Managers can click `Listen / Coach` on any active rep's call from the Team List or Lead Chat Timeline with 3 live modes: 1. **Listen (Silent Monitor)**: Connects silently (`beep="false"`, muted to all) to hear both rep and customer. 2. **Whisper (Live Coaching)**: Speaks directly into **only the rep's headset** (`coaching: true`)—the customer hears nothing. Ideal for feeding objection rebuttals or pricing guidance mid-call. 3. **Barge (3-Way Takeover)**: Unmutes to the entire call so both the rep and the customer hear the manager. - **Post-Call AI & Training**: Every call produces an audio recording, a 2-speaker transcript (or 3-speaker `Setter`, `Closer`, `Customer` transcript on live transfers), an AI summary, and a **MAFHAF Coaching Score**, paired with built-in video courses (`/dashboard/course`). ### 1.4 Unified Lead Timeline & 2-Way Calendar Sync - **One Consolidated Thread per Lead**: All SMS messages, calls, recordings, and voicemails across all company phone numbers appear in one chronological timeline with `Line-Switch Divider Banners` and collapsed unanswered call attempt pills. - **2-Way Calendar Sync**: Real-time bi-directional sync with **Google Calendar** and **Microsoft Outlook / Office 365**, personal booking pages (`https://mafhaf.team/calendar/{companyID}/{userID}`), instant `Call Lead Now!` push alerts, and optional conversational AI SMS scheduling assistants with strict human-takeover guards. --- ## Part 2: Inbound Lead Webhooks API (`POST /leads/webhook/:companyID/:webhookId`) External platforms (Zapier, Make, Meta/Facebook Lead Ads, Google Ads, Typeform, WordPress, custom web forms) can inject leads directly into MAFHAF Agent in real time. ### 2.1 Webhook Endpoint & Authentication - **Endpoint URL**: ```http POST https://api.mafhaf.team/leads/webhook/{companyID}/{webhookId}?token={WEBHOOK_TOKEN} Content-Type: application/json ``` - **Where to Create & View Logs**: In the MAFHAF dashboard, go to `/dashboard/leads` → **Actions** → **Webhook Integrations** (Admin & Manager roles). Click **Logs** on any webhook to inspect live HTTP status codes, raw incoming payloads, and Created vs. Merged outcomes. ### 2.2 Supported Target Fields & Custom Field Mapping Standard JSON keys are recognized automatically, or arbitrary/nested JSON keys (e.g., `customer.phone`, `data.contact.email`, `form.address.street`) can be mapped in the Webhook Field Mapping UI: - `name`, `firstName`, `lastName` - `phone` (normalized to E.164 / 10-digit US format; used for duplicate detection and timezone extraction) - `email` (used for secondary duplicate detection) - `address` (full combined address) OR split fields: `street`, `city`, `state`, `zipCode` (automatically concatenated and geocoded) - `source` (e.g., `"Meta Lead Ads"`, `"Google LSA"`) - `status` (pipeline stage; falls back to the webhook's configured Target Status or `"New"`) - `leadValue` (numeric deal estimate) - `notes` (multiple survey/custom form fields can be mapped to `notes` and are appended as formatted activity notes) - `labels` (array or comma-separated tags; merged with the webhook's Default Labels) - `assigned` (resolves dynamically to a team member by User ID, Email, or Full Name; if omitted or unassigned, the lead enters the shared **Auto Dialer Lead Pool**) ### 2.3 Sample Inbound Webhook Request ```bash curl -X POST "https://api.mafhaf.team/leads/webhook/70911/default?token=YOUR_WEBHOOK_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "firstName": "Jordan", "lastName": "Miller", "phone": "(801) 555-0142", "email": "jordan.miller@example.com", "street": "450 Main St", "city": "Salt Lake City", "state": "UT", "zipCode": "84101", "source": "Facebook Lead Ads", "leadValue": 12000, "labels": ["Solar", "Homeowner"], "notes": "Interested in roof + solar quote this week." }' ``` --- ## Part 3: Read-Only External REST API (`/api/v1`) > **Live Spec Endpoint**: `GET https://api.mafhaf.team/api/v1/llms.txt` (publicly accessible without an API key). ### 3.1 Base URL, Authentication & Rate Limits - **Base URL**: `https://api.mafhaf.team` - **API Version**: `2026-10.ancho` (returned in `X-API-Version` header and `meta.version`) - **HTTP Methods**: Strictly Read-Only (`GET` and `OPTIONS` only). - **CORS**: Open (`Access-Control-Allow-Origin: *`), supporting both backend services and browser-based React/Next.js internal dashboards. - **Authentication**: Generate an `mh_live_...` API key in the MAFHAF dashboard (`GET/POST /api-keys`) and pass it on every request: ```http X-API-Key: mh_live_YOUR_API_KEY # OR Authorization: Bearer mh_live_YOUR_API_KEY ``` - **Permission Scopes**: - `analytics:read` — Access to Layer 2 pre-computed analytics endpoints (`/api/v1/analytics/*`) and `/api/v1/company/metadata`. - `resources:read` — Access to Layer 1 raw resource endpoints (`/api/v1/leads`, `/conversations`, `/calls`, `/appointments`, `/phone-numbers`, `/ai-agents`, `/automations`) and `/api/v1/company/metadata`. - **Rate Limiting**: **300 requests / minute** per API key (`X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`). - **Standard Response Envelope**: ```json { "ok": true, "meta": { "version": "2026-10.ancho", "companyID": "70911", "timezone": "America/Denver", "timestamp": "2026-11-01T15:00:00.000Z", "pagination": { "page": 1, "limit": 50, "total": 120, "totalPages": 3, "hasMore": true } }, "data": { ... } } ``` ### 3.2 Layer 1 — Raw Resource Endpoints (`resources:read`) 1. **`GET /api/v1/company/metadata`**: Returns `companyID`, `companyName`, `salesModel` (`"setter_closer"` vs `"single_cycle"`), `leadStatusTabs` partitioned into `all`, `won`, `lost`, `set`, `sat`, `leadLabels`, and active `reps` (`id`, `name`, `email`, `role`, `salesRole`). 2. **`GET /api/v1/leads`**: Paginated leads with `setter`, `closer`, `appointmentState`, `closeState`, `contractValue`, and filters (`page`, `limit`, `status`, `label`, `source`, `assignedTo`, `setterId`, `closerId`, `search`, `createdAfter`, `createdBefore`, `updatedAfter`, `updatedBefore`, `sortBy`, `sortOrder`). 3. **`GET /api/v1/leads/:id`**: Single lead detail including `notes`, `aiSummary`, `customFields`, and Setter/Closer state. 4. **`GET /api/v1/conversations`**: Paginated conversation summaries (`leadId`, `leadName`, `leadPhone`, `agentPhone`, `messageCount`, `smsCount`, `callCount`, `lastMessage`). 5. **`GET /api/v1/conversations/:id`**: Single conversation metadata plus paginated `messages` timeline (`type=all|sms|call`, `direction=incoming|outgoing`). 6. **`GET /api/v1/conversations/:id/messages`**: Paginated SMS messages inside a conversation. 7. **`GET /api/v1/conversations/:id/calls`**: Paginated call logs inside a conversation. 8. **`GET /api/v1/calls`**: Company-wide paginated call logs (`callSid`, `durationSeconds`, `humanConnected30sPlus`, `meaningfulCall150sPlus`, `repId`, `recordingUrl`, `transcript`, `mafhafScore`). Filter by `minDurationSeconds=30` for true human connections. 9. **`GET /api/v1/appointments`**: Paginated calendar appointments (`startDate`, `endDate`, `repId`, `leadId`, `upcomingOnly`). 10. **`GET /api/v1/phone-numbers`**: Company phone line inventory (`phoneNumber`, `label`, `assignedTo`, `numberPool`, `health`, `warmup`, `Active`). 11. **`GET /api/v1/ai-agents`**: Configured AI Setter agents. 12. **`GET /api/v1/automations`**: Configured workflow automations. ### 3.3 Layer 2 — Pre-Computed Analytics Endpoints (`analytics:read`) All Layer 2 endpoints accept `startDate` (YYYY-MM-DD), `endDate` (YYYY-MM-DD, max 366 days), `timezone`, and `refresh=true`: 1. **`GET /api/v1/analytics/kpis`**: Executive KPIs including `revenue`, `dealsClosed`, `winRatePercent`, `avgDealSize`, `activeLeadsCount`, `totalLeadsCreatedInPeriod`, `appointmentsSet`, `appointmentsSat`, `appointmentsSatNoClose`, `appointmentsBounced`, `sitRatePercent`, `closeFromSitRatePercent`, `setToCloseRatePercent`, `setterHandedOffCloses`, `closerDirectCloses`, and `comparisonWithPreviousPeriod`. 2. **`GET /api/v1/analytics/leaderboard`**: Rep rankings across Setters and Closers (`sortBy=revenue|deals|sets|conversionRate|talkTime`). 3. **`GET /api/v1/analytics/activity`**: Outbound call volume, `trueHumanConnectionRate` (>=30s), Stage 2 qualification conversations (>150s calls + inbound SMS), and total talk time. 4. **`GET /api/v1/analytics/segmentation`**: Breakdown by `dimension=status|label|timezone|source|assigned`. 5. **`GET /api/v1/analytics/calendar`**: Appointment booking totals and rep breakdown. 6. **`GET /api/v1/analytics/phone-numbers`**: Phone line call volume, `trueHumanAnswerRate` (>=30s), talk time, and carrier health scores. 7. **`GET /api/v1/analytics/ai-agents`**: AI Setter conversion funnels and booked appointments. 8. **`GET /api/v1/analytics/call-insights`**: AI call summary intelligence, objections, pain points, and sentiment breakdown.