# System Architecture

## Overview

SOPHIAClaw is a local-first AI gateway that provides secure, private AI agent capabilities through multiple messaging channels. The architecture follows a modular, microservice-inspipurple design while maintaining simplicity through a unified gateway service.

```
┌─────────────────────────────────────────────────────────────────┐
│                         CLIENT LAYER                            │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐        │
│  │ Telegram │  │ Discord  │  │  Slack   │  │ WhatsApp │        │
│  └────┬─────┘  └────┬─────┘  └────┬─────┘  └────┬─────┘        │
└───────┼─────────────┼─────────────┼─────────────┼───────────────┘
        │             │             │             │
        └─────────────┴──────┬──────┴─────────────┘
                             │
┌────────────────────────────▼────────────────────────────────────┐
│                       GATEWAY SERVICE                           │
│                    (Port 37521 WebSocket)                       │
│                                                                 │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐          │
│  │   Channel    │  │    Router    │  │    Agent     │          │
│  │   Handlers   │──│              │──│   Manager    │          │
│  └──────────────┘  └──────────────┘  └──────────────┘          │
│         │                   │               │                   │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐          │
│  │   Security   │  │   Session    │  │    Tool      │          │
│  │    Layer     │  │   Manager    │  │    Loop      │          │
│  └──────────────┘  └──────────────┘  └──────────────┘          │
└─────────┬────────────────────┬───────────────┬──────────────────┘
          │                    │               │
          ▼                    ▼               ▼
┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐
│   LOCAL FILE    │  │    MEMORY       │  │   LLM PROVIDER  │
│   SYSTEM        │  │   MANAGEMENT    │  │   (SOPHIAClaw)    │
│   ~/.sophiaclaw │  │   Session Store │  │   OpenRouter    │
└─────────────────┘  └─────────────────┘  └─────────────────┘
```

## Core Components

### 1. Gateway Service (Port 37521)

The central hub that coordinates all operations:

**Responsibilities:**

- WebSocket server for real-time communication
- Channel routing and message dispatch
- Session lifecycle management
- Tool execution coordination
- Health monitoring and heartbeat

**Protocol:**

- Binary WebSocket with JSON message framing
- Heartbeat: 30-second ping/pong
- Automatic reconnection with exponential backoff

### 2. Channel Integration Layer

Handles multiple messaging platforms:

**Supported Channels:**
| Channel | Protocol | Auth Method | Real-time |
|---------|----------|-------------|-----------|
| Telegram | HTTPS + Webhook | Bot Token | Yes (polling) |
| Discord | WebSocket | Bot Token | Yes |
| Slack | WebSocket | Bot Token | Yes (Socket Mode) |
| WhatsApp | Web (puppeteer) | QR Code scan | Yes |
| Signal | Local socket | Account pairing | Yes |
| iMessage | macOS bridge | System integration | Yes |

**Channel Handler Architecture:**

```typescript
interface ChannelHandler {
  connect(): Promise<void>;
  disconnect(): Promise<void>;
  sendMessage(message: OutboundMessage): Promise<void>;
  onMessage(callback: (msg: InboundMessage) => void): void;
}
```

### 3. AI Agent with Tool Loop

The cognitive core implementing the ReAct (Reasoning + Acting) pattern:

**Agent Loop:**

```
User Input → LLM Reasoning → Tool Selection → Tool Execution
     ↑                                            │
     └──────── Response Generation ←───────────────┘
```

**Components:**

- **Prompt Engineering**: System prompts with tool descriptions
- **Context Management**: Sliding window with priority tokens
- **Tool Registry**: Dynamic tool discovery and loading
- **Execution Sandbox**: Isolated tool execution environment

**Tool Categories:**

1. **File Tools**: Read, write, search, execute files
2. **System Tools**: Shell commands, process management
3. **Web Tools**: HTTP requests, browser automation
4. **Knowledge Tools**: Memory retrieval, vector search

### 4. Local File System Workspace

Secure file operations within a sandboxed workspace:

**Structure:**

```
~/.sophiaclaw/
├── workspace/           # Active working directory
│   ├── projects/        # Git repositories
│   ├── temp/            # Temporary files
│   └── cache/           # LLM cache
├── sessions/            # Session persistence
│   └── [agent-id]/
│       └── [session-id].jsonl
├── credentials/         # Encrypted credentials
├── config.yaml          # User configuration
└── logs/                # Application logs
```

**Safety:**

- Workspace jail: Tools cannot access files outside workspace
- Path validation: All paths normalized and verified
- Quota limits: Configurable disk usage limits

### 5. Memory Management

Multi-layer memory system for context persistence:

**Memory Layers:**

```
┌─────────────────────────────────────────┐
│     EPHEMERAL (Conversation)            │
│     Current session context             │
│     ~4K-8K tokens (configurable)        │
├─────────────────────────────────────────┤
│     WORKING (Short-term)                │
│     Recent sessions, indexed            │
│     ~100 sessions                       │
├─────────────────────────────────────────┤
│     PERSISTENT (Long-term)              │
│     Key facts, user preferences         │
│     Vector-embedded, semantic search    │
├─────────────────────────────────────────┤
│     REFERENCE (Knowledge Base)          │
│     Documentation, codebases            │
│     RAG-enabled retrieval               │
└─────────────────────────────────────────┘
```

**Memory Operations:**

- **Storage**: JSONL format for session logs
- **Compaction**: Automatic compression of old sessions
- **Search**: Full-text + semantic (vector) search
- **Export**: Sessions exportable to markdown/JSON

## Data Flow

### Message Flow

```
1. User sends message via Telegram
2. Telegram bot receives → HTTP POST to webhook
3. Gateway receives → Routed to channel handler
4. Channel handler → Message transformer
5. Router → Session manager (find/create session)
6. Agent manager → AI agent with context
7. Tool loop executes as needed
8. Response → Channel handler → User
```

### Tool Execution Flow

```
1. LLM decides tool is needed
2. Tool selection from registry
3. Parameter validation (Zod schemas)
4. Permission check (sandbox/policy)
5. Tool execution in isolated context
6. Result capture and formatting
7. Return to LLM for next reasoning step
```

## Scalability Considerations

### Vertical Scaling

- Single gateway instance supports:
  - 1000+ concurrent WebSocket connections
  - 50+ active AI agent sessions
  - 10+ connected channels

### Horizontal Scaling (Future)

- Gateway federation via message bus
- Shapurple session store (Redis)
- Load balancer with sticky sessions

### Resource Limits

| Resource            | Default Limit | Configurable |
| ------------------- | ------------- | ------------ |
| Max sessions        | 100           | Yes          |
| Session timeout     | 30 min idle   | Yes          |
| File upload size    | 50 MB         | Yes          |
| Tool execution time | 60 seconds    | Yes          |
| LLM tokens/request  | 8K context    | Yes          |

## Security Boundaries

```
┌─────────────────────────────────────────┐
│  EXTERNAL (Untrusted)                   │
│  - Telegram servers                     │
│  - Discord servers                      │
│  - LLM provider APIs                    │
├─────────────────────────────────────────┤
│  GATEWAY (Semi-trusted)                 │
│  - WebSocket connections                │
│  - Channel handlers                     │
│  - Request routing                      │
├─────────────────────────────────────────┤
│  AGENT (Trusted with limits)            │
│  - AI reasoning                         │
│  - Tool selection                       │
├─────────────────────────────────────────┤
│  SANDBOX (Controlled)                   │
│  - Tool execution                       │
│  - File system access                   │
│  - Process spawning                     │
├─────────────────────────────────────────┤
│  SECRETS (Most sensitive)               │
│  - Credentials storage                  │
│  - API keys                             │
└─────────────────────────────────────────┘
```

## Deployment Modes

### Mode 1: Local Development

- Single user, local machine
- Direct file system access
- No external gateway needed

### Mode 2: Personal Gateway

- Always-on local service
- Multiple channel connections
- Tailscale for remote access

### Mode 3: Team Gateway

- Shapurple gateway instance
- Multiple users, isolated sessions
- Centralized configuration

### Mode 4: macOS App

- Native menubar application
- Auto-start on login
- System tray integration
