⛰️ LifeOS — The AI-powered Life Operating System that helps you hill climb to wherever you're going.
Adding voice server, documentation, and multiple updated files.
Daniel Miessler3bd0fe9685af
diff --git a/.claude/documentation/README.md b/.claude/documentation/README.mdnew file mode 100644index 00000000..c4185629--- /dev/null+++ b/.claude/documentation/README.md@@ -0,0 +1,185 @@+# PAI System Documentation++Welcome to the Personal AI Infrastructure (PAI) documentation. PAI is a comprehensive system for integrating AI assistants into your personal workflow with advanced context management, automation, and extensibility.++## 📚 Documentation Index++### Getting Started+- [Quick Start Guide](./quick-start.md) - Get up and running in minutes+- [Installation Guide](./installation.md) - Detailed installation instructions+- [Configuration Guide](./configuration.md) - System configuration options++### Core Concepts+- [System Architecture](./architecture.md) - Overview of PAI components+- [UFC Context System](./ufc-context-system.md) - Universal Flexible Context management+- [Hook System](./hook-system.md) - Event-driven automation+- [Agent System](./agent-system.md) - Specialized AI agents++### Components+- [Voice Server](../voice-server/README.md) - Voice notification system+- [Context Management](./context-management.md) - Dynamic context loading+- [Command System](./command-system.md) - Custom commands and scripts++### Development+- [API Reference](./api-reference.md) - HTTP APIs and interfaces+- [Security Guide](./security.md) - Security best practices+- [Contributing](./contributing.md) - How to contribute to PAI++## 🚀 What is PAI?++PAI (Personal AI Infrastructure) is a powerful framework that enhances AI assistants with:++- **Dynamic Context Loading**: Automatically loads relevant context based on conversation intent+- **Universal Flexible Context (UFC)**: Intelligent context management system+- **Hook System**: Event-driven automation for tool calls+- **Voice Notifications**: AI-powered voice feedback+- **Multi-Agent Architecture**: Specialized agents for different tasks+- **Security First**: Built with security best practices++## 🎯 Key Features++### 1. Context Intelligence+- Semantic understanding of user intent+- Automatic context loading+- Project-specific knowledge bases+- Dynamic agent selection++### 2. Automation+- Pre and post-execution hooks+- Custom command integration+- Workflow automation+- Event-driven responses++### 3. Voice Integration+- ElevenLabs AI voices+- macOS fallback support+- Multiple voice personalities+- Real-time notifications++### 4. Security+- Input validation and sanitization+- Rate limiting+- CORS protection+- No hardcoded secrets++## 🏗️ System Components++```+PAI/+├── .claude/ # Claude-specific configuration+│ ├── context/ # UFC context files+│ ├── hooks/ # Event hooks+│ ├── commands/ # Custom commands+│ └── voice-server/ # Voice notification server+├── Documentation/ # System documentation+├── Projects/ # Project-specific contexts+└── Library/ # System libraries and logs+```++## 🔧 Environment Variables++PAI uses environment variables for configuration:++- `PAI_HOME`: Base directory for PAI installation+- `CLAUDE_CONFIG_DIR`: Claude configuration directory+- `ELEVENLABS_API_KEY`: API key for voice synthesis+- `PORT`: Voice server port (default: 8888)++## 📖 Quick Links++- [System Requirements](#system-requirements)+- [Installation](#installation)+- [Configuration](#configuration)+- [Usage Examples](#usage-examples)+- [Troubleshooting](#troubleshooting)++## System Requirements++- macOS 11+ (primary support)+- Bun runtime+- Claude Desktop or API access+- Optional: ElevenLabs API key+- Optional: SwiftBar for menu indicators++## Installation++```bash+# Clone PAI repository+git clone https://github.com/yourusername/PAI.git+cd PAI++# Set PAI_HOME+export PAI_HOME="$(pwd)"++# Install voice server (optional)+cd .claude/voice-server+./install.sh++# Configure environment+cp .env.example ~/.env+# Edit ~/.env with your settings+```++## Configuration++PAI is configured through:+1. Environment variables in `~/.env`+2. Context files in `.claude/context/`+3. Hook scripts in `.claude/hooks/`+4. Project-specific configurations++## Usage Examples++### Basic Context Loading+```bash+# Context automatically loads based on conversation+"Help me with my website" → Loads website context+"Research AI trends" → Loads research agent+```++### Voice Notifications+```bash+# Send voice notification+curl -X POST http://localhost:8888/notify \+ -d '{"message": "Task completed"}'+```++### Hook System+```yaml+# .claude/hooks/user-prompt-submit.sh+# Automatically loads context before processing prompts+```++## Troubleshooting++Common issues and solutions:++| Issue | Solution |+|-------|----------|+| Context not loading | Check `${PAI_HOME}/.claude/context/` |+| Voice not working | Verify ElevenLabs API key in `~/.env` |+| Hooks not triggering | Ensure hook scripts are executable |+| Port conflicts | Change PORT in `~/.env` |++## Contributing++PAI is open for contributions. See [Contributing Guide](./contributing.md) for:+- Code style guidelines+- Pull request process+- Issue reporting+- Feature requests++## Support++- GitHub Issues: Report bugs and request features+- Documentation: This directory contains all documentation+- Community: Join discussions in the repository++## License++PAI is part of the Personal AI Infrastructure project.++---++*Last updated: [Current Date]*+*Version: 1.0.0*\ No newline at end of filediff --git a/.claude/documentation/agent-system.md b/.claude/documentation/agent-system.mdnew file mode 100644index 00000000..01159aaf--- /dev/null+++ b/.claude/documentation/agent-system.md@@ -0,0 +1,468 @@+# PAI Agent System++## Overview++The PAI Agent System provides specialized AI agents for different domains and tasks. Each agent has specific capabilities, tools, and expertise to handle complex, multi-step tasks autonomously.++## Available Agents++### 1. General-Purpose Agent++**Purpose**: Default agent for complex, multi-step tasks and general problem-solving.++**Capabilities**:+- Research and information gathering+- Code implementation+- Multi-step task execution+- File system operations+- Web searches++**When to use**:+- Complex tasks requiring multiple steps+- Tasks that span multiple domains+- When you need comprehensive problem-solving+- General automation tasks++**Example triggers**:+```+"Help me solve this complex problem"+"I need to complete multiple tasks"+"Can you figure out how to..."+```++### 2. Researcher Agent++**Purpose**: Specialized in web research, information gathering, and analysis.++**Capabilities**:+- Web searches and crawling+- Information synthesis+- Fact-checking and verification+- Trend analysis+- Literature reviews++**When to use**:+- Finding latest information+- Researching topics in depth+- Gathering multiple sources+- Analyzing trends and patterns++**Example triggers**:+```+"Research the latest AI developments"+"Find information about..."+"What's the current state of..."+```++### 3. Engineer Agent++**Purpose**: Professional software engineering and development tasks.++**Capabilities**:+- Code implementation+- Debugging and troubleshooting+- Performance optimization+- Testing and validation+- Architecture design+- Best practices implementation++**When to use**:+- Writing production-ready code+- Debugging complex issues+- Optimizing performance+- Implementing technical solutions+- Code reviews++**Example triggers**:+```+"Implement this feature"+"Debug this issue"+"Optimize this code"+"Write tests for..."+```++### 4. Designer Agent++**Purpose**: UI/UX design and visual development.++**Capabilities**:+- User interface design+- User experience optimization+- Design system creation+- Prototyping+- Visual testing+- Accessibility improvements+- Browser automation for testing++**When to use**:+- Creating user interfaces+- Improving user experience+- Visual testing and validation+- Design system development+- Accessibility audits++**Example triggers**:+```+"Design a dashboard"+"Improve the UX of..."+"Create a design system"+"Test the visual appearance"+```++### 5. Pentester Agent++**Purpose**: Security testing and vulnerability assessment.++**Capabilities**:+- Vulnerability scanning+- Security audits+- Penetration testing+- Code security review+- Network analysis+- Security best practices++**When to use**:+- Security assessments+- Finding vulnerabilities+- Testing security measures+- Code security reviews+- Compliance checks++**Example triggers**:+```+"Test the security of..."+"Find vulnerabilities in..."+"Perform a security audit"+"Check for security issues"+```++### 6. Architect Agent++**Purpose**: System architecture and technical specifications.++**Capabilities**:+- System design+- Technical documentation+- PRD creation+- Feature breakdown+- Implementation planning+- Architecture diagrams+- Technology selection++**When to use**:+- Planning large projects+- Creating technical specifications+- System design decisions+- Breaking down complex features+- Documentation creation++**Example triggers**:+```+"Design the architecture for..."+"Create a PRD for..."+"Plan the implementation of..."+"Break down this feature"+```++### 7. Writer Agent++**Purpose**: Content creation and documentation.++**Capabilities**:+- Technical writing+- Blog posts and articles+- Documentation+- Copy writing+- Content editing+- Style consistency++**When to use**:+- Creating content+- Writing documentation+- Blog posts+- Marketing copy+- Technical articles++**Example triggers**:+```+"Write a blog post about..."+"Create documentation for..."+"Draft an article on..."+```++## Agent Selection++### Automatic Selection++The UFC system automatically selects agents based on semantic analysis of your request:++```python+def select_agent(user_intent):+ intent_keywords = analyze_intent(user_intent)++ if "research" in intent_keywords:+ return "researcher"+ elif "code" or "debug" in intent_keywords:+ return "engineer"+ elif "design" or "ui" in intent_keywords:+ return "designer"+ elif "security" or "vulnerability" in intent_keywords:+ return "pentester"+ elif "architecture" or "specification" in intent_keywords:+ return "architect"+ elif "write" or "content" in intent_keywords:+ return "writer"+ else:+ return "general-purpose"+```++### Manual Selection++You can explicitly request a specific agent:++```+"Use the engineer agent to implement this feature"+"Have the researcher find information about X"+"Get the pentester to check security"+```++## Agent Configuration++### Agent Context Files++Each agent can have specific context:++```+${PAI_HOME}/.claude/context/agents/+├── researcher.md+├── engineer.md+├── designer.md+├── pentester.md+├── architect.md+└── writer.md+```++### Custom Agent Instructions++Create agent-specific instructions:++```markdown+# Engineer Agent Context++## Coding Standards+- Use TypeScript for type safety+- Follow functional programming principles+- Write comprehensive tests+- Document all functions++## Tools Priority+1. Use existing libraries+2. Follow project conventions+3. Optimize for maintainability+```++## Multi-Agent Collaboration++### Sequential Agents++Agents can work in sequence:++```+1. Architect creates specification+2. Engineer implements solution+3. Pentester validates security+4. Writer creates documentation+```++### Parallel Agents++Launch multiple agents simultaneously:++```bash+# In your request+"Run these in parallel:+- Research latest security threats+- Engineer the authentication system+- Design the user interface"+```++## Agent Tools++Each agent has access to specific tools:++### General Tools (All Agents)+- File operations (Read, Write, Edit)+- Shell commands (Bash)+- Web searches+- Pattern matching (Grep, Glob)++### Specialized Tools++**Researcher**:+- Advanced web searches+- Academic databases+- Trend analysis tools++**Engineer**:+- Code analysis+- Testing frameworks+- Debugging tools+- Performance profilers++**Designer**:+- Browser automation+- Screenshot tools+- Visual comparison+- Accessibility checkers++**Pentester**:+- Security scanners+- Network tools+- Vulnerability databases+- Exploit frameworks++## Best Practices++### 1. Agent Selection+- Let the system auto-select when unsure+- Use specific agents for specialized tasks+- Combine agents for complex projects++### 2. Task Decomposition+- Break complex tasks into agent-specific parts+- Use the architect for planning+- Assign specialized tasks to appropriate agents++### 3. Quality Assurance+- Use pentester for security validation+- Use engineer for code quality+- Use designer for UX validation++### 4. Documentation+- Always use writer for user-facing content+- Use architect for technical specifications+- Use engineer for code documentation++## Agent Performance++### Optimization Tips++1. **Clear Instructions**: Be specific about requirements+2. **Context Loading**: Provide relevant context files+3. **Tool Selection**: Let agents choose appropriate tools+4. **Parallel Execution**: Use multiple agents when possible++### Performance Metrics++| Agent | Speed | Accuracy | Complexity |+|-------|-------|----------|------------|+| General | Medium | High | High |+| Researcher | Slow | Very High | Medium |+| Engineer | Fast | High | High |+| Designer | Medium | High | Medium |+| Pentester | Slow | Very High | High |+| Architect | Medium | High | Very High |+| Writer | Fast | High | Low |++## Troubleshooting++### Agent Not Selected++```bash+# Check intent matching+grep "AGENT:" ${PAI_HOME}/Library/Logs/ufc.log++# Manually specify agent+"Please use the engineer agent to..."+```++### Agent Performance Issues++```bash+# Enable agent debugging+export AGENT_DEBUG=true++# Check agent logs+tail -f ${PAI_HOME}/Library/Logs/agent-*.log+```++### Agent Errors++Common issues and solutions:++| Issue | Solution |+|-------|----------|+| Wrong agent selected | Specify agent explicitly |+| Agent timeout | Break task into smaller parts |+| Tool access denied | Check permissions |+| Context not loaded | Verify context files exist |++## Advanced Features++### Custom Agent Creation++Create your own specialized agent:++```bash+# 1. Define agent in context+cat > ${PAI_HOME}/.claude/context/agents/custom.md << EOF+# Custom Agent+Specialized for specific domain...+EOF++# 2. Add to UFC system+# Edit user-prompt-submit-hook to include custom agent++# 3. Define agent tools+# Specify which tools the agent can access+```++### Agent Chaining++Chain agents for complex workflows:++```python+workflow = [+ ("architect", "Create system design"),+ ("engineer", "Implement core features"),+ ("designer", "Create user interface"),+ ("pentester", "Security validation"),+ ("writer", "Create documentation")+]+```++### Agent Templates++Create reusable agent configurations:++```yaml+template: web_project+agents:+ - architect: specification+ - engineer: backend+ - designer: frontend+ - pentester: security+ - writer: documentation+```++## Future Developments++### Planned Enhancements++1. **Agent Learning**: Agents that improve over time+2. **Agent Marketplace**: Share custom agents+3. **Visual Agent Builder**: GUI for agent creation+4. **Agent Analytics**: Performance tracking+5. **Agent Collaboration**: Better multi-agent coordination++### Experimental Features++- Self-organizing agent teams+- Agent skill trees+- Domain-specific agent training+- Agent personality customization++---++*Agent System Version 1.0.0*+*Part of the PAI Infrastructure*\ No newline at end of filediff --git a/.claude/documentation/architecture.md b/.claude/documentation/architecture.mdnew file mode 100644index 00000000..8c14b835--- /dev/null+++ b/.claude/documentation/architecture.md@@ -0,0 +1,262 @@+# PAI System Architecture++## Overview++PAI (Personal AI Infrastructure) is a modular, event-driven system that enhances AI assistants with dynamic context management, automation, and extensibility. The architecture follows a layered approach with clear separation of concerns.++## Architecture Diagram++```+┌─────────────────────────────────────────────────────────────┐+│ User Interface │+│ (Claude Desktop, Terminal, API) │+└────────────────┬────────────────────────────────────────────┘+ │+┌────────────────▼────────────────────────────────────────────┐+│ Hook System Layer │+│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │+│ │ Pre-prompt │ │ Tool hooks │ │ Post-exec │ │+│ │ Hooks │ │ │ │ Hooks │ │+│ └──────────────┘ └──────────────┘ └──────────────┘ │+└────────────────┬────────────────────────────────────────────┘+ │+┌────────────────▼────────────────────────────────────────────┐+│ UFC Context System │+│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │+│ │ Dynamic │ │ Semantic │ │ Context │ │+│ │ Loading │ │ Matching │ │ Files │ │+│ └──────────────┘ └──────────────┘ └──────────────┘ │+└────────────────┬────────────────────────────────────────────┘+ │+┌────────────────▼────────────────────────────────────────────┐+│ Agent System │+│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │+│ │ Researcher │ │ Engineer │ │ Pentester │ │+│ │ │ │ │ │ │ │+│ └──────────────┘ └──────────────┘ └──────────────┘ │+└────────────────┬────────────────────────────────────────────┘+ │+┌────────────────▼────────────────────────────────────────────┐+│ Service Layer │+│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │+│ │ Voice Server │ │ MCP Tools │ │ Commands │ │+│ │ │ │ │ │ │ │+│ └──────────────┘ └──────────────┘ └──────────────┘ │+└──────────────────────────────────────────────────────────────┘+```++## Core Components++### 1. Hook System Layer++The hook system provides event-driven automation throughout the AI interaction lifecycle.++**Key Features:**+- **Pre-prompt hooks**: Execute before user prompts are processed+- **Tool hooks**: Intercept and modify tool calls+- **Post-execution hooks**: Run after commands complete++**Location:** `${PAI_HOME}/.claude/hooks/`++### 2. UFC Context System++Universal Flexible Context (UFC) is the intelligent context management system that dynamically loads relevant information based on semantic understanding.++**Key Features:**+- **Semantic Matching**: Understands user intent, not just keywords+- **Dynamic Loading**: Loads context files on-demand+- **Project Awareness**: Maintains project-specific contexts++**Location:** `${PAI_HOME}/.claude/context/`++### 3. Agent System++Specialized AI agents for different domains and tasks.++**Available Agents:**+- **General-purpose**: Default agent for most tasks+- **Researcher**: Web research and information gathering+- **Engineer**: Software development and debugging+- **Designer**: UI/UX and visual design+- **Pentester**: Security testing and vulnerability assessment+- **Architect**: System design and technical specifications++### 4. Service Layer++Supporting services that provide additional functionality.++**Services:**+- **Voice Server**: Text-to-speech notifications+- **MCP Tools**: Model Context Protocol integrations+- **Command System**: Custom command execution++## Data Flow++### 1. User Input Flow+```+User Input → Hook System → UFC Context → Agent Selection → Processing+```++1. User submits a prompt+2. Pre-prompt hooks execute+3. UFC system analyzes intent+4. Relevant context is loaded+5. Appropriate agent is selected+6. Prompt is processed with context++### 2. Tool Execution Flow+```+Tool Request → Hook Validation → Execution → Post-hook → Response+```++1. AI requests tool execution+2. Tool hooks validate/modify request+3. Tool executes+4. Post-execution hooks run+5. Response returned to AI++### 3. Context Loading Flow+```+Intent Analysis → Pattern Matching → Context Selection → Dynamic Loading+```++1. System analyzes user intent+2. Matches against context patterns+3. Selects appropriate contexts+4. Loads context files dynamically++## Directory Structure++```+${PAI_HOME}/+├── .claude/+│ ├── context/ # UFC context files+│ │ ├── CLAUDE.md # Main context+│ │ ├── projects/ # Project-specific contexts+│ │ ├── life/ # Personal contexts+│ │ └── tools/ # Tool contexts+│ ├── hooks/ # Event hooks+│ │ ├── user-prompt-submit-hook+│ │ ├── tool-use-hook+│ │ └── post-execution-hook+│ ├── commands/ # Custom commands+│ │ └── *.sh # Command scripts+│ └── voice-server/ # Voice notification service+│ ├── server.ts # Server implementation+│ └── menubar/ # Menu bar integration+├── Documentation/ # System documentation+├── Projects/ # User projects+└── Library/ # System libraries+ └── Logs/ # System logs+```++## Communication Protocols++### HTTP APIs++**Voice Server API:**+- `POST /notify` - Send voice notification+- `GET /health` - Health check+- `POST /pai` - PAI-specific notifications++**Request Format:**+```json+{+ "message": "Text to speak",+ "voice_id": "optional_voice_id",+ "title": "Optional Title"+}+```++### Hook Protocol++Hooks communicate through:+1. **Environment Variables**: Pass configuration+2. **Standard I/O**: Input/output piping+3. **Exit Codes**: Success/failure signaling+4. **File System**: Shared context files++## Security Architecture++### Input Validation+- All user inputs sanitized+- Shell metacharacters blocked+- Length limits enforced++### Process Isolation+- Spawn with argument arrays+- No shell interpretation+- Restricted permissions++### Network Security+- CORS restricted to localhost+- Rate limiting per IP+- Authentication tokens (when configured)++### Data Protection+- No hardcoded credentials+- Environment variable configuration+- Secure file permissions++## Extensibility Points++### 1. Adding Context+Create new context files in:+- `${PAI_HOME}/.claude/context/` - Global contexts+- `${PAI_HOME}/Projects/*/CLAUDE.md` - Project contexts++### 2. Adding Hooks+Create executable scripts in:+- `${PAI_HOME}/.claude/hooks/` - Event hooks++### 3. Adding Agents+Define new agents in UFC context system configuration.++### 4. Adding Commands+Create command scripts in:+- `${PAI_HOME}/.claude/commands/` - Custom commands++## Performance Considerations++### Optimization Strategies+1. **Lazy Loading**: Context loads only when needed+2. **Caching**: Frequently used contexts cached+3. **Parallel Processing**: Independent operations run concurrently+4. **Rate Limiting**: Prevents resource exhaustion++### Resource Management+- Memory: Context files loaded on-demand+- CPU: Agent selection optimized for task+- Network: Batch operations when possible+- Disk: Log rotation and cleanup++## Error Handling++### Error Propagation+```+Service Error → Hook System → User Notification → Fallback Action+```++### Fallback Strategies+1. **Voice Server**: Falls back to macOS `say`+2. **Context Loading**: Uses default context+3. **Agent Selection**: Falls back to general-purpose+4. **Hook Execution**: Continues on non-critical failures++## Future Architecture Considerations++### Planned Enhancements+1. **Distributed Agents**: Multi-machine agent deployment+2. **Plugin System**: Third-party extensions+3. **Cloud Sync**: Context synchronization+4. **API Gateway**: Unified API interface++### Scalability Path+1. **Horizontal Scaling**: Multiple agent instances+2. **Load Balancing**: Request distribution+3. **Caching Layer**: Redis/Memcached integration+4. **Queue System**: Async task processing++---++*This architecture document describes PAI version 1.0.0*\ No newline at end of filediff --git a/.claude/documentation/hook-system.md b/.claude/documentation/hook-system.mdnew file mode 100644index 00000000..553adc66--- /dev/null+++ b/.claude/documentation/hook-system.md@@ -0,0 +1,448 @@+# Hook System Documentation++## Overview++The PAI Hook System provides event-driven automation and control throughout the AI interaction lifecycle. Hooks are scripts that execute at specific points, allowing you to intercept, modify, and enhance AI behavior.++## Hook Types++### 1. User Prompt Submit Hook+**File**: `user-prompt-submit-hook`+**Trigger**: Before user prompts are processed+**Purpose**: Load context, validate input, prepare environment++### 2. Tool Use Hook+**File**: `tool-use-hook`+**Trigger**: Before tool execution+**Purpose**: Validate tool calls, modify parameters, security checks++### 3. Post Execution Hook+**File**: `post-execution-hook`+**Trigger**: After commands complete+**Purpose**: Cleanup, logging, notifications++### 4. Response Hook+**File**: `response-hook`+**Trigger**: Before AI response is shown+**Purpose**: Format output, add information, filter content++## Hook Execution Flow++```+User Input+ ↓+[user-prompt-submit-hook]+ ↓+AI Processing+ ↓+Tool Request → [tool-use-hook] → Tool Execution+ ↓+[post-execution-hook]+ ↓+[response-hook]+ ↓+User Output+```++## Creating Hooks++### Basic Hook Structure++```bash+#!/bin/bash+# Hook Name: user-prompt-submit-hook+# Purpose: Pre-process user prompts++# Access environment variables+USER_PROMPT="$1"+CONTEXT_DIR="${PAI_HOME}/.claude/context"++# Perform actions+echo "Processing prompt: $USER_PROMPT"++# Load context based on intent+if [[ "$USER_PROMPT" =~ "website" ]]; then+ cat "${CONTEXT_DIR}/projects/website/CLAUDE.md"+fi++# Return status (0 = success, non-zero = block)+exit 0+```++### Hook Configuration++Hooks must be:+1. **Executable**: `chmod +x hook-name`+2. **Located in**: `${PAI_HOME}/.claude/hooks/`+3. **Named correctly**: Exact hook name without extension+4. **Return proper exit codes**: 0 for success, non-zero to block++## Hook Examples++### Example 1: Context Loading Hook++```bash+#!/bin/bash+# user-prompt-submit-hook+# Dynamically loads context based on user intent++PROMPT="$1"+PAI_HOME="${PAI_HOME:-$HOME}"++# Load UFC context system+if [[ -f "${PAI_HOME}/.claude/hooks/load-dynamic-requirements" ]]; then+ source "${PAI_HOME}/.claude/hooks/load-dynamic-requirements"+fi++# Analyze intent and load context+case "$PROMPT" in+ *website*|*blog*|*site*)+ echo "Loading website context..."+ cat "${PAI_HOME}/.claude/context/projects/website/CLAUDE.md"+ ;;+ *research*|*investigate*)+ echo "Launching researcher agent..."+ echo "AGENT: researcher"+ ;;+ *security*|*vulnerability*)+ echo "Launching pentester agent..."+ echo "AGENT: pentester"+ ;;+esac++exit 0+```++### Example 2: Security Validation Hook++```bash+#!/bin/bash+# tool-use-hook+# Validates and sanitizes tool calls++TOOL_NAME="$1"+TOOL_PARAMS="$2"++# Block dangerous commands+BLOCKED_PATTERNS=(+ "rm -rf /"+ "sudo"+ "passwd"+ "format"+)++for pattern in "${BLOCKED_PATTERNS[@]}"; do+ if [[ "$TOOL_PARAMS" =~ $pattern ]]; then+ echo "BLOCKED: Dangerous command pattern detected"+ exit 1+ fi+done++# Validate file paths+if [[ "$TOOL_NAME" == "Edit" ]] || [[ "$TOOL_NAME" == "Write" ]]; then+ FILE_PATH=$(echo "$TOOL_PARAMS" | grep -o '"file_path":"[^"]*"' | cut -d'"' -f4)++ # Ensure path is within PAI_HOME+ if [[ ! "$FILE_PATH" =~ ^${PAI_HOME} ]]; then+ echo "WARNING: File operation outside PAI_HOME"+ fi+fi++exit 0+```++### Example 3: Notification Hook++```bash+#!/bin/bash+# post-execution-hook+# Sends voice notifications after task completion++COMMAND="$1"+EXIT_CODE="$2"+OUTPUT="$3"++# Send notification based on result+if [ "$EXIT_CODE" -eq 0 ]; then+ MESSAGE="Task completed successfully"+else+ MESSAGE="Task failed with error"+fi++# Send to voice server+curl -X POST http://localhost:8888/notify \+ -H "Content-Type: application/json" \+ -d "{\"message\": \"$MESSAGE\"}" \+ 2>/dev/null++exit 0+```++### Example 4: Output Formatting Hook++```bash+#!/bin/bash+# response-hook+# Formats AI responses++RESPONSE="$1"++# Add timestamp+echo "[$( date '+%Y-%m-%d %H:%M:%S' )]"+echo "$RESPONSE"++# Add context information+if [ -n "$CURRENT_PROJECT" ]; then+ echo "Project: $CURRENT_PROJECT"+fi++exit 0+```++## Advanced Hook Features++### Hook Communication++Hooks can communicate through:++1. **Environment Variables**+```bash+export HOOK_DATA="value"+```++2. **Temporary Files**+```bash+echo "data" > /tmp/hook_data.txt+```++3. **Standard Output**+```bash+echo "CONTEXT: Additional context here"+```++4. **Exit Codes**+```bash+exit 0 # Success, continue+exit 1 # Failure, block operation+```++### Hook Chaining++Multiple hooks can work together:++```bash+# Hook 1: Analyze intent+echo "INTENT: research" > /tmp/intent.txt++# Hook 2: Load based on intent+INTENT=$(cat /tmp/intent.txt)+if [ "$INTENT" = "research" ]; then+ load_research_context+fi+```++### Conditional Execution++Hooks can run conditionally:++```bash+# Only run for specific users+if [ "$USER" != "authorized_user" ]; then+ exit 0+fi++# Only run in certain directories+if [ "$PWD" != "${PAI_HOME}/Projects" ]; then+ exit 0+fi+```++## Hook Best Practices++### 1. Performance+- Keep hooks lightweight+- Avoid blocking operations+- Use background processes when possible+- Cache frequently used data++### 2. Error Handling+```bash+set -e # Exit on error+trap 'echo "Hook failed: $?"' ERR+```++### 3. Logging+```bash+LOG_FILE="${PAI_HOME}/Library/Logs/hooks.log"+echo "[$(date)] Hook executed: $0" >> "$LOG_FILE"+```++### 4. Security+- Validate all inputs+- Sanitize file paths+- Check permissions+- Avoid executing user input++## Built-in Hook Variables++Hooks have access to these environment variables:++| Variable | Description |+|----------|-------------|+| `PAI_HOME` | PAI installation directory |+| `USER_PROMPT` | Current user prompt |+| `TOOL_NAME` | Tool being called |+| `TOOL_PARAMS` | Tool parameters |+| `CONTEXT_DIR` | Context files directory |+| `HOOKS_DIR` | Hooks directory |+| `AGENT_TYPE` | Current agent type |++## Debugging Hooks++### Enable Debug Mode++```bash+export HOOK_DEBUG=true+```++### Debug Output++```bash+#!/bin/bash+if [ "$HOOK_DEBUG" = "true" ]; then+ set -x # Enable trace+ exec 2>>"${PAI_HOME}/Library/Logs/hook_debug.log"+fi+```++### Testing Hooks++```bash+# Test hook directly+./user-prompt-submit-hook "test prompt"++# Check exit code+echo $?++# View output+cat /tmp/hook_output.txt+```++## Common Hook Patterns++### Pattern 1: Context Injection++```bash+# Inject context before prompt processing+cat << EOF+CONTEXT: You are working on project X+CONSTRAINTS: Follow coding style Y+GOALS: Implement feature Z+EOF+```++### Pattern 2: Tool Wrapper++```bash+# Wrap tool execution with pre/post actions+pre_action+$TOOL_COMMAND+post_action+```++### Pattern 3: Validation Gate++```bash+# Validate before allowing operation+if ! validate_request; then+ echo "ERROR: Validation failed"+ exit 1+fi+```++### Pattern 4: Event Notification++```bash+# Notify external systems+webhook_notify "https://api.example.com/hooks" "$EVENT_DATA"+```++## Troubleshooting++### Hook Not Executing++1. **Check permissions**: `ls -la ${PAI_HOME}/.claude/hooks/`+2. **Verify name**: Must match exactly+3. **Test directly**: `./hook-name test`+4. **Check logs**: `tail -f ${PAI_HOME}/Library/Logs/hooks.log`++### Hook Blocking Operations++- Check exit codes+- Review error output+- Verify logic conditions+- Test with `set -x` for trace++### Performance Issues++- Profile with `time ./hook-name`+- Move heavy operations to background+- Cache expensive computations+- Use timeout for external calls++## Hook Security++### Input Validation++```bash+# Sanitize user input+sanitize() {+ echo "$1" | sed 's/[^a-zA-Z0-9 ._-]//g'+}++SAFE_INPUT=$(sanitize "$USER_INPUT")+```++### Path Restrictions++```bash+# Restrict file operations+if [[ ! "$FILE_PATH" =~ ^${PAI_HOME} ]]; then+ echo "Access denied: Outside PAI_HOME"+ exit 1+fi+```++### Command Filtering++```bash+# Block dangerous commands+DANGEROUS_CMDS=("rm -rf" "sudo" "chmod 777")+for cmd in "${DANGEROUS_CMDS[@]}"; do+ if [[ "$COMMAND" =~ $cmd ]]; then+ exit 1+ fi+done+```++## Future Enhancements++### Planned Features++1. **Hook Marketplace**: Share and download hooks+2. **Hook Templates**: Pre-built hook patterns+3. **Visual Hook Editor**: GUI for hook creation+4. **Hook Testing Framework**: Automated testing+5. **Hook Analytics**: Usage and performance metrics++### Experimental Features++- **Async Hooks**: Non-blocking execution+- **Hook Priorities**: Execution order control+- **Hook Dependencies**: Inter-hook requirements+- **Remote Hooks**: Cloud-based hooks++---++*Hook System Version 1.0.0*+*Last Updated: [Current Date]*\ No newline at end of filediff --git a/.claude/documentation/quick-start.md b/.claude/documentation/quick-start.mdnew file mode 100644index 00000000..5926c0b1--- /dev/null+++ b/.claude/documentation/quick-start.md@@ -0,0 +1,421 @@+# PAI Quick Start Guide++Get your Personal AI Infrastructure up and running in minutes!++## Prerequisites++- **macOS** 11+ (primary platform)+- **Claude Desktop** or Claude API access+- **Bun runtime** (for voice server)+- **Git** (for version control)++## Installation++### 1. Clone or Create PAI Directory++```bash+# Option A: Clone from repository+git clone https://github.com/yourusername/PAI.git+cd PAI++# Option B: Create new PAI installation+mkdir -p ~/PAI+cd ~/PAI+```++### 2. Set Environment Variables++```bash+# Add to your shell profile (~/.zshrc or ~/.bashrc)+export PAI_HOME="$HOME/PAI" # Or your installation path+export PATH="$PAI_HOME/bin:$PATH"++# Reload shell+source ~/.zshrc # or ~/.bashrc+```++### 3. Create Directory Structure++```bash+# Create essential directories+mkdir -p "${PAI_HOME}/.claude/context"+mkdir -p "${PAI_HOME}/.claude/hooks"+mkdir -p "${PAI_HOME}/.claude/commands"+mkdir -p "${PAI_HOME}/Projects"+mkdir -p "${PAI_HOME}/Library/Logs"+mkdir -p "${PAI_HOME}/Documentation"+```++### 4. Configure Environment File++Create `~/.env` with your settings:++```bash+# Essential Configuration+PAI_HOME=/path/to/your/PAI++# Optional: Voice Server+ELEVENLABS_API_KEY=your_api_key_here+ELEVENLABS_VOICE_ID=jqcCZkN6Knx8BJ5TBdYR+PORT=8888++# Optional: API Keys for various services+OPENAI_API_KEY=your_key_here+ANTHROPIC_API_KEY=your_key_here+```++## Core Setup++### 1. Create Main Context File++Create `${PAI_HOME}/.claude/context/CLAUDE.md`:++```markdown+# PAI System Context++## System Information+- PAI_HOME: ${PAI_HOME}+- Platform: macOS+- User: ${USER}++## Core Instructions+You are an AI assistant enhanced with PAI (Personal AI Infrastructure).++## Available Features+- Dynamic context loading+- Hook system for automation+- Voice notifications+- Multi-agent support++## Project Contexts+[Your project-specific information here]+```++### 2. Setup UFC Hook System++Create the main hook file `${PAI_HOME}/.claude/hooks/user-prompt-submit-hook`:++```bash+#!/bin/bash+# UFC Dynamic Context Loader++PROMPT="$1"+PAI_HOME="${PAI_HOME:-$HOME}"++# Simple intent matching for demonstration+case "$PROMPT" in+ *website*|*blog*)+ echo "Loading website context..."+ cat "${PAI_HOME}/.claude/context/projects/website/CLAUDE.md" 2>/dev/null+ ;;+ *research*)+ echo "AGENT: researcher"+ ;;+ *security*|*pentest*)+ echo "AGENT: pentester"+ ;;+esac++exit 0+```++Make it executable:+```bash+chmod +x "${PAI_HOME}/.claude/hooks/user-prompt-submit-hook"+```++### 3. Install Voice Server (Optional)++```bash+# Navigate to voice server+cd "${PAI_HOME}/.claude/voice-server"++# Install dependencies+bun install++# Run installation script+./install.sh++# Test voice server+curl -X POST http://localhost:8888/notify \+ -d '{"message": "PAI system initialized"}'+```++## Basic Usage++### 1. Context Management++Create project-specific contexts:++```bash+# Create a project context+mkdir -p "${PAI_HOME}/.claude/context/projects/myproject"+cat > "${PAI_HOME}/.claude/context/projects/myproject/CLAUDE.md" << EOF+# My Project Context++## Project Details+- Name: My Project+- Path: ${PAI_HOME}/Projects/myproject+- Type: Web Application++## Technical Stack+- Frontend: React+- Backend: Node.js+- Database: PostgreSQL++## Current Tasks+- [ ] Implement user authentication+- [ ] Add dashboard features+EOF+```++### 2. Hook Examples++#### Tool Validation Hook++Create `${PAI_HOME}/.claude/hooks/tool-use-hook`:++```bash+#!/bin/bash+# Validate tool usage++TOOL="$1"+PARAMS="$2"++# Log tool usage+echo "[$(date)] Tool: $TOOL" >> "${PAI_HOME}/Library/Logs/tools.log"++# Validate dangerous operations+if [[ "$TOOL" == "Bash" ]] && [[ "$PARAMS" =~ "rm -rf" ]]; then+ echo "BLOCKED: Dangerous command"+ exit 1+fi++exit 0+```++#### Notification Hook++Create `${PAI_HOME}/.claude/hooks/post-execution-hook`:++```bash+#!/bin/bash+# Send completion notifications++COMMAND="$1"+STATUS="$2"++if [ "$STATUS" -eq 0 ]; then+ curl -X POST http://localhost:8888/notify \+ -d '{"message": "Task completed successfully"}' \+ 2>/dev/null+fi++exit 0+```++### 3. Custom Commands++Create custom command `${PAI_HOME}/.claude/commands/status.sh`:++```bash+#!/bin/bash+# Show PAI system status++echo "PAI System Status"+echo "================="+echo "PAI_HOME: ${PAI_HOME}"+echo "Contexts: $(find ${PAI_HOME}/.claude/context -name "*.md" | wc -l)"+echo "Hooks: $(find ${PAI_HOME}/.claude/hooks -type f | wc -l)"+echo "Projects: $(ls -1 ${PAI_HOME}/Projects 2>/dev/null | wc -l)"++# Check voice server+if curl -s http://localhost:8888/health > /dev/null 2>&1; then+ echo "Voice Server: ✅ Running"+else+ echo "Voice Server: ❌ Stopped"+fi+```++## Testing Your Installation++### 1. Test Context Loading++In Claude, try:+```+"Help me with my website"+# Should load website context++"Research AI trends"+# Should launch researcher agent+```++### 2. Test Voice Server++```bash+# Send test notification+curl -X POST http://localhost:8888/notify \+ -H "Content-Type: application/json" \+ -d '{"message": "Hello from PAI"}'+```++### 3. Test Hooks++```bash+# Test hook directly+${PAI_HOME}/.claude/hooks/user-prompt-submit-hook "test website"++# Check output+echo $? # Should be 0+```++## Common Tasks++### Adding a New Project Context++```bash+# 1. Create project directory+mkdir -p "${PAI_HOME}/Projects/newproject"++# 2. Create context file+cat > "${PAI_HOME}/.claude/context/projects/newproject/CLAUDE.md" << EOF+# New Project Context+[Project specific information]+EOF++# 3. Add to hook system (optional)+# Edit user-prompt-submit-hook to include new project triggers+```++### Creating Agent-Specific Contexts++```bash+# Research agent context+cat > "${PAI_HOME}/.claude/context/agents/researcher.md" << EOF+# Researcher Agent Context+Focus on finding accurate, recent information+Cite sources when possible+EOF+```++### Setting Up Automation++```bash+# Create automation hook+cat > "${PAI_HOME}/.claude/hooks/automation-hook" << EOF+#!/bin/bash+# Automated tasks+if [[ "\$1" =~ "daily report" ]]; then+ generate_daily_report+fi+EOF+chmod +x "${PAI_HOME}/.claude/hooks/automation-hook"+```++## Troubleshooting++### Context Not Loading++```bash+# Check hook permissions+ls -la "${PAI_HOME}/.claude/hooks/"++# Test hook manually+"${PAI_HOME}/.claude/hooks/user-prompt-submit-hook" "test prompt"++# Check PAI_HOME is set+echo $PAI_HOME+```++### Voice Server Issues++```bash+# Check if running+lsof -i :8888++# View logs+tail -f "${PAI_HOME}/Library/Logs/pai-voice-server.log"++# Restart service+cd "${PAI_HOME}/.claude/voice-server"+./restart.sh+```++### Hook Not Executing++```bash+# Check if executable+chmod +x "${PAI_HOME}/.claude/hooks/"*++# Enable debug mode+export HOOK_DEBUG=true++# Check logs+tail -f "${PAI_HOME}/Library/Logs/hooks.log"+```++## Next Steps++1. **Explore Documentation**+ - [System Architecture](./architecture.md)+ - [UFC Context System](./ufc-context-system.md)+ - [Hook System](./hook-system.md)++2. **Customize Your Setup**+ - Add project-specific contexts+ - Create custom hooks+ - Configure voice personalities++3. **Advanced Features**+ - Set up multiple agents+ - Create command shortcuts+ - Integrate with external services++## Quick Reference++### Essential Commands++```bash+# Check system status+"${PAI_HOME}/.claude/commands/status.sh"++# Reload context+source ~/.zshrc++# Test voice+curl -X POST http://localhost:8888/notify -d '{"message":"test"}'++# View logs+tail -f "${PAI_HOME}/Library/Logs/"*.log+```++### File Locations++| Component | Location |+|-----------|----------|+| Main Context | `${PAI_HOME}/.claude/context/CLAUDE.md` |+| Hooks | `${PAI_HOME}/.claude/hooks/` |+| Commands | `${PAI_HOME}/.claude/commands/` |+| Projects | `${PAI_HOME}/Projects/` |+| Logs | `${PAI_HOME}/Library/Logs/` |+| Voice Server | `${PAI_HOME}/.claude/voice-server/` |++### Environment Variables++| Variable | Purpose | Default |+|----------|---------|---------|+| `PAI_HOME` | PAI installation directory | `$HOME` |+| `ELEVENLABS_API_KEY` | Voice synthesis API | None |+| `PORT` | Voice server port | 8888 |+| `HOOK_DEBUG` | Enable hook debugging | false |++## Getting Help++- Check the [Documentation](./README.md)+- Review [Troubleshooting Guide](#troubleshooting)+- File issues on GitHub+- Check logs in `${PAI_HOME}/Library/Logs/`++---++*Welcome to PAI! Your personal AI infrastructure is ready to enhance your workflow.*\ No newline at end of filediff --git a/.claude/documentation/ufc-context-system.md b/.claude/documentation/ufc-context-system.mdnew file mode 100644index 00000000..d8844b2a--- /dev/null+++ b/.claude/documentation/ufc-context-system.md@@ -0,0 +1,390 @@+# UFC Context System Documentation++## Overview++The Universal Flexible Context (UFC) system is PAI's intelligent context management framework. It provides semantic understanding of user intent and dynamically loads relevant context files and agents, making AI interactions more aware and capable.++## Core Concepts++### Semantic Understanding++Unlike traditional keyword matching, UFC understands the **meaning** behind user requests:++- "Help me with my site" → Understands this means website context+- "What's new with AI" → Recognizes research intent+- "Fix this bug" → Identifies engineering context needed++### Dynamic Loading++Context and agents are loaded on-demand based on:+1. User intent analysis+2. Current conversation context+3. Project-specific requirements+4. Task complexity++## How UFC Works++### 1. Intent Recognition Pipeline++```+User Input → Semantic Analysis → Pattern Matching → Context Selection → Loading+```++**Example Flow:**+```yaml+User: "I need to update my blog with AI research"+↓+Semantic Analysis: [blog, update, AI, research]+↓+Pattern Match:+ - "blog" → Website context+ - "research" → Research agent+↓+Context Load:+ - ${PAI_HOME}/.claude/context/projects/website/CLAUDE.md+ - Agent: researcher+```++### 2. Context Loading Rules++Context files are loaded based on semantic triggers defined in the hook system:++```javascript+// Example context rule+{+ trigger: {+ semantic: ["website", "blog", "site", "homepage"],+ phrases: ["update my site", "fix navigation", "publish article"]+ },+ action: {+ loadContext: ["${PAI_HOME}/.claude/context/projects/website/CLAUDE.md"],+ agent: null+ }+}+```++## Configuration++### Context File Structure++Context files use Markdown with special directives:++```markdown+# Context Name++## Purpose+Brief description of this context++## Knowledge Base+Domain-specific information...++## Instructions+Special instructions for the AI...++## Available Commands+- command1: Description+- command2: Description+```++### Creating Context Files++1. **Global Context**: `${PAI_HOME}/.claude/context/CLAUDE.md`+ - Loaded for all conversations+ - Contains system-wide settings++2. **Project Context**: `${PAI_HOME}/.claude/context/projects/*/CLAUDE.md`+ - Project-specific knowledge+ - Loaded based on intent++3. **Domain Context**: `${PAI_HOME}/.claude/context/domains/*/CLAUDE.md`+ - Specialized domain knowledge+ - Technical references++## Context Categories++### 1. Website & Blog Context+**Triggers**: website, blog, site, homepage, navigation+**Files**:+- `${PAI_HOME}/.claude/context/projects/website/CLAUDE.md`+- `${PAI_HOME}/.claude/context/projects/website/content/CLAUDE.md`++### 2. Research Context+**Triggers**: research, investigate, find information, latest news+**Agent**: researcher+**Behavior**: Launches research agent for web searches++### 3. Security Context+**Triggers**: security, vulnerabilities, pentesting, audit+**Agent**: pentester+**Behavior**: Launches security testing agent++### 4. Engineering Context+**Triggers**: code, debug, implement, fix bug+**Agent**: engineer+**Behavior**: Launches engineering agent++### 5. Financial Context+**Triggers**: expenses, bills, budget, spending+**Files**:+- `${PAI_HOME}/.claude/context/life/expenses.md`+- `${PAI_HOME}/.claude/context/life/finances/`++### 6. Health Context+**Triggers**: health, fitness, medical, wellness+**Files**: `${PAI_HOME}/Projects/Life/Health/CLAUDE.md`++## Agent System Integration++UFC can automatically launch specialized agents:++```yaml+Available Agents:+- general-purpose: Default for complex tasks+- researcher: Web research and information gathering+- engineer: Software development+- designer: UI/UX and visual design+- pentester: Security testing+- architect: System design and specs+- writer: Content creation+```++### Agent Selection Logic++```python+def select_agent(intent):+ if "research" in intent:+ return "researcher"+ elif "security" in intent:+ return "pentester"+ elif "code" in intent:+ return "engineer"+ elif "design" in intent:+ return "designer"+ else:+ return "general-purpose"+```++## Dynamic Requirements Loading++The UFC system uses a special hook (`user-prompt-submit-hook`) to load requirements:++### Loading Process++1. **Hook Activation**: Triggered before prompt processing+2. **Intent Analysis**: Semantic understanding of user request+3. **Context Selection**: Matching against defined patterns+4. **File Loading**: Reading selected context files+5. **Agent Launch**: Starting specialized agents if needed++### Example Hook Implementation++```bash+#!/bin/bash+# user-prompt-submit-hook++# Analyze user prompt+INTENT=$(analyze_intent "$USER_PROMPT")++# Load appropriate context+case "$INTENT" in+ "website")+ load_context "${PAI_HOME}/.claude/context/projects/website/CLAUDE.md"+ ;;+ "research")+ launch_agent "researcher"+ ;;+ "security")+ launch_agent "pentester"+ ;;+esac+```++## Best Practices++### 1. Context File Guidelines++- **Keep it focused**: One domain per context file+- **Use clear headers**: Structure with markdown headers+- **Include examples**: Provide usage examples+- **Update regularly**: Keep context current++### 2. Semantic Triggers++- **Be comprehensive**: Include synonyms and variations+- **Test patterns**: Verify trigger accuracy+- **Avoid conflicts**: Ensure clear disambiguation++### 3. Performance Optimization++- **Lazy loading**: Load only what's needed+- **Cache frequently used**: Store common contexts+- **Batch operations**: Load related contexts together++## Advanced Features++### Context Inheritance++Contexts can inherit from others:++```markdown+# Child Context+extends: ${PAI_HOME}/.claude/context/base/CLAUDE.md++## Additional Knowledge+...+```++### Conditional Loading++Load context based on conditions:++```yaml+condition:+ - file_exists: "package.json"+ - directory: "src/"+then:+ load: "${PAI_HOME}/.claude/context/javascript/CLAUDE.md"+```++### Context Variables++Use variables in context files:++```markdown+## Project Path+${PROJECT_PATH}++## Current User+${USER}++## Date+${DATE}+```++## Troubleshooting++### Context Not Loading++1. **Check triggers**: Verify semantic triggers match+2. **File paths**: Ensure context files exist+3. **Permissions**: Check file read permissions+4. **Hook execution**: Verify hooks are running++### Debug Mode++Enable debug logging:++```bash+export UFC_DEBUG=true+```++View debug output:+```bash+tail -f ${PAI_HOME}/Library/Logs/ufc-debug.log+```++### Common Issues++| Issue | Solution |+|-------|----------|+| Context not found | Check file path in hook |+| Wrong agent selected | Review semantic triggers |+| Slow loading | Optimize context file size |+| Duplicate loading | Check for circular references |++## API Reference++### Context Loading Functions++```javascript+// Load single context+loadContext(filePath: string): void++// Load multiple contexts+loadContexts(filePaths: string[]): void++// Launch agent with context+launchAgent(agentType: string, context?: string): void+```++### Hook Interface++```typescript+interface UFCHook {+ trigger: {+ semantic: string[];+ phrases: string[];+ };+ action: {+ loadContext?: string[];+ launchAgent?: string;+ execute?: string;+ };+}+```++## Examples++### Example 1: Website Update++```bash+User: "I need to update my blog with the latest AI news"++UFC Analysis:+- Triggers: ["blog", "update", "AI", "news"]+- Contexts: website, research+- Actions:+ 1. Load website context+ 2. Launch researcher agent+ 3. Combine results+```++### Example 2: Security Audit++```bash+User: "Check my server for vulnerabilities"++UFC Analysis:+- Triggers: ["check", "server", "vulnerabilities"]+- Context: security+- Actions:+ 1. Launch pentester agent+ 2. Load security context+ 3. Execute security scan+```++### Example 3: Financial Analysis++```bash+User: "How much did I spend on utilities last month?"++UFC Analysis:+- Triggers: ["spend", "utilities", "last month"]+- Context: financial+- Actions:+ 1. Load expense context+ 2. Parse financial data+ 3. Calculate utilities total+```++## Future Enhancements++### Planned Features++1. **Machine Learning Integration**: Learn from usage patterns+2. **Context Versioning**: Track context changes+3. **Multi-language Support**: Context in multiple languages+4. **Cloud Sync**: Synchronize contexts across devices+5. **Plugin System**: Third-party context providers++### Experimental Features++- **Auto-context Generation**: Create contexts from documentation+- **Context Compression**: Optimize large contexts+- **Predictive Loading**: Pre-load likely contexts+- **Context Sharing**: Share contexts between users++---++*UFC System Version 1.0.0*+*Last Updated: [Current Date]*\ No newline at end of filediff --git a/.claude/hooks/load-dynamic-requirements.ts b/.claude/hooks/load-dynamic-requirements.tsold mode 100755new mode 100644index 43ed5a6c..b7ffe5cc--- a/.claude/hooks/load-dynamic-requirements.ts+++ b/.claude/hooks/load-dynamic-requirements.ts@@ -48,13 +48,12 @@ async function main() {const data: HookInput = JSON.parse(input);// Read the markdown file with instructions from commands directory- const homeDir = process.env.PAI_HOME || process.env.HOME || '~';- const mdPath = join(homeDir, '.claude/commands/load-dynamic-requirements.md');+ const paiHome = process.env.PAI_HOME || '/Users/daniel';+ const mdPath = `${paiHome}/.claude/commands/load-dynamic-requirements.md`;const mdContent = readFileSync(mdPath, 'utf-8');// Output the markdown content to stdout// This will be passed to Claude as instructions- console.log("\nIMPORTANT: Variable $PAI_HOME = "+ homeDir + "\n");console.log(mdContent);// Also output a special marker to indicate this is a hook instructiondiff --git a/.claude/hooks/stop-hook.ts b/.claude/hooks/stop-hook.tsindex 80b92439..be90d2eb 100755--- a/.claude/hooks/stop-hook.ts+++ b/.claude/hooks/stop-hook.ts@@ -8,6 +8,7 @@ const VOICES = {pentester: 'hmMWXCj9K7N5mCPcRkfC',engineer: 'kmSVBPu7loj4ayNinwWM',designer: 'ZF6FPAbjXT4488VcRRnw',+ architect: 'muZKMsIDGYtIkjjiUS82',writer: 'gfRt6Z3Z8aTbpLfexQ7N',kai: 'jqcCZkN6Knx8BJ5TBdYR'};@@ -118,7 +119,7 @@ async function main() {// Generate the announcementlet message = '';- let voiceId = VOICES.kai;+ let voiceId = VOICES.kai; // Default to Kai's voiceif (agentType && taskResult) {// AGENT DID THE TASK - Look for [AGENT:type] I completed somethingdiff --git a/.claude/hooks/subagent-stop-hook.ts b/.claude/hooks/subagent-stop-hook.tsindex 4d2f55ad..52d632e3 100755--- a/.claude/hooks/subagent-stop-hook.ts+++ b/.claude/hooks/subagent-stop-hook.ts@@ -8,8 +8,10 @@ const AGENT_VOICE_IDS: Record<string, string> = {pentester: 'hmMWXCj9K7N5mCPcRkfC',engineer: 'kmSVBPu7loj4ayNinwWM',designer: 'ZF6FPAbjXT4488VcRRnw',+ architect: 'muZKMsIDGYtIkjjiUS82',writer: 'gfRt6Z3Z8aTbpLfexQ7N',- default: 'AXdMgz6evoL7OPd7eU12'+ kai: 'jqcCZkN6Knx8BJ5TBdYR',+ default: 'jqcCZkN6Knx8BJ5TBdYR'};async function delay(ms: number): Promise<void> {@@ -211,6 +213,7 @@ async function main() {// Prepare the notificationconst fullMessage = completionMessage; // Message is already prepared with agent name+ const agentName = finalAgentType.charAt(0).toUpperCase() + finalAgentType.slice(1);// Send to notification servertry {diff --git a/.claude/statusline-command.sh b/.claude/statusline-command.shindex 99205cb7..e0728ac3 100755--- a/.claude/statusline-command.sh+++ b/.claude/statusline-command.sh@@ -12,10 +12,10 @@ dir_name=$(basename "$current_dir")# Count items from specified directories# - Services count from ~/Projects/FoundryServices/Services-# - Commands from ~/.claude/commands/+# - Commands from ${PAI_HOME}/.claude/commands/# - MCPs from settings.json-# - Patterns from ~/.config/fabric/patterns-claude_dir="/Users/daniel/.claude"+# - Patterns from ${PAI_HOME}/.config/fabric/patterns+claude_dir="${PAI_HOME:-/Users/daniel}/.claude"commands_count=0mcps_count=0fobs_count=0@@ -32,13 +32,13 @@ if [ -f "$claude_dir/settings.json" ]; thenfi# Count Services from FoundryServices directory-services_dir="/Users/daniel/Projects/FoundryServices/Services"+services_dir="${PAI_HOME:-/Users/daniel}/Projects/FoundryServices/Services"if [ -d "$services_dir" ]; thenfobs_count=$(find "$services_dir" -type f -name "*.md" 2>/dev/null | wc -l | tr -d ' ')fi# Count Fabric patterns from ~/.config/fabric/patterns-fabric_patterns_dir="/Users/daniel/.config/fabric/patterns"+fabric_patterns_dir="${PAI_HOME:-/Users/daniel}/.config/fabric/patterns"if [ -d "$fabric_patterns_dir" ]; thenfabric_count=$(find "$fabric_patterns_dir" -maxdepth 1 -type d ! -path "$fabric_patterns_dir" 2>/dev/null | wc -l | tr -d ' ')fi@@ -92,6 +92,8 @@ BRIGHT_RED='\033[38;2;247;118;142m' # #f7768e - Bright red for errors# LINE 1 - MOSTLY PURPLE (#bb9af7)LINE1_PRIMARY="$BRIGHT_PURPLE" # Primary purple for most line 1 contentLINE1_ACCENT='\033[38;2;160;130;210m' # Slightly different purple shade for variety+MODEL_PURPLE='\033[38;2;138;99;210m' # Different purple for model name - deeper violet+KAI_PURPLE='\033[38;2;147;112;219m' # Different purple for "Kai" - medium violet# LINE 2 - MOSTLY DARK BLUELINE2_PRIMARY="$DARK_BLUE" # Primary dark blue for most line 2 content@@ -149,7 +151,7 @@ fiDIR_COLOR='\033[38;2;135;206;250m' # Light sky blue for directory# LINE 1 - MOSTLY PURPLE: Complete first line with all counts (services, commands, MCPs, patterns)-printf "${LINE1_PRIMARY}Kai here${RESET}${LINE1_PRIMARY}, running on ${LINE1_ACCENT}🧠 ${model_name}${RESET}${LINE1_PRIMARY} in ${DIR_COLOR}📁 ${dir_name}${RESET}${LINE1_PRIMARY}, wielding: ${RESET}${LINE1_PRIMARY}🔧 ${fobs_count} Services${RESET}${LINE1_PRIMARY}, ${RESET}${LINE1_PRIMARY}⚙️ ${commands_count} Commands${RESET}${LINE1_PRIMARY}, ${RESET}${LINE1_PRIMARY}🔌 ${mcps_count} MCPs${RESET}${LINE1_PRIMARY}, and ${RESET}${LINE1_PRIMARY}📚 ${fabric_count} Patterns${RESET}\n"+printf "${KAI_PURPLE}Kai${RESET}${LINE1_PRIMARY} here, running on ${MODEL_PURPLE}🧠 ${model_name}${RESET}${LINE1_PRIMARY} in ${DIR_COLOR}📁 ${dir_name}${RESET}${LINE1_PRIMARY}, wielding: ${RESET}${LINE1_PRIMARY}🔧 ${fobs_count} Services${RESET}${LINE1_PRIMARY}, ${RESET}${LINE1_PRIMARY}⚙️ ${commands_count} Commands${RESET}${LINE1_PRIMARY}, ${RESET}${LINE1_PRIMARY}🔌 ${mcps_count} MCPs${RESET}${LINE1_PRIMARY}, and ${RESET}${LINE1_PRIMARY}📚 ${fabric_count} Patterns${RESET}\n"# LINE 2 - MOSTLY DARK BLUE: MCP names listprintf "${LINE2_PRIMARY}🔌 MCPs${RESET}${LINE2_PRIMARY}${SEPARATOR_COLOR}: ${RESET}${mcp_names_formatted}${RESET}\n"diff --git a/.claude/voice-server/README.md b/.claude/voice-server/README.mdindex 3cba4735..6718b3b6 100644--- a/.claude/voice-server/README.md+++ b/.claude/voice-server/README.md@@ -1,195 +1,258 @@-# PAIVoice - Personal AI Voice Framework+# PAI Voice Server-PAIVoice is a flexible voice notification framework for Personal AI (PAI) systems on macOS. It provides natural-sounding voice notifications using ElevenLabs AI voices or fallback to macOS's built-in text-to-speech.+A voice notification server for the Personal AI Infrastructure (PAI) system that provides text-to-speech notifications using ElevenLabs API or macOS's built-in `say` command as fallback.-## 🎯 Purpose+> **Quick Start**: See [QUICKSTART.md](QUICKSTART.md) for a 5-minute setup guide.-This framework enables ANY Personal AI system to:-- Send voice notifications to users-- Provide audio feedback for completed tasks-- Create more engaging AI interactions-- Work with any AI assistant (not limited to a specific name or personality)+## 🎯 Features-## 🚀 Features+- **ElevenLabs Integration**: High-quality AI voices for notifications+- **Fallback Support**: Uses macOS `say` command when ElevenLabs is not configured+- **Multiple Voice Support**: Different voices for different AI agents+- **macOS Service**: Runs automatically in the background+- **Menu Bar Indicator**: Visual status indicator in macOS menu bar+- **Simple HTTP API**: Easy integration with any tool or script-- **AI Voice Support**: Natural voices via ElevenLabs API-- **Fallback Mode**: Works without API key using macOS 'say' command-- **Menu Bar Icon**: Visual status indicator with quick controls-- **Service Management**: Runs as a background service-- **Simple API**: Easy HTTP endpoints for notifications-- **Customizable**: Choose your own voice and personality+## 📋 Prerequisites-## 📦 Quick Setup+- macOS (tested on macOS 11+)+- [Bun](https://bun.sh) runtime installed+- ElevenLabs API key (optional, for AI voices)-### 1. Install Prerequisites+## 🚀 Quick Start++### 1. Install Bun (if not already installed)```bash-# Install Bun (JavaScript runtime)curl -fsSL https://bun.sh/install | bash```-### 2. Configure API Keys (Optional)+### 2. Configure API Key (Optional but Recommended)+Add your ElevenLabs API key to `~/.env`:```bash-# Add to ~/.env for AI voices-echo "ELEVENLABS_API_KEY=your_key_here" >> ~/.env-echo "ELEVENLABS_VOICE_ID=voice_id_here" >> ~/.env+echo "ELEVENLABS_API_KEY=your_api_key_here" >> ~/.env+echo "ELEVENLABS_VOICE_ID=jqcCZkN6Knx8BJ5TBdYR" >> ~/.env```-Get a free API key from [ElevenLabs](https://elevenlabs.io) (10,000 chars/month free)+> Get your free API key at [elevenlabs.io](https://elevenlabs.io) (10,000 characters/month free)-### 3. Install as Service+### 3. Install Voice Server```bash-cd ~/.claude/voice-server/macos-service+cd ~/.claude/voice-server./install.sh```-### 4. Add Menu Bar Icon (Optional)+This will:+- Install dependencies+- Create a macOS LaunchAgent for auto-start+- Start the voice server on port 8888+- Verify the installation+- Optionally install menu bar indicator (requires SwiftBar/BitBar)++## 🛠️ Service Management++### Start Server```bash-cd ~/.claude/voice-server/macos-service/menubar-./install-menubar.sh+./start.sh+# or+launchctl load ~/Library/LaunchAgents/com.pai.voice-server.plist```-## 🎙️ Usage+### Stop Server+```bash+./stop.sh+# or+launchctl unload ~/Library/LaunchAgents/com.pai.voice-server.plist+```-### Send a Notification+### Restart Server+```bash+./restart.sh+```++### Check Status+```bash+./status.sh+```++### Uninstall+```bash+./uninstall.sh+```+This will stop the service and remove the LaunchAgent.++## 📡 API Usage++### Send a Voice Notification```bashcurl -X POST http://localhost:8888/notify \-H "Content-Type: application/json" \-d '{- "title": "Your PAI Name","message": "Task completed successfully",+ "voice_id": "jqcCZkN6Knx8BJ5TBdYR","voice_enabled": true}'```-### PAI Assistant Notification-```bash-curl -X POST http://localhost:8888/pai \- -H "Content-Type: application/json" \- -d '{- "title": "Assistant",- "message": "I've finished analyzing your data"- }'+### Parameters+- `message` (required): The text to speak+- `voice_id` (optional): ElevenLabs voice ID to use+- `voice_enabled` (optional): Whether to speak the notification (default: true)+- `title` (optional): Notification title (default: "PAI Notification")++### Available Voice IDs+```javascript+// PAI System Agents+Kai: jqcCZkN6Knx8BJ5TBdYR // Main assistant+Researcher: AXdMgz6evoL7OPd7eU12 // Research agent+Engineer: kmSVBPu7loj4ayNinwWM // Engineering agent+Designer: ZF6FPAbjXT4488VcRRnw // Design agent+Pentester: hmMWXCj9K7N5mCPcRkfC // Security agent+Architect: muZKMsIDGYtIkjjiUS82 // Architecture agent+Writer: gfRt6Z3Z8aTbpLfexQ7N // Content agent```-## 🔧 Customization+## 🖥️ Menu Bar Indicator++The voice server includes an optional menu bar indicator that shows the server status.-### Choose Your Voice+### Installing the Menu Bar-Popular ElevenLabs voice IDs:-- `jqcCZkN6Knx8BJ5TBdYR` - Friendly assistant (default)-- `21m00Tcm4TlvDq8ikWAM` - Rachel (calm, professional)-- `AZnzlk1XvdvUeBnXmlld` - Domi (energetic)-- `EXAVITQu4vr4xnSDxMaL` - Bella (warm, friendly)+1. **Install SwiftBar** (recommended) or BitBar:+```bash+brew install --cask swiftbar+# OR+brew install --cask bitbar+```-Set in `~/.env`:+2. **Run the menu bar installer**:```bash-ELEVENLABS_VOICE_ID=your_chosen_voice_id+cd ~/.claude/voice-server/menubar+./install-menubar.sh```-### Customize for Your PAI+### Menu Bar Features+- **Visual Status**: 🎙️ (running) or 🎙️⚫ (stopped)+- **Quick Controls**: Start/Stop/Restart server from menu+- **Status Info**: Shows voice type (ElevenLabs/macOS Say)+- **Quick Test**: Test voice with one click+- **View Logs**: Access server logs directly++### Manual Installation+If you prefer manual installation:+1. Copy `menubar/pai-voice.5s.sh` to your SwiftBar/BitBar plugins folder+2. Make it executable: `chmod +x pai-voice.5s.sh`+3. Refresh SwiftBar/BitBar-The framework is designed to work with ANY Personal AI system:-- Use your PAI's name in the `title` field-- Customize messages to match your PAI's personality-- Integrate with your existing AI tools and workflows+## 🔧 Configuration-## 📡 API Endpoints+### Environment Variables+Create or edit `~/.env` in your home directory:-- `POST /notify` - General notification with optional voice-- `POST /pai` - PAI-specific notification (always with voice)-- `GET /health` - Service health check+```bash+# Required for ElevenLabs voices (optional)+ELEVENLABS_API_KEY=your_api_key_here-### Request Format-```json-{- "title": "Your PAI Name",- "message": "Notification text",- "voice_enabled": true,- "voice_id": "optional_voice_override"-}+# Default voice ID (optional, defaults to Kai)+ELEVENLABS_VOICE_ID=jqcCZkN6Knx8BJ5TBdYR++# Server port (optional, defaults to 8888)+PORT=8888```-## 🛠️ Service Management+### Finding Your Voice ID+1. Go to [ElevenLabs Voice Library](https://elevenlabs.io/voice-library)+2. Select a voice you like+3. Click "Use" and copy the Voice ID+4. Update `ELEVENLABS_VOICE_ID` in your `~/.env`+## 🐛 Troubleshooting++### Server won't start```bash-# Control the service-./macos-service/voice-server-ctl.sh status-./macos-service/voice-server-ctl.sh start-./macos-service/voice-server-ctl.sh stop-./macos-service/voice-server-ctl.sh restart+# Check if port 8888 is already in use+lsof -i :8888-# View logs-./macos-service/voice-server-ctl.sh logs+# Kill any existing process+lsof -ti :8888 | xargs kill -9-# Test the service-./macos-service/voice-server-ctl.sh test+# Restart the server+./restart.sh```-## 📊 Menu Bar Icon+### No voice output+```bash+# Check if ElevenLabs key is configured+grep ELEVENLABS_API_KEY ~/.env-The menu bar icon shows:-- 🎙️ = Server running-- 🔇 = Server stopped+# Test with fallback (macOS say)+curl -X POST http://localhost:8888/notify \+ -H "Content-Type: application/json" \+ -d '{"message": "Testing voice output"}'-Click for quick access to controls and status.+# Check server logs+tail -f ~/Library/Logs/pai-voice-server.log+```-## 🔒 Security+### Service not auto-starting+```bash+# Check LaunchAgent status+launchctl list | grep pai.voice-- API keys stored locally in `~/.env`-- Service runs as user (not root)-- Only accepts local connections-- No data sent except to ElevenLabs (if configured)+# Reload LaunchAgent+launchctl unload ~/Library/LaunchAgents/com.pai.voice-server.plist+launchctl load ~/Library/LaunchAgents/com.pai.voice-server.plist-## 📁 Project Structure+# Check for errors+tail -f ~/Library/Logs/pai-voice-server.log+```+## 📁 File Structure```-voice-server/-├── server.ts # Main server code-├── start.sh # Manual start script-├── macos-service/-│ ├── com.paivoice.server.plist # Service configuration-│ ├── install.sh # Service installer-│ ├── uninstall.sh # Service remover-│ ├── voice-server-ctl.sh # Service control-│ ├── validate-setup.sh # Setup validator-│ └── menubar/ # Menu bar icon-└── README.md # This file+~/.claude/voice-server/+├── server.ts # Main server code+├── install.sh # Installation script+├── start.sh # Start server+├── stop.sh # Stop server+├── restart.sh # Restart server+├── status.sh # Check server status+├── uninstall.sh # Uninstall service+├── README.md # This file+└── menubar/+ ├── pai-voice.5s.sh # Menu bar status script+ └── install-menubar.sh # Menu bar installer++~/Library/LaunchAgents/+└── com.pai.voice-server.plist # macOS service definition++~/Library/Logs/+└── pai-voice-server.log # Server logs```-## 🤝 Integration Examples+## 🔐 Security Notes-### With Python AI Agent-```python-import requests+- **No hardcoded API keys**: All sensitive data is read from `~/.env`+- **Local only**: Server only listens on localhost (127.0.0.1)+- **User-specific**: Each user maintains their own API keys+- **Safe for public repos**: No sensitive data in the codebase-def send_voice_notification(message):- requests.post('http://localhost:8888/pai', json={- 'title': 'My AI Assistant',- 'message': message- })+## 🤝 Integration with PAI System-# Use in your AI workflow-send_voice_notification("Analysis complete. Found 3 insights.")-```+This voice server integrates with the PAI (Personal AI Infrastructure) system to provide voice notifications when:+- Tasks are completed+- Agents finish their work+- Important events occur+- User notifications are needed-### With Node.js/Bun-```javascript-async function notify(message) {- await fetch('http://localhost:8888/pai', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- title: 'AI Helper',- message: message- })- });-}-```+The PAI hooks automatically send notifications to this server when configured.## 📝 License-Open source - Customize for your needs!+Part of the PAI (Personal AI Infrastructure) system.-## 🙏 Credits+## 🆘 Support-Built as a framework for Personal AI systems, inspired by the need for better human-AI interaction through voice.\ No newline at end of file+For issues or questions:+1. Check the troubleshooting section above+2. Review logs at `~/Library/Logs/pai-voice-server.log`+3. Ensure your ElevenLabs API key is valid+4. Try the fallback mode (without API key) to isolate issues\ No newline at end of filediff --git a/.claude/voice-server/install.sh b/.claude/voice-server/install.shnew file mode 100755index 00000000..6f5a7e65--- /dev/null+++ b/.claude/voice-server/install.sh@@ -0,0 +1,206 @@+#!/bin/bash++# PAI Voice Server Installation Script+# This script installs the voice server as a macOS service++set -e++# Colors for output+RED='\033[0;31m'+GREEN='\033[0;32m'+YELLOW='\033[1;33m'+BLUE='\033[0;34m'+NC='\033[0m' # No Color++# Configuration+SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"+SERVICE_NAME="com.pai.voice-server"+PLIST_PATH="$HOME/Library/LaunchAgents/${SERVICE_NAME}.plist"+LOG_PATH="$HOME/Library/Logs/pai-voice-server.log"+ENV_FILE="$HOME/.env"++echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"+echo -e "${BLUE} PAI Voice Server Installation${NC}"+echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"+echo++# Check for Bun+echo -e "${YELLOW}▶ Checking prerequisites...${NC}"+if ! command -v bun &> /dev/null; then+ echo -e "${RED}✗ Bun is not installed${NC}"+ echo " Please install Bun first:"+ echo " curl -fsSL https://bun.sh/install | bash"+ exit 1+fi+echo -e "${GREEN}✓ Bun is installed${NC}"++# Check for existing installation+if launchctl list | grep -q "$SERVICE_NAME" 2>/dev/null; then+ echo -e "${YELLOW}⚠ Voice server is already installed${NC}"+ read -p "Do you want to reinstall? (y/n): " -n 1 -r+ echo+ if [[ $REPLY =~ ^[Yy]$ ]]; then+ echo -e "${YELLOW}▶ Stopping existing service...${NC}"+ launchctl unload "$PLIST_PATH" 2>/dev/null || true+ echo -e "${GREEN}✓ Existing service stopped${NC}"+ else+ echo "Installation cancelled"+ exit 0+ fi+fi++# Check for ElevenLabs configuration+echo -e "${YELLOW}▶ Checking ElevenLabs configuration...${NC}"+if [ -f "$ENV_FILE" ] && grep -q "ELEVENLABS_API_KEY=" "$ENV_FILE"; then+ API_KEY=$(grep "ELEVENLABS_API_KEY=" "$ENV_FILE" | cut -d'=' -f2)+ if [ "$API_KEY" != "your_api_key_here" ] && [ -n "$API_KEY" ]; then+ echo -e "${GREEN}✓ ElevenLabs API key configured${NC}"+ ELEVENLABS_CONFIGURED=true+ else+ echo -e "${YELLOW}⚠ ElevenLabs API key not configured${NC}"+ echo " Voice server will use macOS 'say' command as fallback"+ ELEVENLABS_CONFIGURED=false+ fi+else+ echo -e "${YELLOW}⚠ No ElevenLabs configuration found${NC}"+ echo " Voice server will use macOS 'say' command as fallback"+ ELEVENLABS_CONFIGURED=false+fi++if [ "$ELEVENLABS_CONFIGURED" = false ]; then+ echo+ echo "To enable AI voices, add your ElevenLabs API key to ~/.env:"+ echo " echo 'ELEVENLABS_API_KEY=your_api_key_here' >> ~/.env"+ echo " Get a free key at: https://elevenlabs.io"+ echo+fi++# Create LaunchAgent plist+echo -e "${YELLOW}▶ Creating LaunchAgent configuration...${NC}"+mkdir -p "$HOME/Library/LaunchAgents"++cat > "$PLIST_PATH" << 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">+<dict>+ <key>Label</key>+ <string>${SERVICE_NAME}</string>++ <key>ProgramArguments</key>+ <array>+ <string>$(which bun)</string>+ <string>run</string>+ <string>${SCRIPT_DIR}/server.ts</string>+ </array>++ <key>WorkingDirectory</key>+ <string>${SCRIPT_DIR}</string>++ <key>RunAtLoad</key>+ <true/>++ <key>KeepAlive</key>+ <dict>+ <key>SuccessfulExit</key>+ <false/>+ </dict>++ <key>StandardOutPath</key>+ <string>${LOG_PATH}</string>++ <key>StandardErrorPath</key>+ <string>${LOG_PATH}</string>++ <key>EnvironmentVariables</key>+ <dict>+ <key>HOME</key>+ <string>${HOME}</string>+ <key>PATH</key>+ <string>/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:${HOME}/.bun/bin</string>+ </dict>+</dict>+</plist>+EOF++echo -e "${GREEN}✓ LaunchAgent configuration created${NC}"++# Load the LaunchAgent+echo -e "${YELLOW}▶ Starting voice server service...${NC}"+launchctl load "$PLIST_PATH" 2>/dev/null || {+ echo -e "${RED}✗ Failed to load LaunchAgent${NC}"+ echo " Try manually: launchctl load $PLIST_PATH"+ exit 1+}++# Wait for server to start+sleep 2++# Test the server+echo -e "${YELLOW}▶ Testing voice server...${NC}"+if curl -s -f -X GET http://localhost:8888/health > /dev/null 2>&1; then+ echo -e "${GREEN}✓ Voice server is running${NC}"++ # Send test notification+ echo -e "${YELLOW}▶ Sending test notification...${NC}"+ curl -s -X POST http://localhost:8888/notify \+ -H "Content-Type: application/json" \+ -d '{"message": "Voice server installed successfully"}' > /dev/null+ echo -e "${GREEN}✓ Test notification sent${NC}"+else+ echo -e "${RED}✗ Voice server is not responding${NC}"+ echo " Check logs at: $LOG_PATH"+ echo " Try running manually: bun run $SCRIPT_DIR/server.ts"+ exit 1+fi++# Show summary+echo+echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"+echo -e "${GREEN} ✓ Installation Complete!${NC}"+echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"+echo+echo -e "${BLUE}Service Information:${NC}"+echo " • Service: $SERVICE_NAME"+echo " • Status: Running"+echo " • Port: 8888"+echo " • Logs: $LOG_PATH"++if [ "$ELEVENLABS_CONFIGURED" = true ]; then+ echo " • Voice: ElevenLabs AI"+else+ echo " • Voice: macOS Say (fallback)"+fi++echo+echo -e "${BLUE}Management Commands:${NC}"+echo " • Status: ./status.sh"+echo " • Stop: ./stop.sh"+echo " • Start: ./start.sh"+echo " • Restart: ./restart.sh"+echo " • Uninstall: ./uninstall.sh"++echo+echo -e "${BLUE}Test the server:${NC}"+echo " curl -X POST http://localhost:8888/notify \\"+echo " -H 'Content-Type: application/json' \\"+echo " -d '{\"message\": \"Hello from PAI\"}'"++echo+echo -e "${GREEN}The voice server will now start automatically when you log in.${NC}"++# Ask about menu bar indicator+echo+read -p "Would you like to install a menu bar indicator? (y/n): " -n 1 -r+echo+if [[ $REPLY =~ ^[Yy]$ ]]; then+ echo -e "${YELLOW}▶ Installing menu bar indicator...${NC}"+ if [ -f "$SCRIPT_DIR/menubar/install-menubar.sh" ]; then+ chmod +x "$SCRIPT_DIR/menubar/install-menubar.sh"+ "$SCRIPT_DIR/menubar/install-menubar.sh"+ else+ echo -e "${YELLOW}⚠ Menu bar installer not found${NC}"+ echo " You can install it manually later from:"+ echo " $SCRIPT_DIR/menubar/install-menubar.sh"+ fi+fi\ No newline at end of filediff --git a/.claude/voice-server/macos-service/README.md b/.claude/voice-server/macos-service/README.mddeleted file mode 100644index 24d46dd1..00000000--- a/.claude/voice-server/macos-service/README.md+++ /dev/null@@ -1,272 +0,0 @@-# PAIVoice Server - Personal AI Voice Framework for macOS--This directory contains all the components needed to run the PAIVoice Server as a macOS LaunchAgent service that starts automatically on login. PAIVoice is a framework for giving ANY Personal AI (PAI) system voice capabilities on macOS.--## 🚀 Quick Start--### Prerequisites--1. **Install Bun** (if not already installed):- ```bash- curl -fsSL https://bun.sh/install | bash- ```--2. **Set up API Keys** (Optional but recommended):-- The server can work in two modes:- - **Basic Mode**: Uses macOS built-in 'say' command (no API key needed)- - **AI Voice Mode**: Uses ElevenLabs for natural AI voices (requires API key)-- To enable AI voices:- ```bash- # Add to ~/.env file:- echo "ELEVENLABS_API_KEY=your_api_key_here" >> ~/.env- echo "ELEVENLABS_VOICE_ID=voice_id_here" >> ~/.env # Optional- ```-- Get a free API key from [ElevenLabs](https://elevenlabs.io) (includes 10,000 characters/month free)--### Install and Start the Service--```bash-cd ~/.claude/voice-server/macos-service-./install.sh-```--That's it! The server will now start automatically when you log in.--### Validate Setup (Recommended)--Check if everything is configured correctly:-```bash-./validate-setup.sh-```--### Test the Service--```bash-./voice-server-ctl.sh test-```--## 📁 Files in this Directory--- **`com.paivoice.server.plist`** - macOS LaunchAgent configuration file-- **`install.sh`** - Installs the service-- **`uninstall.sh`** - Removes the service-- **`voice-server-ctl.sh`** - Service management utility-- **`validate-setup.sh`** - Checks if everything is configured correctly-- **`README.md`** - This documentation--## 🛠️ Service Management--Use the control script for all service operations:--```bash-# Check service status-./voice-server-ctl.sh status--# Start the service-./voice-server-ctl.sh start--# Stop the service-./voice-server-ctl.sh stop--# Restart the service-./voice-server-ctl.sh restart--# View live logs-./voice-server-ctl.sh logs--# Test with a notification-./voice-server-ctl.sh test-```--## 📋 Manual Commands--If you prefer using launchctl directly:--```bash-# Start service-launchctl start com.paivoice.server--# Stop service-launchctl stop com.paivoice.server--# Check if running-launchctl list | grep com.paivoice.server--# View logs-tail -f ~/.claude/voice-server/logs/voice-server.log-```--## 🔧 Configuration--### Environment Variables--All configuration is done via `~/.env` file in your home directory:--```bash-# Required for AI voices (get free at https://elevenlabs.io)-ELEVENLABS_API_KEY=your_api_key_here--# Optional - customize voice (defaults to default voice)-ELEVENLABS_VOICE_ID=voice_id_here--# Optional - change port (default 8888)-PORT=8888-```--### Available Voice IDs--Popular ElevenLabs voices you can use:-- `jqcCZkN6Knx8BJ5TBdYR` - Default voice (friendly assistant)-- `21m00Tcm4TlvDq8ikWAM` - Rachel (calm, professional)-- `AZnzlk1XvdvUeBnXmlld` - Domi (energetic)-- `EXAVITQu4vr4xnSDxMaL` - Bella (warm, friendly)--Find more voices at [ElevenLabs Voice Library](https://elevenlabs.io/voice-library)--### Service Settings--The service configuration is stored in the plist file:--- **Port**: 8888 (default, configurable via ~/.env)-- **Auto-start**: Yes (RunAtLoad)-- **Keep-alive**: Yes (restarts on crash)-- **Logs**: `~/.claude/voice-server/logs/`--### Modify Settings--After changing `~/.env`:-```bash-./voice-server-ctl.sh restart-```--For plist changes:-```bash-./uninstall.sh-./install.sh-```--## 📡 API Endpoints--Once running, the server provides:--- `POST http://localhost:8888/notify` - Send notification with optional voice-- `POST http://localhost:8888/pai` - Send PAI assistant notification-- `GET http://localhost:8888/health` - Health check--### Example Request--```bash-curl -X POST http://localhost:8888/notify \- -H "Content-Type: application/json" \- -d '{- "title": "Test",- "message": "Hello from Voice Server",- "voice_enabled": true- }'-```--## 🗑️ Uninstall--To completely remove the service:--```bash-./uninstall.sh-```--This will:-- Stop the running service-- Remove it from LaunchAgents-- Preserve log files for reference--## 🔑 About ElevenLabs API Keys--### What is ElevenLabs?-ElevenLabs provides state-of-the-art AI voice synthesis. Their voices sound natural and expressive, far superior to traditional text-to-speech.--### Do I Need an API Key?-- **No** - The server works without one, using macOS 'say' command-- **Recommended** - For natural AI voices that sound like real people--### How to Get a Free API Key-1. Visit [ElevenLabs](https://elevenlabs.io)-2. Sign up for a free account-3. Go to your [API Keys page](https://elevenlabs.io/api-keys)-4. Copy your API key-5. Add it to `~/.env`:- ```bash- echo "ELEVENLABS_API_KEY=your_key_here" >> ~/.env- ```--### Free Tier Limits-- **10,000 characters/month** free-- Approximately 1,500-2,000 notifications-- Resets monthly-- No credit card required--### Is My API Key Safe?-- Stored only in your local `~/.env` file-- Never committed to git (add `.env` to `.gitignore`)-- Only accessible by your user account-- Not included in the service configuration files--## 🐛 Troubleshooting--### Service won't start--1. Check logs:- ```bash- cat ~/.claude/voice-server/logs/voice-server-error.log- ```--2. Verify bun is installed:- ```bash- which bun- ```--3. Check port 8888 is free:- ```bash- lsof -i :8888- ```--### Service starts but no voice--1. Test ElevenLabs API key in the plist file-2. Check network connectivity-3. Verify audio permissions in System Preferences--### Permission Issues--If you get permission denied errors:-```bash-chmod +x ~/.claude/voice-server/macos-service/*.sh-```--## 📊 Service Architecture--```-User Login- ↓-launchd reads plist- ↓-Starts bun process- ↓-server.ts runs- ↓-Listens on port 8888- ↓-Ready for notifications-```--## 🔐 Security Notes--- Service runs as your user (not root)-- Only accepts local connections (localhost)-- API keys stored in plist (user-readable only)-- Logs stored in user home directory--## 📝 License--Internal tool - not for distribution\ No newline at end of filediff --git a/.claude/voice-server/macos-service/menubar/README.md b/.claude/voice-server/macos-service/menubar/README.mddeleted file mode 100644index d2eb6282..00000000--- a/.claude/voice-server/macos-service/menubar/README.md+++ /dev/null@@ -1,120 +0,0 @@-# PAIVoice Server Menu Bar Icon--Adds a status icon to your macOS menu bar that shows if the PAIVoice server is running and provides quick controls for your Personal AI voice system.--## 🚀 Quick Install--```bash-cd ~/.claude/voice-server/macos-service/menubar-./install-menubar.sh-```--## 📊 What It Shows--### Menu Bar Icons-- **🎙️** = Voice server is running (active)-- **🔇** = Voice server is stopped (inactive)--### Click Menu Options-When you click the icon, you'll see:-- Server status (running/stopped)-- Port number-- Voice type (AI/macOS)-- Quick actions:- - Test notification- - Start/Stop/Restart server- - View logs- - Check setup--## 🛠️ Requirements--### SwiftBar (Required)-The menu bar icon uses SwiftBar, a free app that runs scripts in your menu bar.--**Install SwiftBar:**-- **Option 1:** Download from [swiftbar.app](https://swiftbar.app)-- **Option 2:** Install with Homebrew:- ```bash- brew install --cask swiftbar- ```--## 📁 Files--- `voice-server.5s.sh` - The SwiftBar plugin script (refreshes every 5 seconds)-- `install-menubar.sh` - Automated installer-- `README.md` - This documentation--## 🔧 Manual Installation--If you prefer to install manually:--1. Install SwiftBar from [swiftbar.app](https://swiftbar.app)--2. Copy the plugin to SwiftBar's plugins folder:- ```bash- cp voice-server.5s.sh ~/Library/Application\ Support/SwiftBar/Plugins/- chmod +x ~/Library/Application\ Support/SwiftBar/Plugins/voice-server.5s.sh- ```--3. Open SwiftBar and select the plugins folder when prompted--## ⚙️ Customization--### Change Refresh Rate-The `5s` in the filename means it refreshes every 5 seconds. You can change this:-- `voice-server.1s.sh` - Refresh every second (more responsive)-- `voice-server.10s.sh` - Refresh every 10 seconds (less CPU usage)-- `voice-server.30s.sh` - Refresh every 30 seconds (minimal CPU)--### Modify Icons-Edit `voice-server.5s.sh` and change the emoji icons:-```bash-echo "🎙️" # Change this to any emoji or text-```--Popular alternatives:-- `🔊` - Speaker-- `🎵` - Musical note-- `🗣️` - Speaking head-- `📢` - Megaphone-- `●` - Simple dot (red/green with colors)--## 🗑️ Uninstall--Remove the menu bar icon:-```bash-rm ~/Library/Application\ Support/SwiftBar/Plugins/voice-server.5s.sh-```--Or keep SwiftBar and just disable the plugin in SwiftBar preferences.--## 🐛 Troubleshooting--### Icon not appearing-1. Make sure SwiftBar is running-2. Check SwiftBar is using the correct plugins folder:- - Click SwiftBar icon → Preferences- - Verify Plugin Folder path-3. Ensure plugin is executable:- ```bash- chmod +x ~/Library/Application\ Support/SwiftBar/Plugins/voice-server.5s.sh- ```--### Icon not updating-- Click the icon and select "Refresh"-- Check if the server is actually running:- ```bash- curl http://localhost:8888/health- ```--### SwiftBar using too much CPU-- Rename the plugin file to use a longer refresh interval (e.g., `voice-server.30s.sh`)--## 🎨 How It Works--The plugin is a simple bash script that:-1. Checks if the server is running (via health endpoint)-2. Outputs text in SwiftBar format-3. Provides clickable menu items that run commands--SwiftBar runs this script at the specified interval and displays the output in your menu bar.\ No newline at end of filediff --git a/.claude/voice-server/menubar/install-menubar.sh b/.claude/voice-server/menubar/install-menubar.shnew file mode 100755index 00000000..36f58597--- /dev/null+++ b/.claude/voice-server/menubar/install-menubar.sh@@ -0,0 +1,115 @@+#!/bin/bash++# Install Menu Bar Indicator for PAI Voice Server++set -e++# Colors+RED='\033[0;31m'+GREEN='\033[0;32m'+YELLOW='\033[1;33m'+BLUE='\033[0;34m'+NC='\033[0m'++SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"+MENUBAR_SCRIPT="$SCRIPT_DIR/pai-voice.5s.sh"++echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"+echo -e "${BLUE} PAI Voice Menu Bar Installation${NC}"+echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"+echo++# Check if SwiftBar is installed+if [ -d "/Applications/SwiftBar.app" ]; then+ echo -e "${GREEN}✓ SwiftBar is installed${NC}"+ MENUBAR_APP="SwiftBar"+ PLUGIN_DIR="$HOME/Library/Application Support/SwiftBar/Plugins"+elif [ -d "/Applications/BitBar.app" ]; then+ echo -e "${GREEN}✓ BitBar is installed${NC}"+ MENUBAR_APP="BitBar"+ # Check for BitBar plugin directory+ if [ -d "$HOME/Documents/BitBarPlugins" ]; then+ PLUGIN_DIR="$HOME/Documents/BitBarPlugins"+ elif [ -d "$HOME/BitBar" ]; then+ PLUGIN_DIR="$HOME/BitBar"+ else+ PLUGIN_DIR="$HOME/Documents/BitBarPlugins"+ echo -e "${YELLOW}▶ Creating BitBar plugin directory...${NC}"+ mkdir -p "$PLUGIN_DIR"+ fi+else+ echo -e "${RED}✗ Neither SwiftBar nor BitBar is installed${NC}"+ echo+ echo "Please install SwiftBar (recommended) or BitBar first:"+ echo+ echo "Option 1: Install SwiftBar (Recommended)"+ echo " brew install --cask swiftbar"+ echo " Or download from: https://github.com/swiftbar/SwiftBar/releases"+ echo+ echo "Option 2: Install BitBar"+ echo " brew install --cask bitbar"+ echo " Or download from: https://getbitbar.com"+ echo+ exit 1+fi++# Make script executable+chmod +x "$MENUBAR_SCRIPT"++# Create plugin directory if it doesn't exist+mkdir -p "$PLUGIN_DIR"++# Copy or link the script+echo -e "${YELLOW}▶ Installing menu bar plugin...${NC}"++# Remove existing plugin if it exists+rm -f "$PLUGIN_DIR/pai-voice.5s.sh" 2>/dev/null || true++# Create symbolic link to our script+ln -s "$MENUBAR_SCRIPT" "$PLUGIN_DIR/pai-voice.5s.sh"++echo -e "${GREEN}✓ Menu bar plugin installed${NC}"++# Refresh SwiftBar/BitBar+if [ "$MENUBAR_APP" = "SwiftBar" ]; then+ echo -e "${YELLOW}▶ Refreshing SwiftBar...${NC}"+ if pgrep -x "SwiftBar" > /dev/null; then+ # SwiftBar refresh via URL scheme+ open -g "swiftbar://refreshall"+ echo -e "${GREEN}✓ SwiftBar refreshed${NC}"+ else+ echo -e "${YELLOW}▶ Starting SwiftBar...${NC}"+ open -a SwiftBar+ sleep 2+ echo -e "${GREEN}✓ SwiftBar started${NC}"+ fi+else+ echo -e "${YELLOW}▶ Refreshing BitBar...${NC}"+ if pgrep -x "BitBar" > /dev/null; then+ killall BitBar 2>/dev/null || true+ sleep 1+ fi+ open -a BitBar+ echo -e "${GREEN}✓ BitBar started${NC}"+fi++echo+echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"+echo -e "${GREEN} ✓ Menu Bar Installation Complete${NC}"+echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"+echo+echo -e "${BLUE}You should now see a 🎙️ icon in your menu bar!${NC}"+echo+echo "The icon shows:"+echo " • 🎙️ (colored) - Server is running"+echo " • 🎙️⚫ (gray) - Server is stopped"+echo+echo "Click the icon to:"+echo " • Start/Stop the server"+echo " • View status and logs"+echo " • Test voice output"+echo+echo -e "${YELLOW}Note:${NC} If you don't see the icon, you may need to:"+echo " 1. Open $MENUBAR_APP preferences"+echo " 2. Set the plugin folder to: $PLUGIN_DIR"+echo " 3. Restart $MENUBAR_APP"\ No newline at end of filediff --git a/.claude/voice-server/menubar/pai-voice.5s.sh b/.claude/voice-server/menubar/pai-voice.5s.shnew file mode 100755index 00000000..97fbf867--- /dev/null+++ b/.claude/voice-server/menubar/pai-voice.5s.sh@@ -0,0 +1,45 @@+#!/bin/bash++# PAI Voice Server Menu Bar Indicator+# For BitBar/SwiftBar - updates every 5 seconds++# Check if server is running+if curl -s -f http://localhost:8888/health > /dev/null 2>&1; then+ # Server is running - show green indicator with size+ echo "🎙️ | size=18"+ echo "---"+ echo "PAI Voice Server: ✅ Running"++ # Check for ElevenLabs+ if [ -f ~/.env ] && grep -q "ELEVENLABS_API_KEY=" ~/.env 2>/dev/null; then+ API_KEY=$(grep "ELEVENLABS_API_KEY=" ~/.env | cut -d'=' -f2)+ if [ "$API_KEY" != "your_api_key_here" ] && [ -n "$API_KEY" ]; then+ echo "Voice: ElevenLabs AI"+ else+ echo "Voice: macOS Say"+ fi+ else+ echo "Voice: macOS Say"+ fi++ echo "Port: 8888"+ echo "---"+ echo "Stop Server | bash='~/.claude/voice-server/stop.sh' terminal=false refresh=true"+ echo "Restart Server | bash='~/.claude/voice-server/restart.sh' terminal=false refresh=true"+else+ # Server is not running - show gray indicator with size+ echo "🎙️⚫ | size=18"+ echo "---"+ echo "PAI Voice Server: ⚫ Stopped"+ echo "---"+ echo "Start Server | bash='~/.claude/voice-server/start.sh' terminal=false refresh=true"+fi++echo "---"+echo "Check Status | bash='~/.claude/voice-server/status.sh' terminal=true"+echo "View Logs | bash='tail -f ~/Library/Logs/pai-voice-server.log' terminal=true"+echo "---"+echo "Test Voice | bash='curl -X POST http://localhost:8888/notify -H \"Content-Type: application/json\" -d \"{\\\"message\\\":\\\"Testing voice server\\\"}\"' terminal=false"+echo "---"+echo "Open Voice Server Folder | bash='open ~/.claude/voice-server'"+echo "Uninstall | bash='~/.claude/voice-server/uninstall.sh' terminal=true"\ No newline at end of filediff --git a/.claude/voice-server/restart.sh b/.claude/voice-server/restart.shnew file mode 100755index 00000000..5af2f316--- /dev/null+++ b/.claude/voice-server/restart.sh@@ -0,0 +1,23 @@+#!/bin/bash++# Restart the PAI Voice Server++SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"++# Colors+YELLOW='\033[1;33m'+GREEN='\033[0;32m'+NC='\033[0m'++echo -e "${YELLOW}▶ Restarting PAI Voice Server...${NC}"++# Stop the server+"$SCRIPT_DIR/stop.sh"++# Wait a moment+sleep 2++# Start the server+"$SCRIPT_DIR/start.sh"++echo -e "${GREEN}✓ Voice server restarted${NC}"\ No newline at end of filediff --git a/.claude/voice-server/run-server.sh b/.claude/voice-server/run-server.shnew file mode 100755index 00000000..6f27f249--- /dev/null+++ b/.claude/voice-server/run-server.sh@@ -0,0 +1,9 @@+#!/usr/bin/env bash+# Voice Server Launcher Script++export HOME=/Users/daniel+export PATH=/Users/daniel/.bun/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin+export PORT=8888++cd /Users/daniel/.claude/voice-server+exec /Users/daniel/.bun/bin/bun run server.ts\ No newline at end of filediff --git a/.claude/voice-server/server.ts b/.claude/voice-server/server.tsindex 894be9b5..b8f20957 100644--- a/.claude/voice-server/server.ts+++ b/.claude/voice-server/server.ts@@ -4,8 +4,7 @@*/import { serve } from "bun";-import { exec } from "child_process";-import { promisify } from "util";+import { spawn } from "child_process";import { writeFile, unlink } from "fs/promises";import { tmpdir } from "os";import { join } from "path";@@ -24,12 +23,11 @@ if (existsSync(envPath)) {});}-const execAsync = promisify(exec);const PORT = parseInt(process.env.PORT || "8888");// ElevenLabs configuration - MUST be set in ~/.envconst ELEVENLABS_API_KEY = process.env.ELEVENLABS_API_KEY;-const ELEVENLABS_VOICE_ID = process.env.ELEVENLABS_VOICE_ID || "jqcCZkN6Knx8BJ5TBdYR";+const ELEVENLABS_VOICE_ID = process.env.ELEVENLABS_VOICE_ID || process.env.DEFAULT_VOICE_ID || "jqcCZkN6Knx8BJ5TBdYR";if (!ELEVENLABS_API_KEY) {console.error("⚠️ Warning: ELEVENLABS_API_KEY not found in ~/.env");@@ -38,8 +36,42 @@ if (!ELEVENLABS_API_KEY) {console.error(" ELEVENLABS_API_KEY=your_api_key_here");}+// Sanitize input for shell commands+function sanitizeForShell(input: string): string {+ // Remove any characters that could be used for command injection+ // Allow only alphanumeric, spaces, and basic punctuation+ return input.replace(/[^a-zA-Z0-9\s.,!?\-']/g, '').trim().substring(0, 500);+}++// Validate and sanitize user input+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+ ];++ for (const pattern of dangerousPatterns) {+ if (pattern.test(input)) {+ return { valid: false, error: 'Invalid characters in input' };+ }+ }++ return { valid: true };+}+// Generate voice using ElevenLabs-async function generateVoice(text, voiceId = null) {+async function generateVoice(text: string, voiceId: string | null = null): Promise<string | null> {// If no API key, return null to trigger fallbackif (!ELEVENLABS_API_KEY) {return null;@@ -86,29 +118,100 @@ async function generateVoice(text, voiceId = null) {}}+// 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, message, voiceEnabled = true, voiceId = null) {+async function sendNotification(title: string, message: string, voiceEnabled = true, voiceId: string | null = null) {+ // Validate 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}`);+ }++ // Sanitize inputs for shell commands+ const safeTitle = sanitizeForShell(title);+ const safeMessage = sanitizeForShell(message);+if (voiceEnabled) {- const audioFile = await generateVoice(message, voiceId);+ const audioFile = await generateVoice(safeMessage, voiceId);if (audioFile) {- execAsync(`afplay "${audioFile}"`).then(() => {- unlink(audioFile).catch(() => {});- }).catch(() => {- console.error("Failed to play ElevenLabs audio");- execAsync(`say "${message}"`).catch(() => {});- });+ // Use spawn for safer audio playback+ try {+ await spawnSafe('/usr/bin/afplay', [audioFile]);+ await unlink(audioFile).catch(() => {});+ } catch (error) {+ console.error("Failed to play ElevenLabs audio:", error);+ // Fallback to say command+ try {+ await spawnSafe('/usr/bin/say', [safeMessage]);+ } catch (e) {+ console.error("Failed to speak message:", e);+ }+ }} else {- execAsync(`say "${message}"`).catch(() => {- console.error("Failed to speak message");- });+ // Use spawn for say command+ try {+ await spawnSafe('say', [safeMessage]);+ } catch (error) {+ console.error("Say command error:", error);+ }}}- const escapedMessage = message.replace(/'/g, "'\\''").replace(/"/g, '\\"');- const escapedTitle = title.replace(/'/g, "'\\''").replace(/"/g, '\\"');- const script = `display notification "${escapedMessage}" with title "${escapedTitle}" sound name ""`;- await execAsync(`osascript -e '${script}'`);+ // Use spawn for osascript with proper escaping+ try {+ const script = `display notification "${safeMessage}" with title "${safeTitle}" 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; // 10 requests per minute+const RATE_WINDOW = 60000; // 1 minute in milliseconds++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@@ -117,8 +220,12 @@ const server = serve({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 securityconst corsHeaders = {- "Access-Control-Allow-Origin": "*",+ "Access-Control-Allow-Origin": "http://localhost","Access-Control-Allow-Methods": "GET, POST, OPTIONS","Access-Control-Allow-Headers": "Content-Type"};@@ -127,6 +234,17 @@ const server = serve({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+ }+ );+ }+if (url.pathname === "/notify" && req.method === "POST") {try {const data = await req.json();@@ -135,7 +253,12 @@ const server = serve({const voiceEnabled = data.voice_enabled !== false;const voiceId = data.voice_id || null;- console.log(`📨 Received notification: "${title}" - "${message}" (voice: ${voiceEnabled}, voiceId: ${voiceId}`);+ // Validate voice ID if provided+ if (voiceId && typeof voiceId !== 'string') {+ throw new Error('Invalid voice_id');+ }++ console.log(`📨 Received notification: "${title}" - "${message}" (voice: ${voiceEnabled}, voiceId: ${voiceId})`);await sendNotification(title, message, voiceEnabled, voiceId);@@ -146,12 +269,13 @@ const server = serve({status: 200});- } catch (error) {+ } catch (error: any) {+ console.error("Notification error:", error);return new Response(- JSON.stringify({ status: "error", message: error.message }),+ JSON.stringify({ status: "error", message: error.message || "Internal server error" }),{headers: { ...corsHeaders, "Content-Type": "application/json" },- status: 500+ status: error.message?.includes('Invalid') ? 400 : 500});}@@ -165,7 +289,7 @@ const server = serve({console.log(`🤖 PAI notification: "${title}" - "${message}"`);- await sendNotification(title, message, true);+ await sendNotification(title, message, true, null);return new Response(JSON.stringify({ status: "success", message: "PAI notification sent" }),@@ -174,12 +298,13 @@ const server = serve({status: 200});- } catch (error) {+ } catch (error: any) {+ console.error("PAI notification error:", error);return new Response(- JSON.stringify({ status: "error", message: error.message }),+ JSON.stringify({ status: "error", message: error.message || "Internal server error" }),{headers: { ...corsHeaders, "Content-Type": "application/json" },- status: 500+ status: error.message?.includes('Invalid') ? 400 : 500});}@@ -187,7 +312,7 @@ const server = serve({if (url.pathname === "/health") {return new Response(- JSON.stringify({ status: "healthy", port: PORT }),+ JSON.stringify({ status: "healthy", port: PORT, elevenlabs: !!ELEVENLABS_API_KEY }),{headers: { ...corsHeaders, "Content-Type": "application/json" },status: 200@@ -208,4 +333,5 @@ if (ELEVENLABS_API_KEY) {} else {console.log(`🎙️ Using macOS 'say' command (no ElevenLabs API key)`);}-console.log(`📡 POST to http://localhost:${PORT}/notify`);\ No newline at end of file+console.log(`📡 POST to http://localhost:${PORT}/notify`);+console.log(`🔒 Security: CORS restricted to localhost, rate limiting enabled`);\ No newline at end of filediff --git a/.claude/voice-server/start.sh b/.claude/voice-server/start.shindex 368e07cc..e245c2c4 100755--- a/.claude/voice-server/start.sh+++ b/.claude/voice-server/start.sh@@ -1,28 +1,51 @@#!/bin/bash-# PAIVoice Server Start Script+# Start the PAI Voice Server-# Load environment variables from ~/.env-if [ -f ~/.env ]; then- export $(grep -v '^#' ~/.env | xargs)-fi+SERVICE_NAME="com.pai.voice-server"+PLIST_PATH="$HOME/Library/LaunchAgents/${SERVICE_NAME}.plist"+SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"++# Colors+RED='\033[0;31m'+GREEN='\033[0;32m'+YELLOW='\033[1;33m'+NC='\033[0m'-# Set default port if not in .env-export PORT="${PORT:-8888}"+echo -e "${YELLOW}▶ Starting PAI Voice Server...${NC}"-# Kill any existing voice server processes-pkill -f "voice-server/server.ts" 2>/dev/null+# Check if LaunchAgent exists+if [ ! -f "$PLIST_PATH" ]; then+ echo -e "${RED}✗ Service not installed${NC}"+ echo " Run ./install.sh first to install the service"+ exit 1+fi-# Start the server-echo "🚀 Starting PAIVoice Server on port $PORT"-cd /Users/daniel/.claude/voice-server-bun run server.ts &+# Check if already running+if launchctl list | grep -q "$SERVICE_NAME" 2>/dev/null; then+ echo -e "${YELLOW}⚠ Voice server is already running${NC}"+ echo " To restart, use: ./restart.sh"+ exit 0+fi-echo "✅ Voice server started with PID $!"-echo "📡 Listening on http://localhost:$PORT"+# Load the service+launchctl load "$PLIST_PATH" 2>/dev/null-# Check if ElevenLabs API key is configured-if [ -z "$ELEVENLABS_API_KEY" ]; then- echo "⚠️ No ElevenLabs API key found - using macOS 'say' command"- echo " To enable ElevenLabs voices, add ELEVENLABS_API_KEY to ~/.env"+if [ $? -eq 0 ]; then+ # Wait for server to start+ sleep 2++ # Test if server is responding+ if curl -s -f -X GET http://localhost:8888/health > /dev/null 2>&1; then+ echo -e "${GREEN}✓ Voice server started successfully${NC}"+ echo " Port: 8888"+ echo " Test: curl -X POST http://localhost:8888/notify -H 'Content-Type: application/json' -d '{\"message\":\"Test\"}'"+ else+ echo -e "${YELLOW}⚠ Server started but not responding yet${NC}"+ echo " Check logs: tail -f ~/Library/Logs/pai-voice-server.log"+ fi+else+ echo -e "${RED}✗ Failed to start voice server${NC}"+ echo " Try running manually: bun run $SCRIPT_DIR/server.ts"+ exit 1fi\ No newline at end of filediff --git a/.claude/voice-server/status.sh b/.claude/voice-server/status.shnew file mode 100755index 00000000..154a9e20--- /dev/null+++ b/.claude/voice-server/status.sh@@ -0,0 +1,97 @@+#!/bin/bash++# Check status of PAI Voice Server++SERVICE_NAME="com.pai.voice-server"+PLIST_PATH="$HOME/Library/LaunchAgents/${SERVICE_NAME}.plist"+LOG_PATH="$HOME/Library/Logs/pai-voice-server.log"+ENV_FILE="$HOME/.env"++# Colors+RED='\033[0;31m'+GREEN='\033[0;32m'+YELLOW='\033[1;33m'+BLUE='\033[0;34m'+NC='\033[0m'++echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"+echo -e "${BLUE} PAI Voice Server Status${NC}"+echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"+echo++# Check LaunchAgent+echo -e "${BLUE}Service Status:${NC}"+if launchctl list | grep -q "$SERVICE_NAME" 2>/dev/null; then+ PID=$(launchctl list | grep "$SERVICE_NAME" | awk '{print $1}')+ if [ "$PID" != "-" ]; then+ echo -e " ${GREEN}✓ Service is loaded (PID: $PID)${NC}"+ else+ echo -e " ${YELLOW}⚠ Service is loaded but not running${NC}"+ fi+else+ echo -e " ${RED}✗ Service is not loaded${NC}"+fi++# Check if server is responding+echo+echo -e "${BLUE}Server Status:${NC}"+if curl -s -f -X GET http://localhost:8888/health > /dev/null 2>&1; then+ echo -e " ${GREEN}✓ Server is responding on port 8888${NC}"++ # Get health info+ HEALTH=$(curl -s http://localhost:8888/health)+ echo " Response: $HEALTH"+else+ echo -e " ${RED}✗ Server is not responding${NC}"+fi++# Check port binding+echo+echo -e "${BLUE}Port Status:${NC}"+if lsof -i :8888 > /dev/null 2>&1; then+ PROCESS=$(lsof -i :8888 | grep LISTEN | head -1)+ echo -e " ${GREEN}✓ Port 8888 is in use${NC}"+ echo " $PROCESS" | awk '{print " Process: " $1 " (PID: " $2 ")"}'+else+ echo -e " ${YELLOW}⚠ Port 8888 is not in use${NC}"+fi++# Check ElevenLabs configuration+echo+echo -e "${BLUE}Voice Configuration:${NC}"+if [ -f "$ENV_FILE" ] && grep -q "ELEVENLABS_API_KEY=" "$ENV_FILE"; then+ API_KEY=$(grep "ELEVENLABS_API_KEY=" "$ENV_FILE" | cut -d'=' -f2)+ if [ "$API_KEY" != "your_api_key_here" ] && [ -n "$API_KEY" ]; then+ echo -e " ${GREEN}✓ ElevenLabs API configured${NC}"+ if grep -q "ELEVENLABS_VOICE_ID=" "$ENV_FILE"; then+ VOICE_ID=$(grep "ELEVENLABS_VOICE_ID=" "$ENV_FILE" | cut -d'=' -f2)+ echo " Voice ID: $VOICE_ID"+ fi+ else+ echo -e " ${YELLOW}⚠ Using macOS 'say' (no API key)${NC}"+ fi+else+ echo -e " ${YELLOW}⚠ Using macOS 'say' (no configuration)${NC}"+fi++# Check logs+echo+echo -e "${BLUE}Recent Logs:${NC}"+if [ -f "$LOG_PATH" ]; then+ echo " Log file: $LOG_PATH"+ echo " Last 5 lines:"+ tail -5 "$LOG_PATH" | while IFS= read -r line; do+ echo " $line"+ done+else+ echo -e " ${YELLOW}⚠ No log file found${NC}"+fi++# Show commands+echo+echo -e "${BLUE}Available Commands:${NC}"+echo " • Start: ./start.sh"+echo " • Stop: ./stop.sh"+echo " • Restart: ./restart.sh"+echo " • Logs: tail -f $LOG_PATH"+echo " • Test: curl -X POST http://localhost:8888/notify -H 'Content-Type: application/json' -d '{\"message\":\"Test\"}'"\ No newline at end of filediff --git a/.claude/voice-server/stop.sh b/.claude/voice-server/stop.shnew file mode 100755index 00000000..8812a58f--- /dev/null+++ b/.claude/voice-server/stop.sh@@ -0,0 +1,36 @@+#!/bin/bash++# Stop the PAI Voice Server++SERVICE_NAME="com.pai.voice-server"+PLIST_PATH="$HOME/Library/LaunchAgents/${SERVICE_NAME}.plist"++# Colors+RED='\033[0;31m'+GREEN='\033[0;32m'+YELLOW='\033[1;33m'+NC='\033[0m'++echo -e "${YELLOW}▶ Stopping PAI Voice Server...${NC}"++# Check if service is loaded+if launchctl list | grep -q "$SERVICE_NAME" 2>/dev/null; then+ # Unload the service+ launchctl unload "$PLIST_PATH" 2>/dev/null++ if [ $? -eq 0 ]; then+ echo -e "${GREEN}✓ Voice server stopped successfully${NC}"+ else+ echo -e "${RED}✗ Failed to stop voice server${NC}"+ exit 1+ fi+else+ echo -e "${YELLOW}⚠ Voice server is not running${NC}"+fi++# Kill any remaining processes on port 8888+if lsof -i :8888 > /dev/null 2>&1; then+ echo -e "${YELLOW}▶ Cleaning up port 8888...${NC}"+ lsof -ti :8888 | xargs kill -9 2>/dev/null+ echo -e "${GREEN}✓ Port 8888 cleared${NC}"+fi\ No newline at end of filediff --git a/.claude/voice-server/uninstall.sh b/.claude/voice-server/uninstall.shnew file mode 100755index 00000000..5ceb9acf--- /dev/null+++ b/.claude/voice-server/uninstall.sh@@ -0,0 +1,83 @@+#!/bin/bash++# Uninstall PAI Voice Server++SERVICE_NAME="com.pai.voice-server"+PLIST_PATH="$HOME/Library/LaunchAgents/${SERVICE_NAME}.plist"+LOG_PATH="$HOME/Library/Logs/pai-voice-server.log"++# Colors+RED='\033[0;31m'+GREEN='\033[0;32m'+YELLOW='\033[1;33m'+BLUE='\033[0;34m'+NC='\033[0m'++echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"+echo -e "${BLUE} PAI Voice Server Uninstall${NC}"+echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"+echo++# Confirm uninstall+echo -e "${YELLOW}This will:${NC}"+echo " • Stop the voice server"+echo " • Remove the LaunchAgent"+echo " • Keep your server files and configuration"+echo+read -p "Are you sure you want to uninstall? (y/n): " -n 1 -r+echo+echo++if [[ ! $REPLY =~ ^[Yy]$ ]]; then+ echo "Uninstall cancelled"+ exit 0+fi++# Stop the service if running+echo -e "${YELLOW}▶ Stopping voice server...${NC}"+if launchctl list | grep -q "$SERVICE_NAME" 2>/dev/null; then+ launchctl unload "$PLIST_PATH" 2>/dev/null+ echo -e "${GREEN}✓ Voice server stopped${NC}"+else+ echo -e "${YELLOW} Service was not running${NC}"+fi++# Remove LaunchAgent plist+echo -e "${YELLOW}▶ Removing LaunchAgent...${NC}"+if [ -f "$PLIST_PATH" ]; then+ rm "$PLIST_PATH"+ echo -e "${GREEN}✓ LaunchAgent removed${NC}"+else+ echo -e "${YELLOW} LaunchAgent file not found${NC}"+fi++# Kill any remaining processes+if lsof -i :8888 > /dev/null 2>&1; then+ echo -e "${YELLOW}▶ Cleaning up port 8888...${NC}"+ lsof -ti :8888 | xargs kill -9 2>/dev/null+ echo -e "${GREEN}✓ Port 8888 cleared${NC}"+fi++# Ask about logs+echo+read -p "Do you want to remove log files? (y/n): " -n 1 -r+echo+if [[ $REPLY =~ ^[Yy]$ ]]; then+ if [ -f "$LOG_PATH" ]; then+ rm "$LOG_PATH"+ echo -e "${GREEN}✓ Log file removed${NC}"+ fi+fi++echo+echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"+echo -e "${GREEN} ✓ Uninstall Complete${NC}"+echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"+echo+echo -e "${BLUE}Notes:${NC}"+echo " • Your server files are still in: $(dirname "${BASH_SOURCE[0]}")"+echo " • Your ~/.env configuration is preserved"+echo " • To reinstall, run: ./install.sh"+echo+echo "To completely remove all files:"+echo " rm -rf $(dirname "${BASH_SOURCE[0]}")"\ No newline at end of file