> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ccs.kaitran.ca/llms.txt
> Use this file to discover all available pages before exploring further.

# Gemini Provider

> Google Gemini OAuth provider with automatic CLIProxy-managed refresh and model selection

# Gemini Provider

Access Google Gemini models via OAuth authentication with automatic token management and interactive model configuration.

## Quick Start

```bash theme={null}
# First run (browser opens for OAuth)
ccs gemini "explain this code"

# Select model interactively
ccs gemini --config

# Use specific account
ccs gemini --use work
```

## Authentication

### Initial Setup

<Steps>
  <Step title="First Run">
    Run `ccs gemini "your prompt"` - browser opens automatically
  </Step>

  <Step title="Google OAuth">
    Sign in with your Google account
  </Step>

  <Step title="Token Cached">
    OAuth token saved to `~/.ccs/cliproxy/auth/gemini-{email}.json`
  </Step>

  <Step title="Auto Refresh">
    Token refresh is handled automatically by CLIProxy
  </Step>
</Steps>

### OAuth Flow Specifics

**Authorization Code Flow:**

* Callback server spawns on provider-specific port
* Browser opens for Google OAuth consent
* Token received via HTTP callback
* Runtime-managed refresh prevents mid-request failures

**Automatic Token Refresh:**

* refresh ownership is delegated upstream to CLIProxy
* CCS verifies that local auth material still exists
* prevents common mid-session auth failures without requiring manual refresh in normal flows
* prompts for re-auth if upstream refresh can no longer recover the session

### Headless Authentication

For servers without browser access:

```bash theme={null}
ccs gemini --headless

# Output:
# Open this URL on any device:
# https://accounts.google.com/o/oauth2/auth?...
#
# Waiting for authentication...
```

Complete OAuth on another device - CCS detects when token is cached.

## Multi-Account Support

Manage multiple Google accounts seamlessly:

<Tabs>
  <Tab title="Add Account">
    ```bash theme={null}
    # Add second account (preserves existing)
    ccs gemini --auth --add

    # Auto-nicknamed from email prefix
    # john@gmail.com → "john"
    ```
  </Tab>

  <Tab title="List Accounts">
    ```bash theme={null}
    ccs gemini --accounts

    # Output:
    # Available Gemini accounts:
    # * john (john@gmail.com) - default
    #   work (alice@company.com)
    ```
  </Tab>

  <Tab title="Switch Account">
    ```bash theme={null}
    # Switch default account
    ccs gemini --use work

    # Rename account
    ccs gemini --nickname personal
    ```
  </Tab>
</Tabs>

**Account Registry:** `~/.ccs/cliproxy/accounts.json`

## Real-Time Quota Display

CCS displays real-time quota information for Gemini accounts via Dashboard and CLI.

### Dashboard Display

**Location:** Dashboard → OAuth Providers → Gemini

**Displays:**

* Requests per minute (RPM) usage
* Tokens per minute (TPM) usage
* Requests per day (RPD) usage
* Limit reset times

**Backend Caching:**

* Quota data cached for 2 minutes to reduce API load
* Automatic re-authentication if token expired
* Dashboard shows cached timestamp

### CLI Quota Check

```bash theme={null}
# View quota for all Gemini accounts
ccs cliproxy quota --provider gemini

# Output:
# Gemini Quota (as of 2026-02-04 18:00:00):
#   john@gmail.com:
#     RPM: 45/60 requests (resets in 30s)
#     TPM: 28000/32000 tokens (resets in 30s)
#     RPD: 890/1500 requests (resets in 6h)
```

**Features:**

* Displays all authenticated Gemini accounts
* Shows cached timestamp (2-minute cache)
* Proactive token refresh (5 minutes before expiry)

**Quota Response Caching:**

CCS caches quota responses to prevent excessive API calls:

| Cache Duration | Applies To                                          |
| -------------- | --------------------------------------------------- |
| 2 minutes      | Quota data (usage counts, reset times)              |
| Token refresh  | Proactive (5min before expiry, matches CLIProxyAPI) |

**Cache Location:** In-memory (not persisted to disk)

## Tool Name Sanitization

Gemini enforces a 64-character limit on tool names. CCS automatically handles this via ToolSanitizationProxy.

### The Problem

Claude MCP tools can have names exceeding 64 characters:

```
mcp__filesystem__read_multiple_files  # 37 chars - OK
mcp__sequential-thinking__recordThoughtSequence  # 50 chars - OK
mcp__very-long-server-name__someVeryLongToolNameHere  # 70+ chars - FAILS
```

**Gemini API Error:** "Invalid tool name: must be 64 characters or fewer"

### How CCS Fixes It

**ToolSanitizationProxy** intercepts requests and:

1. Detects tool names exceeding 64 characters
2. Creates short hashes using `<prefix>_<6-char-md5>` format (e.g., `mcp__long-server__toolName` → `mcp___a1b2c3`)
3. Maintains bidirectional mapping
4. Restores original names in responses

### Architecture

```
Claude CLI → ToolSanitizationProxy → CLIProxy → Gemini API
             ↓ Sanitize request      ↓ Forward    ↓ Process
             ↑ Restore response      ↑ Return     ↑ Respond
```

**Proxy Lifecycle:**

* Spawned automatically when using Gemini provider
* Runs on random port (127.0.0.1)
* Shuts down with Claude session

### Sanitization Process

**Request Flow:**

```json theme={null}
// Original (Claude CLI sends)
{
  "tools": [
    { "name": "mcp__very-long-server__someVeryLongToolNameThatExceeds64Chars" }
  ]
}

// Sanitized (Proxy → Gemini)
{
  "tools": [
    { "name": "mcp___a1b2c3" }
  ]
}
```

**Response Flow:**

```json theme={null}
// Gemini response
{
  "content": [
    { "type": "tool_use", "name": "mcp___a1b2c3" }
  ]
}

// Restored (Proxy → Claude CLI)
{
  "content": [
    { "type": "tool_use", "name": "mcp__very-long-server__someVeryLongToolNameThatExceeds64Chars" }
  ]
}
```

### Debug Mode

Enable verbose logging to see sanitization activity:

```bash theme={null}
export CCS_DEBUG=1
ccs gemini "use long tool names"

# Logs appear in: ~/.ccs/logs/tool-sanitization-proxy.log
# Console output (if CCS_DEBUG=1):
# [i] ToolSanitizationProxy started on port 54321
# [!] Sanitized 2 tool names (64-char limit)
# [i] Restored 1 tool name in response
```

**Log Location:** `~/.ccs/logs/tool-sanitization-proxy.log`

### When Sanitization Happens

**Automatically enabled for:**

* All CLIProxy providers (gemini, codex, antigravity)
* Any provider configured via `config.cliproxy`

**Why all providers?**

* ToolSanitizationProxy runs for all CLIProxy-based providers to ensure compatibility across different model APIs

### Configuration

Sanitization is automatic and requires no configuration. To disable warnings:

```yaml theme={null}
# config.yaml (not yet implemented - always warns)
cliproxy:
  tool_sanitization:
    warn_on_sanitize: false
```

### Performance Impact

**Minimal overhead:**

* Hash generation: under 1ms per tool
* Request/response transformation: under 5ms
* In-memory mapping (no disk I/O)

**Timeout:** 120 seconds (configurable via `timeoutMs`)

```json theme={null}
{
  "version": 1,
  "providers": {
    "gemini": {
      "default": "john@gmail.com",
      "accounts": {
        "john@gmail.com": {
          "email": "john@gmail.com",
          "nickname": "john",
          "tokenFile": "gemini-john@gmail.com.json",
          "createdAt": "2024-01-01T00:00:00Z",
          "lastUsedAt": "2024-01-05T12:00:00Z"
        }
      }
    }
  }
}
```

## Model Configuration

### Interactive Model Picker

Select Gemini model interactively with `--config` flag:

```bash theme={null}
ccs gemini --config

# Interactive prompt:
# Available models for Gemini:
# 1. Gemini 3 Pro - Recommended (latest model, paid account required)
# 2. Gemini 2.5 Pro - Free tier (works with free Google account)
# Select model [1-2]: 1
```

**First-Run Detection:** If no model configured, prompts automatically before first execution.

### Available Models

| Model ID               | Name           | Tier | Notes                                      |
| ---------------------- | -------------- | ---- | ------------------------------------------ |
| `gemini-3-pro-preview` | Gemini 3 Pro   | Pro  | Latest model, requires paid Google account |
| `gemini-2.5-pro`       | Gemini 2.5 Pro | Free | Stable, works with free Google account     |

<Warning>
  Gemini 3 Pro requires a paid Google account. Use Gemini 2.5 Pro for free tier.
</Warning>

### Model Settings Storage

Settings saved to `~/.ccs/gemini.settings.json`:

```json theme={null}
{
  "model": "gemini-3-pro-high",
  "maxTokens": 8192
}
```

**Priority:** Custom settings → User overrides → Bundled defaults

## Configuration

### Config Keys

Configure via `~/.ccs/config.yaml`:

```yaml theme={null}
# WebSearch integration
websearch:
  providers:
    gemini:
      model: "gemini-2.5-pro"      # Model for WebSearch hook
      timeout: 30000                # CLI timeout (ms)

# CLIProxy settings
cliproxy:
  auth:
    api_key: "ccs-internal-managed"
    management_secret: "ccs"        # Dashboard login password
```

### Environment Variables

<Note>
  These are set automatically by CCS. Manual override rarely needed.
</Note>

```bash theme={null}
# Claude CLI injection (auto-managed)
ANTHROPIC_BASE_URL=http://127.0.0.1:8317/api/provider/gemini
ANTHROPIC_AUTH_TOKEN=ccs-internal-managed
ANTHROPIC_MODEL=gemini-3-pro-high
ANTHROPIC_DEFAULT_OPUS_MODEL=gemini-3-pro-high
ANTHROPIC_DEFAULT_SONNET_MODEL=gemini-3-flash
ANTHROPIC_DEFAULT_HAIKU_MODEL=gemini-3-flash
ANTHROPIC_MAX_TOKENS=8192
```

## Commands Reference

### Basic Usage

```bash theme={null}
# Execute with default model
ccs gemini "your prompt"

# One-shot mode (exit after response)
ccs gemini "explain this function"
```

### Authentication Commands

```bash theme={null}
# Trigger OAuth (no session)
ccs gemini --auth

# Add new account (preserves existing)
ccs gemini --auth --add

# Logout (clear tokens)
ccs gemini --logout

# Headless mode (no browser)
ccs gemini --headless
```

### Account Management

```bash theme={null}
# List all accounts
ccs gemini --accounts

# Switch default account
ccs gemini --use work

# Rename current account
ccs gemini --nickname personal
```

### Configuration

```bash theme={null}
# Interactive model picker
ccs gemini --config

# Dashboard configuration
ccs config
```

## Troubleshooting

### Token Refresh Failures

**Symptom:** `UND_ERR_SOCKET` errors during execution

**Cause:** Token expired mid-request

**Solution:** Proactive refresh handles this automatically. If issue persists:

```bash theme={null}
# Clear and re-authenticate
ccs gemini --logout
ccs gemini --auth
```

### Model Not Working

**Symptom:** API errors, tool call failures

**Cause:** Model incompatible with Claude Code

**Solution:** Change model via `--config`:

```bash theme={null}
ccs gemini --config
# Select "Gemini 3 Pro (High)" - most reliable
```

<Warning>
  Gemini 3 Pro (Preview) has known issues with tool calls. Use "High" variant instead.
</Warning>

### Multiple Accounts Confusion

**Symptom:** Wrong account being used

**Solution:** Check default account:

```bash theme={null}
# View all accounts (default marked with *)
ccs gemini --accounts

# Switch default
ccs gemini --use work
```

### Browser Doesn't Open

**Symptom:** OAuth flow stuck waiting for browser

**Solution:** Use headless mode:

```bash theme={null}
ccs gemini --headless
# Copy URL to browser manually
```

## Storage Locations

| Path                                 | Description                    |
| ------------------------------------ | ------------------------------ |
| `~/.ccs/cliproxy/auth/gemini-*.json` | OAuth tokens (one per account) |
| `~/.ccs/cliproxy/accounts.json`      | Account registry, nicknames    |
| `~/.ccs/gemini.settings.json`        | Model selection, preferences   |
| `~/.ccs/cliproxy/config.yaml`        | CLIProxy configuration         |

## Cost Information

| Tier | Models                                   | Cost                         |
| ---- | ---------------------------------------- | ---------------------------- |
| Free | Gemini 2.5 Pro, Gemini 3 Flash (limited) | \$0                          |
| Paid | Gemini 3 Pro (High/Preview)              | Google subscription required |

**Quota Management:** Automatic rotation if rate limited (config: `quota-exceeded.switch-project: true`)

## Advanced Features

### Token Structure

OAuth token file format (`gemini-{email}.json`):

```json theme={null}
{
  "type": "gemini",
  "access_token": "ya29...",
  "refresh_token": "1//...",
  "email": "user@gmail.com",
  "expired": "2024-12-31T23:59:59Z",
  "expiry_date": 1735689599000
}
```

### Proactive Refresh Logic

1. Before execution: Check `expiry_date`
2. If \< 5 minutes until expiry: Trigger refresh
3. If refresh succeeds: Update token file
4. If refresh fails: Prompt re-auth
5. Execute Claude CLI with valid token

**Why 5 minutes?** Matches CLIProxyAPI behavior, prevents race conditions during long API calls.

## Next Steps

<CardGroup cols={2}>
  <Card title="Multi-Account Setup" icon="users" href="/providers/concepts/overview#multi-account-management">
    Configure multiple Google accounts
  </Card>

  <Card title="Model Selection" icon="sliders" href="/providers/oauth/gemini#model-configuration">
    Choose optimal Gemini model
  </Card>

  <Card title="Remote Proxy" icon="server" href="/features/proxy/remote-proxy">
    Connect to external CLIProxy server
  </Card>

  <Card title="WebSearch Integration" icon="magnifying-glass" href="/features/ai/websearch">
    Enable Gemini-powered web search
  </Card>
</CardGroup>
