{
  "markdown": "# Magpipe - A Conversational Platform\n\nMagpipe is a a conversational platform that manages SMS/Text messsges, Phone Calls, Email, and Web Chat. Built with vanilla JavaScript, Supabase, CPaaS, and LiveKit.\n\n## Features\n\n- **Smart Call Handling** — AI answers calls, screens unknown callers, takes messages, and transfers important calls to you\n- **Intelligent SMS** — Context-aware text responses that understand conversation history and respond appropriately\n- **Email AI** — Automatically respond to emails with context-aware AI replies, drafts for review, or fully autonomous mode\n- **24/7 Availability** — Your assistant never sleeps. Handle calls and messages around the clock\n- **Contact Management** — Whitelist VIPs, block spam, and set custom rules for different callers\n- **Knowledge Base** — Train your assistant with custom information to answer questions accurately\n- **Privacy First** — Your data is encrypted and secure. Full control over what information is shared\n- **Analytics & Insights** — Real-time dashboards with call volume, sentiment analysis, and conversation trends\n- **Real-Time Translation** — Automatic translation across 30+ languages during live calls\n- **Conversation Memory** — Your agent remembers past interactions, caller preferences, and context across every conversation\n- **Integrations** — Connect with HubSpot, Google Workspace, Zapier, and more. Sync contacts, log calls, and automate workflows\n- **Warm Transfer** — Seamlessly hand off live calls to you or your team when the AI detects a conversation needs a human touch\n- **Social Listening** — Automated monitoring of Reddit, HackerNews, and Google for keyword mentions. Email digests, admin dashboard with favorites, search, and status tracking\n- **Voice Library** — 30 voice options (24 ElevenLabs + 6 OpenAI) with AI-generated avatars, audio previews, trait tags (accent, tone, age, use case), and multilingual support. Cloned voices use the Multilingual v2 model for natural accent preservation\n- **Blog & Social** — Built-in blog with AI-generated featured images, Twitter/X auto-posting with image attachments, and a What's New notification card for users\n\n## Tech Stack\n\n- **Frontend**: Vanilla JavaScript (ES6+), HTML5, CSS3, Vite\n- **Backend**: Supabase (PostgreSQL, Auth, Realtime, Edge Functions — TypeScript/Deno)\n- **Telephony**: SignalWire (PSTN calls, SMS, conference bridging)\n- **Voice AI**: LiveKit (real-time audio), OpenAI (LLM), Deepgram (STT), ElevenLabs (TTS)\n- **Payments**: Stripe (credits, subscriptions)\n- **Email**: Postmark (transactional), Gmail API (support tickets, inbox email send/receive)\n- **Enrichment**: Apollo.io (contact data)\n- **Social Listening**: Serper.dev (Google SERP + Reddit), HN Algolia API\n- **Vector DB**: pgvector (conversation context embeddings)\n\n## Project Structure\n\n```\npat/\n├── agents/\n│   └── livekit-voice-agent/      # Python LiveKit agent (deployed on Render)\n│       ├── agent.py              # Main agent logic (~3,400 lines)\n│       ├── requirements.txt\n│       └── render.yaml           # Render deployment config\n├── public/                       # Static assets\n│   ├── index.html\n│   ├── manifest.json             # PWA manifest\n│   ├── sw.js                     # Service worker\n│   └── styles/\n├── src/\n│   ├── components/               # Reusable UI components\n│   │   ├── AdminChatInterface.js # Admin AI chat\n│   │   ├── AdminHeader.js        # Admin portal header with status dropdown\n│   │   ├── BottomNav.js          # Mobile bottom nav / desktop sidebar\n│   │   ├── ConfirmModal.js       # Custom confirm dialog\n│   │   ├── ImpersonationBanner.js\n│   │   ├── LowBalanceBanner.js   # Low credit balance warning\n│   │   └── ...\n│   ├── lib/                      # Utilities\n│   │   └── supabase.js           # Supabase client\n│   ├── models/                   # Data models (User, Contact, AgentConfig, etc.)\n│   ├── pages/                    # UI pages (large pages split into subdirectories)\n│   │   ├── admin/                # Admin portal (split from admin.js)\n│   │   │   ├── index.js          # Entry point\n│   │   │   ├── support-tab.js    # Support tickets, Gmail, AI settings\n│   │   │   ├── users-tab.js      # User management\n│   │   │   ├── analytics-tab.js\n│   │   │   ├── kpi-tab.js\n│   │   │   ├── notifications-tab.js\n│   │   │   ├── chat-tab.js\n│   │   │   ├── global-agent-tab.js\n│   │   │   └── styles.js\n│   │   ├── agent-detail/         # Agent config (split from agent-detail.js)\n│   │   │   ├── index.js\n│   │   │   ├── configure-tab.js\n│   │   │   ├── prompt-tab.js\n│   │   │   ├── functions-tab.js\n│   │   │   ├── knowledge-tab.js\n│   │   │   ├── memory-tab.js\n│   │   │   ├── deployment-tab.js # Phone number assignment + inline buy-number modal\n│   │   │   └── ...\n│   │   ├── inbox/                # Inbox (split from inbox.js)\n│   │   │   ├── index.js\n│   │   │   ├── call-interface.js\n│   │   │   ├── listeners.js\n│   │   │   ├── messaging.js\n│   │   │   └── views.js\n│   │   ├── phone/                # Phone (split from phone.js)\n│   │   │   ├── index.js\n│   │   │   ├── call-handler.js\n│   │   │   ├── dialpad.js\n│   │   │   └── number-management.js\n│   │   ├── batch-calls.js          # Batch outbound calls (CSV upload, scheduling)\n│   │   ├── contacts.js\n│   │   ├── settings.js\n│   │   └── ...\n│   ├── services/                 # Business logic services\n│   │   ├── unreadService.js\n│   │   ├── pushNotifications.js\n│   │   ├── mcpClient.js\n│   │   └── ...\n│   ├── main.js                   # App entry point\n│   └── router.js                 # Client-side SPA routing\n├── supabase/\n│   ├── functions/                # ~160 Edge Functions (TypeScript/Deno)\n│   │   ├── _shared/             # Shared utilities (cors, auth, balance-check)\n│   │   ├── admin-status/\n│   │   ├── contact-lookup/       # Apollo.io enrichment\n│   │   ├── batch-calls/            # Batch call CRUD (create, list, get, start, cancel)\n│   │   ├── process-batch-calls/    # Batch call worker (initiates calls per recipient)\n│   │   ├── initiate-bridged-call/\n│   │   ├── gmail-push-webhook/   # Gmail Pub/Sub push notifications + support ticket mirroring\n│   │   ├── gmail-watch-renew/    # Daily Gmail watch renewal\n│   │   ├── poll-gmail-inbox/     # Fallback email polling (30m)\n│   │   ├── poll-gmail-tickets/\n│   │   ├── support-tickets-api/\n│   │   ├── webhook-inbound-call/\n│   │   ├── webhook-inbound-sms/\n│   │   └── ...\n│   └── migrations/               # Database migrations\n├── packages/\n│   └── mcp-server/               # MCP server for AI coding tools (Claude Code, Cursor)\n├── tests/                        # Playwright & contract tests\n└── specs/                        # Feature specifications\n```\n\n## Getting Started\n\n### Prerequisites\n\n- Node.js 18+ and npm\n- Supabase account & CLI\n- SignalWire account (SIP endpoint, phone numbers)\n- LiveKit Cloud account\n- OpenAI API key\n- Deepgram API key\n- ElevenLabs API key\n\n### Installation\n\n1. **Clone the repository**\n   ```bash\n   git clone <repo-url>\n   cd pat\n   ```\n\n2. **Install dependencies**\n   ```bash\n   npm install\n   ```\n\n3. **Set up environment variables**\n   ```bash\n   cp .env.example .env\n   ```\n\n   Edit `.env` with your credentials:\n   ```\n   # Supabase\n   VITE_SUPABASE_URL=your_supabase_url\n   VITE_SUPABASE_ANON_KEY=your_supabase_anon_key\n   SUPABASE_SERVICE_ROLE_KEY=your_service_role_key\n\n   # SignalWire\n   SIGNALWIRE_PROJECT_ID=your_project_id\n   SIGNALWIRE_API_TOKEN=your_api_token\n   SIGNALWIRE_SPACE_URL=your_space.signalwire.com\n\n   # LiveKit\n   LIVEKIT_URL=wss://your-project.livekit.cloud\n   LIVEKIT_API_KEY=your_api_key\n   LIVEKIT_API_SECRET=your_api_secret\n\n   # AI Services\n   OPENAI_API_KEY=your_openai_key\n   DEEPGRAM_API_KEY=your_deepgram_key\n   ELEVENLABS_API_KEY=your_elevenlabs_key\n   ```\n\n4. **Run database migrations**\n   ```bash\n   npx supabase db push\n   ```\n\n5. **Deploy Edge Functions**\n   ```bash\n   export SUPABASE_ACCESS_TOKEN=your_token\n   npx supabase functions deploy --no-verify-jwt\n   ```\n\n6. **Start development server**\n   ```bash\n   npm run dev\n   ```\n\n   The app will be available at `http://localhost:3000`\n\n## Architecture\n\n### Smart Call Handling\nInbound calls hit a SignalWire number, which triggers a LiveKit room. The AI agent joins, screens the caller, and decides whether to transfer, take a message, or handle the conversation. All calls are recorded with transcripts stored automatically.\n\n### Intelligent SMS\nInbound SMS triggers a webhook that retrieves conversation context (with vector embeddings), generates a context-aware AI response, and sends it via SignalWire. Full conversation history is maintained per contact.\n\nOnly `agent_type = 'text'` agents handle SMS. Voice agents are never routed inbound SMS. Agent selection priority: explicit `text_agent_id` on the service number → user's default text agent → any text agent belonging to the user. If no text agent is found, a one-time auto-reply is sent to the sender and subsequent messages from that number are silently ignored.\n\nLoop detection prevents runaway back-and-forth: if the same message body arrives more than twice in a conversation thread, the AI reply is skipped silently. Normal replies resume as soon as the sender sends a different message.\n\n### Email AI\nGmail integration via OAuth and Pub/Sub push notifications. The agent can operate in draft mode (generates replies for review) or auto mode (sends replies autonomously). Emails are threaded and visible in the unified inbox.\n\n### Warm Transfer\nDuring a live call, the AI can seamlessly hand off to a human. SignalWire bridges the caller to your phone while the agent briefs you, then drops off the line.\n\n### Knowledge Base\nUpload documents or URLs to train your agent. Content is crawled (via Firecrawl), chunked, and embedded with OpenAI into pgvector for RAG-powered retrieval during calls and messages.\n\n### Conversation Memory\nEvery interaction is summarized and stored with vector embeddings. The agent retrieves relevant past context at the start of each new conversation for continuity across calls, SMS, and email.\n\n### Real-Time Translation\nThe voice agent supports automatic translation across 30+ languages during live calls, allowing callers and agents to speak in different languages.\n\n### Analytics & Insights\nReal-time dashboards display call volume, sentiment analysis, and conversation trends. Organization-wide analytics are available for teams.\n\n### Integrations\nHubSpot (CRM), Google Workspace (Calendar, Gmail), Cal.com (booking), Apollo.io (contact enrichment), and Slack (notifications). Native tool execution via the agent chat interface.\n\n### Contact Management\nContacts can be whitelisted for priority handling, blocked, or given custom call rules. CSV import, Apollo.io enrichment, and automatic contact creation from calls/SMS.\n\n### Privacy & Security\nAll data is encrypted in transit and at rest via Supabase. Access codes, phone verification, and role-based permissions control who can access what.\n\n### 24/7 Availability\nThe LiveKit voice agent runs on Render and connects to LiveKit Cloud, handling calls and messages around the clock without downtime.\n\n## Database Schema\n\n### Core Tables\n\n- `users` - User profiles, SIP credentials, preferences, credit balance\n- `organizations` - Multi-user org management\n- `contacts` - Contact information with enrichment fields\n- `agent_configs` - AI agent configuration (5 types: inbound_voice, outbound_voice, text, email, chat_widget; single system_prompt with type-specific defaults; shared_memory_agent_ids for cross-agent memory sharing; voice settings, functions)\n- `call_records` - Call history with purpose, goal, transcripts\n- `sms_messages` - SMS message history\n- `email_messages` - Email threads for inbox (id, user_id, agent_id, contact_id, thread_id, gmail_message_id, from/to/cc/bcc, subject, body_text, body_html, direction, status, is_ai_generated, is_read, sent_at, `attachments` JSONB for image metadata)\n- `agent_email_configs` - Per-agent email channel config (gmail_address, agent_mode: off/draft/auto, watch_expiration, last_history_id)\n- `conversation_contexts` - Conversation memory with embeddings\n- `service_numbers` - User's phone numbers from SignalWire (`agent_id` for voice, `text_agent_id` for SMS — independent routing)\n- `support_tickets` - Support ticket threads (Gmail integration, contact form feedback, `ticket_ref` TKT-XXXXXX, `attachments` JSONB for image metadata)\n- `support_ticket_notes` - Internal notes on support threads\n- `support_email_config` - Gmail connection, AI agent settings, ticket creation toggle\n- `support-attachments` (storage bucket) - Image attachments uploaded from Gmail or admin UI\n- `credit_transactions` - Billing and credit history\n- `knowledge_sources` / `knowledge_chunks` - RAG knowledge base (pgvector)\n- `chat_widgets` / `chat_sessions` / `chat_messages` - Embeddable chat widget\n- `batch_calls` - Batch outbound call jobs (status, scheduling, concurrency settings)\n- `batch_call_recipients` - Per-recipient tracking for batch calls (status, call_record_id)\n- `referral_rewards` - Referral tracking and bonus payouts\n- `social_listening_keywords` - Tracked keywords for social monitoring\n- `social_listening_results` - Reddit/HackerNews/Google mention results\n\n## Deployment\n\n### Frontend (Vite)\n```bash\nnpm run build\n# Deploy dist/ folder to Netlify, Vercel, or similar\n```\n\n### Edge Functions (Supabase)\n```bash\nexport SUPABASE_ACCESS_TOKEN=your_token\nnpx supabase functions deploy --no-verify-jwt\n```\n\n### LiveKit Agent (Render)\nThe agent auto-deploys from the `master` branch:\n```bash\ngit push origin master\n```\n\n## Development\n\n### Available Scripts\n\n- `npm run dev` - Start development server\n- `npm run build` - Build for production\n- `npm run preview` - Preview production build\n- `npm test` - Run Playwright tests\n- `npm run lint` - Lint code\n\n### Testing\n\n```bash\n# Run all Playwright tests\nnpx playwright test\n\n# Run specific test\nnpx playwright test tests/test-outbound-call.spec.js\n\n# Run with UI\nnpx playwright test --ui\n```\n\n## License\n\nMIT\n\n## Support\n\nFor issues and questions, please open a GitHub issue.\n",
  "bytes": 14114,
  "sha": "2fa97324e0a98e28a813d07cefd9c0548f5515f04b30b0a2af0ab7218a5581aa",
  "repo_slug": "elagerway/magpipe",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_elagerway_magpipe_e08a67af/readme"
}