diff --git a/cmd/server/main.go b/cmd/server/main.go index 8ce2ad59..82d170b5 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -1,710 +1,785 @@ -// Package main provides the entry point for the ProxyPilot engine. -// This server acts as a proxy that provides OpenAI/Gemini/Claude compatible API interfaces -// for CLI models, allowing CLI models to be used with tools and libraries designed for standard AI APIs. -package main - -import ( - "context" - "errors" - "flag" - "fmt" - "io/fs" - "net/url" - "os" - "path/filepath" - "strings" - "time" - - "github.com/joho/godotenv" - "github.com/router-for-me/CLIProxyAPI/v6/internal/buildinfo" - "github.com/router-for-me/CLIProxyAPI/v6/internal/cmd" - "github.com/router-for-me/CLIProxyAPI/v6/internal/config" - "github.com/router-for-me/CLIProxyAPI/v6/internal/desktopctl" - "github.com/router-for-me/CLIProxyAPI/v6/internal/logging" - "github.com/router-for-me/CLIProxyAPI/v6/internal/misc" - "github.com/router-for-me/CLIProxyAPI/v6/internal/store" - _ "github.com/router-for-me/CLIProxyAPI/v6/internal/translator" - "github.com/router-for-me/CLIProxyAPI/v6/internal/usage" - "github.com/router-for-me/CLIProxyAPI/v6/internal/util" - sdkAuth "github.com/router-for-me/CLIProxyAPI/v6/sdk/auth" - configaccess "github.com/router-for-me/CLIProxyAPI/v6/sdk/access/config" - coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth" - log "github.com/sirupsen/logrus" -) - -var ( - Version = "dev" - Commit = "none" - BuildDate = "unknown" - DefaultConfigPath = "" -) - -// init initializes the shared logger setup. -func init() { - logging.SetupBaseLogger() - buildinfo.Version = Version - buildinfo.Commit = Commit - buildinfo.BuildDate = BuildDate -} - -// setKiroIncognitoMode sets the incognito browser mode for Kiro authentication. -// Kiro defaults to incognito mode for multi-account support. -// Users can explicitly override with --incognito or --no-incognito flags. -func setKiroIncognitoMode(cfg *config.Config, useIncognito, noIncognito bool) { - if useIncognito { - cfg.IncognitoBrowser = true - } else if noIncognito { - cfg.IncognitoBrowser = false - } else { - cfg.IncognitoBrowser = true // Kiro default - } -} - -// main is the entry point of the application. -// It parses command-line flags, loads configuration, and starts the appropriate -// service based on the provided flags (login, codex-login, or server mode). -func main() { - fmt.Printf("ProxyPilot Engine Version: %s, Commit: %s, BuiltAt: %s\n", buildinfo.Version, buildinfo.Commit, buildinfo.BuildDate) - - // Command-line flags to control the application's behavior. - var login bool - var codexLogin bool - var claudeLogin bool - var qwenLogin bool - var noBrowser bool - var antigravityLogin bool - var kiroLogin bool - var kiroGoogleLogin bool - var kiroAWSLogin bool - var kiroAWSAuthCode bool - var kiroImport bool - var amazonqImport bool - var antigravityImport bool - var minimaxLogin bool - var zhipuLogin bool - // var githubCopilotLogin bool // REMOVED - GitHub Copilot excluded - var detectAgents bool - var setupClaude bool - var setupCodex bool - var setupDroid bool - var setupOpenCode bool - var setupGemini bool - var setupCursor bool - var setupKilo bool - var setupRooCode bool - var setupAll bool - var switchAgent string - var switchMode string - var projectID string - var vertexImport string - var configPath string - var password string - var noIncognito bool - var useIncognito bool - - // Account management flags - var showVersion bool - var showStatus bool - var listAccounts bool - var cleanupExpired bool - var removeAccount string - var jsonOutput bool - var quietMode bool - var verboseMode bool - - // Define command-line flags for different operation modes. - flag.BoolVar(&login, "login", false, "Login Google Account") - flag.BoolVar(&codexLogin, "codex-login", false, "Login to Codex using OAuth") - flag.BoolVar(&claudeLogin, "claude-login", false, "Login to Claude using OAuth") - flag.BoolVar(&qwenLogin, "qwen-login", false, "Login to Qwen using OAuth") - flag.BoolVar(&noBrowser, "no-browser", false, "Don't open browser automatically for OAuth") - flag.BoolVar(&useIncognito, "incognito", false, "Open browser in incognito/private mode for OAuth (useful for multiple accounts)") - flag.BoolVar(&noIncognito, "no-incognito", false, "Force disable incognito mode (uses existing browser session)") - flag.BoolVar(&antigravityLogin, "antigravity-login", false, "Login to Antigravity using OAuth") - flag.BoolVar(&kiroLogin, "kiro-login", false, "Login to Kiro using Google OAuth") - flag.BoolVar(&kiroGoogleLogin, "kiro-google-login", false, "Login to Kiro using Google OAuth (same as --kiro-login)") - flag.BoolVar(&kiroAWSLogin, "kiro-aws-login", false, "Login to Kiro using AWS Builder ID (device code flow)") - flag.BoolVar(&kiroAWSAuthCode, "kiro-aws-authcode", false, "Login to Kiro using AWS Builder ID (authorization code flow, better UX)") - flag.BoolVar(&kiroImport, "kiro-import", false, "Import Kiro token from Kiro IDE (~/.aws/sso/cache/kiro-auth-token.json)") - flag.BoolVar(&amazonqImport, "amazonq-import", false, "Import Amazon Q CLI token from SQLite database") - flag.BoolVar(&antigravityImport, "antigravity-import", false, "Import Antigravity token from Antigravity IDE") - flag.BoolVar(&minimaxLogin, "minimax-login", false, "Add MiniMax API key") - flag.BoolVar(&zhipuLogin, "zhipu-login", false, "Add Zhipu AI API key") - // GitHub Copilot login removed - flag.BoolVar(&detectAgents, "detect-agents", false, "Detect installed CLI agents") - flag.BoolVar(&setupClaude, "setup-claude", false, "Configure Claude Code to use ProxyPilot") - flag.BoolVar(&setupCodex, "setup-codex", false, "Configure Codex CLI to use ProxyPilot") - flag.BoolVar(&setupDroid, "setup-droid", false, "Configure Factory Droid to use ProxyPilot") - flag.BoolVar(&setupOpenCode, "setup-opencode", false, "Configure OpenCode to use ProxyPilot") - flag.BoolVar(&setupGemini, "setup-gemini", false, "Configure Gemini CLI to use ProxyPilot") - flag.BoolVar(&setupCursor, "setup-cursor", false, "Configure Cursor to use ProxyPilot") - flag.BoolVar(&setupKilo, "setup-kilo", false, "Configure Kilo Code CLI to use ProxyPilot") - flag.BoolVar(&setupRooCode, "setup-roocode", false, "Configure RooCode (VS Code) to use ProxyPilot") - flag.BoolVar(&setupAll, "setup-all", false, "Configure all detected CLI agents (with backup)") - flag.StringVar(&switchAgent, "switch", "", "Switch agent config mode (e.g., --switch claude)") - flag.StringVar(&switchMode, "mode", "", "Switch mode: proxy, native, or status (default: status)") - flag.StringVar(&projectID, "project_id", "", "Project ID (Gemini only, not required)") - flag.StringVar(&configPath, "config", DefaultConfigPath, "Configure File Path") - flag.StringVar(&vertexImport, "vertex-import", "", "Import Vertex service account key JSON file") - flag.StringVar(&password, "password", "", "") - - flag.BoolVar(&showVersion, "version", false, "Show ProxyPilot version and exit") - flag.BoolVar(&showStatus, "status", false, "Show ProxyPilot status and exit") - flag.BoolVar(&listAccounts, "list-accounts", false, "List all configured accounts and exit") - flag.BoolVar(&cleanupExpired, "cleanup-expired", false, "Remove expired tokens and exit") - flag.StringVar(&removeAccount, "remove-account", "", "Remove a specific account by name and exit") - flag.BoolVar(&jsonOutput, "json", false, "Output in JSON format (overrides --quiet)") - flag.BoolVar(&quietMode, "quiet", false, "Run in quiet mode (overrides --verbose)") - flag.BoolVar(&verboseMode, "verbose", false, "Run in verbose mode") - - flag.CommandLine.Usage = func() { - out := flag.CommandLine.Output() - _, _ = fmt.Fprintf(out, "Usage of %s\n", os.Args[0]) - flag.CommandLine.VisitAll(func(f *flag.Flag) { - if f.Name == "password" { - return - } - s := fmt.Sprintf(" -%s", f.Name) - name, unquoteUsage := flag.UnquoteUsage(f) - if name != "" { - s += " " + name - } - if len(s) <= 4 { - s += " " - } else { - s += "\n " - } - if unquoteUsage != "" { - s += unquoteUsage - } - if f.DefValue != "" && f.DefValue != "false" && f.DefValue != "0" { - s += fmt.Sprintf(" (default %s)", f.DefValue) - } - _, _ = fmt.Fprint(out, s+"\n") - }) - } - - // Check for subcommand-style switch command before flag.Parse() - // Supports: proxypilot switch [agent] [mode] - // agent can be: claude, gemini, codex, opencode, droid, cursor - // mode can be: proxy, native, status (default if omitted) - var subcommandSwitch bool - args := os.Args[1:] - if len(args) > 0 && args[0] == "switch" { - subcommandSwitch = true - switchArgs := args[1:] - // Filter out any flags like --status from positional args - var positionalArgs []string - for _, arg := range switchArgs { - if arg == "--status" { - switchMode = "status" - } else if !strings.HasPrefix(arg, "-") { - positionalArgs = append(positionalArgs, arg) - } - } - // Parse positional arguments: [agent] [mode] - if len(positionalArgs) >= 1 { - switchAgent = positionalArgs[0] - } - if len(positionalArgs) >= 2 { - switchMode = positionalArgs[1] - } - // Default mode to "status" if not specified - if switchMode == "" { - switchMode = "status" - } - } - - // Parse the command-line flags. - flag.Parse() - - // Core application variables. - var err error - var cfg *config.Config - var isCloudDeploy bool - var ( - usePostgresStore bool - pgStoreDSN string - pgStoreSchema string - pgStoreLocalPath string - pgStoreInst *store.PostgresStore - useGitStore bool - gitStoreRemoteURL string - gitStoreUser string - gitStorePassword string - gitStoreLocalPath string - gitStoreInst *store.GitTokenStore - gitStoreRoot string - useObjectStore bool - objectStoreEndpoint string - objectStoreAccess string - objectStoreSecret string - objectStoreBucket string - objectStoreLocalPath string - objectStoreInst *store.ObjectTokenStore - ) - - wd, err := os.Getwd() - if err != nil { - log.Errorf("failed to get working directory: %v", err) - return - } - - // Load environment variables from .env if present. - if errLoad := godotenv.Load(filepath.Join(wd, ".env")); errLoad != nil { - if !errors.Is(errLoad, os.ErrNotExist) { - log.WithError(errLoad).Warn("failed to load .env file") - } - } - - lookupEnv := func(keys ...string) (string, bool) { - for _, key := range keys { - if value, ok := os.LookupEnv(key); ok { - if trimmed := strings.TrimSpace(value); trimmed != "" { - return trimmed, true - } - } - } - return "", false - } - writableBase := util.WritablePath() - if value, ok := lookupEnv("PGSTORE_DSN", "pgstore_dsn"); ok { - usePostgresStore = true - pgStoreDSN = value - } - if usePostgresStore { - if value, ok := lookupEnv("PGSTORE_SCHEMA", "pgstore_schema"); ok { - pgStoreSchema = value - } - if value, ok := lookupEnv("PGSTORE_LOCAL_PATH", "pgstore_local_path"); ok { - pgStoreLocalPath = value - } - if pgStoreLocalPath == "" { - if writableBase != "" { - pgStoreLocalPath = writableBase - } else { - pgStoreLocalPath = wd - } - } - useGitStore = false - } - if value, ok := lookupEnv("GITSTORE_GIT_URL", "gitstore_git_url"); ok { - useGitStore = true - gitStoreRemoteURL = value - } - if value, ok := lookupEnv("GITSTORE_GIT_USERNAME", "gitstore_git_username"); ok { - gitStoreUser = value - } - if value, ok := lookupEnv("GITSTORE_GIT_TOKEN", "gitstore_git_token"); ok { - gitStorePassword = value - } - if value, ok := lookupEnv("GITSTORE_LOCAL_PATH", "gitstore_local_path"); ok { - gitStoreLocalPath = value - } - if value, ok := lookupEnv("OBJECTSTORE_ENDPOINT", "objectstore_endpoint"); ok { - useObjectStore = true - objectStoreEndpoint = value - } - if value, ok := lookupEnv("OBJECTSTORE_ACCESS_KEY", "objectstore_access_key"); ok { - objectStoreAccess = value - } - if value, ok := lookupEnv("OBJECTSTORE_SECRET_KEY", "objectstore_secret_key"); ok { - objectStoreSecret = value - } - if value, ok := lookupEnv("OBJECTSTORE_BUCKET", "objectstore_bucket"); ok { - objectStoreBucket = value - } - if value, ok := lookupEnv("OBJECTSTORE_LOCAL_PATH", "objectstore_local_path"); ok { - objectStoreLocalPath = value - } - - // Check for cloud deploy mode only on first execution - // Read env var name in uppercase: DEPLOY - deployEnv := os.Getenv("DEPLOY") - if deployEnv == "cloud" { - isCloudDeploy = true - } - - // Determine and load the configuration file. - // Prefer the Postgres store when configured, otherwise fallback to git or local files. - var configFilePath string - if usePostgresStore { - if pgStoreLocalPath == "" { - pgStoreLocalPath = wd - } - pgStoreLocalPath = filepath.Join(pgStoreLocalPath, "pgstore") - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - pgStoreInst, err = store.NewPostgresStore(ctx, store.PostgresStoreConfig{ - DSN: pgStoreDSN, - Schema: pgStoreSchema, - SpoolDir: pgStoreLocalPath, - }) - cancel() - if err != nil { - log.Errorf("failed to initialize postgres token store: %v", err) - return - } - examplePath := filepath.Join(wd, "config.example.yaml") - ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second) - if errBootstrap := pgStoreInst.Bootstrap(ctx, examplePath); errBootstrap != nil { - cancel() - log.Errorf("failed to bootstrap postgres-backed config: %v", errBootstrap) - return - } - cancel() - configFilePath = pgStoreInst.ConfigPath() - cfg, err = config.LoadConfigOptional(configFilePath, isCloudDeploy) - if err == nil { - cfg.AuthDir = pgStoreInst.AuthDir() - log.Infof("postgres-backed token store enabled, workspace path: %s", pgStoreInst.WorkDir()) - } - } else if useObjectStore { - if objectStoreLocalPath == "" { - if writableBase != "" { - objectStoreLocalPath = writableBase - } else { - objectStoreLocalPath = wd - } - } - objectStoreRoot := filepath.Join(objectStoreLocalPath, "objectstore") - resolvedEndpoint := strings.TrimSpace(objectStoreEndpoint) - useSSL := true - if strings.Contains(resolvedEndpoint, "://") { - parsed, errParse := url.Parse(resolvedEndpoint) - if errParse != nil { - log.Errorf("failed to parse object store endpoint %q: %v", objectStoreEndpoint, errParse) - return - } - switch strings.ToLower(parsed.Scheme) { - case "http": - useSSL = false - case "https": - useSSL = true - default: - log.Errorf("unsupported object store scheme %q (only http and https are allowed)", parsed.Scheme) - return - } - if parsed.Host == "" { - log.Errorf("object store endpoint %q is missing host information", objectStoreEndpoint) - return - } - resolvedEndpoint = parsed.Host - if parsed.Path != "" && parsed.Path != "/" { - resolvedEndpoint = strings.TrimSuffix(parsed.Host+parsed.Path, "/") - } - } - resolvedEndpoint = strings.TrimRight(resolvedEndpoint, "/") - objCfg := store.ObjectStoreConfig{ - Endpoint: resolvedEndpoint, - Bucket: objectStoreBucket, - AccessKey: objectStoreAccess, - SecretKey: objectStoreSecret, - LocalRoot: objectStoreRoot, - UseSSL: useSSL, - PathStyle: true, - } - objectStoreInst, err = store.NewObjectTokenStore(objCfg) - if err != nil { - log.Errorf("failed to initialize object token store: %v", err) - return - } - examplePath := filepath.Join(wd, "config.example.yaml") - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - if errBootstrap := objectStoreInst.Bootstrap(ctx, examplePath); errBootstrap != nil { - cancel() - log.Errorf("failed to bootstrap object-backed config: %v", errBootstrap) - return - } - cancel() - configFilePath = objectStoreInst.ConfigPath() - cfg, err = config.LoadConfigOptional(configFilePath, isCloudDeploy) - if err == nil { - if cfg == nil { - cfg = &config.Config{} - } - cfg.AuthDir = objectStoreInst.AuthDir() - log.Infof("object-backed token store enabled, bucket: %s", objectStoreBucket) - } - } else if useGitStore { - if gitStoreLocalPath == "" { - if writableBase != "" { - gitStoreLocalPath = writableBase - } else { - gitStoreLocalPath = wd - } - } - gitStoreRoot = filepath.Join(gitStoreLocalPath, "gitstore") - authDir := filepath.Join(gitStoreRoot, "auths") - gitStoreInst = store.NewGitTokenStore(gitStoreRemoteURL, gitStoreUser, gitStorePassword) - gitStoreInst.SetBaseDir(authDir) - if errRepo := gitStoreInst.EnsureRepository(); errRepo != nil { - log.Errorf("failed to prepare git token store: %v", errRepo) - return - } - configFilePath = gitStoreInst.ConfigPath() - if configFilePath == "" { - configFilePath = filepath.Join(gitStoreRoot, "config", "config.yaml") - } - if _, statErr := os.Stat(configFilePath); errors.Is(statErr, fs.ErrNotExist) { - examplePath := filepath.Join(wd, "config.example.yaml") - if _, errExample := os.Stat(examplePath); errExample != nil { - log.Errorf("failed to find template config file: %v", errExample) - return - } - if errCopy := misc.CopyConfigTemplate(examplePath, configFilePath); errCopy != nil { - log.Errorf("failed to bootstrap git-backed config: %v", errCopy) - return - } - if errCommit := gitStoreInst.PersistConfig(context.Background()); errCommit != nil { - log.Errorf("failed to commit initial git-backed config: %v", errCommit) - return - } - log.Infof("git-backed config initialized from template: %s", configFilePath) - } else if statErr != nil { - log.Errorf("failed to inspect git-backed config: %v", statErr) - return - } - cfg, err = config.LoadConfigOptional(configFilePath, isCloudDeploy) - if err == nil { - cfg.AuthDir = gitStoreInst.AuthDir() - log.Infof("git-backed token store enabled, repository path: %s", gitStoreRoot) - } - } else if configPath != "" { - configFilePath = configPath - cfg, err = config.LoadConfigOptional(configPath, isCloudDeploy) - } else { - wd, err = os.Getwd() - if err != nil { - log.Errorf("failed to get working directory: %v", err) - return - } - configFilePath = filepath.Join(wd, "config.yaml") - cfg, err = config.LoadConfigOptional(configFilePath, isCloudDeploy) - } - if err != nil { - // For switch command, config is optional - use defaults - if subcommandSwitch || switchAgent != "" { - cfg = &config.Config{Port: 8317} - } else { - log.Errorf("failed to load config: %v", err) - return - } - } - if cfg == nil { - cfg = &config.Config{} - } - - // In cloud deploy mode, check if we have a valid configuration - var configFileExists bool - if isCloudDeploy { - if info, errStat := os.Stat(configFilePath); errStat != nil { - // Don't mislead: API server will not start until configuration is provided. - log.Info("Cloud deploy mode: No configuration file detected; standing by for configuration") - configFileExists = false - } else if info.IsDir() { - log.Info("Cloud deploy mode: Config path is a directory; standing by for configuration") - configFileExists = false - } else if cfg.Port == 0 { - // LoadConfigOptional returns empty config when file is empty or invalid. - // Config file exists but is empty or invalid; treat as missing config - log.Info("Cloud deploy mode: Configuration file is empty or invalid; standing by for valid configuration") - configFileExists = false - } else { - log.Info("Cloud deploy mode: Configuration file detected; starting service") - configFileExists = true - } - } - - // Perform basic semantic validation of the loaded configuration. - if warnings, errValidate := config.ValidateConfig(cfg); errValidate != nil { - log.Errorf("invalid configuration: %v", errValidate) - return - } else if len(warnings) > 0 { - for _, w := range warnings { - log.Warnf("config warning: %s", w) - } - } - - usage.SetStatisticsEnabled(cfg.UsageStatisticsEnabled) - coreauth.SetQuotaCooldownDisabled(cfg.DisableCooling) - // AntigravityPrimaryEmail removed - field does not exist - - if err = logging.ConfigureLogOutput(cfg.LoggingToFile, cfg.LogsMaxTotalSizeMB); err != nil { - log.Errorf("failed to configure log output: %v", err) - return - } - - log.Infof("ProxyPilot Engine Version: %s, Commit: %s, BuiltAt: %s", buildinfo.Version, buildinfo.Commit, buildinfo.BuildDate) - - // Set the log level based on the configuration. - util.SetLogLevel(cfg) - - // CLI flags override config-based log level - if quietMode { - logging.SetLogLevel("quiet") - } else if verboseMode { - logging.SetLogLevel("verbose") - } - - if resolvedAuthDir, errResolveAuthDir := util.ResolveAuthDir(cfg.AuthDir); errResolveAuthDir != nil { - log.Errorf("failed to resolve auth directory: %v", errResolveAuthDir) - return - } else { - cfg.AuthDir = resolvedAuthDir - } - - // Create login options to be used in authentication flows. - options := &cmd.LoginOptions{ - NoBrowser: noBrowser, - } - - // Register the shared token store once so all components use the same persistence backend. - if usePostgresStore { - sdkAuth.RegisterTokenStore(pgStoreInst) - } else if useObjectStore { - sdkAuth.RegisterTokenStore(objectStoreInst) - } else if useGitStore { - sdkAuth.RegisterTokenStore(gitStoreInst) - } else { - sdkAuth.RegisterTokenStore(sdkAuth.NewFileTokenStore()) - } - - // Register built-in access providers before constructing services. - configaccess.Register() - - // Handle different command modes based on the provided flags. - - if vertexImport != "" { - // Handle Vertex service account import - cmd.DoVertexImport(cfg, vertexImport) - } else if showVersion { - // Version already printed at startup, just exit - return - } else if showStatus { - if err := cmd.ShowStatus(jsonOutput); err != nil { - log.Errorf("status failed: %v", err) - os.Exit(1) - } - return - } else if listAccounts { - if err := cmd.ListAccounts(jsonOutput); err != nil { - log.Errorf("list-accounts failed: %v", err) - os.Exit(1) - } - return - } else if cleanupExpired { - if err := cmd.CleanupExpired(false); err != nil { - log.Errorf("cleanup-expired failed: %v", err) - os.Exit(1) - } - return - } else if removeAccount != "" { - if err := cmd.RemoveAccount(removeAccount); err != nil { - log.Errorf("remove-account failed: %v", err) - os.Exit(1) - } - return - } else if login { - // Handle Google/Gemini login - cmd.DoLogin(cfg, projectID, options) - } else if antigravityLogin { - // Handle Antigravity login - cmd.DoAntigravityLogin(cfg, options) - } else if false { // GitHub Copilot removed - // Handle GitHub Copilot login - // GitHub Copilot login removed - } else if codexLogin { - // Handle Codex login - cmd.DoCodexLogin(cfg, options) - } else if claudeLogin { - // Handle Claude login - cmd.DoClaudeLogin(cfg, options) - } else if qwenLogin { - cmd.DoQwenLogin(cfg, options) - } else if kiroLogin { - // For Kiro auth, default to incognito mode for multi-account support - // Users can explicitly override with --no-incognito - // Note: This config mutation is safe - auth commands exit after completion - // and don't share config with StartService (which is in the else branch) - setKiroIncognitoMode(cfg, useIncognito, noIncognito) - cmd.DoKiroLogin(cfg, options) - } else if kiroGoogleLogin { - // For Kiro auth, default to incognito mode for multi-account support - // Users can explicitly override with --no-incognito - // Note: This config mutation is safe - auth commands exit after completion - setKiroIncognitoMode(cfg, useIncognito, noIncognito) - cmd.DoKiroGoogleLogin(cfg, options) - } else if kiroAWSLogin { - // For Kiro auth, default to incognito mode for multi-account support - // Users can explicitly override with --no-incognito - setKiroIncognitoMode(cfg, useIncognito, noIncognito) - cmd.DoKiroAWSLogin(cfg, options) - } else if kiroAWSAuthCode { - // For Kiro auth with authorization code flow (better UX) - setKiroIncognitoMode(cfg, useIncognito, noIncognito) - cmd.DoKiroAWSAuthCodeLogin(cfg, options) - } else if kiroImport { - cmd.DoKiroImport(cfg, options) - } else if amazonqImport { - cmd.DoAmazonQImport(cfg, options) - } else if antigravityImport { - cmd.DoAntigravityImport(cfg) - } else if minimaxLogin { - cmd.DoMiniMaxLogin(cfg, options) - } else if zhipuLogin { - cmd.DoZhipuLogin(cfg, options) - } else if detectAgents { - cmd.DoDetectAgents() - } else if setupClaude { - cmd.DoSetupClaude(cfg) - } else if setupCodex { - cmd.DoSetupCodex(cfg) - } else if setupDroid { - cmd.DoSetupDroid(cfg) - } else if setupOpenCode { - cmd.DoSetupOpenCode(cfg) - } else if setupGemini { - cmd.DoSetupGeminiCLI(cfg) - } else if setupCursor { - cmd.DoSetupCursor(cfg) - } else if setupKilo { - cmd.DoSetupKiloCode(cfg) - } else if setupRooCode { - cmd.DoSetupRooCode(cfg) - } else if setupAll { - cmd.DoSetupAll(cfg) - } else if subcommandSwitch || switchAgent != "" || switchMode != "" { - // Handle switch command: - // - Subcommand style: proxypilot switch claude proxy - // - Flag style: proxypilot --switch claude --mode proxy - cmd.DoSwitch(cfg, switchAgent, switchMode) - } else { - // In cloud deploy mode without config file, just wait for shutdown signals - if isCloudDeploy && !configFileExists { - // No config file available, just wait for shutdown - cmd.WaitForCloudDeploy() - return - } - - // Start the main proxy service - // Auto-generate management password if not provided - // This enables browser-based webui access without requiring the -password flag - autoGenPassword := false - if password == "" { - if pw, err := desktopctl.GetManagementPassword(); err == nil { - password = pw - autoGenPassword = true - log.Info("using auto-generated management password for webui access") - } else { - log.Warnf("failed to get management password: %v (webui may require manual authentication)", err) - } - } - // Use standalone mode (no keep-alive shutdown) when password was auto-generated - // Keep-alive shutdown is only needed when the tray app spawns the server as subprocess - if autoGenPassword { - cmd.StartServiceStandalone(cfg, configFilePath, password) - } else { - cmd.StartService(cfg, configFilePath, password) - } - } -} +// Package main provides the entry point for the ProxyPilot engine. +// This server acts as a proxy that provides OpenAI/Gemini/Claude compatible API interfaces +// for CLI models, allowing CLI models to be used with tools and libraries designed for standard AI APIs. +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "io/fs" + "net/url" + "os" + "path/filepath" + "strings" + "time" + + "github.com/joho/godotenv" + "github.com/router-for-me/CLIProxyAPI/v6/internal/buildinfo" + "github.com/router-for-me/CLIProxyAPI/v6/internal/cmd" + "github.com/router-for-me/CLIProxyAPI/v6/internal/config" + "github.com/router-for-me/CLIProxyAPI/v6/internal/desktopctl" + "github.com/router-for-me/CLIProxyAPI/v6/internal/logging" + "github.com/router-for-me/CLIProxyAPI/v6/internal/misc" + "github.com/router-for-me/CLIProxyAPI/v6/internal/store" + _ "github.com/router-for-me/CLIProxyAPI/v6/internal/translator" + "github.com/router-for-me/CLIProxyAPI/v6/internal/usage" + "github.com/router-for-me/CLIProxyAPI/v6/internal/util" + sdkAuth "github.com/router-for-me/CLIProxyAPI/v6/sdk/auth" + configaccess "github.com/router-for-me/CLIProxyAPI/v6/sdk/access/config" + coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth" + log "github.com/sirupsen/logrus" +) + +var ( + Version = "dev" + Commit = "none" + BuildDate = "unknown" + DefaultConfigPath = "" +) + +// init initializes the shared logger setup. +func init() { + logging.SetupBaseLogger() + buildinfo.Version = Version + buildinfo.Commit = Commit + buildinfo.BuildDate = BuildDate +} + +// setKiroIncognitoMode sets the incognito browser mode for Kiro authentication. +// Kiro defaults to incognito mode for multi-account support. +// Users can explicitly override with --incognito or --no-incognito flags. +func setKiroIncognitoMode(cfg *config.Config, useIncognito, noIncognito bool) { + if useIncognito { + cfg.IncognitoBrowser = true + } else if noIncognito { + cfg.IncognitoBrowser = false + } else { + cfg.IncognitoBrowser = true // Kiro default + } +} + +// main is the entry point of the application. +// It parses command-line flags, loads configuration, and starts the appropriate +// service based on the provided flags (login, codex-login, or server mode). +func main() { + fmt.Printf("ProxyPilot Engine Version: %s, Commit: %s, BuiltAt: %s\n", buildinfo.Version, buildinfo.Commit, buildinfo.BuildDate) + + // Command-line flags to control the application's behavior. + var login bool + var codexLogin bool + var claudeLogin bool + var qwenLogin bool + var noBrowser bool + var antigravityLogin bool + var kiroLogin bool + var kiroGoogleLogin bool + var kiroAWSLogin bool + var kiroAWSAuthCode bool + var kiroImport bool + var amazonqImport bool + var antigravityImport bool + var minimaxLogin bool + var zhipuLogin bool + // var githubCopilotLogin bool // REMOVED - GitHub Copilot excluded + var detectAgents bool + var setupClaude bool + var setupCodex bool + var setupDroid bool + var setupOpenCode bool + var setupGemini bool + var setupCursor bool + var setupKilo bool + var setupRooCode bool + var setupAll bool + var switchAgent string + var switchMode string + var projectID string + var vertexImport string + var configPath string + var password string + var noIncognito bool + var useIncognito bool + + // Account management flags + var showVersion bool + var showStatus bool + var listAccounts bool + var cleanupExpired bool + var removeAccount string + var refreshTokens string + var jsonOutput bool + var quietMode bool + var verboseMode bool + + // Usage and logs flags + var showUsage bool + var showLogs bool + var logLines int + + // Model and export flags + var listModels bool + var exportAccounts string + var importAccounts string + var includeTokens bool + var forceImport bool + + // Define command-line flags for different operation modes. + flag.BoolVar(&login, "login", false, "Login Google Account") + flag.BoolVar(&codexLogin, "codex-login", false, "Login to Codex using OAuth") + flag.BoolVar(&claudeLogin, "claude-login", false, "Login to Claude using OAuth") + flag.BoolVar(&qwenLogin, "qwen-login", false, "Login to Qwen using OAuth") + flag.BoolVar(&noBrowser, "no-browser", false, "Don't open browser automatically for OAuth") + flag.BoolVar(&useIncognito, "incognito", false, "Open browser in incognito/private mode for OAuth (useful for multiple accounts)") + flag.BoolVar(&noIncognito, "no-incognito", false, "Force disable incognito mode (uses existing browser session)") + flag.BoolVar(&antigravityLogin, "antigravity-login", false, "Login to Antigravity using OAuth") + flag.BoolVar(&kiroLogin, "kiro-login", false, "Login to Kiro using Google OAuth") + flag.BoolVar(&kiroGoogleLogin, "kiro-google-login", false, "Login to Kiro using Google OAuth (same as --kiro-login)") + flag.BoolVar(&kiroAWSLogin, "kiro-aws-login", false, "Login to Kiro using AWS Builder ID (device code flow)") + flag.BoolVar(&kiroAWSAuthCode, "kiro-aws-authcode", false, "Login to Kiro using AWS Builder ID (authorization code flow, better UX)") + flag.BoolVar(&kiroImport, "kiro-import", false, "Import Kiro token from Kiro IDE (~/.aws/sso/cache/kiro-auth-token.json)") + flag.BoolVar(&amazonqImport, "amazonq-import", false, "Import Amazon Q CLI token from SQLite database") + flag.BoolVar(&antigravityImport, "antigravity-import", false, "Import Antigravity token from Antigravity IDE") + flag.BoolVar(&minimaxLogin, "minimax-login", false, "Add MiniMax API key") + flag.BoolVar(&zhipuLogin, "zhipu-login", false, "Add Zhipu AI API key") + // GitHub Copilot login removed + flag.BoolVar(&detectAgents, "detect-agents", false, "Detect installed CLI agents") + flag.BoolVar(&setupClaude, "setup-claude", false, "Configure Claude Code to use ProxyPilot") + flag.BoolVar(&setupCodex, "setup-codex", false, "Configure Codex CLI to use ProxyPilot") + flag.BoolVar(&setupDroid, "setup-droid", false, "Configure Factory Droid to use ProxyPilot") + flag.BoolVar(&setupOpenCode, "setup-opencode", false, "Configure OpenCode to use ProxyPilot") + flag.BoolVar(&setupGemini, "setup-gemini", false, "Configure Gemini CLI to use ProxyPilot") + flag.BoolVar(&setupCursor, "setup-cursor", false, "Configure Cursor to use ProxyPilot") + flag.BoolVar(&setupKilo, "setup-kilo", false, "Configure Kilo Code CLI to use ProxyPilot") + flag.BoolVar(&setupRooCode, "setup-roocode", false, "Configure RooCode (VS Code) to use ProxyPilot") + flag.BoolVar(&setupAll, "setup-all", false, "Configure all detected CLI agents (with backup)") + flag.StringVar(&switchAgent, "switch", "", "Switch agent config mode (e.g., --switch claude)") + flag.StringVar(&switchMode, "mode", "", "Switch mode: proxy, native, or status (default: status)") + flag.StringVar(&projectID, "project_id", "", "Project ID (Gemini only, not required)") + flag.StringVar(&configPath, "config", DefaultConfigPath, "Configure File Path") + flag.StringVar(&vertexImport, "vertex-import", "", "Import Vertex service account key JSON file") + flag.StringVar(&password, "password", "", "") + + flag.BoolVar(&showVersion, "version", false, "Show ProxyPilot version and exit") + flag.BoolVar(&showStatus, "status", false, "Show ProxyPilot status and exit") + flag.BoolVar(&listAccounts, "list-accounts", false, "List all configured accounts and exit") + flag.BoolVar(&cleanupExpired, "cleanup-expired", false, "Remove expired tokens and exit") + flag.StringVar(&removeAccount, "remove-account", "", "Remove a specific account by name and exit") + flag.StringVar(&refreshTokens, "refresh", "", "Force token refresh (all, or email/id to refresh specific)") + flag.BoolVar(&jsonOutput, "json", false, "Output in JSON format (overrides --quiet)") + flag.BoolVar(&quietMode, "quiet", false, "Run in quiet mode (overrides --verbose)") + flag.BoolVar(&verboseMode, "verbose", false, "Run in verbose mode") + + flag.BoolVar(&listModels, "list-models", false, "List available models per provider and exit") + flag.StringVar(&exportAccounts, "export-accounts", "", "Export accounts to JSON file (use - for stdout)") + flag.StringVar(&importAccounts, "import-accounts", "", "Import accounts from JSON file") + flag.BoolVar(&includeTokens, "include-tokens", false, "Include sensitive tokens in export (use with -export-accounts)") + flag.BoolVar(&forceImport, "force", false, "Force overwrite existing accounts on import") + flag.BoolVar(&showUsage, "usage", false, "Show token usage statistics and exit") + flag.BoolVar(&showLogs, "logs", false, "View recent proxy logs and exit") + flag.IntVar(&logLines, "n", 50, "Number of log lines to show (used with -logs)") + + flag.CommandLine.Usage = func() { + out := flag.CommandLine.Output() + _, _ = fmt.Fprintf(out, "Usage of %s\n", os.Args[0]) + flag.CommandLine.VisitAll(func(f *flag.Flag) { + if f.Name == "password" { + return + } + s := fmt.Sprintf(" -%s", f.Name) + name, unquoteUsage := flag.UnquoteUsage(f) + if name != "" { + s += " " + name + } + if len(s) <= 4 { + s += " " + } else { + s += "\n " + } + if unquoteUsage != "" { + s += unquoteUsage + } + if f.DefValue != "" && f.DefValue != "false" && f.DefValue != "0" { + s += fmt.Sprintf(" (default %s)", f.DefValue) + } + _, _ = fmt.Fprint(out, s+"\n") + }) + } + + // Check for subcommand-style switch command before flag.Parse() + // Supports: proxypilot switch [agent] [mode] + // agent can be: claude, gemini, codex, opencode, droid, cursor + // mode can be: proxy, native, status (default if omitted) + var subcommandSwitch bool + args := os.Args[1:] + if len(args) > 0 && args[0] == "switch" { + subcommandSwitch = true + switchArgs := args[1:] + // Filter out any flags like --status from positional args + var positionalArgs []string + for _, arg := range switchArgs { + if arg == "--status" { + switchMode = "status" + } else if !strings.HasPrefix(arg, "-") { + positionalArgs = append(positionalArgs, arg) + } + } + // Parse positional arguments: [agent] [mode] + if len(positionalArgs) >= 1 { + switchAgent = positionalArgs[0] + } + if len(positionalArgs) >= 2 { + switchMode = positionalArgs[1] + } + // Default mode to "status" if not specified + if switchMode == "" { + switchMode = "status" + } + } + + // Pre-process -refresh flag: if -refresh is present without a value, treat as -refresh=all + for i, arg := range os.Args[1:] { + if arg == "-refresh" || arg == "--refresh" { + // Check if next arg exists and is not another flag + nextIdx := i + 2 // +1 for 1-based slice, +1 for next + if nextIdx >= len(os.Args) || strings.HasPrefix(os.Args[nextIdx], "-") { + os.Args[i+1] = "-refresh=all" + } + break + } + } + + // Parse the command-line flags. + flag.Parse() + + // Core application variables. + var err error + var cfg *config.Config + var isCloudDeploy bool + var ( + usePostgresStore bool + pgStoreDSN string + pgStoreSchema string + pgStoreLocalPath string + pgStoreInst *store.PostgresStore + useGitStore bool + gitStoreRemoteURL string + gitStoreUser string + gitStorePassword string + gitStoreLocalPath string + gitStoreInst *store.GitTokenStore + gitStoreRoot string + useObjectStore bool + objectStoreEndpoint string + objectStoreAccess string + objectStoreSecret string + objectStoreBucket string + objectStoreLocalPath string + objectStoreInst *store.ObjectTokenStore + ) + + wd, err := os.Getwd() + if err != nil { + log.Errorf("failed to get working directory: %v", err) + return + } + + // Load environment variables from .env if present. + if errLoad := godotenv.Load(filepath.Join(wd, ".env")); errLoad != nil { + if !errors.Is(errLoad, os.ErrNotExist) { + log.WithError(errLoad).Warn("failed to load .env file") + } + } + + lookupEnv := func(keys ...string) (string, bool) { + for _, key := range keys { + if value, ok := os.LookupEnv(key); ok { + if trimmed := strings.TrimSpace(value); trimmed != "" { + return trimmed, true + } + } + } + return "", false + } + writableBase := util.WritablePath() + if value, ok := lookupEnv("PGSTORE_DSN", "pgstore_dsn"); ok { + usePostgresStore = true + pgStoreDSN = value + } + if usePostgresStore { + if value, ok := lookupEnv("PGSTORE_SCHEMA", "pgstore_schema"); ok { + pgStoreSchema = value + } + if value, ok := lookupEnv("PGSTORE_LOCAL_PATH", "pgstore_local_path"); ok { + pgStoreLocalPath = value + } + if pgStoreLocalPath == "" { + if writableBase != "" { + pgStoreLocalPath = writableBase + } else { + pgStoreLocalPath = wd + } + } + useGitStore = false + } + if value, ok := lookupEnv("GITSTORE_GIT_URL", "gitstore_git_url"); ok { + useGitStore = true + gitStoreRemoteURL = value + } + if value, ok := lookupEnv("GITSTORE_GIT_USERNAME", "gitstore_git_username"); ok { + gitStoreUser = value + } + if value, ok := lookupEnv("GITSTORE_GIT_TOKEN", "gitstore_git_token"); ok { + gitStorePassword = value + } + if value, ok := lookupEnv("GITSTORE_LOCAL_PATH", "gitstore_local_path"); ok { + gitStoreLocalPath = value + } + if value, ok := lookupEnv("OBJECTSTORE_ENDPOINT", "objectstore_endpoint"); ok { + useObjectStore = true + objectStoreEndpoint = value + } + if value, ok := lookupEnv("OBJECTSTORE_ACCESS_KEY", "objectstore_access_key"); ok { + objectStoreAccess = value + } + if value, ok := lookupEnv("OBJECTSTORE_SECRET_KEY", "objectstore_secret_key"); ok { + objectStoreSecret = value + } + if value, ok := lookupEnv("OBJECTSTORE_BUCKET", "objectstore_bucket"); ok { + objectStoreBucket = value + } + if value, ok := lookupEnv("OBJECTSTORE_LOCAL_PATH", "objectstore_local_path"); ok { + objectStoreLocalPath = value + } + + // Check for cloud deploy mode only on first execution + // Read env var name in uppercase: DEPLOY + deployEnv := os.Getenv("DEPLOY") + if deployEnv == "cloud" { + isCloudDeploy = true + } + + // Determine and load the configuration file. + // Prefer the Postgres store when configured, otherwise fallback to git or local files. + var configFilePath string + if usePostgresStore { + if pgStoreLocalPath == "" { + pgStoreLocalPath = wd + } + pgStoreLocalPath = filepath.Join(pgStoreLocalPath, "pgstore") + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + pgStoreInst, err = store.NewPostgresStore(ctx, store.PostgresStoreConfig{ + DSN: pgStoreDSN, + Schema: pgStoreSchema, + SpoolDir: pgStoreLocalPath, + }) + cancel() + if err != nil { + log.Errorf("failed to initialize postgres token store: %v", err) + return + } + examplePath := filepath.Join(wd, "config.example.yaml") + ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second) + if errBootstrap := pgStoreInst.Bootstrap(ctx, examplePath); errBootstrap != nil { + cancel() + log.Errorf("failed to bootstrap postgres-backed config: %v", errBootstrap) + return + } + cancel() + configFilePath = pgStoreInst.ConfigPath() + cfg, err = config.LoadConfigOptional(configFilePath, isCloudDeploy) + if err == nil { + cfg.AuthDir = pgStoreInst.AuthDir() + log.Infof("postgres-backed token store enabled, workspace path: %s", pgStoreInst.WorkDir()) + } + } else if useObjectStore { + if objectStoreLocalPath == "" { + if writableBase != "" { + objectStoreLocalPath = writableBase + } else { + objectStoreLocalPath = wd + } + } + objectStoreRoot := filepath.Join(objectStoreLocalPath, "objectstore") + resolvedEndpoint := strings.TrimSpace(objectStoreEndpoint) + useSSL := true + if strings.Contains(resolvedEndpoint, "://") { + parsed, errParse := url.Parse(resolvedEndpoint) + if errParse != nil { + log.Errorf("failed to parse object store endpoint %q: %v", objectStoreEndpoint, errParse) + return + } + switch strings.ToLower(parsed.Scheme) { + case "http": + useSSL = false + case "https": + useSSL = true + default: + log.Errorf("unsupported object store scheme %q (only http and https are allowed)", parsed.Scheme) + return + } + if parsed.Host == "" { + log.Errorf("object store endpoint %q is missing host information", objectStoreEndpoint) + return + } + resolvedEndpoint = parsed.Host + if parsed.Path != "" && parsed.Path != "/" { + resolvedEndpoint = strings.TrimSuffix(parsed.Host+parsed.Path, "/") + } + } + resolvedEndpoint = strings.TrimRight(resolvedEndpoint, "/") + objCfg := store.ObjectStoreConfig{ + Endpoint: resolvedEndpoint, + Bucket: objectStoreBucket, + AccessKey: objectStoreAccess, + SecretKey: objectStoreSecret, + LocalRoot: objectStoreRoot, + UseSSL: useSSL, + PathStyle: true, + } + objectStoreInst, err = store.NewObjectTokenStore(objCfg) + if err != nil { + log.Errorf("failed to initialize object token store: %v", err) + return + } + examplePath := filepath.Join(wd, "config.example.yaml") + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + if errBootstrap := objectStoreInst.Bootstrap(ctx, examplePath); errBootstrap != nil { + cancel() + log.Errorf("failed to bootstrap object-backed config: %v", errBootstrap) + return + } + cancel() + configFilePath = objectStoreInst.ConfigPath() + cfg, err = config.LoadConfigOptional(configFilePath, isCloudDeploy) + if err == nil { + if cfg == nil { + cfg = &config.Config{} + } + cfg.AuthDir = objectStoreInst.AuthDir() + log.Infof("object-backed token store enabled, bucket: %s", objectStoreBucket) + } + } else if useGitStore { + if gitStoreLocalPath == "" { + if writableBase != "" { + gitStoreLocalPath = writableBase + } else { + gitStoreLocalPath = wd + } + } + gitStoreRoot = filepath.Join(gitStoreLocalPath, "gitstore") + authDir := filepath.Join(gitStoreRoot, "auths") + gitStoreInst = store.NewGitTokenStore(gitStoreRemoteURL, gitStoreUser, gitStorePassword) + gitStoreInst.SetBaseDir(authDir) + if errRepo := gitStoreInst.EnsureRepository(); errRepo != nil { + log.Errorf("failed to prepare git token store: %v", errRepo) + return + } + configFilePath = gitStoreInst.ConfigPath() + if configFilePath == "" { + configFilePath = filepath.Join(gitStoreRoot, "config", "config.yaml") + } + if _, statErr := os.Stat(configFilePath); errors.Is(statErr, fs.ErrNotExist) { + examplePath := filepath.Join(wd, "config.example.yaml") + if _, errExample := os.Stat(examplePath); errExample != nil { + log.Errorf("failed to find template config file: %v", errExample) + return + } + if errCopy := misc.CopyConfigTemplate(examplePath, configFilePath); errCopy != nil { + log.Errorf("failed to bootstrap git-backed config: %v", errCopy) + return + } + if errCommit := gitStoreInst.PersistConfig(context.Background()); errCommit != nil { + log.Errorf("failed to commit initial git-backed config: %v", errCommit) + return + } + log.Infof("git-backed config initialized from template: %s", configFilePath) + } else if statErr != nil { + log.Errorf("failed to inspect git-backed config: %v", statErr) + return + } + cfg, err = config.LoadConfigOptional(configFilePath, isCloudDeploy) + if err == nil { + cfg.AuthDir = gitStoreInst.AuthDir() + log.Infof("git-backed token store enabled, repository path: %s", gitStoreRoot) + } + } else if configPath != "" { + configFilePath = configPath + cfg, err = config.LoadConfigOptional(configPath, isCloudDeploy) + } else { + wd, err = os.Getwd() + if err != nil { + log.Errorf("failed to get working directory: %v", err) + return + } + configFilePath = filepath.Join(wd, "config.yaml") + cfg, err = config.LoadConfigOptional(configFilePath, isCloudDeploy) + } + if err != nil { + // For switch command, config is optional - use defaults + if subcommandSwitch || switchAgent != "" { + cfg = &config.Config{Port: 8317} + } else { + log.Errorf("failed to load config: %v", err) + return + } + } + if cfg == nil { + cfg = &config.Config{} + } + + // In cloud deploy mode, check if we have a valid configuration + var configFileExists bool + if isCloudDeploy { + if info, errStat := os.Stat(configFilePath); errStat != nil { + // Don't mislead: API server will not start until configuration is provided. + log.Info("Cloud deploy mode: No configuration file detected; standing by for configuration") + configFileExists = false + } else if info.IsDir() { + log.Info("Cloud deploy mode: Config path is a directory; standing by for configuration") + configFileExists = false + } else if cfg.Port == 0 { + // LoadConfigOptional returns empty config when file is empty or invalid. + // Config file exists but is empty or invalid; treat as missing config + log.Info("Cloud deploy mode: Configuration file is empty or invalid; standing by for valid configuration") + configFileExists = false + } else { + log.Info("Cloud deploy mode: Configuration file detected; starting service") + configFileExists = true + } + } + + // Perform basic semantic validation of the loaded configuration. + if warnings, errValidate := config.ValidateConfig(cfg); errValidate != nil { + log.Errorf("invalid configuration: %v", errValidate) + return + } else if len(warnings) > 0 { + for _, w := range warnings { + log.Warnf("config warning: %s", w) + } + } + + usage.SetStatisticsEnabled(cfg.UsageStatisticsEnabled) + coreauth.SetQuotaCooldownDisabled(cfg.DisableCooling) + // AntigravityPrimaryEmail removed - field does not exist + + if err = logging.ConfigureLogOutput(cfg.LoggingToFile, cfg.LogsMaxTotalSizeMB); err != nil { + log.Errorf("failed to configure log output: %v", err) + return + } + + log.Infof("ProxyPilot Engine Version: %s, Commit: %s, BuiltAt: %s", buildinfo.Version, buildinfo.Commit, buildinfo.BuildDate) + + // Set the log level based on the configuration. + util.SetLogLevel(cfg) + + // CLI flags override config-based log level + if quietMode { + logging.SetLogLevel("quiet") + } else if verboseMode { + logging.SetLogLevel("verbose") + } + + if resolvedAuthDir, errResolveAuthDir := util.ResolveAuthDir(cfg.AuthDir); errResolveAuthDir != nil { + log.Errorf("failed to resolve auth directory: %v", errResolveAuthDir) + return + } else { + cfg.AuthDir = resolvedAuthDir + } + + // Create login options to be used in authentication flows. + options := &cmd.LoginOptions{ + NoBrowser: noBrowser, + } + + // Register the shared token store once so all components use the same persistence backend. + if usePostgresStore { + sdkAuth.RegisterTokenStore(pgStoreInst) + } else if useObjectStore { + sdkAuth.RegisterTokenStore(objectStoreInst) + } else if useGitStore { + sdkAuth.RegisterTokenStore(gitStoreInst) + } else { + sdkAuth.RegisterTokenStore(sdkAuth.NewFileTokenStore()) + } + + // Register built-in access providers before constructing services. + configaccess.Register() + + // Handle different command modes based on the provided flags. + + if vertexImport != "" { + // Handle Vertex service account import + cmd.DoVertexImport(cfg, vertexImport) + } else if showVersion { + // Version already printed at startup, just exit + return + } else if showStatus { + if err := cmd.ShowStatus(jsonOutput); err != nil { + log.Errorf("status failed: %v", err) + os.Exit(1) + } + return + } else if listAccounts { + if err := cmd.ListAccounts(jsonOutput); err != nil { + log.Errorf("list-accounts failed: %v", err) + os.Exit(1) + } + return + } else if listModels { + if err := cmd.ListModels(jsonOutput); err != nil { + log.Errorf("list-models failed: %v", err) + os.Exit(1) + } + return + } else if exportAccounts != "" { + if err := cmd.ExportAccounts(exportAccounts, includeTokens, jsonOutput); err != nil { + log.Errorf("export-accounts failed: %v", err) + os.Exit(1) + } + return + } else if importAccounts != "" { + if err := cmd.ImportAccounts(importAccounts, forceImport, jsonOutput); err != nil { + log.Errorf("import-accounts failed: %v", err) + os.Exit(1) + } + return + } else if cleanupExpired { + if err := cmd.CleanupExpired(false); err != nil { + log.Errorf("cleanup-expired failed: %v", err) + os.Exit(1) + } + return + } else if removeAccount != "" { + if err := cmd.RemoveAccount(removeAccount); err != nil { + log.Errorf("remove-account failed: %v", err) + os.Exit(1) + } + return + } else if refreshTokens != "" { + identifier := "" + if refreshTokens != "all" { + identifier = refreshTokens + } + if err := cmd.RefreshTokens(cfg, identifier, jsonOutput); err != nil { + log.Errorf("refresh failed: %v", err) + os.Exit(1) + } + return + } else if showUsage { + if err := cmd.ShowUsage(jsonOutput); err != nil { + log.Errorf("usage failed: %v", err) + os.Exit(1) + } + return + } else if showLogs { + if err := cmd.ShowLogs(logLines, jsonOutput); err != nil { + log.Errorf("logs failed: %v", err) + os.Exit(1) + } + return + } else if login { + // Handle Google/Gemini login + cmd.DoLogin(cfg, projectID, options) + } else if antigravityLogin { + // Handle Antigravity login + cmd.DoAntigravityLogin(cfg, options) + } else if false { // GitHub Copilot removed + // Handle GitHub Copilot login + // GitHub Copilot login removed + } else if codexLogin { + // Handle Codex login + cmd.DoCodexLogin(cfg, options) + } else if claudeLogin { + // Handle Claude login + cmd.DoClaudeLogin(cfg, options) + } else if qwenLogin { + cmd.DoQwenLogin(cfg, options) + } else if kiroLogin { + // For Kiro auth, default to incognito mode for multi-account support + // Users can explicitly override with --no-incognito + // Note: This config mutation is safe - auth commands exit after completion + // and don't share config with StartService (which is in the else branch) + setKiroIncognitoMode(cfg, useIncognito, noIncognito) + cmd.DoKiroLogin(cfg, options) + } else if kiroGoogleLogin { + // For Kiro auth, default to incognito mode for multi-account support + // Users can explicitly override with --no-incognito + // Note: This config mutation is safe - auth commands exit after completion + setKiroIncognitoMode(cfg, useIncognito, noIncognito) + cmd.DoKiroGoogleLogin(cfg, options) + } else if kiroAWSLogin { + // For Kiro auth, default to incognito mode for multi-account support + // Users can explicitly override with --no-incognito + setKiroIncognitoMode(cfg, useIncognito, noIncognito) + cmd.DoKiroAWSLogin(cfg, options) + } else if kiroAWSAuthCode { + // For Kiro auth with authorization code flow (better UX) + setKiroIncognitoMode(cfg, useIncognito, noIncognito) + cmd.DoKiroAWSAuthCodeLogin(cfg, options) + } else if kiroImport { + cmd.DoKiroImport(cfg, options) + } else if amazonqImport { + cmd.DoAmazonQImport(cfg, options) + } else if antigravityImport { + cmd.DoAntigravityImport(cfg) + } else if minimaxLogin { + cmd.DoMiniMaxLogin(cfg, options) + } else if zhipuLogin { + cmd.DoZhipuLogin(cfg, options) + } else if detectAgents { + cmd.DoDetectAgents() + } else if setupClaude { + cmd.DoSetupClaude(cfg) + } else if setupCodex { + cmd.DoSetupCodex(cfg) + } else if setupDroid { + cmd.DoSetupDroid(cfg) + } else if setupOpenCode { + cmd.DoSetupOpenCode(cfg) + } else if setupGemini { + cmd.DoSetupGeminiCLI(cfg) + } else if setupCursor { + cmd.DoSetupCursor(cfg) + } else if setupKilo { + cmd.DoSetupKiloCode(cfg) + } else if setupRooCode { + cmd.DoSetupRooCode(cfg) + } else if setupAll { + cmd.DoSetupAll(cfg) + } else if subcommandSwitch || switchAgent != "" || switchMode != "" { + // Handle switch command: + // - Subcommand style: proxypilot switch claude proxy + // - Flag style: proxypilot --switch claude --mode proxy + cmd.DoSwitch(cfg, switchAgent, switchMode) + } else { + // In cloud deploy mode without config file, just wait for shutdown signals + if isCloudDeploy && !configFileExists { + // No config file available, just wait for shutdown + cmd.WaitForCloudDeploy() + return + } + + // Start the main proxy service + // Auto-generate management password if not provided + // This enables browser-based webui access without requiring the -password flag + autoGenPassword := false + if password == "" { + if pw, err := desktopctl.GetManagementPassword(); err == nil { + password = pw + autoGenPassword = true + log.Info("using auto-generated management password for webui access") + } else { + log.Warnf("failed to get management password: %v (webui may require manual authentication)", err) + } + } + // Use standalone mode (no keep-alive shutdown) when password was auto-generated + // Keep-alive shutdown is only needed when the tray app spawns the server as subprocess + if autoGenPassword { + cmd.StartServiceStandalone(cfg, configFilePath, password) + } else { + cmd.StartService(cfg, configFilePath, password) + } + } +} diff --git a/internal/cmd/export_import.go b/internal/cmd/export_import.go new file mode 100644 index 00000000..c38cf053 --- /dev/null +++ b/internal/cmd/export_import.go @@ -0,0 +1,237 @@ +// Package cmd provides CLI command implementations for ProxyPilot. +package cmd + +import ( + "context" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "time" + + "github.com/router-for-me/CLIProxyAPI/v6/internal/util" + sdkAuth "github.com/router-for-me/CLIProxyAPI/v6/sdk/auth" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth" +) + +// ExportBundle represents exported accounts +type ExportBundle struct { + Version string `json:"version"` + ExportedAt string `json:"exported_at"` + Accounts []ExportedAccount `json:"accounts"` +} + +// ExportedAccount represents a single exported account +type ExportedAccount struct { + ID string `json:"id"` + Provider string `json:"provider"` + Label string `json:"label,omitempty"` + Attributes map[string]string `json:"attributes,omitempty"` + Metadata map[string]any `json:"metadata,omitempty"` + CreatedAt time.Time `json:"created_at,omitempty"` +} + +var sensitiveKeys = []string{ + "access_token", "refresh_token", "token", "api_key", "secret", + "password", "credential", "session", "cookie", "id_token", "bearer", +} + +// ExportAccounts exports all accounts to JSON +func ExportAccounts(outputPath string, includeTokens bool, jsonOutput bool) error { + store := sdkAuth.NewFileTokenStore() + store.SetBaseDir(util.DefaultAuthDir()) + + auths, err := store.List(context.Background()) + if err != nil { + return fmt.Errorf("failed to list accounts: %w", err) + } + + bundle := ExportBundle{ + Version: "1.0", + ExportedAt: time.Now().Format(time.RFC3339), + Accounts: make([]ExportedAccount, 0, len(auths)), + } + + for _, auth := range auths { + exported := ExportedAccount{ + ID: auth.ID, + Provider: auth.Provider, + Label: auth.Label, + Attributes: auth.Attributes, + CreatedAt: auth.CreatedAt, + } + + if auth.Metadata != nil { + exported.Metadata = make(map[string]any, len(auth.Metadata)) + for k, v := range auth.Metadata { + if !includeTokens && isSensitiveKey(k) { + exported.Metadata[k] = "[REDACTED]" + } else { + exported.Metadata[k] = v + } + } + } + bundle.Accounts = append(bundle.Accounts, exported) + } + + // Determine output target + var out io.Writer = os.Stdout + if outputPath != "" && outputPath != "-" { + f, err := os.Create(outputPath) + if err != nil { + return fmt.Errorf("failed to create output file: %w", err) + } + defer f.Close() + out = f + } + + enc := json.NewEncoder(out) + enc.SetIndent("", " ") + if err := enc.Encode(bundle); err != nil { + return fmt.Errorf("failed to encode accounts: %w", err) + } + + if !jsonOutput && outputPath != "" && outputPath != "-" { + fmt.Fprintf(os.Stderr, "%sExported %d accounts to %s%s\n", + colorGreen, len(bundle.Accounts), outputPath, colorReset) + if !includeTokens { + fmt.Fprintf(os.Stderr, "%sNote: Sensitive tokens redacted. Use --include-tokens to include.%s\n", + colorYellow, colorReset) + } + } + + return nil +} + +// ImportAccounts imports accounts from a JSON bundle +func ImportAccounts(inputPath string, force bool, jsonOutput bool) error { + data, err := os.ReadFile(inputPath) + if err != nil { + return fmt.Errorf("failed to read import file: %w", err) + } + + var bundle ExportBundle + if err := json.Unmarshal(data, &bundle); err != nil { + return fmt.Errorf("failed to parse import file: %w", err) + } + + store := sdkAuth.NewFileTokenStore() + store.SetBaseDir(util.DefaultAuthDir()) + + ctx := context.Background() + existing, err := store.List(ctx) + if err != nil { + return fmt.Errorf("failed to list existing accounts: %w", err) + } + + existingIDs := make(map[string]bool) + for _, auth := range existing { + existingIDs[auth.ID] = true + } + + var imported, skipped, skippedRedacted int + var results []map[string]any + + for _, acc := range bundle.Accounts { + // Skip if has redacted tokens + hasRedacted := false + if acc.Metadata != nil { + for k, v := range acc.Metadata { + if s, ok := v.(string); ok && s == "[REDACTED]" && isSensitiveKey(k) { + hasRedacted = true + break + } + } + } + if hasRedacted { + skippedRedacted++ + if jsonOutput { + results = append(results, map[string]any{ + "id": acc.ID, "status": "skipped", "reason": "redacted tokens", + }) + } + continue + } + + // Check if exists + if existingIDs[acc.ID] && !force { + skipped++ + if jsonOutput { + results = append(results, map[string]any{ + "id": acc.ID, "status": "skipped", "reason": "already exists", + }) + } else { + fmt.Fprintf(os.Stderr, "%sSkipping %s (exists). Use --force to overwrite.%s\n", + colorYellow, acc.ID, colorReset) + } + continue + } + + // Convert to Auth + auth := &cliproxyauth.Auth{ + ID: acc.ID, + Provider: acc.Provider, + Label: acc.Label, + Attributes: acc.Attributes, + Metadata: acc.Metadata, + CreatedAt: acc.CreatedAt, + UpdatedAt: time.Now(), + } + + // Set FileName based on authdir + auth.FileName = filepath.Join(util.DefaultAuthDir(), acc.ID+".json") + + if _, err := store.Save(ctx, auth); err != nil { + if jsonOutput { + results = append(results, map[string]any{ + "id": acc.ID, "status": "error", "error": err.Error(), + }) + } else { + fmt.Fprintf(os.Stderr, "%sFailed to import %s: %v%s\n", + colorRed, acc.ID, err, colorReset) + } + continue + } + + imported++ + if jsonOutput { + results = append(results, map[string]any{ + "id": acc.ID, "status": "imported", + }) + } + } + + if jsonOutput { + return outputJSON(map[string]any{ + "imported": imported, + "skipped": skipped, + "skipped_redacted": skippedRedacted, + "results": results, + }) + } + + fmt.Printf("\n%s%sImport Summary%s\n", colorBold, colorCyan, colorReset) + fmt.Printf("%s─────────────────────────%s\n", colorDim, colorReset) + fmt.Printf(" Imported: %s%d%s\n", colorGreen, imported, colorReset) + if skipped > 0 { + fmt.Printf(" Skipped (existing): %s%d%s\n", colorYellow, skipped, colorReset) + } + if skippedRedacted > 0 { + fmt.Printf(" Skipped (redacted): %s%d%s\n", colorYellow, skippedRedacted, colorReset) + } + fmt.Println() + + return nil +} + +func isSensitiveKey(key string) bool { + keyLower := strings.ToLower(key) + for _, s := range sensitiveKeys { + if strings.Contains(keyLower, s) { + return true + } + } + return false +} diff --git a/internal/cmd/list_models.go b/internal/cmd/list_models.go new file mode 100644 index 00000000..e807a8a9 --- /dev/null +++ b/internal/cmd/list_models.go @@ -0,0 +1,107 @@ +// Package cmd provides CLI command implementations for ProxyPilot. +package cmd + +import ( + "encoding/json" + "fmt" + "os" + "sort" + + "github.com/router-for-me/CLIProxyAPI/v6/internal/registry" +) + +// ModelGroup represents a provider and its models +type ModelGroup struct { + Provider string `json:"provider"` + Models []ModelEntry `json:"models"` +} + +// ModelEntry represents a single model entry for output +type ModelEntry struct { + ID string `json:"id"` + DisplayName string `json:"display_name,omitempty"` + Description string `json:"description,omitempty"` + Thinking bool `json:"thinking,omitempty"` +} + +// ListModels lists all available models grouped by provider +func ListModels(jsonOutput bool) error { + groups := collectModelGroups() + if jsonOutput { + return outputModelsAsJSON(groups) + } + return outputModelsTable(groups) +} + +func collectModelGroups() []ModelGroup { + providers := []struct { + name string + models []*registry.ModelInfo + }{ + {"Claude", registry.GetClaudeModels()}, + {"Gemini", registry.GetGeminiModels()}, + {"AI Studio", registry.GetAIStudioModels()}, + {"OpenAI (Codex)", registry.GetOpenAIModels()}, + {"Qwen", registry.GetQwenModels()}, + {"MiniMax", registry.GetMiniMaxModels()}, + {"Zhipu", registry.GetZhipuModels()}, + {"Kiro", registry.GetKiroModels()}, + {"Amazon Q", registry.GetAmazonQModels()}, + {"GitHub Copilot", registry.GetGitHubCopilotModels()}, + } + + var groups []ModelGroup + for _, p := range providers { + if len(p.models) == 0 { + continue + } + entries := make([]ModelEntry, 0, len(p.models)) + for _, m := range p.models { + entry := ModelEntry{ + ID: m.ID, + DisplayName: m.DisplayName, + Description: m.Description, + Thinking: m.Thinking != nil, + } + entries = append(entries, entry) + } + sort.Slice(entries, func(i, j int) bool { + return entries[i].ID < entries[j].ID + }) + groups = append(groups, ModelGroup{Provider: p.name, Models: entries}) + } + return groups +} + +func outputModelsTable(groups []ModelGroup) error { + if len(groups) == 0 { + fmt.Printf("%sNo models available%s\n", colorYellow, colorReset) + return nil + } + + for _, g := range groups { + fmt.Printf("\n%s%s%s %s(%d models)%s\n", + colorBold, g.Provider, colorReset, colorDim, len(g.Models), colorReset) + fmt.Printf("%s─────────────────────────────────────────%s\n", colorDim, colorReset) + + for _, m := range g.Models { + thinkTag := "" + if m.Thinking { + thinkTag = fmt.Sprintf(" %s[thinking]%s", colorCyan, colorReset) + } + name := m.ID + if m.DisplayName != "" && m.DisplayName != m.ID { + name = fmt.Sprintf("%s %s(%s)%s", m.ID, colorDim, m.DisplayName, colorReset) + } + fmt.Printf(" %s%s%s\n", colorGreen, name, thinkTag) + } + } + fmt.Println() + return nil +} + +func outputModelsAsJSON(groups []ModelGroup) error { + enc := json.NewEncoder(os.Stdout) + enc.SetIndent("", " ") + return enc.Encode(groups) +} diff --git a/internal/cmd/logs.go b/internal/cmd/logs.go new file mode 100644 index 00000000..4f9182be --- /dev/null +++ b/internal/cmd/logs.go @@ -0,0 +1,113 @@ +// Package cmd provides CLI command implementations for ProxyPilot. +package cmd + +import ( + "encoding/json" + "fmt" + "os" + "strings" + + "github.com/router-for-me/CLIProxyAPI/v6/internal/logging" +) + +// DefaultLogLines is the default number of log lines to show +const DefaultLogLines = 50 + +// LogEntryOutput represents a log entry for JSON output +type LogEntryOutput struct { + Timestamp string `json:"timestamp"` + Level string `json:"level"` + Message string `json:"message"` + Source string `json:"source,omitempty"` + Fields map[string]interface{} `json:"fields,omitempty"` +} + +// LogsOutput represents the JSON output structure for logs +type LogsOutput struct { + Count int `json:"count"` + Entries []LogEntryOutput `json:"entries"` +} + +// ShowLogs displays recent proxy log entries +func ShowLogs(n int, jsonOutput bool) error { + if n <= 0 { + n = DefaultLogLines + } + + entries := logging.GetRecentGlobalEntries(n) + + if jsonOutput { + return outputLogsJSON(entries) + } + + return outputLogsTable(entries) +} + +func outputLogsJSON(entries []logging.LogEntry) error { + output := LogsOutput{ + Count: len(entries), + Entries: make([]LogEntryOutput, len(entries)), + } + + for i, entry := range entries { + output.Entries[i] = LogEntryOutput{ + Timestamp: entry.Timestamp.Format("2006-01-02T15:04:05.000Z07:00"), + Level: entry.Level, + Message: entry.Message, + Source: entry.Source, + Fields: entry.Fields, + } + } + + enc := json.NewEncoder(os.Stdout) + enc.SetIndent("", " ") + return enc.Encode(output) +} + +func outputLogsTable(entries []logging.LogEntry) error { + if len(entries) == 0 { + fmt.Printf("%sNo log entries available%s\n", colorYellow, colorReset) + fmt.Printf("%sLogs are captured during proxy operation.%s\n", colorDim, colorReset) + return nil + } + + fmt.Printf("\n%s%sProxyPilot Logs%s (%d entries)\n", colorBold, colorCyan, colorReset, len(entries)) + fmt.Printf("%s───────────────────────────────────────────────────────────────────────────────%s\n\n", colorDim, colorReset) + + for _, entry := range entries { + timestamp := entry.Timestamp.Format("15:04:05") + level := formatLogLevel(entry.Level) + message := entry.Message + + // Truncate very long messages + if len(message) > 100 { + message = message[:97] + "..." + } + + // Remove trailing newlines + message = strings.TrimRight(message, "\r\n") + + fmt.Printf("%s%s%s %s %s\n", colorDim, timestamp, colorReset, level, message) + } + + fmt.Printf("\n%s───────────────────────────────────────────────────────────────────────────────%s\n", colorDim, colorReset) + + return nil +} + +func formatLogLevel(level string) string { + switch strings.ToLower(level) { + case "debug": + return colorDim + "[DEBUG]" + colorReset + case "info": + return colorBlue + "[INFO] " + colorReset + case "warn", "warning": + return colorYellow + "[WARN] " + colorReset + case "error": + return colorRed + "[ERROR]" + colorReset + case "fatal": + return colorRed + colorBold + "[FATAL]" + colorReset + default: + return "[" + strings.ToUpper(level) + "]" + } +} diff --git a/internal/cmd/refresh.go b/internal/cmd/refresh.go new file mode 100644 index 00000000..357261d6 --- /dev/null +++ b/internal/cmd/refresh.go @@ -0,0 +1,359 @@ +// Package cmd provides CLI command implementations for ProxyPilot. +package cmd + +import ( + "context" + "fmt" + "strings" + "time" + + claudeauth "github.com/router-for-me/CLIProxyAPI/v6/internal/auth/claude" + codexauth "github.com/router-for-me/CLIProxyAPI/v6/internal/auth/codex" + kiroauth "github.com/router-for-me/CLIProxyAPI/v6/internal/auth/kiro" + qwenauth "github.com/router-for-me/CLIProxyAPI/v6/internal/auth/qwen" + "github.com/router-for-me/CLIProxyAPI/v6/internal/config" + "github.com/router-for-me/CLIProxyAPI/v6/internal/util" + sdkAuth "github.com/router-for-me/CLIProxyAPI/v6/sdk/auth" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth" +) + +// RefreshResult holds the result of a token refresh operation +type RefreshResult struct { + ID string `json:"id"` + Provider string `json:"provider"` + Email string `json:"email,omitempty"` + Success bool `json:"success"` + Error string `json:"error,omitempty"` + ExpiresAt string `json:"expires_at,omitempty"` +} + +// RefreshTokens refreshes tokens for matching accounts. +// If identifier is empty, refresh all accounts. +// If identifier is provided, match by email or ID. +func RefreshTokens(cfg *config.Config, identifier string, jsonOutput bool) error { + store := sdkAuth.NewFileTokenStore() + store.SetBaseDir(util.DefaultAuthDir()) + + auths, err := store.List(context.Background()) + if err != nil { + return fmt.Errorf("failed to list accounts: %w", err) + } + + // Filter accounts if identifier provided + var toRefresh []*cliproxyauth.Auth + identifier = strings.TrimSpace(strings.ToLower(identifier)) + + for _, auth := range auths { + if identifier == "" { + toRefresh = append(toRefresh, auth) + continue + } + + // Match by ID, email, or label + id := strings.ToLower(auth.ID) + email := strings.ToLower(auth.Attributes["email"]) + label := strings.ToLower(auth.Label) + + if id == identifier || strings.Contains(id, identifier) || + email == identifier || strings.Contains(email, identifier) || + label == identifier || strings.Contains(label, identifier) { + toRefresh = append(toRefresh, auth) + } + } + + if len(toRefresh) == 0 { + if identifier != "" { + return fmt.Errorf("no matching accounts found for: %s", identifier) + } + if jsonOutput { + return outputJSON([]RefreshResult{}) + } + fmt.Printf("%sNo accounts found to refresh%s\n", colorYellow, colorReset) + return nil + } + + results := make([]RefreshResult, 0, len(toRefresh)) + + if !jsonOutput { + fmt.Printf("\n%s%sRefreshing tokens...%s\n", colorBold, colorCyan, colorReset) + fmt.Printf("%s─────────────────────────────%s\n\n", colorDim, colorReset) + } + + for _, auth := range toRefresh { + result := refreshSingleAuth(cfg, auth, store) + results = append(results, result) + + if !jsonOutput { + printRefreshResult(result) + } + } + + if jsonOutput { + return outputJSON(results) + } + + // Print summary + succeeded := 0 + failed := 0 + for _, r := range results { + if r.Success { + succeeded++ + } else { + failed++ + } + } + + fmt.Printf("\n%s─────────────────────────────%s\n", colorDim, colorReset) + fmt.Printf("Refreshed: %s%d succeeded%s", colorGreen, succeeded, colorReset) + if failed > 0 { + fmt.Printf(", %s%d failed%s", colorRed, failed, colorReset) + } + fmt.Printf("\n\n") + + return nil +} + +func refreshSingleAuth(cfg *config.Config, auth *cliproxyauth.Auth, store *sdkAuth.FileTokenStore) RefreshResult { + result := RefreshResult{ + ID: auth.ID, + Provider: auth.Provider, + Email: auth.Attributes["email"], + } + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + var refreshErr error + var updated *cliproxyauth.Auth + + switch strings.ToLower(auth.Provider) { + case "claude": + updated, refreshErr = refreshClaude(ctx, cfg, auth) + case "codex": + updated, refreshErr = refreshCodex(ctx, cfg, auth) + case "gemini", "gemini-cli": + // Gemini tokens are refreshed automatically by the OAuth2 library + refreshErr = fmt.Errorf("gemini tokens refresh automatically; use re-login if expired") + case "kiro": + updated, refreshErr = refreshKiro(ctx, cfg, auth) + case "qwen": + updated, refreshErr = refreshQwen(ctx, cfg, auth) + case "antigravity": + // Antigravity uses short-lived tokens - needs re-import + refreshErr = fmt.Errorf("antigravity requires re-import (use --antigravity-import)") + case "vertex": + // Vertex uses service account - no refresh needed + result.Success = true + return result + case "minimax", "zhipu": + // API key based - no refresh needed + result.Success = true + return result + default: + refreshErr = fmt.Errorf("unsupported provider: %s", auth.Provider) + } + + if refreshErr != nil { + result.Error = refreshErr.Error() + return result + } + + if updated != nil { + // Save updated auth + if _, saveErr := store.Save(ctx, updated); saveErr != nil { + result.Error = fmt.Sprintf("refresh succeeded but save failed: %v", saveErr) + return result + } + + // Extract new expiry + if expiry, ok := updated.ExpirationTime(); ok { + result.ExpiresAt = expiry.Format(time.RFC3339) + } + } + + result.Success = true + return result +} + +func refreshClaude(ctx context.Context, cfg *config.Config, auth *cliproxyauth.Auth) (*cliproxyauth.Auth, error) { + if auth.Metadata == nil { + return nil, fmt.Errorf("no metadata") + } + + refreshToken, ok := auth.Metadata["refresh_token"].(string) + if !ok || refreshToken == "" { + return nil, fmt.Errorf("no refresh token") + } + + svc := claudeauth.NewClaudeAuth(cfg) + td, err := svc.RefreshTokens(ctx, refreshToken) + if err != nil { + return nil, err + } + + updated := auth.Clone() + updated.Metadata["access_token"] = td.AccessToken + if td.RefreshToken != "" { + updated.Metadata["refresh_token"] = td.RefreshToken + } + updated.Metadata["email"] = td.Email + updated.Metadata["expired"] = td.Expire + updated.Metadata["last_refresh"] = time.Now().Format(time.RFC3339) + + if expiry, ok := updated.ExpirationTime(); ok { + updated.TokenExpiresAt = expiry + } + + return updated, nil +} + +func refreshCodex(ctx context.Context, cfg *config.Config, auth *cliproxyauth.Auth) (*cliproxyauth.Auth, error) { + if auth.Metadata == nil { + return nil, fmt.Errorf("no metadata") + } + + refreshToken, ok := auth.Metadata["refresh_token"].(string) + if !ok || refreshToken == "" { + return nil, fmt.Errorf("no refresh token") + } + + svc := codexauth.NewCodexAuth(cfg) + td, err := svc.RefreshTokensWithRetry(ctx, refreshToken, 3) + if err != nil { + return nil, err + } + + updated := auth.Clone() + updated.Metadata["id_token"] = td.IDToken + updated.Metadata["access_token"] = td.AccessToken + if td.RefreshToken != "" { + updated.Metadata["refresh_token"] = td.RefreshToken + } + if td.AccountID != "" { + updated.Metadata["account_id"] = td.AccountID + } + updated.Metadata["email"] = td.Email + updated.Metadata["expired"] = td.Expire + updated.Metadata["last_refresh"] = time.Now().Format(time.RFC3339) + + if expiry, ok := updated.ExpirationTime(); ok { + updated.TokenExpiresAt = expiry + } + + return updated, nil +} + +func refreshKiro(ctx context.Context, cfg *config.Config, auth *cliproxyauth.Auth) (*cliproxyauth.Auth, error) { + if auth.Metadata == nil { + return nil, fmt.Errorf("no metadata") + } + + refreshToken, ok := auth.Metadata["refresh_token"].(string) + if !ok || refreshToken == "" { + return nil, fmt.Errorf("no refresh token") + } + + clientID, _ := auth.Metadata["client_id"].(string) + clientSecret, _ := auth.Metadata["client_secret"].(string) + authMethod, _ := auth.Metadata["auth_method"].(string) + startURL, _ := auth.Metadata["start_url"].(string) + region, _ := auth.Metadata["region"].(string) + + var tokenData *kiroauth.KiroTokenData + var err error + + ssoClient := kiroauth.NewSSOOIDCClient(cfg) + + switch { + case clientID != "" && clientSecret != "" && authMethod == "idc" && region != "": + tokenData, err = ssoClient.RefreshTokenWithRegion(ctx, clientID, clientSecret, refreshToken, region, startURL) + case clientID != "" && clientSecret != "" && authMethod == "builder-id": + tokenData, err = ssoClient.RefreshToken(ctx, clientID, clientSecret, refreshToken) + default: + oauth := kiroauth.NewKiroOAuth(cfg) + tokenData, err = oauth.RefreshToken(ctx, refreshToken) + } + + if err != nil { + return nil, err + } + + updated := auth.Clone() + now := time.Now() + updated.UpdatedAt = now + updated.LastRefreshedAt = now + updated.Metadata["access_token"] = tokenData.AccessToken + updated.Metadata["refresh_token"] = tokenData.RefreshToken + updated.Metadata["expires_at"] = tokenData.ExpiresAt + updated.Metadata["last_refresh"] = now.Format(time.RFC3339) + + expiresAt, _ := time.Parse(time.RFC3339, tokenData.ExpiresAt) + if !expiresAt.IsZero() { + updated.NextRefreshAfter = expiresAt.Add(-5 * time.Minute) + } + + return updated, nil +} + +func refreshQwen(ctx context.Context, cfg *config.Config, auth *cliproxyauth.Auth) (*cliproxyauth.Auth, error) { + if auth.Metadata == nil { + return nil, fmt.Errorf("no metadata") + } + + refreshToken, ok := auth.Metadata["refresh_token"].(string) + if !ok || refreshToken == "" { + return nil, fmt.Errorf("no refresh token") + } + + svc := qwenauth.NewQwenAuth(cfg) + td, err := svc.RefreshTokens(ctx, refreshToken) + if err != nil { + return nil, err + } + + updated := auth.Clone() + updated.Metadata["access_token"] = td.AccessToken + if td.RefreshToken != "" { + updated.Metadata["refresh_token"] = td.RefreshToken + } + updated.Metadata["expired"] = td.Expire + updated.Metadata["last_refresh"] = time.Now().Format(time.RFC3339) + + if expiry, ok := updated.ExpirationTime(); ok { + updated.TokenExpiresAt = expiry + } + + return updated, nil +} + +func printRefreshResult(result RefreshResult) { + email := result.Email + if email == "" { + email = result.ID + } + if len(email) > 35 { + email = email[:32] + "..." + } + + if result.Success { + expiry := "" + if result.ExpiresAt != "" { + if t, err := time.Parse(time.RFC3339, result.ExpiresAt); err == nil { + expiry = fmt.Sprintf(" (expires: %s)", t.Format("2006-01-02 15:04")) + } + } + fmt.Printf(" %s+%s %-12s %-35s %srefreshed%s%s\n", + colorGreen, colorReset, + result.Provider, email, + colorGreen, colorReset, expiry) + } else { + errMsg := result.Error + if len(errMsg) > 40 { + errMsg = errMsg[:37] + "..." + } + fmt.Printf(" %sx%s %-12s %-35s %sfailed%s: %s\n", + colorRed, colorReset, + result.Provider, email, + colorRed, colorReset, errMsg) + } +} diff --git a/internal/cmd/usage.go b/internal/cmd/usage.go new file mode 100644 index 00000000..4e88bc08 --- /dev/null +++ b/internal/cmd/usage.go @@ -0,0 +1,257 @@ +// Package cmd provides CLI command implementations for ProxyPilot. +package cmd + +import ( + "encoding/json" + "fmt" + "os" + "sort" + + "github.com/router-for-me/CLIProxyAPI/v6/internal/usage" +) + +// UsageOutput represents the JSON output structure for usage stats +type UsageOutput struct { + TotalRequests int64 `json:"total_requests"` + SuccessCount int64 `json:"success_count"` + FailureCount int64 `json:"failure_count"` + TotalTokens int64 `json:"total_tokens"` + TotalInputTokens int64 `json:"total_input_tokens"` + TotalOutputTokens int64 `json:"total_output_tokens"` + ByProvider map[string]ProviderStats `json:"by_provider"` + ByDay map[string]DayStats `json:"by_day,omitempty"` +} + +// ProviderStats holds usage stats for a single provider +type ProviderStats struct { + Requests int64 `json:"requests"` + Tokens int64 `json:"tokens"` + Models map[string]int64 `json:"models,omitempty"` +} + +// DayStats holds daily usage stats +type DayStats struct { + Requests int64 `json:"requests"` + Tokens int64 `json:"tokens"` + InputTokens int64 `json:"input_tokens"` + OutputTokens int64 `json:"output_tokens"` +} + +// ShowUsage displays token usage stats per account/provider +func ShowUsage(jsonOutput bool) error { + stats := usage.GetRequestStatistics() + if stats == nil { + if jsonOutput { + return outputJSON(UsageOutput{ + ByProvider: make(map[string]ProviderStats), + ByDay: make(map[string]DayStats), + }) + } + fmt.Printf("%sNo usage data available%s\n", colorYellow, colorReset) + return nil + } + + snapshot := stats.Snapshot() + + if jsonOutput { + return outputUsageJSON(snapshot) + } + + return outputUsageTable(snapshot) +} + +func outputUsageJSON(snapshot usage.StatisticsSnapshot) error { + output := UsageOutput{ + TotalRequests: snapshot.TotalRequests, + SuccessCount: snapshot.SuccessCount, + FailureCount: snapshot.FailureCount, + TotalTokens: snapshot.TotalTokens, + TotalInputTokens: snapshot.TotalInputTokens, + TotalOutputTokens: snapshot.TotalOutputTokens, + ByProvider: make(map[string]ProviderStats), + ByDay: make(map[string]DayStats), + } + + // Aggregate by provider + for apiName, apiSnapshot := range snapshot.APIs { + provider := inferProvider(apiName) + ps := output.ByProvider[provider] + ps.Requests += apiSnapshot.TotalRequests + ps.Tokens += apiSnapshot.TotalTokens + if ps.Models == nil { + ps.Models = make(map[string]int64) + } + for modelName, modelSnapshot := range apiSnapshot.Models { + ps.Models[modelName] += modelSnapshot.TotalRequests + } + output.ByProvider[provider] = ps + } + + // Daily stats + for day, requests := range snapshot.RequestsByDay { + ds := output.ByDay[day] + ds.Requests = requests + ds.Tokens = snapshot.TokensByDay[day] + ds.InputTokens = snapshot.InputTokensByDay[day] + ds.OutputTokens = snapshot.OutputTokensByDay[day] + output.ByDay[day] = ds + } + + enc := json.NewEncoder(os.Stdout) + enc.SetIndent("", " ") + return enc.Encode(output) +} + +func outputUsageTable(snapshot usage.StatisticsSnapshot) error { + if snapshot.TotalRequests == 0 { + fmt.Printf("%sNo usage data available%s\n", colorYellow, colorReset) + fmt.Printf("%sUsage statistics are collected during proxy operation.%s\n", colorDim, colorReset) + return nil + } + + fmt.Printf("\n%s%sProxyPilot Usage Statistics%s\n", colorBold, colorCyan, colorReset) + fmt.Printf("%s─────────────────────────────────────────────────────────%s\n\n", colorDim, colorReset) + + // Summary + fmt.Printf("%sTotal Requests:%s %d", colorBold, colorReset, snapshot.TotalRequests) + if snapshot.FailureCount > 0 { + fmt.Printf(" (%s%d failed%s)", colorRed, snapshot.FailureCount, colorReset) + } + fmt.Println() + fmt.Printf("%sTotal Tokens:%s %s\n", colorBold, colorReset, formatTokenCount(snapshot.TotalTokens)) + fmt.Printf(" Input: %s\n", formatTokenCount(snapshot.TotalInputTokens)) + fmt.Printf(" Output: %s\n", formatTokenCount(snapshot.TotalOutputTokens)) + + // By provider + if len(snapshot.APIs) > 0 { + fmt.Printf("\n%s%sByProvider%s\n", colorBold, colorCyan, colorReset) + fmt.Printf("%s─────────────────────────────────────────────────────────%s\n", colorDim, colorReset) + + // Aggregate by provider + providerStats := make(map[string]struct { + requests int64 + tokens int64 + }) + + for apiName, apiSnapshot := range snapshot.APIs { + provider := inferProvider(apiName) + ps := providerStats[provider] + ps.requests += apiSnapshot.TotalRequests + ps.tokens += apiSnapshot.TotalTokens + providerStats[provider] = ps + } + + // Sort providers + providers := make([]string, 0, len(providerStats)) + for p := range providerStats { + providers = append(providers, p) + } + sort.Strings(providers) + + fmt.Printf(" %-15s %10s %15s\n", "Provider", "Requests", "Tokens") + fmt.Printf(" %s───────────────────────────────────────────%s\n", colorDim, colorReset) + + for _, provider := range providers { + ps := providerStats[provider] + fmt.Printf(" %-15s %10d %15s\n", provider, ps.requests, formatTokenCount(ps.tokens)) + } + } + + // Recent daily stats + if len(snapshot.RequestsByDay) > 0 { + fmt.Printf("\n%s%sRecent Activity%s\n", colorBold, colorCyan, colorReset) + fmt.Printf("%s─────────────────────────────────────────────────────────%s\n", colorDim, colorReset) + + // Sort days + days := make([]string, 0, len(snapshot.RequestsByDay)) + for day := range snapshot.RequestsByDay { + days = append(days, day) + } + sort.Sort(sort.Reverse(sort.StringSlice(days))) + + // Show last 7 days max + if len(days) > 7 { + days = days[:7] + } + + fmt.Printf(" %-12s %10s %15s\n", "Date", "Requests", "Tokens") + fmt.Printf(" %s─────────────────────────────────────%s\n", colorDim, colorReset) + + for _, day := range days { + requests := snapshot.RequestsByDay[day] + tokens := snapshot.TokensByDay[day] + fmt.Printf(" %-12s %10d %15s\n", day, requests, formatTokenCount(tokens)) + } + } + + fmt.Printf("\n%s─────────────────────────────────────────────────────────%s\n\n", colorDim, colorReset) + + return nil +} + +func inferProvider(apiName string) string { + switch { + case contains(apiName, "claude", "anthropic"): + return "anthropic" + case contains(apiName, "gpt", "openai", "codex"): + return "openai" + case contains(apiName, "gemini", "google"): + return "google" + case contains(apiName, "qwen"): + return "qwen" + case contains(apiName, "deepseek"): + return "deepseek" + case contains(apiName, "kiro", "amazon"): + return "kiro" + default: + return apiName + } +} + +func contains(s string, substrs ...string) bool { + lower := toLower(s) + for _, sub := range substrs { + if indexOfLower(lower, sub) >= 0 { + return true + } + } + return false +} + +func toLower(s string) string { + b := make([]byte, len(s)) + for i := 0; i < len(s); i++ { + c := s[i] + if c >= 'A' && c <= 'Z' { + c += 'a' - 'A' + } + b[i] = c + } + return string(b) +} + +func indexOfLower(s, sub string) int { + for i := 0; i <= len(s)-len(sub); i++ { + match := true + for j := 0; j < len(sub); j++ { + if s[i+j] != sub[j] { + match = false + break + } + } + if match { + return i + } + } + return -1 +} + +func formatTokenCount(tokens int64) string { + if tokens < 1000 { + return fmt.Sprintf("%d", tokens) + } + if tokens < 1000000 { + return fmt.Sprintf("%.1fK", float64(tokens)/1000) + } + return fmt.Sprintf("%.2fM", float64(tokens)/1000000) +}