mirror of
https://github.com/Finesssee/ProxyPilot.git
synced 2026-11-19 02:17:46 +00:00
Synced all changes from router-for-me/CLIProxyAPIPlus including: Executor updates: - claude_executor: response decompression, beta extraction, model resolution - gemini_executor/codex_executor: usage reporting - antigravity_executor: fallback URLs, thinking metadata, token refresh - kiro_executor: token refresh, profile ARN handling, quota fallback Translator updates: - Updated all translators for improved request/response handling - Enhanced tool result formatting and streaming support Configuration: - Added IncognitoBrowser option for OAuth - Updated KiroKey configuration - Enhanced PayloadConfig options SDK updates: - Auth refresh registry improvements - Cliproxy service enhancements - Added ErrNotImplemented for executor interface Excluded features (not synced): - Amp CLI Integration module - GitHub Copilot executor 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
345 lines
11 KiB
Go
345 lines
11 KiB
Go
package management
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
|
|
"github.com/router-for-me/CLIProxyAPI/v6/internal/routingdebug"
|
|
"github.com/router-for-me/CLIProxyAPI/v6/internal/util"
|
|
sdkconfig "github.com/router-for-me/CLIProxyAPI/v6/sdk/config"
|
|
log "github.com/sirupsen/logrus"
|
|
"github.com/tidwall/gjson"
|
|
"gopkg.in/yaml.v3"
|
|
)
|
|
|
|
const (
|
|
latestReleaseURL = "https://api.github.com/repos/router-for-me/CLIProxyAPIPlus/releases/latest"
|
|
latestReleaseUserAgent = "CLIProxyAPIPlus"
|
|
)
|
|
|
|
func (h *Handler) GetConfig(c *gin.Context) {
|
|
if h == nil || h.cfg == nil {
|
|
c.JSON(200, gin.H{})
|
|
return
|
|
}
|
|
cfgCopy := *h.cfg
|
|
c.JSON(200, &cfgCopy)
|
|
}
|
|
|
|
// GetRoutingPreview returns a JSON description of how a given model would be normalised and routed.
|
|
//
|
|
// Query parameters:
|
|
// - model: required model identifier (may be alias, auto, or provider://model)
|
|
func (h *Handler) GetRoutingPreview(c *gin.Context) {
|
|
if h == nil || h.cfg == nil {
|
|
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "unavailable", "message": "configuration not loaded"})
|
|
return
|
|
}
|
|
model := strings.TrimSpace(c.Query("model"))
|
|
if model == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "missing_model", "message": "provide model via ?model="})
|
|
return
|
|
}
|
|
preview, err := h.computeRoutingPreview(model)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "routing_error", "message": err.Error()})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, preview)
|
|
}
|
|
|
|
// GetRoutingRecent returns a small ring buffer of recently routed requests using the runtime selection trace.
|
|
func (h *Handler) GetRoutingRecent(c *gin.Context) {
|
|
// Even if h or cfg are nil, routingdebug.Snapshot() is safe; this endpoint is purely diagnostic.
|
|
entries := routingdebug.Snapshot()
|
|
if len(entries) == 0 {
|
|
c.JSON(http.StatusOK, gin.H{"entries": []routingdebug.Entry{}})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, gin.H{"entries": entries})
|
|
}
|
|
|
|
// PostRoutingPreview accepts a full request JSON (OpenAI/OpenAIResponses-compatible) and
|
|
// extracts the model name for routing preview.
|
|
func (h *Handler) PostRoutingPreview(c *gin.Context) {
|
|
if h == nil || h.cfg == nil {
|
|
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "unavailable", "message": "configuration not loaded"})
|
|
return
|
|
}
|
|
|
|
body, err := io.ReadAll(io.LimitReader(c.Request.Body, 1<<20)) // 1 MiB safety cap
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid_body", "message": "cannot read request body"})
|
|
return
|
|
}
|
|
if !gjson.ValidBytes(body) {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid_json", "message": "body is not valid JSON"})
|
|
return
|
|
}
|
|
|
|
// Try a few common shapes to extract the model name.
|
|
paths := []string{
|
|
"model", // standard OpenAI
|
|
"request.model", // some wrapper shapes
|
|
"response.model", // responses-style wrappers
|
|
}
|
|
var model string
|
|
for _, path := range paths {
|
|
v := gjson.GetBytes(body, path)
|
|
if v.Exists() && strings.TrimSpace(v.String()) != "" {
|
|
model = strings.TrimSpace(v.String())
|
|
break
|
|
}
|
|
}
|
|
if model == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "missing_model", "message": "could not find model field in JSON body"})
|
|
return
|
|
}
|
|
|
|
preview, err := h.computeRoutingPreview(model)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "routing_error", "message": err.Error(), "model": model})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"model": model,
|
|
"preview": preview,
|
|
})
|
|
}
|
|
|
|
type releaseInfo struct {
|
|
TagName string `json:"tag_name"`
|
|
Name string `json:"name"`
|
|
}
|
|
|
|
// GetLatestVersion returns the latest release version from GitHub without downloading assets.
|
|
func (h *Handler) GetLatestVersion(c *gin.Context) {
|
|
client := &http.Client{Timeout: 10 * time.Second}
|
|
proxyURL := ""
|
|
if h != nil && h.cfg != nil {
|
|
proxyURL = strings.TrimSpace(h.cfg.ProxyURL)
|
|
}
|
|
if proxyURL != "" {
|
|
sdkCfg := &sdkconfig.SDKConfig{ProxyURL: proxyURL}
|
|
util.SetProxy(sdkCfg, client)
|
|
}
|
|
|
|
req, err := http.NewRequestWithContext(c.Request.Context(), http.MethodGet, latestReleaseURL, nil)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "request_create_failed", "message": err.Error()})
|
|
return
|
|
}
|
|
req.Header.Set("Accept", "application/vnd.github+json")
|
|
req.Header.Set("User-Agent", latestReleaseUserAgent)
|
|
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadGateway, gin.H{"error": "request_failed", "message": err.Error()})
|
|
return
|
|
}
|
|
defer func() {
|
|
if errClose := resp.Body.Close(); errClose != nil {
|
|
log.WithError(errClose).Debug("failed to close latest version response body")
|
|
}
|
|
}()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
|
|
c.JSON(http.StatusBadGateway, gin.H{"error": "unexpected_status", "message": fmt.Sprintf("status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))})
|
|
return
|
|
}
|
|
|
|
var info releaseInfo
|
|
if errDecode := json.NewDecoder(resp.Body).Decode(&info); errDecode != nil {
|
|
c.JSON(http.StatusBadGateway, gin.H{"error": "decode_failed", "message": errDecode.Error()})
|
|
return
|
|
}
|
|
|
|
version := strings.TrimSpace(info.TagName)
|
|
if version == "" {
|
|
version = strings.TrimSpace(info.Name)
|
|
}
|
|
if version == "" {
|
|
c.JSON(http.StatusBadGateway, gin.H{"error": "invalid_response", "message": "missing release version"})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"latest-version": version})
|
|
}
|
|
|
|
func WriteConfig(path string, data []byte) error {
|
|
data = config.NormalizeCommentIndentation(data)
|
|
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if _, errWrite := f.Write(data); errWrite != nil {
|
|
_ = f.Close()
|
|
return errWrite
|
|
}
|
|
if errSync := f.Sync(); errSync != nil {
|
|
_ = f.Close()
|
|
return errSync
|
|
}
|
|
return f.Close()
|
|
}
|
|
|
|
func (h *Handler) PutConfigYAML(c *gin.Context) {
|
|
body, err := io.ReadAll(c.Request.Body)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid_yaml", "message": "cannot read request body"})
|
|
return
|
|
}
|
|
var cfg config.Config
|
|
if err = yaml.Unmarshal(body, &cfg); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid_yaml", "message": err.Error()})
|
|
return
|
|
}
|
|
// Validate config using LoadConfigOptional with optional=false to enforce parsing
|
|
tmpDir := filepath.Dir(h.configFilePath)
|
|
tmpFile, err := os.CreateTemp(tmpDir, "config-validate-*.yaml")
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "write_failed", "message": err.Error()})
|
|
return
|
|
}
|
|
tempFile := tmpFile.Name()
|
|
if _, errWrite := tmpFile.Write(body); errWrite != nil {
|
|
_ = tmpFile.Close()
|
|
_ = os.Remove(tempFile)
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "write_failed", "message": errWrite.Error()})
|
|
return
|
|
}
|
|
if errClose := tmpFile.Close(); errClose != nil {
|
|
_ = os.Remove(tempFile)
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "write_failed", "message": errClose.Error()})
|
|
return
|
|
}
|
|
defer func() {
|
|
_ = os.Remove(tempFile)
|
|
}()
|
|
validatedCfg, err := config.LoadConfigOptional(tempFile, false)
|
|
if err != nil {
|
|
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "invalid_config", "message": err.Error()})
|
|
return
|
|
}
|
|
if validatedCfg == nil {
|
|
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "invalid_config", "message": "configuration is empty"})
|
|
return
|
|
}
|
|
if warnings, errValidate := config.ValidateConfig(validatedCfg); errValidate != nil {
|
|
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "invalid_config", "message": errValidate.Error()})
|
|
return
|
|
} else if len(warnings) > 0 {
|
|
// Surface warnings in logs; the response body will include them after successful persist.
|
|
for _, w := range warnings {
|
|
log.Warnf("config warning (management update): %s", w)
|
|
}
|
|
}
|
|
h.mu.Lock()
|
|
defer h.mu.Unlock()
|
|
if WriteConfig(h.configFilePath, body) != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "write_failed", "message": "failed to write config"})
|
|
return
|
|
}
|
|
// Reload into handler to keep memory in sync
|
|
newCfg, err := config.LoadConfig(h.configFilePath)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "reload_failed", "message": err.Error()})
|
|
return
|
|
}
|
|
h.cfg = newCfg
|
|
resp := gin.H{"ok": true, "changed": []string{"config"}}
|
|
if warnings, errValidate := config.ValidateConfig(newCfg); errValidate == nil && len(warnings) > 0 {
|
|
resp["warnings"] = warnings
|
|
}
|
|
c.JSON(http.StatusOK, resp)
|
|
}
|
|
|
|
// GetConfigYAML returns the raw config.yaml file bytes without re-encoding.
|
|
// It preserves comments and original formatting/styles.
|
|
func (h *Handler) GetConfigYAML(c *gin.Context) {
|
|
data, err := os.ReadFile(h.configFilePath)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "not_found", "message": "config file not found"})
|
|
return
|
|
}
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "read_failed", "message": err.Error()})
|
|
return
|
|
}
|
|
c.Header("Content-Type", "application/yaml; charset=utf-8")
|
|
c.Header("Cache-Control", "no-store")
|
|
c.Header("X-Content-Type-Options", "nosniff")
|
|
// Write raw bytes as-is
|
|
_, _ = c.Writer.Write(data)
|
|
}
|
|
|
|
// Debug
|
|
func (h *Handler) GetDebug(c *gin.Context) { c.JSON(200, gin.H{"debug": h.cfg.Debug}) }
|
|
func (h *Handler) PutDebug(c *gin.Context) { h.updateBoolField(c, func(v bool) { h.cfg.Debug = v }) }
|
|
|
|
// UsageStatisticsEnabled
|
|
func (h *Handler) GetUsageStatisticsEnabled(c *gin.Context) {
|
|
c.JSON(200, gin.H{"usage-statistics-enabled": h.cfg.UsageStatisticsEnabled})
|
|
}
|
|
func (h *Handler) PutUsageStatisticsEnabled(c *gin.Context) {
|
|
h.updateBoolField(c, func(v bool) { h.cfg.UsageStatisticsEnabled = v })
|
|
}
|
|
|
|
// UsageStatisticsEnabled
|
|
func (h *Handler) GetLoggingToFile(c *gin.Context) {
|
|
c.JSON(200, gin.H{"logging-to-file": h.cfg.LoggingToFile})
|
|
}
|
|
func (h *Handler) PutLoggingToFile(c *gin.Context) {
|
|
h.updateBoolField(c, func(v bool) { h.cfg.LoggingToFile = v })
|
|
}
|
|
|
|
// Request log
|
|
func (h *Handler) GetRequestLog(c *gin.Context) { c.JSON(200, gin.H{"request-log": h.cfg.RequestLog}) }
|
|
func (h *Handler) PutRequestLog(c *gin.Context) {
|
|
h.updateBoolField(c, func(v bool) { h.cfg.RequestLog = v })
|
|
}
|
|
|
|
// Websocket auth
|
|
func (h *Handler) GetWebsocketAuth(c *gin.Context) {
|
|
c.JSON(200, gin.H{"ws-auth": h.cfg.WebsocketAuth})
|
|
}
|
|
func (h *Handler) PutWebsocketAuth(c *gin.Context) {
|
|
h.updateBoolField(c, func(v bool) { h.cfg.WebsocketAuth = v })
|
|
}
|
|
|
|
// Request retry
|
|
func (h *Handler) GetRequestRetry(c *gin.Context) {
|
|
c.JSON(200, gin.H{"request-retry": h.cfg.RequestRetry})
|
|
}
|
|
func (h *Handler) PutRequestRetry(c *gin.Context) {
|
|
h.updateIntField(c, func(v int) { h.cfg.RequestRetry = v })
|
|
}
|
|
|
|
// Max retry interval
|
|
func (h *Handler) GetMaxRetryInterval(c *gin.Context) {
|
|
c.JSON(200, gin.H{"max-retry-interval": h.cfg.MaxRetryInterval})
|
|
}
|
|
func (h *Handler) PutMaxRetryInterval(c *gin.Context) {
|
|
h.updateIntField(c, func(v int) { h.cfg.MaxRetryInterval = v })
|
|
}
|
|
|
|
// Proxy URL
|
|
func (h *Handler) GetProxyURL(c *gin.Context) { c.JSON(200, gin.H{"proxy-url": h.cfg.ProxyURL}) }
|
|
func (h *Handler) PutProxyURL(c *gin.Context) {
|
|
h.updateStringField(c, func(v string) { h.cfg.ProxyURL = v })
|
|
}
|
|
func (h *Handler) DeleteProxyURL(c *gin.Context) {
|
|
h.cfg.ProxyURL = ""
|
|
h.persist(c)
|
|
}
|