# zCode CLI X - Installation & Setup Guide

## Prerequisites

### Required
- **Node.js** ≥ 20.0.0 ([Download](https://nodejs.org/))
- **npm** ≥ 9.0.0 (comes with Node.js)
- **Git** (for version control)
- **systemd** (for 24/7 service on Linux)
- **ffmpeg** (for voice I/O)
- **Python 3.8+** (for Vosk STT)

### Optional
- **SSL certificate** (for HTTPS webhook)
- **Domain name** (for custom webhook URL)
- **Docker** (for containerized deployment - coming soon)

---

## Quick Start (5 Minutes)

### 1. Clone Repository

```bash
git clone https://github.rommark.dev/admin/zCode-CLI-X.git
cd zCode-CLI-X
```

### 2. Install Dependencies

```bash
npm install
```

### 3. Configure Environment

```bash
cp .env.example .env
nano .env
```

Edit `.env` with your credentials:

```env
# Z.AI Configuration (Coding Plan)
GLM_BASE_URL=https://api.z.ai/api/coding/paas/v4
ZAI_API_KEY=your_zai_api_key_here

# Telegram Bot Configuration
TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here
TELEGRAM_ALLOWED_USERS=your_telegram_id,friend_id
ZCODE_WEBHOOK_URL=https://your-domain.com/telegram/webhook
```

### 4. Test Run

```bash
# Test as CLI (temporary session)
node bin/zcode.js

# Test as bot (24/7)
node bin/zcode.js --no-cli
```

### 5. Install as Systemd Service

```bash
# Copy service file
cp scripts/zcode.service ~/.config/systemd/user/

# Reload systemd
systemctl --user daemon-reload

# Enable and start service
systemctl --user enable zcode
systemctl --user start zcode

# Check status
systemctl --user status zcode

# View logs
journalctl --user -u zcode -f
```

✅ **Done!** Your bot is now running 24/7.

---

## Detailed Setup

### Step 1: Install Node.js

#### Ubuntu/Debian
```bash
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs
node --version  # Should show v20.x or higher
npm --version   # Should show 9.x or higher
```

#### macOS (Homebrew)
```bash
brew install node@20
node --version
npm --version
```

#### CentOS/RHEL
```bash
curl -fsSL https://rpm.nodesource.com/setup_20.x | sudo bash -
sudo yum install -y nodejs
node --version
npm --version
```

### Step 2: Install ffmpeg (for Voice I/O)

#### Ubuntu/Debian
```bash
sudo apt-get update
sudo apt-get install -y ffmpeg
ffmpeg -version  # Verify installation
```

#### macOS
```bash
brew install ffmpeg
ffmpeg -version
```

#### CentOS/RHEL
```bash
sudo yum install -y ffmpeg
ffmpeg -version
```

### Step 3: Install Python & Vosk (for Voice STT)

#### Install Python 3.8+
```bash
# Ubuntu/Debian
sudo apt-get install -y python3 python3-pip

# macOS
brew install python

# Verify
python3 --version  # Should show 3.8+
pip3 --version
```

#### Install Vosk Model
```bash
# Create model directory
mkdir -p ~/vosk-models

# Download small model (68MB, ~95% accuracy)
cd ~/vosk-models
wget https://alphacephei.com/vosk-models/vosk-model-small-0.15.zip
unzip vosk-model-small-0.15.zip

# Verify
ls -la vosk-model-small-0.15/  # Should show model files
```

#### Install Vosk Python Package
```bash
pip3 install vosk
pip3 install sounddevice  # For audio recording
pip3 install scipy  # For audio processing
```

### Step 4: Configure Telegram Bot

#### 1. Create Bot with BotFather
1. Open Telegram and search for `@BotFather`
2. Send `/newbot` command
3. Follow prompts to name your bot
4. Save the **API Token** (looks like: `123456789:ABCdefGHIjklMNOpqrsTUVwxyz`)

#### 2. Get Your Telegram ID
1. Search for `@userinfobot` in Telegram
2. Send any message
3. Copy your **User ID** (looks like: `123456789`)

#### 3. Update `.env`
```env
TELEGRAM_BOT_TOKEN=123456789:ABCdefGHIjklMNOpqrsTUVwxyz
TELEGRAM_ALLOWED_USERS=123456789,987654321  # Your ID + friends' IDs
```

### Step 5: Set Up Webhook

#### Option A: Using ngrok (Quick Testing)
```bash
# Install ngrok
npm install -g ngrok

# Start local server
node bin/zcode.js --no-cli &

# Expose to internet (in new terminal)
ngrok http 3001

# Copy the HTTPS URL (e.g., https://abc123.ngrok.io)
# Update .env:
# ZCODE_WEBHOOK_URL=https://abc123.ngrok.io/telegram/webhook

# Set webhook via API
curl -X POST "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook?url=https://abc123.ngrok.io/telegram/webhook"
```

#### Option B: Using Domain (Production)
```bash
# 1. Set up Nginx reverse proxy
sudo nano /etc/nginx/sites-available/zcode

# Add:
server {
    listen 80;
    server_name your-domain.com;

    location /telegram/webhook {
        proxy_pass http://localhost:3001;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

# Enable site
sudo ln -s /etc/nginx/sites-available/zcode /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
```

```bash
# 2. Get SSL certificate (Let's Encrypt)
sudo apt-get install -y certbot python3-certbot-nginx
sudo certbot --nginx -d your-domain.com

# 3. Set webhook
curl -X POST "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook?url=https://your-domain.com/telegram/webhook"
```

### Step 6: Install Systemd Service

#### 1. Copy Service File
```bash
cp scripts/zcode.service ~/.config/systemd/user/
```

#### 2. Edit Service File (if needed)
```bash
nano ~/.config/systemd/user/zcode.service
```

Update paths if necessary:
```ini
[Service]
ExecStart=/usr/bin/node /home/uroma2/zcode-cli-x/bin/zcode.js --no-cli
WorkingDirectory=/home/uroma2/zcode-cli-x
```

#### 3. Enable and Start
```bash
systemctl --user daemon-reload
systemctl --user enable zcode
systemctl --user start zcode
```

#### 4. Verify
```bash
systemctl --user status zcode
# Should show: Active: active (running)

journalctl --user -u zcode -f
# Should show: zCode CLI X running 24/7
```

---

## Configuration Reference

### Environment Variables

| Variable | Required | Description | Example |
|----------|----------|-------------|---------|
| `GLM_BASE_URL` | ✅ | Z.AI API base URL | `https://api.z.ai/api/coding/paas/v4` |
| `ZAI_API_KEY` | ✅ | Z.AI API key | `d88afea988...` |
| `TELEGRAM_BOT_TOKEN` | ✅ | Telegram bot token | `123456789:ABCdef...` |
| `TELEGRAM_ALLOWED_USERS` | ✅ | Comma-separated user IDs | `123456789,987654321` |
| `ZCODE_WEBHOOK_URL` | ✅ | Webhook endpoint URL | `https://your-domain.com/telegram/webhook` |
| `VOSK_MODEL_PATH` | ❌ | Path to Vosk model | `~/vosk-models/vosk-model-small-0.15` |
| `FFMPEG_PATH` | ❌ | Path to ffmpeg binary | `/usr/bin/ffmpeg` |
| `RTK_PATH` | ❌ | Path to RTK binary | `~/.local/bin/rtk` |
| `LOG_LEVEL` | ❌ | Logging level | `debug`, `info`, `warn`, `error` |
| `LOG_FILE` | ❌ | Log file path | `logs/zcode.log` |

### Config File (`.zcode.config.json`)

```json
{
  "api": {
    "baseUrl": "https://api.z.ai/api/coding/paas/v4",
    "models": {
      "default": "glm-5.1",
      "fallback": "glm-4v"
    }
  },
  "telegram": {
    "allowedUsers": ["123456789"],
    "webhookUrl": "https://your-domain.com/telegram/webhook"
  },
  "memory": {
    "maxEntries": 500,
    "evictionPolicy": "lru"
  },
  "agents": {
    "enabled": ["coder", "reviewer", "architect"],
    "maxTurns": 10
  }
}
```

---

## Troubleshooting

### Bot Not Starting

**Error**: `EADDRINUSE: address already in use :::3001`
```bash
# Kill existing process
lsof -ti:3001 | xargs kill -9
systemctl --user restart zcode
```

**Error**: `Telegram bot token not configured`
```bash
# Check .env file
cat .env | grep TELEGRAM_BOT_TOKEN
# Should show: TELEGRAM_BOT_TOKEN=123456789:ABCdef...
```

### Voice I/O Not Working

**Error**: `Vosk model not found`
```bash
# Check model path
ls -la ~/vosk-models/vosk-model-small-0.15/
# Should show: model.json, graphs, etc.

# Update .env
VOSK_MODEL_PATH=/home/uroma2/vosk-models/vosk-model-small-0.15
```

**Error**: `ffmpeg not found`
```bash
# Install ffmpeg
sudo apt-get install -y ffmpeg

# Verify
ffmpeg -version
```

### Webhook Not Receiving Messages

**Error**: `Webhook not set`
```bash
# Manually set webhook
curl -X POST "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook?url=https://your-domain.com/telegram/webhook"

# Check webhook info
curl -X GET "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getWebhookInfo"
```

**Error**: `Connection timeout`
```bash
# Check firewall
sudo ufw status
# Should allow port 80 and 443

# Check Nginx
sudo nginx -t
sudo systemctl status nginx
```

### Service Not Running

**Error**: `Active: inactive (dead)`
```bash
# Check logs
journalctl --user -u zcode -n 50 --no-pager

# Restart service
systemctl --user restart zcode

# Check status
systemctl --user status zcode
```

---

## Advanced Setup

### Docker Deployment (Coming Soon)

```bash
# Build image
docker build -t zcode-cli-x .

# Run container
docker run -d \
  --name zcode \
  -v $(pwd)/.env:/app/.env \
  -v $(pwd)/logs:/app/logs \
  -p 3001:3001 \
  zcode-cli-x
```

### Multiple Instances

```bash
# Copy service file with different name
cp scripts/zcode.service ~/.config/systemd/user/zcode-2.service

# Edit service file
nano ~/.config/systemd/user/zcode-2.service
# Change: ExecStart=/usr/bin/node /home/uroma2/zcode-cli-x/bin/zcode.js --no-cli
# To: ExecStart=/usr/bin/node /home/uroma2/zcode-cli-x/bin/zcode.js --no-cli --instance 2

# Enable and start
systemctl --user enable zcode-2
systemctl --user start zcode-2
```

### Custom Domain with SSL

```bash
# 1. Get domain DNS record
# Add A record: your-domain.com -> YOUR_SERVER_IP

# 2. Install Nginx
sudo apt-get install -y nginx

# 3. Configure Nginx
sudo nano /etc/nginx/sites-available/zcode

server {
    listen 80;
    server_name your-domain.com;

    location /telegram/webhook {
        proxy_pass http://localhost:3001;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

# 4. Enable site
sudo ln -s /etc/nginx/sites-available/zcode /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx

# 5. Get SSL certificate
sudo certbot --nginx -d your-domain.com

# 6. Set webhook
curl -X POST "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook?url=https://your-domain.com/telegram/webhook"
```

---

## Verification

### Check All Components

```bash
# 1. Node.js version
node --version  # Should show v20.x+

# 2. npm version
npm --version   # Should show 9.x+

# 3. ffmpeg
ffmpeg -version  # Should show version info

# 4. Python & Vosk
python3 --version  # Should show 3.8+
python3 -c "import vosk; print(vosk.__version__)"  # Should print version

# 5. Service status
systemctl --user status zcode  # Should show: active (running)

# 6. Webhook info
curl -X GET "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getWebhookInfo"
# Should show: {"ok":true,"url":"https://your-domain.com/telegram/webhook"}

# 7. Test bot
curl -X POST "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getMe"
# Should show your bot info
```

### Run Smoke Tests

```bash
# Run Ruflo smoke tests
node test-ruflo-smoke.mjs

# Should show:
# ✅ PluginSystem: 10/10
# ✅ HookSystem: 4/4
# ✅ AgentSystem: 9/9
# ✅ SwarmCoordinator: 12/12
# ✅ AgentOrchestrator: 4/4
# ✅ MemoryBackend: 14/14
# Total: 53/53
```

---

## Next Steps

1. ✅ **Test the bot** — Send `/start` in Telegram
2. ✅ **Explore features** — Try `/tools`, `/agents`, `/memory`
3. ✅ **Configure voice** — Set up Vosk model and ffmpeg
4. ✅ **Customize** — Edit `.zcode.config.json` for your needs
5. ✅ **Monitor** — Use `journalctl --user -u zcode -f` to watch logs

---

## Support

- **Issues**: [GitHub Issues](https://github.rommark.dev/admin/zCode-CLI-X/issues)
- **Discussions**: [GitHub Discussions](https://github.rommark.dev/admin/zCode-CLI-X/discussions)
- **Documentation**: [README.md](./README.md), [ARCHITECTURE.md](./ARCHITECTURE.md)

---

<div align="center">

**Ready to deploy?** Follow the steps above and your bot will be running in minutes! 🚀

</div>
