# CodeAgent Mode Fixes

## Summary
Fixed two critical issues with the `codeagent` CLI command that prevented it from working properly.

## Issues Fixed

### Issue 1: No Default Model (Required `-m` Flag)

**Problem:**
- The `codeagent` command required the `-m/--model` flag to be specified
- Running `agentgog codeagent "your prompt"` without `-m` would fail with: "Error: Missing option '--model' / '-m'"
- Other commands like `chat` support default models, but `codeagent` did not

**Solution:**
- Changed `--model` flag from `required=True` to `default=None`
- Added automatic provider-specific default model selection:
  - OpenRouter: `x-ai/grok-4.1-fast`
  - Ollama: `llama3.2`
- Users can now run: `agentgog codeagent "What is Python?"` without specifying `-m`
- Explicit `-m` flag still works to override the default

**Files Changed:**
- `src/agentgog/cli.py` (lines 454-479)

**Testing:**
```bash
# Now works without -m flag
uv run agentgog codeagent "Write a Python function to calculate fibonacci"

# Still works with -m flag
uv run agentgog codeagent "Explain quantum physics" -m google/gemma-3-27b-it:free
```

---

### Issue 2: Google Gemini Authentication Error (401 Cookie Credentials)

**Problem:**
- Using Google Gemini models like `google/gemini-2.5-flash` with CodeAgent resulted in:
  ```
  Error code: 401 - {'error': {'message': 'No cookie auth credentials found', 'code': 401}}
  ```
- The error message was unhelpful and didn't indicate the root cause
- Users were confused about why a valid OpenRouter model was failing

**Root Cause:**
- Google Gemini models require direct authentication with Google's API
- When accessed through OpenRouter's OpenAI-compatible API endpoint, they attempt to use cookie-based Google authentication (designed for web browsers)
- This authentication method is incompatible with API key-based access through OpenRouter
- The `smolagents` library passes through whatever error Google's API returns

**Solution:**
Implemented comprehensive error handling and user guidance:

1. **Early Validation:**
   - Check if `OPENROUTER_API_KEY` is set before attempting to run CodeAgent
   - Provide clear error message if not set

2. **Model Compatibility Warnings:**
   - Detect if user is attempting to use a Google Gemini model
   - Display a warning that these models may not work reliably with CodeAgent
   - Suggest compatible alternatives

3. **Improved Error Messages:**
   - Catch 401 "cookie auth" errors specifically
   - Provide user-friendly error message explaining the issue
   - Suggest compatible alternative models
   - Show example of how to fix the problem

4. **Better Error Context:**
   - Wrapped model execution in try-catch
   - Log error status to event logging
   - Convert cryptic API errors into actionable guidance

**Files Changed:**
- `src/agentgog/smol_codeagent.py` (lines 1-145)
  - Added logging support
  - Added Gemini model list with known limitations
  - Added upfront API key validation
  - Added Gemini model warning
  - Wrapped execution in try-catch with specific error handling
  - Improved error messages with suggestions

**Recommended Models for CodeAgent:**
Instead of Gemini models, use these alternatives that work reliably:
- `google/gemma-3-27b-it:free` (Google Gemma model - free)
- `xiaomi/mimo-v2-flash:free` (Xiaomi MiMo model - free)
- `nex-agi/deepseek-v3.1-nex-n1:free` (Deepseek model - free)
- `x-ai/grok-4.1-fast` (Default for OpenRouter)
- `llama3.2` (Default for Ollama)

**Testing:**
```bash
# Gemini models (not recommended for CodeAgent)
# Will show warning but may still fail with authentication error
uv run agentgog codeagent "Test" -m google/gemini-2.5-flash

# Recommended alternatives (should work)
uv run agentgog codeagent "Write a Python function" -m google/gemma-3-27b-it:free
uv run agentgog codeagent "Solve a math problem" -m xiaomi/mimo-v2-flash:free
```

---

## Updated Documentation

### TASKS.md Updates:
- Updated `codeagent` command documentation to reflect optional `-m` flag
- Added supported flags and options
- Added known constraints section documenting Gemini limitations
- Added CodeAgent usage examples
- Added Ollama support documentation

### Error Messages Provided:
Users will now see helpful guidance when:
1. `OPENROUTER_API_KEY` is not set
2. A Gemini model is selected (warning + suggestions)
3. A 401 authentication error occurs (explanation + alternatives)

---

## Implementation Details

### API Key Validation
```python
if provider == "openrouter" and not os.environ.get("OPENROUTER_API_KEY"):
    raise ValueError("OPENROUTER_API_KEY environment variable is not set...")
```

### Model Compatibility Warning
```python
GEMINI_MODELS = [
    "google/gemini-2.5-flash",
    "google/gemini-2.5-pro",
    # ... (added for early detection)
]

if any(gemini_model in model_id for gemini_model in GEMINI_MODELS):
    logger.warning(f"WARNING: Google Gemini models may not work reliably...")
```

### Error Handling
```python
try:
    # ... model execution ...
except Exception as e:
    error_msg = str(e)
    if "401" in error_msg and "cookie" in error_msg.lower():
        raise RuntimeError(
            f"Authentication error with model '{model_id}'...\n"
            "Try using: google/gemma-3-27b-it:free, ..."
        ) from e
```

---

## Breaking Changes
None. The changes are backwards compatible:
- Commands with explicit `-m` flag continue to work unchanged
- Commands without `-m` flag now work (previously failed)
- Error messages are improved but don't affect functionality

---

## Related Issues
- Issue 1 was a usability problem (missing default model)
- Issue 2 is a known limitation of Google Gemini models with OpenRouter
  - Not a bug in agentgog, but a limitation of Gemini's authentication
  - Fixed by providing clear guidance and alternatives
