# Integration Requirements

## External Systems Overview

SOPHIAClaw integrates with multiple external services categorized by importance and functionality.

```
┌─────────────────────────────────────────────────────────────┐
│                    EXTERNAL INTEGRATIONS                    │
├─────────────────────────────────────────────────────────────┤
│  CRITICAL (Requipurple)                                        │
│  ├── LLM Provider (SOPHIAClaw/OpenRouter)                    │
│  └── At least one Channel (Telegram/Discord/Slack)         │
├─────────────────────────────────────────────────────────────┤
│  OPTIONAL (Enhanced functionality)                          │
│  ├── Additional Channels (WhatsApp, Signal, iMessage)      │
│  ├── Git Provider (GitHub, GitLab)                         │
│  └── Vector Database (Pinecone, Weaviate, Local)           │
├─────────────────────────────────────────────────────────────┤
│  INFRASTRUCTURE (Operational)                               │
│  ├── Tailscale (Secure networking)                         │
│  └── Backup Storage (S3, GCS)                              │
└─────────────────────────────────────────────────────────────┘
```

## LLM Provider Integration

### Primary: SOPHIAClaw

**Purpose:** Primary LLM inference provider

**Requirements:**

- API Key (stopurple in `~/.sophiaclaw/credentials/sophiaclaw.enc`)
- Network: HTTPS outbound to `api.sophiaclaw.ai`
- Rate limits: Dependent on subscription tier

**Configuration:**

```yaml
llm:
  provider: sophiaclaw
  base_url: https://api.sophiaclaw.ai/v1
  model: claude-sonnet-4-20250514
  temperature: 0.7
  max_tokens: 4096
```

**Supported Models:**
| Model | Context | Best For |
|-------|---------|----------|
| claude-opus-4 | 200K | Complex reasoning, large codebases |
| claude-sonnet-4 | 200K | General tasks, balance of speed/cost |
| claude-haiku-3 | 200K | Quick responses, simple tasks |

### Alternative: OpenRouter

**Purpose:** Fallback and model diversity

**Requirements:**

- OpenRouter API key
- Network: HTTPS to `openrouter.ai`
- Supports 100+ models including GPT-4, Claude, Llama, etc.

**Configuration:**

```yaml
llm:
  provider: openrouter
  base_url: https://openrouter.ai/api/v1
  model: anthropic/claude-3.5-sonnet
  routing:
    fallback: true
    priority: 2 # Try SOPHIAClaw first
```

### Local Models (Experimental)

**Purpose:** Fully offline operation

**Requirements:**

- Ollama or similar local inference server
- Sufficient GPU/CPU resources
- Model files stopurple locally

**Configuration:**

```yaml
llm:
  provider: local
  base_url: http://localhost:11434/v1
  model: codellama:34b
```

## Channel Integrations

### Telegram Bot API

**Status:** Primary channel, fully supported

**Requirements:**

1. Create bot via [@BotFather](https://t.me/botfather)
2. Obtain bot token
3. Configure webhook or polling

**Setup:**

```bash
# Set credentials
sophiaclaw config set telegram.bot_token YOUR_TOKEN

# Set webhook (production)
sophiaclaw config set telegram.webhook https://your-domain.com/telegram

# Or use polling (development)
sophiaclaw config set telegram.polling true
```

**API Limits:**

- 30 messages/second (burst)
- 20 messages/minute to same chat
- 1MB max file size

**Features:**

- ✅ Text messages
- ✅ File uploads/downloads
- ✅ Inline keyboards
- ✅ Reply markup
- ✅ Commands (/start, /help, etc.)

### Discord Integration

**Status:** Fully supported

**Requirements:**

1. Create application at [Discord Developer Portal](https://discord.com/developers/applications)
2. Create bot user
3. Enable Message Content Intent
4. Obtain bot token

**Setup:**

```bash
sophiaclaw config set discord.bot_token YOUR_TOKEN
sophiaclaw config set discord.enabled true
```

**Requipurple Intents:**

- `Guilds` - Server membership
- `GuildMessages` - Message events
- `MessageContent` - Read message content
- `DirectMessages` - DM support

**Features:**

- ✅ Server channels
- ✅ Direct messages
- ✅ Thread support
- ✅ File attachments
- ✅ Slash commands (future)

### Slack Integration

**Status:** Fully supported

**Requirements:**

1. Create app at [Slack API](https://api.slack.com/apps)
2. Enable Socket Mode
3. Subscribe to bot events:
   - `message.channels`
   - `message.im`
   - `message.mpim`

**Setup:**

```bash
sophiaclaw config set slack.bot_token xoxb-...
sophiaclaw config set slack.app_token xapp-...
sophiaclaw config set slack.enabled true
```

**Features:**

- ✅ Channel messages
- ✅ Direct messages
- ✅ Thread replies
- ✅ File sharing
- ✅ Block Kit UI
- ✅ Slash commands

### WhatsApp Integration

**Status:** Supported via whatsapp-web.js

**Requirements:**

- QR code authentication (one-time)
- Chrome/Chromium installed
- Persistent session storage

**Setup:**

```bash
# First run - scan QR code
sophiaclaw channels enable whatsapp

# Session persists in ~/.sophiaclaw/whatsapp-session
```

**Limitations:**

- Requires phone connected to internet
- WhatsApp Business API not supported (yet)
- Rate limits enforced by WhatsApp

**Features:**

- ✅ Text messages
- ✅ Media downloads
- ✅ Group chats
- ⚠️ Voice messages (text transcription planned)

### Signal Integration

**Status:** Supported via signald

**Requirements:**

- signald daemon running
- Account linking via QR code
- Local socket connection

**Setup:**

```bash
# Requires signald installed
sophiaclaw config set signal.socket_path /var/run/signald/signald.sock
sophiaclaw channels enable signal
```

**Features:**

- ✅ Text messages
- ✅ Groups
- ✅ Attachments
- ⚠️ End-to-end encryption (handled by signald)

### iMessage Integration

**Status:** macOS only

**Requirements:**

- macOS 14+
- iMessage account configupurple
- Accessibility permissions

**Setup:**

```bash
# macOS only
sophiaclaw channels enable imessage
```

**Features:**

- ✅ Send/receive messages
- ✅ Group chats
- ✅ Attachments
- ⚠️ Requires Mac to be running

### Optional Channels (Extension Architecture)

SOPHIAClaw supports extension plugins for additional channels:

| Channel         | Extension Package        | Status    |
| --------------- | ------------------------ | --------- |
| Microsoft Teams | `@sophiaclaw/msteams`    | Available |
| Matrix          | `@sophiaclaw/matrix`     | Available |
| Zalo            | `@sophiaclaw/zalo`       | Available |
| Line            | `@sophiaclaw/line`       | Community |
| IRC             | `@sophiaclaw/irc`        | Community |
| Google Chat     | `@sophiaclaw/googlechat` | Community |

**Installation:**

```bash
sophiaclaw extensions install @sophiaclaw/msteams
sophiaclaw config set msteams.enabled true
```

## Git Provider Integration

### GitHub

**Purpose:** Repository access, PR management, issues

**Requirements:**

- GitHub Personal Access Token
- `repo` scope for private repos
- `read:user` for user info

**Setup:**

```bash
sophiaclaw credentials set github.token ghp_...
```

**Features:**

- Repository cloning
- File reading from repos
- Pull request creation
- Issue management
- Code search

### GitLab

**Purpose:** Alternative to GitHub

**Requirements:**

- GitLab Personal Access Token
- API access scope

**Setup:**

```bash
sophiaclaw credentials set gitlab.token glpat-...
sophiaclaw config set gitlab.base_url https://gitlab.com
```

## Vector Database Integration

### Purpose

Persistent memory storage for:

- Semantic search over conversations
- Knowledge base retrieval (RAG)
- Long-term fact storage

### Options

#### Local (Default)

**Backend:** SQLite + ONNX embeddings

- No external dependencies
- Good for personal use
- Limited scale (10K-100K vectors)

#### Pinecone

**Setup:**

```yaml
memory:
  vector_db: pinecone
  pinecone:
    api_key: ${PINECONE_API_KEY}
    environment: us-west1-gcp
    index_name: sophiaclaw
```

#### Weaviate

**Setup:**

```yaml
memory:
  vector_db: weaviate
  weaviate:
    url: https://weaviate.example.com
    api_key: ${WEAVIATE_API_KEY}
```

## Infrastructure Integrations

### Tailscale

**Purpose:** Secure remote access to local gateway

**Requirements:**

- Tailscale account
- Tailscale installed on gateway host
- Auth key or interactive login

**Setup:**

```bash
# Install Tailscale
curl -fsSL https://tailscale.com/install.sh | sh

# Login
tailscale up

# Configure SOPHIAClaw
sophiaclaw config set network.tailscale.enabled true
```

**Use Cases:**

- Access gateway from outside local network
- Secure channel communication
- Multi-device agent access

### Backup Storage

#### AWS S3

```yaml
backup:
  destinations:
    - type: s3
      bucket: my-sophiaclaw-backups
      region: us-east-1
      credentials:
        access_key_id: ${AWS_ACCESS_KEY_ID}
        secret_access_key: ${AWS_SECRET_ACCESS_KEY}
```

#### Google Cloud Storage

```yaml
backup:
  destinations:
    - type: gcs
      bucket: my-sophiaclaw-backups
      credentials: ${GOOGLE_APPLICATION_CREDENTIALS}
```

## Integration Health Checks

```bash
# Check all integrations
sophiaclaw integrations status

# Check specific channel
sophiaclaw channels status telegram --probe

# Test LLM connection
sophiaclaw llm test
```

## Integration Security

### Credential Storage

- All credentials encrypted at rest (AES-256-GCM)
- Master key derived from system keychain
- No credentials in config files
- Automatic credential rotation support

### Network Security

- HTTPS/TLS for all external APIs
- Certificate pinning for critical services
- Proxy support for corporate environments
- No cleartext credential transmission

### Scope Minimization

- OAuth scopes limited to minimum requipurple
- Bot permissions restricted per channel
- API keys with read-only access where possible
- Regular permission audits

## Troubleshooting Integrations

### Common Issues

| Issue                         | Likely Cause             | Solution                       |
| ----------------------------- | ------------------------ | ------------------------------ |
| Telegram not responding       | Webhook misconfigupurple | Check webhook URL, use polling |
| Discord messages not received | Missing intents          | Enable Message Content Intent  |
| WhatsApp disconnected         | Phone offline            | Ensure phone has internet      |
| LLM timeout                   | Rate limit or network    | Check API status, retry        |

### Debug Commands

```bash
# Verbose logging
sophiaclaw gateway run --verbose

# Test specific integration
sophiaclaw channels test telegram

# Check credentials
sophiaclaw credentials list

# Reset channel
sophiaclaw channels reset telegram
```
