CLIRELAY(1)

NAME

CliRelayWrap Gemini CLI, Antigravity, ChatGPT Codex, Claude Code, Qwen Code, iFlow as an OpenAI/Gemini/Claude/Codex compatible…

SYNOPSIS

INFO

616 stars
50 forks
0 views

DESCRIPTION

Wrap Gemini CLI, Antigravity, ChatGPT Codex, Claude Code, Qwen Code, iFlow as an OpenAI/Gemini/Claude/Codex compatible API service, allowing you to enjoy the free Gemini 2.5 Pro, GPT 5, Claude, Qwen model through API

README

Go License Stars Forks

🔀 CliRelay

A unified proxy server for AI CLI tools — use your existing subscriptions with any OpenAI / Gemini / Claude / Codex compatible client.

English | 中文

📖 Docs · 🖥️ Management Panel · 🐛 Report Bug · ✨ Request Feature


⚡ What is CliRelay?

✨ Heavily enhanced fork of the CLIProxyAPI project — rebuilt with a production-grade management layer, web control panel hosting, and a terminal TUI for day-2 operations.

CliRelay turns AI CLI subscriptions, OAuth credentials, API keys, and compatible upstream services into one managed API layer. It proxies Claude Code, Gemini CLI, OpenAI Codex, Amp CLI, OpenAI-compatible clients, and other AI coding tools through a unified endpoint, then adds routing groups, failover, request logging, quota control, model pricing, image-generation support, API-key self-service, online updates, /manage web hosting, and terminal management workflows around that traffic.

┌───────────────────────┐         ┌──────────────┐         ┌────────────────────┐
│   AI Coding Tools     │         │              │         │  Upstream Providers │
│                       │         │              │ ──────▶ │  Google Gemini      │
│  Claude Code          │ ──────▶ │   CliRelay   │ ──────▶ │  OpenAI / Codex    │
│  Gemini CLI           │         │   :8317      │ ──────▶ │  Anthropic Claude  │
│  OpenAI Codex         │         │              │ ──────▶ │  Qwen / iFlow      │
│  Amp CLI / IDE        │         │              │ ──────▶ │  Antigravity       │
│  Any OAI-compatible   │         └──────────────┘         │  Vertex / OpenAI   │
└───────────────────────┘                                  │  iFlow / Qwen /    │
                                                           │  Kimi / Claude     │
                                                           └────────────────────┘

✨ Key Features

🔌 Multi-Provider Proxy Engine

FeatureDescription
🌐 Unified EndpointOne http://localhost:8317 fronts Gemini, Claude, Codex, Qwen, iFlow, Antigravity, Vertex-compatible endpoints, OpenAI-compatible upstreams, and Amp integration
⚖️ Smart Load BalancingRound-robin or fill-first scheduling across multiple API keys for the same provider
🧭 Group & Path RoutingBind channels into groups, restrict API keys to allowed groups, and expose custom path namespaces for teams or workloads
🔄 Auto FailoverAutomatically switches to backup channels when quotas are exhausted or errors occur
🧠 Multimodal SupportFull support for text + image inputs, image-generation routing, function calling (tools), and streaming SSE responses
🔗 OpenAI-CompatibleWorks with any upstream that speaks the OpenAI Chat Completions protocol

📊 Request Logging & Monitoring (SQLite)

FeatureDescription
📝 Full Request CaptureEvery API request is logged to SQLite with timestamp, model, tokens (in/out/reasoning/cache), latency, status, and source channel
💬 Message Body StorageFull request/response message content captured in compressed SQLite storage, with separate retention for content vs. metadata
🔍 Advanced QueryingFilter logs by API Key, model, status, time range with efficient pagination (LIMIT/OFFSET)
📈 Analytics AggregationPre-computed dashboards: daily trends, model distribution, hourly heatmaps, per-key statistics
🏥 Health Score EngineReal-time 0–100 health score considering success rate, latency, active channels, and error patterns
📡 WebSocket MonitoringLive system stats streamed via WebSocket: CPU, memory, goroutines, network I/O, DB size
🗄️ No-CGO SQLiteUses modernc.org/sqlite — pure Go, no CGO dependency, easy cross-compilation

🔐 API Key & Access Management

FeatureDescription
🔑 API Key CRUDCreate, edit, delete API keys via Management API — each with custom name, notes, and independent enable/disable toggle
📊 Per-Key QuotasSet max token / request quotas per key with automatic enforcement
⏱️ Rate LimitingPer-key rate limiting (requests per minute/hour)
👥 Team PermissionsAssign API keys to different users or groups with scoped channel access and model permissions
🔒 Key MaskingAPI keys are always displayed masked (sk-***xxx) in UI and logs
🌍 Public Lookup PageEnd users can query their own usage stats and request logs via a public self-service page (no login required)

🔗 Provider Channel Management

FeatureDescription
📋 Multi-Tab ConfigManage channels organized by provider type: Gemini, Claude, Codex, Vertex, OpenAI Compatible, Ampcode
🏷️ Channel NamingEach channel can have a custom name, notes, proxy URL, custom headers, and model alias mappings
🧩 Reusable Proxy PoolMaintain outbound proxy entries once and attach them to OAuth/auth channels when needed
⏱️ Latency TrackingAverage latency (latency_ms) tracked per channel with visual indicators
🔄 Enable/DisableIndividually toggle channels on/off without deletion
🚫 Model ExclusionsExclude specific models from a channel (e.g., block expensive models on backup keys)
🧾 Model Library SyncMaintain custom models and sync model IDs/pricing from OpenRouter for quota accounting
📊 Channel StatsPer-channel success/fail counts and model availability displayed on each channel card

🛡️ Security & Authentication

FeatureDescription
🔐 OAuth SupportNative OAuth flows for Gemini, Claude, Codex, Qwen, iFlow, Antigravity, and Kimi, plus device/browser/cookie variants where supported
🪪 Identity FingerprintsCentralize upstream identity metadata so providers receive consistent client fingerprints
🔒 TLS HandlingConfigurable TLS settings for upstream communication
🏠 Panel IsolationManagement panel access controlled independently with admin password
🛡️ Request CloakingUpstream requests are stripped of client-identifying headers for privacy

🛠️ Operator Experience

FeatureDescription
🖥️ Visual Management PanelConfigure providers, auth, API keys, models, routing, logs, updates, and system status from /manage
🌐 Chinese / English UIBuilt-in i18n for the management panel and Compose/TUI language selection
🌙 Dark ModeFull dark theme for long-running operational sessions
🧬 Visual Config EditorEdit runtime config visually or inspect source YAML when you need exact control
🔄 Online Update FlowCheck versions, review update notes, trigger the updater sidecar, and wait for backend recovery from the panel
📥 CC Switch ImportImport cc-switch style configuration into the managed model/channel workspace

🗄️ Data Persistence

FeatureDescription
💾 SQLite StorageAll usage data, request logs, and message bodies stored in local SQLite database
🔄 Redis BackupOptional Redis integration for periodic snapshotting and cross-restart metric preservation
🗃️ Pluggable Auth/Config BackendsLocal files by default, with optional PostgreSQL, Git, or S3-compatible object storage backends for config/auth persistence
📦 Config SnapshotsImport/export entire system configuration as JSON for backup and migration

📸 Management Panel Preview

CliRelay can expose a built-in web control panel at /manage. The server can host bundled SPA assets or fall back to synced management assets from the configured panel repository.

The gallery below uses the latest supplied screenshots, covering the current end-to-end management workflow.

Dashboard, Locale & Theme

Home overviewOperations overview
CliRelay dashboard overviewCliRelay operations dashboard
Chinese / English interfaceDark mode
Chinese and English management panel localeManagement panel dark mode

Monitoring, Logs & Self-Service

Monitor centerRequest logs
Monitor center charts and request metricsRequest log table with filters
Request detailsLog query system
Request details viewerLog query system
API key lookup
Public API key lookup page

Auth, Identity & Access

Unified OAuth managementIdentity fingerprints
Unified OAuth managementIdentity fingerprint management
Team permissionsOAuth proxy assignment
Team API key assignment and permissionsProxy configuration assigned to OAuth auth records

Channels, Routing & Configuration

Multi-channel API setupGroup routing and custom paths
Add multiple API channelsChannel group routing and custom path configuration
Visual configUpstream debug passthrough
Visual configuration editorDebug passthrough content sent to upstream
CC Switch import
Configurable CC Switch import

Models, Image Generation & Updates

OpenRouter model syncCustom model maintenance
OpenRouter model ID and pricing syncCustom model maintenance
Image generation configOnline update flow
Image generation configurationOnline update mechanism
System information
System information page

🔗 The runtime panel source is configurable via remote-management.panel-github-repository. The default repository is kittors/codeProxy.

🏗️ Supported Providers

Provider / ChannelAuthNotes
Google GeminiOAuth + API KeyGemini CLI / AI Studio style flows
Anthropic ClaudeOAuth + API KeyClaude Code and Claude-compatible clients
OpenAI CodexOAuth + API KeyIncludes Responses and WebSocket bridging
QwenOAuthQwen Code style login flow
iFlow / GLMOAuth + CookieSupports iFlow routing and related model families
KimiOAuthBrowser-based login flow
AntigravityOAuthDedicated OAuth channel with model backfill support
Vertex-compatible endpointsAPI KeyCustom base URL, headers, aliases, exclusions
OpenAI-compatible upstreamsAPI KeyOpenRouter, Grok-compatible endpoints, and custom providers
Amp integrationUpstream API key + mappingsDirect Amp upstream fallback or mapped local routing

🚀 Quick Start

🐳 Install With Docker Compose

Docker Compose is the recommended installation path for CliRelay. The included docker-compose.yml uses the published ghcr.io/kittors/clirelay:latest image by default and starts both the API service and updater sidecar.

git clone https://github.com/kittors/CliRelay.git
cd CliRelay
cp config.example.yaml config.yaml
docker compose up -d

Edit config.yaml to add your API keys or OAuth credentials, then restart the service:

docker compose restart cli-proxy-api

By default, client API routes (/v1, /v1beta) require an API key. To run without client keys, set allow-unauthenticated: true in config.yaml (not recommended for production).

After startup:

  • API endpoint: http://localhost:8317
  • Web panel: http://localhost:8317/manage
  • Logs: docker compose logs -f cli-proxy-api
  • Restart: docker compose restart cli-proxy-api
  • Stop: docker compose down
  • TUI: docker compose exec cli-proxy-api ./cli-proxy-api -tui
  • OAuth login modes: docker compose exec cli-proxy-api ./cli-proxy-api -login

Set CLIRELAY_LOCALE=en or CLIRELAY_LOCALE=zh in your Compose environment to control the default TUI language.

To disable automatic update prompts, set the following in config.yaml or turn off Automatic Update Checks in the Config page:

auto-update:
  enabled: false

Update checks follow the stable main Docker image by default. To test dev builds, set channel: dev in config.yaml or choose Development (dev) from Update Channel in the Config page:

auto-update:
  channel: dev

🗄️ Enabling Data Persistence

By default, API usage logs are stored in SQLite for persistence. For additional backup:

  1. Ensure you have a Redis server running.
  2. Edit config.yaml and set redis.enable: true with your Redis address. CliRelay will automatically snapshot and restore traffic metrics on every startup!

For large installations, tune request-log-storage in config.yaml to control how full request/response bodies are retained. By default, full bodies are compressed, kept for 30 days, and capped at ~1GB (1024MB); lightweight request metadata remains queryable for longer-term statistics. Set content-retention-days: 0 to keep full content indefinitely, set store-content: false to stop new body storage without deleting existing historical content, and adjust max-total-size-mb to cap body storage so the oldest full bodies are pruned before the retention window is reached.

If you need non-local config/auth persistence, the server also supports PostgreSQL, Git-backed, and S3-compatible object-store backends through environment-based bootstrap settings.

3️⃣ Point Your Tools

Set your AI tool's API base to http://localhost:8317 and start coding!

Example: OpenAI Codex (~/.codex/config.toml)

[model_providers.tabcode]
name = "openai"
base_url = "http://localhost:8317/v1"
requires_openai_auth = true

📖 Full setup guides → help.router-for.me

🖥️ Management Panel

When the control panel is enabled, open:

http://localhost:8317/manage
  • remote-management.disable-control-panel defaults to false in the example config, so the control panel is reachable after a standard Docker Compose deployment.
  • When enabled, the current panel route is /manage/login. The old management.html#/login route is legacy-only.
  • Docker Compose deployments expose the panel at /manage.
  • The server can serve a bundled SPA directory or auto-fetch panel assets when needed.
  • This repository contains the hosting/update path for /manage; the standalone web panel source is maintained separately from the Go server code.
  • Terminal-first management is also available through docker compose exec cli-proxy-api ./cli-proxy-api -tui.
  • If you want to customize the panel asset source, set remote-management.panel-github-repository.

📐 Architecture

CliRelay/
├── cmd/server/               # Binary entry point and CLI mode dispatch
├── internal/api/             # HTTP server, management routes, middleware
├── internal/auth/            # Provider OAuth / cookie / browser auth flows
├── internal/config/          # Config parsing, defaults, migrations
├── internal/store/           # Local, Git, PostgreSQL, object-store auth/config persistence
├── internal/tui/             # Terminal management UI
├── internal/usage/           # SQLite usage DB, retention, analytics
├── internal/managementasset/ # /manage panel hosting and asset sync
├── sdk/                      # Reusable Go SDK, handlers, executors
├── auths/                    # Local credential storage
├── examples/                 # SDK / custom provider examples
├── docs/                     # Local docs and panel screenshots
└── docker-compose.yml        # Container deployment entry

📚 Documentation

DocDescription
Getting StartedFull installation and setup guide
Management APIREST API reference for management endpoints
Amp CLI GuideIntegrate with Amp CLI & IDE extensions
SDK UsageEmbed the proxy in Go applications
SDK AdvancedExecutors & translators deep-dive
SDK AccessAuthentication in SDK context
SDK WatcherCredential loading & hot-reload

🤝 Contributing

Contributions are welcome! Here's how to get started:

# 1. Clone the repository
git clone https://github.com/kittors/CliRelay.git
cd CliRelay

2. Create a feature branch from the latest dev baseline

git fetch origin git switch -c feature/amazing-feature origin/dev

3. Make your changes & commit

git commit -m "feat: add amazing feature"

4. Push to your branch & open a PR targeting dev

git push origin feature/amazing-feature

Please target pull requests at dev, not main. Maintainers merge verified changes into dev first; main is updated separately for release/stable integration. See CONTRIBUTING.md for the full branch and merge workflow.

📜 License

This project is licensed under the MIT License — see the LICENSE file for details.


🙏 Acknowledgements & Special Thanks

This project is a deeply enhanced fork built upon the excellent core logic of the open-source router-for-me/CLIProxyAPI project. We want to express our deepest gratitude to the original CLIProxyAPI project and all its contributors!

It is thanks to the solid, innovative proxy distribution foundation built by the upstream that we were able to stand on the shoulders of giants. This allowed us to develop unique advanced management features (like API Key tracking & control, full request logging with SQLite, and real-time system monitoring) and rebuild an entirely new frontend dashboard from scratch.

A huge salute to the spirit of open source! ❤️

SEE ALSO

clihub5/1/2026CLIRELAY(1)