# OpenClaw Personal AI Assistant - Technology Context

## Overview

OpenClaw is an open-source personal AI assistant that runs locally with autonomous agent capabilities. Originally created as "Clawdbot" by Peter Steinberger, now community-maintained as OpenClaw.

**Deployment:** LXC 224 (10.10.0.224)
**Installation Method:** npm global installation (not Docker)
**Status:** Active
**Primary Use:** Personal automation, task management, Discord integration

## Architecture

### Deployment Model
**Installation:** OpenClaw installed globally via npm on LXC host (not containerized)
- Installed to: `/usr/lib/node_modules/openclaw/`
- Binary symlink: `/usr/bin/openclaw -> ../lib/node_modules/openclaw/openclaw.mjs`
- Service management: systemd user service (`openclaw-gateway.service`)
- Running as: `root` user (PID varies, check with `ps aux | grep openclaw-gateway`)

### Gateway-Centric Design
- **Gateway Daemon:** Single control plane for all operations
- **Messaging:** Handles chat platform integrations (Discord, Telegram, etc.)
- **Tool Execution:** Sandboxed code execution via nested Docker containers
- **Client Connections:** WebSocket and HTTP API for external integrations

### Key Components
1. **OpenClaw Gateway** - Node.js application, port 18789
2. **Docker-in-Docker Sandbox** - Isolated execution environment for skill code execution
3. **Persistent Workspace** - `~/.openclaw/` for configuration, agents, and memory
4. **Configuration Layer** - `~/.openclaw/openclaw.json` + environment variables

## System Users and Package Management

### User Accounts
- **root:** System administration, Docker operations, service management
- **openclaw:** Non-root user for Homebrew package management (UID 1000)
  - Member of `sudo` and `docker` groups
  - Password: `openclaw`
  - Home directory: `/home/openclaw`

### Homebrew Installation
OpenClaw skills often depend on system binaries distributed via Homebrew. Following OpenClaw's official recommendations, Homebrew is installed for the `openclaw` user.

**Location:** `/home/linuxbrew/.linuxbrew/`
**User:** `openclaw` (non-root, as required by Homebrew)

**Critical: Homebrew Wrapper for Root Access**

Since OpenClaw gateway runs as root but Homebrew refuses to run as root, we use a transparent wrapper:

- **Real brew binary:** `/home/linuxbrew/.linuxbrew/bin/brew.real`
- **Wrapper script:** `/home/linuxbrew/.linuxbrew/bin/brew`
- **Behavior:** When root runs `brew`, wrapper automatically delegates to `openclaw` user
- **Result:** OpenClaw can auto-install skill dependencies without "running as root" errors

**Usage Patterns:**

```bash
# OpenClaw auto-installs skill dependencies (uses wrapper automatically)
# No manual intervention needed when installing skills from web UI

# Manual installation as root (uses wrapper)
brew install <package>
brew list

# Manual installation as openclaw user (direct)
su - openclaw
brew install <package>
brew list

# Legacy helper script (still available)
brew-as-openclaw install <package>
```

**Helper Script:** `/usr/local/bin/brew-as-openclaw`
- Legacy wrapper script for explicit `openclaw` user delegation
- Still available but unnecessary due to transparent wrapper at brew binary location
- Usage: `brew-as-openclaw <command> [args]`

**PATH Configuration:**
- System-wide: `/etc/profile.d/homebrew.sh` adds Homebrew to PATH
- User-specific: `openclaw` user's `~/.bashrc` includes Homebrew shellenv
- Binaries available at `/home/linuxbrew/.linuxbrew/bin/`
- All users can access Homebrew-installed binaries

### Package Management Strategy
1. **System packages:** Install via `apt` as root (Docker, git, curl, etc.)
2. **Skill dependencies:** Install via Homebrew as `openclaw` user
3. **Node packages:** Install via `npm` within OpenClaw workspace

## AI Provider Integration

**Current Provider:** MiniMax M2.1
- **Model:** MiniMax-M2.1 (200K context window)
- **API Type:** Anthropic-compatible messages API
- **Endpoint:** https://api.minimax.io/anthropic
- **Authentication:** Bearer token via `MINIMAX_API_KEY`

**Model Selection:**
- Primary: `minimax/MiniMax-M2.1` (standard, balanced performance)
- Fast variant: `minimax/MiniMax-M2.1-lightning` (lower latency, lower cost)

**Pricing (per 1M tokens):**
- M2.1: $0.50 input / $1.50 output
- M2.1 Lightning: $0.30 input / $0.90 output

## Discord Integration

**Bot Configuration:**
- **Policy:** DM pairing (secure by default)
- **Intents Required:** Message Content + Server Members
- **Permissions:** View/Send/History + Embeds + Files + Reactions

**Access Control:**
- DMs: Pairing code required (1-hour expiry)
- Guild channels: Can be enabled per-server with allowlists
- Mention requirement: Optional gating for shared channels

**Message Handling:**
- History context: 20 messages (configurable)
- File uploads: 8MB max (configurable)
- Response format: Markdown with embeds

## Security Model

### Process Isolation
- **Gateway Process:** Runs as root user on LXC host (systemd service)
- **Skill Execution:** Code sandboxed in Docker containers spawned by gateway
- **Docker Access:** Gateway has access to Docker socket for skill sandboxing
- **Container Isolation:** Skills run in isolated containers, not on host

### Secrets Management
- **Storage:** `~/.openclaw/openclaw.json` (JSON5 format)
- **Environment Variables:** Can be referenced via `${VAR_NAME}` syntax
- **Credentials Directory:** `~/.openclaw/credentials/` for sensitive data
- **Permissions:** Files owned by root (gateway user)

### Network Security
- **Exposed Ports:** 18789 (gateway web UI) accessible on LXC network
- **Outbound:** Requires internet access for AI API calls (MiniMax, etc.)
- **LXC Network:** 10.10.0.224 on internal homelab network
- **Discord:** WebSocket connection to Discord API for bot integration

## Operational Patterns

### Standard Operations
```bash
# Start OpenClaw gateway
openclaw gateway start

# Stop OpenClaw gateway
openclaw gateway stop

# Restart gateway (picks up config changes)
openclaw gateway restart

# Check service status
systemctl --user status openclaw-gateway.service
ps aux | grep openclaw-gateway
```

### Viewing Logs
```bash
# Follow gateway logs
journalctl --user -u openclaw-gateway.service -f

# View recent logs
journalctl --user -u openclaw-gateway.service -n 100

# Check startup logs
journalctl --user -u openclaw-gateway.service --since "10 minutes ago"
```

### Pairing Management
```bash
# List pending pairing requests
openclaw pairing list discord

# Approve pairing
openclaw pairing approve discord <code>

# Revoke access
openclaw pairing revoke discord <user_id>
```

### Diagnostics
```bash
# Full system health check
openclaw doctor

# Channel status (Discord, etc.)
openclaw channels status --probe

# Model configuration
openclaw models list
openclaw models get minimax/MiniMax-M2.1

# Check which user is running gateway
ps aux | grep openclaw-gateway | grep -v grep
```

### Configuration Updates
```bash
# Edit configuration
nano ~/.openclaw/openclaw.json

# Restart to apply changes
openclaw gateway restart

# Verify changes via logs
journalctl --user -u openclaw-gateway.service -n 50 | grep -i "config\|error"

# Check if gateway is running
ps aux | grep openclaw-gateway | grep -v grep
```

### Skills Management

OpenClaw skills extend the assistant's capabilities with specialized tools and integrations.

**Skill Installation Methods:**

1. **ClawHub Registry** (recommended):
   ```bash
   # SSH to LXC as openclaw user
   ssh openclaw@10.10.0.224
   cd /opt/openclaw/workspace

   # Install specific skill
   clawhub install <skill-slug>

   # Sync all configured skills
   clawhub sync --all

   # Update existing skills
   clawhub update --all
   ```

2. **Manual Installation:**
   ```bash
   # Create skill directory
   mkdir -p /opt/openclaw/workspace/skills/<skill-name>

   # Create SKILL.md file
   nano /opt/openclaw/workspace/skills/<skill-name>/SKILL.md
   ```

**Skill Locations (priority order):**
1. `/opt/openclaw/workspace/skills/` (workspace skills, highest priority)
2. `~/.openclaw/skills/` (user skills, shared across agents)
3. Bundled skills (shipped with OpenClaw)

**Installing Skill Dependencies:**

Many skills require system binaries. Install dependencies using Homebrew:

```bash
# From root shell on LXC
brew-as-openclaw install jq          # JSON processing
brew-as-openclaw install ffmpeg      # Media processing
brew-as-openclaw install imagemagick # Image manipulation

# Or as openclaw user
su - openclaw
brew install <package-name>
```

**Enabling Skills:**

Configure in `openclaw.json`:
```json5
{
  "skills": {
    "entries": {
      "skill-name": {
        "enabled": true,
        "apiKey": "${SKILL_API_KEY}",  // If needed
        "env": {
          "CUSTOM_VAR": "value"
        }
      }
    }
  }
}
```

**Security Note:** Always review third-party skill code before enabling. Skills run with full OpenClaw privileges.

**Common Skills:**
- `browser` - Web automation via Playwright
- `shell` - Execute shell commands in sandbox
- `file-manager` - Advanced file operations
- `code-editor` - Code editing and refactoring
- `git` - Git repository operations

## Resource Usage Patterns

**Expected Baseline:**
- Idle: ~200MB RAM, <5% CPU
- Active chat: ~500MB RAM, 10-20% CPU
- Browser automation: ~1GB RAM, 30-50% CPU
- Concurrent operations: Up to 2GB RAM

**Disk Usage:**
- Application: ~500MB
- Workspace files: Variable (user-dependent)
- Logs: ~50MB/week (with rotation)
- Docker images: ~1GB

**Network:**
- AI API calls: ~10-100KB per request
- Discord: WebSocket connection (minimal bandwidth)
- File uploads: Up to 8MB per message

## Integration Points

### Current Integrations
- **Discord:** DM-based personal assistant
- **MiniMax API:** AI model provider
- **Docker:** Sandboxed execution environment

### Potential Future Integrations
- **n8n:** Workflow automation triggers (not currently configured)
- **Home Assistant:** Smart home control via API
- **Additional chat platforms:** Telegram, Signal, WhatsApp
- **Browser automation skills:** Web scraping, form filling

## Troubleshooting Quick Reference

| Issue | Solution |
|-------|----------|
| Gateway won't start | Check `docker compose logs` for errors; verify .env secrets |
| Discord not connecting | Verify `DISCORD_BOT_TOKEN` and intents enabled |
| "Used disallowed intents" error | Enable Message Content Intent in Discord portal |
| Pairing code not working | Check expiry (1 hour), regenerate if needed |
| High memory usage | Check for stuck browser automation processes |
| MiniMax API errors | Verify `MINIMAX_API_KEY`, check API quota |

## References

- **Official Docs:** https://docs.openclaw.ai/
- **GitHub:** https://github.com/openclaw/openclaw
- **Discord Setup:** https://docs.openclaw.ai/channels/discord
- **MiniMax Provider:** https://docs.openclaw.ai/providers/minimax
- **MiniMax Platform:** https://platform.minimax.io/

## Maintenance Notes

**Update Strategy:**
- Auto-updates: Gateway pulls `:latest` tag on restart
- Breaking changes: Check release notes before updating
- Rollback: Pin specific version tag if needed

**Backup Strategy:**
- Configuration: `openclaw.json` + `.env` (version controlled template)
- Workspace: `/opt/openclaw/workspace` (contains agent memory/files)
- Logs: Optional retention for debugging

**Monitoring:**
- Health check: HTTP endpoint at http://10.10.0.224:18789/health
- Discord connectivity: Verify bot status in server member list
- Resource usage: Monitor via Proxmox dashboard
