diff --git a/.agent/AGENTS.md b/.agent/AGENTS.md index 4b1713ec..ec9d3a34 100644 --- a/.agent/AGENTS.md +++ b/.agent/AGENTS.md @@ -395,6 +395,7 @@ Subagents provide specialized capabilities. Read them when tasks require domain | `tools/wordpress/` | WordPress ecosystem - local dev, fleet management, plugin curation, custom fields | wp-dev, wp-admin, localwp, mainwp, wp-preferred, scf | | `services/hosting/` | Hosting providers - DNS, domains, cloud servers, managed WordPress | hostinger, hetzner, cloudflare, cloudron, closte, 101domains, spaceship | | `services/email/` | Email services - transactional email, deliverability | ses | +| `services/communications/` | Communications platform - SMS, voice, WhatsApp, verify, recordings | twilio, telfon | | `services/accounting/` | Accounting integration - invoicing, expenses, financial reports | quickfile | | `workflows/` | Development processes - branching, releases, PR reviews, quality gates | git-workflow, plans, release, version-bump, pr, preflight, postflight, ralph-loop, session-review | | `templates/` | Document templates - PRDs, task lists, planning documents | prd-template, tasks-template, plans-template, todo-template | diff --git a/.agent/aidevops/api-integrations.md b/.agent/aidevops/api-integrations.md index 20f90eb3..dc190635 100644 --- a/.agent/aidevops/api-integrations.md +++ b/.agent/aidevops/api-integrations.md @@ -127,6 +127,16 @@ Our framework provides standardized access to APIs across all major infrastructu - **Helper Script**: `.agent/scripts/ses-helper.sh` - **Key Features**: Email sending, bounce tracking, reputation monitoring +### **Twilio API** + +- **Purpose**: SMS, voice calls, WhatsApp, phone verification, call recording +- **Authentication**: Account SID + Auth Token +- **Configuration**: `configs/twilio-config.json` +- **Helper Script**: `.agent/scripts/twilio-helper.sh` +- **Key Features**: SMS/MMS, voice calls, WhatsApp Business, Verify (2FA), Lookup, recordings, transcriptions +- **AUP Compliance**: Must follow Twilio Acceptable Use Policy +- **Recommended Client**: Telfon app for end-user interface (https://mytelfon.com/) + ### **MainWP API** - **Purpose**: WordPress site management, updates, monitoring diff --git a/.agent/aidevops/services.md b/.agent/aidevops/services.md index 3cec1853..9f2684ff 100644 --- a/.agent/aidevops/services.md +++ b/.agent/aidevops/services.md @@ -210,7 +210,30 @@ tools: - **Use Cases**: Transactional emails, marketing emails, email monitoring - **Helper**: `ses-helper.sh` - **Config**: `ses-config.json` -- **Docs**: `.agent/ses.md` +- **Docs**: `.agent/services/email/ses.md` + +## Communications Services (2 Services) + +### Twilio + +- **Type**: Cloud communications platform (CPaaS) +- **Strengths**: Global coverage, comprehensive APIs, multi-channel (SMS, Voice, WhatsApp) +- **API**: REST API for messaging, voice, verify, lookup +- **Use Cases**: SMS notifications, voice calls, 2FA/OTP, WhatsApp Business, call recording +- **Helper**: `twilio-helper.sh` +- **Config**: `twilio-config.json` +- **Docs**: `.agent/services/communications/twilio.md` +- **AUP**: Must comply with Twilio Acceptable Use Policy + +### Telfon + +- **Type**: Twilio-powered cloud phone system with mobile/desktop apps +- **Strengths**: User-friendly interface, mobile apps, WhatsApp integration, call recording +- **Website**: https://mytelfon.com/ +- **Use Cases**: Sales teams, customer support, remote teams needing softphone +- **Apps**: iOS, Android, Chrome Extension, Edge Add-on +- **Docs**: `.agent/services/communications/telfon.md` +- **Note**: Recommended for end users who need a calling/SMS interface ## Domain & DNS (5 Services) diff --git a/.agent/scripts/twilio-helper.sh b/.agent/scripts/twilio-helper.sh new file mode 100755 index 00000000..a16e692a --- /dev/null +++ b/.agent/scripts/twilio-helper.sh @@ -0,0 +1,917 @@ +#!/bin/bash +# shellcheck disable=SC2034,SC2155,SC2317,SC2329,SC2016,SC2181,SC1091,SC2154,SC2015,SC2086,SC2129,SC2030,SC2031,SC2119,SC2120,SC2001,SC2162,SC2088,SC2089,SC2090,SC2029,SC2006,SC2153 + +# Twilio Helper Script +# Comprehensive Twilio management for AI assistants +# Supports SMS, Voice, WhatsApp, Verify, Lookup, Recordings, Transcriptions + +# Colors for output +GREEN='\033[0;32m' +BLUE='\033[0;34m' +YELLOW='\033[1;33m' +RED='\033[0;31m' +NC='\033[0m' # No Color + +# Common message constants +readonly HELP_SHOW_MESSAGE="Show this help" +readonly USAGE_COMMAND_OPTIONS="Usage: $0 [account] [options]" + +print_info() { + local msg="$1" + echo -e "${BLUE}[INFO]${NC} $msg" + return 0 +} + +print_success() { + local msg="$1" + echo -e "${GREEN}[SUCCESS]${NC} $msg" + return 0 +} + +print_warning() { + local msg="$1" + echo -e "${YELLOW}[WARNING]${NC} $msg" + return 0 +} + +print_error() { + local msg="$1" + echo -e "${RED}[ERROR]${NC} $msg" >&2 + return 0 +} + +# Script directory for relative paths +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# Config can be in repo configs/ or ~/.aidevops/configs/ +if [[ -f "${SCRIPT_DIR}/../../configs/twilio-config.json" ]]; then + CONFIG_FILE="${SCRIPT_DIR}/../../configs/twilio-config.json" +elif [[ -f "${HOME}/.aidevops/configs/twilio-config.json" ]]; then + CONFIG_FILE="${HOME}/.aidevops/configs/twilio-config.json" +else + CONFIG_FILE="${SCRIPT_DIR}/../../configs/twilio-config.json" +fi + +# Check if Twilio CLI or curl is available +check_dependencies() { + if ! command -v curl &> /dev/null; then + print_error "curl is required but not installed" + exit 1 + fi + + if ! command -v jq &> /dev/null; then + print_error "jq is required but not installed" + print_info "Install on macOS: brew install jq" + print_info "Install on Ubuntu: sudo apt-get install jq" + exit 1 + fi + + # Twilio CLI is optional but recommended + if command -v twilio &> /dev/null; then + TWILIO_CLI_AVAILABLE=true + else + TWILIO_CLI_AVAILABLE=false + fi + + return 0 +} + +# Load Twilio configuration +load_config() { + if [[ ! -f "$CONFIG_FILE" ]]; then + print_error "Configuration file not found: $CONFIG_FILE" + print_info "Copy and customize: cp configs/twilio-config.json.txt configs/twilio-config.json" + exit 1 + fi + return 0 +} + +# Get account configuration +get_account_config() { + local account_name="$1" + + if [[ -z "$account_name" ]]; then + print_error "Account name is required" + list_accounts + exit 1 + fi + + local account_config + account_config=$(jq -r ".accounts.\"$account_name\"" "$CONFIG_FILE") + if [[ "$account_config" == "null" ]]; then + print_error "Account '$account_name' not found in configuration" + list_accounts + exit 1 + fi + + echo "$account_config" + return 0 +} + +# Set Twilio credentials for account +set_twilio_credentials() { + local account_name="$1" + local config + config=$(get_account_config "$account_name") + + TWILIO_ACCOUNT_SID=$(echo "$config" | jq -r '.account_sid') + TWILIO_AUTH_TOKEN=$(echo "$config" | jq -r '.auth_token') + TWILIO_DEFAULT_FROM=$(echo "$config" | jq -r '.default_from // empty') + + if [[ "$TWILIO_ACCOUNT_SID" == "null" || "$TWILIO_AUTH_TOKEN" == "null" ]]; then + print_error "Invalid Twilio credentials for account '$account_name'" + exit 1 + fi + + export TWILIO_ACCOUNT_SID + export TWILIO_AUTH_TOKEN + return 0 +} + +# Make Twilio API request +twilio_api() { + local method="$1" + local endpoint="$2" + shift 2 + local data="$*" + + local url="https://api.twilio.com/2010-04-01/Accounts/${TWILIO_ACCOUNT_SID}${endpoint}" + + if [[ "$method" == "GET" ]]; then + curl -s -X GET "$url" \ + -u "${TWILIO_ACCOUNT_SID}:${TWILIO_AUTH_TOKEN}" + else + curl -s -X "$method" "$url" \ + -u "${TWILIO_ACCOUNT_SID}:${TWILIO_AUTH_TOKEN}" \ + $data + fi + return 0 +} + +# List all configured accounts +list_accounts() { + load_config + print_info "Available Twilio accounts:" + jq -r '.accounts | keys[]' "$CONFIG_FILE" | while read -r account; do + local description + description=$(jq -r ".accounts.\"$account\".description" "$CONFIG_FILE") + local default_from + default_from=$(jq -r ".accounts.\"$account\".default_from // \"not set\"" "$CONFIG_FILE") + echo " - $account (from: $default_from) - $description" + done + return 0 +} + +# Get account balance +get_balance() { + local account_name="$1" + set_twilio_credentials "$account_name" + + print_info "Getting balance for account: $account_name" + local response + response=$(twilio_api GET "/Balance.json") + + local balance currency + balance=$(echo "$response" | jq -r '.balance') + currency=$(echo "$response" | jq -r '.currency') + + echo "Balance: $currency $balance" + return 0 +} + +# List phone numbers +list_numbers() { + local account_name="$1" + set_twilio_credentials "$account_name" + + print_info "Phone numbers for account: $account_name" + local response + response=$(twilio_api GET "/IncomingPhoneNumbers.json") + + echo "$response" | jq -r '.incoming_phone_numbers[] | "\(.phone_number) - \(.friendly_name) [\(.capabilities | to_entries | map(select(.value == true) | .key) | join(", "))]"' + return 0 +} + +# Search available numbers +search_numbers() { + local account_name="$1" + local country="$2" + shift 2 + + set_twilio_credentials "$account_name" + + local params="" + while [[ $# -gt 0 ]]; do + case "$1" in + --area-code) + params="${params}&AreaCode=$2" + shift 2 + ;; + --contains) + params="${params}&Contains=$2" + shift 2 + ;; + --sms) + params="${params}&SmsEnabled=true" + shift + ;; + --voice) + params="${params}&VoiceEnabled=true" + shift + ;; + --mms) + params="${params}&MmsEnabled=true" + shift + ;; + *) + shift + ;; + esac + done + + print_info "Searching for available numbers in $country..." + local url="https://api.twilio.com/2010-04-01/Accounts/${TWILIO_ACCOUNT_SID}/AvailablePhoneNumbers/${country}/Local.json?${params}" + + local response + response=$(curl -s -X GET "$url" -u "${TWILIO_ACCOUNT_SID}:${TWILIO_AUTH_TOKEN}") + + local count + count=$(echo "$response" | jq -r '.available_phone_numbers | length') + + if [[ "$count" == "0" ]]; then + print_warning "No numbers available with those criteria" + print_info "Try different search parameters or contact Twilio support for special numbers" + return 1 + fi + + echo "$response" | jq -r '.available_phone_numbers[] | "\(.phone_number) - \(.locality // "N/A"), \(.region // "N/A") [\(.capabilities | to_entries | map(select(.value == true) | .key) | join(", "))]"' + return 0 +} + +# Buy a phone number +buy_number() { + local account_name="$1" + local phone_number="$2" + + set_twilio_credentials "$account_name" + + print_warning "About to purchase number: $phone_number" + read -p "Confirm purchase? (yes/no): " confirm + + if [[ "$confirm" != "yes" ]]; then + print_info "Purchase cancelled" + return 1 + fi + + local response + response=$(twilio_api POST "/IncomingPhoneNumbers.json" -d "PhoneNumber=$phone_number") + + if echo "$response" | jq -e '.sid' > /dev/null 2>&1; then + print_success "Number purchased successfully!" + echo "$response" | jq -r '"SID: \(.sid)\nNumber: \(.phone_number)\nFriendly Name: \(.friendly_name)"' + else + print_error "Failed to purchase number" + echo "$response" | jq -r '.message // .' + fi + return 0 +} + +# Send SMS +send_sms() { + local account_name="$1" + local to="$2" + local body="$3" + local from="${4:-$TWILIO_DEFAULT_FROM}" + + set_twilio_credentials "$account_name" + + if [[ -z "$from" ]]; then + from="$TWILIO_DEFAULT_FROM" + fi + + if [[ -z "$from" ]]; then + print_error "No 'from' number specified and no default configured" + return 1 + fi + + # AUP compliance check + print_info "Sending SMS from $from to $to" + + local response + response=$(twilio_api POST "/Messages.json" \ + -d "To=$to" \ + -d "From=$from" \ + -d "Body=$body") + + if echo "$response" | jq -e '.sid' > /dev/null 2>&1; then + print_success "SMS sent successfully!" + echo "$response" | jq -r '"SID: \(.sid)\nStatus: \(.status)\nTo: \(.to)\nFrom: \(.from)"' + else + print_error "Failed to send SMS" + echo "$response" | jq -r '.message // .' + fi + return 0 +} + +# List messages +list_messages() { + local account_name="$1" + local limit="${2:-20}" + + set_twilio_credentials "$account_name" + + print_info "Recent messages for account: $account_name" + local response + response=$(twilio_api GET "/Messages.json?PageSize=$limit") + + echo "$response" | jq -r '.messages[] | "\(.date_sent) | \(.direction) | \(.from) -> \(.to) | \(.status) | \(.body[0:50])..."' + return 0 +} + +# Get message status +get_message_status() { + local account_name="$1" + local message_sid="$2" + + set_twilio_credentials "$account_name" + + print_info "Getting status for message: $message_sid" + local response + response=$(twilio_api GET "/Messages/${message_sid}.json") + + echo "$response" | jq -r '"SID: \(.sid)\nStatus: \(.status)\nDirection: \(.direction)\nFrom: \(.from)\nTo: \(.to)\nBody: \(.body)\nDate Sent: \(.date_sent)\nError Code: \(.error_code // "none")\nError Message: \(.error_message // "none")"' + return 0 +} + +# Make a call +make_call() { + local account_name="$1" + local to="$2" + shift 2 + + set_twilio_credentials "$account_name" + + local from="$TWILIO_DEFAULT_FROM" + local twiml="" + local url="" + local record="false" + + while [[ $# -gt 0 ]]; do + case "$1" in + --from) + from="$2" + shift 2 + ;; + --twiml) + twiml="$2" + shift 2 + ;; + --url) + url="$2" + shift 2 + ;; + --record) + record="true" + shift + ;; + *) + shift + ;; + esac + done + + if [[ -z "$from" ]]; then + print_error "No 'from' number specified and no default configured" + return 1 + fi + + print_info "Initiating call from $from to $to" + + local data="-d To=$to -d From=$from" + + if [[ -n "$twiml" ]]; then + data="$data -d Twiml=$twiml" + elif [[ -n "$url" ]]; then + data="$data -d Url=$url" + else + # Default TwiML + data="$data -d Twiml=Hello from AI DevOps!" + fi + + if [[ "$record" == "true" ]]; then + data="$data -d Record=true" + fi + + local response + response=$(twilio_api POST "/Calls.json" $data) + + if echo "$response" | jq -e '.sid' > /dev/null 2>&1; then + print_success "Call initiated successfully!" + echo "$response" | jq -r '"SID: \(.sid)\nStatus: \(.status)\nTo: \(.to)\nFrom: \(.from)"' + else + print_error "Failed to initiate call" + echo "$response" | jq -r '.message // .' + fi + return 0 +} + +# List calls +list_calls() { + local account_name="$1" + local limit="${2:-20}" + + set_twilio_credentials "$account_name" + + print_info "Recent calls for account: $account_name" + local response + response=$(twilio_api GET "/Calls.json?PageSize=$limit") + + echo "$response" | jq -r '.calls[] | "\(.start_time) | \(.direction) | \(.from) -> \(.to) | \(.status) | \(.duration)s"' + return 0 +} + +# List recordings +list_recordings() { + local account_name="$1" + local limit="${2:-20}" + + set_twilio_credentials "$account_name" + + print_info "Recordings for account: $account_name" + local response + response=$(twilio_api GET "/Recordings.json?PageSize=$limit") + + echo "$response" | jq -r '.recordings[] | "\(.date_created) | \(.sid) | \(.duration)s | \(.call_sid)"' + return 0 +} + +# Get recording details +get_recording() { + local account_name="$1" + local recording_sid="$2" + + set_twilio_credentials "$account_name" + + print_info "Getting recording: $recording_sid" + local response + response=$(twilio_api GET "/Recordings/${recording_sid}.json") + + echo "$response" | jq -r '"SID: \(.sid)\nCall SID: \(.call_sid)\nDuration: \(.duration)s\nDate: \(.date_created)\nStatus: \(.status)"' + + echo "" + echo "Download URL: https://api.twilio.com/2010-04-01/Accounts/${TWILIO_ACCOUNT_SID}/Recordings/${recording_sid}.mp3" + return 0 +} + +# Download recording +download_recording() { + local account_name="$1" + local recording_sid="$2" + local output_dir="${3:-.}" + + set_twilio_credentials "$account_name" + + local url="https://api.twilio.com/2010-04-01/Accounts/${TWILIO_ACCOUNT_SID}/Recordings/${recording_sid}.mp3" + local output_file="${output_dir}/${recording_sid}.mp3" + + print_info "Downloading recording to: $output_file" + curl -s -o "$output_file" -u "${TWILIO_ACCOUNT_SID}:${TWILIO_AUTH_TOKEN}" "$url" + + if [[ -f "$output_file" ]]; then + print_success "Recording downloaded: $output_file" + else + print_error "Failed to download recording" + fi + return 0 +} + +# List transcriptions +list_transcriptions() { + local account_name="$1" + local limit="${2:-20}" + + set_twilio_credentials "$account_name" + + print_info "Transcriptions for account: $account_name" + local response + response=$(twilio_api GET "/Transcriptions.json?PageSize=$limit") + + echo "$response" | jq -r '.transcriptions[] | "\(.date_created) | \(.sid) | \(.status) | \(.recording_sid)"' + return 0 +} + +# Get transcription +get_transcription() { + local account_name="$1" + local transcription_sid="$2" + + set_twilio_credentials "$account_name" + + print_info "Getting transcription: $transcription_sid" + local response + response=$(twilio_api GET "/Transcriptions/${transcription_sid}.json") + + echo "$response" | jq -r '"SID: \(.sid)\nRecording SID: \(.recording_sid)\nStatus: \(.status)\nDate: \(.date_created)\n\nTranscription:\n\(.transcription_text)"' + return 0 +} + +# Send WhatsApp message +send_whatsapp() { + local account_name="$1" + local to="$2" + local body="$3" + local from="${4:-}" + + set_twilio_credentials "$account_name" + + # WhatsApp numbers need whatsapp: prefix + if [[ ! "$to" =~ ^whatsapp: ]]; then + to="whatsapp:$to" + fi + + if [[ -z "$from" ]]; then + # Get WhatsApp sender from config + from=$(jq -r ".accounts.\"$account_name\".whatsapp_from // empty" "$CONFIG_FILE") + fi + + if [[ -z "$from" ]]; then + print_error "No WhatsApp sender configured for account '$account_name'" + return 1 + fi + + if [[ ! "$from" =~ ^whatsapp: ]]; then + from="whatsapp:$from" + fi + + print_info "Sending WhatsApp message from $from to $to" + + local response + response=$(twilio_api POST "/Messages.json" \ + -d "To=$to" \ + -d "From=$from" \ + -d "Body=$body") + + if echo "$response" | jq -e '.sid' > /dev/null 2>&1; then + print_success "WhatsApp message sent successfully!" + echo "$response" | jq -r '"SID: \(.sid)\nStatus: \(.status)"' + else + print_error "Failed to send WhatsApp message" + echo "$response" | jq -r '.message // .' + fi + return 0 +} + +# Lookup phone number +lookup_number() { + local account_name="$1" + local phone_number="$2" + local lookup_type="${3:-}" + + set_twilio_credentials "$account_name" + + local url="https://lookups.twilio.com/v1/PhoneNumbers/${phone_number}" + + if [[ -n "$lookup_type" ]]; then + url="${url}?Type=${lookup_type}" + fi + + print_info "Looking up: $phone_number" + local response + response=$(curl -s -X GET "$url" -u "${TWILIO_ACCOUNT_SID}:${TWILIO_AUTH_TOKEN}") + + echo "$response" | jq '.' + return 0 +} + +# Verify - Create service +verify_create_service() { + local account_name="$1" + local friendly_name="$2" + + set_twilio_credentials "$account_name" + + print_info "Creating Verify service: $friendly_name" + + local response + response=$(curl -s -X POST "https://verify.twilio.com/v2/Services" \ + -u "${TWILIO_ACCOUNT_SID}:${TWILIO_AUTH_TOKEN}" \ + -d "FriendlyName=$friendly_name") + + if echo "$response" | jq -e '.sid' > /dev/null 2>&1; then + print_success "Verify service created!" + echo "$response" | jq -r '"SID: \(.sid)\nName: \(.friendly_name)"' + print_info "Save this SID in your config as 'verify_service_sid'" + else + print_error "Failed to create Verify service" + echo "$response" | jq -r '.message // .' + fi + return 0 +} + +# Verify - Send code +verify_send() { + local account_name="$1" + local to="$2" + local channel="${3:-sms}" + + set_twilio_credentials "$account_name" + + local service_sid + service_sid=$(jq -r ".accounts.\"$account_name\".verify_service_sid // empty" "$CONFIG_FILE") + + if [[ -z "$service_sid" ]]; then + print_error "No Verify service SID configured for account '$account_name'" + print_info "Create one with: $0 verify-create-service $account_name \"Service Name\"" + return 1 + fi + + print_info "Sending verification code to $to via $channel" + + local response + response=$(curl -s -X POST "https://verify.twilio.com/v2/Services/${service_sid}/Verifications" \ + -u "${TWILIO_ACCOUNT_SID}:${TWILIO_AUTH_TOKEN}" \ + -d "To=$to" \ + -d "Channel=$channel") + + if echo "$response" | jq -e '.sid' > /dev/null 2>&1; then + print_success "Verification code sent!" + echo "$response" | jq -r '"Status: \(.status)\nChannel: \(.channel)\nTo: \(.to)"' + else + print_error "Failed to send verification code" + echo "$response" | jq -r '.message // .' + fi + return 0 +} + +# Verify - Check code +verify_check() { + local account_name="$1" + local to="$2" + local code="$3" + + set_twilio_credentials "$account_name" + + local service_sid + service_sid=$(jq -r ".accounts.\"$account_name\".verify_service_sid // empty" "$CONFIG_FILE") + + if [[ -z "$service_sid" ]]; then + print_error "No Verify service SID configured for account '$account_name'" + return 1 + fi + + print_info "Checking verification code for $to" + + local response + response=$(curl -s -X POST "https://verify.twilio.com/v2/Services/${service_sid}/VerificationCheck" \ + -u "${TWILIO_ACCOUNT_SID}:${TWILIO_AUTH_TOKEN}" \ + -d "To=$to" \ + -d "Code=$code") + + local status + status=$(echo "$response" | jq -r '.status') + + if [[ "$status" == "approved" ]]; then + print_success "Verification successful!" + else + print_error "Verification failed" + fi + + echo "$response" | jq -r '"Status: \(.status)\nTo: \(.to)\nValid: \(.valid)"' + return 0 +} + +# Get usage summary +get_usage() { + local account_name="$1" + local period="${2:-today}" + + set_twilio_credentials "$account_name" + + local start_date end_date + case "$period" in + today) + start_date=$(date +%Y-%m-%d) + end_date=$(date +%Y-%m-%d) + ;; + week) + start_date=$(date -v-7d +%Y-%m-%d 2>/dev/null || date -d "7 days ago" +%Y-%m-%d) + end_date=$(date +%Y-%m-%d) + ;; + month) + start_date=$(date -v-30d +%Y-%m-%d 2>/dev/null || date -d "30 days ago" +%Y-%m-%d) + end_date=$(date +%Y-%m-%d) + ;; + *) + start_date="$period" + end_date=$(date +%Y-%m-%d) + ;; + esac + + print_info "Usage for account: $account_name ($start_date to $end_date)" + local response + response=$(twilio_api GET "/Usage/Records.json?StartDate=$start_date&EndDate=$end_date") + + echo "$response" | jq -r '.usage_records[] | select(.count != "0") | "\(.category): \(.count) (\(.price) \(.price_unit))"' + return 0 +} + +# Audit account +audit_account() { + local account_name="$1" + set_twilio_credentials "$account_name" + + print_info "=== Twilio Account Audit: $account_name ===" + echo "" + + print_info "Account Balance:" + get_balance "$account_name" + echo "" + + print_info "Phone Numbers:" + list_numbers "$account_name" + echo "" + + print_info "Recent Messages (last 5):" + list_messages "$account_name" 5 + echo "" + + print_info "Recent Calls (last 5):" + list_calls "$account_name" 5 + echo "" + + print_info "Usage Summary (this month):" + get_usage "$account_name" month + + return 0 +} + +# Show help +show_help() { + cat << EOF +Twilio Helper Script - Comprehensive Twilio management for AI assistants + +$USAGE_COMMAND_OPTIONS + +ACCOUNT COMMANDS: + accounts List all configured accounts + balance Get account balance + usage [period] Get usage summary (today|week|month) + audit Full account audit + status Check account status + +PHONE NUMBER COMMANDS: + numbers List owned phone numbers + search-numbers [options] + Search available numbers + --area-code Filter by area code + --contains Filter by containing digits + --sms Must support SMS + --voice Must support voice + --mms Must support MMS + buy-number Purchase a phone number + release-number Release a phone number + +SMS COMMANDS: + sms [from] Send SMS message + messages [limit] List recent messages + message-status Get message status + +VOICE COMMANDS: + call [options] Make outbound call + --from From number + --twiml TwiML instructions + --url TwiML URL + --record Record the call + calls [limit] List recent calls + call-details Get call details + +RECORDING COMMANDS: + recordings [limit] List recordings + recording Get recording details + download-recording [dir] + Download recording MP3 + +TRANSCRIPTION COMMANDS: + transcriptions [limit] List transcriptions + transcription Get transcription text + +WHATSAPP COMMANDS: + whatsapp Send WhatsApp message + +VERIFY (2FA) COMMANDS: + verify-create-service + Create Verify service + verify-send [channel] + Send verification code (sms|call|email) + verify-check + Check verification code + +LOOKUP COMMANDS: + lookup [type] Lookup phone number info + Types: carrier, caller-name + +EXAMPLES: + $0 accounts + $0 sms production "+1234567890" "Hello!" + $0 search-numbers production US --area-code 415 --sms + $0 call production "+1234567890" --record + $0 verify-send production "+1234567890" sms + $0 audit production + +CONFIGURATION: + Config file: configs/twilio-config.json + Template: configs/twilio-config.json.txt + +For more information, see: .agent/services/communications/twilio.md +EOF + return 0 +} + +# Main function +main() { + local command="${1:-help}" + local account_name="${2:-}" + shift 2 2>/dev/null || true + + check_dependencies + load_config + + case "$command" in + "accounts") + list_accounts + ;; + "balance") + get_balance "$account_name" + ;; + "numbers") + list_numbers "$account_name" + ;; + "search-numbers") + local country="$1" + shift + search_numbers "$account_name" "$country" "$@" + ;; + "buy-number") + buy_number "$account_name" "$1" + ;; + "sms") + send_sms "$account_name" "$1" "$2" "${3:-}" + ;; + "messages") + list_messages "$account_name" "${1:-20}" + ;; + "message-status") + get_message_status "$account_name" "$1" + ;; + "call") + make_call "$account_name" "$1" "${@:2}" + ;; + "calls") + list_calls "$account_name" "${1:-20}" + ;; + "recordings") + list_recordings "$account_name" "${1:-20}" + ;; + "recording") + get_recording "$account_name" "$1" + ;; + "download-recording") + download_recording "$account_name" "$1" "${2:-.}" + ;; + "transcriptions") + list_transcriptions "$account_name" "${1:-20}" + ;; + "transcription") + get_transcription "$account_name" "$1" + ;; + "whatsapp") + send_whatsapp "$account_name" "$1" "$2" + ;; + "lookup") + lookup_number "$account_name" "$1" "${2:-}" + ;; + "verify-create-service") + verify_create_service "$account_name" "$1" + ;; + "verify-send") + verify_send "$account_name" "$1" "${2:-sms}" + ;; + "verify-check") + verify_check "$account_name" "$1" "$2" + ;; + "usage") + get_usage "$account_name" "${1:-today}" + ;; + "audit") + audit_account "$account_name" + ;; + "status") + get_balance "$account_name" + ;; + "help"|*) + show_help + ;; + esac + return 0 +} + +main "$@" diff --git a/.agent/services/communications/telfon.md b/.agent/services/communications/telfon.md new file mode 100644 index 00000000..619e859f --- /dev/null +++ b/.agent/services/communications/telfon.md @@ -0,0 +1,470 @@ +--- +description: Telfon cloud VoIP app - Twilio-powered calling, SMS, WhatsApp with user-friendly interface +mode: subagent +tools: + read: true + write: false + edit: false + bash: true + glob: true + grep: true + webfetch: true +--- + +# Telfon - Cloud VoIP & Virtual Phone System + + + +## Quick Reference + +- **Type**: Twilio-powered cloud phone system with mobile/desktop apps +- **Website**: https://mytelfon.com/ +- **Apps**: iOS, Android, Chrome Extension, Microsoft Edge Add-on +- **Features**: Calls, SMS, WhatsApp, Call Recording, Bulk SMS, Multi-number +- **Pricing**: Pay-as-you-go via Twilio credits +- **Setup Time**: ~5 minutes +- **Best For**: End users who want a calling/SMS interface without coding + +**Key Capabilities**: + +- Virtual phone numbers in 180+ countries +- Inbound/outbound calls and SMS +- Call recording with cloud storage +- WhatsApp Business integration +- Bulk SMS campaigns +- Chrome extension for click-to-call +- Multi-account management + +**When to Recommend Telfon**: + +- User needs a phone interface (not just API) +- Sales/support teams needing softphone +- Users who want WhatsApp + SMS in one app +- Non-technical users managing Twilio numbers + + + +Telfon is a Twilio-based cloud phone system that provides a user-friendly interface for making calls, sending SMS, and managing WhatsApp communications. It's ideal for users who want the power of Twilio without writing code. + +## Overview + +### What is Telfon? + +Telfon is a third-party application built on top of Twilio that provides: + +- **Mobile Apps** (iOS/Android) for calls and SMS on the go +- **Chrome Extension** for click-to-call from any webpage +- **Web Dashboard** for account management and analytics +- **WhatsApp Integration** for business messaging + +### Telfon vs Direct Twilio + +| Aspect | Telfon | Direct Twilio | +|--------|--------|---------------| +| **Interface** | Mobile/desktop apps | API/CLI only | +| **Setup** | 5 minutes | Requires development | +| **Best For** | End users, sales teams | Developers, automation | +| **Customization** | Limited to app features | Fully customizable | +| **Cost** | Telfon subscription + Twilio usage | Twilio usage only | +| **WhatsApp** | Built-in | Requires setup | +| **Call Recording** | One-click enable | Requires TwiML config | + +### When to Use Each + +**Use Telfon when**: + +- You need a phone interface for daily calling/SMS +- Sales or support teams need a softphone +- You want WhatsApp + SMS in one place +- Quick setup is more important than customization + +**Use Direct Twilio when**: + +- Building automated workflows +- Integrating with custom applications +- Need full API control +- Cost optimization is critical + +## Getting Started + +### Prerequisites + +1. **Twilio Account** - Sign up at https://www.twilio.com/try-twilio +2. **Twilio Phone Number** - Purchase via Twilio console or Telfon +3. **Telfon Account** - Sign up at https://mytelfon.com/ + +### Quick Setup (5 Minutes) + +#### Step 1: Get Twilio Credentials + +1. Log in to [Twilio Console](https://console.twilio.com/) +2. Copy your **Account SID** and **Auth Token** from the dashboard +3. Note your Twilio phone number(s) + +#### Step 2: Install Telfon + +**Mobile Apps**: + +- [iOS App Store](https://apps.apple.com/in/app/telfon-twilio-calls-chats/id6443471885) +- [Google Play Store](https://play.google.com/store/apps/details?id=com.wmt.cloud_telephony.android) + +**Browser Extensions**: + +- [Chrome Web Store](https://chromewebstore.google.com/detail/telfon-twilio-calls/bgkbahmggkomlcagkagcmiggkmcjmgdi) +- [Microsoft Edge Add-ons](https://microsoftedge.microsoft.com/addons/detail/telfon-virtual-phone-sys/hbdeajgckookmiogfljihebodfammogd) + +#### Step 3: Connect Twilio to Telfon + +1. Open Telfon app and sign up/login +2. Go to Settings > Twilio Integration +3. Enter your Twilio Account SID +4. Enter your Twilio Auth Token +5. Select your Twilio phone number(s) +6. Save and verify connection + +### Video Tutorial + +Telfon provides setup guides at: https://mytelfon.com/demo/ + +## Number Management + +### Scenario 1: Numbers Purchased via Twilio + +If you already have Twilio numbers: + +1. Open Telfon app +2. Go to Settings > Phone Numbers +3. Your Twilio numbers will appear automatically +4. Select which numbers to use in Telfon +5. Configure each number's settings (voicemail, forwarding, etc.) + +**Note**: Numbers remain in your Twilio account. Telfon just provides the interface. + +### Scenario 2: Numbers Purchased via Telfon + +Telfon can also help you purchase numbers: + +1. Open Telfon app +2. Go to Phone Numbers > Buy New Number +3. Search by country, area code, or capabilities +4. Purchase directly (charged to your Twilio account) +5. Number is automatically configured in Telfon + +**Advantage**: Simpler purchase flow, automatic configuration. + +### Scenario 3: Numbers Not Available via API + +Some numbers require contacting Twilio support: + +- Toll-free in certain countries +- Short codes +- Specific area codes with limited availability + +**AI-Assisted Process**: + +1. Search in Telfon/Twilio - if unavailable +2. AI can compose support request (see `twilio.md`) +3. Once acquired, add to Telfon manually + +## Features Guide + +### Making Calls + +**Mobile App**: + +1. Open Telfon +2. Tap the dialer icon +3. Enter number or select contact +4. Tap call button +5. Select which Twilio number to call from (if multiple) + +**Chrome Extension**: + +1. Click any phone number on a webpage +2. Telfon popup appears +3. Click to initiate call +4. Call connects via your Twilio number + +### Sending SMS + +**Single SMS**: + +1. Open Telfon > Messages +2. Tap compose +3. Enter recipient number +4. Type message +5. Send + +**Bulk SMS**: + +1. Open Telfon > Broadcasts +2. Create new broadcast +3. Import contacts (CSV) or select from list +4. Compose message +5. Schedule or send immediately + +**Compliance Note**: Ensure recipients have opted in for bulk messages. + +### Call Recording + +1. Go to Settings > Call Recording +2. Enable recording (per number or all) +3. Recordings are stored in Telfon cloud +4. Access via Telfon > Recordings +5. Download or share as needed + +**Storage**: Recordings count against Twilio storage limits. + +### WhatsApp Integration + +**Setup**: + +1. Go to Settings > WhatsApp +2. Link your WhatsApp Business account +3. Scan QR code with WhatsApp +4. WhatsApp messages appear in Telfon + +**Features**: + +- Send/receive WhatsApp messages +- Manage multiple WhatsApp accounts +- Unified inbox with SMS + +**Requirements**: + +- WhatsApp Business account +- Approved message templates for outbound (outside 24h window) + +### Voicemail + +1. Go to Settings > Voicemail +2. Enable voicemail for each number +3. Record custom greeting (or use default) +4. Voicemails appear in Telfon > Voicemail +5. Optionally enable voicemail-to-text transcription + +### Call Forwarding + +1. Go to Settings > Call Forwarding +2. Select number to configure +3. Set forwarding rules: + - Always forward + - Forward when busy + - Forward when no answer + - Forward when unreachable +4. Enter destination number +5. Save + +## Use Cases + +### Sales Teams + +**Setup**: + +- Multiple sales reps, each with their own Twilio number +- Shared team number for inbound +- Call recording for training +- Chrome extension for CRM click-to-call + +**Workflow**: + +1. Lead comes in via website +2. Rep clicks phone number in CRM +3. Telfon initiates call via their Twilio number +4. Call is recorded automatically +5. Recording linked to CRM contact + +### Customer Support + +**Setup**: + +- Toll-free number for inbound support +- Call forwarding to available agents +- Voicemail for after-hours +- SMS for ticket updates + +**Workflow**: + +1. Customer calls toll-free number +2. IVR routes to available agent (via Twilio Studio) +3. Agent answers in Telfon app +4. Call recorded for quality assurance +5. Follow-up SMS sent via Telfon + +### Remote Teams + +**Setup**: + +- Virtual numbers in multiple countries +- Team members use mobile app anywhere +- Unified company presence + +**Benefits**: + +- Local presence in multiple markets +- No hardware required +- Work from anywhere + +### Real Estate + +**Setup**: + +- Dedicated number per listing or agent +- SMS for appointment reminders +- Call tracking for marketing attribution + +**Workflow**: + +1. Prospect sees listing with dedicated number +2. Calls or texts that number +3. Agent receives in Telfon with listing context +4. Follow-up automated via SMS + +## Integration with aidevops + +### Recommended Architecture + +```text ++------------------+ +------------------+ +------------------+ +| AI Workflows |---->| Twilio API |---->| Telfon App | +| (Automation) | | (Backend) | | (User UI) | ++------------------+ +------------------+ +------------------+ + | | | + v v v + Scheduled SMS Webhooks for Manual calls + Automated calls CRM logging SMS conversations + Verify/OTP Recording storage WhatsApp chats +``` + +### When AI Uses Twilio Directly + +- Automated appointment reminders +- OTP/verification codes +- Bulk notifications +- Webhook-triggered messages + +### When Users Use Telfon + +- Manual outbound calls +- Conversational SMS +- WhatsApp conversations +- Reviewing recordings + +### Hybrid Workflow Example + +1. **AI** sends appointment reminder SMS via Twilio API +2. **Customer** replies with question +3. **Webhook** logs reply to CRM +4. **User** sees notification in Telfon +5. **User** responds via Telfon app +6. **Twilio** delivers response +7. **Webhook** logs outbound message to CRM + +## Pricing + +### Telfon Subscription + +Check current pricing at: https://mytelfon.com/pricing/ + +Typical tiers: + +- **Free Trial**: Limited features, try before buying +- **Starter**: Basic calling/SMS for individuals +- **Professional**: Full features, multiple numbers +- **Enterprise**: Custom pricing, dedicated support + +### Twilio Usage (Separate) + +Telfon uses your Twilio account for actual communications: + +- **SMS**: ~$0.0079/message (US) +- **Voice**: ~$0.014/minute (US outbound) +- **Phone Numbers**: ~$1.15/month (US local) +- **Recording Storage**: ~$0.0025/minute + +See: https://www.twilio.com/en-us/pricing + +### Cost Optimization + +1. **Use Messaging Services** for bulk SMS (better deliverability) +2. **Monitor usage** in Twilio console +3. **Set alerts** for spending thresholds +4. **Review unused numbers** monthly + +## Troubleshooting + +### Connection Issues + +**Telfon can't connect to Twilio**: + +1. Verify Account SID is correct +2. Verify Auth Token is correct (regenerate if needed) +3. Check Twilio account is active (not suspended) +4. Ensure phone number is active + +### Call Quality Issues + +**Poor audio quality**: + +1. Check internet connection (WiFi preferred) +2. Close other bandwidth-heavy apps +3. Try switching between WiFi and cellular +4. Check Twilio status: https://status.twilio.com/ + +### SMS Not Delivering + +**Messages not received**: + +1. Verify recipient number format (+1XXXXXXXXXX) +2. Check message status in Telfon > Messages +3. Review Twilio debugger for errors +4. Ensure compliance with carrier requirements (10DLC for US A2P) + +### WhatsApp Issues + +**Can't send WhatsApp messages**: + +1. Verify WhatsApp Business account is connected +2. Check if within 24-hour conversation window +3. Use approved templates for outbound outside window +4. Review WhatsApp Business API requirements + +## Security Considerations + +### Data Storage + +- Call recordings stored in Telfon cloud (and Twilio) +- Messages stored in Telfon for conversation history +- Review Telfon's privacy policy for data handling + +### Access Control + +- Use strong passwords for Telfon account +- Enable 2FA if available +- Regularly review connected devices +- Revoke access for departed team members + +### Compliance + +- Telfon inherits Twilio's compliance certifications +- Additional compliance depends on Telfon's practices +- For regulated industries, verify Telfon meets requirements + +## Alternatives to Telfon + +If Telfon doesn't meet your needs: + +| App | Strengths | Best For | +|-----|-----------|----------| +| **OpenPhone** | Team features, shared numbers | Small teams | +| **Dialpad** | AI features, transcription | Enterprise | +| **Grasshopper** | Simple, reliable | Solopreneurs | +| **RingCentral** | Full UCaaS | Large organizations | +| **JustCall** | CRM integrations | Sales teams | + +## Related Documentation + +- `twilio.md` - Direct Twilio API usage +- `ses.md` - Email integration for multi-channel +- Telfon Help: https://mytelfon.com/support/ +- Telfon Blog: https://mytelfon.com/blog/ diff --git a/.agent/services/communications/twilio.md b/.agent/services/communications/twilio.md new file mode 100644 index 00000000..40cc2cc0 --- /dev/null +++ b/.agent/services/communications/twilio.md @@ -0,0 +1,569 @@ +--- +description: Twilio communications platform - SMS, voice, WhatsApp, verify with multi-account support +mode: subagent +tools: + read: true + write: false + edit: false + bash: true + glob: true + grep: true + webfetch: true +--- + +# Twilio Communications Provider + + + +## Quick Reference + +- **Type**: Cloud communications platform (CPaaS) +- **Auth**: Account SID + Auth Token (per account) +- **Config**: `configs/twilio-config.json` +- **Commands**: `twilio-helper.sh [accounts|numbers|sms|call|verify|lookup|recordings|transcriptions|whatsapp|status|audit] [account] [args]` +- **Capabilities**: SMS, Voice, WhatsApp, Verify (2FA), Lookup, Recordings, Transcriptions +- **Regions**: Global with local number availability in 180+ countries +- **Pricing**: Pay-as-you-go per message/minute +- **AUP**: Must comply with Twilio Acceptable Use Policy +- **Recommended Client**: Telfon app (see `telfon.md`) + +**Critical Compliance Rules**: + +- Obtain consent before sending marketing messages +- Honor opt-out requests immediately +- No spam, phishing, or deceptive content +- Follow country-specific regulations (TCPA, GDPR, etc.) + + + +Twilio is a cloud communications platform that enables programmatic SMS, voice calls, WhatsApp messaging, phone number verification, and more. + +## Acceptable Use Policy (AUP) Compliance + +**CRITICAL**: Before any messaging operation, verify compliance with Twilio's AUP. + +### Prohibited Activities + +| Category | Examples | Action | +|----------|----------|--------| +| **Spam** | Unsolicited bulk messages, marketing without consent | BLOCK - Do not send | +| **Phishing** | Deceptive links, credential harvesting | BLOCK - Do not send | +| **Illegal Content** | Fraud, harassment, threats | BLOCK - Do not send | +| **Identity Spoofing** | Misleading sender information | BLOCK - Do not send | +| **Bypassing Limits** | Circumventing rate limits or restrictions | BLOCK - Do not attempt | + +### Pre-Send Validation Checklist + +Before sending any message, the AI assistant should verify: + +1. **Consent**: Does the recipient expect this message? +2. **Opt-out**: Is there a clear way to unsubscribe? +3. **Content**: Is the message legitimate and non-deceptive? +4. **Compliance**: Does it meet country-specific requirements? + +### Country-Specific Requirements + +| Region | Key Requirements | +|--------|------------------| +| **US (TCPA)** | Prior express consent for marketing, 10DLC registration for A2P | +| **EU (GDPR)** | Explicit consent, right to erasure, data protection | +| **UK** | PECR compliance, consent for marketing | +| **Canada (CASL)** | Express or implied consent, unsubscribe mechanism | +| **Australia** | Spam Act compliance, consent required | + +### When AI Should Refuse + +The AI assistant should **refuse** to send messages that: + +- Target recipients who haven't opted in +- Contain deceptive or misleading content +- Attempt to bypass Twilio's systems +- Violate local telecommunications laws +- Could be considered harassment or spam + +**Response template when refusing**: + +```text +I cannot send this message because it may violate Twilio's Acceptable Use Policy: +- [Specific concern] + +To proceed legitimately: +1. [Suggested alternative approach] +2. [Compliance requirement to meet] + +See: https://www.twilio.com/en-us/legal/aup +``` + +## Provider Overview + +### Twilio Characteristics + +- **Service Type**: Cloud communications platform (CPaaS) +- **Global Coverage**: Phone numbers in 180+ countries +- **Authentication**: Account SID + Auth Token per account +- **API Support**: REST API, SDKs (Node.js, Python, etc.) +- **Pricing**: Pay-per-use (SMS, minutes, verifications) +- **Compliance**: SOC 2, HIPAA eligible, GDPR compliant + +### Best Use Cases + +- **Transactional SMS** (order confirmations, alerts, OTPs) +- **Voice calls** (outbound notifications, IVR systems) +- **Two-factor authentication** (Verify API) +- **WhatsApp Business** messaging +- **Phone number validation** (Lookup API) +- **Call recording and transcription** +- **CRM integration** for communication logging + +## Configuration + +### Setup Configuration + +```bash +# Copy template +cp configs/twilio-config.json.txt configs/twilio-config.json + +# Edit with your Twilio credentials +# Get credentials from: https://console.twilio.com/ +``` + +### Multi-Account Configuration + +```json +{ + "accounts": { + "production": { + "account_sid": "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "auth_token": "your_auth_token_here", + "description": "Production Twilio account", + "phone_numbers": ["+1234567890"], + "messaging_service_sid": "MGxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "default_from": "+1234567890" + }, + "staging": { + "account_sid": "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "auth_token": "your_auth_token_here", + "description": "Staging/Test account", + "phone_numbers": ["+1987654321"], + "default_from": "+1987654321" + } + } +} +``` + +### Twilio CLI Setup + +```bash +# Install Twilio CLI +brew tap twilio/brew && brew install twilio # macOS +npm install -g twilio-cli # npm + +# Verify installation +twilio --version + +# Login (interactive - stores credentials locally) +twilio login + +# Or use environment variables +export TWILIO_ACCOUNT_SID="ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" +export TWILIO_AUTH_TOKEN="your_auth_token_here" +``` + +## Usage Examples + +### SMS Operations + +```bash +# Send SMS +./.agent/scripts/twilio-helper.sh sms production "+1234567890" "Hello from aidevops!" + +# Send SMS with status callback +./.agent/scripts/twilio-helper.sh sms production "+1234567890" "Order confirmed" --callback "https://your-webhook.com/status" + +# List recent messages +./.agent/scripts/twilio-helper.sh messages production --limit 20 + +# Get message status +./.agent/scripts/twilio-helper.sh message-status production "SMxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" +``` + +### Voice Operations + +```bash +# Make outbound call with TwiML +./.agent/scripts/twilio-helper.sh call production "+1234567890" --twiml "Hello!" + +# Make call with URL +./.agent/scripts/twilio-helper.sh call production "+1234567890" --url "https://your-server.com/voice.xml" + +# List recent calls +./.agent/scripts/twilio-helper.sh calls production --limit 20 + +# Get call details +./.agent/scripts/twilio-helper.sh call-details production "CAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" +``` + +### Call Recording & Transcription + +```bash +# List recordings for account +./.agent/scripts/twilio-helper.sh recordings production + +# Get recording details +./.agent/scripts/twilio-helper.sh recording production "RExxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + +# Download recording +./.agent/scripts/twilio-helper.sh download-recording production "RExxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ./recordings/ + +# Get transcription +./.agent/scripts/twilio-helper.sh transcription production "TRxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + +# List all transcriptions +./.agent/scripts/twilio-helper.sh transcriptions production +``` + +### Phone Number Management + +```bash +# List owned numbers +./.agent/scripts/twilio-helper.sh numbers production + +# Search available numbers +./.agent/scripts/twilio-helper.sh search-numbers production US --area-code 415 + +# Search by capabilities +./.agent/scripts/twilio-helper.sh search-numbers production GB --sms --voice + +# Purchase number (requires confirmation) +./.agent/scripts/twilio-helper.sh buy-number production "+14155551234" + +# Release number (requires confirmation) +./.agent/scripts/twilio-helper.sh release-number production "+14155551234" +``` + +### Verify (2FA/OTP) + +```bash +# Create verification service (one-time setup) +./.agent/scripts/twilio-helper.sh verify-create-service production "MyApp Verification" + +# Send verification code +./.agent/scripts/twilio-helper.sh verify-send production "+1234567890" --channel sms + +# Check verification code +./.agent/scripts/twilio-helper.sh verify-check production "+1234567890" "123456" +``` + +### Lookup (Phone Validation) + +```bash +# Basic lookup +./.agent/scripts/twilio-helper.sh lookup production "+1234567890" + +# Carrier lookup +./.agent/scripts/twilio-helper.sh lookup production "+1234567890" --type carrier + +# Caller name lookup +./.agent/scripts/twilio-helper.sh lookup production "+1234567890" --type caller-name +``` + +### WhatsApp + +```bash +# Send WhatsApp message (requires approved template or 24h window) +./.agent/scripts/twilio-helper.sh whatsapp production "+1234567890" "Hello via WhatsApp!" + +# Send WhatsApp template +./.agent/scripts/twilio-helper.sh whatsapp-template production "+1234567890" "appointment_reminder" '{"1":"John","2":"Tomorrow 3pm"}' +``` + +### Account Status & Audit + +```bash +# List all configured accounts +./.agent/scripts/twilio-helper.sh accounts + +# Get account balance +./.agent/scripts/twilio-helper.sh balance production + +# Get usage summary +./.agent/scripts/twilio-helper.sh usage production + +# Full account audit +./.agent/scripts/twilio-helper.sh audit production +``` + +## Number Acquisition + +### Via Twilio API (Standard) + +Most numbers can be purchased directly via the API: + +```bash +# Search and purchase +./.agent/scripts/twilio-helper.sh search-numbers production US --area-code 212 +./.agent/scripts/twilio-helper.sh buy-number production "+12125551234" +``` + +### Via Telfon App (Recommended for End Users) + +For a better user experience with calling/SMS interface, use Telfon: + +- See `telfon.md` for setup guide +- Numbers purchased via Telfon are managed in Telfon's interface +- Numbers purchased via Twilio can be connected to Telfon + +### Via Twilio Support (Special Numbers) + +Some numbers are not available via API and require contacting Twilio support: + +- Toll-free numbers in certain countries +- Short codes +- Specific area codes with limited availability +- Numbers requiring regulatory approval + +**When API returns no results for a desired number**: + +```bash +# If search returns empty +./.agent/scripts/twilio-helper.sh search-numbers production GB --area-code 020 +# Result: No numbers available + +# AI should offer to help contact support +``` + +**AI-Assisted Support Request**: + +When numbers aren't available via API, the AI can help by: + +1. **Composing an email** to Twilio support with the request +2. **Using browser automation** to submit via Twilio console +3. **Drafting a support ticket** with all required details + +Template for support request: + +```text +Subject: Phone Number Request - [Country] [Type] + +Account SID: ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx +Request Type: Phone Number Acquisition + +Details: +- Country: [Country] +- Number Type: [Local/Toll-Free/Mobile] +- Desired Area Code: [Area code if applicable] +- Quantity: [Number of numbers needed] +- Use Case: [Brief description] +- Regulatory Documents: [Available/Will provide] + +Please advise on availability and any requirements. +``` + +## Webhook Configuration + +### Inbound SMS/Call Handling + +Configure webhooks for receiving messages and calls: + +```bash +# Update number webhook URLs +./.agent/scripts/twilio-helper.sh configure-webhooks production "+1234567890" \ + --sms-url "https://your-server.com/sms" \ + --voice-url "https://your-server.com/voice" +``` + +### Webhook Endpoints for CRM/AI Integration + +For CRM logging and AI orchestration, configure status callbacks: + +```json +{ + "webhooks": { + "sms_status": "https://your-server.com/webhooks/twilio/sms-status", + "voice_status": "https://your-server.com/webhooks/twilio/voice-status", + "recording_status": "https://your-server.com/webhooks/twilio/recording", + "transcription_callback": "https://your-server.com/webhooks/twilio/transcription" + } +} +``` + +### Deployment Options for Webhooks + +| Platform | Use Case | Setup | +|----------|----------|-------| +| **Coolify** | Self-hosted, full control | Deploy webhook handler app | +| **Vercel** | Serverless, quick setup | Edge functions for webhooks | +| **Cloudflare Workers** | Low latency, global | Worker scripts | +| **n8n/Make** | No-code automation | Built-in Twilio triggers | + +## AI Orchestration Integration + +### Use Cases for AI Agents + +| Scenario | Implementation | +|----------|----------------| +| **Appointment Reminders** | Scheduled SMS via cron/workflow | +| **Order Notifications** | Triggered by e-commerce events | +| **2FA for Apps** | Verify API integration | +| **Lead Follow-up** | CRM-triggered outreach | +| **Support Escalation** | Voice call when ticket urgent | +| **Survey Collection** | SMS with response handling | + +### CRM Logging Pattern + +```javascript +// Example webhook handler for CRM logging +app.post('/webhooks/twilio/sms-status', (req, res) => { + const { MessageSid, MessageStatus, To, From } = req.body; + + // Log to CRM + crm.logCommunication({ + type: 'sms', + direction: 'outbound', + status: MessageStatus, + recipient: To, + sender: From, + externalId: MessageSid, + timestamp: new Date() + }); + + res.sendStatus(200); +}); +``` + +### Recording Transcription for AI Analysis + +```bash +# Enable recording on calls +./.agent/scripts/twilio-helper.sh call production "+1234567890" \ + --record \ + --transcribe \ + --transcription-callback "https://your-server.com/webhooks/twilio/transcription" +``` + +Transcriptions can be: + +- Stored for compliance/training +- Analyzed by AI for sentiment/intent +- Summarized for CRM notes +- Used for quality assurance + +## Security Best Practices + +### Credential Security + +```bash +# Store credentials securely +# In ~/.config/aidevops/mcp-env.sh (600 permissions) +export TWILIO_ACCOUNT_SID_PRODUCTION="ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" +export TWILIO_AUTH_TOKEN_PRODUCTION="your_token_here" + +# Never commit credentials to git +# Use configs/twilio-config.json (gitignored) +``` + +### Webhook Security + +```bash +# Validate webhook signatures +# Twilio signs all webhook requests +# Verify X-Twilio-Signature header + +# Example validation (Node.js) +const twilio = require('twilio'); +const valid = twilio.validateRequest( + authToken, + req.headers['x-twilio-signature'], + webhookUrl, + req.body +); +``` + +### Rate Limiting + +- Twilio has built-in rate limits +- Implement application-level throttling for bulk operations +- Use Messaging Services for high-volume SMS (automatic queuing) + +## Troubleshooting + +### Common Issues + +#### Authentication Errors + +```bash +# Verify credentials +./.agent/scripts/twilio-helper.sh status production + +# Check environment variables +echo $TWILIO_ACCOUNT_SID +``` + +#### Message Delivery Issues + +```bash +# Check message status +./.agent/scripts/twilio-helper.sh message-status production "SMxxxxxxxx" + +# Common status codes: +# - queued: Message queued for sending +# - sent: Message sent to carrier +# - delivered: Confirmed delivery +# - undelivered: Delivery failed +# - failed: Message could not be sent +``` + +#### Number Not Available + +```bash +# Search returns empty - try different criteria +./.agent/scripts/twilio-helper.sh search-numbers production US --contains "555" + +# If still unavailable, contact Twilio support (see above) +``` + +#### Webhook Not Receiving + +```bash +# Verify webhook URL is accessible +curl -X POST https://your-server.com/webhooks/twilio/sms -d "test=1" + +# Check Twilio debugger +# https://console.twilio.com/debugger +``` + +## Monitoring & Analytics + +### Usage Monitoring + +```bash +# Daily usage summary +./.agent/scripts/twilio-helper.sh usage production --period day + +# Monthly costs +./.agent/scripts/twilio-helper.sh usage production --period month + +# Set up alerts in Twilio console for: +# - Balance threshold +# - Error rate spike +# - Unusual activity +``` + +### Delivery Analytics + +```bash +# Message delivery rates +./.agent/scripts/twilio-helper.sh analytics production messages --days 7 + +# Call completion rates +./.agent/scripts/twilio-helper.sh analytics production calls --days 7 +``` + +## Related Documentation + +- `telfon.md` - Telfon app setup and integration +- `ses.md` - Email integration (for multi-channel) +- `workflows/webhook-handlers.md` - Webhook deployment patterns +- Twilio Docs: https://www.twilio.com/docs +- Twilio AUP: https://www.twilio.com/en-us/legal/aup +- Twilio Console: https://console.twilio.com/ diff --git a/configs/mcp-templates/twilio.json b/configs/mcp-templates/twilio.json new file mode 100644 index 00000000..1adcb071 --- /dev/null +++ b/configs/mcp-templates/twilio.json @@ -0,0 +1,61 @@ +{ + "_comment": "Twilio MCP Configuration Templates for AI Assistants", + "_docs": "https://www.twilio.com/docs", + "_note": "Twilio does not have an official MCP server. Use the helper script via Bash tool.", + + "opencode": { + "_comment": "OpenCode uses helper script via Bash - no MCP server needed", + "_usage": "Agents with Bash tool access can use: ~/.aidevops/agents/scripts/twilio-helper.sh", + "_enabled_agents": ["Build+", "AI-DevOps", "Marketing", "Sales"] + }, + + "claude_code": { + "_comment": "Claude Code uses helper script via Bash - no MCP server needed", + "_usage": "Use Bash tool to call: ~/.aidevops/agents/scripts/twilio-helper.sh" + }, + + "cursor": { + "_comment": "Cursor uses helper script via terminal - no MCP server needed", + "_usage": "Run in terminal: ~/.aidevops/agents/scripts/twilio-helper.sh" + }, + + "environment_variables": { + "_comment": "Store in ~/.config/aidevops/mcp-env.sh", + "TWILIO_ACCOUNT_SID_PRODUCTION": "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "TWILIO_AUTH_TOKEN_PRODUCTION": "your_auth_token_here", + "TWILIO_ACCOUNT_SID_STAGING": "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "TWILIO_AUTH_TOKEN_STAGING": "your_auth_token_here" + }, + + "helper_script_commands": { + "list_accounts": "twilio-helper.sh accounts", + "send_sms": "twilio-helper.sh sms ", + "make_call": "twilio-helper.sh call [--record]", + "list_numbers": "twilio-helper.sh numbers ", + "search_numbers": "twilio-helper.sh search-numbers [--area-code X]", + "verify_send": "twilio-helper.sh verify-send [sms|call]", + "verify_check": "twilio-helper.sh verify-check ", + "whatsapp": "twilio-helper.sh whatsapp ", + "recordings": "twilio-helper.sh recordings ", + "transcription": "twilio-helper.sh transcription ", + "audit": "twilio-helper.sh audit " + }, + + "ai_orchestration_patterns": { + "appointment_reminder": { + "description": "Send SMS reminder before appointment", + "command": "twilio-helper.sh sms production \"+1234567890\" \"Reminder: Your appointment is tomorrow at 3pm\"", + "trigger": "cron or workflow event" + }, + "otp_verification": { + "description": "Send and verify OTP code", + "send": "twilio-helper.sh verify-send production \"+1234567890\" sms", + "check": "twilio-helper.sh verify-check production \"+1234567890\" \"123456\"" + }, + "call_with_recording": { + "description": "Make call and record for CRM", + "command": "twilio-helper.sh call production \"+1234567890\" --record", + "post_action": "Download recording and transcription for CRM logging" + } + } +} diff --git a/configs/twilio-config.json.txt b/configs/twilio-config.json.txt new file mode 100644 index 00000000..a9e265d6 --- /dev/null +++ b/configs/twilio-config.json.txt @@ -0,0 +1,71 @@ +{ + "accounts": { + "production": { + "account_sid": "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "auth_token": "YOUR_PRODUCTION_AUTH_TOKEN_HERE", + "description": "Production Twilio account", + "phone_numbers": [ + "+1234567890" + ], + "default_from": "+1234567890", + "messaging_service_sid": "MGxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "verify_service_sid": "VAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "whatsapp_from": "+14155238886", + "webhooks": { + "sms_status": "https://your-server.com/webhooks/twilio/sms-status", + "voice_status": "https://your-server.com/webhooks/twilio/voice-status", + "recording_callback": "https://your-server.com/webhooks/twilio/recording", + "transcription_callback": "https://your-server.com/webhooks/twilio/transcription" + } + }, + "staging": { + "account_sid": "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "auth_token": "YOUR_STAGING_AUTH_TOKEN_HERE", + "description": "Staging/Test Twilio account", + "phone_numbers": [ + "+1987654321" + ], + "default_from": "+1987654321", + "verify_service_sid": "VAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + }, + "client-project": { + "account_sid": "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "auth_token": "YOUR_CLIENT_AUTH_TOKEN_HERE", + "description": "Client project Twilio account", + "phone_numbers": [ + "+1555123456" + ], + "default_from": "+1555123456" + } + }, + "defaults": { + "sms_status_callback": true, + "voice_record": false, + "voice_transcribe": false, + "verify_channel": "sms" + }, + "compliance": { + "require_consent_confirmation": true, + "block_bulk_without_messaging_service": true, + "max_bulk_recipients": 100, + "rate_limit_per_second": 10 + }, + "telfon": { + "recommended": true, + "website": "https://mytelfon.com/", + "ios_app": "https://apps.apple.com/in/app/telfon-twilio-calls-chats/id6443471885", + "android_app": "https://play.google.com/store/apps/details?id=com.wmt.cloud_telephony.android", + "chrome_extension": "https://chromewebstore.google.com/detail/telfon-twilio-calls/bgkbahmggkomlcagkagcmiggkmcjmgdi" + }, + "aup_reference": { + "url": "https://www.twilio.com/en-us/legal/aup", + "last_reviewed": "2025-01-11", + "key_prohibitions": [ + "Spam and unsolicited bulk messages", + "Phishing and deceptive content", + "Identity spoofing", + "Bypassing service limitations", + "Illegal activities" + ] + } +}