⛰️ LifeOS — The AI-powered Life Operating System that helps you hill climb to wherever you're going.
Migrate voice system back to ElevenLabs TTS
Daniel Miessler17e8b9067653
diff --git a/PAI_DIRECTORY/env-example b/PAI_DIRECTORY/env-exampleindex 6f518f33..b586b776 100644--- a/PAI_DIRECTORY/env-example+++ b/PAI_DIRECTORY/env-example@@ -1,8 +1,16 @@# Your core .env file for everything PAI related-# Copy this file to ${PAI_DIR}/.env: cp .env-example ${PAI_DIR}/.env-# Then add your actual API keys to ${PAI_DIR}/.env-# Commands and agents should reference keys from ${PAI_DIR}/.env, not store them directly in their files+# Copy this file to ~/.env: cp env-example ~/.env+# Then add your actual API keys to ~/.env+# Commands and agents should reference keys from ~/.env, not store them directly in their files-OPENAI_API_KEY="example-key-here"-SOME_OTHER_KEY="another-example-key-here"-KEEP_ADDING_MORE="yet-another-example-key-here"+# ElevenLabs API Configuration (for voice notifications)+# Get your free API key at https://elevenlabs.io (10,000 chars/month free)+ELEVENLABS_API_KEY="your_elevenlabs_api_key_here"+ELEVENLABS_VOICE_ID="s3TPKV1kjDlVtZbl4Ksh" # Default voice ID (Kai)++# Voice Server Configuration (optional)+PORT="8888" # Voice server port (default: 8888)++# Add your other API keys below+OPENAI_API_KEY="your_openai_api_key_here"+ANTHROPIC_API_KEY="your_anthropic_api_key_here"diff --git a/PAI_DIRECTORY/voice-server/QUICKSTART.md b/PAI_DIRECTORY/voice-server/QUICKSTART.mdnew file mode 100644index 00000000..cf5d94d8--- /dev/null+++ b/PAI_DIRECTORY/voice-server/QUICKSTART.md@@ -0,0 +1,222 @@+# PAI Voice Server - Quick Start Guide++Get voice notifications working in 5 minutes with ElevenLabs TTS.++## Prerequisites++- macOS (tested on macOS 11+)+- [Bun](https://bun.sh) runtime+- ElevenLabs account (free tier available)++## Step 1: Install Bun++If you don't have Bun installed:++```bash+curl -fsSL https://bun.sh/install | bash+```++## Step 2: Get Your ElevenLabs API Key++1. Go to [elevenlabs.io](https://elevenlabs.io) and create a free account+2. Navigate to your [Profile Settings](https://elevenlabs.io/app/settings/api-keys)+3. Click "Create API Key" or copy your existing key+4. Copy the API key (starts with something like `sk_...`)++**Free Tier:** 10,000 characters/month (perfect for notifications)++## Step 3: Configure Your Environment++Add your ElevenLabs API key to `~/.env`:++```bash+# Create or edit ~/.env+echo "ELEVENLABS_API_KEY=your_api_key_here" >> ~/.env+echo "ELEVENLABS_VOICE_ID=s3TPKV1kjDlVtZbl4Ksh" >> ~/.env+```++Replace `your_api_key_here` with your actual API key from Step 2.++**Important:** The `~/.env` file should be in your home directory, NOT in the PAI directory.++## Step 4: Install the Voice Server++```bash+cd ${PAI_DIR}/voice-server+./install.sh+```++This will:+- Install dependencies+- Create a macOS LaunchAgent for auto-start+- Start the voice server on port 8888+- Verify the installation works++## Step 5: Test It!++Send a test notification:++```bash+curl -X POST http://localhost:8888/notify \+ -H "Content-Type: application/json" \+ -d '{"message": "Voice system is working perfectly!"}'+```++You should hear the message spoken aloud!++## What's Next?++### Choose Different Voices++Browse the [ElevenLabs Voice Library](https://elevenlabs.io/voice-library) to find voices you like:++1. Click on a voice to preview it+2. Click "Use" and copy the Voice ID+3. Update `ELEVENLABS_VOICE_ID` in your `~/.env`++### Agent Voice Configuration++The PAI system supports different voices for different agents:++| Agent | Default Voice ID | Purpose |+|-------|------------------|---------|+| Kai | s3TPKV1kjDlVtZbl4Ksh | Main assistant voice |+| Perplexity-Researcher | AXdMgz6evoL7OPd7eU12 | Research agent |+| Claude-Researcher | AXdMgz6evoL7OPd7eU12 | Research agent |+| Engineer | kmSVBPu7loj4ayNinwWM | Development agent |+| Designer | ZF6FPAbjXT4488VcRRnw | Design agent |+| Pentester | hmMWXCj9K7N5mCPcRkfC | Security agent |+| Architect | muZKMsIDGYtIkjjiUS82 | Architecture agent |+| Writer | gfRt6Z3Z8aTbpLfexQ7N | Content agent |++These voice IDs are configured in your hooks and agent files.++### Install Menu Bar Indicator (Optional)++Get visual status in your macOS menu bar:++```bash+# Install SwiftBar (recommended)+brew install --cask swiftbar++# Install the menu bar indicator+cd ${PAI_DIR}/voice-server/menubar+./install-menubar.sh+```++## Troubleshooting++### "No voice output"++**Check 1:** Verify API key is set:+```bash+grep ELEVENLABS_API_KEY ~/.env+```++**Check 2:** Test the server:+```bash+curl http://localhost:8888/health+```++Expected output:+```json+{+ "status": "healthy",+ "port": 8888,+ "voice_system": "ElevenLabs",+ "default_voice_id": "s3TPKV1kjDlVtZbl4Ksh",+ "api_key_configured": true+}+```++**Check 3:** Look at server logs:+```bash+tail -f ~/.claude/voice-server/logs/voice-server.log+```++### "Port 8888 already in use"++Kill any existing process and restart:+```bash+lsof -ti:8888 | xargs kill -9+cd ${PAI_DIR}/voice-server && ./restart.sh+```++### "Invalid API key"++1. Verify your API key is correct in `~/.env`+2. Check that it doesn't have extra spaces or quotes+3. Make sure you copied the entire key from ElevenLabs++## Service Management++Once installed, the voice server runs automatically. You can control it with:++```bash+# Check status+./status.sh++# Stop server+./stop.sh++# Start server+./start.sh++# Restart server+./restart.sh++# Uninstall (removes LaunchAgent)+./uninstall.sh+```++## API Usage++### Send a Notification++```bash+curl -X POST http://localhost:8888/notify \+ -H "Content-Type: application/json" \+ -d '{+ "message": "Your notification message here",+ "voice_id": "s3TPKV1kjDlVtZbl4Ksh",+ "title": "Optional Title"+ }'+```++### Parameters++- `message` (required): Text to speak+- `voice_id` (optional): ElevenLabs voice ID (uses default if not specified)+- `voice_enabled` (optional): Set to `false` to disable voice+- `title` (optional): Notification title (default: "PAI Notification")++## Security Notes++- Your API key is stored securely in `~/.env` (not in code)+- Server only accepts connections from localhost+- Rate limited to 10 requests/minute+- No sensitive data is logged++## What You've Accomplished++✅ Voice server running automatically on startup+✅ High-quality AI voices for notifications+✅ Secure API key storage+✅ Simple HTTP API for integration+✅ Different voices for different agents (optional)++## Learn More++- [Full Documentation](README.md) - Complete feature guide+- [Voice System Architecture](../documentation/voice-system.md) - How it works+- [ElevenLabs Docs](https://elevenlabs.io/docs) - Voice API reference++## Need Help?++1. Check the [README](README.md) for detailed troubleshooting+2. Review server logs: `tail -f ~/.claude/voice-server/logs/voice-server.log`+3. Test the health endpoint: `curl http://localhost:8888/health`++---++**🎉 Congratulations!** Your PAI voice system is now set up with professional AI voices!diff --git a/PAI_DIRECTORY/voice-server/server.ts b/PAI_DIRECTORY/voice-server/server.tsindex 4b267e72..9e72a5d4 100644--- a/PAI_DIRECTORY/voice-server/server.ts+++ b/PAI_DIRECTORY/voice-server/server.ts@@ -1,6 +1,6 @@#!/usr/bin/env bun/**- * PAIVoice - Personal AI Voice notification server for macOS with native voices+ * PAIVoice - Personal AI Voice notification server using ElevenLabs TTS*/import { serve } from "bun";@@ -9,7 +9,7 @@ import { homedir } from "os";import { join } from "path";import { existsSync } from "fs";-// Load .env from user home directory (optional, for future use)+// Load .env from user home directoryconst envPath = join(homedir(), '.env');if (existsSync(envPath)) {const envContent = await Bun.file(envPath).text();@@ -22,15 +22,18 @@ if (existsSync(envPath)) {}const PORT = parseInt(process.env.PORT || "8888");+const ELEVENLABS_API_KEY = process.env.ELEVENLABS_API_KEY;-// macOS Voice configuration-// Jamie (Premium) is Kai's voice - UK Male, professional and conversational-const DEFAULT_VOICE = "Jamie (Premium)";+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 (Kai's voice)+const DEFAULT_VOICE_ID = process.env.ELEVENLABS_VOICE_ID || "s3TPKV1kjDlVtZbl4Ksh";// Sanitize input for shell commandsfunction sanitizeForShell(input: string): string {- // Remove any characters that could be used for command injection- // Allow only alphanumeric, spaces, and basic punctuationreturn input.replace(/[^a-zA-Z0-9\s.,!?\-']/g, '').trim().substring(0, 500);}@@ -39,54 +42,82 @@ function validateInput(input: any): { valid: boolean; error?: string } {if (!input || typeof input !== 'string') {return { valid: false, error: 'Invalid input type' };}-- // Limit message length+if (input.length > 500) {return { valid: false, error: 'Message too long (max 500 characters)' };}-- // Check for potentially malicious patterns+const dangerousPatterns = [- /[;&|><`\$\(\)\{\}\[\]\\]/, // Shell metacharacters- /\.\.\//, // Path traversal- /<script/i, // Script injection+ /[;&|><`\$\(\)\{\}\[\]\\]/,+ /\.\.\//,+ /<script/i,];-+for (const pattern of dangerousPatterns) {if (pattern.test(input)) {return { valid: false, error: 'Invalid characters in input' };}}-+return { valid: true };}-// Speak using native macOS say command-async function speak(text: string, voiceName: string | null = null, rate: number | null = null): Promise<void> {- const voice = voiceName || DEFAULT_VOICE;- const speechRate = rate || 175; // Default macOS rate is ~175 wpm+// Generate speech using ElevenLabs API+async function generateSpeech(text: string, voiceId: string): Promise<ArrayBuffer> {+ if (!ELEVENLABS_API_KEY) {+ throw new Error('ElevenLabs API key not configured');+ }- return new Promise((resolve, reject) => {- // Build args: if voice is null, don't include -v flag (uses system default)- // Always include rate for speed control- const args = [];- if (voice) {- args.push('-v', voice);- }- args.push('-r', speechRate.toString(), text);+ const url = `https://api.elevenlabs.io/v1/text-to-speech/${voiceId}`;- const proc = spawn('/usr/bin/say', args);+ 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_monolingual_v1',+ voice_settings: {+ stability: 0.5,+ similarity_boost: 0.5,+ },+ }),+ });++ if (!response.ok) {+ const errorText = await response.text();+ throw new Error(`ElevenLabs API error: ${response.status} - ${errorText}`);+ }++ return await response.arrayBuffer();+}++// 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);++ return new Promise((resolve, reject) => {+ const proc = spawn('/usr/bin/afplay', [tempFile]);proc.on('error', (error) => {- console.error(`Error speaking with voice ${voice || 'system default'} at rate ${speechRate}:`, 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(`say command exited with code ${code}`));+ reject(new Error(`afplay exited with code ${code}`));}});});@@ -96,12 +127,12 @@ async function speak(text: string, voiceName: string | null = null, rate: numberfunction 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();@@ -113,7 +144,12 @@ function spawnSafe(command: string, args: string[]): Promise<void> {}// Send macOS notification with voice-async function sendNotification(title: string, message: string, voiceEnabled = true, voiceName: string | null = null, rate: number | null = null) {+async function sendNotification(+ title: string,+ message: string,+ voiceEnabled = true,+ voiceId: string | null = null+) {// Validate inputsconst titleValidation = validateInput(title);const messageValidation = validateInput(message);@@ -126,19 +162,24 @@ async function sendNotification(title: string, message: string, voiceEnabled = tthrow new Error(`Invalid message: ${messageValidation.error}`);}- // Sanitize inputs for shell commands+ // Sanitize inputsconst safeTitle = sanitizeForShell(title);const safeMessage = sanitizeForShell(message);- if (voiceEnabled) {+ // Generate and play voice using ElevenLabs+ if (voiceEnabled && ELEVENLABS_API_KEY) {try {- await speak(safeMessage, voiceName, rate);+ const voice = voiceId || DEFAULT_VOICE_ID;+ console.log(`🎙️ Generating speech with ElevenLabs (voice: ${voice})`);++ const audioBuffer = await generateSpeech(safeMessage, voice);+ await playAudio(audioBuffer);} catch (error) {- console.error("Failed to speak message:", error);+ console.error("Failed to generate/play speech:", error);}}- // Use spawn for osascript with proper escaping+ // Display macOS notificationtry {const script = `display notification "${safeMessage}" with title "${safeTitle}" sound name ""`;await spawnSafe('/usr/bin/osascript', ['-e', script]);@@ -149,22 +190,22 @@ async function sendNotification(title: string, message: string, voiceEnabled = t// Rate limitingconst requestCounts = new Map<string, { count: number; resetTime: number }>();-const RATE_LIMIT = 10; // 10 requests per minute-const RATE_WINDOW = 60000; // 1 minute in milliseconds+const RATE_LIMIT = 10;+const RATE_WINDOW = 60000;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;}@@ -174,54 +215,44 @@ const server = serve({port: PORT,async fetch(req) {const url = new URL(req.url);-- // Get client IP for rate limiting (localhost only)+const clientIp = req.headers.get('x-forwarded-for') || 'localhost';-- // Restrict CORS to localhost only for security+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 });}-- // Check rate limit+if (!checkRateLimit(clientIp)) {return new Response(JSON.stringify({ status: "error", message: "Rate limit exceeded" }),- {+ {headers: { ...corsHeaders, "Content-Type": "application/json" },- status: 429+ status: 429});}-+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 voiceName = data.voice_name || data.voice_id || null; // Support both voice_name and legacy voice_id- const rate = data.rate || null; // Speech rate in words per minute+ const voiceId = data.voice_id || data.voice_name || null; // Support both voice_id and voice_name- // Validate voice name if provided- if (voiceName && typeof voiceName !== 'string') {- throw new Error('Invalid voice_name');+ if (voiceId && typeof voiceId !== 'string') {+ throw new Error('Invalid voice_id');}- // Validate rate if provided- if (rate && (typeof rate !== 'number' || rate < 100 || rate > 500)) {- throw new Error('Invalid rate: must be between 100-500 wpm');- }+ console.log(`📨 Notification: "${title}" - "${message}" (voice: ${voiceEnabled}, voiceId: ${voiceId || DEFAULT_VOICE_ID})`);- console.log(`📨 Received notification: "${title}" - "${message}" (voice: ${voiceEnabled}, voiceName: ${voiceName}, rate: ${rate})`);-- await sendNotification(title, message, voiceEnabled, voiceName, rate);+ await sendNotification(title, message, voiceEnabled, voiceId);return new Response(JSON.stringify({ status: "success", message: "Notification sent" }),@@ -241,39 +272,45 @@ const server = serve({);}}-+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+ 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+ status: error.message?.includes('Invalid') ? 400 : 500});}}-+if (url.pathname === "/health") {return new Response(- JSON.stringify({ status: "healthy", port: PORT, voice_system: "macOS Native", default_voice: DEFAULT_VOICE || "System Default" }),+ JSON.stringify({+ status: "healthy",+ port: PORT,+ voice_system: "ElevenLabs",+ default_voice_id: DEFAULT_VOICE_ID,+ api_key_configured: !!ELEVENLABS_API_KEY+ }),{headers: { ...corsHeaders, "Content-Type": "application/json" },status: 200@@ -289,6 +326,7 @@ const server = serve({});console.log(`🚀 PAIVoice Server running on port ${PORT}`);-console.log(`🎙️ Using macOS native voices (default: ${DEFAULT_VOICE || "System Default - Highest Quality"})`);+console.log(`🎙️ Using ElevenLabs TTS (default voice: ${DEFAULT_VOICE_ID})`);console.log(`📡 POST to http://localhost:${PORT}/notify`);-console.log(`🔒 Security: CORS restricted to localhost, rate limiting enabled`);\ No newline at end of file+console.log(`🔒 Security: CORS restricted to localhost, rate limiting enabled`);+console.log(`🔑 API Key: ${ELEVENLABS_API_KEY ? '✅ Configured' : '❌ Missing'}`);