# OpenAI & LLM Provider Setup Guide

Complete guide to configuring Kollabor CLI with OpenAI, Anthropic, Azure OpenAI, and custom LLM providers.

**Table of Contents**
- [Quick Start](#quick-start)
- [Configuration Basics](#configuration-basics)
- [4-Tier Keyring System](#4-tier-keyring-system)
- [Provider Setup](#provider-setup)
- [Environment Variables](#environment-variables)
- [Migration Guide](#migration-guide)
- [Troubleshooting](#troubleshooting)
- [Enterprise Deployment](#enterprise-deployment)

---

## Quick Start

Get started in 5 minutes with OpenAI:

### 1. Install Dependencies

```bash
# Install with OpenAI SDK support
pip install kollabor[openai]

# Or install keyring for secure storage (recommended)
pip install kollabor[openai,keyring]
```

### 2. Set Your API Key

**Option A: Environment Variable (Quickest)**

```bash
# Set OpenAI API key
export OPENAI_API_KEY="sk-..."

# Run Kollabor
kollab
```

**Option B: OS Keyring (Secure - Recommended)**

```bash
# Use the /profile command to store securely
kollab
> /profile set openai

# Follow prompts to enter your API key
# It will be stored in your OS keyring (macOS Keychain, Windows Credential Manager, etc.)
```

### 3. Start Chatting

```bash
kollab
> Hello, can you help me write Python code?
```

That's it! Kollabor is now configured and ready to use.

---

## Configuration Basics

Kollabor uses **profiles** to manage LLM configurations. Each profile defines:
- API endpoint URL
- Model name
- Temperature and other parameters
- Tool calling format
- API token

### Built-in Profiles

Kollabor includes these default profiles:

| Profile | Description | Endpoint | Model |
|---------|-------------|----------|-------|
| `default` | Local LLM for general use | localhost:1234 | qwen/qwen3-4b |
| `fast` | Fast local model for quick queries | localhost:1234 | qwen/qwen3-0.6b |
| `claude` | Anthropic Claude for complex tasks | api.anthropic.com | claude-sonnet-4-20250514 |
| `openai` | OpenAI GPT-4 for general tasks | api.openai.com | gpt-4-turbo |

### Profile Configuration

Profiles are stored in `~/.kollabor-cli/config.json`:

```json
{
  "core": {
    "llm": {
      "default_profile": "openai",
      "active_profile": "openai",
      "profiles": {
        "openai": {
          "api_url": "https://api.openai.com",
          "model": "gpt-4-turbo",
          "temperature": 0.7,
          "max_tokens": 4096,
          "tool_format": "openai",
          "native_tool_calling": true,
          "description": "OpenAI GPT-4 for general tasks"
        }
      }
    }
  }
}
```

### Managing Profiles

Use the `/profile` command (also available as `/prof` or `/llm`):

```bash
# List all profiles
/profile list

# Switch to a profile
/profile set claude

# Create a new profile
/profile create

# Delete a profile
/profile delete my-profile
```

---

## 4-Tier Keyring System

Kollabor uses a **4-tier fallback system** for secure API key storage. This ensures the application works in all environments, from personal laptops to enterprise Docker containers.

### Tier Priority

Keys are loaded in this order (higher priority first):

1. **Environment Variables** - Highest priority, overrides all
2. **OS Keyring** - Secure, recommended for daily use
3. **Encrypted File** - Secure fallback for headless environments
4. **Plaintext** - Development only (requires opt-in)

### Tier 1: OS Native Keyring (Secure - Recommended)

**Platforms:**
- **macOS**: Keychain Access
- **Windows**: Credential Manager (DPAPI)
- **Linux**: Secret Service (Gnome Keyring, KWallet)

**Setup:**

```bash
# Install keyring support
pip install keyring

# On Linux, install backend
sudo apt-get install gnome-keyring  # Ubuntu/Debian
# or
sudo apt-get install kwalletmanager  # KDE

# Store key using Kollabor
kollab
> /profile set openai
> Enter API key: sk-...

# Key is now stored in OS keyring
```

**Verification:**

```bash
# Verify keyring is working
python -c "import keyring; print(keyring.get_keyring())"

# Should show:
# macOS: keyring.backends.macOS.Keyring
# Windows: keyring.backends.Windows.WinVaultKeyring
# Linux: keyring.backends.SecretService.Keyring
```

**Platform-Specific Instructions:**

#### macOS Keychain

```bash
# Keyring works automatically with macOS Keychain
# No setup required

# View stored keys
open /Applications/Utilities/Keychain\ Access.app
# Search for "kollabor-cli"

# Delete a key
# Find "kollabor-cli" in Keychain Access and delete
```

#### Windows Credential Manager

```bash
# Keyring works automatically with Windows Credential Manager
# No setup required

# View stored keys
cmdkey /list | findstr kollabor

# Delete a key
cmdkey /delete:LegacyGeneric:target=kollabor-cli
```

#### Linux Secret Service

```bash
# Ubuntu/Debian
sudo apt-get install gnome-keyring
sudo apt-get install libsecret-1-0  # Required library

# Verify dbus session is running (required for Secret Service)
echo $DBUS_SESSION_BUS_ADDRESS

# If empty, start gnome-keyring daemon
gnome-keyring-daemon --start

# For KDE/KWallet
sudo apt-get install kwalletmanager
```

**Troubleshooting Keyring:**

```bash
# Issue: "No keyring backend found"
# Solution: Install keyring package
pip install keyring

# Issue: "DBus connection not available" (Linux)
# Solution: Ensure dbus session is running
eval $(dbus-launch --sh-syntax)

# Issue: "Keyring is locked" (Linux)
# Solution: Unlock keyring
gnome-keyring-daemon --unlock
```

### Tier 2: Encrypted File Storage (Secure - Fallback)

**Use Cases:**
- Docker containers (minimal base images)
- CI/CD environments (headless)
- Kubernetes pods
- Air-gapped systems

**Setup:**

```bash
# Install cryptography library
pip install cryptography

# Set encryption password via environment variable
export KOLLABOR_KEY_ENCRYPTION_PASSWORD="your-secure-password"

# Or store key in encrypted file
kollab
> /profile set openai
> Enter API key: sk-...
> Key stored in encrypted file: ~/.kollabor-cli/keys.encrypted
```

**Encryption Details:**
- **Algorithm**: AES-256-GCM (authenticated encryption)
- **Key Derivation**: PBKDF2-HMAC-SHA256 (100,000 iterations)
- **File Location**: `~/.kollabor-cli/keys.encrypted`
- **File Permissions**: 0600 (owner read/write only)

**Manual Encryption (Advanced):**

```python
import asyncio
from pathlib import Path
from kollabor.llm.providers.security import EncryptedFileKeyStorage

async def store_key():
    storage = EncryptedFileKeyStorage(
        storage_path=Path.home() / ".kollabor-cli" / "keys.encrypted",
        password=os.environ.get("KOLLABOR_KEY_ENCRYPTION_PASSWORD")
    )
    await storage.store_key("openai", "sk-...")
    print("Key encrypted and stored")

asyncio.run(store_key())
```

**Docker Example:**

```dockerfile
FROM python:3.12-slim

# Install dependencies
RUN pip install kollabor[cryptography]

# Set encryption password at runtime
ENV KOLLABOR_KEY_ENCRYPTION_PASSWORD=""

# Volume for encrypted keys
VOLUME ["/root/.kollabor-cli"]

# Store key on first run
CMD ["sh", "-c", "kollab"]
```

```bash
# Run container with encryption password
docker run -it \
  -e KOLLABOR_KEY_ENCRYPTION_PASSWORD="my-secure-password" \
  -v kollabor-data:/root/.kollabor-cli \
  kollabor-cli
```

### Tier 3: Environment Variables (Development/CI)

**Use Cases:**
- CI/CD pipelines
- Development environments
- Temporary testing
- Quick prototyping

**Supported Environment Variables:**

```bash
# OpenAI
export OPENAI_API_KEY="sk-..."

# Anthropic
export ANTHROPIC_API_KEY="sk-ant-..."

# Azure OpenAI
export AZURE_OPENAI_API_KEY="..."

# Custom profile (profile name normalized)
export KOLLABOR_MY_PROFILE_TOKEN="..."
export KOLLABOR_MY_PROFILE_ENDPOINT="https://..."
export KOLLABOR_MY_PROFILE_MODEL="gpt-4"
```

**CI/CD Example (GitHub Actions):**

```yaml
name: Test Kollabor
on: [push]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-python@v4
        with:
          python-version: '3.12'
      - run: pip install kollabor[openai]
      - name: Run Kollabor
        env:
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
        run: |
          echo "Explain async/await" | kollab -p
```

**Limitations:**
- Keys are NOT persisted (must be set each session)
- Not secure for production (visible in process list)
- Intended for CI/CD and development only

### Tier 4: Plaintext Storage (Development Only)

**WARNING**: This is **INSECURE** and should ONLY be used for local development.

**Setup (Explicit Opt-In Required):**

```bash
# Enable plaintext storage (NOT RECOMMENDED)
export KOLLABOR_ALLOW_PLAINTEXT_KEYS="true"

# Store key in plaintext
kollab
> /profile set openai
> Enter API key: sk-...
> WARNING: Key stored in PLAINTEXT at ~/.kollabor-cli/keys.json
```

**Security Warning:**

When you enable plaintext storage, Kollabor will display this warning:

```
======================================================================
WARNING: PLAINTEXT KEY STORAGE ENABLED
API keys are stored WITHOUT encryption.
This is INSECURE and should ONLY be used for development.
NEVER use in production or commit to version control.
======================================================================
```

**Best Practices:**
- NEVER commit `keys.json` to version control
- Add `keys.json` to `.gitignore`
- Only use on isolated development machines
- Migrate to encrypted storage before deploying

### Automatic Migration

Kollabor **automatically migrates** plaintext keys from config to secure storage:

```json
// Old config.json (INSECURE)
{
  "core": {
    "llm": {
      "profiles": {
        "openai": {
          "api_url": "https://api.openai.com",
          "api_token": "sk-..."  // Plaintext key in config
        }
      }
    }
  }
}
```

When Kollabor detects a plaintext key in config:
1. Reads the key from config
2. Logs migration warning
3. Stores key in OS keyring or encrypted file
4. Removes key from config
5. Saves updated config

---

## Provider Setup

### OpenAI

**Step 1: Get API Key**

1. Visit https://platform.openai.com/api-keys
2. Sign in or create account
3. Click "Create new secret key"
4. Copy key (starts with `sk-`)

**Step 2: Configure Profile**

```bash
# Option A: Use built-in profile
kollab
> /profile set openai
> Enter API key: sk-...

# Option B: Use environment variable
export OPENAI_API_KEY="sk-..."
kollab

# Option C: Create custom profile
kollab
> /profile create
> Profile name: gpt4
> API URL: https://api.openai.com
> Model: gpt-4
> API Key: sk-...
> Temperature (0.7):
> Max Tokens (4096):
```

**Recommended Models:**

| Model | Use Case | Context | Cost |
|-------|----------|---------|------|
| `gpt-4-turbo` | General tasks | 128K | $$$ |
| `gpt-4o` | Latest GPT-4 | 128K | $$$$ |
| `gpt-4o-mini` | Fast/cheap | 128K | $ |
| `o1-preview` | Complex reasoning | 128K | $$$$ |

**Configuration Examples:**

```json
{
  "core": {
    "llm": {
      "profiles": {
        "gpt4-turbo": {
          "api_url": "https://api.openai.com",
          "model": "gpt-4-turbo",
          "temperature": 0.7,
          "max_tokens": 4096,
          "description": "GPT-4 Turbo for general use"
        },
        "gpt4-coding": {
          "api_url": "https://api.openai.com",
          "model": "gpt-4-turbo",
          "temperature": 0.2,
          "max_tokens": 8192,
          "description": "Low temperature for code generation"
        },
        "gpt4-creative": {
          "api_url": "https://api.openai.com",
          "model": "gpt-4-turbo",
          "temperature": 1.0,
          "max_tokens": 4096,
          "description": "High temperature for creative writing"
        }
      }
    }
  }
}
```

**Custom Base URL (Azure OpenAI, Proxies):**

```bash
# Using Azure OpenAI
/profile create
> Profile name: azure-openai
> API URL: https://my-resource.openai.azure.com
> Model: gpt-4
> API Key: ...

# Using OpenAI-compatible proxy
/profile create
> Profile name: openai-proxy
> API URL: https://my-proxy.com/v1
> Model: gpt-4
> API Key: ...
```

### Anthropic Claude

**Step 1: Get API Key**

1. Visit https://console.anthropic.com/
2. Sign in or create account
3. Navigate to API Keys
4. Click "Create Key"
5. Copy key (starts with `sk-ant-`)

**Step 2: Configure Profile**

```bash
# Option A: Use built-in profile
kollab
> /profile set claude
> Enter API key: sk-ant-...

# Option B: Use environment variable
export ANTHROPIC_API_KEY="sk-ant-..."
kollab

# Option C: Create custom profile
kollab
> /profile create
> Profile name: claude-opus
> API URL: https://api.anthropic.com
> Model: claude-opus-4-20250514
> API Key: sk-ant-...
```

**Recommended Models:**

| Model | Use Case | Context | Cost |
|-------|----------|---------|------|
| `claude-opus-4-20250514` | Complex tasks | 200K | $$$$ |
| `claude-sonnet-4-20250514` | General use | 200K | $$$ |
| `claude-haiku-4-20250514` | Fast/cheap | 200K | $ |

**Configuration Examples:**

```json
{
  "core": {
    "llm": {
      "profiles": {
        "claude-sonnet": {
          "api_url": "https://api.anthropic.com",
          "model": "claude-sonnet-4-20250514",
          "temperature": 0.7,
          "max_tokens": 4096,
          "tool_format": "anthropic",
          "native_tool_calling": true,
          "description": "Claude Sonnet for general use"
        },
        "claude-opus": {
          "api_url": "https://api.anthropic.com",
          "model": "claude-opus-4-20250514",
          "temperature": 0.7,
          "max_tokens": 4096,
          "tool_format": "anthropic",
          "description": "Claude Opus for complex tasks"
        }
      }
    }
  }
}
```

### Azure OpenAI

**Step 1: Get Credentials**

1. Visit https://portal.azure.com/
2. Create/Open Azure OpenAI resource
3. Get endpoint URL (e.g., `https://my-resource.openai.azure.com`)
4. Get API key from resource keys
5. Note deployment name (not model name)

**Step 2: Configure Profile**

```bash
kollab
> /profile create
> Profile name: azure-gpt4
> API URL: https://my-resource.openai.azure.com/openai/deployments/my-deployment
> Model: gpt-4  # This is ignored by Azure, uses deployment name
> API Key: <azure-api-key>
```

**Configuration Examples:**

```json
{
  "core": {
    "llm": {
      "profiles": {
        "azure-gpt4": {
          "api_url": "https://my-resource.openai.azure.com/openai/deployments/gpt4-deployment",
          "model": "gpt-4",
          "temperature": 0.7,
          "max_tokens": 4096,
          "description": "Azure OpenAI GPT-4"
        }
      }
    }
  }
}
```

**Environment Variables:**

```bash
export AZURE_OPENAI_API_KEY="..."
export AZURE_OPENAI_ENDPOINT="https://my-resource.openai.azure.com"
```

### Local LLMs (Ollama, LM Studio, vLLM)

**Ollama Setup:**

```bash
# Install Ollama
curl -fsSL https://ollama.com/install.sh | sh

# Pull a model
ollama pull llama2

# Start Ollama server (runs on localhost:11434)
ollama serve
```

```bash
# Configure Kollabor
kollab
> /profile create
> Profile name: ollama-llama2
> API URL: http://localhost:11434/v1
> Model: llama2
> API Key: ollama  # Ollama doesn't require real key
```

**LM Studio Setup:**

```bash
# Start LM Studio with server enabled
# LM Studio -> Developer -> Enable Server
# Server runs on localhost:1234

# Configure Kollabor
kollab
> /profile create
> Profile name: lm-studio
> API URL: http://localhost:1234/v1
> Model: local-model  # Loaded model name in LM Studio
> API Key: not-needed
```

**vLLM Setup:**

```bash
# Start vLLM server
vllm serve meta-llama/Llama-2-7b --port 8000

# Configure Kollabor
kollab
> /profile create
> Profile name: vllm-llama2
> API URL: http://localhost:8000/v1
> Model: meta-llama/Llama-2-7b
> API Key: not-needed
```

---

## Environment Variables

Kollabor supports environment variables for all profile settings. Environment variables **override** config file settings.

### Naming Convention

```
KOLLABOR_{PROFILE_NAME}_{SETTING}
```

Profile name is normalized (uppercase, non-alphanumeric → underscore).

### Examples

```bash
# OpenAI profile
export KOLLABOR_OPENAI_ENDPOINT="https://api.openai.com"
export KOLLABOR_OPENAI_TOKEN="sk-..."
export KOLLABOR_OPENAI_MODEL="gpt-4-turbo"
export KOLLABOR_OPENAI_TEMPERATURE="0.7"
export KOLLABOR_OPENAI_MAX_TOKENS="4096"
export KOLLABOR_OPENAI_TIMEOUT="60000"

# Custom profile "my-llm"
export KOLLABOR_MY_LLM_ENDPOINT="https://my-llm.com"
export KOLLABOR_MY_LLM_TOKEN="..."
export KOLLABOR_MY_LLM_MODEL="my-model"

# Profile with special characters "My LLM!"
# Normalizes to: KOLLABOR_MY_LLM__*
export KOLLABOR_MY_LLM__ENDPOINT="..."
export KOLLABOR_MY_LLM__TOKEN="..."
```

### Available Environment Variables

| Setting | Environment Variable | Example |
|---------|---------------------|---------|
| Endpoint | `KOLLABOR_{PROFILE}_ENDPOINT` | `https://api.openai.com` |
| Token | `KOLLABOR_{PROFILE}_TOKEN` | `sk-...` |
| Model | `KOLLABOR_{PROFILE}_MODEL` | `gpt-4-turbo` |
| Temperature | `KOLLABOR_{PROFILE}_TEMPERATURE` | `0.7` |
| Max Tokens | `KOLLABOR_{PROFILE}_MAX_TOKENS` | `4096` |
| Timeout | `KOLLABOR_{PROFILE}_TIMEOUT` | `60000` |
| Tool Format | `KOLLABOR_{PROFILE}_TOOL_FORMAT` | `openai` |
| Native Tool Calling | `KOLLABOR_{PROFILE}_NATIVE_TOOL_CALLING` | `true` |

### Special Environment Variables

```bash
# Encryption password for Tier 2 encrypted file storage
export KOLLABOR_KEY_ENCRYPTION_PASSWORD="my-secure-password"

# Allow insecure plaintext storage (development only)
export KOLLABOR_ALLOW_PLAINTEXT_KEYS="true"  # NOT RECOMMENDED

# Custom allowed API hosts (security allowlist)
export KOLLABOR_ALLOWED_API_HOSTS="api.openai.com,api.anthropic.com,my-proxy.com"

# Color mode override
export KOLLABOR_COLOR_MODE="truecolor"  # or "256", "16", "none"
```

---

## Migration Guide

### From Legacy HTTP System

Kollabor previously used a legacy HTTP client. Here's how to migrate:

**Step 1: Backup Existing Config**

```bash
cp ~/.kollabor-cli/config.json ~/.kollabor-cli/config.json.backup
```

**Step 2: Update Config Structure**

**Old config format:**

```json
{
  "llm": {
    "api_endpoint": "http://localhost:1234",
    "model": "qwen/qwen3-4b",
    "api_key": "sk-..."
  }
}
```

**New config format:**

```json
{
  "core": {
    "llm": {
      "default_profile": "default",
      "active_profile": "default",
      "profiles": {
        "default": {
          "api_url": "http://localhost:1234",
          "model": "qwen/qwen3-4b",
          "temperature": 0.7
        }
      }
    }
  }
}
```

**Step 3: Migrate API Keys**

Keys are automatically migrated from config to secure storage:

```bash
# Run Kollabor - it will auto-migrate
kollab

# Check logs for migration confirmation
# "Migrated default API key to OS keyring"
```

**Step 4: Remove Legacy Config**

After confirming migration works:

```bash
# Edit config and remove old api_key field
nano ~/.kollabor-cli/config.json

# Remove "api_key" from profile configs
# Keys are now stored in OS keyring
```

### From Environment Variables Only

If you previously used only environment variables:

```bash
# Old way (still works)
export OPENAI_API_KEY="sk-..."
kollab

# New way (with persistence)
kollab
> /profile set openai
> Enter API key: sk-...
# Key now persisted in OS keyring

# Remove from shell profile (~/.bashrc, ~/.zshrc, etc.)
# export OPENAI_API_KEY="..."  # Remove this line
```

### Migrating Between Profiles

```bash
# Export profile config
kollab
> /profile list
# Copy profile settings

# Import into new profile
/profile create
> Profile name: new-profile
> API URL: <paste>
> Model: <paste>
# ... etc

# Switch to new profile
/profile set new-profile

# Delete old profile
/profile delete old-profile
```

---

## Troubleshooting

### Common Issues

#### "No API key found for profile"

**Cause:** API key not configured in any tier.

**Solution:**

```bash
# Check which tiers are available
kollab
> /profile list

# Tier 3: Set environment variable
export OPENAI_API_KEY="sk-..."

# Tier 1: Store in OS keyring
/profile set openai
> Enter API key: sk-...

# Tier 2: Use encrypted file
export KOLLABOR_KEY_ENCRYPTION_PASSWORD="password"
/profile set openai
> Enter API key: sk-...
```

#### "OS keyring not available"

**Cause:** Keyring library not installed or backend not configured.

**Solution:**

```bash
# Install keyring
pip install keyring

# macOS: No backend needed (uses Keychain)
# Windows: No backend needed (uses Credential Manager)

# Linux: Install Secret Service
sudo apt-get install gnome-keyring libsecret-1-0

# Verify backend
python -c "import keyring; print(keyring.get_keyring())"
```

#### "Failed to decrypt keystore"

**Cause:** Wrong encryption password for Tier 2 encrypted file.

**Solution:**

```bash
# Set correct password
export KOLLABOR_KEY_ENCRYPTION_PASSWORD="correct-password"

# Or delete encrypted file and start over
rm ~/.kollabor-cli/keys.encrypted
kollab
> /profile set openai
> Enter API key: sk-...
```

#### "API endpoint not in allowlist"

**Cause:** Custom API endpoint not in security allowlist.

**Solution:**

```bash
# Add custom host to allowlist
export KOLLABOR_ALLOWED_API_HOSTS="my-proxy.com,api.custom.com"

# Or use localhost (always allowed)
http://localhost:8000
```

#### "Module 'keyring' not found"

**Cause:** Keyring library not installed.

**Solution:**

```bash
# Install keyring
pip install keyring

# Or reinstall Kollabor with keyring support
pip install kollabor[keyring]
```

### Debug Mode

Enable debug logging to troubleshoot issues:

```bash
# Enable debug logging
export KOLLABOR_LOG_LEVEL="DEBUG"

# Run Kollabor
kollab

# Check logs
tail -f ~/.kollabor-cli/projects/<encoded-path>/logs/kollabor.log
```

### Log Redaction

Kollabor automatically redacts API keys from logs:

```
# Before redaction
Using API key: sk-proj-abc123def456...

# After redaction
Using API key: [REDACTED-OPENAI-PROJECT-KEY]
```

### Profile Corruption

If profile config becomes corrupted:

```bash
# Backup config
cp ~/.kollabor-cli/config.json ~/.kollabor-cli/config.json.corrupted

# Reset to defaults
rm ~/.kollabor-cli/config.json
kollab
# Config will be recreated with defaults

# Restore specific profiles from backup
# Edit config.json and copy profiles from backup
```

### API Key Not Persisting

If API keys aren't being saved:

```bash
# Check keyring availability
python -c "import keyring; print(keyring.get_keyring())"

# If "keyring.backends.plaintext.Keyring", backend not configured
# Install proper backend (see Tier 1 setup)

# Test keyring manually
python -c "
import keyring
keyring.set_password('kollabor-cli-test', 'test-profile', 'test-key')
print(keyring.get_password('kollabor-cli-test', 'test-profile'))
"

# Use encrypted file as fallback
export KOLLABOR_KEY_ENCRYPTION_PASSWORD="password"
```

---

## Enterprise Deployment

### Docker Deployment

**Dockerfile:**

```dockerfile
FROM python:3.12-slim

# Install dependencies
RUN pip install --no-cache-dir kollabor[openai,cryptography]

# Create data directory
RUN mkdir -p /root/.kollabor-cli

# Set environment variables
ENV KOLLABOR_KEY_ENCRYPTION_PASSWORD=""
ENV KOLLABOR_LOG_LEVEL="INFO"

# Volume for persistence
VOLUME ["/root/.kollabor-cli"]

# Set entrypoint
ENTRYPOINT ["kollab"]
CMD ["--help"]
```

**docker-compose.yml:**

```yaml
version: '3.8'
services:
  kollabor:
    build: .
    environment:
      - KOLLABOR_KEY_ENCRYPTION_PASSWORD=${KOLLABOR_PASSWORD}
      - OPENAI_API_KEY=${OPENAI_API_KEY}
      - KOLLABOR_LOG_LEVEL=INFO
    volumes:
      - kollabor-data:/root/.kollabor-cli
    stdin_open: true
    tty: true

volumes:
  kollabor-data:
```

**Deploy:**

```bash
# Build image
docker-compose build

# Start container
docker-compose run --rm kollabor

# Use environment file
echo "KOLLABOR_PASSWORD=secure-password" > .env
echo "OPENAI_API_KEY=sk-..." >> .env
docker-compose run --rm kollabor
```

### Kubernetes Deployment

**ConfigMap:**

```yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: kollabor-config
data:
  KOLLABOR_LOG_LEVEL: "INFO"
  KOLLABOR_DEFAULT_PROFILE: "openai"
```

**Secret:**

```yaml
apiVersion: v1
kind: Secret
metadata:
  name: kollabor-secrets
type: Opaque
stringData:
  KOLLABOR_KEY_ENCRYPTION_PASSWORD: "secure-password"
  OPENAI_API_KEY: "sk-..."
```

**Deployment:**

```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: kollabor
spec:
  replicas: 1
  selector:
    matchLabels:
      app: kollabor
  template:
    metadata:
      labels:
        app: kollabor
    spec:
      containers:
      - name: kollabor
        image: kollabor-cli:latest
        envFrom:
        - configMapRef:
            name: kollabor-config
        - secretRef:
            name: kollabor-secrets
        volumeMounts:
        - name: data
          mountPath: /root/.kollabor-cli
      volumes:
      - name: data
        persistentVolumeClaim:
          claimName: kollabor-pvc
```

**Persistent Volume Claim:**

```yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: kollabor-pvc
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi
```

### CI/CD Integration

**GitHub Actions:**

```yaml
name: Kollabor Tests
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.12'

      - name: Install Kollabor
        run: pip install kollabor[openai]

      - name: Run tests
        env:
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
        run: |
          echo "Write a fibonacci function" | kollab -p --timeout 2min
```

**GitLab CI:**

```yaml
stages:
  - test

test:
  stage: test
  image: python:3.12
  script:
    - pip install kollabor[openai]
    - echo "Explain async/await" | kollab -p
  variables:
    OPENAI_API_KEY: $OPENAI_API_KEY
```

### Air-Gapped Systems

For systems without internet access:

```bash
# 1. Install dependencies on internet-connected machine
pip download -d ./packages kollabor[openai,cryptography,keyring]

# 2. Transfer packages to air-gapped system
scp -r ./packages user@air-gapped:/tmp/

# 3. Install from local packages
pip install --no-index --find-links=/tmp/packages kollabor

# 4. Configure encrypted file storage
export KOLLABOR_KEY_ENCRYPTION_PASSWORD="password"

# 5. Manually import API key (via secure channel)
# Paste API key into prompt
kollab
> /profile set openai
> Enter API key: <paste-from-secure-channel>
```

### Security Best Practices

**1. Never Commit API Keys**

```bash
# Add to .gitignore
echo ".env" >> .gitignore
echo "keys.json" >> .gitignore
echo "keys.encrypted" >> .gitignore
echo "*.key" >> .gitignore
```

**2. Use Secrets Management**

```bash
# Use environment variables in production
export OPENAI_API_KEY=$(vault read -field=value secret/openai)

# Or use Kubernetes secrets
kubectl create secret generic openai-key --from-literal=api-key="sk-..."
```

**3. Rotate Keys Regularly**

```bash
# Generate new key in provider console
# Update in Kollabor
kollab
> /profile set openai
> Enter API key: <new-key>

# Old key is automatically replaced in keyring
```

**4. Audit Access**

```bash
# macOS: Check keychain access
log show --predicate 'subsystem == "com.apple.security"' --info

# Windows: Check Credential Manager usage
rundll32.exe keymgr.dll,KRShowKeyMgr

# Linux: Check keyring access
journalctl -u gnome-keyring-daemon
```

**5. Least Privilege**

```bash
# Use minimum required scopes
# OpenAI: No scopes (API key has fixed permissions)
# Anthropic: No scopes (API key has fixed permissions)

# Set rate limits in provider console
# OpenAI: Set usage limits and rate limits
# Anthropic: Set rate limits
```

---

## Quick Reference

### Profile Commands

```bash
/profile list              # List all profiles
/profile set <name>        # Switch to profile
/profile create            # Create new profile
/profile delete <name>     # Delete profile
/profile show <name>       # Show profile details
```

### Environment Variables

```bash
# Provider-specific
OPENAI_API_KEY="sk-..."
ANTHROPIC_API_KEY="sk-ant-..."
AZURE_OPENAI_API_KEY="..."

# Profile-specific
KOLLABOR_MY_PROFILE_TOKEN="..."
KOLLABOR_MY_PROFILE_ENDPOINT="https://..."
KOLLABOR_MY_PROFILE_MODEL="gpt-4"

# Encryption
KOLLABOR_KEY_ENCRYPTION_PASSWORD="password"

# Security
KOLLABOR_ALLOWED_API_HOSTS="api.openai.com,my-proxy.com"
KOLLABOR_ALLOW_PLAINTEXT_KEYS="false"  # Default
```

### Config File Location

```bash
~/.kollabor-cli/config.json
```

### Encrypted Keys Location

```bash
~/.kollabor-cli/keys.encrypted
```

### Logs Location

```bash
~/.kollabor-cli/projects/<encoded-path>/logs/kollabor.log
```

---

## Support

For issues and questions:
- GitHub Issues: https://github.com/your-org/kollabor-cli/issues
- Documentation: https://docs.kollabor.ai
- Community: https://discord.gg/kollabor
