Metadata-Version: 2.4
Name: spritz-cli
Version: 1.2.1
Summary: Spritz CLI (spx) - Deploy and manage AI agents
Home-page: https://github.com/Activate-Intelligence/spritz-cli
Author: Incaendo Technology
Author-email: support@incaendo.com
Project-URL: Bug Reports, https://github.com/Activate-Intelligence/spritz-cli/issues
Project-URL: Source, https://github.com/Activate-Intelligence/spritz-cli
Project-URL: Documentation, https://github.com/Activate-Intelligence/spritz-cli#readme
Keywords: cli agent deployment ai spritz management spx
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Topic :: Software Development :: Build Tools
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.7
Description-Content-Type: text/markdown
Requires-Dist: click>=8.0.0
Requires-Dist: requests>=2.25.0
Requires-Dist: pyyaml>=6.0
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: keywords
Dynamic: project-url
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# Spritz CLI (spx)

Command-line interface for deploying and managing Spritz AI agents across dev and production environments.

## 📋 Table of Contents

- [Requirements](#-requirements)
- [Setup](#-setup)
  - [1. Installation](#1-installation)
  - [2. Configure Environment](#2-configure-environment)
  - [3. Login](#3-login)
- [Commands](#-commands)
  - [spx configure](#spx-configure)
  - [spx login](#spx-login)
  - [spx list-profiles](#spx-list-profiles)
  - [spx whoami](#spx-whoami)
  - [spx help](#spx-help)
  - [spx agent-onboarding](#spx-agent-onboarding)
  - [spx agent-update](#spx-agent-update)
  - [spx assign-agents](#spx-assign-agents)
  - [spx validate](#spx-validate)
  - [Preview Before Deploy (Dry Run)](#preview-before-deploy-dry-run)
- [Troubleshooting](#-troubleshooting)
- [Development](#-development)
  - [Project Structure](#project-structure)
  - [Getting Started](#getting-started)
  - [Publishing to PyPI](#publishing-to-pypi)
  - [PyPI Credentials](#pypi-credentials)
- [Automation Scripts](#-automation-scripts)
  - [Shell Scripts](#shell-scripts)
  - [Python Scripts](#python-scripts)
- [License](#-license)

---

## 🔧 Requirements

- **Python**: 3.7 or higher
- **Browser**: Modern browser with localStorage support
- **Internet**: Active internet connection
- **Access**: Spritz dashboard access

---

## ⚙️ Setup

### 1. Installation

Install via pip:
```bash
pip install spritz-cli
```

Verify installation:
```bash
spx --version
spx --help
```

### 2. Configure Environment

Configure your development environment:
```bash
spx configure --profile dev
# Spritz URL: https://app.dev.spritz.activate.bar
# API URL: https://api.dev.spritz.activate.bar
```

Configure your production environment:
```bash
spx configure --profile prod
# Spritz URL: https://spritz.activate.bar
# API URL: https://api.spritz.activate.bar
```

### 3. Login

Authenticate with Spritz:
```bash
# Login to dev
spx login --profile dev

# Login to prod
spx login --profile prod
```

**You're ready!** 🎉

---

## 📖 Commands

### `spx configure`

Configure Spritz URL and API URL for different environments.

**Usage:**
```bash
spx configure [--profile PROFILE]
```

**Options:**
- `--profile` - Profile name (default, dev, prod)

**Example:**
```bash
spx configure --profile dev
# Spritz URL [https://app.dev.spritz.activate.bar]: 
# API URL [https://api.dev.spritz.activate.bar]:
# ✓ Profile 'dev' configured successfully
# Do you want to login now? [Y/n]: y
```

**Configuration File:** `~/.spx/config`

**Format:**
```ini
[profile default]
spritz_url = https://spritz.activate.bar
api_url = https://api.spritz.activate.bar

[profile dev]
spritz_url = https://app.dev.spritz.activate.bar
api_url = https://api.dev.spritz.activate.bar

[profile prod]
spritz_url = https://spritz.activate.bar
api_url = https://api.spritz.activate.bar
```

---

### `spx login`

Authenticate with Spritz via browser.

**Usage:**
```bash
spx login [--profile PROFILE]
```

**Options:**
- `--profile` - Profile to login (default: default)

**Example:**
```bash
spx login --profile prod

# Output:
# → Opening browser for authentication...
#    Spritz URL: https://spritz.activate.bar
#    Waiting for authentication...
#    Please login in the browser window.
# 
# [Browser opens, user logs in, window closes]
# 
# → Verifying token...
# ✓ Authentication successful!
#    Logged in as: pradeep@incaendo.com
```

**How it works:**
1. Opens browser to Spritz dashboard
2. Extracts token from localStorage automatically
3. Verifies token with API
4. Saves token for future use
5. Browser window closes automatically

---

### `spx list-profiles`

List all configured profiles and their login status.

**Usage:**
```bash
spx list-profiles
```

**Example:**
```bash
spx list-profiles

# Output:
# Configured profiles:
#   - default (https://spritz.activate.bar) ✓ logged in
#   - dev (https://app.dev.spritz.activate.bar) ✓ logged in
#   - prod (https://spritz.activate.bar) ✗ not logged in
```

---

### `spx whoami`

Show current user information for a profile.

**Usage:**
```bash
spx whoami [--profile PROFILE]
```

**Example:**
```bash
spx whoami --profile prod

# Output:
# Profile: prod
# Spritz URL: https://spritz.activate.bar
# Email: pradeep@incaendo.com
# Auth0 ID: email|64e8a0485efd44509ed20f06
# Organization ID: 64a54a30899afb66425722fc
# Last Login: 2025-10-13T09:20:00.988Z
```

---

### `spx help`

Show help for commands.

**Usage:**
```bash
spx --help                    # Show all commands
spx configure --help          # Configure command help
spx login --help              # Login command help
spx agent-onboarding --help   # Agent onboarding help
spx agent-update --help       # Agent update help
```

---

### `spx agent-onboarding`

Deploy new agents from a configuration URL.

**Usage:**
```bash
spx agent-onboarding --profile PROFILE --url URL [--dry-run]
```

**Options:**
- `--profile` - Environment profile (default, dev, prod)
- `--url` - URL that returns agent configuration JSON (required)
- `--dry-run` - Preview without deploying

**Example:**
```bash
spx agent-onboarding --profile prod --url https://config.example.com/agents.json

# Output:
# ╔═══════════════════════════════════════════════════════════╗
# ║           🚀 SPRITZ AGENT ONBOARDING                      ║
# ╚═══════════════════════════════════════════════════════════╝
# 
# 📋 Profile: prod
# 🌐 Spritz Web: https://spritz.activate.bar
# 🔌 Spritz API: https://api.spritz.activate.bar
# 
# 📥 Loading agent configuration...
#    Source: https://config.example.com/agents.json
# ✅ Found 3 agent(s) to onboard
# 
# 📦 Agent Configurations:
#   [1] Customer Support Agent
#   [2] Sales Assistant
#   [3] Analytics Bot
# 
# ⚙️  Creating agents...
#   ✅ [1/3] Customer Support Agent onboarded successfully
#      🆔 Agent ID: 6925db4a0ad000cbdfa44cb5
#   ✅ [2/3] Sales Assistant onboarded successfully
#      🆔 Agent ID: 6925db4a0ad000cbdfa44cb6
#   ✅ [3/3] Analytics Bot onboarded successfully
#      🆔 Agent ID: 6925db4a0ad000cbdfa44cb7
# 
# ╔═══════════════════════════════════════════════════════════╗
# ║                    📊 SUMMARY                             ║
# ╚═══════════════════════════════════════════════════════════╝
# 
# ✅ Success: 3/3
# 
# 🎉 All agents onboarded successfully!
```

**Agent Configuration Format:**

Single agent:
```json
{
  "name": "Customer Support Agent",
  "url": "https://your-agent.com/agent",
  "type": "chat",
  "description": "Handles customer inquiries"
}
```

Multiple agents:
```json
[
  {
    "name": "Customer Support Agent",
    "url": "https://your-agent.com/agent1",
    "type": "chat"
  },
  {
    "name": "Sales Assistant",
    "url": "https://your-agent.com/agent2",
    "type": "voice"
  }
]
```

---

### `spx agent-update`

Update existing agents from a configuration URL.

**Usage:**
```bash
spx agent-update --profile PROFILE --url URL [--dry-run]
```

**Options:**
- `--profile` - Environment profile (default, dev, prod)
- `--url` - URL that returns agent configuration JSON (required)
- `--dry-run` - Preview without updating

**How it works:**
1. Fetches agent configuration from the provided URL
2. Extracts the `url` field from the configuration
3. Searches for the existing agent in Spritz using that URL
4. Updates the agent with the new configuration (PATCH)

**Example:**
```bash
spx agent-update --profile prod --url http://localhost:8000/agent

# Output:
# ╔═══════════════════════════════════════════════════════════╗
# ║           🚀 SPRITZ AGENT UPDATE                          ║
# ╚═══════════════════════════════════════════════════════════╝
# 
# 📋 Profile: prod
# 🌐 Spritz Web: https://spritz.activate.bar
# 🔌 Spritz API: https://api.spritz.activate.bar
# 
# 📥 Loading agent configuration...
#    Source: http://localhost:8000/agent
# ✅ Configuration loaded successfully
# 
# 🔍 Agent URL from config: http://localhost:8000/agent
# 🔎 Searching for existing agent in Spritz...
# ✅ Found agent: Customer Support Agent
#    Agent ID: 6925db4a0ad000cbdfa44cb5
# 
# ⚙️  Updating agent...
# 
# ✅ Agent updated successfully!
# 
# 📝 Agent: Customer Support Agent
# 🆔 ID: 6925db4a0ad000cbdfa44cb5
```

**Requirements:**
- Agent must already exist in Spritz
- Agent configuration must have a `url` field
- The `url` field must match the agent's URL in Spritz

---

### `spx assign-agents`

Assign agents (resolved from a discover JSON) to an organization.

**Usage:**
```bash
spx assign-agents --profile PROFILE --url URL
```

**What it does:**
1. Fetches organizations from Spritz
   (`$limit=999`, `$skip=0`, sorted by `_id desc`, selecting `profile.name`/`logo`)
2. Shows the names in 3-4 columns with numbered entries (logo indicator when present)
3. Prompts you to pick an organization number
4. Loads agents from your discover JSON, searches Spritz by each agent `url` to resolve IDs
5. PATCHes the organization with the resolved agent IDs

**Example:**
```bash
spx assign-agents \
  --profile dev \
  --url https://example.com/agents-discover.json

# Output (trimmed):
# 📥 Fetching organizations...
# ✅ Found 10 organization(s)
# [ 1] 🖼️ Alpha Labs      [ 2] 🖼️ Beta Group      [ 3] Gamma Corp
# [ 4] Delta Ventures    [ 5] 🖼️ Epsilon Studio   [ 6] Zeta Partners
# ...
# 🔢 Enter organization number: 3
# ✅ Selected: Gamma Corp
# 📥 Loading agent configuration...
# 🔍 Resolving agent IDs...
# ✅ Resolved 3 agent ID(s)
# ⚙️  Assigning agents to organization...
# ✅ Agents assigned successfully!
```

**Agent JSON requirements:**
- Provide a `url` for each agent so the CLI can search and resolve the Spritz agent ID.
- Other agent fields are ignored for assignment but help with readability in logs.

---

### `spx validate`

Validate profile configuration and authentication.

**Usage:**
```bash
spx validate [--profile PROFILE]
```

**Example:**
```bash
spx validate --profile prod

# Output:
# ✓ Profile 'prod' is valid
#   Spritz URL: https://spritz.activate.bar
#   API URL: https://api.spritz.activate.bar
#   Token: ****************************************...tQuDQ
#   User: pradeep@incaendo.com
#   Organization: 64a54a30899afb66425722fc
```

**What it checks:**
- Profile exists
- Spritz URL is configured
- API URL is configured
- Authentication token is present
- Token is valid and not expired
- User information is accessible

---

### Preview Before Deploy (Dry Run)

Test your deployment without making changes using the `--dry-run` flag.

**Agent Onboarding (Dry Run):**
```bash
spx agent-onboarding \
  --profile prod \
  --url https://config.example.com/agents.json \
  --dry-run

# Output:
# ⚠️  DRY RUN MODE - No changes will be made
# 
# 📦 Agent Configurations:
#   [1] Customer Support Agent
#   [2] Sales Assistant
# 
# 🔍 [DRY RUN] Would create the above agents
#    Endpoint: POST https://api.spritz.activate.bar/v1/agent/create
```

**Agent Update (Dry Run):**
```bash
spx agent-update \
  --profile prod \
  --url http://localhost:8000/agent \
  --dry-run

# Output:
# ⚠️  DRY RUN MODE - No changes will be made
# 
# 🔧 DRY RUN: Would PATCH the following data:
# {
#   "name": "Customer Support Agent",
#   "url": "http://localhost:8000/agent",
#   "type": "chat"
# }
#    Endpoint: PATCH https://api.spritz.activate.bar/v1/agent/6925db4a0ad000cbdfa44cb5
```

---

## 🔄 Complete Workflow

### Development to Production Pipeline
```bash
# 1. Configure environments
spx configure --profile dev
spx configure --profile prod

# 2. Login to both environments
spx login --profile dev
spx login --profile prod

# 3. Deploy to dev first (test environment)
spx agent-onboarding \
  --profile dev \
  --url https://config-dev.example.com/agents.json

# 4. Test your agents in dev
# ... manual testing ...

# 5. Preview production deployment
spx agent-onboarding \
  --profile prod \
  --url https://config-prod.example.com/agents.json \
  --dry-run

# 6. Deploy to production
spx agent-onboarding \
  --profile prod \
  --url https://config-prod.example.com/agents.json

# 7. Update agents when configuration changes
spx agent-update \
  --profile prod \
  --url https://config-prod.example.com/agents.json
```

---

## 🐛 Troubleshooting

### "Profile not found"

**Problem:** Profile hasn't been configured.

**Solution:**
```bash
spx configure --profile prod
```

---

### "Token expired" or "Authentication failed"

**Problem:** Authentication token has expired or is invalid.

**Solution:**
```bash
# Re-authenticate
spx login --profile prod
```

---

### "Agent not found" (during update)

**Problem:** Agent doesn't exist in Spritz or URL doesn't match.

**Solution:**
```bash
# Option 1: Create the agent first
spx agent-onboarding --profile prod --url https://config.example.com/agent.json

# Option 2: Verify the agent exists and URL matches
spx whoami --profile prod
```

---

### "Connection Error" or "Connection refused"

**Problem:** Agent server is not running or URL is incorrect.

**Solution:**
```bash
# Check if your agent server is running
curl http://localhost:8000/agent

# Test with dry-run first
spx agent-onboarding --profile dev --url http://localhost:8000/agent --dry-run

# Verify the URL is correct and accessible
```

---

### "Request Timeout"

**Problem:** Server is taking too long to respond.

**Solution:**
```bash
# Check server response time
curl -w "@curl-format.txt" -o /dev/null -s http://localhost:8000/agent

# Increase timeout by contacting support
# Or optimize your agent's response time
```

---

### "Browser doesn't close automatically"

**Problem:** Browser automation didn't complete properly.

**Solution:**
- Close the browser window manually after seeing the success message
- Token has already been saved to your configuration

---

### "Cannot connect to localhost:8765"

**Problem:** Port 8765 is already in use.

**Solution:**
```bash
# Check what's using the port
lsof -i :8765

# Kill the process if needed
kill -9 <PID>

# Try login again
spx login --profile prod
```

---

### Reset Everything

**Remove all configuration and credentials:**
```bash
rm -rf ~/.spx
```

**Uninstall CLI:**
```bash
pip uninstall spritz-cli -y
```

**Complete reinstall:**
```bash
# 1. Uninstall
pip uninstall spritz-cli -y
rm -rf ~/.spx

# 2. Reinstall
pip install spritz-cli

# 3. Reconfigure
spx configure --profile default
spx login --profile default
```

---

## 💻 Development

### Project Structure
```
spritz-cli/
├── spritz.py              # Main CLI entry point
├── setup.py               # Package configuration
├── pyproject.toml         # Build configuration
├── requirements.txt       # Dependencies
├── README.md              # This file
├── LICENSE                # MIT License
├── MANIFEST.in            # Package manifest
├── publish.sh             # Publishing script
├── src/
│   ├── __init__.py
│   ├── config.py          # Configuration management
│   ├── auth.py            # Authentication handling
│   ├── utils.py           # Utility functions
│   └── commands/
│       ├── __init__.py
│       ├── configure.py   # Configure command
│       ├── login.py       # Login command
│       ├── onboarding.py  # Agent onboarding & update
│       └── info.py        # whoami, list-profiles, validate
└── tests/
    └── test_cli.py        # Unit tests
```

---

### Getting Started

**1. Clone the repository:**
```bash
git clone https://github.com/Activate-Intelligence/spritz-cli.git
cd spritz-cli
```

**2. Create virtual environment:**
```bash
python3 -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
```

**3. Install dependencies:**
```bash
pip install -r requirements.txt
```

**4. Install in editable mode:**
```bash
pip install -e .
```

**5. Test the CLI:**
```bash
spx --version
spx --help
```

**6. Run tests:**
```bash
pytest tests/
```

---

### Publishing to PyPI

#### Quick Publish

Make the script executable (first time only):
```bash
chmod +x publish.sh
```

Publish to PyPI:
```bash
./publish.sh
```

Publish to TestPyPI (for testing):
```bash
./publish.sh --test
```

#### Manual Publishing

**Install build tools:**
```bash
pip install --upgrade pip build twine
```

**Clean and build:**
```bash
rm -rf dist/ build/ *.egg-info
python -m build
```

**Check the package:**
```bash
twine check dist/*
```

**Upload to TestPyPI (recommended first):**
```bash
twine upload --repository testpypi dist/*
```

**Test installation:**
```bash
pip install --index-url https://test.pypi.org/simple/ spritz-cli
```

**Upload to PyPI:**
```bash
twine upload dist/*
```

**Verify:**
```bash
pip install spritz-cli
spx --version
```

#### Troubleshooting Publishing

**Package name already taken:**

Update `setup.py`:
```python
setup(
    name='spritz-ai-cli',  # Or 'incaendo-spritz-cli'
    version='1.0.0',
    # ... rest of configuration
)
```

Then rebuild and publish:
```bash
rm -rf dist/ build/ *.egg-info
python -m build
twine upload dist/*
```

**Upload with verbose output:**
```bash
twine upload dist/* --verbose
```

**Clear pip cache:**
```bash
pip cache purge
pip install spritz-cli --no-cache-dir
```

**Verify package exists:**
```bash
curl -I https://pypi.org/project/spritz-cli/ | grep HTTP
```

---

### PyPI Credentials

**Create API Token:**

1. Go to https://pypi.org/manage/account/token/
2. Click "Add API token"
3. Name: `spritz-cli-upload`
4. Scope: "Entire account" or specific project
5. Copy the token (starts with `pypi-`)

**Save credentials:**
```bash
cat > ~/.pypirc << 'EOF'
[distutils]
index-servers =
    pypi
    testpypi

[pypi]
username = __token__
password = pypi-YOUR-TOKEN-HERE

[testpypi]
username = __token__
password = pypi-YOUR-TESTPYPI-TOKEN-HERE
repository = https://test.pypi.org/legacy/
EOF

chmod 600 ~/.pypirc
```

**Using environment variables:**
```bash
export TWINE_USERNAME=__token__
export TWINE_PASSWORD=pypi-YOUR-TOKEN-HERE
twine upload dist/*
```

---

## 🤖 Automation Scripts

### Shell Scripts

**`agent-onboarding.sh`** - Onboard agents without assuming authentication
```bash
#!/bin/bash

# Configuration
PROFILE="prod"
AGENT_URL="http://localhost:8000/agent"

echo "🚀 Spritz Agent Onboarding Automation"
echo "======================================"

# Check if spx is installed
if ! command -v spx &> /dev/null; then
    echo "❌ Error: spritz-cli is not installed"
    echo "Install with: pip install spritz-cli"
    exit 1
fi

# Check if profile exists
if ! spx list-profiles 2>/dev/null | grep -q "$PROFILE"; then
    echo "⚙️  Configuring profile: $PROFILE"
    spx configure --profile "$PROFILE"
fi

# Check authentication
echo "🔐 Checking authentication..."
if ! spx validate --profile "$PROFILE" &>/dev/null; then
    echo "🔑 Authentication required"
    spx login --profile "$PROFILE"
fi

# Onboard agents
echo "📦 Onboarding agents from: $AGENT_URL"
spx agent-onboarding --profile "$PROFILE" --url "$AGENT_URL"

if [ $? -eq 0 ]; then
    echo "✅ Agent onboarding completed successfully!"
else
    echo "❌ Agent onboarding failed!"
    exit 1
fi
```

**Make it executable:**
```bash
chmod +x agent-onboarding.sh
```

**Usage:**
```bash
./agent-onboarding.sh
```

---

**`agent-update.sh`** - Update agents without assuming authentication
```bash
#!/bin/bash

# Configuration
PROFILE="prod"
AGENT_URL="http://localhost:8000/agent"

echo "🔄 Spritz Agent Update Automation"
echo "=================================="

# Check if spx is installed
if ! command -v spx &> /dev/null; then
    echo "❌ Error: spritz-cli is not installed"
    echo "Install with: pip install spritz-cli"
    exit 1
fi

# Check if profile exists
if ! spx list-profiles 2>/dev/null | grep -q "$PROFILE"; then
    echo "⚙️  Configuring profile: $PROFILE"
    spx configure --profile "$PROFILE"
fi

# Check authentication
echo "🔐 Checking authentication..."
if ! spx validate --profile "$PROFILE" &>/dev/null; then
    echo "🔑 Authentication required"
    spx login --profile "$PROFILE"
fi

# Update agents
echo "🔄 Updating agent from: $AGENT_URL"
spx agent-update --profile "$PROFILE" --url "$AGENT_URL"

if [ $? -eq 0 ]; then
    echo "✅ Agent update completed successfully!"
else
    echo "❌ Agent update failed!"
    exit 1
fi
```

**Make it executable:**
```bash
chmod +x agent-update.sh
```

**Usage:**
```bash
./agent-update.sh
```

---

### Python Scripts

**`agent-onboarding.py`** - Python automation for agent onboarding
```python
#!/usr/bin/env python3
"""
Spritz Agent Onboarding Automation
Handles authentication automatically before onboarding
"""

import subprocess
import sys

# Configuration
PROFILE = "prod"
AGENT_URL = "http://localhost:8000/agent"

def run_command(cmd):
    """Run shell command and return result"""
    try:
        result = subprocess.run(
            cmd,
            shell=True,
            capture_output=True,
            text=True,
            check=False
        )
        return result.returncode == 0, result.stdout, result.stderr
    except Exception as e:
        return False, "", str(e)

def check_spx_installed():
    """Check if spx CLI is installed"""
    success, _, _ = run_command("spx --version")
    return success

def check_profile_exists(profile):
    """Check if profile is configured"""
    success, output, _ = run_command("spx list-profiles")
    return success and profile in output

def check_authentication(profile):
    """Check if user is authenticated"""
    success, _, _ = run_command(f"spx validate --profile {profile}")
    return success

def configure_profile(profile):
    """Configure a new profile"""
    print(f"⚙️  Configuring profile: {profile}")
    success, _, _ = run_command(f"spx configure --profile {profile}")
    return success

def login(profile):
    """Login to profile"""
    print(f"🔑 Logging in to: {profile}")
    success, _, _ = run_command(f"spx login --profile {profile}")
    return success

def onboard_agent(profile, url):
    """Onboard agent"""
    print(f"📦 Onboarding agent from: {url}")
    cmd = f"spx agent-onboarding --profile {profile} --url {url}"
    result = subprocess.run(cmd, shell=True)
    return result.returncode == 0

def main():
    print("🚀 Spritz Agent Onboarding Automation")
    print("=" * 40)
    
    # Check if spx is installed
    if not check_spx_installed():
        print("❌ Error: spritz-cli is not installed")
        print("Install with: pip install spritz-cli")
        sys.exit(1)
    
    # Check if profile exists
    if not check_profile_exists(PROFILE):
        if not configure_profile(PROFILE):
            print(f"❌ Failed to configure profile: {PROFILE}")
            sys.exit(1)
    
    # Check authentication
    print("🔐 Checking authentication...")
    if not check_authentication(PROFILE):
        if not login(PROFILE):
            print("❌ Authentication failed")
            sys.exit(1)
    
    # Onboard agent
    if onboard_agent(PROFILE, AGENT_URL):
        print("✅ Agent onboarding completed successfully!")
        sys.exit(0)
    else:
        print("❌ Agent onboarding failed!")
        sys.exit(1)

if __name__ == "__main__":
    main()
```

**Make it executable:**
```bash
chmod +x agent-onboarding.py
```

**Usage:**
```bash
python3 agent-onboarding.py
```

---

**`agent-update.py`** - Python automation for agent updates
```python
#!/usr/bin/env python3
"""
Spritz Agent Update Automation
Handles authentication automatically before updating
"""

import subprocess
import sys

# Configuration
PROFILE = "prod"
AGENT_URL = "http://localhost:8000/agent"

def run_command(cmd):
    """Run shell command and return result"""
    try:
        result = subprocess.run(
            cmd,
            shell=True,
            capture_output=True,
            text=True,
            check=False
        )
        return result.returncode == 0, result.stdout, result.stderr
    except Exception as e:
        return False, "", str(e)

def check_spx_installed():
    """Check if spx CLI is installed"""
    success, _, _ = run_command("spx --version")
    return success

def check_profile_exists(profile):
    """Check if profile is configured"""
    success, output, _ = run_command("spx list-profiles")
    return success and profile in output

def check_authentication(profile):
    """Check if user is authenticated"""
    success, _, _ = run_command(f"spx validate --profile {profile}")
    return success

def configure_profile(profile):
    """Configure a new profile"""
    print(f"⚙️  Configuring profile: {profile}")
    success, _, _ = run_command(f"spx configure --profile {profile}")
    return success

def login(profile):
    """Login to profile"""
    print(f"🔑 Logging in to: {profile}")
    success, _, _ = run_command(f"spx login --profile {profile}")
    return success

def update_agent(profile, url):
    """Update agent"""
    print(f"🔄 Updating agent from: {url}")
    cmd = f"spx agent-update --profile {profile} --url {url}"
    result = subprocess.run(cmd, shell=True)
    return result.returncode == 0

def main():
    print("🔄 Spritz Agent Update Automation")
    print("=" * 40)
    
    # Check if spx is installed
    if not check_spx_installed():
        print("❌ Error: spritz-cli is not installed")
        print("Install with: pip install spritz-cli")
        sys.exit(1)
    
    # Check if profile exists
    if not check_profile_exists(PROFILE):
        if not configure_profile(PROFILE):
            print(f"❌ Failed to configure profile: {PROFILE}")
            sys.exit(1)
    
    # Check authentication
    print("🔐 Checking authentication...")
    if not check_authentication(PROFILE):
        if not login(PROFILE):
            print("❌ Authentication failed")
            sys.exit(1)
    
    # Update agent
    if update_agent(PROFILE, AGENT_URL):
        print("✅ Agent update completed successfully!")
        sys.exit(0)
    else:
        print("❌ Agent update failed!")
        sys.exit(1)

if __name__ == "__main__":
    main()
```

**Make it executable:**
```bash
chmod +x agent-update.py
```

**Usage:**
```bash
python3 agent-update.py
```

---

### Using Scripts in CI/CD

**GitHub Actions Example:**
```yaml
name: Deploy Agent

on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.11'
      
      - name: Install Spritz CLI
        run: pip install spritz-cli
      
      - name: Configure Spritz
        run: |
          mkdir -p ~/.spx
          echo "[profile prod]" > ~/.spx/config
          echo "spritz_url = https://spritz.activate.bar" >> ~/.spx/config
          echo "api_url = https://api.spritz.activate.bar" >> ~/.spx/config
      
      - name: Set Credentials
        run: |
          echo "${{ secrets.SPRITZ_TOKEN }}" > ~/.spx/credentials_prod
        env:
          SPRITZ_TOKEN: ${{ secrets.SPRITZ_TOKEN }}
      
      - name: Deploy Agent
        run: |
          python3 agent-onboarding.py
```

**GitLab CI Example:**
```yaml
deploy_agent:
  stage: deploy
  image: python:3.11
  before_script:
    - pip install spritz-cli
    - mkdir -p ~/.spx
    - echo "[profile prod]" > ~/.spx/config
    - echo "spritz_url = https://spritz.activate.bar" >> ~/.spx/config
    - echo "api_url = https://api.spritz.activate.bar" >> ~/.spx/config
    - echo "$SPRITZ_TOKEN" > ~/.spx/credentials_prod
  script:
    - python3 agent-onboarding.py
  only:
    - main
```

---

## 🔐 Security Best Practices

### Local Development
```bash
# Use dev profile for local testing
spx configure --profile dev
spx login --profile dev
spx agent-onboarding --profile dev --url http://localhost:8000/agent
```

### Production
```bash
# Always verify before deploying to prod
spx agent-onboarding --profile prod --url https://prod.example.com/agent --dry-run

# Deploy after verification
spx agent-onboarding --profile prod --url https://prod.example.com/agent
```

### CI/CD

- Store tokens as encrypted secrets
- Use separate profiles for different environments
- Rotate tokens regularly
- Never commit tokens to version control

### Token Management
```bash
# Check token status
spx validate --profile prod

# Re-authenticate when needed
spx login --profile prod

# Logout to remove token
rm ~/.spx/credentials_prod
```

---

## 🤝 Contributing

We welcome contributions! Here's how to get started:

### Development Setup
```bash
# Fork and clone the repository
git clone https://github.com/YOUR-USERNAME/spritz-cli.git
cd spritz-cli

# Create virtual environment
python3 -m venv venv
source venv/bin/activate

# Install in development mode
pip install -e .

# Install development dependencies
pip install pytest black flake8 mypy

# Run tests
pytest tests/

# Format code
black .

# Lint code
flake8 .
```

### Making Changes

1. Create a feature branch: `git checkout -b feature/amazing-feature`
2. Make your changes
3. Add tests for new features
4. Run tests: `pytest tests/`
5. Commit changes: `git commit -m 'Add amazing feature'`
6. Push to branch: `git push origin feature/amazing-feature`
7. Open a Pull Request
---

## 📚 Additional Resources

### Documentation

- **Spritz Platform:** https://docs.spritz.ai
- **API Documentation:** https://api.spritz.activate.bar/docs
- **GitHub Repository:** https://github.com/Activate-Intelligence/spritz-cli

### Support

- **Issues:** https://github.com/Activate-Intelligence/spritz-cli/issues
- **Email:** support@incaendo.com

---

## 📝 Changelog

### v1.0.0 (2024-12-02)

**Initial Release**

- ✅ Profile-based configuration management
- ✅ Browser-based authentication
- ✅ Agent onboarding from URL
- ✅ Agent updates from URL
- ✅ Multiple environment support (dev, prod)
- ✅ Dry-run mode for safe previews
- ✅ Automatic token refresh
- ✅ Comprehensive error handling

---

## 🙏 Acknowledgments

- **Click** - Beautiful command line interfaces
- **Requests** - HTTP library for Python
- **PyYAML** - YAML parser and emitter

Built with ❤️ by the Incaendo Technology Team

---

**Quick Links:**

- 📦 [PyPI Package](https://pypi.org/project/spritz-cli/)
- 💻 [GitHub Repository](https://github.com/Activate-Intelligence/spritz-cli)
- 🐛 [Report Issues](https://github.com/Activate-Intelligence/spritz-cli/issues)
- ⭐ [Star on GitHub](https://github.com/Activate-Intelligence/spritz-cli)

---
