# WP Agentic Writer - Local Backend Mode Feature Brief

## Overview

**Feature Name**: Local Backend Mode (Self-Hosted AI Proxy)

**Purpose**: Allow users to connect their WP Agentic Writer plugin to their own local Claude CLI (with Z.ai, OpenRouter, or official Anthropic) running on their development machine, enabling unlimited private AI content generation without external API costs or rate limits.

**Target Users**: 
- Developers with Claude CLI + Z.ai/Anthropic accounts
- Users with coding plans (Z.ai, OpenRouter BYOK)
- Privacy-conscious users wanting on-premise inference
- High-volume content creators avoiding API metering

---

## User Journey

### Current State (Remote APIs)
```
User → WP Admin → Agentic Writer → OpenRouter/Z.ai Cloud → $$ per token
```

### New State (Local Backend)
```
User's M1/PC: Claude CLI + Z.ai → Local Proxy (Port 8080)
                                        ↓
User → WP Admin (Live Site) → Agentic Writer → http://user-ip:8080 → FREE
```

### Complete Flow
1. User downloads "Agentic Writer Local Backend" package (ZIP)
2. Extracts on machine with Claude CLI already installed
3. Runs `./start-proxy.sh` → sees their local IP + config instructions
4. Opens WP Admin → Agentic Writer Settings → "Local Backend" tab
5. Enters: Base URL `http://192.168.1.105:8080`, API Key `dummy`
6. Clicks "Test Connection" → sees success message
7. Generates articles → content flows through their private backend → zero API costs

---

## Technical Architecture

### Components

#### 1. Local Proxy Package (Distributed ZIP)
**File**: `agentic-writer-local-backend.zip`

**Contents**:
```
agentic-writer-local-backend/
├── claude-proxy.js          # Node.js HTTP server (10 lines)
├── start-proxy.sh           # Launch script with IP detection
├── stop-proxy.sh            # Clean shutdown
├── test-connection.sh       # Verify proxy responds
├── get-local-ip.sh          # Helper to find machine IP
├── package.json             # Express dependency
├── README.md                # User setup guide
├── TROUBLESHOOTING.md       # Common issues + fixes
└── examples/
    └── plugin-config-screenshot.png
```

#### 2. Core Proxy Server (`claude-proxy.js`)
**Technology**: Node.js + Express
**Port**: 8080 (configurable)
**Dependencies**: `express` only

**Code**:
```javascript
const express = require('express');
const { spawn } = require('child_process');
const app = express();
app.use(express.json());

// Health check endpoint
app.get('/ping', (req, res) => res.send('pong'));

// Main inference endpoint
app.post('/v1/messages', async (req, res) => {
  const { messages } = req.body;
  const prompt = messages[messages.length - 1].content;
  
  console.log('Request from:', req.ip);
  console.log('Prompt:', prompt.substring(0, 100) + '...');
  
  const claude = spawn('claude', []);
  let output = '';
  
  claude.stdout.on('data', (data) => {
    output += data.toString();
    console.log('Claude response chunk:', data.toString().length, 'bytes');
  });
  
  claude.stderr.on('data', (data) => {
    console.error('Claude stderr:', data.toString());
  });
  
  claude.on('close', (code) => {
    console.log('Claude exit code:', code);
    res.json({
      id: 'local-' + Date.now(),
      object: 'chat.completion',
      created: Math.floor(Date.now() / 1000),
      model: 'claude-local',
      choices: [{
        index: 0,
        message: {
          role: 'assistant',
          content: output.trim() || 'No response from Claude'
        },
        finish_reason: 'stop'
      }]
    });
  });
  
  // Send prompt after brief pause (let Claude boot)
  setTimeout(() => {
    claude.stdin.write(prompt + '\n');
    claude.stdin.end();
  }, 500);
});

const PORT = process.env.PORT || 8080;
app.listen(PORT, '0.0.0.0', () => {
  console.log('═══════════════════════════════════════════════════');
  console.log('🚀 Agentic Writer Local Backend Started!');
  console.log('═══════════════════════════════════════════════════');
  console.log(`Local:   http://localhost:${PORT}`);
  console.log(`Network: http://YOUR-IP:${PORT}`);
  console.log('');
  console.log('Plugin Configuration:');
  console.log(`  Base URL: http://YOUR-IP:${PORT}`);
  console.log(`  API Key:  dummy`);
  console.log(`  Model:    glm-4-7 (or your Claude model)`);
  console.log('═══════════════════════════════════════════════════');
});
```

**Key Features**:
- Spawns user's local `claude` CLI for each request
- Captures stdout/stderr for debugging
- OpenAI-compatible `/v1/messages` endpoint
- Health check `/ping` for connection testing
- Logs all requests for transparency

#### 3. Startup Script (`start-proxy.sh`)
```bash
#!/bin/bash

echo "🚀 Starting Agentic Writer Local Backend..."
echo ""

# Check dependencies
if ! command -v node &> /dev/null; then
    echo "❌ Node.js not found. Install from https://nodejs.org/"
    exit 1
fi

if ! command -v claude &> /dev/null; then
    echo "❌ Claude CLI not found. Install and configure first."
    echo "   Check: https://claude.ai/code or https://z.ai"
    exit 1
fi

# Auto-install express if needed
if [ ! -d "node_modules" ]; then
    echo "📦 Installing dependencies..."
    npm install express
fi

# Detect local IP
if [[ "$OSTYPE" == "darwin"* ]]; then
    # macOS
    LOCAL_IP=$(ifconfig en0 | grep "inet " | awk '{print $2}')
elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
    # Linux
    LOCAL_IP=$(ip route get 1 | awk '{print $7;exit}')
else
    # Windows/other
    LOCAL_IP="YOUR-IP"
fi

echo "✅ Dependencies OK"
echo "✅ Claude CLI found"
echo ""
echo "Starting proxy server..."
echo ""

# Start server in background
nohup node claude-proxy.js > proxy.log 2>&1 &
PID=$!
echo $PID > proxy.pid

# Wait for server to boot
sleep 2

# Test if running
if kill -0 $PID 2>/dev/null; then
    echo "═══════════════════════════════════════════════════"
    echo "✅ Local Backend Running!"
    echo "═══════════════════════════════════════════════════"
    echo ""
    echo "Your Configuration:"
    echo "  Base URL: http://$LOCAL_IP:8080"
    echo "  API Key:  dummy"
    echo "  Model:    glm-4-7"
    echo ""
    echo "Next Steps:"
    echo "  1. Open your WordPress Admin"
    echo "  2. Go to Agentic Writer → Settings → Local Backend"
    echo "  3. Paste the Base URL above"
    echo "  4. Click 'Test Connection'"
    echo ""
    echo "Logs: tail -f proxy.log"
    echo "Stop:  ./stop-proxy.sh"
    echo "═══════════════════════════════════════════════════"
else
    echo "❌ Failed to start. Check proxy.log for errors."
    cat proxy.log
    exit 1
fi
```

#### 4. Stop Script (`stop-proxy.sh`)
```bash
#!/bin/bash

if [ -f proxy.pid ]; then
    PID=$(cat proxy.pid)
    if kill -0 $PID 2>/dev/null; then
        kill $PID
        rm proxy.pid
        echo "🛑 Local Backend stopped (PID: $PID)"
    else
        echo "⚠️  No process found with PID: $PID"
        rm proxy.pid
    fi
else
    # Fallback: kill by process name
    pkill -f claude-proxy.js
    echo "🛑 Stopped all claude-proxy processes"
fi
```

#### 5. Connection Test Script (`test-connection.sh`)
```bash
#!/bin/bash

echo "Testing local backend connection..."

RESPONSE=$(curl -s -X POST http://localhost:8080/v1/messages \
  -H "Content-Type: application/json" \
  -d '{"messages":[{"role":"user","content":"Reply with: Test successful"}]}')

if echo "$RESPONSE" | grep -q "Test successful"; then
    echo "✅ Local Backend working correctly!"
    echo "Response: $RESPONSE"
else
    echo "❌ Test failed. Response:"
    echo "$RESPONSE"
    echo ""
    echo "Troubleshooting:"
    echo "  1. Check proxy is running: ps aux | grep claude-proxy"
    echo "  2. Check logs: tail -f proxy.log"
    echo "  3. Verify Claude CLI: claude --version"
fi
```

---

## Plugin Integration (WordPress Side)

### 1. Settings Page - New "Local Backend" Tab

**Location**: WP Admin → Agentic Writer → Settings → Local Backend

**UI Elements**:

```php
// Add to plugin settings page
function render_local_backend_settings() {
    ?>
    <div class="wrap">
        <h2><?php _e('Local Backend Mode', 'wp-agentic-writer'); ?></h2>
        
        <!-- Download Section -->
        <div class="notice notice-info inline">
            <h3>📦 Step 1: Download Local Backend Package</h3>
            <p>Run AI inference on your own machine with your Claude CLI + Z.ai account.</p>
            <p>
                <a href="<?php echo plugins_url('downloads/agentic-writer-local-backend.zip', __FILE__); ?>" 
                   class="button button-primary" download>
                    Download Local Backend (v1.0.0)
                </a>
            </p>
            <details>
                <summary>Prerequisites</summary>
                <ul>
                    <li>✅ Claude CLI installed (<a href="https://claude.ai/code" target="_blank">Get Claude Code</a> or <a href="https://z.ai" target="_blank">Z.ai</a>)</li>
                    <li>✅ Node.js 18+ (<a href="https://nodejs.org" target="_blank">Download</a>)</li>
                    <li>✅ Z.ai Coding Plan or Anthropic API key configured in Claude CLI</li>
                </ul>
            </details>
        </div>
        
        <!-- Configuration Section -->
        <table class="form-table">
            <tr>
                <th scope="row">
                    <label for="local_backend_url"><?php _e('Base URL', 'wp-agentic-writer'); ?></label>
                </th>
                <td>
                    <input type="url" 
                           id="local_backend_url" 
                           name="agentic_writer_settings[local_backend_url]" 
                           value="<?php echo esc_attr(get_option('agentic_writer_local_backend_url', '')); ?>" 
                           class="regular-text" 
                           placeholder="http://192.168.1.105:8080">
                    <p class="description">
                        Enter the URL from your Local Backend startup message (e.g., http://YOUR-IP:8080)
                    </p>
                </td>
            </tr>
            <tr>
                <th scope="row">
                    <label for="local_backend_key"><?php _e('API Key', 'wp-agentic-writer'); ?></label>
                </th>
                <td>
                    <input type="text" 
                           id="local_backend_key" 
                           name="agentic_writer_settings[local_backend_key]" 
                           value="<?php echo esc_attr(get_option('agentic_writer_local_backend_key', 'dummy')); ?>" 
                           class="regular-text" 
                           placeholder="dummy">
                    <p class="description">
                        Use "dummy" for local backend (ignored by proxy)
                    </p>
                </td>
            </tr>
            <tr>
                <th scope="row">
                    <label for="local_backend_model"><?php _e('Model', 'wp-agentic-writer'); ?></label>
                </th>
                <td>
                    <input type="text" 
                           id="local_backend_model" 
                           name="agentic_writer_settings[local_backend_model]" 
                           value="<?php echo esc_attr(get_option('agentic_writer_local_backend_model', 'glm-4-7')); ?>" 
                           class="regular-text" 
                           placeholder="glm-4-7">
                    <p class="description">
                        Model identifier (informational only, proxy uses your Claude CLI default)
                    </p>
                </td>
            </tr>
        </table>
        
        <!-- Connection Test -->
        <p>
            <button type="button" id="test-local-backend" class="button">
                🔌 Test Connection
            </button>
            <span id="connection-status" style="margin-left: 10px;"></span>
        </p>
        
        <!-- Help Section -->
        <div class="notice notice-warning inline" style="margin-top: 20px;">
            <h4>🛠️ Troubleshooting</h4>
            <ul>
                <li><strong>Connection failed?</strong> Ensure proxy is running: <code>./start-proxy.sh</code></li>
                <li><strong>Wrong IP?</strong> Run <code>./get-local-ip.sh</code> to find correct address</li>
                <li><strong>Firewall blocking?</strong> Allow Node.js on port 8080 (System Preferences → Network → Firewall)</li>
                <li><strong>Claude not found?</strong> Check Claude CLI: <code>which claude</code> or <code>claude --version</code></li>
            </ul>
            <p><a href="https://docs.your-site.com/local-backend" target="_blank">Full Setup Guide →</a></p>
        </div>
    </div>
    
    <script>
    jQuery('#test-local-backend').on('click', function() {
        const btn = jQuery(this);
        const status = jQuery('#connection-status');
        const url = jQuery('#local_backend_url').val();
        
        if (!url) {
            status.html('⚠️ Enter Base URL first');
            return;
        }
        
        btn.prop('disabled', true).text('Testing...');
        status.html('⏳ Connecting...');
        
        jQuery.ajax({
            url: ajaxurl,
            method: 'POST',
            data: {
                action: 'test_local_backend',
                url: url,
                nonce: '<?php echo wp_create_nonce('test_local_backend'); ?>'
            },
            success: function(response) {
                if (response.success) {
                    status.html('✅ Connected! Ready to generate content.');
                    status.css('color', 'green');
                } else {
                    status.html('❌ Failed: ' + response.data.message);
                    status.css('color', 'red');
                }
            },
            error: function() {
                status.html('❌ Connection failed. Check URL and proxy status.');
                status.css('color', 'red');
            },
            complete: function() {
                btn.prop('disabled', false).text('🔌 Test Connection');
            }
        });
    });
    </script>
    <?php
}
```

### 2. AJAX Connection Test Handler

```php
// Add to plugin main file
add_action('wp_ajax_test_local_backend', 'test_local_backend_connection');

function test_local_backend_connection() {
    check_ajax_referer('test_local_backend', 'nonce');
    
    $url = sanitize_url($_POST['url']);
    
    // Test /ping endpoint
    $response = wp_remote_get($url . '/ping', [
        'timeout' => 5,
        'sslverify' => false  // Local network
    ]);
    
    if (is_wp_error($response)) {
        wp_send_json_error([
            'message' => 'Cannot reach proxy: ' . $response->get_error_message()
        ]);
    }
    
    $body = wp_remote_retrieve_body($response);
    
    if ($body === 'pong') {
        // Test actual inference
        $test_response = wp_remote_post($url . '/v1/messages', [
            'headers' => ['Content-Type' => 'application/json'],
            'body' => json_encode([
                'messages' => [
                    ['role' => 'user', 'content' => 'Reply with: Connection test successful']
                ]
            ]),
            'timeout' => 30
        ]);
        
        if (!is_wp_error($test_response)) {
            $result = json_decode(wp_remote_retrieve_body($test_response), true);
            if (isset($result['choices'][0]['message']['content'])) {
                wp_send_json_success([
                    'message' => 'Proxy responding correctly',
                    'sample' => $result['choices'][0]['message']['content']
                ]);
            }
        }
    }
    
    wp_send_json_error(['message' => 'Proxy not responding correctly']);
}
```

### 3. Provider Integration

**Add to existing provider system**:

```php
// In your provider factory/registry
class LocalBackendProvider extends BaseProvider {
    
    public function generate_content($prompt, $options = []) {
        $url = get_option('agentic_writer_local_backend_url');
        $api_key = get_option('agentic_writer_local_backend_key', 'dummy');
        
        if (empty($url)) {
            return new WP_Error('no_url', 'Local Backend URL not configured');
        }
        
        $response = wp_remote_post($url . '/v1/messages', [
            'headers' => [
                'Content-Type' => 'application/json',
                'Authorization' => 'Bearer ' . $api_key
            ],
            'body' => json_encode([
                'model' => get_option('agentic_writer_local_backend_model', 'glm-4-7'),
                'messages' => [
                    ['role' => 'user', 'content' => $prompt]
                ]
            ]),
            'timeout' => 120  // Long timeout for content generation
        ]);
        
        if (is_wp_error($response)) {
            return $response;
        }
        
        $body = json_decode(wp_remote_retrieve_body($response), true);
        
        if (isset($body['choices'][0]['message']['content'])) {
            return $body['choices'][0]['message']['content'];
        }
        
        return new WP_Error('invalid_response', 'Invalid response from local backend');
    }
    
    public function is_configured() {
        return !empty(get_option('agentic_writer_local_backend_url'));
    }
}

// Register provider
add_filter('agentic_writer_providers', function($providers) {
    $providers['local_backend'] = [
        'name' => 'Local Backend (Your Machine)',
        'class' => 'LocalBackendProvider',
        'icon' => '🖥️',
        'description' => 'Use your own Claude CLI + Z.ai for unlimited private generation'
    ];
    return $providers;
});
```

---

## User Documentation

### README.md (Included in ZIP)

```markdown
# Agentic Writer Local Backend

Run unlimited AI content generation on your own machine using your Claude CLI.

## Prerequisites

- ✅ Claude CLI installed and configured
  - Get it: https://claude.ai/code or https://z.ai
- ✅ Node.js 18+ installed
  - Download: https://nodejs.org
- ✅ Z.ai Coding Plan, OpenRouter, or Anthropic API key (configured in Claude CLI)

## Quick Start

### 1. Extract this package
```bash
unzip agentic-writer-local-backend.zip
cd agentic-writer-local-backend
```

### 2. Start the proxy
```bash
chmod +x start-proxy.sh
./start-proxy.sh
```

You'll see:
```
═══════════════════════════════════════════════════
✅ Local Backend Running!
═══════════════════════════════════════════════════

Your Configuration:
  Base URL: http://192.168.1.105:8080
  API Key:  dummy
  Model:    glm-4-7
```

### 3. Configure WordPress plugin

1. Open WP Admin → Agentic Writer → Settings → **Local Backend**
2. Paste the **Base URL** shown above
3. API Key: `dummy`
4. Click **Test Connection** → should show ✅
5. Start generating content!

## Commands

```bash
./start-proxy.sh       # Start proxy (runs in background)
./stop-proxy.sh        # Stop proxy
./test-connection.sh   # Test if proxy responds
tail -f proxy.log      # View real-time logs
```

## Firewall Setup

### macOS
System Settings → Network → Firewall → Options → Add `node` → Allow incoming

### Linux (ufw)
```bash
sudo ufw allow 8080/tcp
```

### Windows
Windows Defender Firewall → Advanced Settings → Inbound Rules → New Rule → Port 8080

## Troubleshooting

### "Connection failed" in plugin
- ✅ Check proxy is running: `ps aux | grep claude-proxy`
- ✅ Test manually: `./test-connection.sh`
- ✅ Check IP is correct: `./get-local-ip.sh`

### "Claude CLI not found"
```bash
# Verify Claude is installed
which claude
claude --version

# If not found, check installation:
# - macOS: /opt/homebrew/bin/claude
# - Linux: ~/.local/bin/claude
```

### "No response from Claude"
- ✅ Check Claude CLI works: `echo "Hello" | claude`
- ✅ Verify Z.ai/API key is configured: `claude --help` (shows auth status)
- ✅ Check logs: `tail -f proxy.log`

### Port 8080 already in use
```bash
# Find what's using port
lsof -i :8080

# Change port (edit claude-proxy.js)
PORT=9000 node claude-proxy.js
# Update plugin Base URL: http://your-ip:9000
```

## Security Notes

- Proxy binds to `0.0.0.0` (all interfaces) for LAN access
- No authentication by design (LAN trust model)
- For internet exposure, use ngrok/reverse proxy with auth
- Logs contain request prompts (for debugging)

## Support

- Full docs: https://docs.your-site.com/local-backend
- Issues: https://github.com/your/plugin/issues
- Discord: https://discord.gg/your-server
```

---

## Benefits & Use Cases

### Key Benefits

1. **Zero API Costs**: Use prepaid Z.ai Coding Plan or existing Anthropic sub
2. **Unlimited Generation**: No rate limits, no token counting
3. **Privacy**: Content never leaves your network
4. **Speed**: LAN latency << internet API calls
5. **Offline Ready**: Works without internet (if local WP)
6. **Model Flexibility**: Switch Claude models via CLI config

### Target Use Cases

| Use Case | Why Local Backend |
|----------|------------------|
| **High-volume content creation** | Avoid per-token costs, no rate limits |
| **Sensitive/NDA content** | Never hits external APIs |
| **Development/Testing** | Iterate rapidly without API spend |
| **Agency workflows** | One Z.ai account → unlimited client sites |
| **Offline scenarios** | Local WP + local AI = fully offline |

---

## Technical Considerations

### Performance

- **Latency**: ~50-200ms LAN vs ~500-2000ms internet API
- **Throughput**: Limited by Claude CLI speed (~20-30 tokens/sec on M1)
- **Concurrency**: One request at a time (spawn per request)
- **Scalability**: Single-user/dev-team, not multi-tenant SaaS

### Security

- **Network**: Runs on LAN, accessible to any device on network
- **Authentication**: None (trust LAN devices)
- **Logging**: All prompts logged to `proxy.log` (GDPR consideration)
- **Recommendation**: Firewall to specific IPs if multi-user network

### Limitations

- Requires Node.js on user machine (technical barrier)
- User must maintain Claude CLI (updates, auth refresh)
- No built-in retry/failover (single point of failure)
- Not suitable for public/shared hosting (security)

---

## Implementation Checklist

### Phase 1: Core Proxy (Week 1)
- [ ] Create `claude-proxy.js` with `/v1/messages` endpoint
- [ ] Add `/ping` health check
- [ ] Create `start-proxy.sh` with IP detection
- [ ] Create `stop-proxy.sh`
- [ ] Create `test-connection.sh`
- [ ] Write `README.md` with setup guide
- [ ] Package as `agentic-writer-local-backend.zip`

### Phase 2: Plugin Integration (Week 1)
- [ ] Add "Local Backend" settings tab
- [ ] Implement ZIP download from plugin settings
- [ ] Add Base URL / API Key / Model inputs
- [ ] Create AJAX "Test Connection" handler
- [ ] Add `LocalBackendProvider` class
- [ ] Register provider in provider factory
- [ ] Update main generation flow to support local backend

### Phase 3: Documentation (Week 2)
- [ ] Write full setup guide (with screenshots)
- [ ] Create video tutorial (5-min screencast)
- [ ] Add troubleshooting section to docs
- [ ] Create FAQ page
- [ ] Add to plugin welcome wizard

### Phase 4: Polish (Week 2)
- [ ] Auto-detect if proxy running (plugin UI indicator)
- [ ] Add "Start Proxy" button (launch via system command)
- [ ] Connection status widget (green/red indicator)
- [ ] Proxy version check (ensure compatibility)
- [ ] Error message improvements (actionable guidance)

### Phase 5: Advanced (Future)
- [ ] Multi-model support (detect available Claude models)
- [ ] Request queue (handle concurrent generation)
- [ ] WebSocket streaming (real-time output)
- [ ] Docker image option (one-click deployment)
- [ ] Windows .exe wrapper (no Node.js install needed)

---

## Success Metrics

### User Adoption
- **Target**: 15% of active users enable Local Backend within 3 months
- **Measure**: Track `local_backend_url` option set count

### Performance
- **Target**: <100ms LAN latency for content generation
- **Measure**: Log round-trip time in plugin

### Support
- **Target**: <5% support ticket rate for Local Backend setup
- **Measure**: Track "Local Backend" tagged tickets

### Cost Savings
- **Target**: 30% reduction in external API spend for heavy users
- **Measure**: Compare pre/post API usage in analytics

---

## Marketing Angle

### Positioning
**"Unlimited Private AI Content Generation"**

Run WP Agentic Writer with your own Claude CLI + Z.ai account. Zero per-token costs. Complete privacy. Unlimited throughput.

### Key Messages
- 🚀 **Unlimited**: No rate limits, no token counting, generate 24/7
- 🔒 **Private**: Your content never leaves your network
- 💰 **Free**: Use existing Z.ai/Anthropic subscription, no extra API costs
- ⚡ **Fast**: LAN speed beats internet API latency
- 🛠️ **Developer-Friendly**: Full control, local logs, easy debugging

### Competitive Advantage
No other WordPress AI plugin offers seamless local LLM integration with enterprise-grade models (Claude via Z.ai). Competitors force cloud API usage = ongoing costs + privacy concerns.

---

## Risk Assessment

| Risk | Impact | Mitigation |
|------|--------|------------|
| **Technical barrier** (Node.js install) | Medium | Provide video tutorial, one-click installers (future) |
| **Support burden** (networking issues) | Medium | Comprehensive troubleshooting docs, community Discord |
| **Security misconfiguration** | Low | Clear warnings in docs, bind to 127.0.0.1 by default option |
| **Claude CLI breaking changes** | Low | Version pinning, update notifications |
| **User expects 100% uptime** | Low | Docs clearly state "dev/team use, not production SaaS" |

---

## Future Enhancements

### V2 Features
1. **Auto-start on boot** (launchd/systemd/Task Scheduler)
2. **Multi-user support** (API key auth per WP site)
3. **Load balancing** (multiple Claude CLI instances)
4. **Model switching** (UI to select Claude Opus/Sonnet/Haiku)
5. **Monitoring dashboard** (requests/sec, uptime, error rate)

### V3 Features
1. **Docker image** (one-command deployment)
2. **GUI app** (macOS/Windows tray icon + config UI)
3. **Cloud sync** (fallback to OpenRouter if local offline)
4. **Team mode** (shared proxy for agency/team)
5. **Plugin marketplace** (middleware for image gen, RAG, etc.)

---

## Conclusion

**Local Backend Mode** positions WP Agentic Writer as the only WordPress AI plugin that gives users complete control over their inference stack. By leveraging users' existing Claude CLI + Z.ai setups, we unlock unlimited content generation without sacrificing quality or incurring per-token costs.

**Differentiator**: Privacy + Cost + Control in one feature.
**Target**: Developer-savvy users, agencies, high-volume creators.
**Effort**: 2 weeks MVP, ongoing maintenance minimal.

**Go/No-Go Decision**: ✅ GO
- Low implementation cost (10 lines Node.js + settings UI)
- High perceived value (unlimited AI = killer feature)
- Strong market differentiation (no competitor offers this)
- Aligns with dev-first positioning of plugin

---

## Appendix

### File Manifest (Deliverables)

```
WordPress Plugin Files:
├── includes/providers/class-local-backend-provider.php
├── admin/views/settings-local-backend.php
├── admin/js/test-local-backend.js
└── downloads/agentic-writer-local-backend.zip
    ├── claude-proxy.js
    ├── start-proxy.sh
    ├── stop-proxy.sh
    ├── test-connection.sh
    ├── get-local-ip.sh
    ├── package.json
    ├── README.md
    ├── TROUBLESHOOTING.md
    └── examples/
        └── plugin-config-screenshot.png
```

### Sample Error Messages

```php
// Connection errors with actionable guidance
$errors = [
    'timeout' => 'Connection timeout. Is the proxy running? Check with: ps aux | grep claude-proxy',
    'refused' => 'Connection refused. Ensure proxy started successfully: ./start-proxy.sh',
    'wrong_ip' => 'Cannot reach this IP. Run ./get-local-ip.sh to find correct address.',
    'no_claude' => 'Claude CLI not responding. Test manually: echo "test" | claude',
    'invalid_response' => 'Proxy returned invalid data. Check logs: tail -f proxy.log'
];
```

### Version History

- **v1.0.0** (Initial): Core proxy + plugin integration
- **v1.1.0** (Planned): Auto-start, connection monitoring
- **v2.0.0** (Future): Docker image, GUI app, team mode

---

**Document Version**: 1.0  
**Last Updated**: 2026-02-27  
**Author**: Implementation Brief for WP Agentic Writer  
**Status**: Ready for Development
