docs: reposition Amp CLI as integrated feature for upstream PR

- Update README.md to present Amp CLI as standard feature, not fork differentiator
- Remove USING_WITH_FACTORY_AND_AMP.md (fork-specific, Factory docs live upstream)
- Add comprehensive docs/amp-cli-integration.md with setup, config, troubleshooting
- Eliminate fork justification messaging throughout documentation
- Prepare Amp CLI integration for upstream merge consideration

This positions Amp CLI support as a natural extension of CLIProxyAPI's
multi-client architecture rather than a fork-specific feature.
This commit is contained in:
Ben Vargas
2025-11-19 14:40:38 -07:00
parent 897d108e4c
commit 1fb96f5379
3 changed files with 374 additions and 543 deletions

View File

@@ -1,37 +1,5 @@
# CLI Proxy API
---
## 🔔 Important: Amp CLI Support Fork
**This is a specialized fork of [router-for-me/CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI) that adds support for the Amp CLI tool.**
### Why This Fork Exists
The **Amp CLI** requires custom routing patterns to function properly. The upstream CLIProxyAPI project maintainers opted not to merge Amp-specific routing support into the main codebase.
### Which Version Should You Use?
- **Use this fork** if you want to run **both Factory CLI and Amp CLI** with the same proxy server
- **Use upstream** ([router-for-me/CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI)) if you only need Factory CLI support
### 📖 Complete Setup Guide
**→ [USING_WITH_FACTORY_AND_AMP.md](USING_WITH_FACTORY_AND_AMP.md)** - Comprehensive guide for using this proxy with both Factory CLI (Droid) and Amp CLI and IDE extensions, including OAuth setup, configuration examples, and troubleshooting.
### Key Differences
This fork includes:
-**Amp CLI route aliases** (`/api/provider/{provider}/v1...`)
-**Amp upstream proxy support** for OAuth and management routes
-**Automatic gzip decompression** for Amp upstream responses
-**Smart secret management** with precedence: config > env > file
-**All Factory CLI features** from upstream (fully compatible)
All Amp-specific code is isolated in the `internal/api/modules/amp` module, making it easy to sync upstream changes with minimal conflicts.
---
English | [中文](README_CN.md)
A proxy server that provides OpenAI/Gemini/Claude/Codex compatible API interfaces for CLI.
@@ -57,6 +25,7 @@ Get 10% OFF GLM CODING PLANhttps://z.ai/subscribe?ic=8JVLJQFSKB
- Claude Code support via OAuth login
- Qwen Code support via OAuth login
- iFlow support via OAuth login
- Amp CLI and IDE extensions support with provider routing
- Streaming and non-streaming responses
- Function calling/tools support
- Multimodal input support (text and images)
@@ -72,15 +41,6 @@ Get 10% OFF GLM CODING PLANhttps://z.ai/subscribe?ic=8JVLJQFSKB
- OpenAI-compatible upstream providers via config (e.g., OpenRouter)
- Reusable Go SDK for embedding the proxy (see `docs/sdk-usage.md`)
### Fork-Specific: Amp CLI Support 🔥
- **Full Amp CLI integration** via provider route aliases (`/api/provider/{provider}/v1...`)
- **Amp upstream proxy** for OAuth authentication and management routes
- **Smart secret management** with configurable precedence (config > env > file)
- **Automatic gzip decompression** for Amp upstream responses
- **5-minute secret caching** to reduce file I/O overhead
- **Zero conflict** with Factory CLI - use both tools simultaneously
- **Modular architecture** for easy upstream sync (90% reduction in merge conflicts)
## Getting Started
CLIProxyAPI Guides: [https://help.router-for.me/](https://help.router-for.me/)
@@ -89,6 +49,17 @@ CLIProxyAPI Guides: [https://help.router-for.me/](https://help.router-for.me/)
see [MANAGEMENT_API.md](https://help.router-for.me/management/api)
## Amp CLI Support
CLIProxyAPI includes integrated support for [Amp CLI](https://ampcode.com) and Amp IDE extensions, enabling you to use your Google/ChatGPT/Claude OAuth subscriptions with Amp's coding tools:
- Provider route aliases for Amp's API patterns (`/api/provider/{provider}/v1...`)
- Management proxy for OAuth authentication and account features
- Smart model fallback with automatic routing
- Security-first design with localhost-only management endpoints
**→ [Complete Amp CLI Integration Guide](docs/amp-cli-integration.md)**
## SDK Docs
- Usage: [docs/sdk-usage.md](docs/sdk-usage.md)

View File

@@ -1,501 +0,0 @@
# Using Factory CLI (Droid) and Amp CLI with ChatGPT/Claude Subscriptions (OAuth)
## Why Use Subscriptions Instead of API Keys or Pass-Through Pricing?
Using Factory CLI (droid) or Amp CLI/IDE with this CLIProxyAPI fork lets you leverage your **existing provider subscriptions** (ChatGPT Plus/Pro, Claude Pro/Max) instead of per-token API billing.
**The value proposition is compelling:**
- **ChatGPT Plus/Pro** ($20-200/month) includes substantial use based on 5h and weekly quota limits
- **Claude Pro/Max** ($20-100-200/month) includes substantial Claude Sonnet 4.5 and Opus 4.1 on 5h and weekly quota limits
- **Pay-per-token APIs** can cost 5-10x+ for equivalent usage, even with pass-through pricing and no markup
By using OAuth subscriptions through this proxy, you get significantly better value while using the powerful CLI and IDE harnesses from Factory and AmpCode.
## Disclaimer
- This project is for personal/educational use only. You are solely responsible for how you use it.
- Using reverse proxies or alternate API bases may violate provider Terms of Service (OpenAI, Anthropic, Google, etc.).
- Accounts can be rate-limited, locked, or banned. Credentials and data may be at risk if misconfigured.
- Do not use to resell access, bypass access controls, or otherwise abuse services.
- No warranties. Use at your own risk.
## Summary
- Run Factory CLI (droid) and Amp CLI through a single local proxy server.
- This fork keeps all upstream Factory compatibility and adds Amp-specific support:
- Provider route aliases for Amp: `/api/provider/{provider}/v1...`
- Amp OAuth/management upstream proxy
- Smart secret resolution and automatic gzip handling
- Outcome: one proxy for both tools, minimal switching, clean separation of Amp supporting code from upstream repo.
## Why This Fork?
- Upstream maintainers chose not to include Amp-specific routing to keep scope focused on pure proxy functionality.
- Amp CLI expects Amp-specific alias routes and management endpoints the upstream CLIProxyAPI does not expose.
- This fork adds:
- Route aliases: `/api/provider/{provider}/v1...`
- Amp upstream proxy and OAuth
- Localhost-only access controls for Amp management routes (secure-by-default)
- Amp-specific code is isolated under `internal/api/modules/amp`, reducing merge conflicts with upstream.
## Architecture Overview
### Factory (droid) flow
```mermaid
flowchart LR
A["Factory CLI (droid)"] -->|"OpenAI/Claude-compatible calls"| B["CLIProxyAPI Fork"]
B -->|"/v1/chat/completions<br>/v1/messages<br>/v1/models"| C["Translators/Router"]
C -->|"OAuth tokens"| D[("Providers")]
D -->|"OpenAI Codex / Claude"| E["Responses+Streaming"]
E --> B --> A
```
### Amp flow
```mermaid
flowchart LR
A["Amp CLI"] -->|"/api/provider/provider/v1..."| B["CLIProxyAPI Fork"]
B -->|"Route aliases map to<br>upstream /v1 handlers"| C["Translators/Router"]
A -->|"/api/auth<br>/api/user<br>/api/meta<br>/api/threads..."| B
B -->|"Amp upstream proxy<br>(config: amp-upstream-url)"| F[("ampcode.com")]
C -->|"OpenAI / Anthropic"| D[("Providers")]
D --> B --> A
```
### Notes
- Factory uses standard OpenAI-compatible routes under `/v1/...`.
- Amp uses `/api/provider/{provider}/v1...` plus management routes proxied to `amp-upstream-url`.
- Management routes are restricted to localhost by default.
## Prerequisites
- Go 1.24+
- Active subscriptions:
- **ChatGPT Plus/Pro** (for GPT-5/GPT-5 Codex via OAuth)
- **Claude Pro/Max** (for Claude models via OAuth)
- **Amp** (for Amp CLI features in this fork)
- CLI tools:
- Factory CLI (droid)
- Amp CLI
- Local port `8317` available (or choose your own in config)
## Installation & Build
### Clone and build:
```bash
git clone https://github.com/ben-vargas/ai-cli-proxy-api.git
cd ai-cli-proxy-api
```
**macOS/Linux:**
```bash
go build -o cli-proxy-api ./cmd/server
```
**Windows:**
```bash
go build -o cli-proxy-api.exe ./cmd/server
```
### Homebrew (Factory CLI only):
> **⚠️ Note:** The Homebrew package installs the upstream version without Amp CLI support. Use the git clone method above if you need Amp CLI functionality.
```bash
brew install cliproxyapi
brew services start cliproxyapi
```
## OAuth Setup
Run these commands in the repo folder after building to authenticate with your subscriptions:
### OpenAI (ChatGPT Plus/Pro for GPT-5/Codex):
```bash
./cli-proxy-api --codex-login
```
- Opens browser on port `1455` for OAuth callback
- Requires active ChatGPT Plus or Pro subscription
- Tokens saved to `~/.cli-proxy-api/codex-<email>.json`
### Claude (Anthropic for Claude models):
```bash
./cli-proxy-api --claude-login
```
- Opens browser on port `54545` for OAuth callback
- Requires active Claude Pro or Claude Max subscription
- Tokens saved to `~/.cli-proxy-api/claude-<email>.json`
**Tip:** Add `--no-browser` to print the login URL instead of opening a browser (useful for remote/headless servers).
## Configuration for Factory CLI
Factory CLI uses `~/.factory/config.json` to define custom models. Add entries to the `custom_models` array.
### Complete configuration example
Copy this entire configuration to `~/.factory/config.json` for quick setup:
```json
{
"custom_models": [
{
"model_display_name": "Claude Haiku 4.5 [Proxy]",
"model": "claude-haiku-4-5-20251001",
"base_url": "http://localhost:8317",
"api_key": "dummy-not-used",
"provider": "anthropic"
},
{
"model_display_name": "Claude Sonnet 4.5 [Proxy]",
"model": "claude-sonnet-4-5-20250929",
"base_url": "http://localhost:8317",
"api_key": "dummy-not-used",
"provider": "anthropic"
},
{
"model_display_name": "Claude Opus 4.1 [Proxy]",
"model": "claude-opus-4-1-20250805",
"base_url": "http://localhost:8317",
"api_key": "dummy-not-used",
"provider": "anthropic"
},
{
"model_display_name": "GPT-5.1 Low [Proxy]",
"model": "gpt-5.1-low",
"base_url": "http://localhost:8317/v1",
"api_key": "dummy-not-used",
"provider": "openai"
},
{
"model_display_name": "GPT-5.1 Medium [Proxy]",
"model": "gpt-5.1-medium",
"base_url": "http://localhost:8317/v1",
"api_key": "dummy-not-used",
"provider": "openai"
},
{
"model_display_name": "GPT-5.1 High [Proxy]",
"model": "gpt-5.1-high",
"base_url": "http://localhost:8317/v1",
"api_key": "dummy-not-used",
"provider": "openai"
},
{
"model_display_name": "GPT-5.1 Codex Low [Proxy]",
"model": "gpt-5.1-codex-low",
"base_url": "http://localhost:8317/v1",
"api_key": "dummy-not-used",
"provider": "openai"
},
{
"model_display_name": "GPT-5.1 Codex Medium [Proxy]",
"model": "gpt-5.1-codex-medium",
"base_url": "http://localhost:8317/v1",
"api_key": "dummy-not-used",
"provider": "openai"
},
{
"model_display_name": "GPT-5.1 Codex High [Proxy]",
"model": "gpt-5.1-codex-high",
"base_url": "http://localhost:8317/v1",
"api_key": "dummy-not-used",
"provider": "openai"
},
{
"model_display_name": "GPT-5.1 Codex Mini Medium [Proxy]",
"model": "gpt-5.1-codex-mini-medium",
"base_url": "http://localhost:8317/v1",
"api_key": "dummy-not-used",
"provider": "openai"
},
{
"model_display_name": "GPT-5.1 Codex Mini High [Proxy]",
"model": "gpt-5.1-codex-mini-high",
"base_url": "http://localhost:8317/v1",
"api_key": "dummy-not-used",
"provider": "openai"
}
]
}
```
After configuration, your custom models will appear in the `/model` selector:
![Factory CLI model selector showing custom models](assets/factory_droid_custom_models.png)
### Required fields:
| Field | Required | Description | Example |
|-------|----------|-------------|---------|
| `model_display_name` | ✓ | Human-friendly name shown in `/model` selector | `"Claude Sonnet 4.5 [Proxy]"` |
| `model` | ✓ | Model identifier sent to API | `"claude-sonnet-4-5-20250929"` |
| `base_url` | ✓ | Proxy endpoint | `"http://localhost:8317"` or `"http://localhost:8317/v1"` |
| `api_key` | ✓ | API key (use `"dummy-not-used"` for proxy) | `"dummy-not-used"` |
| `provider` | ✓ | API format type | `"anthropic"`, `"openai"`, or `"generic-chat-completion-api"` |
### Provider-specific base URLs:
| Provider | Base URL | Reason |
|----------|----------|--------|
| `anthropic` | `http://localhost:8317` | Factory appends `/v1/messages` automatically |
| `openai` | `http://localhost:8317/v1` | Factory appends `/responses` (needs `/v1` prefix) |
| `generic-chat-completion-api` | `http://localhost:8317/v1` | For OpenAI Chat Completions compatible models |
### Using custom models:
1. Edit `~/.factory/config.json` with the models above
2. Restart Factory CLI (`droid`)
3. Use `/model` command to select your custom model
## Configuration for Amp CLI
Enable Amp integration (fork-specific):
In `config.yaml`:
```yaml
# Amp CLI integration
amp-upstream-url: "https://ampcode.com"
# Optional override; otherwise uses env or file (see precedence below)
# amp-upstream-api-key: "your-amp-api-key"
# Security: restrict management routes to localhost (recommended)
amp-restrict-management-to-localhost: true
```
### Secret resolution precedence
| Source | Key | Priority |
|-----------------------------------------|----------------------------------|----------|
| Config file | `amp-upstream-api-key` | High |
| Environment | `AMP_API_KEY` | Medium |
| Amp secrets file | `~/.local/share/amp/secrets.json`| Low |
### Set Amp CLI to use this proxy
Edit `~/.config/amp/settings.json` and add the `amp.url` setting:
```json
{
"amp.url": "http://localhost:8317"
}
```
Or set the environment variable:
```bash
export AMP_URL=http://localhost:8317
```
Then login (proxied via `amp-upstream-url`):
```bash
amp login
```
Use Amp as normal:
```bash
amp "Hello, world!"
```
### Supported Amp routes
**Provider Aliases (always available):**
- `/api/provider/openai/v1/chat/completions`
- `/api/provider/openai/v1/responses`
- `/api/provider/anthropic/v1/messages`
- And related provider routes/versions your Amp CLI calls
**Management Routes (require `amp-upstream-url`):**
- `/api/auth`, `/api/user`, `/api/meta`, `/api/internal`, `/api/threads`, `/api/telemetry`
- Localhost-only by default for security
### Works with Amp IDE Extension
This proxy configuration also works with the Amp IDE extension for VSCode and forks (Cursor, Windsurf, etc). Simply set the Amp URL in your IDE extension settings:
1. Open Amp extension settings in your IDE
2. Set **Amp URL** to `http://localhost:8317`
3. Login with your Amp account
4. Start using Amp in your IDE with the same OAuth subscriptions!
![Amp IDE extension settings](assets/amp_ide_extension_amp_url.png)
The IDE extension uses the same routes as the CLI, so both can share the proxy simultaneously.
## Running the Proxy
> **Important:** The proxy requires a config file with `port` set (e.g., `port: 8317`). There is no built-in default port.
### With config file:
```bash
./cli-proxy-api --config config.yaml
```
If `config.yaml` is in the current directory:
```bash
./cli-proxy-api
```
### Tmux (recommended for remote servers):
Running in tmux keeps the proxy alive across SSH disconnects:
**Start proxy in detached tmux session:**
```bash
tmux new-session -d -s proxy -c ~/ai-cli-proxy-api \
"./cli-proxy-api --config config.yaml"
```
**View/attach to proxy session:**
```bash
tmux attach-session -t proxy
```
**Detach from session (proxy keeps running):**
```
Ctrl+b, then d
```
**Stop proxy:**
```bash
tmux kill-session -t proxy
```
**Check if running:**
```bash
tmux has-session -t proxy && echo "Running" || echo "Not running"
```
**Optional: Add to `~/.bashrc` for convenience:**
```bash
alias proxy-start='tmux new-session -d -s proxy -c ~/ai-cli-proxy-api "./cli-proxy-api --config config.yaml" && echo "Proxy started (use proxy-view to attach)"'
alias proxy-view='tmux attach-session -t proxy'
alias proxy-stop='tmux kill-session -t proxy 2>/dev/null && echo "Proxy stopped"'
alias proxy-status='tmux has-session -t proxy 2>/dev/null && echo "✓ Running" || echo "✗ Not running"'
```
### As a service (examples):
**Homebrew:**
```bash
brew services start cliproxyapi
```
**Systemd/Docker:** use your standard service templates; point the binary and config appropriately
### Key config fields (example)
```yaml
port: 8317
auth-dir: "~/.cli-proxy-api"
debug: false
logging-to-file: true
remote-management:
allow-remote: false
secret-key: "" # leave empty to disable management API
disable-control-panel: false
# Amp integration
amp-upstream-url: "https://ampcode.com"
# amp-upstream-api-key: "your-amp-api-key"
amp-restrict-management-to-localhost: true
# Retries and quotas
request-retry: 3
quota-exceeded:
switch-project: true
switch-preview-model: true
```
## Usage Examples
### Factory
**List models:**
```bash
curl http://localhost:8317/v1/models
```
**Chat Completions (Claude):**
```bash
curl -s http://localhost:8317/v1/messages \
-H "Content-Type: application/json" \
-d '{
"model": "claude-sonnet-4-5-20250929",
"messages": [{"role": "user", "content": "Hello"}],
"max_tokens": 1024
}'
```
### Amp
**Provider alias (OpenAI-style):**
```bash
curl -s http://localhost:8317/api/provider/openai/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-5",
"messages": [{"role": "user", "content": "Hello"}]
}'
```
**Management (localhost only by default):**
```bash
curl -s http://localhost:8317/api/user
```
## Troubleshooting
### Common errors and fixes
| Symptom/Code | Likely Cause | Fix |
|------------------------------------------|------------------------------------------------------|----------------------------------------------------------------------|
| 404 /v1/chat/completions | Factory not pointing to proxy base | Set base to `http://localhost:8317/v1` (env/flag/config). |
| 404 /api/provider/... | Incorrect route path or typo | Ensure you're calling `/api/provider/{provider}/v1...` paths exactly.|
| 403 on /api/user (Amp) | Management restricted to localhost | Run from same machine or set `amp-restrict-management-to-localhost: false` (not recommended). |
| 401/403 from provider | Missing/expired OAuth or API key | Re-run the relevant `--*-login` or configure keys in `config.yaml`. |
| 429/Quota exceeded | Project/model quota exhausted | Enable `quota-exceeded` switching or switch accounts. |
| 5xx from provider | Upstream transient error | Increase `request-retry` and try again. |
| SSE/stream stuck | Client not handling SSE properly | Use SSE-capable client or set `stream: false`. |
| Amp gzip decoding errors | Compressed upstream responses | Fork auto-decompresses; update to latest build if issue persists. |
| CORS errors in browser | Protected management endpoints | Use CLI/terminal; avoid browsers for management endpoints. |
| Wrong model name | Provider alias mismatch | Use `gpt-*` for OpenAI or `claude-*` for Anthropic models. |
### Diagnostics
- Check logs (`debug: true` temporarily or `logging-to-file: true`).
- Verify config in effect: print effective config or confirm with startup logs.
- Test base reachability: `curl http://localhost:8317/v1/models`.
- For Amp, verify `amp-upstream-url` and secrets resolution.
## Security Checklist
- Keep `amp-restrict-management-to-localhost: true` (default).
- Do not expose the proxy publicly; bind to localhost or protect with firewall/VPN.
- If enabling remote management, set `remote-management.secret-key` and TLS/ingress protections.
- Disable the built-in management UI if hosting your own:
- `remote-management.disable-control-panel: true`
- Rotate tokens/keys; store config and auth-dir on encrypted disk or managed secret stores.
- Keep binary up to date to receive security fixes.
## References
- This fork README: [README.md](README.md)
- Upstream project: [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI)
- Amp CLI: [Official Manual](https://ampcode.com/manual)
- Factory CLI (droid): [Official Documentation](https://docs.factory.ai/cli/getting-started/overview)

361
docs/amp-cli-integration.md Normal file
View File

@@ -0,0 +1,361 @@
# Amp CLI Integration Guide
This guide explains how to use CLIProxyAPI with Amp CLI and Amp IDE extensions, enabling you to use your existing Google/ChatGPT/Claude subscriptions (via OAuth) with Amp's CLI.
## Table of Contents
- [Overview](#overview)
- [Which Providers Should You Authenticate?](#which-providers-should-you-authenticate)
- [Architecture](#architecture)
- [Configuration](#configuration)
- [Setup](#setup)
- [Usage](#usage)
- [Troubleshooting](#troubleshooting)
## Overview
The Amp CLI integration adds specialized routing to support Amp's API patterns while maintaining full compatibility with all existing CLIProxyAPI features. This allows you to use both traditional CLIProxyAPI features and Amp CLI with the same proxy server.
### Key Features
- **Provider route aliases**: Maps Amp's `/api/provider/{provider}/v1...` patterns to CLIProxyAPI handlers
- **Management proxy**: Forwards OAuth and account management requests to Amp's control plane
- **Smart fallback**: Automatically routes unconfigured models to ampcode.com
- **Secret management**: Configurable precedence (config > env > file) with 5-minute caching
- **Security-first**: Management routes restricted to localhost by default
- **Automatic gzip handling**: Decompresses responses from Amp upstream
### What You Can Do
- Use Amp CLI with your Google account (Gemini 3 Pro Preview, Gemini 2.5 Pro, Gemini 2.5 Flash)
- Use Amp CLI with your ChatGPT Plus/Pro subscription (GPT-5, GPT-5 Codex models)
- Use Amp CLI with your Claude Pro/Max subscription (Claude Sonnet 4.5, Opus 4.1)
- Use Amp IDE extensions (VS Code, Cursor, Windsurf, etc.) with the same proxy
- Run multiple CLI tools (Factory + Amp) through one proxy server
- Route unconfigured models automatically through ampcode.com
### Which Providers Should You Authenticate?
**Important**: The providers you need to authenticate depend on which models and features your installed version of Amp currently uses. Amp employs different providers for various agent modes and specialized subagents:
- **Smart mode**: Uses Google/Gemini models (Gemini 3 Pro)
- **Rush mode**: Uses Anthropic/Claude models (Claude Haiku 4.5)
- **Oracle subagent**: Uses OpenAI/GPT models (GPT-5 medium reasoning)
- **Librarian subagent**: Uses Anthropic/Claude models (Claude Sonnet 4.5)
- **Search subagent**: Uses Anthropic/Claude models (Claude Haiku 4.5)
- **Review feature**: Uses Google/Gemini models (Gemini 2.5 Flash-Lite)
For the most current information about which models Amp uses, see the **[Amp Models Documentation](https://ampcode.com/models)**.
#### Fallback Behavior
CLIProxyAPI uses a smart fallback system:
1. **Provider authenticated locally** (`--login`, `--codex-login`, `--claude-login`):
- Requests use **your OAuth subscription** (ChatGPT Plus/Pro, Claude Pro/Max, Google account)
- You benefit from your subscription's included usage quotas
- No Amp credits consumed
2. **Provider NOT authenticated locally**:
- Requests automatically forward to **ampcode.com**
- Uses Amp's backend provider connections
- **Requires Amp credits** if the provider is paid (OpenAI, Anthropic paid tiers)
- May result in errors if Amp credit balance is insufficient
**Recommendation**: Authenticate all providers you have subscriptions for to maximize value and minimize Amp credit usage. If you don't have subscriptions to all providers Amp uses, ensure you have sufficient Amp credits available for fallback requests.
## Architecture
### Request Flow
```
Amp CLI/IDE
├─ Provider API requests (/api/provider/{provider}/v1/...)
│ ↓
│ ├─ Model configured locally?
│ │ YES → Use local OAuth tokens (OpenAI/Claude/Gemini handlers)
│ │ NO → Forward to ampcode.com (reverse proxy)
│ ↓
│ Response
└─ Management requests (/api/auth, /api/user, /api/threads, ...)
├─ Localhost check (security)
└─ Reverse proxy to ampcode.com
Response (auto-decompressed if gzipped)
```
### Components
The Amp integration is implemented as a modular routing module (`internal/api/modules/amp/`) with these components:
1. **Route Aliases** (`routes.go`): Maps Amp-style paths to standard handlers
2. **Reverse Proxy** (`proxy.go`): Forwards management requests to ampcode.com
3. **Fallback Handler** (`fallback_handlers.go`): Routes unconfigured models to ampcode.com
4. **Secret Management** (`secret.go`): Multi-source API key resolution with caching
5. **Main Module** (`amp.go`): Orchestrates registration and configuration
## Configuration
### Basic Configuration
Add these fields to your `config.yaml`:
```yaml
# Amp upstream control plane (required for management routes)
amp-upstream-url: "https://ampcode.com"
# Optional: Override API key (otherwise uses env or file)
# amp-upstream-api-key: "your-amp-api-key"
# Security: restrict management routes to localhost (recommended)
amp-restrict-management-to-localhost: true
```
### Secret Resolution Precedence
The Amp module resolves API keys using this precedence order:
| Source | Key | Priority | Cache |
|--------|-----|----------|-------|
| Config file | `amp-upstream-api-key` | High | No |
| Environment | `AMP_API_KEY` | Medium | No |
| Amp secrets file | `~/.local/share/amp/secrets.json` | Low | 5 min |
**Recommendation**: Use the Amp secrets file (lowest precedence) for normal usage. This file is automatically managed by `amp login`.
### Security Settings
**`amp-restrict-management-to-localhost`** (default: `true`)
When enabled, management routes (`/api/auth`, `/api/user`, `/api/threads`, etc.) only accept connections from localhost (127.0.0.1, ::1). This prevents:
- Drive-by browser attacks
- Remote access to management endpoints
- CORS-based attacks
**Important**: Only disable this if you understand the security implications and have other protections in place (VPN, firewall, etc.).
## Setup
### 1. Configure CLIProxyAPI
Create or edit `config.yaml`:
```yaml
port: 8317
auth-dir: "~/.cli-proxy-api"
# Amp integration
amp-upstream-url: "https://ampcode.com"
amp-restrict-management-to-localhost: true
# Other standard settings...
debug: false
logging-to-file: true
```
### 2. Authenticate with Providers
Run OAuth login for the providers you want to use:
**Google Account (Gemini 2.5 Pro, Gemini 2.5 Flash, Gemini 3 Pro Preview):**
```bash
./cli-proxy-api --login
```
**ChatGPT Plus/Pro (GPT-5, GPT-5 Codex):**
```bash
./cli-proxy-api --codex-login
```
**Claude Pro/Max (Claude Sonnet 4.5, Opus 4.1):**
```bash
./cli-proxy-api --claude-login
```
Tokens are saved to:
- Gemini: `~/.cli-proxy-api/gemini-<email>.json`
- OpenAI Codex: `~/.cli-proxy-api/codex-<email>.json`
- Claude: `~/.cli-proxy-api/claude-<email>.json`
### 3. Start the Proxy
```bash
./cli-proxy-api --config config.yaml
```
Or run in background with tmux (recommended for remote servers):
```bash
tmux new-session -d -s proxy "./cli-proxy-api --config config.yaml"
```
### 4. Configure Amp CLI
#### Option A: Settings File
Edit `~/.config/amp/settings.json`:
```json
{
"amp.url": "http://localhost:8317"
}
```
#### Option B: Environment Variable
```bash
export AMP_URL=http://localhost:8317
```
### 5. Login and Use Amp
Login through the proxy (proxied to ampcode.com):
```bash
amp login
```
Use Amp as normal:
```bash
amp "Write a hello world program in Python"
```
### 6. (Optional) Configure Amp IDE Extension
The proxy also works with Amp IDE extensions for VS Code, Cursor, Windsurf, etc.
1. Open Amp extension settings in your IDE
2. Set **Amp URL** to `http://localhost:8317`
3. Login with your Amp account
4. Start using Amp in your IDE
Both CLI and IDE can use the proxy simultaneously.
## Usage
### Supported Routes
#### Provider Aliases (Always Available)
These routes work even without `amp-upstream-url` configured:
- `/api/provider/openai/v1/chat/completions`
- `/api/provider/openai/v1/responses`
- `/api/provider/anthropic/v1/messages`
- `/api/provider/google/v1beta/models/:action`
Amp CLI calls these routes with your OAuth-authenticated models configured in CLIProxyAPI.
#### Management Routes (Require `amp-upstream-url`)
These routes are proxied to ampcode.com:
- `/api/auth` - Authentication
- `/api/user` - User profile
- `/api/meta` - Metadata
- `/api/threads` - Conversation threads
- `/api/telemetry` - Usage telemetry
- `/api/internal` - Internal APIs
**Security**: Restricted to localhost by default.
### Model Fallback Behavior
When Amp requests a model:
1. **Check local configuration**: Does CLIProxyAPI have OAuth tokens for this model's provider?
2. **If YES**: Route to local handler (use your OAuth subscription)
3. **If NO**: Forward to ampcode.com (use Amp's default routing)
This enables seamless mixed usage:
- Models you've configured (Gemini, ChatGPT, Claude) → Your OAuth subscriptions
- Models you haven't configured → Amp's default providers
### Example API Calls
**Chat completion with local OAuth:**
```bash
curl http://localhost:8317/api/provider/openai/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-5",
"messages": [{"role": "user", "content": "Hello"}]
}'
```
**Management endpoint (localhost only):**
```bash
curl http://localhost:8317/api/user
```
## Troubleshooting
### Common Issues
| Symptom | Likely Cause | Fix |
|---------|--------------|-----|
| 404 on `/api/provider/...` | Incorrect route path | Ensure exact path: `/api/provider/{provider}/v1...` |
| 403 on `/api/user` | Non-localhost request | Run from same machine or disable `amp-restrict-management-to-localhost` (not recommended) |
| 401/403 from provider | Missing/expired OAuth | Re-run `--codex-login` or `--claude-login` |
| Amp gzip errors | Response decompression issue | Update to latest build; auto-decompression should handle this |
| Models not using proxy | Wrong Amp URL | Verify `amp.url` setting or `AMP_URL` environment variable |
| CORS errors | Protected management endpoint | Use CLI/terminal, not browser |
### Diagnostics
**Check proxy logs:**
```bash
# If logging-to-file: true
tail -f logs/requests.log
# If running in tmux
tmux attach-session -t proxy
```
**Enable debug mode** (temporarily):
```yaml
debug: true
```
**Test basic connectivity:**
```bash
# Check if proxy is running
curl http://localhost:8317/v1/models
# Check Amp-specific route
curl http://localhost:8317/api/provider/openai/v1/models
```
**Verify Amp configuration:**
```bash
# Check if Amp is using proxy
amp config get amp.url
# Or check environment
echo $AMP_URL
```
### Security Checklist
- ✅ Keep `amp-restrict-management-to-localhost: true` (default)
- ✅ Don't expose proxy publicly (bind to localhost or use firewall/VPN)
- ✅ Use the Amp secrets file (`~/.local/share/amp/secrets.json`) managed by `amp login`
- ✅ Rotate OAuth tokens periodically by re-running login commands
- ✅ Store config and auth-dir on encrypted disk if handling sensitive data
- ✅ Keep proxy binary up to date for security fixes
## Additional Resources
- [CLIProxyAPI Main Documentation](https://help.router-for.me/)
- [Amp CLI Official Manual](https://ampcode.com/manual)
- [Management API Reference](https://help.router-for.me/management/api)
- [SDK Documentation](sdk-usage.md)
## Disclaimer
This integration is for personal/educational use. Using reverse proxies or alternate API bases may violate provider Terms of Service. You are solely responsible for how you use this software. Accounts may be rate-limited, locked, or banned. No warranties. Use at your own risk.