# Turumba CLI

Command-line interface for the [Turumba](https://turumba.net) message automation platform. Manage accounts, delivery channels, messages, templates, groups, and more -- directly from your terminal or through AI agents.

## Features

- **Full API coverage** -- wraps all 84 Turumba API endpoints (accounts, channels, messages, templates, group messages, scheduled messages, conversations, and more)
- **Secure authentication** -- login via email/password, tokens stored in your system keyring (macOS Keychain, GNOME Keyring, Windows Credential Manager) with file and environment variable fallbacks
- **Multiple output formats** -- rich terminal tables (default), JSON for scripting and AI agents, CSV for spreadsheets
- **Filter and sort** -- use the same `field:op:value` filter syntax as the API directly from the CLI
- **AI agent integration** -- built-in `skills` command with structured parameter specs that AI agents (Claude Code, Codex, GPT, etc.) can query at runtime to execute any Turumba operation in one shot
- **Non-interactive mode** -- every interactive prompt has a `--flag` equivalent, making the CLI fully scriptable for CI/CD pipelines

## Installation

**Recommended** (isolated environment via pipx):

```bash
# Install pipx first if you don't have it
brew install pipx        # macOS
sudo apt install pipx    # Ubuntu/Debian

# Install turumba
pipx install turumba
```

**Alternative** (pip, inside a virtual environment):

```bash
pip install turumba
```

> **Note:** On macOS (Homebrew Python) and modern Linux, system-wide `pip install` is blocked by [PEP 668](https://peps.python.org/pep-0668/). Use `pipx` instead -- it automatically manages an isolated virtual environment for CLI tools.

**From source** (development):

```bash
git clone <repo-url> turumba_cli
cd turumba_cli
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
```

### Requirements

- Python 3.11 or higher
- An active Turumba account (register at [turumba.net](https://turumba.net) or via `turumba auth register`)

## Quick Start

```bash
# 1. Authenticate
turumba auth login
# > Email: you@company.com
# > Password: ********
# ok Logged in as you@company.com
# info Default account set to: My Company

# 2. Set your default account (one-time, avoids passing --account-id every time)
turumba config set default_account_id <your-account-uuid>

# 3. List your delivery channels
turumba channels list

# 4. Create a Telegram channel
turumba channels create \
  --name "Support Bot" \
  --type telegram \
  --credentials '{"bot_token": "123456:ABC-DEF"}'

# 5. Create a person
turumba persons create \
  --properties '{"name": "Abebe", "phone": "+251911123456"}'

# 6. Check auth status anytime
turumba auth status
```

## Configuration

The CLI stores configuration in `~/.turumba/config.yaml`.

```bash
# View all config
turumba config list

# Set the gateway URL (default: https://api.dev.turumba.net)
turumba config set gateway_url https://api.dev.turumba.net

# Set default output format
turumba config set default_output json

# Set default account (used by persons, contacts, group-messages, etc.)
turumba config set default_account_id <account-uuid>

# Switch active account (for multi-tenant users)
turumba config use-account <account-id>
```

### Config Keys

| Key | Default | Description |
|-----|---------|-------------|
| `gateway_url` | `https://api.dev.turumba.net` | Turumba API gateway URL |
| `default_account_id` | *(none)* | Default account for multi-tenant operations. Required by persons, contacts, group-messages, and scheduled-messages. |
| `default_output` | `table` | Default output format (`table`, `json`, `csv`) |

### Environment Variables

For CI/CD and automation, you can skip interactive login entirely:

| Variable | Description |
|----------|-------------|
| `TURUMBA_ACCESS_TOKEN` | JWT access token (overrides stored credentials) |
| `TURUMBA_REFRESH_TOKEN` | Optional refresh token |

## Command Reference

### Authentication

```bash
turumba auth login              # Interactive login (email + password)
turumba auth login -e user@co.com -p secret   # Non-interactive login
turumba auth logout             # Clear stored tokens
turumba auth status             # Show token expiry, user info, active account
turumba auth register           # Create a new Turumba account
turumba auth verify-email       # Verify email with confirmation code
```

### Context

```bash
turumba context                 # Show current user's accounts and roles
turumba context -o json         # JSON output for scripting
```

### Configuration

```bash
turumba config list             # Show all configuration
turumba config get gateway_url  # Get a single value
turumba config set <key> <val>  # Set a value
turumba config use-account <id> # Set default account
```

### Delivery Channels

```bash
turumba channels list                                   # List all channels
turumba channels list -f channel_type:eq:telegram       # Filter by type
turumba channels list -f status:eq:connected -s name:asc  # Filter + sort
turumba channels get <id>                               # Get channel details
turumba channels create --name "Bot" --type telegram \
  --credentials '{"bot_token": "..."}' --priority 10    # Create channel
turumba channels update <id> --enabled                  # Enable channel
turumba channels update <id> --disabled                 # Disable channel
turumba channels delete <id>                            # Delete (with confirmation)
turumba channels delete <id> --force                    # Delete (skip confirmation)
turumba channels test-connection --id <id>              # Test existing channel
turumba channels test-connection --type telegram \
  --credentials '{"bot_token": "..."}'                  # Test new credentials
```

### Persons

```bash
turumba persons list                                    # List all persons
turumba persons list -o json                            # JSON output
turumba persons get <id>                                # Get person details
turumba persons create --account-id <uuid> \
  --properties '{"name": "Abebe", "phone": "+251911..."}' \
  --group-id <group-id>                                 # Create person
turumba persons create \
  --properties '{"name": "Abebe"}'                      # Uses default_account_id
turumba persons update <id> \
  --properties '{"email": "a@b.com"}'                   # Merge properties
turumba persons update <id> \
  --properties '{"phone": "+251..."}' --replace         # Replace all properties
turumba persons delete <id> --force                     # Delete
```

### Contacts

```bash
turumba contacts list                                   # List all contacts
turumba contacts get <id>                               # Get contact details
turumba contacts create --account-id <uuid> \
  --properties '{"phone": "+251...", "name": "Abebe"}'  # Create contact
turumba contacts update <id> \
  --properties '{"email": "new@example.com"}'           # Merge properties
turumba contacts delete <id> --force                    # Delete
```

### Group Messages

```bash
turumba group-messages list                             # List all
turumba group-messages list -f status:eq:completed      # Filter by status
turumba group-messages get <id>                         # Get details + stats
turumba group-messages create \
  --group-id <gid> --channel-id <cid> \
  --body "Hello everyone!"                              # Send to group
turumba group-messages create \
  --person-id <pid1> --person-id <pid2> \
  --channel-id <cid> --body "Direct"                    # Send to persons
turumba group-messages create \
  --group-id <gid> --template-id <tid> \
  --channel-id <cid> \
  --custom-values '{"promo_code": "MARCH25"}'           # Template-based
turumba group-messages delete <id> --force              # Delete
```

### Scheduled Messages

```bash
turumba scheduled-messages list                         # List all
turumba scheduled-messages list -f status:eq:pending    # Filter pending
turumba scheduled-messages get <id>                     # Get details

# One-time single recipient
turumba scheduled-messages create --send-type single \
  --delivery-address "+251911..." --channel-id <cid> \
  --body "Reminder" --scheduled-at 2026-04-01T09:00:00Z

# Recurring weekly group broadcast
turumba scheduled-messages create --send-type group \
  --group-id <gid> --channel-id <cid> \
  --body "Weekly update" --scheduled-at 2026-04-07T09:00:00Z \
  --recurring --recurrence-rule RRULE:FREQ=WEEKLY

turumba scheduled-messages update <id> \
  --scheduled-at 2026-04-05T14:00:00Z                   # Reschedule
turumba scheduled-messages delete <id> --force          # Cancel
```

### Chat Endpoints

```bash
turumba chat-endpoints list                             # List all
turumba chat-endpoints get <id>                         # Get details
turumba chat-endpoints create --name "Support Chat" \
  --channel-id <cid> --welcome-message "Hello!" \
  --origin https://example.com                          # Create
turumba chat-endpoints update <id> --inactive           # Disable
turumba chat-endpoints delete <id> --force              # Delete
```

### Conversation Configs

```bash
turumba conversation-configs list                       # List all
turumba conversation-configs get <id>                   # Get details
turumba conversation-configs create \
  --name "Default" --priority 0                         # Create
turumba conversation-configs create \
  --name "VIP Support" --priority 10 \
  --audience-mode groups \
  --audience-group-ids '["<group-uuid>"]'               # Group targeting
turumba conversation-configs evaluate \
  --channel-type telegram --channel-id <cid> --known    # Test matching
turumba conversation-configs delete <id> --force        # Delete
```

### Skills (AI Agent Integration)

```bash
turumba skills list                                     # List all topics
turumba skills show channels                            # Detailed reference
turumba skills show channels -o json                    # JSON for agents
turumba skills show create-resource                     # Quick-ref for all creates
turumba skills how-to "send telegram message to group"  # Find best workflow
```

## Filtering and Sorting

List commands support the same filter and sort syntax as the Turumba API.

### Filter Syntax

```bash
--filter field:op:value
```

| Operator | Description | Example |
|----------|-------------|---------|
| `eq` | Equals | `--filter status:eq:connected` |
| `ne` | Not equals | `--filter status:ne:disabled` |
| `lt`, `le`, `gt`, `ge` | Comparison | `--filter priority:gt:5` |
| `contains` | Substring (case-sensitive) | `--filter name:contains:bot` |
| `icontains` | Substring (case-insensitive) | `--filter name:icontains:Bot` |
| `startswith` | Starts with | `--filter name:startswith:prod` |
| `endswith` | Ends with | `--filter email:endswith:@co.com` |
| `in` | In list | `--filter channel_type:in:telegram,whatsapp` |
| `is_null` | Is null | `--filter error_message:is_null:true` |
| `range` | Range | `--filter created_at:range:2024-01-01,2024-12-31` |

Multiple filters are combined with AND:

```bash
turumba channels list \
  -f channel_type:eq:telegram \
  -f status:eq:connected \
  -f is_enabled:eq:true
```

### Sort Syntax

```bash
--sort field:asc|desc
```

```bash
turumba channels list -s created_at:desc        # Newest first
turumba channels list -s name:asc -s priority:desc  # Multi-sort
```

### Pagination

```bash
turumba channels list --limit 20 --skip 40      # Page 3 (20 items/page)
```

## Output Formats

### Table (default)

```
                    Channels
 ID     Name          Type       Status      Enabled
 abc... Support Bot   telegram   connected   Yes
 def... SMS Gateway   sms        connected   Yes
```

### JSON

```bash
turumba channels list -o json
```

```json
[
  {
    "id": "abc...",
    "name": "Support Bot",
    "channel_type": "telegram",
    "status": "connected",
    "is_enabled": true
  }
]
```

### CSV

```bash
turumba channels list -o csv > channels.csv
```

## AI Agent Integration

Turumba CLI includes a built-in **skills system** designed for AI agents. Instead of hardcoding Turumba knowledge into agent prompts, agents query the CLI at runtime for up-to-date instructions -- including exact parameter specs, validation rules, and credential schemas.

### How It Works

```bash
# List all skill topics
turumba skills list

# Get detailed reference with parameter table
turumba skills show channels

# Get structured JSON output (for agent parsing)
turumba skills show channels -o json

# Quick-reference for creating ANY resource
turumba skills show create-resource

# Ask "how do I..." and get step-by-step instructions
turumba skills how-to "send a telegram message to a group"
```

### What Agents Get

When an agent runs `turumba skills show channels -o json`, it receives:

- **create_params**: Structured parameter specs with name, type, required flag, description, enum values, defaults, and conditional requirements
- **notes**: Credential schemas per channel type, validation rules, important caveats
- **examples**: Ready-to-execute one-shot commands
- **workflows**: Multi-step sequences for common tasks

### Setting Up an AI Agent

Add this to your project's `CLAUDE.md` (or equivalent agent instructions):

```markdown
## Turumba CLI
This project uses Turumba for messaging. The `turumba` CLI is installed.
- Run `turumba skills show create-resource -o json` for a quick-reference of all creation parameters
- Run `turumba skills show <topic> -o json` for detailed parameter specs on a specific resource
- Run `turumba skills how-to "<task>"` to get step-by-step instructions
- Always use `--output json` when parsing CLI output programmatically
- Set default account: `turumba config set default_account_id <uuid>`
```

### Available Skill Topics

| Topic | Description |
|-------|-------------|
| `create-resource` | Quick-reference for creating ANY resource (params, credentials, examples) |
| `channels` | Delivery channels: SMS, Telegram, WhatsApp, Email, etc. |
| `persons` | Persons (recipients with dynamic properties and group membership) |
| `contacts` | Contacts (dynamic-property contact records) |
| `templates` | Message templates with `{{variable}}` substitution |
| `group-messages` | Broadcast messages to groups, persons, or contacts |
| `scheduled-messages` | Schedule one-time or recurring messages |
| `sending` | Overview of all message sending methods |
| `chat-endpoints` | Embeddable chat widgets |
| `conversation-configs` | Conversation routing rules and audience targeting |
| `auth` | Authentication: login, logout, register |
| `filtering` | Filter and sort query syntax for list commands |
| `overview` | Platform overview and getting started |
| `troubleshooting` | Common issues and debugging tips |

## Global Options

These flags are available on most commands:

| Flag | Short | Description |
|------|-------|-------------|
| `--gateway-url` | `-g` | Override the gateway URL for this command |
| `--output` | `-o` | Output format: `table`, `json`, `csv` |
| `--filter` | `-f` | Filter expression (list commands only) |
| `--sort` | `-s` | Sort expression (list commands only) |
| `--limit` | `-l` | Max results (list commands only, default: 100) |
| `--skip` | | Pagination offset (list commands only, default: 0) |
| `--account-id` | `-a` | Account ID override (create commands for persons, contacts, etc.) |
| `--version` | `-V` | Show CLI version |
| `--help` | | Show help for any command |

## Security

### Token Storage

Tokens are stored using a layered approach (first available wins):

1. **System keyring** (recommended) -- macOS Keychain, GNOME Secret Service, Windows Credential Manager
2. **File fallback** -- `~/.turumba/credentials` with `0600` permissions (owner read/write only)
3. **Environment variables** -- `TURUMBA_ACCESS_TOKEN` for CI/CD environments

### Token Lifecycle

- Tokens are obtained via `turumba auth login` (calls `POST /v1/auth/login`)
- Access tokens are JWT (RS256, issued by AWS Cognito) with a 1-hour expiry
- The CLI checks token expiry before every request with a 5-minute buffer
- When expired, the CLI prompts for re-login (a refresh endpoint is planned)
- `turumba auth logout` removes tokens from all storage backends

## Development

```bash
# Setup
cd turumba_cli
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"

# Run
turumba --help

# Lint and format
ruff check src/                   # Check for issues
ruff check --fix src/             # Auto-fix
ruff format src/                  # Format code

# Test
pytest                            # All tests
pytest --cov=src/turumba_cli      # With coverage (80% minimum)
pytest -m unit                    # Unit tests only
```

### Adding a New Resource

See [ARCHITECTURE.md](ARCHITECTURE.md) for the detailed guide. In brief:

1. Create `src/turumba_cli/commands/<resource>.py` (follow `channels.py` as reference)
2. Define `app`, `API_PATH`, `LIST_COLUMNS`
3. Add CRUD commands + any special commands
4. For resources needing `account_id`, add `--account-id / -a` with `get_value("default_account_id")` fallback
5. Register in `main.py` via `app.add_typer()`
6. Add or update skill topic in `skills/topics/` with `create_params` and `notes`

## Roadmap

| Phase | Status | Scope |
|-------|--------|-------|
| Phase 1: Foundation | Done | Auth, config, context, channels (reference CRUD) |
| Phase 2: Full CRUD + Skills | Done | Persons, contacts, group-messages, scheduled-messages, chat-endpoints, conversation-configs, skills system with parameter specs |
| Phase 3: Polish & Publish | Planned | Remaining resources (accounts, users, groups, roles, messages, templates, conversations), CRUD factory, PyPI, shell completion, --dry-run, 80% coverage |

## License

MIT
