# CLI Authentication Guide

## Overview

The VassaAI SDK now includes a CLI tool with browser-based Google Sign-In authentication. Users can authenticate once and use the CLI without manually copying tokens.

## How It Works

1. **User runs CLI command** (e.g., `vassa query "What is AI?"`)
2. **SDK checks for stored credentials** in `~/.vassa/credentials.json`
3. **If not authenticated:**
   - Opens browser to your VassaAI app
   - User signs in with Google
   - Token is captured and stored locally
4. **CLI uses stored token** for API requests

## Setup Required

### Backend Changes

You need to add a CLI authentication endpoint to your backend:

```python
# backend/main.py

@app.get("/auth/cli")
async def cli_auth(callback: str):
    """
    CLI authentication page.
    Opens Firebase auth, then redirects to callback with token.
    """
    return FileResponse("frontend/dist/cli-auth.html")
```

### Frontend Changes

Create `frontend/src/cli-auth.html`:

```html
<!DOCTYPE html>
<html>
<head>
    <title>VassaAI - CLI Authentication</title>
    <script src="https://www.gstatic.com/firebasejs/9.0.0/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/9.0.0/firebase-auth-compat.js"></script>
</head>
<body>
    <h1>Authenticating...</h1>
    <p>Please sign in with Google</p>
    
    <script>
        // Initialize Firebase (use your config)
        const firebaseConfig = {
            // Your Firebase config here
        };
        firebase.initializeApp(firebaseConfig);
        
        // Get callback URL from query params
        const urlParams = new URLSearchParams(window.location.search);
        const callbackUrl = urlParams.get('callback');
        
        // Sign in with Google
        const provider = new firebase.auth.GoogleAuthProvider();
        firebase.auth().signInWithPopup(provider)
            .then((result) => {
                // Get ID token
                return result.user.getIdToken();
            })
            .then((token) => {
                // Redirect to callback with token
                window.location.href = `${callbackUrl}?token=${token}`;
            })
            .catch((error) => {
                document.body.innerHTML = `<h1>Error</h1><p>${error.message}</p>`;
            });
    </script>
</body>
</html>
```

## CLI Usage

### Installation

```bash
pip install vassa-ai
```

### Authentication

```bash
# Sign in (opens browser)
vassa login

# Check authentication status
vassa whoami

# Sign out
vassa logout
```

### Querying

```bash
# Send a query
vassa query "What is artificial intelligence?"

# Continue a conversation
vassa query "Tell me more" -c conv-123

# Non-streaming mode
vassa query "What is AI?" --no-stream
```

### Managing Conversations

```bash
# List all conversations
vassa conversations

# Search conversations
vassa search "machine learning"
```

### Usage Statistics

```bash
# Check your usage
vassa usage
```

## CLI Commands Reference

```
vassa --help                    # Show all commands
vassa login                     # Sign in with Google
vassa logout                    # Sign out
vassa whoami                    # Check auth status
vassa query MESSAGE             # Send a query
vassa query MESSAGE -c ID       # Continue conversation
vassa conversations             # List conversations
vassa search QUERY              # Search conversations
vassa usage                     # Show usage stats
```

## Configuration

### Custom API URL

```bash
vassa --base-url http://localhost:8001 query "test"
```

### Stored Credentials

Credentials are stored in `~/.vassa/credentials.json` with user-only permissions (chmod 600).

## Security

- Tokens are stored locally with restricted permissions
- Browser-based OAuth flow (no password in CLI)
- Tokens can be revoked via `vassa logout`
- Same Firebase authentication as web app

## Alternative: Manual Token

If you prefer not to use the browser flow:

```bash
# Set token manually
export Vassa_API_KEY="your-firebase-token"

# Use CLI
vassa query "What is AI?"
```

## Troubleshooting

### "Authentication failed"
- Make sure your backend is running
- Check that the `/auth/cli` endpoint exists
- Verify Firebase is configured correctly

### "Port already in use"
- The CLI uses port 8765 for OAuth callback
- Close any application using that port
- Or wait a few seconds and try again

### "Token expired"
- Run `vassa logout` then `vassa login`
- Firebase tokens expire after 1 hour
- The CLI will prompt for re-authentication

## For Developers

### Testing Locally

```bash
# Start your backend
cd backend && uv run uvicorn main:app --reload --port 8001

# Use CLI with local backend
vassa --base-url http://localhost:8001 query "test"
```

### Implementing the Backend Endpoint

See the example code above for adding the `/auth/cli` endpoint to your FastAPI backend.
