⛰️ LifeOS — The AI-powered Life Operating System that helps you hill climb to wherever you're going.
feat(pai-voice-system): Add complete voice server implementation v1.4.0
Daniel Miessler34385771ac7f
diff --git a/Packs/pai-voice-system/INSTALL.md b/Packs/pai-voice-system/INSTALL.mdindex 60ed7615..f835a031 100644--- a/Packs/pai-voice-system/INSTALL.md+++ b/Packs/pai-voice-system/INSTALL.md@@ -1,91 +1,19 @@-# Kai Voice System - Installation Guide+# PAI Voice System - Installation Guide## Prerequisites- **Bun runtime**: `curl -fsSL https://bun.sh/install | bash`-- **macOS or Linux**: Cross-platform audio support included-- **TTS API account** (choose one):- - **Google Cloud** (recommended): 4M free chars/month - [console.cloud.google.com](https://console.cloud.google.com)- - **ElevenLabs**: ~10K free chars/month - [elevenlabs.io](https://elevenlabs.io)+- **macOS**: Currently the primary supported platform+- **ElevenLabs account**: [elevenlabs.io](https://elevenlabs.io) - API key required- **Required PAI Packs** (install these first):- `pai-hook-system` - Foundation hook infrastructure- `pai-core-install` - Skills, identity, and response format----## Platform Compatibility Check--### Step 0.0: Operating System Check--```bash-OS_TYPE="$(uname -s)"-echo "Detected OS: $OS_TYPE"--if [ "$OS_TYPE" = "Darwin" ]; then- echo "✓ macOS detected - Voice system is fully supported"- echo " Audio: afplay (built-in)"-elif [ "$OS_TYPE" = "Linux" ]; then- echo "✓ Linux detected - Voice system is fully supported"- echo ""- echo "Checking audio players..."- if command -v mpg123 &> /dev/null; then- echo " ✓ mpg123 found (preferred)"- elif command -v mpv &> /dev/null; then- echo " ✓ mpv found"- elif command -v paplay &> /dev/null; then- echo " ✓ paplay found"- else- echo " ⚠️ No audio player found. Install one:"- echo " sudo apt install mpg123 # Recommended"- echo " sudo apt install mpv"- fi-else- echo ""- echo "❌ UNSUPPORTED: $OS_TYPE detected"- echo "The Kai Voice System supports macOS and Linux only."- echo "Windows is not currently supported."-fi-```--**AI Agent Instructions:**-- If OS is macOS → Proceed with installation-- If OS is Linux → Ensure audio player is installed (mpg123 recommended), then proceed-- If OS is Windows → STOP, do not proceed, inform user it's unsupported-------## Pre-Installation: Port Configuration--### Step 0.1: Choose Voice Server Port--The default port is **8888**. If this port is in use, choose an alternative.--```bash-# Check if default port 8888 is available-if lsof -i :8888 > /dev/null 2>&1; then- echo "⚠️ Port 8888 is IN USE"- lsof -i :8888 | head -5- echo ""- echo "Options:"- echo " 1. Stop the service using port 8888"- echo " 2. Use a different port (set VOICE_SERVER_PORT in .env)"-else- echo "✓ Port 8888 is available"-fi-```--**To use a custom port:** Add to `$PAI_DIR/.env`:-```bash-VOICE_SERVER_PORT=8889 # or any available port-```--The voice server and hooks will automatically use this port if set.------## Pre-Installation: System Analysis-### Step 0.2: Verify Required Dependencies+### Step 0.1: Verify Required Dependencies```bashPAI_CHECK="${PAI_DIR:-$HOME/.config/pai}"@@ -93,7 +21,7 @@ PAI_CHECK="${PAI_DIR:-$HOME/.config/pai}"echo "=== Checking Required Dependencies ==="# Check hook system (REQUIRED)-if [ -f "$PAI_CHECK/hooks/lib/observability.ts" ]; then+if [ -d "$PAI_CHECK/hooks" ]; thenecho "✓ pai-hook-system is installed"elseecho "❌ pai-hook-system NOT installed - REQUIRED!"@@ -105,196 +33,132 @@ if [ -d "$PAI_CHECK/skills" ] && [ -f "$PAI_CHECK/skills/CORE/SKILL.md" ]; thenelseecho "❌ pai-core-install NOT installed - REQUIRED!"fi--# Check for TTS API key (either Google or ElevenLabs)-PAI_ENV="${PAI_DIR:-$HOME/.config/pai}/.env"-if [ -f "$PAI_ENV" ]; then- if grep -q "GOOGLE_API_KEY" "$PAI_ENV"; then- echo "✓ GOOGLE_API_KEY found (Google TTS available)"- fi- if grep -q "ELEVENLABS_API_KEY" "$PAI_ENV"; then- echo "✓ ELEVENLABS_API_KEY found (ElevenLabs available)"- fi- if ! grep -q "GOOGLE_API_KEY\|ELEVENLABS_API_KEY" "$PAI_ENV"; then- echo "⚠️ No TTS API key found - add GOOGLE_API_KEY or ELEVENLABS_API_KEY to $PAI_ENV"- fi-else- echo "⚠️ No .env file found at $PAI_ENV"-fi```-### Step 0.3: Check for Existing Voice System+### Step 0.2: Check Port Availability```bash-PAI_CHECK="${PAI_DIR:-$HOME/.config/pai}"--# Check for existing voice directory-if [ -d "$PAI_CHECK/voice" ]; then- echo "⚠️ Voice directory EXISTS"-else- echo "✓ No existing voice directory"-fi--# Check for running voice server+# Check if default port 8888 is availableif lsof -i :8888 > /dev/null 2>&1; then- echo "⚠️ Something running on port 8888"+ echo "⚠️ Port 8888 is IN USE"+ lsof -i :8888 | head -5+ echo ""+ echo "Options:"+ echo " 1. Stop the service using port 8888"+ echo " 2. Use a different port (set VOICE_SERVER_PORT in ~/.env)"elseecho "✓ Port 8888 is available"fi```-### Step 0.4: Stop Existing Voice Server (If Running)--```bash-# Stop any running voice server-pkill -f "voice/server.ts" 2>/dev/null || true--# Unload LaunchAgent if exists (macOS)-if [ -f "$HOME/Library/LaunchAgents/com.pai.voice-server.plist" ]; then- launchctl unload "$HOME/Library/LaunchAgents/com.pai.voice-server.plist" 2>/dev/null-fi-```----## Step 1: Create Directory Structure```bash+PAI_DIR="${PAI_DIR:-$HOME/.config/pai}"+mkdir -p $PAI_DIR/hooks/lib-mkdir -p $PAI_DIR/configmkdir -p $PAI_DIR/voice-server```----## Step 2: Install Prosody Enhancer Library--Copy `src/hooks/lib/prosody-enhancer.ts` to `$PAI_DIR/hooks/lib/prosody-enhancer.ts`-----+## Step 2: Install Voice Server-## Step 3: Install Voice Hooks+Copy the voice server files:-Copy the following files:-- `src/hooks/stop-hook-voice.ts` → `$PAI_DIR/hooks/stop-hook-voice.ts`-- `src/hooks/subagent-stop-hook-voice.ts` → `$PAI_DIR/hooks/subagent-stop-hook-voice.ts`+```bash+# From pack directory+cp src/voice/server.ts $PAI_DIR/voice-server/server.ts+cp src/voice/manage.sh $PAI_DIR/voice-server/manage.sh+chmod +x $PAI_DIR/voice-server/manage.sh+```----## Step 4: Install Voice Configuration--Copy `config/voice-personalities.json` to `$PAI_DIR/config/voice-personalities.json`+## Step 3: Install Prosody Enhancer------## Step 5: Install Voice Server+Copy the prosody enhancer library:-Copy `src/voice/server.ts` to `$PAI_DIR/voice-server/server.ts`+```bash+cp src/hooks/lib/prosody-enhancer.ts $PAI_DIR/hooks/lib/prosody-enhancer.ts+```----## Step 6: Set Up TTS Provider--Choose one of the following providers:--### Option A: Google Cloud TTS (Recommended)+## Step 4: Install Voice Hooks-**Why Google?** 4 million free characters per month vs ~10K for ElevenLabs. Effectively unlimited for PAI notifications.--1. **Create a Google Cloud project** at [console.cloud.google.com](https://console.cloud.google.com)-2. **Enable Cloud Text-to-Speech API**:- - Go to APIs & Services → Library- - Search for "Cloud Text-to-Speech API"- - Click Enable-3. **Create API key**:- - Go to APIs & Services → Credentials- - Create Credentials → API Key- - (Optional) Restrict key to Cloud Text-to-Speech API-4. **Add to $PAI_DIR/.env**:+Copy the voice hooks:```bash-TTS_PROVIDER=google-GOOGLE_API_KEY=your-google-api-key-GOOGLE_TTS_VOICE=en-US-Neural2-J # Optional, this is the default+cp src/hooks/stop-hook-voice.ts $PAI_DIR/hooks/stop-hook-voice.ts+cp src/hooks/subagent-stop-hook-voice.ts $PAI_DIR/hooks/subagent-stop-hook-voice.ts```-5. **Test your API key**:--```bash-curl -X POST "https://texttospeech.googleapis.com/v1/text:synthesize?key=YOUR_API_KEY" \- -H "Content-Type: application/json" \- -d '{"input":{"text":"Hello, this is Google Cloud TTS."},"voice":{"languageCode":"en-US","name":"en-US-Neural2-J"},"audioConfig":{"audioEncoding":"MP3"}}' \- | jq -r '.audioContent' | base64 -d > test.mp3--# Play (macOS: afplay, Linux: mpg123)-mpg123 test.mp3 || afplay test.mp3-rm test.mp3-```+----### Option B: ElevenLabs+## Step 5: Configure ElevenLabs API1. **Sign up** at [elevenlabs.io](https://elevenlabs.io)2. **Get your API key** from Profile → API key-3. **Add to $PAI_DIR/.env**:+3. **Choose a voice** from the Voice Library and copy its ID+4. **Add to ~/.env**:```bash-TTS_PROVIDER=elevenlabs-ELEVENLABS_API_KEY=your-api-key-ELEVENLABS_VOICE_ID=your-voice-id+ELEVENLABS_API_KEY=your-api-key-here+ELEVENLABS_VOICE_ID=your-voice-id-here```-4. **Test your API key**:+### Test Your API Key```bash-curl -X POST "https://api.elevenlabs.io/v1/text-to-speech/s3TPKV1kjDlVtZbl4Ksh" \- -H "xi-api-key: YOUR_API_KEY_HERE" \+curl -X POST "https://api.elevenlabs.io/v1/text-to-speech/YOUR_VOICE_ID" \+ -H "xi-api-key: YOUR_API_KEY" \-H "Content-Type: application/json" \-d '{"text": "Hello, this is a test.", "model_id": "eleven_turbo_v2_5"}' \--output test.mp3-mpg123 test.mp3 || afplay test.mp3 # Should hear "Hello, this is a test"+afplay test.mp3 # Should hear "Hello, this is a test"rm test.mp3```----## Step 7: Register Hooks+## Step 6: Register Hooks-Merge the hook configuration from `config/settings-hooks.json` into your `~/.claude/settings.json`:+Add the voice hooks to your `~/.claude/settings.json`:```json{"hooks": {"Stop": [{- "hooks": [- {- "type": "command",- "command": "bun run $PAI_DIR/hooks/stop-hook-voice.ts"- }- ]+ "type": "command",+ "command": "bun run $PAI_DIR/hooks/stop-hook-voice.ts"}],"SubagentStop": [{- "hooks": [- {- "type": "command",- "command": "bun run $PAI_DIR/hooks/subagent-stop-hook-voice.ts"- }- ]+ "type": "command",+ "command": "bun run $PAI_DIR/hooks/subagent-stop-hook-voice.ts"}]}}```+**Note:** Replace `$PAI_DIR` with your actual PAI directory path, or ensure the environment variable is set.+----## Step 8: Start Voice Server+## Step 7: Start Voice Server```bash# Start the voice server+$PAI_DIR/voice-server/manage.sh start++# Or manuallybun run $PAI_DIR/voice-server/server.ts &# Verify it's running@@ -303,12 +167,12 @@ curl http://localhost:8888/health----## Step 9: (Optional) Set Up Auto-Start+## Step 8: (Optional) Auto-Start on Login-Create a LaunchAgent to auto-start the voice server on login:+### macOS (LaunchAgent)```bash-cat > ~/Library/LaunchAgents/com.pai.voice-server.plist << 'EOF'+cat > ~/Library/LaunchAgents/com.pai.voice-server.plist << EOF<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0">@@ -317,92 +181,31 @@ cat > ~/Library/LaunchAgents/com.pai.voice-server.plist << 'EOF'<string>com.pai.voice-server</string><key>ProgramArguments</key><array>- <string>/Users/YOUR_USERNAME/.bun/bin/bun</string>+ <string>$HOME/.bun/bin/bun</string><string>run</string>- <string>/Users/YOUR_USERNAME/.config/pai/voice-server/server.ts</string>+ <string>$PAI_DIR/voice-server/server.ts</string></array><key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>StandardOutPath</key>- <string>/Users/YOUR_USERNAME/Library/Logs/pai-voice-server.log</string>+ <string>$HOME/Library/Logs/pai-voice-server.log</string><key>StandardErrorPath</key>- <string>/Users/YOUR_USERNAME/Library/Logs/pai-voice-server.log</string>+ <string>$HOME/Library/Logs/pai-voice-server.log</string></dict></plist>EOF-# Replace YOUR_USERNAME with your actual username-# Fallback if USER is undefined (edge case but deterministic)-USERNAME="${USER:-$(whoami)}"--if [ "$(uname -s)" = "Darwin" ]; then- sed -i '' "s/YOUR_USERNAME/${USERNAME}/g" ~/Library/LaunchAgents/com.pai.voice-server.plist-else- sed -i "s/YOUR_USERNAME/${USERNAME}/g" ~/Library/LaunchAgents/com.pai.voice-server.plist-fi-# Load the agentlaunchctl load ~/Library/LaunchAgents/com.pai.voice-server.plist```-### Linux (systemd user service)--**Note:** Requires systemd (most modern distros have it)-**WSL2 users:** Run `sudo systemctl enable --now systemd` first if systemd isn't enabled--```bash-mkdir -p ~/.config/systemd/user-mkdir -p ~/.config/pai/voice-server # Ensure log directory exists--cat > ~/.config/systemd/user/pai-voice-server.service << 'EOF'-[Unit]-Description=PAI Voice Server-After=network.target--[Service]-Type=simple-# Use %h for home directory (systemd variable expansion)-WorkingDirectory=%h/.config/pai/voice-server-# Ensure log directory exists before starting-ExecStartPre=/bin/mkdir -p %h/.config/pai/voice-server-# Run server.ts from working directory-ExecStart=%h/.bun/bin/bun run server.ts-Restart=on-failure-RestartSec=5-# Logging-StandardOutput=append:%h/.config/pai/voice-server/voice-server.log-StandardError=append:%h/.config/pai/voice-server/voice-server.log-# Environment (bun needs to find node_modules if any)-Environment=PATH=%h/.bun/bin:/usr/local/bin:/usr/bin--[Install]-WantedBy=default.target-EOF--# Enable linger so service survives logout-loginctl enable-linger $USER--# Reload, enable, and start-systemctl --user daemon-reload-systemctl --user enable pai-voice-server.service-systemctl --user start pai-voice-server.service--# Verify it's running-systemctl --user status pai-voice-server.service--# Test the server responds-curl http://localhost:8888/health--echo "✓ Voice server will auto-start on boot"-echo " Control: systemctl --user {start|stop|restart|status} pai-voice-server.service"-echo " Logs: journalctl --user -u pai-voice-server.service -f"-```+**Note:** You'll need to replace `$HOME` and `$PAI_DIR` with actual paths in the plist file.----## Step 10: Verify Installation+## Step 9: Verify InstallationRun the verification checklist in VERIFY.md to confirm everything works.@@ -413,39 +216,26 @@ Run the verification checklist in VERIFY.md to confirm everything works.### No Voice Output1. Check voice server is running: `curl http://localhost:8888/health`-2. Verify TTS API key is set in `$PAI_DIR/.env`-3. Check which provider is active: response shows `provider: google` or `provider: elevenlabs`-4. Check logs: `tail -f $PAI_DIR/voice-server/voice-server.log`--### Google TTS Errors--| Error | Solution |-|-------|----------|-| `SERVICE_DISABLED` | Enable Cloud Text-to-Speech API in Google Cloud Console |-| `API_KEY_SERVICE_BLOCKED` | Add Cloud Text-to-Speech API to allowed APIs for your key |-| `PERMISSION_DENIED` | Check API key is valid and has correct permissions |+2. Verify API key is set in `~/.env`+3. Check logs: `tail -f /tmp/pai-voice-server.log`### ElevenLabs Errors| Error | Solution ||-------|----------|-| `invalid_uid` | Remove quotes from API key in .env: `ELEVENLABS_API_KEY=your_key` not `"abc123"` |-| `quota_exceeded` | Free tier exhausted. Consider switching to Google TTS |+| `invalid_uid` | Remove quotes from API key in .env |+| `quota_exceeded` | Free tier exhausted (~10K chars/month) || `missing_permissions` | Enable TTS permission in ElevenLabs dashboard |+| `voice_not_found` | Check voice ID is correct |-### Wrong Voice--1. Verify voice ID in `config/voice-personalities.json`-2. Check agent type is being detected correctly in hooks+### Audio Playback Issues-### Audio Playback Issues (Linux)--1. Install an audio player: `sudo apt install mpg123`-2. Check it works: `echo "test" | mpg123 -`-3. Server auto-detects: mpg123 → mpv → paplay+1. Verify `afplay` works: `afplay /System/Library/Sounds/Ping.aiff`+2. Check system volume+3. Check audio permissions in System Preferences-### Audio Playback Issues (macOS)+### Server Won't Start-1. Ensure `afplay` is available (macOS built-in)-2. Check system volume-3. Verify audio permissions+1. Check port 8888 is free: `lsof -i :8888`+2. Check bun is installed: `bun --version`+3. Check for syntax errors: `bun run $PAI_DIR/voice-server/server.ts`diff --git a/Packs/pai-voice-system/README.md b/Packs/pai-voice-system/README.mdindex b10c769f..778f3e40 100644--- a/Packs/pai-voice-system/README.md+++ b/Packs/pai-voice-system/README.md@@ -1,23 +1,23 @@----name: Kai Voice System-pack-id: danielmiessler-pai-voice-system-core-v1.3.0-version: 1.3.0+name: PAI Voice System+pack-id: danielmiessler-pai-voice-system-v1.4.0+version: 1.4.0author: danielmiessler-description: Voice notification system with multi-provider TTS (Google Cloud or ElevenLabs), prosody enhancement for natural speech, and agent personality-driven voice delivery+description: Voice notification system with ElevenLabs TTS, prosody enhancement for natural speech, and agent personality-driven voice deliverytype: featurepurpose-type: [notifications, accessibility, automation]-platform: macos, linux+platform: macosdependencies:- pai-hook-system (required) - Hooks trigger voice notifications- pai-core-install (required) - Skills, identity, and response format drive voice output-keywords: [voice, tts, elevenlabs, google-cloud-tts, notifications, prosody, speech, agents, personalities, accessibility]+keywords: [voice, tts, elevenlabs, notifications, prosody, speech, agents, personalities, accessibility]---<p align="center">- <img src="../icons/pai-voice-system-v2.png" alt="Kai Voice System" width="256">+ <img src="../icons/pai-voice-system-v2.png" alt="PAI Voice System" width="256"></p>-# Kai Voice System (pai-voice-system)+# PAI Voice System (pai-voice-system)> Voice notification system with natural speech synthesis and personality-driven delivery@@ -25,81 +25,80 @@ keywords: [voice, tts, elevenlabs, google-cloud-tts, notifications, prosody, spe----## 🚨 Platform Requirements+## Platform Requirements| Platform | Status | Notes ||----------|--------|-------|| **macOS** | ✅ Fully Supported | Uses `afplay` (built-in) for audio playback |-| **Linux** | ✅ Fully Supported | Auto-detects `mpg123`, `mpv`, or `paplay` for audio |+| **Linux** | ⚠️ Experimental | Requires audio player modification || **Windows** | ❌ Not Supported | No current implementation |-**Audio player priority (Linux):** mpg123 → mpv → paplay (install one: `sudo apt install mpg123`)----## What This Pack Provides- **Spoken Notifications**: Hear task completions via text-to-speech-- **Multi-Provider TTS**: Choose between Google Cloud TTS or ElevenLabs-- **Prosody Enhancement**: Natural speech patterns with emotional markers+- **ElevenLabs TTS**: High-quality voice synthesis via ElevenLabs API+- **Prosody Enhancement**: Natural speech patterns with 13 emotional markers- **Agent Personalities**: Different voices for different agent types- **Intelligent Cleaning**: Strips code blocks and artifacts for clean speech- **Graceful Degradation**: Works silently when voice server is offline-## TTS Provider Options--Choose your text-to-speech provider based on your needs:+## Voice Server-| Provider | Free Tier | Quality | Setup |-|----------|-----------|---------|-------|-| **Google Cloud TTS** | 4M chars/month | High (Neural2/WaveNet) | Google API key |-| **ElevenLabs** | ~10K chars/month | Premium | ElevenLabs API key |+The voice server runs locally on port 8888 and:+- Receives notification requests via HTTP POST+- Generates speech using ElevenLabs API+- Plays audio using system audio player+- Supports emotional markers for prosody variation-**Recommendation:** Google Cloud TTS offers **400x more free characters** — effectively unlimited for typical PAI notification usage.+### Endpoints-### Configuration+| Endpoint | Method | Purpose |+|----------|--------|---------|+| `/notify` | POST | Full notification with voice/emotion support |+| `/pai` | POST | Simple notification with default voice |+| `/health` | GET | Health check and configuration status |-Set in your `.env` file:+### Example Request```bash-# Choose provider: "google" or "elevenlabs" (default: elevenlabs)-TTS_PROVIDER=google--# Google Cloud TTS (if using google)-GOOGLE_API_KEY=your_google_api_key-GOOGLE_TTS_VOICE=en-US-Neural2-J # Optional, has sensible default--# ElevenLabs (if using elevenlabs)-ELEVENLABS_API_KEY=your_api_key-ELEVENLABS_VOICE_ID=your_voice_id+curl -X POST http://localhost:8888/notify \+ -H "Content-Type: application/json" \+ -d '{"message": "Task completed successfully", "voice_enabled": true}'```-### Google Cloud TTS Voices+## Architecture Overview-| Voice | Type | Description |-|-------|------|-------------|-| `en-US-Neural2-J` | Neural2 (default) | Natural male voice |-| `en-US-Neural2-F` | Neural2 | Natural female voice |-| `en-US-Wavenet-D` | WaveNet | Premium male voice |-| `en-US-Standard-A` | Standard | Basic voice (more free chars) |+```+┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐+│ Stop Hook │ ───► │ Voice Server │ ───► │ ElevenLabs │+│ (extracts msg) │ │ (localhost:8888)│ │ TTS API │+└─────────────────┘ └──────────────────┘ └─────────────────┘+ │ │+ │ ▼+ │ ┌─────────────────┐+ │ │ Audio Player │+ │ │ (afplay) │+ │ └─────────────────┘+ │+ ▼+┌─────────────────┐+│ Response Format │+│ 🗣️ [AI_NAME]: │+└─────────────────┘+```-See [Google Cloud TTS voices](https://cloud.google.com/text-to-speech/docs/voices) for full list.+## Response Format Integration-## Architecture Overview+The voice system reads from the response format defined in `pai-core-install`:```-┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐-│ Stop Hook │ ───► │ Voice Server │ ───► │ TTS Provider │-│ (extracts msg) │ │ (localhost:8888)│ │ │-└─────────────────┘ └──────────────────┘ │ ┌─────────────┐ │- │ │ Google TTS │ │- │ └─────────────┘ │- │ ┌─────────────┐ │- │ │ ElevenLabs │ │- │ └─────────────┘ │- └─────────────────┘+🗣️ PAI: [12 words max - spoken aloud by voice server]```+The hook extracts this line, enhances it with prosody markers, and sends it to the voice server.+## The 5-Layer Prosody Enhancement Pipeline```@@ -118,33 +117,18 @@ See [Google Cloud TTS voices](https://cloud.google.com/text-to-speech/docs/voice| Component | File | Purpose ||-----------|------|---------|+| Voice server | `src/voice/server.ts` | HTTP server for TTS requests |+| Server management | `src/voice/manage.sh` | Start/stop/restart server || Voice stop hook | `src/hooks/stop-hook-voice.ts` | Main agent voice notification || Subagent voice hook | `src/hooks/subagent-stop-hook-voice.ts` | Subagent voice notification || Prosody enhancer | `src/hooks/lib/prosody-enhancer.ts` | Add emotion/pauses to speech |-| Voice server | `src/voice/server.ts` | HTTP server for TTS requests |-| Server management | `src/voice/manage.sh` | Start/stop/restart server |-| Voice personalities | `config/voice-personalities.json` | Agent voice configurations |-| Hook configuration | `config/settings-hooks.json` | Hook registration template |+| Voice personalities | `voice-personalities.json` | Agent voice configurations |**Summary:**-- **Files created:** 7+- **Files created:** 6- **Hooks registered:** 2 (Stop, SubagentStop)- **Dependencies:** pai-hook-system (required), pai-core-install (required)-- **TTS API key:** Google Cloud API key OR ElevenLabs API key (choose one)--## Agent Voice Mapping--| Agent Type | Voice Name | Speaking Rate | Stability | Archetype |-|------------|------------|---------------|-----------|-----------|-| PAI (Main) | Your DA | 235 wpm | 0.38 | enthusiast |-| Intern | Dev Patel | 270 wpm | 0.30 | enthusiast |-| Engineer | Marcus Webb | 212 wpm | 0.72 | wise-leader |-| Architect | Serena Blackwood | 205 wpm | 0.75 | wise-leader |-| Researcher | Ava Sterling | 229 wpm | 0.64 | analyst |-| Designer | Aditi Sharma | 226 wpm | 0.52 | critic |-| Artist | Priya Desai | 215 wpm | 0.20 | enthusiast |-| Pentester | Rook Blackburn | 260 wpm | 0.18 | enthusiast |-| Writer | Emma Hartley | 230 wpm | 0.48 | storyteller |+- **TTS API key:** ElevenLabs API key required## Emotional Detection@@ -162,14 +146,64 @@ The prosody enhancer detects emotional context from message patterns:| 8 | success | "completed", "fixed", "deployed" | [✨ success] || 9 | caution | "warning", "careful", "partial" | [⚠️ caution] |+These markers are embedded in the message and the voice server adjusts stability/similarity_boost parameters accordingly.++## Environment Variables++| Variable | Required | Default | Description |+|----------|----------|---------|-------------|+| `ELEVENLABS_API_KEY` | Yes | - | Your ElevenLabs API key |+| `ELEVENLABS_VOICE_ID` | Yes | - | Default voice ID for TTS |+| `VOICE_SERVER_PORT` | No | 8888 | Voice server port |+| `VOICE_SERVER_URL` | No | http://localhost:8888 | Voice server URL (for hooks) |+| `PAI_DIR` | No | ~/.config/pai | PAI installation directory |++## Agent Voice Mapping++Configure multiple voices in `voice-personalities.json` for multi-agent conversations:++```json+{+ "voices": {+ "PAI": {+ "voice_id": "YOUR_VOICE_ID",+ "stability": 0.5,+ "similarity_boost": 0.5,+ "description": "Default PAI voice"+ },+ "Engineer": {+ "voice_id": "ENGINEER_VOICE_ID",+ "stability": 0.72,+ "similarity_boost": 0.65,+ "description": "Technical, precise"+ }+ }+}+```+## Credits- **Author:** Daniel Miessler-- **Origin:** Extracted from production Kai system (2024-2025)+- **Origin:** Extracted from production Kai system (2024-2026)- **License:** MIT## Works Well With- **pai-hook-system** (required) - Hooks trigger voice notifications-- **pai-core-install** (required) - Response format provides 🎯 COMPLETED line+- **pai-core-install** (required) - Response format provides 🗣️ line- **pai-history-system** - Complementary functionality++## Changelog++### 1.4.0 - 2026-01-08+- **BREAKING:** Removed Google Cloud TTS support (ElevenLabs only)+- Added complete voice server implementation (`src/voice/server.ts`)+- Added server management script (`src/voice/manage.sh`)+- Added stop hook for main agent (`src/hooks/stop-hook-voice.ts`)+- Added stop hook for subagents (`src/hooks/subagent-stop-hook-voice.ts`)+- Updated response format from `🎯 COMPLETED:` to `🗣️ [AI_NAME]:`+- Integrated with DAIDENTITY.md for AI name and voice ID++### 1.3.0 - 2026-01-03+- Initial release with prosody enhancer+- Voice personalities configurationdiff --git a/Packs/pai-voice-system/VERIFY.md b/Packs/pai-voice-system/VERIFY.mdindex 17e85592..447fc834 100644--- a/Packs/pai-voice-system/VERIFY.md+++ b/Packs/pai-voice-system/VERIFY.md@@ -1,29 +1,4 @@-# Kai Voice System - Verification Checklist--## 🚨 Platform Verification (FIRST)--> **FOR AI AGENTS:** Run this check FIRST. If the OS check fails, the installation is NOT valid.--```bash-OS_TYPE="$(uname -s)"-if [ "$OS_TYPE" = "Darwin" ]; then- echo "✓ Platform: macOS - fully supported"- echo " Audio: afplay (built-in)"-elif [ "$OS_TYPE" = "Linux" ]; then- echo "✓ Platform: Linux - fully supported"- echo " Audio: mpg123 (preferred) or mpv"- if ! command -v mpg123 &> /dev/null && ! command -v mpv &> /dev/null; then- echo " ⚠️ No audio player found. Install: sudo apt install mpg123"- fi-else- echo "❌ Platform: $OS_TYPE - NOT SUPPORTED"- echo " Installation cannot be verified on this platform"-fi-```--**Cross-platform note:** Voice server auto-detects audio players (macOS: afplay, Linux: mpg123/mpv).-----+# PAI Voice System - Verification Checklist## Mandatory Completion Checklist@@ -32,7 +7,6 @@ fi### Directory Structure- [ ] `$PAI_DIR/hooks/lib/` directory exists-- [ ] `$PAI_DIR/config/` directory exists- [ ] `$PAI_DIR/voice-server/` directory exists### Core Files@@ -41,11 +15,12 @@ fi- [ ] `$PAI_DIR/hooks/stop-hook-voice.ts` exists- [ ] `$PAI_DIR/hooks/subagent-stop-hook-voice.ts` exists- [ ] `$PAI_DIR/voice-server/server.ts` exists-- [ ] `$PAI_DIR/config/voice-personalities.json` exists+- [ ] `$PAI_DIR/voice-server/manage.sh` exists### Configuration-- [ ] `ELEVENLABS_API_KEY` set in `$PAI_DIR/.env`+- [ ] `ELEVENLABS_API_KEY` set in `~/.env`+- [ ] `ELEVENLABS_VOICE_ID` set in `~/.env`- [ ] Voice hooks registered in `~/.claude/settings.json`### Services@@ -59,14 +34,16 @@ fi### Test 1: Verify Directory Structure```bash-ls -la $PAI_DIR/hooks/lib/+PAI_CHECK="${PAI_DIR:-$HOME/.config/pai}"++ls -la $PAI_CHECK/hooks/lib/# Expected: prosody-enhancer.ts-ls -la $PAI_DIR/voice-server/-# Expected: server.ts+ls -la $PAI_CHECK/voice-server/+# Expected: server.ts, manage.sh-ls -la $PAI_DIR/config/-# Expected: voice-personalities.json+ls -la $PAI_CHECK/hooks/+# Expected: stop-hook-voice.ts, subagent-stop-hook-voice.ts```### Test 2: Check Voice Server Health@@ -91,25 +68,21 @@ curl -X POST http://localhost:8888/notify \curl -X POST http://localhost:8888/notify \-H "Content-Type: application/json" \-d '{"title":"Test","message":"[✨ success] Fixed the authentication bug!","voice_enabled":true}'-# Expected: Success tone with emphasis on "Fixed"+# Expected: Success tone with adjusted voice parameters```-### Test 5: Verify Prosody Enhancer+### Test 5: Check Hook Registration```bash-# In a bun REPL or test file:-import { enhanceProsody, cleanForSpeech } from '$PAI_DIR/hooks/lib/prosody-enhancer';--const result = enhanceProsody("Completed fixing the login bug", "engineer");-console.log(result);-# Expected: Enhanced text with emotional markers+grep -A5 "stop-hook-voice" ~/.claude/settings.json+# Expected: Shows hook configuration```-### Test 6: Check Hook Registration+### Test 6: Test Management Script```bash-grep -A5 "stop-hook-voice" ~/.claude/settings.json-# Expected: Shows hook configuration+$PAI_DIR/voice-server/manage.sh status+# Expected: Shows server running status```---@@ -119,28 +92,28 @@ grep -A5 "stop-hook-voice" ~/.claude/settings.json### Test A: Main Agent VoiceIn a Claude Code session:-1. Complete a task that produces 🎯 COMPLETED output+1. Complete a task that produces `🗣️ PAI:` output2. Listen for voice announcement-3. Should hear the COMPLETED message spoken+3. Should hear the message spoken### Test B: Subagent VoiceIn a Claude Code session:1. Run a Task that spawns a subagent2. Wait for subagent to complete-3. Should hear different voice for the agent type+3. Should hear voice notification### Test C: Graceful Degradation```bash# Stop the voice server-pkill -f "voice/server.ts"+$PAI_DIR/voice-server/manage.sh stop# In Claude Code, complete a task# Should complete without errors (silent, no crash)# Restart voice server-bun run $PAI_DIR/voice-server/server.ts &+$PAI_DIR/voice-server/manage.sh start```---@@ -151,34 +124,45 @@ bun run $PAI_DIR/voice-server/server.ts &#!/bin/bashPAI_CHECK="${PAI_DIR:-$HOME/.config/pai}"-echo "=== Kai Voice System Verification ==="+echo "=== PAI Voice System v1.4.0 Verification ==="echo ""# Check files-for file in "hooks/lib/prosody-enhancer.ts" "hooks/stop-hook-voice.ts" "hooks/subagent-stop-hook-voice.ts" "voice-server/server.ts" "config/voice-personalities.json"; do+echo "📁 Files:"+for file in "hooks/lib/prosody-enhancer.ts" "hooks/stop-hook-voice.ts" "hooks/subagent-stop-hook-voice.ts" "voice-server/server.ts" "voice-server/manage.sh"; doif [ -f "$PAI_CHECK/$file" ]; then- echo "✓ $file"+ echo " ✓ $file"else- echo "❌ $file MISSING"+ echo " ❌ $file MISSING"fidoneecho ""# Check API key-if [ -f "$PAI_CHECK/.env" ] && grep -q "ELEVENLABS_API_KEY" "$PAI_CHECK/.env"; then- echo "✓ ELEVENLABS_API_KEY configured"+echo "🔑 Configuration:"+if [ -f "$HOME/.env" ] && grep -q "ELEVENLABS_API_KEY" "$HOME/.env"; then+ echo " ✓ ELEVENLABS_API_KEY configured"+else+ echo " ❌ ELEVENLABS_API_KEY not configured"+fi++if [ -f "$HOME/.env" ] && grep -q "ELEVENLABS_VOICE_ID" "$HOME/.env"; then+ echo " ✓ ELEVENLABS_VOICE_ID configured"else- echo "❌ ELEVENLABS_API_KEY not configured"+ echo " ❌ ELEVENLABS_VOICE_ID not configured"fiecho ""# Check voice server+echo "🔊 Voice Server:"if curl -s http://localhost:8888/health > /dev/null 2>&1; then- echo "✓ Voice server running on port 8888"+ echo " ✓ Voice server running on port 8888"+ curl -s http://localhost:8888/health | head -c 100+ echo ""else- echo "❌ Voice server NOT running"+ echo " ❌ Voice server NOT running"fiecho ""@@ -191,9 +175,9 @@ echo "=== Verification Complete ==="Installation is complete when:-1. All directory structure items are checked-2. All core files are present-3. ElevenLabs API key is configured-4. Voice server responds to health check-5. Test notification produces audible output-6. Hooks are registered in settings.json+1. ✅ All directory structure items exist+2. ✅ All core files are present+3. ✅ ElevenLabs API key and voice ID are configured+4. ✅ Voice server responds to health check+5. ✅ Test notification produces audible output+6. ✅ Hooks are registered in settings.jsondiff --git a/Packs/pai-voice-system/src/hooks/stop-hook-voice.ts b/Packs/pai-voice-system/src/hooks/stop-hook-voice.tsnew file mode 100644index 00000000..b6ee3b70--- /dev/null+++ b/Packs/pai-voice-system/src/hooks/stop-hook-voice.ts@@ -0,0 +1,261 @@+#!/usr/bin/env bun+/**+ * PAI Voice Stop Hook - Main Agent Voice Notifications+ *+ * This hook runs when the main Claude Code agent finishes responding.+ * It extracts the 🗣️ line from responses and sends it to the voice server.+ *+ * Part of the pai-voice-system pack.+ *+ * Configuration (settings.json):+ * ```json+ * {+ * "hooks": {+ * "Stop": [{+ * "type": "command",+ * "command": "bun run ${PAI_DIR}/skills/VoiceSystem/hooks/stop-hook-voice.ts"+ * }]+ * }+ * }+ * ```+ *+ * Environment Variables:+ * VOICE_SERVER_URL - Voice server URL (default: http://localhost:8888)+ * ELEVENLABS_VOICE_ID - Default voice ID for TTS+ * PAI_DIR - PAI installation directory+ */++import { readFileSync, existsSync } from 'fs';+import { join } from 'path';+import { homedir } from 'os';+import { enhanceProsody, cleanForSpeech } from './lib/prosody-enhancer';++// Configuration+const VOICE_SERVER_URL = process.env.VOICE_SERVER_URL || 'http://localhost:8888';+const DEFAULT_VOICE_ID = process.env.ELEVENLABS_VOICE_ID || '';+const PAI_DIR = process.env.PAI_DIR || join(homedir(), '.config', 'pai');++// AI Identity - loaded from DAIDENTITY.md if it exists+interface AIIdentity {+ name: string;+ displayName: string;+ voiceId: string;+}++function loadIdentity(): AIIdentity {+ const defaultIdentity: AIIdentity = {+ name: 'PAI',+ displayName: 'PAI',+ voiceId: DEFAULT_VOICE_ID+ };++ try {+ // Try to load from DAIDENTITY.md+ const identityPath = join(PAI_DIR, 'skills', 'CORE', 'USER', 'DAIDENTITY.md');+ if (existsSync(identityPath)) {+ const content = readFileSync(identityPath, 'utf-8');++ // Extract fields from markdown format: **Field:** Value+ const nameMatch = content.match(/\*\*Name:\*\*\s*(\w+)/);+ const displayMatch = content.match(/\*\*Display\s*Name:\*\*\s*(.+?)(?:\n|$)/i);+ const voiceMatch = content.match(/\*\*Voice\s*ID:\*\*\s*(\S+)/i);++ return {+ name: nameMatch?.[1] || defaultIdentity.name,+ displayName: displayMatch?.[1]?.trim() || nameMatch?.[1] || defaultIdentity.displayName,+ voiceId: voiceMatch?.[1] || defaultIdentity.voiceId+ };+ }+ } catch (error) {+ console.error('Error loading identity:', error);+ }++ return defaultIdentity;+}++const AI_IDENTITY = loadIdentity();++interface HookInput {+ session_id: string;+ transcript_path: string;+ hook_event_name: string;+}++interface NotificationPayload {+ title: string;+ message: string;+ voice_enabled: boolean;+ voice_id?: string;+}++/**+ * Convert Claude content (string or array of blocks) to plain text+ */+function contentToText(content: unknown): string {+ if (typeof content === 'string') return content;+ if (Array.isArray(content)) {+ return content+ .map(c => {+ if (typeof c === 'string') return c;+ if (c?.text) return c.text;+ if (c?.content) return contentToText(c.content);+ return '';+ })+ .join(' ')+ .trim();+ }+ return '';+}++/**+ * Extract the voice message from the response+ * Looks for: 🗣️ AI_NAME: [message]+ * Falls back to: 🎯 COMPLETED: [message]+ */+function extractVoiceMessage(text: string): string | null {+ // Remove system-reminder tags+ text = text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, '');++ // Patterns to try (in order of priority)+ const patterns = [+ // Primary: 🗣️ AI_NAME: [text]+ new RegExp(`🗣️\\s*\\*{0,2}${AI_IDENTITY.name}:?\\*{0,2}\\s*(.+?)(?:\\n|$)`, 'is'),+ // Fallback: 🎯 COMPLETED: [text]+ /🎯\s*\*{0,2}COMPLETED:?\*{0,2}\s*(.+?)(?:\n|$)/i,+ ];++ for (const pattern of patterns) {+ const match = text.match(pattern);+ if (match && match[1]) {+ let message = match[1].trim();++ // Clean up the message+ message = message.replace(/^\[AGENT:\w+\]\s*/i, ''); // Remove agent tags++ // Clean for speech while preserving prosody markers+ message = cleanForSpeech(message);++ // Enhance with prosody markers+ message = enhanceProsody(message, AI_IDENTITY.name.toLowerCase());++ return message;+ }+ }++ return null;+}++/**+ * Read the last assistant message from the transcript+ */+function getLastAssistantMessage(transcriptPath: string): string {+ try {+ const content = readFileSync(transcriptPath, 'utf-8');+ const lines = content.trim().split('\n');++ let lastAssistantMessage = '';++ for (const line of lines) {+ if (line.trim()) {+ try {+ const entry = JSON.parse(line) as any;++ if (entry.type === 'assistant' && entry.message?.content) {+ const text = contentToText(entry.message.content);+ if (text) {+ lastAssistantMessage = text;+ }+ }+ } catch {+ // Skip invalid JSON lines+ }+ }+ }++ return lastAssistantMessage;+ } catch (error) {+ console.error('Error reading transcript:', error);+ return '';+ }+}++/**+ * Send notification to the voice server+ */+async function sendVoiceNotification(payload: NotificationPayload): Promise<void> {+ try {+ const response = await fetch(`${VOICE_SERVER_URL}/notify`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(payload),+ });++ if (!response.ok) {+ console.error('Voice server error:', response.statusText);+ }+ } catch (error) {+ // Fail silently - voice server may not be running+ console.error('Failed to send voice notification:', error);+ }+}++async function main() {+ let hookInput: HookInput | null = null;++ // Read hook input from stdin+ try {+ const decoder = new TextDecoder();+ const reader = Bun.stdin.stream().getReader();+ let input = '';++ const timeoutPromise = new Promise<void>((resolve) => {+ setTimeout(() => resolve(), 500);+ });++ const readPromise = (async () => {+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ input += decoder.decode(value, { stream: true });+ }+ })();++ await Promise.race([readPromise, timeoutPromise]);++ if (input.trim()) {+ hookInput = JSON.parse(input) as HookInput;+ }+ } catch (error) {+ console.error('Error reading hook input:', error);+ }++ // Extract voice message from the last response+ let voiceMessage: string | null = null;++ if (hookInput && hookInput.transcript_path) {+ const lastMessage = getLastAssistantMessage(hookInput.transcript_path);+ if (lastMessage) {+ voiceMessage = extractVoiceMessage(lastMessage);+ }+ }++ // Send voice notification if we have a message+ if (voiceMessage) {+ const payload: NotificationPayload = {+ title: AI_IDENTITY.displayName,+ message: voiceMessage,+ voice_enabled: true,+ voice_id: AI_IDENTITY.voiceId || undefined+ };++ await sendVoiceNotification(payload);+ }++ process.exit(0);+}++// Run the hook+main().catch((error) => {+ console.error('Voice stop hook error:', error);+ process.exit(0); // Don't fail the hook - always exit cleanly+});diff --git a/Packs/pai-voice-system/src/hooks/subagent-stop-hook-voice.ts b/Packs/pai-voice-system/src/hooks/subagent-stop-hook-voice.tsnew file mode 100644index 00000000..258eae2f--- /dev/null+++ b/Packs/pai-voice-system/src/hooks/subagent-stop-hook-voice.ts@@ -0,0 +1,318 @@+#!/usr/bin/env bun+/**+ * PAI Voice Subagent Stop Hook - Delegated Agent Voice Notifications+ *+ * This hook runs when a subagent (spawned via Task tool) finishes responding.+ * It extracts the 🗣️ line and sends it to the voice server with the agent's voice.+ *+ * Part of the pai-voice-system pack.+ *+ * Key difference from main agent hook:+ * - Subagents may have different voice IDs configured+ * - Looks for [AGENT:Name] tags in the response+ * - Supports multi-voice agent conversations+ *+ * Configuration (settings.json):+ * ```json+ * {+ * "hooks": {+ * "SubagentStop": [{+ * "type": "command",+ * "command": "bun run ${PAI_DIR}/skills/VoiceSystem/hooks/subagent-stop-hook-voice.ts"+ * }]+ * }+ * }+ * ```+ *+ * Environment Variables:+ * VOICE_SERVER_URL - Voice server URL (default: http://localhost:8888)+ * PAI_DIR - PAI installation directory+ */++import { readFileSync, existsSync } from 'fs';+import { join } from 'path';+import { homedir } from 'os';+import { enhanceProsody, cleanForSpeech } from './lib/prosody-enhancer';++// Configuration+const VOICE_SERVER_URL = process.env.VOICE_SERVER_URL || 'http://localhost:8888';+const PAI_DIR = process.env.PAI_DIR || join(homedir(), '.config', 'pai');++// Voice personalities configuration+interface VoicePersonality {+ voice_id: string;+ voice_name: string;+ stability: number;+ similarity_boost: number;+ description: string;+ type: string;+}++interface VoiceConfig {+ voices: Record<string, VoicePersonality>;+}++// Load voice personalities from configuration+function loadVoicePersonalities(): VoiceConfig | null {+ try {+ // Try PAI skill voice-personalities.md first+ const paiPersonalitiesPath = join(PAI_DIR, 'skills', 'CORE', 'voice-personalities.md');+ if (existsSync(paiPersonalitiesPath)) {+ const markdownContent = readFileSync(paiPersonalitiesPath, 'utf-8');+ const jsonMatch = markdownContent.match(/```json\n([\s\S]*?)\n```/);+ if (jsonMatch && jsonMatch[1]) {+ return JSON.parse(jsonMatch[1]);+ }+ }++ // Fallback to voice-personalities.json in pack+ const jsonPath = join(PAI_DIR, 'skills', 'VoiceSystem', 'voice-personalities.json');+ if (existsSync(jsonPath)) {+ return JSON.parse(readFileSync(jsonPath, 'utf-8'));+ }+ } catch (error) {+ console.error('Error loading voice personalities:', error);+ }+ return null;+}++const voiceConfig = loadVoicePersonalities();++interface HookInput {+ session_id: string;+ transcript_path: string;+ hook_event_name: string;+}++interface NotificationPayload {+ title: string;+ message: string;+ voice_enabled: boolean;+ voice_id?: string;+ voice_name?: string;+}++/**+ * Convert Claude content (string or array of blocks) to plain text+ */+function contentToText(content: unknown): string {+ if (typeof content === 'string') return content;+ if (Array.isArray(content)) {+ return content+ .map(c => {+ if (typeof c === 'string') return c;+ if (c?.text) return c.text;+ if (c?.content) return contentToText(c.content);+ return '';+ })+ .join(' ')+ .trim();+ }+ return '';+}++/**+ * Extract agent name from response+ * Looks for [AGENT:Name] tags+ */+function extractAgentName(text: string): string | null {+ const agentMatch = text.match(/\[AGENT:(\w+)\]/i);+ return agentMatch ? agentMatch[1] : null;+}++/**+ * Get voice ID for an agent name+ */+function getVoiceIdForAgent(agentName: string): string | null {+ if (!voiceConfig) return null;++ // Try exact match first+ if (voiceConfig.voices[agentName]) {+ return voiceConfig.voices[agentName].voice_id;+ }++ // Try case-insensitive match+ const lowerName = agentName.toLowerCase();+ for (const [name, config] of Object.entries(voiceConfig.voices)) {+ if (name.toLowerCase() === lowerName) {+ return config.voice_id;+ }+ }++ return null;+}++/**+ * Extract the voice message from the response+ */+function extractVoiceMessage(text: string): { message: string; agentName: string | null } | null {+ // Remove system-reminder tags+ text = text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, '');++ // Extract agent name if present+ const agentName = extractAgentName(text);++ // Patterns to try (in order of priority)+ const patterns = [+ // 🗣️ AgentName: [text]+ /🗣️\s*\*{0,2}(\w+):?\*{0,2}\s*(.+?)(?:\n|$)/i,+ // 🎯 COMPLETED: [text]+ /🎯\s*\*{0,2}COMPLETED:?\*{0,2}\s*(.+?)(?:\n|$)/i,+ ];++ for (const pattern of patterns) {+ const match = text.match(pattern);+ if (match) {+ // Handle both patterns - first has agentName in group 1+ let message: string;+ let extractedAgent: string | null = null;++ if (pattern.source.includes('(\\w+)')) {+ // First pattern: 🗣️ AgentName: message+ extractedAgent = match[1];+ message = match[2];+ } else {+ // Second pattern: 🎯 COMPLETED: message+ message = match[1];+ }++ message = message.trim();++ // Clean up the message+ message = message.replace(/^\[AGENT:\w+\]\s*/i, '');++ // Clean for speech while preserving prosody markers+ message = cleanForSpeech(message);++ // Enhance with prosody markers+ const prosodyAgent = extractedAgent || agentName || 'assistant';+ message = enhanceProsody(message, prosodyAgent.toLowerCase());++ return {+ message,+ agentName: extractedAgent || agentName+ };+ }+ }++ return null;+}++/**+ * Read the last assistant message from the transcript+ */+function getLastAssistantMessage(transcriptPath: string): string {+ try {+ const content = readFileSync(transcriptPath, 'utf-8');+ const lines = content.trim().split('\n');++ let lastAssistantMessage = '';++ for (const line of lines) {+ if (line.trim()) {+ try {+ const entry = JSON.parse(line) as any;++ if (entry.type === 'assistant' && entry.message?.content) {+ const text = contentToText(entry.message.content);+ if (text) {+ lastAssistantMessage = text;+ }+ }+ } catch {+ // Skip invalid JSON lines+ }+ }+ }++ return lastAssistantMessage;+ } catch (error) {+ console.error('Error reading transcript:', error);+ return '';+ }+}++/**+ * Send notification to the voice server+ */+async function sendVoiceNotification(payload: NotificationPayload): Promise<void> {+ try {+ const response = await fetch(`${VOICE_SERVER_URL}/notify`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(payload),+ });++ if (!response.ok) {+ console.error('Voice server error:', response.statusText);+ }+ } catch (error) {+ // Fail silently - voice server may not be running+ console.error('Failed to send voice notification:', error);+ }+}++async function main() {+ let hookInput: HookInput | null = null;++ // Read hook input from stdin+ try {+ const decoder = new TextDecoder();+ const reader = Bun.stdin.stream().getReader();+ let input = '';++ const timeoutPromise = new Promise<void>((resolve) => {+ setTimeout(() => resolve(), 500);+ });++ const readPromise = (async () => {+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ input += decoder.decode(value, { stream: true });+ }+ })();++ await Promise.race([readPromise, timeoutPromise]);++ if (input.trim()) {+ hookInput = JSON.parse(input) as HookInput;+ }+ } catch (error) {+ console.error('Error reading hook input:', error);+ }++ // Extract voice message from the last response+ let extracted: { message: string; agentName: string | null } | null = null;++ if (hookInput && hookInput.transcript_path) {+ const lastMessage = getLastAssistantMessage(hookInput.transcript_path);+ if (lastMessage) {+ extracted = extractVoiceMessage(lastMessage);+ }+ }++ // Send voice notification if we have a message+ if (extracted) {+ // Get voice ID for the agent (if configured)+ const voiceId = extracted.agentName ? getVoiceIdForAgent(extracted.agentName) : null;++ const payload: NotificationPayload = {+ title: extracted.agentName || 'Agent',+ message: extracted.message,+ voice_enabled: true,+ voice_id: voiceId || undefined,+ voice_name: extracted.agentName || undefined+ };++ await sendVoiceNotification(payload);+ }++ process.exit(0);+}++// Run the hook+main().catch((error) => {+ console.error('Voice subagent stop hook error:', error);+ process.exit(0); // Don't fail the hook - always exit cleanly+});diff --git a/Packs/pai-voice-system/src/voice/manage.sh b/Packs/pai-voice-system/src/voice/manage.shnew file mode 100644index 00000000..36c0cc44--- /dev/null+++ b/Packs/pai-voice-system/src/voice/manage.sh@@ -0,0 +1,152 @@+#!/bin/bash+#+# PAI Voice Server Management Script+#+# Usage:+# ./manage.sh start - Start the voice server+# ./manage.sh stop - Stop the voice server+# ./manage.sh restart - Restart the voice server+# ./manage.sh status - Check server status+# ./manage.sh test - Send a test notification+#+# Environment Variables:+# VOICE_SERVER_PORT - Server port (default: 8888)+# PAI_DIR - PAI installation directory+#++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+PORT="${VOICE_SERVER_PORT:-8888}"+PID_FILE="/tmp/pai-voice-server.pid"+LOG_FILE="/tmp/pai-voice-server.log"++start() {+ if [ -f "$PID_FILE" ] && kill -0 "$(cat "$PID_FILE")" 2>/dev/null; then+ echo "⚠️ Voice server is already running (PID: $(cat "$PID_FILE"))"+ return 1+ fi++ echo "🚀 Starting PAI Voice Server on port $PORT..."++ # Start server in background+ nohup bun run "$SCRIPT_DIR/server.ts" > "$LOG_FILE" 2>&1 &+ echo $! > "$PID_FILE"++ # Wait a moment for server to start+ sleep 1++ if kill -0 "$(cat "$PID_FILE")" 2>/dev/null; then+ echo "✅ Voice server started (PID: $(cat "$PID_FILE"))"+ echo "📝 Log file: $LOG_FILE"+ echo "🔊 Test: curl -X POST http://localhost:$PORT/notify -H 'Content-Type: application/json' -d '{\"message\":\"Hello!\"}'"+ else+ echo "❌ Failed to start voice server"+ echo "📝 Check log: cat $LOG_FILE"+ rm -f "$PID_FILE"+ return 1+ fi+}++stop() {+ if [ ! -f "$PID_FILE" ]; then+ echo "⚠️ No PID file found - server may not be running"+ # Try to find and kill by port+ PID=$(lsof -ti:$PORT 2>/dev/null)+ if [ -n "$PID" ]; then+ echo "🔍 Found process on port $PORT (PID: $PID)"+ kill "$PID" 2>/dev/null+ echo "✅ Stopped process on port $PORT"+ fi+ return 0+ fi++ PID=$(cat "$PID_FILE")+ if kill -0 "$PID" 2>/dev/null; then+ echo "🛑 Stopping voice server (PID: $PID)..."+ kill "$PID"+ rm -f "$PID_FILE"+ echo "✅ Voice server stopped"+ else+ echo "⚠️ Process $PID not running, cleaning up PID file"+ rm -f "$PID_FILE"+ fi+}++restart() {+ echo "🔄 Restarting voice server..."+ stop+ sleep 1+ start+}++status() {+ echo "📊 PAI Voice Server Status"+ echo "========================="++ if [ -f "$PID_FILE" ]; then+ PID=$(cat "$PID_FILE")+ if kill -0 "$PID" 2>/dev/null; then+ echo "✅ Running (PID: $PID)"+ else+ echo "❌ PID file exists but process not running"+ fi+ else+ echo "⏹️ Not running (no PID file)"+ fi++ # Check if port is in use+ if lsof -i:$PORT -sTCP:LISTEN > /dev/null 2>&1; then+ echo "🔌 Port $PORT: IN USE"+ else+ echo "🔌 Port $PORT: FREE"+ fi++ # Health check+ echo ""+ echo "🏥 Health Check:"+ if curl -s "http://localhost:$PORT/health" 2>/dev/null | head -c 200; then+ echo ""+ else+ echo "❌ Server not responding"+ fi+}++test_notification() {+ echo "🧪 Sending test notification..."++ RESPONSE=$(curl -s -X POST "http://localhost:$PORT/notify" \+ -H "Content-Type: application/json" \+ -d '{"message": "PAI Voice Server test notification"}')++ echo "📨 Response: $RESPONSE"+}++case "$1" in+ start)+ start+ ;;+ stop)+ stop+ ;;+ restart)+ restart+ ;;+ status)+ status+ ;;+ test)+ test_notification+ ;;+ *)+ echo "PAI Voice Server Management"+ echo ""+ echo "Usage: $0 {start|stop|restart|status|test}"+ echo ""+ echo "Commands:"+ echo " start - Start the voice server"+ echo " stop - Stop the voice server"+ echo " restart - Restart the voice server"+ echo " status - Check server status"+ echo " test - Send a test notification"+ exit 1+ ;;+esacdiff --git a/Packs/pai-voice-system/src/voice/server.ts b/Packs/pai-voice-system/src/voice/server.tsnew file mode 100644index 00000000..e91fd3da--- /dev/null+++ b/Packs/pai-voice-system/src/voice/server.ts@@ -0,0 +1,552 @@+#!/usr/bin/env bun+/**+ * PAI Voice Server - Text-to-Speech notification server using ElevenLabs+ *+ * Part of the pai-voice-system pack.+ *+ * Usage:+ * bun run src/voice/server.ts+ *+ * Environment Variables:+ * ELEVENLABS_API_KEY - Your ElevenLabs API key (required)+ * ELEVENLABS_VOICE_ID - Default voice ID (optional)+ * VOICE_SERVER_PORT - Server port (default: 8888)+ * PAI_DIR - PAI installation directory (default: ~/.config/pai)+ *+ * Endpoints:+ * POST /notify - Send TTS notification with optional voice/emotion+ * POST /pai - Simple notification with default voice+ * GET /health - Health check+ */++import { serve } from "bun";+import { spawn } from "child_process";+import { homedir } from "os";+import { join } from "path";+import { existsSync, readFileSync } from "fs";++// Load .env from user home directory+const envPath = join(homedir(), '.env');+if (existsSync(envPath)) {+ const envContent = await Bun.file(envPath).text();+ envContent.split('\n').forEach(line => {+ const [key, value] = line.split('=');+ if (key && value && !key.startsWith('#')) {+ process.env[key.trim()] = value.trim();+ }+ });+}++const PORT = parseInt(process.env.VOICE_SERVER_PORT || process.env.PORT || "8888");+const ELEVENLABS_API_KEY = process.env.ELEVENLABS_API_KEY;+const PAI_DIR = process.env.PAI_DIR || join(homedir(), '.config', 'pai');++if (!ELEVENLABS_API_KEY) {+ console.error('⚠️ ELEVENLABS_API_KEY not found in ~/.env');+ console.error('Add: ELEVENLABS_API_KEY=your_key_here');+}++// Default voice ID - configure via environment variable+const DEFAULT_VOICE_ID = process.env.ELEVENLABS_VOICE_ID || "";++if (!DEFAULT_VOICE_ID) {+ console.warn('⚠️ ELEVENLABS_VOICE_ID not set - voice requests will fail without explicit voice_id');+}++// Voice configuration types+interface VoiceConfig {+ voice_id: string;+ voice_name: string;+ stability: number;+ similarity_boost: number;+ description: string;+ type: string;+}++interface VoicesConfig {+ voices: Record<string, VoiceConfig>;+ default_volume?: number;+}++// Emotional markers for dynamic voice adjustment+interface EmotionalSettings {+ stability: number;+ similarity_boost: number;+}++// 13 Emotional Presets - Prosody System+// These markers can be embedded in messages: [💥 excited], [✨ success], etc.+// The server extracts them and adjusts voice parameters accordingly+const EMOTIONAL_PRESETS: Record<string, EmotionalSettings> = {+ // High Energy / Positive+ 'excited': { stability: 0.7, similarity_boost: 0.9 }, // Energetic, expressive+ 'celebration': { stability: 0.65, similarity_boost: 0.85 }, // Joyful, triumphant+ 'insight': { stability: 0.55, similarity_boost: 0.8 }, // Illuminating, clarity+ 'creative': { stability: 0.5, similarity_boost: 0.75 }, // Inspired, innovative++ // Success / Achievement+ 'success': { stability: 0.6, similarity_boost: 0.8 }, // Confident, warm+ 'progress': { stability: 0.55, similarity_boost: 0.75 }, // Steady, encouraging++ // Analysis / Investigation+ 'investigating': { stability: 0.6, similarity_boost: 0.85 }, // Focused, analytical+ 'debugging': { stability: 0.55, similarity_boost: 0.8 }, // Persistent, detective-like+ 'learning': { stability: 0.5, similarity_boost: 0.75 }, // Curious, educational++ // Thoughtful / Careful+ 'pondering': { stability: 0.65, similarity_boost: 0.8 }, // Thoughtful, measured+ 'focused': { stability: 0.7, similarity_boost: 0.85 }, // Concentrated, determined+ 'caution': { stability: 0.4, similarity_boost: 0.6 }, // Uncertain, careful++ // Urgent / Critical+ 'urgent': { stability: 0.3, similarity_boost: 0.9 }, // Fast, intense+};++// Load voices configuration+let voicesConfig: VoicesConfig | null = null;+try {+ // Try PAI skill voice-personalities.md first (canonical source)+ const paiPersonalitiesPath = join(PAI_DIR, 'skills', 'CORE', 'voice-personalities.md');+ if (existsSync(paiPersonalitiesPath)) {+ const markdownContent = readFileSync(paiPersonalitiesPath, 'utf-8');+ // Extract JSON block from markdown+ const jsonMatch = markdownContent.match(/```json\n([\s\S]*?)\n```/);+ if (jsonMatch && jsonMatch[1]) {+ voicesConfig = JSON.parse(jsonMatch[1]);+ console.log('✅ Loaded voice personalities from CORE/voice-personalities.md');+ }+ } else {+ // Fallback to local voices.json+ const voicesPath = join(import.meta.dir, '..', '..', 'voice-personalities.json');+ if (existsSync(voicesPath)) {+ const voicesContent = readFileSync(voicesPath, 'utf-8');+ voicesConfig = JSON.parse(voicesContent);+ console.log('✅ Loaded from voice-personalities.json');+ }+ }+} catch (error) {+ console.warn('⚠️ Failed to load voice personalities, using defaults');+}++// Escape special characters for AppleScript+function escapeForAppleScript(input: string): string {+ return input.replace(/\\/g, '\\\\').replace(/"/g, '\\"');+}++// Extract emotional marker from message+// Supports all 13 prosody markers from the expanded system+function extractEmotionalMarker(message: string): { cleaned: string; emotion?: string } {+ // Map emoji to emotion name+ const emojiToEmotion: Record<string, string> = {+ '💥': 'excited',+ '🎉': 'celebration',+ '💡': 'insight',+ '🎨': 'creative',+ '✨': 'success',+ '📈': 'progress',+ '🔍': 'investigating',+ '🐛': 'debugging',+ '📚': 'learning',+ '🤔': 'pondering',+ '🎯': 'focused',+ '⚠️': 'caution',+ '🚨': 'urgent'+ };++ // Match pattern: [emoji emotion-name]+ // Examples: [💥 excited], [✨ success], [🎉 celebration]+ const emotionMatch = message.match(/\[(💥|🎉|💡|🎨|✨|📈|🔍|🐛|📚|🤔|🎯|⚠️|🚨)\s+(\w+)\]/);+ if (emotionMatch) {+ const emoji = emotionMatch[1];+ const emotionName = emotionMatch[2].toLowerCase();++ // Verify emoji matches emotion name+ if (emojiToEmotion[emoji] === emotionName) {+ return {+ cleaned: message.replace(emotionMatch[0], '').trim(),+ emotion: emotionName+ };+ }+ }++ return { cleaned: message };+}++// Get voice configuration by voice ID or agent name+function getVoiceConfig(identifier: string): VoiceConfig | null {+ if (!voicesConfig) return null;++ // Try direct agent name lookup+ if (voicesConfig.voices[identifier]) {+ return voicesConfig.voices[identifier];+ }++ // Try voice_id lookup+ for (const config of Object.values(voicesConfig.voices)) {+ if (config.voice_id === identifier) {+ return config;+ }+ }++ return null;+}++// Sanitize input for TTS and notifications - allow natural speech punctuation+function sanitizeForSpeech(input: string): string {+ // Allow: letters, numbers, spaces, common punctuation for natural speech+ // Block: shell metacharacters, path traversal, script tags, markdown+ const cleaned = input+ .replace(/<script/gi, '') // Remove script tags+ .replace(/\.\.\//g, '') // Remove path traversal+ .replace(/[;&|><`$\\]/g, '') // Remove shell metacharacters+ .replace(/\*\*([^*]+)\*\*/g, '$1') // Strip bold markdown: **text** → text+ .replace(/\*([^*]+)\*/g, '$1') // Strip italic markdown: *text* → text+ .replace(/`([^`]+)`/g, '$1') // Strip inline code: `text` → text+ .replace(/#{1,6}\s+/g, '') // Strip markdown headers: ### → (empty)+ .trim()+ .substring(0, 500);++ return cleaned;+}++// Validate user input - check for obviously malicious content+function validateInput(input: any): { valid: boolean; error?: string; sanitized?: string } {+ if (!input || typeof input !== 'string') {+ return { valid: false, error: 'Invalid input type' };+ }++ if (input.length > 500) {+ return { valid: false, error: 'Message too long (max 500 characters)' };+ }++ // Sanitize and check if anything remains+ const sanitized = sanitizeForSpeech(input);++ if (!sanitized || sanitized.length === 0) {+ return { valid: false, error: 'Message contains no valid content after sanitization' };+ }++ return { valid: true, sanitized };+}++// Generate speech using ElevenLabs API+async function generateSpeech(+ text: string,+ voiceId: string,+ voiceSettings?: { stability: number; similarity_boost: number }+): Promise<ArrayBuffer> {+ if (!ELEVENLABS_API_KEY) {+ throw new Error('ElevenLabs API key not configured');+ }++ if (!voiceId) {+ throw new Error('Voice ID not configured - set ELEVENLABS_VOICE_ID environment variable');+ }++ const url = `https://api.elevenlabs.io/v1/text-to-speech/${voiceId}`;++ // Use provided settings or defaults+ const settings = voiceSettings || { stability: 0.5, similarity_boost: 0.5 };++ const response = await fetch(url, {+ method: 'POST',+ headers: {+ 'Accept': 'audio/mpeg',+ 'Content-Type': 'application/json',+ 'xi-api-key': ELEVENLABS_API_KEY,+ },+ body: JSON.stringify({+ text: text,+ model_id: 'eleven_turbo_v2_5',+ voice_settings: settings,+ }),+ });++ if (!response.ok) {+ const errorText = await response.text();+ throw new Error(`ElevenLabs API error: ${response.status} - ${errorText}`);+ }++ return await response.arrayBuffer();+}++// Get volume setting from config (defaults to 1.0 = 100%)+function getVolumeSetting(): number {+ if (voicesConfig && 'default_volume' in voicesConfig) {+ const vol = voicesConfig.default_volume;+ if (typeof vol === 'number' && vol >= 0 && vol <= 1) {+ return vol;+ }+ }+ return 1.0; // Default to full volume+}++// Play audio using afplay (macOS)+async function playAudio(audioBuffer: ArrayBuffer): Promise<void> {+ const tempFile = `/tmp/voice-${Date.now()}.mp3`;++ // Write audio to temp file+ await Bun.write(tempFile, audioBuffer);++ const volume = getVolumeSetting();++ return new Promise((resolve, reject) => {+ // afplay -v takes a value from 0.0 to 1.0+ const proc = spawn('/usr/bin/afplay', ['-v', volume.toString(), tempFile]);++ proc.on('error', (error) => {+ console.error('Error playing audio:', error);+ reject(error);+ });++ proc.on('exit', (code) => {+ // Clean up temp file+ spawn('/bin/rm', [tempFile]);++ if (code === 0) {+ resolve();+ } else {+ reject(new Error(`afplay exited with code ${code}`));+ }+ });+ });+}++// Spawn a process safely+function spawnSafe(command: string, args: string[]): Promise<void> {+ return new Promise((resolve, reject) => {+ const proc = spawn(command, args);++ proc.on('error', (error) => {+ console.error(`Error spawning ${command}:`, error);+ reject(error);+ });++ proc.on('exit', (code) => {+ if (code === 0) {+ resolve();+ } else {+ reject(new Error(`${command} exited with code ${code}`));+ }+ });+ });+}++// Send macOS notification with voice+async function sendNotification(+ title: string,+ message: string,+ voiceEnabled = true,+ voiceId: string | null = null+) {+ // Validate and sanitize inputs+ const titleValidation = validateInput(title);+ const messageValidation = validateInput(message);++ if (!titleValidation.valid) {+ throw new Error(`Invalid title: ${titleValidation.error}`);+ }++ if (!messageValidation.valid) {+ throw new Error(`Invalid message: ${messageValidation.error}`);+ }++ // Use pre-sanitized values from validation+ const safeTitle = titleValidation.sanitized!;+ let safeMessage = messageValidation.sanitized!;++ // Extract emotional marker if present+ const { cleaned, emotion } = extractEmotionalMarker(safeMessage);+ safeMessage = cleaned;++ // Generate and play voice using ElevenLabs+ if (voiceEnabled && ELEVENLABS_API_KEY) {+ try {+ const voice = voiceId || DEFAULT_VOICE_ID;++ // Get voice configuration (personality settings)+ const voiceConfig = getVoiceConfig(voice);++ // Determine voice settings (priority: emotional > personality > defaults)+ let voiceSettings = { stability: 0.5, similarity_boost: 0.5 };++ if (emotion && EMOTIONAL_PRESETS[emotion]) {+ // Emotional marker overrides personality+ voiceSettings = EMOTIONAL_PRESETS[emotion];+ console.log(`🎭 Emotion: ${emotion}`);+ } else if (voiceConfig) {+ // Use personality settings from voices config+ voiceSettings = {+ stability: voiceConfig.stability,+ similarity_boost: voiceConfig.similarity_boost+ };+ console.log(`👤 Personality: ${voiceConfig.description}`);+ }++ console.log(`🎙️ Generating speech (voice: ${voice}, stability: ${voiceSettings.stability}, boost: ${voiceSettings.similarity_boost})`);++ const audioBuffer = await generateSpeech(safeMessage, voice, voiceSettings);+ await playAudio(audioBuffer);+ } catch (error) {+ console.error("Failed to generate/play speech:", error);+ }+ }++ // Display macOS notification - escape for AppleScript+ try {+ const escapedTitle = escapeForAppleScript(safeTitle);+ const escapedMessage = escapeForAppleScript(safeMessage);+ const script = `display notification "${escapedMessage}" with title "${escapedTitle}" sound name ""`;+ await spawnSafe('/usr/bin/osascript', ['-e', script]);+ } catch (error) {+ console.error("Notification display error:", error);+ }+}++// Rate limiting+const requestCounts = new Map<string, { count: number; resetTime: number }>();+const RATE_LIMIT = 10;+const RATE_WINDOW = 60000; // 1 minute++function checkRateLimit(ip: string): boolean {+ const now = Date.now();+ const record = requestCounts.get(ip);++ if (!record || now > record.resetTime) {+ requestCounts.set(ip, { count: 1, resetTime: now + RATE_WINDOW });+ return true;+ }++ if (record.count >= RATE_LIMIT) {+ return false;+ }++ record.count++;+ return true;+}++// Start HTTP server+const server = serve({+ port: PORT,+ async fetch(req) {+ const url = new URL(req.url);++ const clientIp = req.headers.get('x-forwarded-for') || 'localhost';++ const corsHeaders = {+ "Access-Control-Allow-Origin": "http://localhost",+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",+ "Access-Control-Allow-Headers": "Content-Type"+ };++ if (req.method === "OPTIONS") {+ return new Response(null, { headers: corsHeaders, status: 204 });+ }++ if (!checkRateLimit(clientIp)) {+ return new Response(+ JSON.stringify({ status: "error", message: "Rate limit exceeded" }),+ {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 429+ }+ );+ }++ // POST /notify - Full notification with voice/emotion support+ if (url.pathname === "/notify" && req.method === "POST") {+ try {+ const data = await req.json();+ const title = data.title || "PAI Notification";+ const message = data.message || "Task completed";+ const voiceEnabled = data.voice_enabled !== false;+ const voiceId = data.voice_id || data.voice_name || null;++ if (voiceId && typeof voiceId !== 'string') {+ throw new Error('Invalid voice_id');+ }++ console.log(`📨 Notification: "${title}" - "${message}" (voice: ${voiceEnabled}, voiceId: ${voiceId || DEFAULT_VOICE_ID})`);++ await sendNotification(title, message, voiceEnabled, voiceId);++ return new Response(+ JSON.stringify({ status: "success", message: "Notification sent" }),+ {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 200+ }+ );+ } catch (error: any) {+ console.error("Notification error:", error);+ return new Response(+ JSON.stringify({ status: "error", message: error.message || "Internal server error" }),+ {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: error.message?.includes('Invalid') ? 400 : 500+ }+ );+ }+ }++ // POST /pai - Simple notification with default voice+ if (url.pathname === "/pai" && req.method === "POST") {+ try {+ const data = await req.json();+ const title = data.title || "PAI Assistant";+ const message = data.message || "Task completed";++ console.log(`🤖 PAI notification: "${title}" - "${message}"`);++ await sendNotification(title, message, true, null);++ return new Response(+ JSON.stringify({ status: "success", message: "PAI notification sent" }),+ {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 200+ }+ );+ } catch (error: any) {+ console.error("PAI notification error:", error);+ return new Response(+ JSON.stringify({ status: "error", message: error.message || "Internal server error" }),+ {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: error.message?.includes('Invalid') ? 400 : 500+ }+ );+ }+ }++ // GET /health - Health check+ if (url.pathname === "/health") {+ return new Response(+ JSON.stringify({+ status: "healthy",+ port: PORT,+ voice_system: "ElevenLabs",+ default_voice_id: DEFAULT_VOICE_ID || "(not configured)",+ api_key_configured: !!ELEVENLABS_API_KEY,+ pai_dir: PAI_DIR+ }),+ {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 200+ }+ );+ }++ return new Response("PAI Voice Server - POST to /notify or /pai", {+ headers: corsHeaders,+ status: 200+ });+ },+});++console.log(`🚀 PAI Voice Server running on port ${PORT}`);+console.log(`🎙️ Using ElevenLabs TTS`);+console.log(`🔊 Default voice: ${DEFAULT_VOICE_ID || '(not configured - set ELEVENLABS_VOICE_ID)'}`);+console.log(`📡 POST to http://localhost:${PORT}/notify`);+console.log(`🔒 Security: CORS restricted to localhost, rate limiting enabled`);+console.log(`🔑 API Key: ${ELEVENLABS_API_KEY ? '✅ Configured' : '❌ Missing'}`);