mirror of
https://github.com/router-for-me/CLIProxyAPIPlus.git
synced 2026-03-29 16:54:41 +00:00
Compare commits
29 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5d33d6b8ea | ||
|
|
e124db723b | ||
|
|
05444cf32d | ||
|
|
478aff1189 | ||
|
|
8edbda57cf | ||
|
|
2331b9a2e7 | ||
|
|
ee33863b47 | ||
|
|
cd22c849e2 | ||
|
|
f0e73efda2 | ||
|
|
3156109c71 | ||
|
|
5ca3508284 | ||
|
|
771fec9447 | ||
|
|
7815ee338d | ||
|
|
44b6c872e2 | ||
|
|
7a77b23f2d | ||
|
|
672e8549c0 | ||
|
|
66f5269a23 | ||
|
|
4eaf769894 | ||
|
|
ebec293497 | ||
|
|
e02ceecd35 | ||
|
|
9116392a45 | ||
|
|
c8b33a8cc3 | ||
|
|
dca8d5ded8 | ||
|
|
2a7fd1e897 | ||
|
|
b9d1e70ac2 | ||
|
|
fdf5720217 | ||
|
|
f40bd0cd51 | ||
|
|
e33676bb87 | ||
|
|
b1f1cee1e5 |
@@ -221,6 +221,7 @@ ws-auth: false
|
|||||||
# gemini-cli:
|
# gemini-cli:
|
||||||
# - name: "gemini-2.5-pro" # original model name under this channel
|
# - name: "gemini-2.5-pro" # original model name under this channel
|
||||||
# alias: "g2.5p" # client-visible alias
|
# alias: "g2.5p" # client-visible alias
|
||||||
|
# fork: true # when true, keep original and also add the alias as an extra model (default: false)
|
||||||
# vertex:
|
# vertex:
|
||||||
# - name: "gemini-2.5-pro"
|
# - name: "gemini-2.5-pro"
|
||||||
# alias: "g2.5p"
|
# alias: "g2.5p"
|
||||||
|
|||||||
128
docker-build.sh
128
docker-build.sh
@@ -5,9 +5,115 @@
|
|||||||
# This script automates the process of building and running the Docker container
|
# This script automates the process of building and running the Docker container
|
||||||
# with version information dynamically injected at build time.
|
# with version information dynamically injected at build time.
|
||||||
|
|
||||||
# Exit immediately if a command exits with a non-zero status.
|
# Hidden feature: Preserve usage statistics across rebuilds
|
||||||
|
# Usage: ./docker-build.sh --with-usage
|
||||||
|
# First run prompts for management API key, saved to temp/stats/.api_secret
|
||||||
|
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
|
STATS_DIR="temp/stats"
|
||||||
|
STATS_FILE="${STATS_DIR}/.usage_backup.json"
|
||||||
|
SECRET_FILE="${STATS_DIR}/.api_secret"
|
||||||
|
WITH_USAGE=false
|
||||||
|
|
||||||
|
get_port() {
|
||||||
|
if [[ -f "config.yaml" ]]; then
|
||||||
|
grep -E "^port:" config.yaml | sed -E 's/^port: *["'"'"']?([0-9]+)["'"'"']?.*$/\1/'
|
||||||
|
else
|
||||||
|
echo "8317"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
export_stats_api_secret() {
|
||||||
|
if [[ -f "${SECRET_FILE}" ]]; then
|
||||||
|
API_SECRET=$(cat "${SECRET_FILE}")
|
||||||
|
else
|
||||||
|
if [[ ! -d "${STATS_DIR}" ]]; then
|
||||||
|
mkdir -p "${STATS_DIR}"
|
||||||
|
fi
|
||||||
|
echo "First time using --with-usage. Management API key required."
|
||||||
|
read -r -p "Enter management key: " -s API_SECRET
|
||||||
|
echo
|
||||||
|
echo "${API_SECRET}" > "${SECRET_FILE}"
|
||||||
|
chmod 600 "${SECRET_FILE}"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
check_container_running() {
|
||||||
|
local port
|
||||||
|
port=$(get_port)
|
||||||
|
|
||||||
|
if ! curl -s -o /dev/null -w "%{http_code}" "http://localhost:${port}/" | grep -q "200"; then
|
||||||
|
echo "Error: cli-proxy-api service is not responding at localhost:${port}"
|
||||||
|
echo "Please start the container first or use without --with-usage flag."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
export_stats() {
|
||||||
|
local port
|
||||||
|
port=$(get_port)
|
||||||
|
|
||||||
|
if [[ ! -d "${STATS_DIR}" ]]; then
|
||||||
|
mkdir -p "${STATS_DIR}"
|
||||||
|
fi
|
||||||
|
check_container_running
|
||||||
|
echo "Exporting usage statistics..."
|
||||||
|
EXPORT_RESPONSE=$(curl -s -w "\n%{http_code}" -H "X-Management-Key: ${API_SECRET}" \
|
||||||
|
"http://localhost:${port}/v0/management/usage/export")
|
||||||
|
HTTP_CODE=$(echo "${EXPORT_RESPONSE}" | tail -n1)
|
||||||
|
RESPONSE_BODY=$(echo "${EXPORT_RESPONSE}" | sed '$d')
|
||||||
|
|
||||||
|
if [[ "${HTTP_CODE}" != "200" ]]; then
|
||||||
|
echo "Export failed (HTTP ${HTTP_CODE}): ${RESPONSE_BODY}"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "${RESPONSE_BODY}" > "${STATS_FILE}"
|
||||||
|
echo "Statistics exported to ${STATS_FILE}"
|
||||||
|
}
|
||||||
|
|
||||||
|
import_stats() {
|
||||||
|
local port
|
||||||
|
port=$(get_port)
|
||||||
|
|
||||||
|
echo "Importing usage statistics..."
|
||||||
|
IMPORT_RESPONSE=$(curl -s -w "\n%{http_code}" -X POST \
|
||||||
|
-H "X-Management-Key: ${API_SECRET}" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d @"${STATS_FILE}" \
|
||||||
|
"http://localhost:${port}/v0/management/usage/import")
|
||||||
|
IMPORT_CODE=$(echo "${IMPORT_RESPONSE}" | tail -n1)
|
||||||
|
IMPORT_BODY=$(echo "${IMPORT_RESPONSE}" | sed '$d')
|
||||||
|
|
||||||
|
if [[ "${IMPORT_CODE}" == "200" ]]; then
|
||||||
|
echo "Statistics imported successfully"
|
||||||
|
else
|
||||||
|
echo "Import failed (HTTP ${IMPORT_CODE}): ${IMPORT_BODY}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
rm -f "${STATS_FILE}"
|
||||||
|
}
|
||||||
|
|
||||||
|
wait_for_service() {
|
||||||
|
local port
|
||||||
|
port=$(get_port)
|
||||||
|
|
||||||
|
echo "Waiting for service to be ready..."
|
||||||
|
for i in {1..30}; do
|
||||||
|
if curl -s -o /dev/null -w "%{http_code}" "http://localhost:${port}/" | grep -q "200"; then
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
sleep 2
|
||||||
|
}
|
||||||
|
|
||||||
|
if [[ "${1:-}" == "--with-usage" ]]; then
|
||||||
|
WITH_USAGE=true
|
||||||
|
export_stats_api_secret
|
||||||
|
fi
|
||||||
|
|
||||||
# --- Step 1: Choose Environment ---
|
# --- Step 1: Choose Environment ---
|
||||||
echo "Please select an option:"
|
echo "Please select an option:"
|
||||||
echo "1) Run using Pre-built Image (Recommended)"
|
echo "1) Run using Pre-built Image (Recommended)"
|
||||||
@@ -18,7 +124,14 @@ read -r -p "Enter choice [1-2]: " choice
|
|||||||
case "$choice" in
|
case "$choice" in
|
||||||
1)
|
1)
|
||||||
echo "--- Running with Pre-built Image ---"
|
echo "--- Running with Pre-built Image ---"
|
||||||
|
if [[ "${WITH_USAGE}" == "true" ]]; then
|
||||||
|
export_stats
|
||||||
|
fi
|
||||||
docker compose up -d --remove-orphans --no-build
|
docker compose up -d --remove-orphans --no-build
|
||||||
|
if [[ "${WITH_USAGE}" == "true" ]]; then
|
||||||
|
wait_for_service
|
||||||
|
import_stats
|
||||||
|
fi
|
||||||
echo "Services are starting from remote image."
|
echo "Services are starting from remote image."
|
||||||
echo "Run 'docker compose logs -f' to see the logs."
|
echo "Run 'docker compose logs -f' to see the logs."
|
||||||
;;
|
;;
|
||||||
@@ -38,7 +151,11 @@ case "$choice" in
|
|||||||
|
|
||||||
# Build and start the services with a local-only image tag
|
# Build and start the services with a local-only image tag
|
||||||
export CLI_PROXY_IMAGE="cli-proxy-api:local"
|
export CLI_PROXY_IMAGE="cli-proxy-api:local"
|
||||||
|
|
||||||
|
if [[ "${WITH_USAGE}" == "true" ]]; then
|
||||||
|
export_stats
|
||||||
|
fi
|
||||||
|
|
||||||
echo "Building the Docker image..."
|
echo "Building the Docker image..."
|
||||||
docker compose build \
|
docker compose build \
|
||||||
--build-arg VERSION="${VERSION}" \
|
--build-arg VERSION="${VERSION}" \
|
||||||
@@ -48,6 +165,11 @@ case "$choice" in
|
|||||||
echo "Starting the services..."
|
echo "Starting the services..."
|
||||||
docker compose up -d --remove-orphans --pull never
|
docker compose up -d --remove-orphans --pull never
|
||||||
|
|
||||||
|
if [[ "${WITH_USAGE}" == "true" ]]; then
|
||||||
|
wait_for_service
|
||||||
|
import_stats
|
||||||
|
fi
|
||||||
|
|
||||||
echo "Build complete. Services are starting."
|
echo "Build complete. Services are starting."
|
||||||
echo "Run 'docker compose logs -f' to see the logs."
|
echo "Run 'docker compose logs -f' to see the logs."
|
||||||
;;
|
;;
|
||||||
@@ -55,4 +177,4 @@ case "$choice" in
|
|||||||
echo "Invalid choice. Please enter 1 or 2."
|
echo "Invalid choice. Please enter 1 or 2."
|
||||||
exit 1
|
exit 1
|
||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
|
|||||||
@@ -202,6 +202,26 @@ func (h *Handler) PutLoggingToFile(c *gin.Context) {
|
|||||||
h.updateBoolField(c, func(v bool) { h.cfg.LoggingToFile = v })
|
h.updateBoolField(c, func(v bool) { h.cfg.LoggingToFile = v })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// LogsMaxTotalSizeMB
|
||||||
|
func (h *Handler) GetLogsMaxTotalSizeMB(c *gin.Context) {
|
||||||
|
c.JSON(200, gin.H{"logs-max-total-size-mb": h.cfg.LogsMaxTotalSizeMB})
|
||||||
|
}
|
||||||
|
func (h *Handler) PutLogsMaxTotalSizeMB(c *gin.Context) {
|
||||||
|
var body struct {
|
||||||
|
Value *int `json:"value"`
|
||||||
|
}
|
||||||
|
if errBindJSON := c.ShouldBindJSON(&body); errBindJSON != nil || body.Value == nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
value := *body.Value
|
||||||
|
if value < 0 {
|
||||||
|
value = 0
|
||||||
|
}
|
||||||
|
h.cfg.LogsMaxTotalSizeMB = value
|
||||||
|
h.persist(c)
|
||||||
|
}
|
||||||
|
|
||||||
// Request log
|
// Request log
|
||||||
func (h *Handler) GetRequestLog(c *gin.Context) { c.JSON(200, gin.H{"request-log": h.cfg.RequestLog}) }
|
func (h *Handler) GetRequestLog(c *gin.Context) { c.JSON(200, gin.H{"request-log": h.cfg.RequestLog}) }
|
||||||
func (h *Handler) PutRequestLog(c *gin.Context) {
|
func (h *Handler) PutRequestLog(c *gin.Context) {
|
||||||
@@ -232,6 +252,52 @@ func (h *Handler) PutMaxRetryInterval(c *gin.Context) {
|
|||||||
h.updateIntField(c, func(v int) { h.cfg.MaxRetryInterval = v })
|
h.updateIntField(c, func(v int) { h.cfg.MaxRetryInterval = v })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ForceModelPrefix
|
||||||
|
func (h *Handler) GetForceModelPrefix(c *gin.Context) {
|
||||||
|
c.JSON(200, gin.H{"force-model-prefix": h.cfg.ForceModelPrefix})
|
||||||
|
}
|
||||||
|
func (h *Handler) PutForceModelPrefix(c *gin.Context) {
|
||||||
|
h.updateBoolField(c, func(v bool) { h.cfg.ForceModelPrefix = v })
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeRoutingStrategy(strategy string) (string, bool) {
|
||||||
|
normalized := strings.ToLower(strings.TrimSpace(strategy))
|
||||||
|
switch normalized {
|
||||||
|
case "", "round-robin", "roundrobin", "rr":
|
||||||
|
return "round-robin", true
|
||||||
|
case "fill-first", "fillfirst", "ff":
|
||||||
|
return "fill-first", true
|
||||||
|
default:
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RoutingStrategy
|
||||||
|
func (h *Handler) GetRoutingStrategy(c *gin.Context) {
|
||||||
|
strategy, ok := normalizeRoutingStrategy(h.cfg.Routing.Strategy)
|
||||||
|
if !ok {
|
||||||
|
c.JSON(200, gin.H{"strategy": strings.TrimSpace(h.cfg.Routing.Strategy)})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(200, gin.H{"strategy": strategy})
|
||||||
|
}
|
||||||
|
func (h *Handler) PutRoutingStrategy(c *gin.Context) {
|
||||||
|
var body struct {
|
||||||
|
Value *string `json:"value"`
|
||||||
|
}
|
||||||
|
if errBindJSON := c.ShouldBindJSON(&body); errBindJSON != nil || body.Value == nil {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
normalized, ok := normalizeRoutingStrategy(*body.Value)
|
||||||
|
if !ok {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid strategy"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.cfg.Routing.Strategy = normalized
|
||||||
|
h.persist(c)
|
||||||
|
}
|
||||||
|
|
||||||
// Proxy URL
|
// Proxy URL
|
||||||
func (h *Handler) GetProxyURL(c *gin.Context) { c.JSON(200, gin.H{"proxy-url": h.cfg.ProxyURL}) }
|
func (h *Handler) GetProxyURL(c *gin.Context) { c.JSON(200, gin.H{"proxy-url": h.cfg.ProxyURL}) }
|
||||||
func (h *Handler) PutProxyURL(c *gin.Context) {
|
func (h *Handler) PutProxyURL(c *gin.Context) {
|
||||||
|
|||||||
@@ -487,6 +487,137 @@ func (h *Handler) DeleteOpenAICompat(c *gin.Context) {
|
|||||||
c.JSON(400, gin.H{"error": "missing name or index"})
|
c.JSON(400, gin.H{"error": "missing name or index"})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// vertex-api-key: []VertexCompatKey
|
||||||
|
func (h *Handler) GetVertexCompatKeys(c *gin.Context) {
|
||||||
|
c.JSON(200, gin.H{"vertex-api-key": h.cfg.VertexCompatAPIKey})
|
||||||
|
}
|
||||||
|
func (h *Handler) PutVertexCompatKeys(c *gin.Context) {
|
||||||
|
data, err := c.GetRawData()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(400, gin.H{"error": "failed to read body"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var arr []config.VertexCompatKey
|
||||||
|
if err = json.Unmarshal(data, &arr); err != nil {
|
||||||
|
var obj struct {
|
||||||
|
Items []config.VertexCompatKey `json:"items"`
|
||||||
|
}
|
||||||
|
if err2 := json.Unmarshal(data, &obj); err2 != nil || len(obj.Items) == 0 {
|
||||||
|
c.JSON(400, gin.H{"error": "invalid body"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
arr = obj.Items
|
||||||
|
}
|
||||||
|
for i := range arr {
|
||||||
|
normalizeVertexCompatKey(&arr[i])
|
||||||
|
}
|
||||||
|
h.cfg.VertexCompatAPIKey = arr
|
||||||
|
h.cfg.SanitizeVertexCompatKeys()
|
||||||
|
h.persist(c)
|
||||||
|
}
|
||||||
|
func (h *Handler) PatchVertexCompatKey(c *gin.Context) {
|
||||||
|
type vertexCompatPatch struct {
|
||||||
|
APIKey *string `json:"api-key"`
|
||||||
|
Prefix *string `json:"prefix"`
|
||||||
|
BaseURL *string `json:"base-url"`
|
||||||
|
ProxyURL *string `json:"proxy-url"`
|
||||||
|
Headers *map[string]string `json:"headers"`
|
||||||
|
Models *[]config.VertexCompatModel `json:"models"`
|
||||||
|
}
|
||||||
|
var body struct {
|
||||||
|
Index *int `json:"index"`
|
||||||
|
Match *string `json:"match"`
|
||||||
|
Value *vertexCompatPatch `json:"value"`
|
||||||
|
}
|
||||||
|
if errBindJSON := c.ShouldBindJSON(&body); errBindJSON != nil || body.Value == nil {
|
||||||
|
c.JSON(400, gin.H{"error": "invalid body"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
targetIndex := -1
|
||||||
|
if body.Index != nil && *body.Index >= 0 && *body.Index < len(h.cfg.VertexCompatAPIKey) {
|
||||||
|
targetIndex = *body.Index
|
||||||
|
}
|
||||||
|
if targetIndex == -1 && body.Match != nil {
|
||||||
|
match := strings.TrimSpace(*body.Match)
|
||||||
|
if match != "" {
|
||||||
|
for i := range h.cfg.VertexCompatAPIKey {
|
||||||
|
if h.cfg.VertexCompatAPIKey[i].APIKey == match {
|
||||||
|
targetIndex = i
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if targetIndex == -1 {
|
||||||
|
c.JSON(404, gin.H{"error": "item not found"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
entry := h.cfg.VertexCompatAPIKey[targetIndex]
|
||||||
|
if body.Value.APIKey != nil {
|
||||||
|
trimmed := strings.TrimSpace(*body.Value.APIKey)
|
||||||
|
if trimmed == "" {
|
||||||
|
h.cfg.VertexCompatAPIKey = append(h.cfg.VertexCompatAPIKey[:targetIndex], h.cfg.VertexCompatAPIKey[targetIndex+1:]...)
|
||||||
|
h.cfg.SanitizeVertexCompatKeys()
|
||||||
|
h.persist(c)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
entry.APIKey = trimmed
|
||||||
|
}
|
||||||
|
if body.Value.Prefix != nil {
|
||||||
|
entry.Prefix = strings.TrimSpace(*body.Value.Prefix)
|
||||||
|
}
|
||||||
|
if body.Value.BaseURL != nil {
|
||||||
|
trimmed := strings.TrimSpace(*body.Value.BaseURL)
|
||||||
|
if trimmed == "" {
|
||||||
|
h.cfg.VertexCompatAPIKey = append(h.cfg.VertexCompatAPIKey[:targetIndex], h.cfg.VertexCompatAPIKey[targetIndex+1:]...)
|
||||||
|
h.cfg.SanitizeVertexCompatKeys()
|
||||||
|
h.persist(c)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
entry.BaseURL = trimmed
|
||||||
|
}
|
||||||
|
if body.Value.ProxyURL != nil {
|
||||||
|
entry.ProxyURL = strings.TrimSpace(*body.Value.ProxyURL)
|
||||||
|
}
|
||||||
|
if body.Value.Headers != nil {
|
||||||
|
entry.Headers = config.NormalizeHeaders(*body.Value.Headers)
|
||||||
|
}
|
||||||
|
if body.Value.Models != nil {
|
||||||
|
entry.Models = append([]config.VertexCompatModel(nil), (*body.Value.Models)...)
|
||||||
|
}
|
||||||
|
normalizeVertexCompatKey(&entry)
|
||||||
|
h.cfg.VertexCompatAPIKey[targetIndex] = entry
|
||||||
|
h.cfg.SanitizeVertexCompatKeys()
|
||||||
|
h.persist(c)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) DeleteVertexCompatKey(c *gin.Context) {
|
||||||
|
if val := strings.TrimSpace(c.Query("api-key")); val != "" {
|
||||||
|
out := make([]config.VertexCompatKey, 0, len(h.cfg.VertexCompatAPIKey))
|
||||||
|
for _, v := range h.cfg.VertexCompatAPIKey {
|
||||||
|
if v.APIKey != val {
|
||||||
|
out = append(out, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h.cfg.VertexCompatAPIKey = out
|
||||||
|
h.cfg.SanitizeVertexCompatKeys()
|
||||||
|
h.persist(c)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if idxStr := c.Query("index"); idxStr != "" {
|
||||||
|
var idx int
|
||||||
|
_, errScan := fmt.Sscanf(idxStr, "%d", &idx)
|
||||||
|
if errScan == nil && idx >= 0 && idx < len(h.cfg.VertexCompatAPIKey) {
|
||||||
|
h.cfg.VertexCompatAPIKey = append(h.cfg.VertexCompatAPIKey[:idx], h.cfg.VertexCompatAPIKey[idx+1:]...)
|
||||||
|
h.cfg.SanitizeVertexCompatKeys()
|
||||||
|
h.persist(c)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.JSON(400, gin.H{"error": "missing api-key or index"})
|
||||||
|
}
|
||||||
|
|
||||||
// oauth-excluded-models: map[string][]string
|
// oauth-excluded-models: map[string][]string
|
||||||
func (h *Handler) GetOAuthExcludedModels(c *gin.Context) {
|
func (h *Handler) GetOAuthExcludedModels(c *gin.Context) {
|
||||||
c.JSON(200, gin.H{"oauth-excluded-models": config.NormalizeOAuthExcludedModels(h.cfg.OAuthExcludedModels)})
|
c.JSON(200, gin.H{"oauth-excluded-models": config.NormalizeOAuthExcludedModels(h.cfg.OAuthExcludedModels)})
|
||||||
@@ -572,6 +703,103 @@ func (h *Handler) DeleteOAuthExcludedModels(c *gin.Context) {
|
|||||||
h.persist(c)
|
h.persist(c)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// oauth-model-mappings: map[string][]ModelNameMapping
|
||||||
|
func (h *Handler) GetOAuthModelMappings(c *gin.Context) {
|
||||||
|
c.JSON(200, gin.H{"oauth-model-mappings": sanitizedOAuthModelMappings(h.cfg.OAuthModelMappings)})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) PutOAuthModelMappings(c *gin.Context) {
|
||||||
|
data, err := c.GetRawData()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(400, gin.H{"error": "failed to read body"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var entries map[string][]config.ModelNameMapping
|
||||||
|
if err = json.Unmarshal(data, &entries); err != nil {
|
||||||
|
var wrapper struct {
|
||||||
|
Items map[string][]config.ModelNameMapping `json:"items"`
|
||||||
|
}
|
||||||
|
if err2 := json.Unmarshal(data, &wrapper); err2 != nil {
|
||||||
|
c.JSON(400, gin.H{"error": "invalid body"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
entries = wrapper.Items
|
||||||
|
}
|
||||||
|
h.cfg.OAuthModelMappings = sanitizedOAuthModelMappings(entries)
|
||||||
|
h.persist(c)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) PatchOAuthModelMappings(c *gin.Context) {
|
||||||
|
var body struct {
|
||||||
|
Provider *string `json:"provider"`
|
||||||
|
Channel *string `json:"channel"`
|
||||||
|
Mappings []config.ModelNameMapping `json:"mappings"`
|
||||||
|
}
|
||||||
|
if errBindJSON := c.ShouldBindJSON(&body); errBindJSON != nil {
|
||||||
|
c.JSON(400, gin.H{"error": "invalid body"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
channelRaw := ""
|
||||||
|
if body.Channel != nil {
|
||||||
|
channelRaw = *body.Channel
|
||||||
|
} else if body.Provider != nil {
|
||||||
|
channelRaw = *body.Provider
|
||||||
|
}
|
||||||
|
channel := strings.ToLower(strings.TrimSpace(channelRaw))
|
||||||
|
if channel == "" {
|
||||||
|
c.JSON(400, gin.H{"error": "invalid channel"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
normalizedMap := sanitizedOAuthModelMappings(map[string][]config.ModelNameMapping{channel: body.Mappings})
|
||||||
|
normalized := normalizedMap[channel]
|
||||||
|
if len(normalized) == 0 {
|
||||||
|
if h.cfg.OAuthModelMappings == nil {
|
||||||
|
c.JSON(404, gin.H{"error": "channel not found"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, ok := h.cfg.OAuthModelMappings[channel]; !ok {
|
||||||
|
c.JSON(404, gin.H{"error": "channel not found"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
delete(h.cfg.OAuthModelMappings, channel)
|
||||||
|
if len(h.cfg.OAuthModelMappings) == 0 {
|
||||||
|
h.cfg.OAuthModelMappings = nil
|
||||||
|
}
|
||||||
|
h.persist(c)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if h.cfg.OAuthModelMappings == nil {
|
||||||
|
h.cfg.OAuthModelMappings = make(map[string][]config.ModelNameMapping)
|
||||||
|
}
|
||||||
|
h.cfg.OAuthModelMappings[channel] = normalized
|
||||||
|
h.persist(c)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) DeleteOAuthModelMappings(c *gin.Context) {
|
||||||
|
channel := strings.ToLower(strings.TrimSpace(c.Query("channel")))
|
||||||
|
if channel == "" {
|
||||||
|
channel = strings.ToLower(strings.TrimSpace(c.Query("provider")))
|
||||||
|
}
|
||||||
|
if channel == "" {
|
||||||
|
c.JSON(400, gin.H{"error": "missing channel"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if h.cfg.OAuthModelMappings == nil {
|
||||||
|
c.JSON(404, gin.H{"error": "channel not found"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, ok := h.cfg.OAuthModelMappings[channel]; !ok {
|
||||||
|
c.JSON(404, gin.H{"error": "channel not found"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
delete(h.cfg.OAuthModelMappings, channel)
|
||||||
|
if len(h.cfg.OAuthModelMappings) == 0 {
|
||||||
|
h.cfg.OAuthModelMappings = nil
|
||||||
|
}
|
||||||
|
h.persist(c)
|
||||||
|
}
|
||||||
|
|
||||||
// codex-api-key: []CodexKey
|
// codex-api-key: []CodexKey
|
||||||
func (h *Handler) GetCodexKeys(c *gin.Context) {
|
func (h *Handler) GetCodexKeys(c *gin.Context) {
|
||||||
c.JSON(200, gin.H{"codex-api-key": h.cfg.CodexKey})
|
c.JSON(200, gin.H{"codex-api-key": h.cfg.CodexKey})
|
||||||
@@ -789,6 +1017,53 @@ func normalizeCodexKey(entry *config.CodexKey) {
|
|||||||
entry.Models = normalized
|
entry.Models = normalized
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func normalizeVertexCompatKey(entry *config.VertexCompatKey) {
|
||||||
|
if entry == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
entry.APIKey = strings.TrimSpace(entry.APIKey)
|
||||||
|
entry.Prefix = strings.TrimSpace(entry.Prefix)
|
||||||
|
entry.BaseURL = strings.TrimSpace(entry.BaseURL)
|
||||||
|
entry.ProxyURL = strings.TrimSpace(entry.ProxyURL)
|
||||||
|
entry.Headers = config.NormalizeHeaders(entry.Headers)
|
||||||
|
if len(entry.Models) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
normalized := make([]config.VertexCompatModel, 0, len(entry.Models))
|
||||||
|
for i := range entry.Models {
|
||||||
|
model := entry.Models[i]
|
||||||
|
model.Name = strings.TrimSpace(model.Name)
|
||||||
|
model.Alias = strings.TrimSpace(model.Alias)
|
||||||
|
if model.Name == "" || model.Alias == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
normalized = append(normalized, model)
|
||||||
|
}
|
||||||
|
entry.Models = normalized
|
||||||
|
}
|
||||||
|
|
||||||
|
func sanitizedOAuthModelMappings(entries map[string][]config.ModelNameMapping) map[string][]config.ModelNameMapping {
|
||||||
|
if len(entries) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
copied := make(map[string][]config.ModelNameMapping, len(entries))
|
||||||
|
for channel, mappings := range entries {
|
||||||
|
if len(mappings) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
copied[channel] = append([]config.ModelNameMapping(nil), mappings...)
|
||||||
|
}
|
||||||
|
if len(copied) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
cfg := config.Config{OAuthModelMappings: copied}
|
||||||
|
cfg.SanitizeOAuthModelMappings()
|
||||||
|
if len(cfg.OAuthModelMappings) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return cfg.OAuthModelMappings
|
||||||
|
}
|
||||||
|
|
||||||
// GetAmpCode returns the complete ampcode configuration.
|
// GetAmpCode returns the complete ampcode configuration.
|
||||||
func (h *Handler) GetAmpCode(c *gin.Context) {
|
func (h *Handler) GetAmpCode(c *gin.Context) {
|
||||||
if h == nil || h.cfg == nil {
|
if h == nil || h.cfg == nil {
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ import (
|
|||||||
"github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers/claude"
|
"github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers/claude"
|
||||||
"github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers/gemini"
|
"github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers/gemini"
|
||||||
"github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers/openai"
|
"github.com/router-for-me/CLIProxyAPI/v6/sdk/api/handlers/openai"
|
||||||
|
sdkAuth "github.com/router-for-me/CLIProxyAPI/v6/sdk/auth"
|
||||||
"github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
|
"github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
|
||||||
log "github.com/sirupsen/logrus"
|
log "github.com/sirupsen/logrus"
|
||||||
"gopkg.in/yaml.v3"
|
"gopkg.in/yaml.v3"
|
||||||
@@ -511,6 +512,10 @@ func (s *Server) registerManagementRoutes() {
|
|||||||
mgmt.PUT("/logging-to-file", s.mgmt.PutLoggingToFile)
|
mgmt.PUT("/logging-to-file", s.mgmt.PutLoggingToFile)
|
||||||
mgmt.PATCH("/logging-to-file", s.mgmt.PutLoggingToFile)
|
mgmt.PATCH("/logging-to-file", s.mgmt.PutLoggingToFile)
|
||||||
|
|
||||||
|
mgmt.GET("/logs-max-total-size-mb", s.mgmt.GetLogsMaxTotalSizeMB)
|
||||||
|
mgmt.PUT("/logs-max-total-size-mb", s.mgmt.PutLogsMaxTotalSizeMB)
|
||||||
|
mgmt.PATCH("/logs-max-total-size-mb", s.mgmt.PutLogsMaxTotalSizeMB)
|
||||||
|
|
||||||
mgmt.GET("/usage-statistics-enabled", s.mgmt.GetUsageStatisticsEnabled)
|
mgmt.GET("/usage-statistics-enabled", s.mgmt.GetUsageStatisticsEnabled)
|
||||||
mgmt.PUT("/usage-statistics-enabled", s.mgmt.PutUsageStatisticsEnabled)
|
mgmt.PUT("/usage-statistics-enabled", s.mgmt.PutUsageStatisticsEnabled)
|
||||||
mgmt.PATCH("/usage-statistics-enabled", s.mgmt.PutUsageStatisticsEnabled)
|
mgmt.PATCH("/usage-statistics-enabled", s.mgmt.PutUsageStatisticsEnabled)
|
||||||
@@ -583,6 +588,14 @@ func (s *Server) registerManagementRoutes() {
|
|||||||
mgmt.PUT("/max-retry-interval", s.mgmt.PutMaxRetryInterval)
|
mgmt.PUT("/max-retry-interval", s.mgmt.PutMaxRetryInterval)
|
||||||
mgmt.PATCH("/max-retry-interval", s.mgmt.PutMaxRetryInterval)
|
mgmt.PATCH("/max-retry-interval", s.mgmt.PutMaxRetryInterval)
|
||||||
|
|
||||||
|
mgmt.GET("/force-model-prefix", s.mgmt.GetForceModelPrefix)
|
||||||
|
mgmt.PUT("/force-model-prefix", s.mgmt.PutForceModelPrefix)
|
||||||
|
mgmt.PATCH("/force-model-prefix", s.mgmt.PutForceModelPrefix)
|
||||||
|
|
||||||
|
mgmt.GET("/routing/strategy", s.mgmt.GetRoutingStrategy)
|
||||||
|
mgmt.PUT("/routing/strategy", s.mgmt.PutRoutingStrategy)
|
||||||
|
mgmt.PATCH("/routing/strategy", s.mgmt.PutRoutingStrategy)
|
||||||
|
|
||||||
mgmt.GET("/claude-api-key", s.mgmt.GetClaudeKeys)
|
mgmt.GET("/claude-api-key", s.mgmt.GetClaudeKeys)
|
||||||
mgmt.PUT("/claude-api-key", s.mgmt.PutClaudeKeys)
|
mgmt.PUT("/claude-api-key", s.mgmt.PutClaudeKeys)
|
||||||
mgmt.PATCH("/claude-api-key", s.mgmt.PatchClaudeKey)
|
mgmt.PATCH("/claude-api-key", s.mgmt.PatchClaudeKey)
|
||||||
@@ -598,11 +611,21 @@ func (s *Server) registerManagementRoutes() {
|
|||||||
mgmt.PATCH("/openai-compatibility", s.mgmt.PatchOpenAICompat)
|
mgmt.PATCH("/openai-compatibility", s.mgmt.PatchOpenAICompat)
|
||||||
mgmt.DELETE("/openai-compatibility", s.mgmt.DeleteOpenAICompat)
|
mgmt.DELETE("/openai-compatibility", s.mgmt.DeleteOpenAICompat)
|
||||||
|
|
||||||
|
mgmt.GET("/vertex-api-key", s.mgmt.GetVertexCompatKeys)
|
||||||
|
mgmt.PUT("/vertex-api-key", s.mgmt.PutVertexCompatKeys)
|
||||||
|
mgmt.PATCH("/vertex-api-key", s.mgmt.PatchVertexCompatKey)
|
||||||
|
mgmt.DELETE("/vertex-api-key", s.mgmt.DeleteVertexCompatKey)
|
||||||
|
|
||||||
mgmt.GET("/oauth-excluded-models", s.mgmt.GetOAuthExcludedModels)
|
mgmt.GET("/oauth-excluded-models", s.mgmt.GetOAuthExcludedModels)
|
||||||
mgmt.PUT("/oauth-excluded-models", s.mgmt.PutOAuthExcludedModels)
|
mgmt.PUT("/oauth-excluded-models", s.mgmt.PutOAuthExcludedModels)
|
||||||
mgmt.PATCH("/oauth-excluded-models", s.mgmt.PatchOAuthExcludedModels)
|
mgmt.PATCH("/oauth-excluded-models", s.mgmt.PatchOAuthExcludedModels)
|
||||||
mgmt.DELETE("/oauth-excluded-models", s.mgmt.DeleteOAuthExcludedModels)
|
mgmt.DELETE("/oauth-excluded-models", s.mgmt.DeleteOAuthExcludedModels)
|
||||||
|
|
||||||
|
mgmt.GET("/oauth-model-mappings", s.mgmt.GetOAuthModelMappings)
|
||||||
|
mgmt.PUT("/oauth-model-mappings", s.mgmt.PutOAuthModelMappings)
|
||||||
|
mgmt.PATCH("/oauth-model-mappings", s.mgmt.PatchOAuthModelMappings)
|
||||||
|
mgmt.DELETE("/oauth-model-mappings", s.mgmt.DeleteOAuthModelMappings)
|
||||||
|
|
||||||
mgmt.GET("/auth-files", s.mgmt.ListAuthFiles)
|
mgmt.GET("/auth-files", s.mgmt.ListAuthFiles)
|
||||||
mgmt.GET("/auth-files/models", s.mgmt.GetAuthFileModels)
|
mgmt.GET("/auth-files/models", s.mgmt.GetAuthFileModels)
|
||||||
mgmt.GET("/auth-files/download", s.mgmt.DownloadAuthFile)
|
mgmt.GET("/auth-files/download", s.mgmt.DownloadAuthFile)
|
||||||
@@ -987,8 +1010,12 @@ func (s *Server) UpdateClients(cfg *config.Config) {
|
|||||||
log.Warnf("amp module is nil, skipping config update")
|
log.Warnf("amp module is nil, skipping config update")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Count client sources from configuration and auth directory
|
// Count client sources from configuration and auth store.
|
||||||
authFiles := util.CountAuthFiles(cfg.AuthDir)
|
tokenStore := sdkAuth.GetTokenStore()
|
||||||
|
if dirSetter, ok := tokenStore.(interface{ SetBaseDir(string) }); ok {
|
||||||
|
dirSetter.SetBaseDir(cfg.AuthDir)
|
||||||
|
}
|
||||||
|
authEntries := util.CountAuthFiles(context.Background(), tokenStore)
|
||||||
geminiAPIKeyCount := len(cfg.GeminiKey)
|
geminiAPIKeyCount := len(cfg.GeminiKey)
|
||||||
claudeAPIKeyCount := len(cfg.ClaudeKey)
|
claudeAPIKeyCount := len(cfg.ClaudeKey)
|
||||||
codexAPIKeyCount := len(cfg.CodexKey)
|
codexAPIKeyCount := len(cfg.CodexKey)
|
||||||
@@ -999,10 +1026,10 @@ func (s *Server) UpdateClients(cfg *config.Config) {
|
|||||||
openAICompatCount += len(entry.APIKeyEntries)
|
openAICompatCount += len(entry.APIKeyEntries)
|
||||||
}
|
}
|
||||||
|
|
||||||
total := authFiles + geminiAPIKeyCount + claudeAPIKeyCount + codexAPIKeyCount + vertexAICompatCount + openAICompatCount
|
total := authEntries + geminiAPIKeyCount + claudeAPIKeyCount + codexAPIKeyCount + vertexAICompatCount + openAICompatCount
|
||||||
fmt.Printf("server clients and configuration updated: %d clients (%d auth files + %d Gemini API keys + %d Claude API keys + %d Codex keys + %d Vertex-compat + %d OpenAI-compat)\n",
|
fmt.Printf("server clients and configuration updated: %d clients (%d auth entries + %d Gemini API keys + %d Claude API keys + %d Codex keys + %d Vertex-compat + %d OpenAI-compat)\n",
|
||||||
total,
|
total,
|
||||||
authFiles,
|
authEntries,
|
||||||
geminiAPIKeyCount,
|
geminiAPIKeyCount,
|
||||||
claudeAPIKeyCount,
|
claudeAPIKeyCount,
|
||||||
codexAPIKeyCount,
|
codexAPIKeyCount,
|
||||||
|
|||||||
@@ -157,11 +157,14 @@ type RoutingConfig struct {
|
|||||||
Strategy string `yaml:"strategy,omitempty" json:"strategy,omitempty"`
|
Strategy string `yaml:"strategy,omitempty" json:"strategy,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ModelNameMapping defines a model ID rename mapping for a specific channel.
|
// ModelNameMapping defines a model ID mapping for a specific channel.
|
||||||
// It maps the original model name (Name) to the client-visible alias (Alias).
|
// It maps the upstream model name (Name) to the client-visible alias (Alias).
|
||||||
|
// When Fork is true, the alias is added as an additional model in listings while
|
||||||
|
// keeping the original model ID available.
|
||||||
type ModelNameMapping struct {
|
type ModelNameMapping struct {
|
||||||
Name string `yaml:"name" json:"name"`
|
Name string `yaml:"name" json:"name"`
|
||||||
Alias string `yaml:"alias" json:"alias"`
|
Alias string `yaml:"alias" json:"alias"`
|
||||||
|
Fork bool `yaml:"fork,omitempty" json:"fork,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// AmpModelMapping defines a model name mapping for Amp CLI requests.
|
// AmpModelMapping defines a model name mapping for Amp CLI requests.
|
||||||
@@ -596,7 +599,7 @@ func (cfg *Config) SanitizeOAuthModelMappings() {
|
|||||||
}
|
}
|
||||||
seenName[nameKey] = struct{}{}
|
seenName[nameKey] = struct{}{}
|
||||||
seenAlias[aliasKey] = struct{}{}
|
seenAlias[aliasKey] = struct{}{}
|
||||||
clean = append(clean, ModelNameMapping{Name: name, Alias: alias})
|
clean = append(clean, ModelNameMapping{Name: name, Alias: alias, Fork: mapping.Fork})
|
||||||
}
|
}
|
||||||
if len(clean) > 0 {
|
if len(clean) > 0 {
|
||||||
out[channel] = clean
|
out[channel] = clean
|
||||||
|
|||||||
27
internal/config/oauth_model_mappings_test.go
Normal file
27
internal/config/oauth_model_mappings_test.go
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestSanitizeOAuthModelMappings_PreservesForkFlag(t *testing.T) {
|
||||||
|
cfg := &Config{
|
||||||
|
OAuthModelMappings: map[string][]ModelNameMapping{
|
||||||
|
" CoDeX ": {
|
||||||
|
{Name: " gpt-5 ", Alias: " g5 ", Fork: true},
|
||||||
|
{Name: "gpt-6", Alias: "g6"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg.SanitizeOAuthModelMappings()
|
||||||
|
|
||||||
|
mappings := cfg.OAuthModelMappings["codex"]
|
||||||
|
if len(mappings) != 2 {
|
||||||
|
t.Fatalf("expected 2 sanitized mappings, got %d", len(mappings))
|
||||||
|
}
|
||||||
|
if mappings[0].Name != "gpt-5" || mappings[0].Alias != "g5" || !mappings[0].Fork {
|
||||||
|
t.Fatalf("expected first mapping to be gpt-5->g5 fork=true, got name=%q alias=%q fork=%v", mappings[0].Name, mappings[0].Alias, mappings[0].Fork)
|
||||||
|
}
|
||||||
|
if mappings[1].Name != "gpt-6" || mappings[1].Alias != "g6" || mappings[1].Fork {
|
||||||
|
t.Fatalf("expected second mapping to be gpt-6->g6 fork=false, got name=%q alias=%q fork=%v", mappings[1].Name, mappings[1].Alias, mappings[1].Fork)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@
|
|||||||
package registry
|
package registry
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -84,6 +85,13 @@ type ModelRegistration struct {
|
|||||||
SuspendedClients map[string]string
|
SuspendedClients map[string]string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ModelRegistryHook provides optional callbacks for external integrations to track model list changes.
|
||||||
|
// Hook implementations must be non-blocking and resilient; calls are executed asynchronously and panics are recovered.
|
||||||
|
type ModelRegistryHook interface {
|
||||||
|
OnModelsRegistered(ctx context.Context, provider, clientID string, models []*ModelInfo)
|
||||||
|
OnModelsUnregistered(ctx context.Context, provider, clientID string)
|
||||||
|
}
|
||||||
|
|
||||||
// ModelRegistry manages the global registry of available models
|
// ModelRegistry manages the global registry of available models
|
||||||
type ModelRegistry struct {
|
type ModelRegistry struct {
|
||||||
// models maps model ID to registration information
|
// models maps model ID to registration information
|
||||||
@@ -97,6 +105,8 @@ type ModelRegistry struct {
|
|||||||
clientProviders map[string]string
|
clientProviders map[string]string
|
||||||
// mutex ensures thread-safe access to the registry
|
// mutex ensures thread-safe access to the registry
|
||||||
mutex *sync.RWMutex
|
mutex *sync.RWMutex
|
||||||
|
// hook is an optional callback sink for model registration changes
|
||||||
|
hook ModelRegistryHook
|
||||||
}
|
}
|
||||||
|
|
||||||
// Global model registry instance
|
// Global model registry instance
|
||||||
@@ -117,6 +127,53 @@ func GetGlobalRegistry() *ModelRegistry {
|
|||||||
return globalRegistry
|
return globalRegistry
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetHook sets an optional hook for observing model registration changes.
|
||||||
|
func (r *ModelRegistry) SetHook(hook ModelRegistryHook) {
|
||||||
|
if r == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
r.mutex.Lock()
|
||||||
|
defer r.mutex.Unlock()
|
||||||
|
r.hook = hook
|
||||||
|
}
|
||||||
|
|
||||||
|
const defaultModelRegistryHookTimeout = 5 * time.Second
|
||||||
|
|
||||||
|
func (r *ModelRegistry) triggerModelsRegistered(provider, clientID string, models []*ModelInfo) {
|
||||||
|
hook := r.hook
|
||||||
|
if hook == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
modelsCopy := cloneModelInfosUnique(models)
|
||||||
|
go func() {
|
||||||
|
defer func() {
|
||||||
|
if recovered := recover(); recovered != nil {
|
||||||
|
log.Errorf("model registry hook OnModelsRegistered panic: %v", recovered)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), defaultModelRegistryHookTimeout)
|
||||||
|
defer cancel()
|
||||||
|
hook.OnModelsRegistered(ctx, provider, clientID, modelsCopy)
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *ModelRegistry) triggerModelsUnregistered(provider, clientID string) {
|
||||||
|
hook := r.hook
|
||||||
|
if hook == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
go func() {
|
||||||
|
defer func() {
|
||||||
|
if recovered := recover(); recovered != nil {
|
||||||
|
log.Errorf("model registry hook OnModelsUnregistered panic: %v", recovered)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), defaultModelRegistryHookTimeout)
|
||||||
|
defer cancel()
|
||||||
|
hook.OnModelsUnregistered(ctx, provider, clientID)
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
// RegisterClient registers a client and its supported models
|
// RegisterClient registers a client and its supported models
|
||||||
// Parameters:
|
// Parameters:
|
||||||
// - clientID: Unique identifier for the client
|
// - clientID: Unique identifier for the client
|
||||||
@@ -177,6 +234,7 @@ func (r *ModelRegistry) RegisterClient(clientID, clientProvider string, models [
|
|||||||
} else {
|
} else {
|
||||||
delete(r.clientProviders, clientID)
|
delete(r.clientProviders, clientID)
|
||||||
}
|
}
|
||||||
|
r.triggerModelsRegistered(provider, clientID, models)
|
||||||
log.Debugf("Registered client %s from provider %s with %d models", clientID, clientProvider, len(rawModelIDs))
|
log.Debugf("Registered client %s from provider %s with %d models", clientID, clientProvider, len(rawModelIDs))
|
||||||
misc.LogCredentialSeparator()
|
misc.LogCredentialSeparator()
|
||||||
return
|
return
|
||||||
@@ -310,6 +368,7 @@ func (r *ModelRegistry) RegisterClient(clientID, clientProvider string, models [
|
|||||||
delete(r.clientProviders, clientID)
|
delete(r.clientProviders, clientID)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
r.triggerModelsRegistered(provider, clientID, models)
|
||||||
if len(added) == 0 && len(removed) == 0 && !providerChanged {
|
if len(added) == 0 && len(removed) == 0 && !providerChanged {
|
||||||
// Only metadata (e.g., display name) changed; skip separator when no log output.
|
// Only metadata (e.g., display name) changed; skip separator when no log output.
|
||||||
return
|
return
|
||||||
@@ -400,6 +459,25 @@ func cloneModelInfo(model *ModelInfo) *ModelInfo {
|
|||||||
return ©Model
|
return ©Model
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func cloneModelInfosUnique(models []*ModelInfo) []*ModelInfo {
|
||||||
|
if len(models) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
cloned := make([]*ModelInfo, 0, len(models))
|
||||||
|
seen := make(map[string]struct{}, len(models))
|
||||||
|
for _, model := range models {
|
||||||
|
if model == nil || model.ID == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, exists := seen[model.ID]; exists {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[model.ID] = struct{}{}
|
||||||
|
cloned = append(cloned, cloneModelInfo(model))
|
||||||
|
}
|
||||||
|
return cloned
|
||||||
|
}
|
||||||
|
|
||||||
// UnregisterClient removes a client and decrements counts for its models
|
// UnregisterClient removes a client and decrements counts for its models
|
||||||
// Parameters:
|
// Parameters:
|
||||||
// - clientID: Unique identifier for the client to remove
|
// - clientID: Unique identifier for the client to remove
|
||||||
@@ -460,6 +538,7 @@ func (r *ModelRegistry) unregisterClientInternal(clientID string) {
|
|||||||
log.Debugf("Unregistered client %s", clientID)
|
log.Debugf("Unregistered client %s", clientID)
|
||||||
// Separator line after completing client unregistration (after the summary line)
|
// Separator line after completing client unregistration (after the summary line)
|
||||||
misc.LogCredentialSeparator()
|
misc.LogCredentialSeparator()
|
||||||
|
r.triggerModelsUnregistered(provider, clientID)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetModelQuotaExceeded marks a model as quota exceeded for a specific client
|
// SetModelQuotaExceeded marks a model as quota exceeded for a specific client
|
||||||
|
|||||||
204
internal/registry/model_registry_hook_test.go
Normal file
204
internal/registry/model_registry_hook_test.go
Normal file
@@ -0,0 +1,204 @@
|
|||||||
|
package registry
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func newTestModelRegistry() *ModelRegistry {
|
||||||
|
return &ModelRegistry{
|
||||||
|
models: make(map[string]*ModelRegistration),
|
||||||
|
clientModels: make(map[string][]string),
|
||||||
|
clientModelInfos: make(map[string]map[string]*ModelInfo),
|
||||||
|
clientProviders: make(map[string]string),
|
||||||
|
mutex: &sync.RWMutex{},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type registeredCall struct {
|
||||||
|
provider string
|
||||||
|
clientID string
|
||||||
|
models []*ModelInfo
|
||||||
|
}
|
||||||
|
|
||||||
|
type unregisteredCall struct {
|
||||||
|
provider string
|
||||||
|
clientID string
|
||||||
|
}
|
||||||
|
|
||||||
|
type capturingHook struct {
|
||||||
|
registeredCh chan registeredCall
|
||||||
|
unregisteredCh chan unregisteredCall
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *capturingHook) OnModelsRegistered(ctx context.Context, provider, clientID string, models []*ModelInfo) {
|
||||||
|
h.registeredCh <- registeredCall{provider: provider, clientID: clientID, models: models}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *capturingHook) OnModelsUnregistered(ctx context.Context, provider, clientID string) {
|
||||||
|
h.unregisteredCh <- unregisteredCall{provider: provider, clientID: clientID}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestModelRegistryHook_OnModelsRegisteredCalled(t *testing.T) {
|
||||||
|
r := newTestModelRegistry()
|
||||||
|
hook := &capturingHook{
|
||||||
|
registeredCh: make(chan registeredCall, 1),
|
||||||
|
unregisteredCh: make(chan unregisteredCall, 1),
|
||||||
|
}
|
||||||
|
r.SetHook(hook)
|
||||||
|
|
||||||
|
inputModels := []*ModelInfo{
|
||||||
|
{ID: "m1", DisplayName: "Model One"},
|
||||||
|
{ID: "m2", DisplayName: "Model Two"},
|
||||||
|
}
|
||||||
|
r.RegisterClient("client-1", "OpenAI", inputModels)
|
||||||
|
|
||||||
|
select {
|
||||||
|
case call := <-hook.registeredCh:
|
||||||
|
if call.provider != "openai" {
|
||||||
|
t.Fatalf("provider mismatch: got %q, want %q", call.provider, "openai")
|
||||||
|
}
|
||||||
|
if call.clientID != "client-1" {
|
||||||
|
t.Fatalf("clientID mismatch: got %q, want %q", call.clientID, "client-1")
|
||||||
|
}
|
||||||
|
if len(call.models) != 2 {
|
||||||
|
t.Fatalf("models length mismatch: got %d, want %d", len(call.models), 2)
|
||||||
|
}
|
||||||
|
if call.models[0] == nil || call.models[0].ID != "m1" {
|
||||||
|
t.Fatalf("models[0] mismatch: got %#v, want ID=%q", call.models[0], "m1")
|
||||||
|
}
|
||||||
|
if call.models[1] == nil || call.models[1].ID != "m2" {
|
||||||
|
t.Fatalf("models[1] mismatch: got %#v, want ID=%q", call.models[1], "m2")
|
||||||
|
}
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("timeout waiting for OnModelsRegistered hook call")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestModelRegistryHook_OnModelsUnregisteredCalled(t *testing.T) {
|
||||||
|
r := newTestModelRegistry()
|
||||||
|
hook := &capturingHook{
|
||||||
|
registeredCh: make(chan registeredCall, 1),
|
||||||
|
unregisteredCh: make(chan unregisteredCall, 1),
|
||||||
|
}
|
||||||
|
r.SetHook(hook)
|
||||||
|
|
||||||
|
r.RegisterClient("client-1", "OpenAI", []*ModelInfo{{ID: "m1"}})
|
||||||
|
select {
|
||||||
|
case <-hook.registeredCh:
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("timeout waiting for OnModelsRegistered hook call")
|
||||||
|
}
|
||||||
|
|
||||||
|
r.UnregisterClient("client-1")
|
||||||
|
|
||||||
|
select {
|
||||||
|
case call := <-hook.unregisteredCh:
|
||||||
|
if call.provider != "openai" {
|
||||||
|
t.Fatalf("provider mismatch: got %q, want %q", call.provider, "openai")
|
||||||
|
}
|
||||||
|
if call.clientID != "client-1" {
|
||||||
|
t.Fatalf("clientID mismatch: got %q, want %q", call.clientID, "client-1")
|
||||||
|
}
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("timeout waiting for OnModelsUnregistered hook call")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type blockingHook struct {
|
||||||
|
started chan struct{}
|
||||||
|
unblock chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *blockingHook) OnModelsRegistered(ctx context.Context, provider, clientID string, models []*ModelInfo) {
|
||||||
|
select {
|
||||||
|
case <-h.started:
|
||||||
|
default:
|
||||||
|
close(h.started)
|
||||||
|
}
|
||||||
|
<-h.unblock
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *blockingHook) OnModelsUnregistered(ctx context.Context, provider, clientID string) {}
|
||||||
|
|
||||||
|
func TestModelRegistryHook_DoesNotBlockRegisterClient(t *testing.T) {
|
||||||
|
r := newTestModelRegistry()
|
||||||
|
hook := &blockingHook{
|
||||||
|
started: make(chan struct{}),
|
||||||
|
unblock: make(chan struct{}),
|
||||||
|
}
|
||||||
|
r.SetHook(hook)
|
||||||
|
defer close(hook.unblock)
|
||||||
|
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
r.RegisterClient("client-1", "OpenAI", []*ModelInfo{{ID: "m1"}})
|
||||||
|
close(done)
|
||||||
|
}()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-hook.started:
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("timeout waiting for hook to start")
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(200 * time.Millisecond):
|
||||||
|
t.Fatal("RegisterClient appears to be blocked by hook")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !r.ClientSupportsModel("client-1", "m1") {
|
||||||
|
t.Fatal("model registration failed; expected client to support model")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type panicHook struct {
|
||||||
|
registeredCalled chan struct{}
|
||||||
|
unregisteredCalled chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *panicHook) OnModelsRegistered(ctx context.Context, provider, clientID string, models []*ModelInfo) {
|
||||||
|
if h.registeredCalled != nil {
|
||||||
|
h.registeredCalled <- struct{}{}
|
||||||
|
}
|
||||||
|
panic("boom")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *panicHook) OnModelsUnregistered(ctx context.Context, provider, clientID string) {
|
||||||
|
if h.unregisteredCalled != nil {
|
||||||
|
h.unregisteredCalled <- struct{}{}
|
||||||
|
}
|
||||||
|
panic("boom")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestModelRegistryHook_PanicDoesNotAffectRegistry(t *testing.T) {
|
||||||
|
r := newTestModelRegistry()
|
||||||
|
hook := &panicHook{
|
||||||
|
registeredCalled: make(chan struct{}, 1),
|
||||||
|
unregisteredCalled: make(chan struct{}, 1),
|
||||||
|
}
|
||||||
|
r.SetHook(hook)
|
||||||
|
|
||||||
|
r.RegisterClient("client-1", "OpenAI", []*ModelInfo{{ID: "m1"}})
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-hook.registeredCalled:
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("timeout waiting for OnModelsRegistered hook call")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !r.ClientSupportsModel("client-1", "m1") {
|
||||||
|
t.Fatal("model registration failed; expected client to support model")
|
||||||
|
}
|
||||||
|
|
||||||
|
r.UnregisterClient("client-1")
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-hook.unregisteredCalled:
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("timeout waiting for OnModelsUnregistered hook call")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -45,6 +45,7 @@ const (
|
|||||||
defaultAntigravityAgent = "antigravity/1.104.0 darwin/arm64"
|
defaultAntigravityAgent = "antigravity/1.104.0 darwin/arm64"
|
||||||
antigravityAuthType = "antigravity"
|
antigravityAuthType = "antigravity"
|
||||||
refreshSkew = 3000 * time.Second
|
refreshSkew = 3000 * time.Second
|
||||||
|
tokenRefreshTimeout = 30 * time.Second
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -914,7 +915,13 @@ func (e *AntigravityExecutor) ensureAccessToken(ctx context.Context, auth *clipr
|
|||||||
if accessToken != "" && expiry.After(time.Now().Add(refreshSkew)) {
|
if accessToken != "" && expiry.After(time.Now().Add(refreshSkew)) {
|
||||||
return accessToken, nil, nil
|
return accessToken, nil, nil
|
||||||
}
|
}
|
||||||
updated, errRefresh := e.refreshToken(ctx, auth.Clone())
|
refreshCtx := context.Background()
|
||||||
|
if ctx != nil {
|
||||||
|
if rt, ok := ctx.Value("cliproxy.roundtripper").(http.RoundTripper); ok && rt != nil {
|
||||||
|
refreshCtx = context.WithValue(refreshCtx, "cliproxy.roundtripper", rt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
updated, errRefresh := e.refreshToken(refreshCtx, auth.Clone())
|
||||||
if errRefresh != nil {
|
if errRefresh != nil {
|
||||||
return "", nil, errRefresh
|
return "", nil, errRefresh
|
||||||
}
|
}
|
||||||
@@ -944,7 +951,7 @@ func (e *AntigravityExecutor) refreshToken(ctx context.Context, auth *cliproxyau
|
|||||||
httpReq.Header.Set("User-Agent", defaultAntigravityAgent)
|
httpReq.Header.Set("User-Agent", defaultAntigravityAgent)
|
||||||
httpReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
httpReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
|
||||||
httpClient := newProxyAwareHTTPClient(ctx, e.cfg, auth, 0)
|
httpClient := newProxyAwareHTTPClient(ctx, e.cfg, auth, tokenRefreshTimeout)
|
||||||
httpResp, errDo := httpClient.Do(httpReq)
|
httpResp, errDo := httpClient.Do(httpReq)
|
||||||
if errDo != nil {
|
if errDo != nil {
|
||||||
return auth, errDo
|
return auth, errDo
|
||||||
|
|||||||
@@ -79,9 +79,14 @@ func (e *GitHubCopilotExecutor) Execute(ctx context.Context, auth *cliproxyauth.
|
|||||||
|
|
||||||
from := opts.SourceFormat
|
from := opts.SourceFormat
|
||||||
to := sdktranslator.FromString("openai")
|
to := sdktranslator.FromString("openai")
|
||||||
|
originalPayload := bytes.Clone(req.Payload)
|
||||||
|
if len(opts.OriginalRequest) > 0 {
|
||||||
|
originalPayload = bytes.Clone(opts.OriginalRequest)
|
||||||
|
}
|
||||||
|
originalTranslated := sdktranslator.TranslateRequest(from, to, req.Model, originalPayload, false)
|
||||||
body := sdktranslator.TranslateRequest(from, to, req.Model, bytes.Clone(req.Payload), false)
|
body := sdktranslator.TranslateRequest(from, to, req.Model, bytes.Clone(req.Payload), false)
|
||||||
body = e.normalizeModel(req.Model, body)
|
body = e.normalizeModel(req.Model, body)
|
||||||
body = applyPayloadConfig(e.cfg, req.Model, body)
|
body = applyPayloadConfigWithRoot(e.cfg, req.Model, to.String(), "", body, originalTranslated)
|
||||||
body, _ = sjson.SetBytes(body, "stream", false)
|
body, _ = sjson.SetBytes(body, "stream", false)
|
||||||
|
|
||||||
url := githubCopilotBaseURL + githubCopilotChatPath
|
url := githubCopilotBaseURL + githubCopilotChatPath
|
||||||
@@ -162,9 +167,14 @@ func (e *GitHubCopilotExecutor) ExecuteStream(ctx context.Context, auth *cliprox
|
|||||||
|
|
||||||
from := opts.SourceFormat
|
from := opts.SourceFormat
|
||||||
to := sdktranslator.FromString("openai")
|
to := sdktranslator.FromString("openai")
|
||||||
|
originalPayload := bytes.Clone(req.Payload)
|
||||||
|
if len(opts.OriginalRequest) > 0 {
|
||||||
|
originalPayload = bytes.Clone(opts.OriginalRequest)
|
||||||
|
}
|
||||||
|
originalTranslated := sdktranslator.TranslateRequest(from, to, req.Model, originalPayload, false)
|
||||||
body := sdktranslator.TranslateRequest(from, to, req.Model, bytes.Clone(req.Payload), true)
|
body := sdktranslator.TranslateRequest(from, to, req.Model, bytes.Clone(req.Payload), true)
|
||||||
body = e.normalizeModel(req.Model, body)
|
body = e.normalizeModel(req.Model, body)
|
||||||
body = applyPayloadConfig(e.cfg, req.Model, body)
|
body = applyPayloadConfigWithRoot(e.cfg, req.Model, to.String(), "", body, originalTranslated)
|
||||||
body, _ = sjson.SetBytes(body, "stream", true)
|
body, _ = sjson.SetBytes(body, "stream", true)
|
||||||
// Enable stream options for usage stats in stream
|
// Enable stream options for usage stats in stream
|
||||||
body, _ = sjson.SetBytes(body, "stream_options.include_usage", true)
|
body, _ = sjson.SetBytes(body, "stream_options.include_usage", true)
|
||||||
|
|||||||
@@ -223,6 +223,7 @@ func ConvertOpenAIRequestToAntigravity(modelName string, inputRawJSON []byte, _
|
|||||||
data := pieces[1][7:]
|
data := pieces[1][7:]
|
||||||
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".inlineData.mime_type", mime)
|
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".inlineData.mime_type", mime)
|
||||||
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".inlineData.data", data)
|
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".inlineData.data", data)
|
||||||
|
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".thoughtSignature", geminiCLIFunctionThoughtSignature)
|
||||||
p++
|
p++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -266,6 +267,7 @@ func ConvertOpenAIRequestToAntigravity(modelName string, inputRawJSON []byte, _
|
|||||||
data := pieces[1][7:]
|
data := pieces[1][7:]
|
||||||
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".inlineData.mime_type", mime)
|
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".inlineData.mime_type", mime)
|
||||||
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".inlineData.data", data)
|
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".inlineData.data", data)
|
||||||
|
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".thoughtSignature", geminiCLIFunctionThoughtSignature)
|
||||||
p++
|
p++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -191,6 +191,7 @@ func ConvertOpenAIRequestToGeminiCLI(modelName string, inputRawJSON []byte, _ bo
|
|||||||
data := pieces[1][7:]
|
data := pieces[1][7:]
|
||||||
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".inlineData.mime_type", mime)
|
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".inlineData.mime_type", mime)
|
||||||
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".inlineData.data", data)
|
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".inlineData.data", data)
|
||||||
|
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".thoughtSignature", geminiCLIFunctionThoughtSignature)
|
||||||
p++
|
p++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -236,6 +237,7 @@ func ConvertOpenAIRequestToGeminiCLI(modelName string, inputRawJSON []byte, _ bo
|
|||||||
data := pieces[1][7:]
|
data := pieces[1][7:]
|
||||||
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".inlineData.mime_type", mime)
|
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".inlineData.mime_type", mime)
|
||||||
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".inlineData.data", data)
|
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".inlineData.data", data)
|
||||||
|
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".thoughtSignature", geminiCLIFunctionThoughtSignature)
|
||||||
p++
|
p++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -209,6 +209,7 @@ func ConvertOpenAIRequestToGemini(modelName string, inputRawJSON []byte, _ bool)
|
|||||||
data := pieces[1][7:]
|
data := pieces[1][7:]
|
||||||
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".inlineData.mime_type", mime)
|
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".inlineData.mime_type", mime)
|
||||||
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".inlineData.data", data)
|
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".inlineData.data", data)
|
||||||
|
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".thoughtSignature", geminiFunctionThoughtSignature)
|
||||||
p++
|
p++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -253,6 +254,7 @@ func ConvertOpenAIRequestToGemini(modelName string, inputRawJSON []byte, _ bool)
|
|||||||
data := pieces[1][7:]
|
data := pieces[1][7:]
|
||||||
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".inlineData.mime_type", mime)
|
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".inlineData.mime_type", mime)
|
||||||
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".inlineData.data", data)
|
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".inlineData.data", data)
|
||||||
|
node, _ = sjson.SetBytes(node, "parts."+itoa(p)+".thoughtSignature", geminiFunctionThoughtSignature)
|
||||||
p++
|
p++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -299,17 +299,16 @@ func convertOpenAIStreamingChunkToAnthropic(rawJSON []byte, param *ConvertOpenAI
|
|||||||
inputTokens = promptTokens.Int()
|
inputTokens = promptTokens.Int()
|
||||||
outputTokens = completionTokens.Int()
|
outputTokens = completionTokens.Int()
|
||||||
}
|
}
|
||||||
|
// Send message_delta with usage
|
||||||
|
messageDeltaJSON := `{"type":"message_delta","delta":{"stop_reason":"","stop_sequence":null},"usage":{"input_tokens":0,"output_tokens":0}}`
|
||||||
|
messageDeltaJSON, _ = sjson.Set(messageDeltaJSON, "delta.stop_reason", mapOpenAIFinishReasonToAnthropic(param.FinishReason))
|
||||||
|
messageDeltaJSON, _ = sjson.Set(messageDeltaJSON, "usage.input_tokens", inputTokens)
|
||||||
|
messageDeltaJSON, _ = sjson.Set(messageDeltaJSON, "usage.output_tokens", outputTokens)
|
||||||
|
results = append(results, "event: message_delta\ndata: "+messageDeltaJSON+"\n\n")
|
||||||
|
param.MessageDeltaSent = true
|
||||||
|
|
||||||
|
emitMessageStopIfNeeded(param, &results)
|
||||||
}
|
}
|
||||||
// Send message_delta with usage
|
|
||||||
messageDeltaJSON := `{"type":"message_delta","delta":{"stop_reason":"","stop_sequence":null},"usage":{"input_tokens":0,"output_tokens":0}}`
|
|
||||||
messageDeltaJSON, _ = sjson.Set(messageDeltaJSON, "delta.stop_reason", mapOpenAIFinishReasonToAnthropic(param.FinishReason))
|
|
||||||
messageDeltaJSON, _ = sjson.Set(messageDeltaJSON, "usage.input_tokens", inputTokens)
|
|
||||||
messageDeltaJSON, _ = sjson.Set(messageDeltaJSON, "usage.output_tokens", outputTokens)
|
|
||||||
results = append(results, "event: message_delta\ndata: "+messageDeltaJSON+"\n\n")
|
|
||||||
param.MessageDeltaSent = true
|
|
||||||
|
|
||||||
emitMessageStopIfNeeded(param, &results)
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return results
|
return results
|
||||||
|
|||||||
@@ -71,10 +71,13 @@ func ApplyGeminiThinkingConfig(body []byte, budget *int, includeThoughts *bool)
|
|||||||
incl = &defaultInclude
|
incl = &defaultInclude
|
||||||
}
|
}
|
||||||
if incl != nil {
|
if incl != nil {
|
||||||
valuePath := "generationConfig.thinkingConfig.include_thoughts"
|
if !gjson.GetBytes(updated, "generationConfig.thinkingConfig.includeThoughts").Exists() &&
|
||||||
rewritten, err := sjson.SetBytes(updated, valuePath, *incl)
|
!gjson.GetBytes(updated, "generationConfig.thinkingConfig.include_thoughts").Exists() {
|
||||||
if err == nil {
|
valuePath := "generationConfig.thinkingConfig.include_thoughts"
|
||||||
updated = rewritten
|
rewritten, err := sjson.SetBytes(updated, valuePath, *incl)
|
||||||
|
if err == nil {
|
||||||
|
updated = rewritten
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return updated
|
return updated
|
||||||
@@ -99,10 +102,13 @@ func ApplyGeminiCLIThinkingConfig(body []byte, budget *int, includeThoughts *boo
|
|||||||
incl = &defaultInclude
|
incl = &defaultInclude
|
||||||
}
|
}
|
||||||
if incl != nil {
|
if incl != nil {
|
||||||
valuePath := "request.generationConfig.thinkingConfig.include_thoughts"
|
if !gjson.GetBytes(updated, "request.generationConfig.thinkingConfig.includeThoughts").Exists() &&
|
||||||
rewritten, err := sjson.SetBytes(updated, valuePath, *incl)
|
!gjson.GetBytes(updated, "request.generationConfig.thinkingConfig.include_thoughts").Exists() {
|
||||||
if err == nil {
|
valuePath := "request.generationConfig.thinkingConfig.include_thoughts"
|
||||||
updated = rewritten
|
rewritten, err := sjson.SetBytes(updated, valuePath, *incl)
|
||||||
|
if err == nil {
|
||||||
|
updated = rewritten
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return updated
|
return updated
|
||||||
@@ -130,15 +136,15 @@ func ApplyGeminiThinkingLevel(body []byte, level string, includeThoughts *bool)
|
|||||||
incl = &defaultInclude
|
incl = &defaultInclude
|
||||||
}
|
}
|
||||||
if incl != nil {
|
if incl != nil {
|
||||||
valuePath := "generationConfig.thinkingConfig.includeThoughts"
|
if !gjson.GetBytes(updated, "generationConfig.thinkingConfig.includeThoughts").Exists() &&
|
||||||
rewritten, err := sjson.SetBytes(updated, valuePath, *incl)
|
!gjson.GetBytes(updated, "generationConfig.thinkingConfig.include_thoughts").Exists() {
|
||||||
if err == nil {
|
valuePath := "generationConfig.thinkingConfig.includeThoughts"
|
||||||
updated = rewritten
|
rewritten, err := sjson.SetBytes(updated, valuePath, *incl)
|
||||||
|
if err == nil {
|
||||||
|
updated = rewritten
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if it := gjson.GetBytes(body, "generationConfig.thinkingConfig.include_thoughts"); it.Exists() {
|
|
||||||
updated, _ = sjson.DeleteBytes(updated, "generationConfig.thinkingConfig.include_thoughts")
|
|
||||||
}
|
|
||||||
if tb := gjson.GetBytes(body, "generationConfig.thinkingConfig.thinkingBudget"); tb.Exists() {
|
if tb := gjson.GetBytes(body, "generationConfig.thinkingConfig.thinkingBudget"); tb.Exists() {
|
||||||
updated, _ = sjson.DeleteBytes(updated, "generationConfig.thinkingConfig.thinkingBudget")
|
updated, _ = sjson.DeleteBytes(updated, "generationConfig.thinkingConfig.thinkingBudget")
|
||||||
}
|
}
|
||||||
@@ -167,15 +173,15 @@ func ApplyGeminiCLIThinkingLevel(body []byte, level string, includeThoughts *boo
|
|||||||
incl = &defaultInclude
|
incl = &defaultInclude
|
||||||
}
|
}
|
||||||
if incl != nil {
|
if incl != nil {
|
||||||
valuePath := "request.generationConfig.thinkingConfig.includeThoughts"
|
if !gjson.GetBytes(updated, "request.generationConfig.thinkingConfig.includeThoughts").Exists() &&
|
||||||
rewritten, err := sjson.SetBytes(updated, valuePath, *incl)
|
!gjson.GetBytes(updated, "request.generationConfig.thinkingConfig.include_thoughts").Exists() {
|
||||||
if err == nil {
|
valuePath := "request.generationConfig.thinkingConfig.includeThoughts"
|
||||||
updated = rewritten
|
rewritten, err := sjson.SetBytes(updated, valuePath, *incl)
|
||||||
|
if err == nil {
|
||||||
|
updated = rewritten
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if it := gjson.GetBytes(body, "request.generationConfig.thinkingConfig.include_thoughts"); it.Exists() {
|
|
||||||
updated, _ = sjson.DeleteBytes(updated, "request.generationConfig.thinkingConfig.include_thoughts")
|
|
||||||
}
|
|
||||||
if tb := gjson.GetBytes(body, "request.generationConfig.thinkingConfig.thinkingBudget"); tb.Exists() {
|
if tb := gjson.GetBytes(body, "request.generationConfig.thinkingConfig.thinkingBudget"); tb.Exists() {
|
||||||
updated, _ = sjson.DeleteBytes(updated, "request.generationConfig.thinkingConfig.thinkingBudget")
|
updated, _ = sjson.DeleteBytes(updated, "request.generationConfig.thinkingConfig.thinkingBudget")
|
||||||
}
|
}
|
||||||
@@ -251,9 +257,14 @@ func ThinkingBudgetToGemini3Level(model string, budget int) (string, bool) {
|
|||||||
|
|
||||||
// modelsWithDefaultThinking lists models that should have thinking enabled by default
|
// modelsWithDefaultThinking lists models that should have thinking enabled by default
|
||||||
// when no explicit thinkingConfig is provided.
|
// when no explicit thinkingConfig is provided.
|
||||||
|
// Note: Gemini 3 models are NOT included here because per Google's official documentation:
|
||||||
|
// - thinkingLevel defaults to "high" (dynamic thinking)
|
||||||
|
// - includeThoughts defaults to false
|
||||||
|
//
|
||||||
|
// We should not override these API defaults; let users explicitly configure if needed.
|
||||||
var modelsWithDefaultThinking = map[string]bool{
|
var modelsWithDefaultThinking = map[string]bool{
|
||||||
"gemini-3-pro-preview": true,
|
// "gemini-3-pro-preview": true,
|
||||||
"gemini-3-pro-image-preview": true,
|
// "gemini-3-pro-image-preview": true,
|
||||||
// "gemini-3-flash-preview": true,
|
// "gemini-3-flash-preview": true,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,8 +4,8 @@
|
|||||||
package util
|
package util
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/fs"
|
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"regexp"
|
"regexp"
|
||||||
@@ -93,36 +93,23 @@ func ResolveAuthDir(authDir string) (string, error) {
|
|||||||
return filepath.Clean(authDir), nil
|
return filepath.Clean(authDir), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// CountAuthFiles returns the number of JSON auth files located under the provided directory.
|
// CountAuthFiles returns the number of auth records available through the provided Store.
|
||||||
// The function resolves leading tildes to the user's home directory and performs a case-insensitive
|
// For filesystem-backed stores, this reflects the number of JSON auth files under the configured directory.
|
||||||
// match on the ".json" suffix so that files saved with uppercase extensions are also counted.
|
func CountAuthFiles[T any](ctx context.Context, store interface {
|
||||||
func CountAuthFiles(authDir string) int {
|
List(context.Context) ([]T, error)
|
||||||
dir, err := ResolveAuthDir(authDir)
|
}) int {
|
||||||
|
if store == nil {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
if ctx == nil {
|
||||||
|
ctx = context.Background()
|
||||||
|
}
|
||||||
|
entries, err := store.List(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Debugf("countAuthFiles: failed to resolve auth directory: %v", err)
|
log.Debugf("countAuthFiles: failed to list auth records: %v", err)
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
if dir == "" {
|
return len(entries)
|
||||||
return 0
|
|
||||||
}
|
|
||||||
count := 0
|
|
||||||
walkErr := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
|
|
||||||
if err != nil {
|
|
||||||
log.Debugf("countAuthFiles: error accessing %s: %v", path, err)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if d.IsDir() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if strings.HasSuffix(strings.ToLower(d.Name()), ".json") {
|
|
||||||
count++
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if walkErr != nil {
|
|
||||||
log.Debugf("countAuthFiles: walk error: %v", walkErr)
|
|
||||||
}
|
|
||||||
return count
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// WritablePath returns the cleaned WRITABLE_PATH environment variable when it is set.
|
// WritablePath returns the cleaned WRITABLE_PATH environment variable when it is set.
|
||||||
|
|||||||
@@ -80,6 +80,9 @@ func summarizeOAuthModelMappingList(list []config.ModelNameMapping) OAuthModelMa
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
key := name + "->" + alias
|
key := name + "->" + alias
|
||||||
|
if mapping.Fork {
|
||||||
|
key += "|fork"
|
||||||
|
}
|
||||||
if _, exists := seen[key]; exists {
|
if _, exists := seen[key]; exists {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1536,6 +1536,9 @@ func (m *Manager) markRefreshPending(id string, now time.Time) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (m *Manager) refreshAuth(ctx context.Context, id string) {
|
func (m *Manager) refreshAuth(ctx context.Context, id string) {
|
||||||
|
if ctx == nil {
|
||||||
|
ctx = context.Background()
|
||||||
|
}
|
||||||
m.mu.RLock()
|
m.mu.RLock()
|
||||||
auth := m.auths[id]
|
auth := m.auths[id]
|
||||||
var exec ProviderExecutor
|
var exec ProviderExecutor
|
||||||
@@ -1548,6 +1551,10 @@ func (m *Manager) refreshAuth(ctx context.Context, id string) {
|
|||||||
}
|
}
|
||||||
cloned := auth.Clone()
|
cloned := auth.Clone()
|
||||||
updated, err := exec.Refresh(ctx, cloned)
|
updated, err := exec.Refresh(ctx, cloned)
|
||||||
|
if err != nil && errors.Is(err, context.Canceled) {
|
||||||
|
log.Debugf("refresh canceled for %s, %s", auth.Provider, auth.ID)
|
||||||
|
return
|
||||||
|
}
|
||||||
log.Debugf("refreshed %s, %s, %v", auth.Provider, auth.ID, err)
|
log.Debugf("refreshed %s, %s, %v", auth.Provider, auth.ID, err)
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -5,6 +5,9 @@ import "github.com/router-for-me/CLIProxyAPI/v6/internal/registry"
|
|||||||
// ModelInfo re-exports the registry model info structure.
|
// ModelInfo re-exports the registry model info structure.
|
||||||
type ModelInfo = registry.ModelInfo
|
type ModelInfo = registry.ModelInfo
|
||||||
|
|
||||||
|
// ModelRegistryHook re-exports the registry hook interface for external integrations.
|
||||||
|
type ModelRegistryHook = registry.ModelRegistryHook
|
||||||
|
|
||||||
// ModelRegistry describes registry operations consumed by external callers.
|
// ModelRegistry describes registry operations consumed by external callers.
|
||||||
type ModelRegistry interface {
|
type ModelRegistry interface {
|
||||||
RegisterClient(clientID, clientProvider string, models []*ModelInfo)
|
RegisterClient(clientID, clientProvider string, models []*ModelInfo)
|
||||||
@@ -20,3 +23,8 @@ type ModelRegistry interface {
|
|||||||
func GlobalModelRegistry() ModelRegistry {
|
func GlobalModelRegistry() ModelRegistry {
|
||||||
return registry.GetGlobalRegistry()
|
return registry.GetGlobalRegistry()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetGlobalModelRegistryHook registers an optional hook on the shared global registry instance.
|
||||||
|
func SetGlobalModelRegistryHook(hook ModelRegistryHook) {
|
||||||
|
registry.GetGlobalRegistry().SetHook(hook)
|
||||||
|
}
|
||||||
|
|||||||
@@ -1240,7 +1240,13 @@ func applyOAuthModelMappings(cfg *config.Config, provider, authKind string, mode
|
|||||||
if len(mappings) == 0 {
|
if len(mappings) == 0 {
|
||||||
return models
|
return models
|
||||||
}
|
}
|
||||||
forward := make(map[string]string, len(mappings))
|
|
||||||
|
type mappingEntry struct {
|
||||||
|
alias string
|
||||||
|
fork bool
|
||||||
|
}
|
||||||
|
|
||||||
|
forward := make(map[string]mappingEntry, len(mappings))
|
||||||
for i := range mappings {
|
for i := range mappings {
|
||||||
name := strings.TrimSpace(mappings[i].Name)
|
name := strings.TrimSpace(mappings[i].Name)
|
||||||
alias := strings.TrimSpace(mappings[i].Alias)
|
alias := strings.TrimSpace(mappings[i].Alias)
|
||||||
@@ -1254,7 +1260,7 @@ func applyOAuthModelMappings(cfg *config.Config, provider, authKind string, mode
|
|||||||
if _, exists := forward[key]; exists {
|
if _, exists := forward[key]; exists {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
forward[key] = alias
|
forward[key] = mappingEntry{alias: alias, fork: mappings[i].Fork}
|
||||||
}
|
}
|
||||||
if len(forward) == 0 {
|
if len(forward) == 0 {
|
||||||
return models
|
return models
|
||||||
@@ -1269,10 +1275,45 @@ func applyOAuthModelMappings(cfg *config.Config, provider, authKind string, mode
|
|||||||
if id == "" {
|
if id == "" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
mappedID := id
|
key := strings.ToLower(id)
|
||||||
if to, ok := forward[strings.ToLower(id)]; ok && strings.TrimSpace(to) != "" {
|
entry, ok := forward[key]
|
||||||
mappedID = strings.TrimSpace(to)
|
if !ok {
|
||||||
|
if _, exists := seen[key]; exists {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[key] = struct{}{}
|
||||||
|
out = append(out, model)
|
||||||
|
continue
|
||||||
}
|
}
|
||||||
|
mappedID := strings.TrimSpace(entry.alias)
|
||||||
|
if mappedID == "" {
|
||||||
|
if _, exists := seen[key]; exists {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[key] = struct{}{}
|
||||||
|
out = append(out, model)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if entry.fork {
|
||||||
|
if _, exists := seen[key]; !exists {
|
||||||
|
seen[key] = struct{}{}
|
||||||
|
out = append(out, model)
|
||||||
|
}
|
||||||
|
aliasKey := strings.ToLower(mappedID)
|
||||||
|
if _, exists := seen[aliasKey]; exists {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[aliasKey] = struct{}{}
|
||||||
|
clone := *model
|
||||||
|
clone.ID = mappedID
|
||||||
|
if clone.Name != "" {
|
||||||
|
clone.Name = rewriteModelInfoName(clone.Name, id, mappedID)
|
||||||
|
}
|
||||||
|
out = append(out, &clone)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
uniqueKey := strings.ToLower(mappedID)
|
uniqueKey := strings.ToLower(mappedID)
|
||||||
if _, exists := seen[uniqueKey]; exists {
|
if _, exists := seen[uniqueKey]; exists {
|
||||||
continue
|
continue
|
||||||
|
|||||||
58
sdk/cliproxy/service_oauth_model_mappings_test.go
Normal file
58
sdk/cliproxy/service_oauth_model_mappings_test.go
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
package cliproxy
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/router-for-me/CLIProxyAPI/v6/sdk/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestApplyOAuthModelMappings_Rename(t *testing.T) {
|
||||||
|
cfg := &config.Config{
|
||||||
|
OAuthModelMappings: map[string][]config.ModelNameMapping{
|
||||||
|
"codex": {
|
||||||
|
{Name: "gpt-5", Alias: "g5"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
models := []*ModelInfo{
|
||||||
|
{ID: "gpt-5", Name: "models/gpt-5"},
|
||||||
|
}
|
||||||
|
|
||||||
|
out := applyOAuthModelMappings(cfg, "codex", "oauth", models)
|
||||||
|
if len(out) != 1 {
|
||||||
|
t.Fatalf("expected 1 model, got %d", len(out))
|
||||||
|
}
|
||||||
|
if out[0].ID != "g5" {
|
||||||
|
t.Fatalf("expected model id %q, got %q", "g5", out[0].ID)
|
||||||
|
}
|
||||||
|
if out[0].Name != "models/g5" {
|
||||||
|
t.Fatalf("expected model name %q, got %q", "models/g5", out[0].Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestApplyOAuthModelMappings_ForkAddsAlias(t *testing.T) {
|
||||||
|
cfg := &config.Config{
|
||||||
|
OAuthModelMappings: map[string][]config.ModelNameMapping{
|
||||||
|
"codex": {
|
||||||
|
{Name: "gpt-5", Alias: "g5", Fork: true},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
models := []*ModelInfo{
|
||||||
|
{ID: "gpt-5", Name: "models/gpt-5"},
|
||||||
|
}
|
||||||
|
|
||||||
|
out := applyOAuthModelMappings(cfg, "codex", "oauth", models)
|
||||||
|
if len(out) != 2 {
|
||||||
|
t.Fatalf("expected 2 models, got %d", len(out))
|
||||||
|
}
|
||||||
|
if out[0].ID != "gpt-5" {
|
||||||
|
t.Fatalf("expected first model id %q, got %q", "gpt-5", out[0].ID)
|
||||||
|
}
|
||||||
|
if out[1].ID != "g5" {
|
||||||
|
t.Fatalf("expected second model id %q, got %q", "g5", out[1].ID)
|
||||||
|
}
|
||||||
|
if out[1].Name != "models/g5" {
|
||||||
|
t.Fatalf("expected forked model name %q, got %q", "models/g5", out[1].Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user