mirror of
https://github.com/githubhjs/CLIProxyAPIPlus.git
synced 2026-07-10 15:43:48 +00:00
Merge branch 'router-for-me:main' into main
This commit is contained in:
@@ -19,7 +19,7 @@ jobs:
|
|||||||
- run: git fetch --force --tags
|
- run: git fetch --force --tags
|
||||||
- uses: actions/setup-go@v4
|
- uses: actions/setup-go@v4
|
||||||
with:
|
with:
|
||||||
go-version: '>=1.24.0'
|
go-version: '>=1.26.0'
|
||||||
cache: true
|
cache: true
|
||||||
- name: Generate Build Metadata
|
- name: Generate Build Metadata
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
FROM golang:1.24-alpine AS builder
|
FROM golang:1.26-alpine AS builder
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
module github.com/router-for-me/CLIProxyAPI/v6
|
module github.com/router-for-me/CLIProxyAPI/v6
|
||||||
|
|
||||||
go 1.24.0
|
go 1.26.0
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/andybalholm/brotli v1.0.6
|
github.com/andybalholm/brotli v1.0.6
|
||||||
|
|||||||
@@ -1193,6 +1193,30 @@ func (h *Handler) RequestGeminiCLIToken(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
ts.ProjectID = strings.Join(projects, ",")
|
ts.ProjectID = strings.Join(projects, ",")
|
||||||
ts.Checked = true
|
ts.Checked = true
|
||||||
|
} else if strings.EqualFold(requestedProjectID, "GOOGLE_ONE") {
|
||||||
|
ts.Auto = false
|
||||||
|
if errSetup := performGeminiCLISetup(ctx, gemClient, &ts, ""); errSetup != nil {
|
||||||
|
log.Errorf("Google One auto-discovery failed: %v", errSetup)
|
||||||
|
SetOAuthSessionError(state, "Google One auto-discovery failed")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(ts.ProjectID) == "" {
|
||||||
|
log.Error("Google One auto-discovery returned empty project ID")
|
||||||
|
SetOAuthSessionError(state, "Google One auto-discovery returned empty project ID")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
isChecked, errCheck := checkCloudAPIIsEnabled(ctx, gemClient, ts.ProjectID)
|
||||||
|
if errCheck != nil {
|
||||||
|
log.Errorf("Failed to verify Cloud AI API status: %v", errCheck)
|
||||||
|
SetOAuthSessionError(state, "Failed to verify Cloud AI API status")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ts.Checked = isChecked
|
||||||
|
if !isChecked {
|
||||||
|
log.Error("Cloud AI API is not enabled for the auto-discovered project")
|
||||||
|
SetOAuthSessionError(state, "Cloud AI API not enabled")
|
||||||
|
return
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
if errEnsure := ensureGeminiProjectAndOnboard(ctx, gemClient, &ts, requestedProjectID); errEnsure != nil {
|
if errEnsure := ensureGeminiProjectAndOnboard(ctx, gemClient, &ts, requestedProjectID); errEnsure != nil {
|
||||||
log.Errorf("Failed to complete Gemini CLI onboarding: %v", errEnsure)
|
log.Errorf("Failed to complete Gemini CLI onboarding: %v", errEnsure)
|
||||||
@@ -2124,7 +2148,48 @@ func performGeminiCLISetup(ctx context.Context, httpClient *http.Client, storage
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if projectID == "" {
|
if projectID == "" {
|
||||||
return &projectSelectionRequiredError{}
|
// Auto-discovery: try onboardUser without specifying a project
|
||||||
|
// to let Google auto-provision one (matches Gemini CLI headless behavior
|
||||||
|
// and Antigravity's FetchProjectID pattern).
|
||||||
|
autoOnboardReq := map[string]any{
|
||||||
|
"tierId": tierID,
|
||||||
|
"metadata": metadata,
|
||||||
|
}
|
||||||
|
|
||||||
|
autoCtx, autoCancel := context.WithTimeout(ctx, 30*time.Second)
|
||||||
|
defer autoCancel()
|
||||||
|
for attempt := 1; ; attempt++ {
|
||||||
|
var onboardResp map[string]any
|
||||||
|
if errOnboard := callGeminiCLI(autoCtx, httpClient, "onboardUser", autoOnboardReq, &onboardResp); errOnboard != nil {
|
||||||
|
return fmt.Errorf("auto-discovery onboardUser: %w", errOnboard)
|
||||||
|
}
|
||||||
|
|
||||||
|
if done, okDone := onboardResp["done"].(bool); okDone && done {
|
||||||
|
if resp, okResp := onboardResp["response"].(map[string]any); okResp {
|
||||||
|
switch v := resp["cloudaicompanionProject"].(type) {
|
||||||
|
case string:
|
||||||
|
projectID = strings.TrimSpace(v)
|
||||||
|
case map[string]any:
|
||||||
|
if id, okID := v["id"].(string); okID {
|
||||||
|
projectID = strings.TrimSpace(id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debugf("Auto-discovery: onboarding in progress, attempt %d...", attempt)
|
||||||
|
select {
|
||||||
|
case <-autoCtx.Done():
|
||||||
|
return &projectSelectionRequiredError{}
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if projectID == "" {
|
||||||
|
return &projectSelectionRequiredError{}
|
||||||
|
}
|
||||||
|
log.Infof("Auto-discovered project ID via onboarding: %s", projectID)
|
||||||
}
|
}
|
||||||
|
|
||||||
onboardReqBody := map[string]any{
|
onboardReqBody := map[string]any{
|
||||||
|
|||||||
@@ -28,8 +28,7 @@ func (h *Handler) GetConfig(c *gin.Context) {
|
|||||||
c.JSON(200, gin.H{})
|
c.JSON(200, gin.H{})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
cfgCopy := *h.cfg
|
c.JSON(200, new(*h.cfg))
|
||||||
c.JSON(200, &cfgCopy)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type releaseInfo struct {
|
type releaseInfo struct {
|
||||||
|
|||||||
@@ -127,8 +127,7 @@ func (m *AmpModule) Register(ctx modules.Context) error {
|
|||||||
m.modelMapper = NewModelMapper(settings.ModelMappings)
|
m.modelMapper = NewModelMapper(settings.ModelMappings)
|
||||||
|
|
||||||
// Store initial config for partial reload comparison
|
// Store initial config for partial reload comparison
|
||||||
settingsCopy := settings
|
m.lastConfig = new(settings)
|
||||||
m.lastConfig = &settingsCopy
|
|
||||||
|
|
||||||
// Initialize localhost restriction setting (hot-reloadable)
|
// Initialize localhost restriction setting (hot-reloadable)
|
||||||
m.setRestrictToLocalhost(settings.RestrictManagementToLocalhost)
|
m.setRestrictToLocalhost(settings.RestrictManagementToLocalhost)
|
||||||
|
|||||||
@@ -40,8 +40,7 @@ func DoClaudeLogin(cfg *config.Config, options *LoginOptions) {
|
|||||||
|
|
||||||
_, savedPath, err := manager.Login(context.Background(), "claude", cfg, authOpts)
|
_, savedPath, err := manager.Login(context.Background(), "claude", cfg, authOpts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
var authErr *claude.AuthenticationError
|
if authErr, ok := errors.AsType[*claude.AuthenticationError](err); ok {
|
||||||
if errors.As(err, &authErr) {
|
|
||||||
log.Error(claude.GetUserFriendlyMessage(authErr))
|
log.Error(claude.GetUserFriendlyMessage(authErr))
|
||||||
if authErr.Type == claude.ErrPortInUse.Type {
|
if authErr.Type == claude.ErrPortInUse.Type {
|
||||||
os.Exit(claude.ErrPortInUse.Code)
|
os.Exit(claude.ErrPortInUse.Code)
|
||||||
|
|||||||
@@ -32,8 +32,7 @@ func DoIFlowLogin(cfg *config.Config, options *LoginOptions) {
|
|||||||
|
|
||||||
_, savedPath, err := manager.Login(context.Background(), "iflow", cfg, authOpts)
|
_, savedPath, err := manager.Login(context.Background(), "iflow", cfg, authOpts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
var emailErr *sdkAuth.EmailRequiredError
|
if emailErr, ok := errors.AsType[*sdkAuth.EmailRequiredError](err); ok {
|
||||||
if errors.As(err, &emailErr) {
|
|
||||||
log.Error(emailErr.Error())
|
log.Error(emailErr.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
+104
-38
@@ -100,49 +100,74 @@ func DoLogin(cfg *config.Config, projectID string, options *LoginOptions) {
|
|||||||
|
|
||||||
log.Info("Authentication successful.")
|
log.Info("Authentication successful.")
|
||||||
|
|
||||||
projects, errProjects := fetchGCPProjects(ctx, httpClient)
|
var activatedProjects []string
|
||||||
if errProjects != nil {
|
|
||||||
log.Errorf("Failed to get project list: %v", errProjects)
|
useGoogleOne := false
|
||||||
return
|
if trimmedProjectID == "" && promptFn != nil {
|
||||||
|
fmt.Println("\nSelect login mode:")
|
||||||
|
fmt.Println(" 1. Code Assist (GCP project, manual selection)")
|
||||||
|
fmt.Println(" 2. Google One (personal account, auto-discover project)")
|
||||||
|
choice, errPrompt := promptFn("Enter choice [1/2] (default: 1): ")
|
||||||
|
if errPrompt == nil && strings.TrimSpace(choice) == "2" {
|
||||||
|
useGoogleOne = true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
selectedProjectID := promptForProjectSelection(projects, trimmedProjectID, promptFn)
|
if useGoogleOne {
|
||||||
projectSelections, errSelection := resolveProjectSelections(selectedProjectID, projects)
|
log.Info("Google One mode: auto-discovering project...")
|
||||||
if errSelection != nil {
|
if errSetup := performGeminiCLISetup(ctx, httpClient, storage, ""); errSetup != nil {
|
||||||
log.Errorf("Invalid project selection: %v", errSelection)
|
log.Errorf("Google One auto-discovery failed: %v", errSetup)
|
||||||
return
|
|
||||||
}
|
|
||||||
if len(projectSelections) == 0 {
|
|
||||||
log.Error("No project selected; aborting login.")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
activatedProjects := make([]string, 0, len(projectSelections))
|
|
||||||
seenProjects := make(map[string]bool)
|
|
||||||
for _, candidateID := range projectSelections {
|
|
||||||
log.Infof("Activating project %s", candidateID)
|
|
||||||
if errSetup := performGeminiCLISetup(ctx, httpClient, storage, candidateID); errSetup != nil {
|
|
||||||
var projectErr *projectSelectionRequiredError
|
|
||||||
if errors.As(errSetup, &projectErr) {
|
|
||||||
log.Error("Failed to start user onboarding: A project ID is required.")
|
|
||||||
showProjectSelectionHelp(storage.Email, projects)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
log.Errorf("Failed to complete user setup: %v", errSetup)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
finalID := strings.TrimSpace(storage.ProjectID)
|
autoProject := strings.TrimSpace(storage.ProjectID)
|
||||||
if finalID == "" {
|
if autoProject == "" {
|
||||||
finalID = candidateID
|
log.Error("Google One auto-discovery returned empty project ID")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Infof("Auto-discovered project: %s", autoProject)
|
||||||
|
activatedProjects = []string{autoProject}
|
||||||
|
} else {
|
||||||
|
projects, errProjects := fetchGCPProjects(ctx, httpClient)
|
||||||
|
if errProjects != nil {
|
||||||
|
log.Errorf("Failed to get project list: %v", errProjects)
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Skip duplicates
|
selectedProjectID := promptForProjectSelection(projects, trimmedProjectID, promptFn)
|
||||||
if seenProjects[finalID] {
|
projectSelections, errSelection := resolveProjectSelections(selectedProjectID, projects)
|
||||||
log.Infof("Project %s already activated, skipping", finalID)
|
if errSelection != nil {
|
||||||
continue
|
log.Errorf("Invalid project selection: %v", errSelection)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(projectSelections) == 0 {
|
||||||
|
log.Error("No project selected; aborting login.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
seenProjects := make(map[string]bool)
|
||||||
|
for _, candidateID := range projectSelections {
|
||||||
|
log.Infof("Activating project %s", candidateID)
|
||||||
|
if errSetup := performGeminiCLISetup(ctx, httpClient, storage, candidateID); errSetup != nil {
|
||||||
|
if _, ok := errors.AsType[*projectSelectionRequiredError](errSetup); ok {
|
||||||
|
log.Error("Failed to start user onboarding: A project ID is required.")
|
||||||
|
showProjectSelectionHelp(storage.Email, projects)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Errorf("Failed to complete user setup: %v", errSetup)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
finalID := strings.TrimSpace(storage.ProjectID)
|
||||||
|
if finalID == "" {
|
||||||
|
finalID = candidateID
|
||||||
|
}
|
||||||
|
|
||||||
|
if seenProjects[finalID] {
|
||||||
|
log.Infof("Project %s already activated, skipping", finalID)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seenProjects[finalID] = true
|
||||||
|
activatedProjects = append(activatedProjects, finalID)
|
||||||
}
|
}
|
||||||
seenProjects[finalID] = true
|
|
||||||
activatedProjects = append(activatedProjects, finalID)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
storage.Auto = false
|
storage.Auto = false
|
||||||
@@ -235,7 +260,48 @@ func performGeminiCLISetup(ctx context.Context, httpClient *http.Client, storage
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if projectID == "" {
|
if projectID == "" {
|
||||||
return &projectSelectionRequiredError{}
|
// Auto-discovery: try onboardUser without specifying a project
|
||||||
|
// to let Google auto-provision one (matches Gemini CLI headless behavior
|
||||||
|
// and Antigravity's FetchProjectID pattern).
|
||||||
|
autoOnboardReq := map[string]any{
|
||||||
|
"tierId": tierID,
|
||||||
|
"metadata": metadata,
|
||||||
|
}
|
||||||
|
|
||||||
|
autoCtx, autoCancel := context.WithTimeout(ctx, 30*time.Second)
|
||||||
|
defer autoCancel()
|
||||||
|
for attempt := 1; ; attempt++ {
|
||||||
|
var onboardResp map[string]any
|
||||||
|
if errOnboard := callGeminiCLI(autoCtx, httpClient, "onboardUser", autoOnboardReq, &onboardResp); errOnboard != nil {
|
||||||
|
return fmt.Errorf("auto-discovery onboardUser: %w", errOnboard)
|
||||||
|
}
|
||||||
|
|
||||||
|
if done, okDone := onboardResp["done"].(bool); okDone && done {
|
||||||
|
if resp, okResp := onboardResp["response"].(map[string]any); okResp {
|
||||||
|
switch v := resp["cloudaicompanionProject"].(type) {
|
||||||
|
case string:
|
||||||
|
projectID = strings.TrimSpace(v)
|
||||||
|
case map[string]any:
|
||||||
|
if id, okID := v["id"].(string); okID {
|
||||||
|
projectID = strings.TrimSpace(id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debugf("Auto-discovery: onboarding in progress, attempt %d...", attempt)
|
||||||
|
select {
|
||||||
|
case <-autoCtx.Done():
|
||||||
|
return &projectSelectionRequiredError{}
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if projectID == "" {
|
||||||
|
return &projectSelectionRequiredError{}
|
||||||
|
}
|
||||||
|
log.Infof("Auto-discovered project ID via onboarding: %s", projectID)
|
||||||
}
|
}
|
||||||
|
|
||||||
onboardReqBody := map[string]any{
|
onboardReqBody := map[string]any{
|
||||||
@@ -617,7 +683,7 @@ func updateAuthRecord(record *cliproxyauth.Auth, storage *gemini.GeminiTokenStor
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
finalName := gemini.CredentialFileName(storage.Email, storage.ProjectID, false)
|
finalName := gemini.CredentialFileName(storage.Email, storage.ProjectID, true)
|
||||||
|
|
||||||
if record.Metadata == nil {
|
if record.Metadata == nil {
|
||||||
record.Metadata = make(map[string]any)
|
record.Metadata = make(map[string]any)
|
||||||
|
|||||||
@@ -54,8 +54,7 @@ func DoCodexLogin(cfg *config.Config, options *LoginOptions) {
|
|||||||
|
|
||||||
_, savedPath, err := manager.Login(context.Background(), "codex", cfg, authOpts)
|
_, savedPath, err := manager.Login(context.Background(), "codex", cfg, authOpts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
var authErr *codex.AuthenticationError
|
if authErr, ok := errors.AsType[*codex.AuthenticationError](err); ok {
|
||||||
if errors.As(err, &authErr) {
|
|
||||||
log.Error(codex.GetUserFriendlyMessage(authErr))
|
log.Error(codex.GetUserFriendlyMessage(authErr))
|
||||||
if authErr.Type == codex.ErrPortInUse.Type {
|
if authErr.Type == codex.ErrPortInUse.Type {
|
||||||
os.Exit(codex.ErrPortInUse.Code)
|
os.Exit(codex.ErrPortInUse.Code)
|
||||||
|
|||||||
@@ -44,8 +44,7 @@ func DoQwenLogin(cfg *config.Config, options *LoginOptions) {
|
|||||||
|
|
||||||
_, savedPath, err := manager.Login(context.Background(), "qwen", cfg, authOpts)
|
_, savedPath, err := manager.Login(context.Background(), "qwen", cfg, authOpts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
var emailErr *sdkAuth.EmailRequiredError
|
if emailErr, ok := errors.AsType[*sdkAuth.EmailRequiredError](err); ok {
|
||||||
if errors.As(err, &emailErr) {
|
|
||||||
log.Error(emailErr.Error())
|
log.Error(emailErr.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -601,8 +601,7 @@ func (r *ModelRegistry) SetModelQuotaExceeded(clientID, modelID string) {
|
|||||||
defer r.mutex.Unlock()
|
defer r.mutex.Unlock()
|
||||||
|
|
||||||
if registration, exists := r.models[modelID]; exists {
|
if registration, exists := r.models[modelID]; exists {
|
||||||
now := time.Now()
|
registration.QuotaExceededClients[clientID] = new(time.Now())
|
||||||
registration.QuotaExceededClients[clientID] = &now
|
|
||||||
log.Debugf("Marked model %s as quota exceeded for client %s", modelID, clientID)
|
log.Debugf("Marked model %s as quota exceeded for client %s", modelID, clientID)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -899,8 +899,7 @@ func parseRetryDelay(errorBody []byte) (*time.Duration, error) {
|
|||||||
if matches := re.FindStringSubmatch(message); len(matches) > 1 {
|
if matches := re.FindStringSubmatch(message); len(matches) > 1 {
|
||||||
seconds, err := strconv.Atoi(matches[1])
|
seconds, err := strconv.Atoi(matches[1])
|
||||||
if err == nil {
|
if err == nil {
|
||||||
duration := time.Duration(seconds) * time.Second
|
return new(time.Duration(seconds) * time.Second), nil
|
||||||
return &duration, nil
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -90,6 +90,9 @@ func ConvertCodexResponseToOpenAI(_ context.Context, modelName string, originalR
|
|||||||
if inputTokensResult := usageResult.Get("input_tokens"); inputTokensResult.Exists() {
|
if inputTokensResult := usageResult.Get("input_tokens"); inputTokensResult.Exists() {
|
||||||
template, _ = sjson.Set(template, "usage.prompt_tokens", inputTokensResult.Int())
|
template, _ = sjson.Set(template, "usage.prompt_tokens", inputTokensResult.Int())
|
||||||
}
|
}
|
||||||
|
if cachedTokensResult := usageResult.Get("input_tokens_details.cached_tokens"); cachedTokensResult.Exists() {
|
||||||
|
template, _ = sjson.Set(template, "usage.prompt_tokens_details.cached_tokens", cachedTokensResult.Int())
|
||||||
|
}
|
||||||
if reasoningTokensResult := usageResult.Get("output_tokens_details.reasoning_tokens"); reasoningTokensResult.Exists() {
|
if reasoningTokensResult := usageResult.Get("output_tokens_details.reasoning_tokens"); reasoningTokensResult.Exists() {
|
||||||
template, _ = sjson.Set(template, "usage.completion_tokens_details.reasoning_tokens", reasoningTokensResult.Int())
|
template, _ = sjson.Set(template, "usage.completion_tokens_details.reasoning_tokens", reasoningTokensResult.Int())
|
||||||
}
|
}
|
||||||
@@ -205,6 +208,9 @@ func ConvertCodexResponseToOpenAINonStream(_ context.Context, _ string, original
|
|||||||
if inputTokensResult := usageResult.Get("input_tokens"); inputTokensResult.Exists() {
|
if inputTokensResult := usageResult.Get("input_tokens"); inputTokensResult.Exists() {
|
||||||
template, _ = sjson.Set(template, "usage.prompt_tokens", inputTokensResult.Int())
|
template, _ = sjson.Set(template, "usage.prompt_tokens", inputTokensResult.Int())
|
||||||
}
|
}
|
||||||
|
if cachedTokensResult := usageResult.Get("input_tokens_details.cached_tokens"); cachedTokensResult.Exists() {
|
||||||
|
template, _ = sjson.Set(template, "usage.prompt_tokens_details.cached_tokens", cachedTokensResult.Int())
|
||||||
|
}
|
||||||
if reasoningTokensResult := usageResult.Get("output_tokens_details.reasoning_tokens"); reasoningTokensResult.Exists() {
|
if reasoningTokensResult := usageResult.Get("output_tokens_details.reasoning_tokens"); reasoningTokensResult.Exists() {
|
||||||
template, _ = sjson.Set(template, "usage.completion_tokens_details.reasoning_tokens", reasoningTokensResult.Int())
|
template, _ = sjson.Set(template, "usage.completion_tokens_details.reasoning_tokens", reasoningTokensResult.Int())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -185,8 +185,7 @@ func (h *GeminiCLIAPIHandler) handleInternalGenerateContent(c *gin.Context, rawJ
|
|||||||
func (h *GeminiCLIAPIHandler) forwardCLIStream(c *gin.Context, flusher http.Flusher, alt string, cancel func(error), data <-chan []byte, errs <-chan *interfaces.ErrorMessage) {
|
func (h *GeminiCLIAPIHandler) forwardCLIStream(c *gin.Context, flusher http.Flusher, alt string, cancel func(error), data <-chan []byte, errs <-chan *interfaces.ErrorMessage) {
|
||||||
var keepAliveInterval *time.Duration
|
var keepAliveInterval *time.Duration
|
||||||
if alt != "" {
|
if alt != "" {
|
||||||
disabled := time.Duration(0)
|
keepAliveInterval = new(time.Duration(0))
|
||||||
keepAliveInterval = &disabled
|
|
||||||
}
|
}
|
||||||
|
|
||||||
h.ForwardStream(c, flusher, cancel, data, errs, handlers.StreamForwardOptions{
|
h.ForwardStream(c, flusher, cancel, data, errs, handlers.StreamForwardOptions{
|
||||||
|
|||||||
@@ -300,8 +300,7 @@ func (h *GeminiAPIHandler) handleGenerateContent(c *gin.Context, modelName strin
|
|||||||
func (h *GeminiAPIHandler) forwardGeminiStream(c *gin.Context, flusher http.Flusher, alt string, cancel func(error), data <-chan []byte, errs <-chan *interfaces.ErrorMessage) {
|
func (h *GeminiAPIHandler) forwardGeminiStream(c *gin.Context, flusher http.Flusher, alt string, cancel func(error), data <-chan []byte, errs <-chan *interfaces.ErrorMessage) {
|
||||||
var keepAliveInterval *time.Duration
|
var keepAliveInterval *time.Duration
|
||||||
if alt != "" {
|
if alt != "" {
|
||||||
disabled := time.Duration(0)
|
keepAliveInterval = new(time.Duration(0))
|
||||||
keepAliveInterval = &disabled
|
|
||||||
}
|
}
|
||||||
|
|
||||||
h.ForwardStream(c, flusher, cancel, data, errs, handlers.StreamForwardOptions{
|
h.ForwardStream(c, flusher, cancel, data, errs, handlers.StreamForwardOptions{
|
||||||
|
|||||||
@@ -28,8 +28,7 @@ func (AntigravityAuthenticator) Provider() string { return "antigravity" }
|
|||||||
|
|
||||||
// RefreshLead instructs the manager to refresh five minutes before expiry.
|
// RefreshLead instructs the manager to refresh five minutes before expiry.
|
||||||
func (AntigravityAuthenticator) RefreshLead() *time.Duration {
|
func (AntigravityAuthenticator) RefreshLead() *time.Duration {
|
||||||
lead := 5 * time.Minute
|
return new(5 * time.Minute)
|
||||||
return &lead
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Login launches a local OAuth flow to obtain antigravity tokens and persists them.
|
// Login launches a local OAuth flow to obtain antigravity tokens and persists them.
|
||||||
|
|||||||
+1
-2
@@ -32,8 +32,7 @@ func (a *ClaudeAuthenticator) Provider() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (a *ClaudeAuthenticator) RefreshLead() *time.Duration {
|
func (a *ClaudeAuthenticator) RefreshLead() *time.Duration {
|
||||||
d := 4 * time.Hour
|
return new(4 * time.Hour)
|
||||||
return &d
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *ClaudeAuthenticator) Login(ctx context.Context, cfg *config.Config, opts *LoginOptions) (*coreauth.Auth, error) {
|
func (a *ClaudeAuthenticator) Login(ctx context.Context, cfg *config.Config, opts *LoginOptions) (*coreauth.Auth, error) {
|
||||||
|
|||||||
+1
-2
@@ -34,8 +34,7 @@ func (a *CodexAuthenticator) Provider() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (a *CodexAuthenticator) RefreshLead() *time.Duration {
|
func (a *CodexAuthenticator) RefreshLead() *time.Duration {
|
||||||
d := 5 * 24 * time.Hour
|
return new(5 * 24 * time.Hour)
|
||||||
return &d
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *CodexAuthenticator) Login(ctx context.Context, cfg *config.Config, opts *LoginOptions) (*coreauth.Auth, error) {
|
func (a *CodexAuthenticator) Login(ctx context.Context, cfg *config.Config, opts *LoginOptions) (*coreauth.Auth, error) {
|
||||||
|
|||||||
+73
-4
@@ -4,8 +4,10 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"io/fs"
|
"io/fs"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -186,15 +188,21 @@ func (s *FileTokenStore) readAuthFile(path, baseDir string) (*cliproxyauth.Auth,
|
|||||||
if provider == "" {
|
if provider == "" {
|
||||||
provider = "unknown"
|
provider = "unknown"
|
||||||
}
|
}
|
||||||
if provider == "antigravity" {
|
if provider == "antigravity" || provider == "gemini" {
|
||||||
projectID := ""
|
projectID := ""
|
||||||
if pid, ok := metadata["project_id"].(string); ok {
|
if pid, ok := metadata["project_id"].(string); ok {
|
||||||
projectID = strings.TrimSpace(pid)
|
projectID = strings.TrimSpace(pid)
|
||||||
}
|
}
|
||||||
if projectID == "" {
|
if projectID == "" {
|
||||||
accessToken := ""
|
accessToken := extractAccessToken(metadata)
|
||||||
if token, ok := metadata["access_token"].(string); ok {
|
// For gemini type, the stored access_token is likely expired (~1h lifetime).
|
||||||
accessToken = strings.TrimSpace(token)
|
// Refresh it using the long-lived refresh_token before querying.
|
||||||
|
if provider == "gemini" {
|
||||||
|
if tokenMap, ok := metadata["token"].(map[string]any); ok {
|
||||||
|
if refreshed, errRefresh := refreshGeminiAccessToken(tokenMap, http.DefaultClient); errRefresh == nil {
|
||||||
|
accessToken = refreshed
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if accessToken != "" {
|
if accessToken != "" {
|
||||||
fetchedProjectID, errFetch := FetchAntigravityProjectID(context.Background(), accessToken, http.DefaultClient)
|
fetchedProjectID, errFetch := FetchAntigravityProjectID(context.Background(), accessToken, http.DefaultClient)
|
||||||
@@ -313,6 +321,67 @@ func (s *FileTokenStore) baseDirSnapshot() string {
|
|||||||
return s.baseDir
|
return s.baseDir
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func extractAccessToken(metadata map[string]any) string {
|
||||||
|
if at, ok := metadata["access_token"].(string); ok {
|
||||||
|
if v := strings.TrimSpace(at); v != "" {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if tokenMap, ok := metadata["token"].(map[string]any); ok {
|
||||||
|
if at, ok := tokenMap["access_token"].(string); ok {
|
||||||
|
if v := strings.TrimSpace(at); v != "" {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func refreshGeminiAccessToken(tokenMap map[string]any, httpClient *http.Client) (string, error) {
|
||||||
|
refreshToken, _ := tokenMap["refresh_token"].(string)
|
||||||
|
clientID, _ := tokenMap["client_id"].(string)
|
||||||
|
clientSecret, _ := tokenMap["client_secret"].(string)
|
||||||
|
tokenURI, _ := tokenMap["token_uri"].(string)
|
||||||
|
|
||||||
|
if refreshToken == "" || clientID == "" || clientSecret == "" {
|
||||||
|
return "", fmt.Errorf("missing refresh credentials")
|
||||||
|
}
|
||||||
|
if tokenURI == "" {
|
||||||
|
tokenURI = "https://oauth2.googleapis.com/token"
|
||||||
|
}
|
||||||
|
|
||||||
|
data := url.Values{
|
||||||
|
"grant_type": {"refresh_token"},
|
||||||
|
"refresh_token": {refreshToken},
|
||||||
|
"client_id": {clientID},
|
||||||
|
"client_secret": {clientSecret},
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := httpClient.PostForm(tokenURI, data)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("refresh request: %w", err)
|
||||||
|
}
|
||||||
|
defer func() { _ = resp.Body.Close() }()
|
||||||
|
|
||||||
|
body, _ := io.ReadAll(resp.Body)
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return "", fmt.Errorf("refresh failed: status %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
var result map[string]any
|
||||||
|
if errUnmarshal := json.Unmarshal(body, &result); errUnmarshal != nil {
|
||||||
|
return "", fmt.Errorf("decode refresh response: %w", errUnmarshal)
|
||||||
|
}
|
||||||
|
|
||||||
|
newAccessToken, _ := result["access_token"].(string)
|
||||||
|
if newAccessToken == "" {
|
||||||
|
return "", fmt.Errorf("no access_token in refresh response")
|
||||||
|
}
|
||||||
|
|
||||||
|
tokenMap["access_token"] = newAccessToken
|
||||||
|
return newAccessToken, nil
|
||||||
|
}
|
||||||
|
|
||||||
// jsonEqual compares two JSON blobs by parsing them into Go objects and deep comparing.
|
// jsonEqual compares two JSON blobs by parsing them into Go objects and deep comparing.
|
||||||
func jsonEqual(a, b []byte) bool {
|
func jsonEqual(a, b []byte) bool {
|
||||||
var objA any
|
var objA any
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestExtractAccessToken(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
metadata map[string]any
|
||||||
|
expected string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
"antigravity top-level access_token",
|
||||||
|
map[string]any{"access_token": "tok-abc"},
|
||||||
|
"tok-abc",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"gemini nested token.access_token",
|
||||||
|
map[string]any{
|
||||||
|
"token": map[string]any{"access_token": "tok-nested"},
|
||||||
|
},
|
||||||
|
"tok-nested",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"top-level takes precedence over nested",
|
||||||
|
map[string]any{
|
||||||
|
"access_token": "tok-top",
|
||||||
|
"token": map[string]any{"access_token": "tok-nested"},
|
||||||
|
},
|
||||||
|
"tok-top",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"empty metadata",
|
||||||
|
map[string]any{},
|
||||||
|
"",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"whitespace-only access_token",
|
||||||
|
map[string]any{"access_token": " "},
|
||||||
|
"",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"wrong type access_token",
|
||||||
|
map[string]any{"access_token": 12345},
|
||||||
|
"",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"token is not a map",
|
||||||
|
map[string]any{"token": "not-a-map"},
|
||||||
|
"",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"nested whitespace-only",
|
||||||
|
map[string]any{
|
||||||
|
"token": map[string]any{"access_token": " "},
|
||||||
|
},
|
||||||
|
"",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fallback to nested when top-level empty",
|
||||||
|
map[string]any{
|
||||||
|
"access_token": "",
|
||||||
|
"token": map[string]any{"access_token": "tok-fallback"},
|
||||||
|
},
|
||||||
|
"tok-fallback",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
tt := tt
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
got := extractAccessToken(tt.metadata)
|
||||||
|
if got != tt.expected {
|
||||||
|
t.Errorf("extractAccessToken() = %q, want %q", got, tt.expected)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-2
@@ -26,8 +26,7 @@ func (a *IFlowAuthenticator) Provider() string { return "iflow" }
|
|||||||
|
|
||||||
// RefreshLead indicates how soon before expiry a refresh should be attempted.
|
// RefreshLead indicates how soon before expiry a refresh should be attempted.
|
||||||
func (a *IFlowAuthenticator) RefreshLead() *time.Duration {
|
func (a *IFlowAuthenticator) RefreshLead() *time.Duration {
|
||||||
d := 24 * time.Hour
|
return new(24 * time.Hour)
|
||||||
return &d
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Login performs the OAuth code flow using a local callback server.
|
// Login performs the OAuth code flow using a local callback server.
|
||||||
|
|||||||
+1
-2
@@ -27,8 +27,7 @@ func (a *QwenAuthenticator) Provider() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (a *QwenAuthenticator) RefreshLead() *time.Duration {
|
func (a *QwenAuthenticator) RefreshLead() *time.Duration {
|
||||||
d := 3 * time.Hour
|
return new(3 * time.Hour)
|
||||||
return &d
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *QwenAuthenticator) Login(ctx context.Context, cfg *config.Config, opts *LoginOptions) (*coreauth.Auth, error) {
|
func (a *QwenAuthenticator) Login(ctx context.Context, cfg *config.Config, opts *LoginOptions) (*coreauth.Auth, error) {
|
||||||
|
|||||||
@@ -599,8 +599,7 @@ func (m *Manager) executeMixedOnce(ctx context.Context, providers []string, req
|
|||||||
return cliproxyexecutor.Response{}, errCtx
|
return cliproxyexecutor.Response{}, errCtx
|
||||||
}
|
}
|
||||||
result.Error = &Error{Message: errExec.Error()}
|
result.Error = &Error{Message: errExec.Error()}
|
||||||
var se cliproxyexecutor.StatusError
|
if se, ok := errors.AsType[cliproxyexecutor.StatusError](errExec); ok && se != nil {
|
||||||
if errors.As(errExec, &se) && se != nil {
|
|
||||||
result.Error.HTTPStatus = se.StatusCode()
|
result.Error.HTTPStatus = se.StatusCode()
|
||||||
}
|
}
|
||||||
if ra := retryAfterFromError(errExec); ra != nil {
|
if ra := retryAfterFromError(errExec); ra != nil {
|
||||||
@@ -655,8 +654,7 @@ func (m *Manager) executeCountMixedOnce(ctx context.Context, providers []string,
|
|||||||
return cliproxyexecutor.Response{}, errCtx
|
return cliproxyexecutor.Response{}, errCtx
|
||||||
}
|
}
|
||||||
result.Error = &Error{Message: errExec.Error()}
|
result.Error = &Error{Message: errExec.Error()}
|
||||||
var se cliproxyexecutor.StatusError
|
if se, ok := errors.AsType[cliproxyexecutor.StatusError](errExec); ok && se != nil {
|
||||||
if errors.As(errExec, &se) && se != nil {
|
|
||||||
result.Error.HTTPStatus = se.StatusCode()
|
result.Error.HTTPStatus = se.StatusCode()
|
||||||
}
|
}
|
||||||
if ra := retryAfterFromError(errExec); ra != nil {
|
if ra := retryAfterFromError(errExec); ra != nil {
|
||||||
@@ -710,8 +708,7 @@ func (m *Manager) executeStreamMixedOnce(ctx context.Context, providers []string
|
|||||||
return nil, errCtx
|
return nil, errCtx
|
||||||
}
|
}
|
||||||
rerr := &Error{Message: errStream.Error()}
|
rerr := &Error{Message: errStream.Error()}
|
||||||
var se cliproxyexecutor.StatusError
|
if se, ok := errors.AsType[cliproxyexecutor.StatusError](errStream); ok && se != nil {
|
||||||
if errors.As(errStream, &se) && se != nil {
|
|
||||||
rerr.HTTPStatus = se.StatusCode()
|
rerr.HTTPStatus = se.StatusCode()
|
||||||
}
|
}
|
||||||
result := Result{AuthID: auth.ID, Provider: provider, Model: routeModel, Success: false, Error: rerr}
|
result := Result{AuthID: auth.ID, Provider: provider, Model: routeModel, Success: false, Error: rerr}
|
||||||
@@ -732,8 +729,7 @@ func (m *Manager) executeStreamMixedOnce(ctx context.Context, providers []string
|
|||||||
if chunk.Err != nil && !failed {
|
if chunk.Err != nil && !failed {
|
||||||
failed = true
|
failed = true
|
||||||
rerr := &Error{Message: chunk.Err.Error()}
|
rerr := &Error{Message: chunk.Err.Error()}
|
||||||
var se cliproxyexecutor.StatusError
|
if se, ok := errors.AsType[cliproxyexecutor.StatusError](chunk.Err); ok && se != nil {
|
||||||
if errors.As(chunk.Err, &se) && se != nil {
|
|
||||||
rerr.HTTPStatus = se.StatusCode()
|
rerr.HTTPStatus = se.StatusCode()
|
||||||
}
|
}
|
||||||
m.MarkResult(streamCtx, Result{AuthID: streamAuth.ID, Provider: streamProvider, Model: routeModel, Success: false, Error: rerr})
|
m.MarkResult(streamCtx, Result{AuthID: streamAuth.ID, Provider: streamProvider, Model: routeModel, Success: false, Error: rerr})
|
||||||
@@ -1431,8 +1427,7 @@ func retryAfterFromError(err error) *time.Duration {
|
|||||||
if retryAfter == nil {
|
if retryAfter == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
val := *retryAfter
|
return new(*retryAfter)
|
||||||
return &val
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func statusCodeFromResult(err *Error) int {
|
func statusCodeFromResult(err *Error) int {
|
||||||
|
|||||||
Reference in New Issue
Block a user