diff --git a/.changeset/yellow-pens-behave.md b/.changeset/yellow-pens-behave.md new file mode 100644 index 00000000..71429975 --- /dev/null +++ b/.changeset/yellow-pens-behave.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +Add interactive provider configuration wizard with add/list capabilities, support for 8 API providers (Anthropic, OpenAI, OpenAI Native, OpenRouter, X AI, AWS Bedrock, Google Gemini, Ollama), and UpdateSettings gRPC implementation for persisting configurations to Cline Core state. diff --git a/cli/go.mod b/cli/go.mod index 8e860a31..44eabfcd 100644 --- a/cli/go.mod +++ b/cli/go.mod @@ -4,10 +4,12 @@ go 1.23.0 require ( github.com/atotto/clipboard v0.1.4 + github.com/charmbracelet/glamour v0.10.0 github.com/charmbracelet/huh v0.7.0 github.com/cline/grpc-go v0.0.0 github.com/mattn/go-sqlite3 v1.14.24 github.com/spf13/cobra v1.8.0 + golang.org/x/term v0.32.0 google.golang.org/grpc v1.75.0 google.golang.org/protobuf v1.36.6 ) @@ -22,7 +24,6 @@ require ( github.com/charmbracelet/bubbles v0.21.0 // indirect github.com/charmbracelet/bubbletea v1.3.4 // indirect github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect - github.com/charmbracelet/glamour v0.10.0 // indirect github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 // indirect github.com/charmbracelet/x/ansi v0.8.0 // indirect github.com/charmbracelet/x/cellbuf v0.0.13 // indirect @@ -52,7 +53,6 @@ require ( golang.org/x/net v0.41.0 // indirect golang.org/x/sync v0.15.0 // indirect golang.org/x/sys v0.33.0 // indirect - golang.org/x/term v0.32.0 // indirect golang.org/x/text v0.26.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20250707201910-8d1bb00bc6a7 // indirect ) diff --git a/cli/go.sum b/cli/go.sum index 2f4a306a..f51d847e 100644 --- a/cli/go.sum +++ b/cli/go.sum @@ -1,7 +1,11 @@ github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ= github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE= +github.com/alecthomas/assert/v2 v2.7.0 h1:QtqSACNS3tF7oasA8CU6A6sXZSBDqnm7RfpLl9bZqbE= +github.com/alecthomas/assert/v2 v2.7.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k= github.com/alecthomas/chroma/v2 v2.14.0 h1:R3+wzpnUArGcQz7fCETQBzO5n9IMNi13iIs46aU4V9E= github.com/alecthomas/chroma/v2 v2.14.0/go.mod h1:QolEbTfmUHIMVpBqxeDnNBj2uoeI4EbYP4i6n68SG4I= +github.com/alecthomas/repr v0.4.0 h1:GhI2A8MACjfegCPVq9f1FLvIBS+DrQ2KQBFZP1iFzXc= +github.com/alecthomas/repr v0.4.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= @@ -22,8 +26,6 @@ github.com/charmbracelet/glamour v0.10.0 h1:MtZvfwsYCx8jEPFJm3rIBFIMZUfUJ765oX8V github.com/charmbracelet/glamour v0.10.0/go.mod h1:f+uf+I/ChNmqo087elLnVdCiVgjSKWuXa/l6NU2ndYk= github.com/charmbracelet/huh v0.7.0 h1:W8S1uyGETgj9Tuda3/JdVkc3x7DBLZYPZc4c+/rnRdc= github.com/charmbracelet/huh v0.7.0/go.mod h1:UGC3DZHlgOKHvHC07a5vHag41zzhpPFj34U92sOmyuk= -github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY= -github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30= github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 h1:ZR7e0ro+SZZiIZD7msJyA+NjkCNNavuiPBLgerbOziE= github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834/go.mod h1:aKC/t2arECF6rNOnaKaVU6y4t4ZeHQzqfxedE/VkVhA= github.com/charmbracelet/x/ansi v0.8.0 h1:9GTq3xq9caJW8ZrBTe0LIe2fvfLR/bYXKTx2llXn7xE= @@ -67,6 +69,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8= github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0= +github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= +github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= diff --git a/cli/pkg/cli/auth/auth_cline_provider.go b/cli/pkg/cli/auth/auth_cline_provider.go new file mode 100644 index 00000000..68cfec53 --- /dev/null +++ b/cli/pkg/cli/auth/auth_cline_provider.go @@ -0,0 +1,197 @@ +package auth + +import ( + "context" + "fmt" + "time" + + "github.com/charmbracelet/huh" + "github.com/cline/cli/pkg/cli/global" + "github.com/cline/cli/pkg/cli/task" + "github.com/cline/grpc-go/cline" +) + +var isSessionAuthenticated bool + +// Cline provider specific code + +func HandleClineAuth(ctx context.Context) error { + fmt.Println("Authenticating with Cline...") + + // Check if already authenticated + if IsAuthenticated(ctx) { + return signOutDialog(ctx) + } + + // Perform sign in + if err := signIn(ctx); err != nil { + return err + } + + fmt.Println("✓ You are signed in!") + + // Configure default Cline model after successful authentication + if err := configureDefaultClineModel(ctx); err != nil { + fmt.Printf("Warning: Could not configure default Cline model: %v\n", err) + fmt.Println("You can configure a model later with 'cline auth' and selecting 'Change Cline model'") + } + + // Return to main auth menu after successful authentication + return HandleAuthMenuNoArgs(ctx) +} + +func signOut(ctx context.Context) error { + client, err := global.GetDefaultClient(ctx) + if err != nil { + return err + } + + if _, err = client.Account.AccountLogoutClicked(ctx, &cline.EmptyRequest{}); err != nil { + return err + } + + isSessionAuthenticated = false + fmt.Println("You have been signed out of Cline.") + return nil +} + +func signOutDialog(ctx context.Context) error { + var confirm bool + form := huh.NewForm( + huh.NewGroup( + huh.NewConfirm(). + Title("You are already signed in to Cline."). + Description("Would you like to sign out?"). + Value(&confirm), + ), + ) + + if err := form.Run(); err != nil { + return nil + } + + if confirm { + if err := signOut(ctx); err != nil { + fmt.Printf("Failed to sign out: %v\n", err) + return err + } + } + return HandleAuthMenuNoArgs(ctx) +} + +func signIn(ctx context.Context) error { + if IsAuthenticated(ctx) { + return nil + } + + verboseLog("Ensuring default instance exists...") + if err := global.EnsureDefaultInstance(ctx); err != nil { + verboseLog("Failed to ensure default instance: %v", err) + return fmt.Errorf("failed to ensure default instance: %w", err) + } + + verboseLog("Default instance ensured successfully.") + time.Sleep(2 * time.Second) // Allow services to start + + // Subscribe to auth updates before initiating login + verboseLog("Subscribing to auth status updates...") + listener, err := NewAuthStatusListener(ctx) + if err != nil { + verboseLog("Failed to subscribe to auth updates: %v", err) + return fmt.Errorf("failed to subscribe to auth updates: %w", err) + } + defer listener.Stop() + + if err := listener.Start(); err != nil { + verboseLog("Failed to start auth listener: %v", err) + return fmt.Errorf("failed to start auth listener: %w", err) + } + + // Initiate login (opens browser with callback URL from cline-core's AuthHandler) + verboseLog("Initiating login...") + client, err := global.GetDefaultClient(ctx) + if err != nil { + verboseLog("Failed to obtain client: %v", err) + return fmt.Errorf("failed to obtain client: %w", err) + } + + _, err = client.Account.AccountLoginClicked(ctx, &cline.EmptyRequest{}) + if err != nil { + verboseLog("Failed to initiate login: %v", err) + return fmt.Errorf("failed to initiate login: %w", err) + } + + fmt.Println("\n Opening browser for authentication...") + fmt.Println(" Waiting for you to complete authentication in your browser...") + fmt.Println(" (This may take a few moments. Timeout: 5 minutes)") + + // Wait for auth status update confirming success + verboseLog("Waiting for authentication to complete...") + if err := listener.WaitForAuthentication(5 * time.Minute); err != nil { + verboseLog("Authentication failed or timed out: %v", err) + fmt.Println("\n Authentication failed or timed out.") + fmt.Println(" Please try again with 'cline auth'") + return err + } + + // Only NOW set the session flag after confirmed authentication + isSessionAuthenticated = true + verboseLog("Login successful") + return nil +} + +func IsAuthenticated(ctx context.Context) bool { + if isSessionAuthenticated { + verboseLog("Session is already authenticated") + return true + } + + verboseLog("Verifying authentication with server...") + client, err := global.GetDefaultClient(ctx) + if err != nil { + verboseLog("Failed to get client for auth check: %v", err) + return false + } + + _, err = client.Account.GetUserCredits(ctx, &cline.EmptyRequest{}) + if err == nil { + // Update session variable for future fast-path checks + verboseLog("Server verification successful, updating session flag") + isSessionAuthenticated = true + return true + } + + verboseLog("Server verification failed: %v", err) + return false +} + +// HandleChangeClineModel allows Cline-authenticated users to change their Cline model selection. Hidden when not authenticated. +func HandleChangeClineModel(ctx context.Context) error { + // Ensure user is authenticated + if !IsAuthenticated(ctx) { + return fmt.Errorf("you must be authenticated with Cline to change models. Run 'cline auth' to sign in") + } + + // Get task manager + manager, err := createTaskManager(ctx) + if err != nil { + return fmt.Errorf("failed to create task manager: %w", err) + } + + // Launch Cline model selection + return SelectClineModel(ctx, manager) +} + +// configureDefaultClineModel configures the default Cline model after authentication +func configureDefaultClineModel(ctx context.Context) error { + verboseLog("Configuring default Cline model...") + + // Create task manager + manager, err := task.NewManagerForDefault(ctx) + if err != nil { + return fmt.Errorf("failed to create task manager: %w", err) + } + + // Set default Cline model + return SetDefaultClineModel(ctx, manager) +} diff --git a/cli/pkg/cli/auth/auth_menu.go b/cli/pkg/cli/auth/auth_menu.go index 7541523e..16465c6b 100644 --- a/cli/pkg/cli/auth/auth_menu.go +++ b/cli/pkg/cli/auth/auth_menu.go @@ -5,16 +5,37 @@ import ( "fmt" "github.com/charmbracelet/huh" + "github.com/cline/cli/pkg/cli/global" + "github.com/cline/cli/pkg/cli/task" + "github.com/cline/grpc-go/cline" ) // AuthAction represents the type of authentication action type AuthAction string const ( - AuthActionClineLogin AuthAction = "cline_login" - AuthActionBYOSetup AuthAction = "provider_setup" + AuthActionClineLogin AuthAction = "cline_login" + AuthActionBYOSetup AuthAction = "provider_setup" + AuthActionChangeClineModel AuthAction = "change_cline_model" + AuthActionSelectProvider AuthAction = "select_provider" + AuthActionExit AuthAction = "exit_wizard" ) +// Cline Auth Menu +// Example Layout +// +// ┃ Cline Account: +// ┃ Active Provider: +// ┃ Active Model: +// ┃ +// ┃ What would you like to do? +// ┃ Change Cline model (only if authenticated) - hidden if not authenticated +// ┃ Authenticate with Cline account / Sign out of Cline - changes based on auth status +// ┃ Select active provider (Cline or BYO) - always shown. Used to switch between Cline and BYO providers +// ┃ Configure API provider - always shown. Launches provider setup wizard +// ┃ Exit authorization wizard - always shown. Exits the auth menu + +// Main entry point for handling the `cline auth` command // HandleAuthCommand routes the auth command based on the number of arguments func HandleAuthCommand(ctx context.Context, args []string) error { switch len(args) { @@ -28,13 +49,28 @@ func HandleAuthCommand(ctx context.Context, args []string) error { // Two args: Provider ID and API key return QuickAPISetup(args[0], args[1]) default: - return fmt.Errorf("too many arguments. Usage: cline auth [provider] [key]") + return fmt.Errorf("quick BYO API setup is currently stubbed - not yet implemented") } } -// HandleAuthMenuNoArgs offers Cline auth or provider setup when no args are given +// HandleAuthMenuNoArgs prepares the auth menu when no arguments are provided func HandleAuthMenuNoArgs(ctx context.Context) error { - action, err := ShowAuthMenuNoArgs() + // Check if Cline is authenticated + isClineAuth := IsAuthenticated(ctx) + + // Get current provider config for display + var currentProvider string + var currentModel string + if manager, err := createTaskManager(ctx); err == nil { + if providerList, err := GetProviderConfigurations(ctx, manager); err == nil { + if providerList.ActProvider != nil { + currentProvider = getProviderDisplayName(providerList.ActProvider.Provider) + currentModel = providerList.ActProvider.ModelID + } + } + } + + action, err := ShowAuthMenuWithStatus(isClineAuth, currentProvider, currentModel) if err != nil { return err } @@ -43,23 +79,65 @@ func HandleAuthMenuNoArgs(ctx context.Context) error { case AuthActionClineLogin: return HandleClineAuth(ctx) case AuthActionBYOSetup: - return HandleAPIProviderSetup() + return HandleAPIProviderSetup(ctx) + case AuthActionChangeClineModel: + return HandleChangeClineModel(ctx) + case AuthActionSelectProvider: + return HandleSelectProvider(ctx) + case AuthActionExit: + return nil default: return fmt.Errorf("invalid action") } } -// ShowAuthMenu displays the main auth menu and returns the selected action -func ShowAuthMenuNoArgs() (AuthAction, error) { +// ShowAuthMenuWithStatus displays the main auth menu with Cline + provider status +func ShowAuthMenuWithStatus(isClineAuthenticated bool, currentProvider, currentModel string) (AuthAction, error) { var action AuthAction + var options []huh.Option[AuthAction] + + // Build menu options based on authentication status + if isClineAuthenticated { + options = []huh.Option[AuthAction]{ + huh.NewOption("Change Cline model", AuthActionChangeClineModel), + huh.NewOption("Sign out of Cline", AuthActionClineLogin), + huh.NewOption("Select active provider (Cline or BYO)", AuthActionSelectProvider), + huh.NewOption("Configure API provider", AuthActionBYOSetup), + huh.NewOption("Exit authorization wizard", AuthActionExit), + } + } else { + options = []huh.Option[AuthAction]{ + huh.NewOption("Authenticate with Cline account", AuthActionClineLogin), + huh.NewOption("Select active provider (Cline or BYO)", AuthActionSelectProvider), + huh.NewOption("Configure API provider", AuthActionBYOSetup), + huh.NewOption("Exit authorization wizard", AuthActionExit), + } + } + + // Determine menu title based on status + var title string + + // Always show Cline authentication status + if isClineAuthenticated { + title = "Cline Account: \033[32m✓\033[0m Authenticated\n" + } else { + title = "Cline Account: \033[31m✗\033[0m Not authenticated\n" + } + + // Show active provider and model if configured (regardless of Cline auth status) + // ANSI color codes: Normal intensity = \033[22m, White = \033[37m, Reset = \033[0m + if currentProvider != "" && currentModel != "" { + title += fmt.Sprintf("Active Provider: \033[22m\033[37m%s\033[0m\nActive Model: \033[22m\033[37m%s\033[0m\n", currentProvider, currentModel) + } + + // Always end with a huh? + title += "\nWhat would you like to do?" + form := huh.NewForm( huh.NewGroup( huh.NewSelect[AuthAction](). - Title("What would you like to do?"). - Options( - huh.NewOption("Authenticate with Cline account", AuthActionClineLogin), - huh.NewOption("Configure API provider", AuthActionBYOSetup), - ). + Title(title). + Options(options...). Value(&action), ), ) @@ -71,12 +149,93 @@ func ShowAuthMenuNoArgs() (AuthAction, error) { return action, nil } -// HandleProviderSetup launches the API provider configuration wizard -func HandleAPIProviderSetup() error { - wizard, err := NewProviderWizard() +// HandleAPIProviderSetup launches the API provider configuration wizard +func HandleAPIProviderSetup(ctx context.Context) error { + wizard, err := NewProviderWizard(ctx) if err != nil { return fmt.Errorf("failed to create provider wizard: %w", err) } return wizard.Run() } + +// HandleSelectProvider allows users to switch between Cline provider and BYO providers +func HandleSelectProvider(ctx context.Context) error { + // Get task manager + manager, err := createTaskManager(ctx) + if err != nil { + return fmt.Errorf("failed to create task manager: %w", err) + } + + // Detect all providers with valid configurations (is an API key present) + availableProviders, err := DetectAllConfiguredProviders(ctx, manager) + if err != nil { + return fmt.Errorf("failed to detect configured providers: %w", err) + } + + // Build list of available providers + var providerOptions []huh.Option[string] + var providerMapping = make(map[string]cline.ApiProvider) + + // Add each configured provider to the selection menu + for _, provider := range availableProviders { + providerName := getProviderDisplayName(provider) + providerKey := fmt.Sprintf("provider_%d", provider) + providerOptions = append(providerOptions, huh.NewOption(providerName, providerKey)) + providerMapping[providerKey] = provider + } + + if len(providerOptions) == 0 { + fmt.Println("No providers available. Please configure a provider first.") + return HandleAuthMenuNoArgs(ctx) + } + + if len(providerOptions) == 1 { + fmt.Println("Only one provider is configured. Configure another provider to switch between them.") + return HandleAuthMenuNoArgs(ctx) + } + + providerOptions = append(providerOptions, huh.NewOption("(Cancel)", "cancel")) + + // Show selection menu + var selected string + form := huh.NewForm( + huh.NewGroup( + huh.NewSelect[string](). + Title("Select which provider to use"). + Options(providerOptions...). + Value(&selected), + ), + ) + + if err := form.Run(); err != nil { + return fmt.Errorf("failed to select provider: %w", err) + } + + if selected == "cancel" { + return HandleAuthMenuNoArgs(ctx) + } + + // Get the selected provider + selectedProvider := providerMapping[selected] + + // Apply the selected provider + if selectedProvider == cline.ApiProvider_CLINE { + // Configure Cline as the active provider + return SelectClineModel(ctx, manager) + } else { + // Switch to the selected BYO provider + return SwitchToBYOProvider(ctx, manager, selectedProvider) + } +} + +// createTaskManager is a helper to create a task manager (avoids import cycles) +func createTaskManager(ctx context.Context) (*task.Manager, error) { + return task.NewManagerForDefault(ctx) +} + +func verboseLog(format string, args ...interface{}) { + if global.Config != nil && global.Config.Verbose { + fmt.Printf("[VERBOSE] "+format+"\n", args...) + } +} diff --git a/cli/pkg/cli/auth/auth_subscription.go b/cli/pkg/cli/auth/auth_subscription.go new file mode 100644 index 00000000..b1a14a57 --- /dev/null +++ b/cli/pkg/cli/auth/auth_subscription.go @@ -0,0 +1,130 @@ +package auth + +import ( + "context" + "fmt" + "io" + "time" + + "github.com/cline/cli/pkg/cli/global" + "github.com/cline/grpc-go/cline" +) + +// AuthStatusListener manages subscription to auth status updates +type AuthStatusListener struct { + stream cline.AccountService_SubscribeToAuthStatusUpdateClient + updatesCh chan *cline.AuthState + errCh chan error + ctx context.Context + cancel context.CancelFunc +} + +// NewAuthStatusListener creates a new auth status listener +func NewAuthStatusListener(parentCtx context.Context) (*AuthStatusListener, error) { + client, err := global.GetDefaultClient(parentCtx) + if err != nil { + return nil, fmt.Errorf("failed to get client: %w", err) + } + + // Create cancellable context + ctx, cancel := context.WithCancel(parentCtx) + + // Subscribe to auth status updates + stream, err := client.Account.SubscribeToAuthStatusUpdate(ctx, &cline.EmptyRequest{}) + if err != nil { + cancel() + return nil, fmt.Errorf("failed to subscribe to auth updates: %w", err) + } + + return &AuthStatusListener{ + stream: stream, + updatesCh: make(chan *cline.AuthState, 10), + errCh: make(chan error, 1), + ctx: ctx, + cancel: cancel, + }, nil +} + +// Start begins listening to the auth status update stream +func (l *AuthStatusListener) Start() error { + verboseLog("Starting auth status listener...") + + go l.readStream() + + return nil +} + +// readStream reads from the gRPC stream and forwards messages to channels +func (l *AuthStatusListener) readStream() { + defer close(l.updatesCh) + defer close(l.errCh) + + for { + select { + case <-l.ctx.Done(): + verboseLog("Auth listener context cancelled") + return + default: + state, err := l.stream.Recv() + if err != nil { + if err == io.EOF { + verboseLog("Auth status stream closed") + return + } + verboseLog("Error reading from auth status stream: %v", err) + select { + case l.errCh <- err: + case <-l.ctx.Done(): + } + return + } + + verboseLog("Received auth state update: user=%v", state.User != nil) + + select { + case l.updatesCh <- state: + case <-l.ctx.Done(): + return + } + } + } +} + +// WaitForAuthentication blocks until authentication succeeds or timeout occurs +func (l *AuthStatusListener) WaitForAuthentication(timeout time.Duration) error { + verboseLog("Waiting for authentication (timeout: %v)...", timeout) + + timer := time.NewTimer(timeout) + defer timer.Stop() + + for { + select { + case <-timer.C: + return fmt.Errorf("authentication timeout after %v - please try again", timeout) + + case <-l.ctx.Done(): + return fmt.Errorf("authentication cancelled") + + case err := <-l.errCh: + return fmt.Errorf("authentication stream error: %w", err) + + case state := <-l.updatesCh: + if isAuthenticated(state) { + verboseLog("Authentication successful!") + return nil + } + verboseLog("Received auth update but not authenticated yet...") + } + } +} + +// Stop closes the stream and cleans up resources +func (l *AuthStatusListener) Stop() { + verboseLog("Stopping auth status listener...") + l.cancel() +} + +// isAuthenticated checks if AuthState indicates successful authentication +func isAuthenticated(state *cline.AuthState) bool { + return state != nil && state.User != nil +} diff --git a/cli/pkg/cli/auth/byo_wizard.go b/cli/pkg/cli/auth/byo_wizard.go deleted file mode 100644 index c25e410b..00000000 --- a/cli/pkg/cli/auth/byo_wizard.go +++ /dev/null @@ -1,76 +0,0 @@ -package auth - -import ( - "fmt" - - "github.com/charmbracelet/huh" -) - -// ProviderWizard handles the interactive provider configuration process -type ProviderWizard struct{} - -// NewProviderWizard creates a new provider configuration wizard -func NewProviderWizard() (*ProviderWizard, error) { - return &ProviderWizard{}, nil -} - -// Run runs the provider configuration wizard -func (pw *ProviderWizard) Run() error { - fmt.Println("Welcome to Cline API Provider Configuration!") - fmt.Println("(Currently stubbed - full implementation coming soon)") - fmt.Println() - - for { - action, err := pw.showMainMenu() - if err != nil { - return err - } - - switch action { - case "add": - fmt.Println("Provider setup is currently stubbed - not yet implemented.") - case "remove": - fmt.Println("Provider removal is currently stubbed - not yet implemented.") - case "list": - fmt.Println("Provider listing is currently stubbed - not yet implemented.") - case "test": - fmt.Println("Provider testing is currently stubbed - not yet implemented.") - case "default": - fmt.Println("Setting default provider is currently stubbed - not yet implemented.") - case "save": - fmt.Println("No configuration to save.") - return nil - case "exit": - fmt.Println("Exiting configuration wizard.") - return nil - } - fmt.Println() - } -} - -// showMainMenu displays the main provider configuration menu -func (pw *ProviderWizard) showMainMenu() (string, error) { - var action string - form := huh.NewForm( - huh.NewGroup( - huh.NewSelect[string](). - Title("What would you like to do?"). - Options( - huh.NewOption("Add a new provider", "add"), - huh.NewOption("Remove a provider", "remove"), - huh.NewOption("List configured providers", "list"), - huh.NewOption("Test provider connections", "test"), - huh.NewOption("Set default provider", "default"), - huh.NewOption("Save configuration and exit", "save"), - huh.NewOption("Exit without saving", "exit"), - ). - Value(&action), - ), - ) - - if err := form.Run(); err != nil { - return "", fmt.Errorf("failed to get menu choice: %w", err) - } - - return action, nil -} diff --git a/cli/pkg/cli/auth/cline_auth.go b/cli/pkg/cli/auth/cline_auth.go deleted file mode 100644 index b41b61cc..00000000 --- a/cli/pkg/cli/auth/cline_auth.go +++ /dev/null @@ -1,120 +0,0 @@ -package auth - -import ( - "context" - "fmt" - "time" - - "github.com/charmbracelet/huh" - "github.com/cline/cli/pkg/cli/global" - "github.com/cline/grpc-go/cline" -) - -var isSessionAuthenticated bool - -func HandleClineAuth(ctx context.Context) error { - fmt.Println("Authenticating with Cline...") - - // Check if already authenticated - if IsAuthenticated(ctx) { - return signOutDialog(ctx) - } - - // Perform sign in - if err := signIn(ctx); err != nil { - return err - } - - fmt.Println("You are signed in!") - return nil -} - -func signOut(ctx context.Context) error { - client, err := global.GetDefaultClient(ctx) - if err != nil { - return err - } - - if _, err = client.Account.AccountLogoutClicked(ctx, &cline.EmptyRequest{}); err != nil { - return err - } - - isSessionAuthenticated = false - fmt.Println("You have been signed out of Cline.") - return nil -} - -func signOutDialog(ctx context.Context) error { - var confirm bool - form := huh.NewForm( - huh.NewGroup( - huh.NewConfirm(). - Title("You are already signed in to Cline."). - Description("Would you like to sign out?"). - Value(&confirm), - ), - ) - - if err := form.Run(); err != nil { - return nil - } - - if confirm { - if err := signOut(ctx); err != nil { - fmt.Printf("Failed to sign out: %v\n", err) - return err - } - } - return nil -} - -func signIn(ctx context.Context) error { - if IsAuthenticated(ctx) { - return nil - } - - verboseLog("Ensuring default instance exists...") - if err := global.EnsureDefaultInstance(ctx); err != nil { - verboseLog("Failed to ensure default instance: %v", err) - return err - } - - verboseLog("Default instance ensured successfully.") - time.Sleep(2 * time.Second) // Allow services to start - - client, err := global.GetDefaultClient(ctx) - if err != nil { - verboseLog("Failed to obtain client: %v", err) - return err - } - - _, err = client.Account.AccountLoginClicked(ctx, &cline.EmptyRequest{}) - if err != nil { - verboseLog("Failed to login: %v", err) - return err - } - - isSessionAuthenticated = true - verboseLog("Login successful") - return nil -} - -func IsAuthenticated(ctx context.Context) bool { - if isSessionAuthenticated { - return true - } - - client, err := global.GetDefaultClient(ctx) - if err != nil { - return false - } - - _, err = client.Account.GetUserCredits(ctx, &cline.EmptyRequest{}) - return err == nil -} - -func verboseLog(format string, args ...interface{}) { - if global.Config != nil && global.Config.Verbose { - fmt.Printf("[VERBOSE] "+format+"\n", args...) - } -} diff --git a/cli/pkg/cli/auth/models_byo.go b/cli/pkg/cli/auth/models_byo.go new file mode 100644 index 00000000..8832b06d --- /dev/null +++ b/cli/pkg/cli/auth/models_byo.go @@ -0,0 +1 @@ +package auth diff --git a/cli/pkg/cli/auth/models_cline.go b/cli/pkg/cli/auth/models_cline.go new file mode 100644 index 00000000..3f0e54eb --- /dev/null +++ b/cli/pkg/cli/auth/models_cline.go @@ -0,0 +1,123 @@ +package auth + +import ( + "context" + "fmt" + + "github.com/cline/cli/pkg/cli/global" + "github.com/cline/cli/pkg/cli/task" + "github.com/cline/grpc-go/cline" +) + +// DefaultClineModelID is the default model ID for Cline provider. +// Cline uses OpenRouter-compatible model IDs. +const DefaultClineModelID = "anthropic/claude-sonnet-4.5" + +// FetchClineModels fetches available Cline models from Cline Core. +// Note: Cline provider uses OpenRouter-compatible API and model format. +// The models are fetched using the same method as OpenRouter. +func FetchClineModels(ctx context.Context, manager *task.Manager) (map[string]*cline.OpenRouterModelInfo, error) { + if global.Config.Verbose { + fmt.Println("Fetching Cline models (using OpenRouter-compatible API)") + } + + // Cline uses OpenRouter model fetching + models, err := FetchOpenRouterModels(ctx, manager) + if err != nil { + return nil, fmt.Errorf("failed to fetch Cline models: %w", err) + } + + return models, nil +} + +// GetClineModelInfo retrieves information for a specific Cline model. +func GetClineModelInfo(modelID string, models map[string]*cline.OpenRouterModelInfo) (*cline.OpenRouterModelInfo, error) { + modelInfo, exists := models[modelID] + if !exists { + return nil, fmt.Errorf("model %s not found", modelID) + } + return modelInfo, nil +} + +// SetDefaultClineModel configures the default Cline model after authentication. +// This is called automatically after successful Cline sign-in. +func SetDefaultClineModel(ctx context.Context, manager *task.Manager) error { + + // Fetch available models + models, err := FetchClineModels(ctx, manager) + if err != nil { + // If we can't fetch models, we'll use the default without model info + fmt.Printf("Warning: Could not fetch Cline models: %v\n", err) + fmt.Printf("Using default model: %s\n", DefaultClineModelID) + return applyDefaultClineModel(ctx, manager, nil) + } + + // Check if default model is available + modelInfo, err := GetClineModelInfo(DefaultClineModelID, models) + if err != nil { + fmt.Printf("Warning: Default model not found: %v\n", err) + // Try to use any available model + for modelID := range models { + fmt.Printf("Using available model: %s\n", modelID) + return applyClineModelConfiguration(ctx, manager, modelID, models[modelID]) + } + return fmt.Errorf("no usable Cline models found") + } + + // Apply the default model + return applyClineModelConfiguration(ctx, manager, DefaultClineModelID, modelInfo) +} + +// SelectClineModel presents a menu to select a Cline model and applies the configuration. +func SelectClineModel(ctx context.Context, manager *task.Manager) error { + + // Fetch models (uses OpenRouter-compatible format) + models, err := FetchClineModels(ctx, manager) + if err != nil { + return fmt.Errorf("failed to fetch Cline models: %w", err) + } + + // Convert to interface map for generic utilities + modelMap := ConvertOpenRouterModelsToInterface(models) + + // Get model IDs as a sorted list + modelIDs := ConvertModelsMapToSlice(modelMap) + + // Display selection menu + selectedModelID, err := DisplayModelSelectionMenu(modelIDs, "Cline") + if err != nil { + return fmt.Errorf("model selection failed: %w", err) + } + + // Get the selected model info + modelInfo := models[selectedModelID] + + // Apply the configuration + if err := applyClineModelConfiguration(ctx, manager, selectedModelID, modelInfo); err != nil { + return err + } + + fmt.Println() + + // Return to main auth menu after model selection + return HandleAuthMenuNoArgs(ctx) +} + +// applyClineModelConfiguration applies a Cline model configuration to both Act and Plan modes using UpdateProviderPartial. +// Cline uses OpenRouter-compatible model format. +func applyClineModelConfiguration(ctx context.Context, manager *task.Manager, modelID string, modelInfo *cline.OpenRouterModelInfo) error { + provider := cline.ApiProvider_CLINE + + updates := ProviderUpdatesPartial{ + ModelID: &modelID, + ModelInfo: modelInfo, + } + + return UpdateProviderPartial(ctx, manager, provider, updates, true) +} + +// applyDefaultClineModel applies the default Cline model without model info. +// This is a fallback when model fetching fails. +func applyDefaultClineModel(ctx context.Context, manager *task.Manager, modelInfo *cline.OpenRouterModelInfo) error { + return applyClineModelConfiguration(ctx, manager, DefaultClineModelID, modelInfo) +} diff --git a/cli/pkg/cli/auth/models_list_fetch.go b/cli/pkg/cli/auth/models_list_fetch.go new file mode 100644 index 00000000..0e89297a --- /dev/null +++ b/cli/pkg/cli/auth/models_list_fetch.go @@ -0,0 +1,136 @@ +package auth + +import ( + "context" + "fmt" + "os" + "sort" + + "github.com/charmbracelet/huh" + "github.com/cline/cli/pkg/cli/task" + "github.com/cline/grpc-go/cline" + "golang.org/x/term" +) + +// FetchOpenRouterModels fetches available OpenRouter models from Cline Core +func FetchOpenRouterModels(ctx context.Context, manager *task.Manager) (map[string]*cline.OpenRouterModelInfo, error) { + resp, err := manager.GetClient().Models.RefreshOpenRouterModels(ctx, &cline.EmptyRequest{}) + if err != nil { + return nil, fmt.Errorf("failed to fetch OpenRouter models: %w", err) + } + return resp.Models, nil +} + +// FetchOpenAiModels fetches available OpenAI models from Cline Core +// Takes the API key and returns a list of model IDs +func FetchOpenAiModels(ctx context.Context, manager *task.Manager, baseURL, apiKey string) ([]string, error) { + req := &cline.OpenAiModelsRequest{ + BaseUrl: baseURL, + ApiKey: apiKey, + } + + resp, err := manager.GetClient().Models.RefreshOpenAiModels(ctx, req) + if err != nil { + return nil, fmt.Errorf("failed to fetch OpenAI models: %w", err) + } + return resp.Values, nil +} + +// FetchOllamaModels fetches available Ollama models from Cline Core +// Takes the base URL (empty string for default) and returns a list of model IDs +func FetchOllamaModels(ctx context.Context, manager *task.Manager, baseURL string) ([]string, error) { + req := &cline.StringRequest{ + Value: baseURL, + } + + resp, err := manager.GetClient().Models.GetOllamaModels(ctx, req) + if err != nil { + return nil, fmt.Errorf("failed to fetch Ollama models: %w", err) + } + return resp.Values, nil +} + +// DisplayModelSelectionMenu shows an interactive menu for selecting a model from a list. +// Models are displayed alphabetically. Uses model ID as the option value to avoid +// index-based bugs when list order changes. +// Returns the selected model ID. +func DisplayModelSelectionMenu(models []string, providerName string) (string, error) { + if len(models) == 0 { + return "", fmt.Errorf("no models available for selection") + } + + // Use model ID as the value (not index) to avoid positional coupling bugs + var selectedModel string + options := make([]huh.Option[string], len(models)) + for i, model := range models { + options[i] = huh.NewOption(model, model) + } + + title := fmt.Sprintf("Select a %s model", providerName) + + form := huh.NewForm( + huh.NewGroup( + huh.NewSelect[string](). + Title(title). + Options(options...). + Height(calculateSelectHeight()). + Filtering(true). + Value(&selectedModel), + ), + ) + + if err := form.Run(); err != nil { + return "", fmt.Errorf("failed to select model: %w", err) + } + + return selectedModel, nil +} + +// ConvertModelsMapToSlice converts a map of models to a sorted slice of model IDs. +// This is useful for displaying models in a consistent order in UI components. +func ConvertModelsMapToSlice(models map[string]interface{}) []string { + result := make([]string, 0, len(models)) + for modelID := range models { + result = append(result, modelID) + } + + // Sort alphabetically for consistent display + sort.Strings(result) + + return result +} + +// ConvertOpenRouterModelsToInterface converts OpenRouter model map to generic interface map. +// This allows OpenRouter and Cline models to be used with the generic fetching utilities. +func ConvertOpenRouterModelsToInterface(models map[string]*cline.OpenRouterModelInfo) map[string]interface{} { + result := make(map[string]interface{}, len(models)) + for k, v := range models { + result[k] = v + } + return result +} + +// getTerminalHeight returns the terminal height (rows) +func getTerminalHeight() int { + _, height, err := term.GetSize(int(os.Stdout.Fd())) + if err != nil || height <= 0 { + return 25 // safe fallback for non-TTY or errors + } + return height +} + +// calculateSelectHeight computes appropriate height for Select component +// Reserves space for title, search UI, and margins +func calculateSelectHeight() int { + height := getTerminalHeight() + // Reserve ~10 rows for UI chrome (title, search, margins) + visibleRows := height - 10 + // Clamp between 8 (minimum usable) and 25 (maximum before unwieldy) + if visibleRows < 8 { + return 8 + } + if visibleRows > 25 { + return 25 + } + return visibleRows +} diff --git a/cli/pkg/cli/auth/models_list_static.go b/cli/pkg/cli/auth/models_list_static.go new file mode 100644 index 00000000..400b75f6 --- /dev/null +++ b/cli/pkg/cli/auth/models_list_static.go @@ -0,0 +1,69 @@ +package auth + +import ( + "fmt" + "sort" + + "github.com/cline/cli/pkg/generated" + "github.com/cline/grpc-go/cline" +) + +// SupportsStaticModelList returns true if the provider has a predefined static model list +func SupportsStaticModelList(provider cline.ApiProvider) bool { + providerID := GetProviderIDForEnum(provider) + if providerID == "" { + return false + } + + // Check if this provider has static models defined + def, err := generated.GetProviderDefinition(providerID) + if err != nil { + return false + } + + // Return true if provider has models and isn't dynamic-only + // (Dynamic providers like OpenRouter/OpenAI/Ollama fetch from API) + return len(def.Models) > 0 && !def.HasDynamicModels +} + +// FetchStaticModels retrieves the static model list for a provider from generated definitions +// Returns a sorted list of model IDs and a map of model IDs to their info +func FetchStaticModels(provider cline.ApiProvider) ([]string, map[string]generated.ModelInfo, error) { + providerID := GetProviderIDForEnum(provider) + if providerID == "" { + return nil, nil, fmt.Errorf("unknown provider enum: %v", provider) + } + + def, err := generated.GetProviderDefinition(providerID) + if err != nil { + return nil, nil, fmt.Errorf("failed to get provider definition: %w", err) + } + + if len(def.Models) == 0 { + return nil, nil, fmt.Errorf("no models defined for provider %s", providerID) + } + + // Extract model IDs and sort them + modelIDs := make([]string, 0, len(def.Models)) + for modelID := range def.Models { + modelIDs = append(modelIDs, modelID) + } + sort.Strings(modelIDs) + + return modelIDs, def.Models, nil +} + +// GetDefaultModelForProvider returns the default model ID for a provider if one is defined +func GetDefaultModelForProvider(provider cline.ApiProvider) string { + providerID := GetProviderIDForEnum(provider) + if providerID == "" { + return "" + } + + def, err := generated.GetProviderDefinition(providerID) + if err != nil { + return "" + } + + return def.DefaultModelID +} diff --git a/cli/pkg/cli/auth/providers_byo.go b/cli/pkg/cli/auth/providers_byo.go new file mode 100644 index 00000000..fe7ede6e --- /dev/null +++ b/cli/pkg/cli/auth/providers_byo.go @@ -0,0 +1,174 @@ +package auth + +import ( + "fmt" + + "github.com/charmbracelet/huh" + "github.com/cline/grpc-go/cline" +) + +// BYOProviderOption represents a selectable BYO (bring-your-own) provider option +type BYOProviderOption struct { + Name string + Provider cline.ApiProvider +} + +// GetBYOProviderList returns the list of supported BYO providers for CLI configuration. +// This list excludes Cline provider which is handled separately. +func GetBYOProviderList() []BYOProviderOption { + return []BYOProviderOption{ + {Name: "Anthropic", Provider: cline.ApiProvider_ANTHROPIC}, + {Name: "OpenAI", Provider: cline.ApiProvider_OPENAI}, + {Name: "OpenAI Native", Provider: cline.ApiProvider_OPENAI_NATIVE}, + {Name: "OpenRouter", Provider: cline.ApiProvider_OPENROUTER}, + {Name: "X AI (Grok)", Provider: cline.ApiProvider_XAI}, + {Name: "AWS Bedrock", Provider: cline.ApiProvider_BEDROCK}, + {Name: "Google Gemini", Provider: cline.ApiProvider_GEMINI}, + {Name: "Ollama", Provider: cline.ApiProvider_OLLAMA}, + } +} + +// SelectBYOProvider displays a menu for selecting a BYO provider. +func SelectBYOProvider() (cline.ApiProvider, error) { + providers := GetBYOProviderList() + var selectedIndex int + + options := make([]huh.Option[int], len(providers)+1) + for i, provider := range providers { + options[i] = huh.NewOption(provider.Name, i) + } + options[len(providers)] = huh.NewOption("(Cancel)", -1) + + form := huh.NewForm( + huh.NewGroup( + huh.NewSelect[int](). + Title("Select an API provider"). + Options(options...). + Value(&selectedIndex), + ), + ) + + if err := form.Run(); err != nil { + return 0, fmt.Errorf("failed to select provider: %w", err) + } + + if selectedIndex == -1 { + return 0, fmt.Errorf("provider selection cancelled") + } + + return providers[selectedIndex].Provider, nil +} + +// SupportsBYOModelFetching returns true if the provider supports fetching models dynamically +// from a remote API, or if it has a static list of predefined models. +// This is used to determine whether to show a model list before prompting for manual entry. +func SupportsBYOModelFetching(provider cline.ApiProvider) bool { + switch provider { + case cline.ApiProvider_OPENROUTER: + return true + case cline.ApiProvider_OPENAI: + return true + case cline.ApiProvider_OLLAMA: + return true + } + + return SupportsStaticModelList(provider) +} + +// GetBYOProviderPlaceholder returns a placeholder model ID for manual entry based on provider. +func GetBYOProviderPlaceholder(provider cline.ApiProvider) string { + switch provider { + case cline.ApiProvider_ANTHROPIC: + return "e.g., claude-sonnet-4-5-20250929" + case cline.ApiProvider_OPENAI: + return "e.g., gpt-5-2025-08-07" + case cline.ApiProvider_OPENAI_NATIVE: + return "e.g., openai/gpt-oss-120b" + case cline.ApiProvider_OPENROUTER: + return "e.g., google/gemini-2.0-flash-exp:free" + case cline.ApiProvider_XAI: + return "e.g., grok-code-fast-1" + case cline.ApiProvider_BEDROCK: + return "e.g., anthropic.claude-sonnet-4-5-20250929-v1:0" + case cline.ApiProvider_GEMINI: + return "e.g., gemini-2.5-pro" + case cline.ApiProvider_OLLAMA: + return "e.g., qwen3-coder:30b" + default: + return "Enter model ID" + } +} + +// GetBYOAPIKeyFieldConfig returns field configuration for API key input based on provider. +type APIKeyFieldConfig struct { + Title string + EchoMode huh.EchoMode + IsRequired bool +} + +// GetBYOAPIKeyFieldConfig returns the configuration for the API key field based on provider. +func GetBYOAPIKeyFieldConfig(provider cline.ApiProvider) APIKeyFieldConfig { + if provider == cline.ApiProvider_OLLAMA { + return APIKeyFieldConfig{ + Title: "Base URL (optional, press Enter for default)", + EchoMode: huh.EchoModeNormal, + IsRequired: false, + } + } + + return APIKeyFieldConfig{ + Title: "API Key", + EchoMode: huh.EchoModePassword, + IsRequired: true, + } +} + +// PromptForAPIKey prompts the user to enter an API key (or base URL for Ollama). +// For OpenAI Native provider, also prompts for an optional base URL. +func PromptForAPIKey(provider cline.ApiProvider) (string, error) { + var apiKey string + config := GetBYOAPIKeyFieldConfig(provider) + + apiKeyField := huh.NewInput(). + Title(config.Title). + EchoMode(config.EchoMode). + Value(&apiKey) + + if config.IsRequired { + apiKeyField = apiKeyField.Validate(func(s string) error { + if s == "" { + return fmt.Errorf("API key cannot be empty") + } + return nil + }) + } + + form := huh.NewForm(huh.NewGroup(apiKeyField)) + + if err := form.Run(); err != nil { + return "", fmt.Errorf("failed to get API key: %w", err) + } + + // For OpenAI Native provider, also prompt for base URL + if provider == cline.ApiProvider_OPENAI_NATIVE { + var baseURL string + baseURLForm := huh.NewForm( + huh.NewGroup( + huh.NewInput(). + Title("Base URL (optional, for OpenAI-compatible providers)"). + Placeholder("e.g., https://api.example.com/v1"). + Value(&baseURL). + Description("Press Enter to skip if using standard OpenAI API"), + ), + ) + + if err := baseURLForm.Run(); err != nil { + return "", fmt.Errorf("failed to get base URL: %w", err) + } + + // TODO - connect baseURL + _ = baseURL + } + + return apiKey, nil +} diff --git a/cli/pkg/cli/auth/providers_list.go b/cli/pkg/cli/auth/providers_list.go new file mode 100644 index 00000000..f5a131b3 --- /dev/null +++ b/cli/pkg/cli/auth/providers_list.go @@ -0,0 +1,469 @@ +package auth + +import ( + "context" + "encoding/json" + "fmt" + "strings" + + "github.com/cline/cli/pkg/cli/global" + "github.com/cline/cli/pkg/cli/task" + "github.com/cline/grpc-go/cline" +) + +// ProviderDisplay represents a configured provider for display purposes +type ProviderDisplay struct { + Mode string // "Plan" or "Act" + Provider cline.ApiProvider // Provider enum + ModelID string // Model identifier + HasAPIKey bool // Whether an API key is configured (never show actual key) + BaseURL string // Base URL for providers like Ollama (can be shown publicly) +} + +// ProviderListResult holds the parsed provider configuration from state +type ProviderListResult struct { + PlanProvider *ProviderDisplay + ActProvider *ProviderDisplay + apiConfig map[string]interface{} // Store the raw apiConfig for scanning all providers +} + +// GetProviderConfigurations retrieves and parses provider configurations from Cline Core state +func GetProviderConfigurations(ctx context.Context, manager *task.Manager) (*ProviderListResult, error) { + if global.Config.Verbose { + fmt.Println("[DEBUG] Retrieving provider configurations from Cline Core") + } + + // Get latest state from Cline Core + state, err := manager.GetClient().State.GetLatestState(ctx, &cline.EmptyRequest{}) + if err != nil { + return nil, fmt.Errorf("failed to get state: %w", err) + } + + stateJSON := state.StateJson + + if global.Config.Verbose { + fmt.Printf("[DEBUG] Retrieved state, parsing JSON (length: %d)\n", len(stateJSON)) + } + + // Parse state_json as map[string]interface{} + var stateData map[string]interface{} + if err := json.Unmarshal([]byte(stateJSON), &stateData); err != nil { + return nil, fmt.Errorf("failed to parse state JSON: %w", err) + } + + if global.Config.Verbose { + fmt.Printf("[DEBUG] Parsed state data with %d keys\n", len(stateData)) + } + + // Extract apiConfiguration object from state + apiConfig, ok := stateData["apiConfiguration"].(map[string]interface{}) + if !ok { + if global.Config.Verbose { + fmt.Println("[DEBUG] No apiConfiguration found in state") + } + return &ProviderListResult{ + apiConfig: make(map[string]interface{}), + }, nil + } + + if global.Config.Verbose { + fmt.Printf("[DEBUG] Found apiConfiguration with %d keys\n", len(apiConfig)) + } + + // Extract plan mode configuration + planProvider := extractProviderFromState(apiConfig, "plan") + if global.Config.Verbose && planProvider != nil { + fmt.Printf("[DEBUG] Plan mode: provider=%v, model=%s\n", planProvider.Provider, planProvider.ModelID) + } + + // Extract act mode configuration + actProvider := extractProviderFromState(apiConfig, "act") + if global.Config.Verbose && actProvider != nil { + fmt.Printf("[DEBUG] Act mode: provider=%v, model=%s\n", actProvider.Provider, actProvider.ModelID) + } + + return &ProviderListResult{ + PlanProvider: planProvider, + ActProvider: actProvider, + apiConfig: apiConfig, + }, nil +} + +// GetAllReadyProviders returns all providers that have both a model and API key configured +func (r *ProviderListResult) GetAllReadyProviders() []*ProviderDisplay { + if r.apiConfig == nil { + return []*ProviderDisplay{} + } + + var readyProviders []*ProviderDisplay + seenProviders := make(map[cline.ApiProvider]bool) + + // Check all possible providers + allProviders := []cline.ApiProvider{ + cline.ApiProvider_CLINE, + cline.ApiProvider_ANTHROPIC, + cline.ApiProvider_OPENAI, + cline.ApiProvider_OPENAI_NATIVE, + cline.ApiProvider_OPENROUTER, + cline.ApiProvider_XAI, + cline.ApiProvider_BEDROCK, + cline.ApiProvider_GEMINI, + cline.ApiProvider_OLLAMA, + } + + // Check each provider to see if it's ready to use + // We use "plan" mode to check, since both plan and act should have the same providers configured + for _, provider := range allProviders { + // Skip if we've already seen this provider + if seenProviders[provider] { + continue + } + + // Check if this provider has an API key + hasAPIKey := checkAPIKeyExists(r.apiConfig, provider) + if !hasAPIKey { + continue + } + + // Check if this provider has a model configured + modelID := getProviderSpecificModelID(r.apiConfig, "plan", provider) + if modelID == "" { + continue + } + + // Get base URL for Ollama + baseURL := "" + if provider == cline.ApiProvider_OLLAMA { + if url, ok := r.apiConfig["ollamaBaseUrl"].(string); ok { + baseURL = url + } + } + + // This provider is ready to use + readyProviders = append(readyProviders, &ProviderDisplay{ + Mode: "Ready", + Provider: provider, + ModelID: modelID, + HasAPIKey: hasAPIKey, + BaseURL: baseURL, + }) + seenProviders[provider] = true + } + + return readyProviders +} + +// extractProviderFromState extracts provider configuration for specific plan/act mode +func extractProviderFromState(stateData map[string]interface{}, mode string) *ProviderDisplay { + // Build key names based on mode + providerKey := mode + "ModeApiProvider" + + // Extract provider string from state + providerStr, ok := stateData[providerKey].(string) + if !ok || providerStr == "" { + if global.Config.Verbose { + fmt.Printf("[DEBUG] No provider configured for %s mode\n", mode) + } + return nil + } + + // Map provider string to enum + provider, ok := mapProviderStringToEnum(providerStr) + if !ok { + if global.Config.Verbose { + fmt.Printf("[DEBUG] Unknown provider type: %s\n", providerStr) + } + return nil + } + + // Get provider-specific model ID + modelID := getProviderSpecificModelID(stateData, mode, provider) + + // Check if API key exists + hasAPIKey := checkAPIKeyExists(stateData, provider) + + // Get base URL for Ollama (can be shown publicly) + baseURL := "" + if provider == cline.ApiProvider_OLLAMA { + if url, ok := stateData["ollamaBaseUrl"].(string); ok { + baseURL = url + } + } + + return &ProviderDisplay{ + Mode: capitalizeMode(mode), + Provider: provider, + ModelID: modelID, + HasAPIKey: hasAPIKey, + BaseURL: baseURL, + } +} + +// mapProviderStringToEnum converts provider string from state to ApiProvider enum +// Returns (provider, ok) where ok is false if the provider is unknown +func mapProviderStringToEnum(providerStr string) (cline.ApiProvider, bool) { + // Map string values to enum values + switch providerStr { + case "anthropic": + return cline.ApiProvider_ANTHROPIC, true + case "openai": + return cline.ApiProvider_OPENAI, true + case "openai-native": + return cline.ApiProvider_OPENAI_NATIVE, true + case "openrouter": + return cline.ApiProvider_OPENROUTER, true + case "xai": + return cline.ApiProvider_XAI, true + case "bedrock": + return cline.ApiProvider_BEDROCK, true + case "gemini": + return cline.ApiProvider_GEMINI, true + case "ollama": + return cline.ApiProvider_OLLAMA, true + case "cline": + return cline.ApiProvider_CLINE, true + default: + return cline.ApiProvider_ANTHROPIC, false // Return 0 value with false + } +} + +// GetProviderIDForEnum converts a provider enum to the provider ID string +// This is the inverse of mapProviderStringToEnum and is used for provider definitions +func GetProviderIDForEnum(provider cline.ApiProvider) string { + switch provider { + case cline.ApiProvider_ANTHROPIC: + return "anthropic" + case cline.ApiProvider_OPENAI: + return "openai" + case cline.ApiProvider_OPENAI_NATIVE: + return "openai-native" + case cline.ApiProvider_OPENROUTER: + return "openrouter" + case cline.ApiProvider_XAI: + return "xai" + case cline.ApiProvider_BEDROCK: + return "bedrock" + case cline.ApiProvider_GEMINI: + return "gemini" + case cline.ApiProvider_OLLAMA: + return "ollama" + case cline.ApiProvider_CLINE: + return "cline" + default: + return "" + } +} + +// getProviderSpecificModelID gets the provider-specific model ID field from state +func getProviderSpecificModelID(stateData map[string]interface{}, mode string, provider cline.ApiProvider) string { + modelKey, err := GetModelIDFieldName(provider, mode) + if err != nil { + if global.Config.Verbose { + fmt.Printf("[DEBUG] Error getting model ID field name: %v\n", err) + } + return "" + } + + if global.Config.Verbose { + fmt.Printf("[DEBUG] Looking for model ID in key: %s\n", modelKey) + } + + // Extract model ID from state + modelID, _ := stateData[modelKey].(string) + return modelID +} + +// checkAPIKeyExists checks if API key field exists in state (never retrieve actual key) +func checkAPIKeyExists(stateData map[string]interface{}, provider cline.ApiProvider) bool { + // Get field mapping from centralized function + fields, err := GetProviderFields(provider) + if err != nil { + return false + } + + keyField := fields.APIKeyField + + // Check if the key exists and is not empty + if value, ok := stateData[keyField]; ok { + if str, ok := value.(string); ok && str != "" { + return true + } + } + + return false +} + +// capitalizeMode capitalizes the mode string for display +func capitalizeMode(mode string) string { + if len(mode) == 0 { + return mode + } + return strings.ToUpper(mode[:1]) + mode[1:] +} + +// getProviderDisplayName returns a user-friendly name for the provider +func getProviderDisplayName(provider cline.ApiProvider) string { + switch provider { + case cline.ApiProvider_ANTHROPIC: + return "Anthropic" + case cline.ApiProvider_OPENAI: + return "OpenAI" + case cline.ApiProvider_OPENAI_NATIVE: + return "OpenAI Native" + case cline.ApiProvider_OPENROUTER: + return "OpenRouter" + case cline.ApiProvider_XAI: + return "X AI (Grok)" + case cline.ApiProvider_BEDROCK: + return "AWS Bedrock" + case cline.ApiProvider_GEMINI: + return "Google Gemini" + case cline.ApiProvider_OLLAMA: + return "Ollama" + case cline.ApiProvider_CLINE: + return "Cline (Official)" + default: + return "Unknown" + } +} + +// FormatProviderList formats the complete provider list for console display +// This now shows ALL providers that have both a model and API key configured +func FormatProviderList(result *ProviderListResult) string { + var output strings.Builder + + output.WriteString("\n=== Configured API Providers ===\n\n") + + // Get the currently active provider + var activeProvider cline.ApiProvider + var activeProviderSet bool + if result.ActProvider != nil { + activeProvider = result.ActProvider.Provider + activeProviderSet = true + } + + // Get all ready-to-use providers (those with both API key and model configured) + readyProviders := result.GetAllReadyProviders() + + if len(readyProviders) == 0 { + output.WriteString(" No providers ready to use.\n") + output.WriteString(" A provider is ready when it has both a model and API key configured.\n") + output.WriteString(" Use 'Configure a new provider' to configure one.\n\n") + } else { + //output.WriteString(fmt.Sprintf(" %d provider(s) ready to use:\n\n", len(readyProviders))) + + for _, display := range readyProviders { + // Check if this is the active provider + isActive := activeProviderSet && display.Provider == activeProvider + + if isActive { + output.WriteString(fmt.Sprintf(" ✓ %s (ACTIVE)\n", getProviderDisplayName(display.Provider))) + } else { + output.WriteString(fmt.Sprintf(" • %s\n", getProviderDisplayName(display.Provider))) + } + + output.WriteString(fmt.Sprintf(" Model: %s\n", display.ModelID)) + + // Show status based on provider type + if display.Provider == cline.ApiProvider_OLLAMA { + if display.BaseURL != "" { + output.WriteString(fmt.Sprintf(" Base URL: %s\n", display.BaseURL)) + } else { + output.WriteString(" Base URL: (default)\n") + } + } else if display.Provider == cline.ApiProvider_CLINE { + output.WriteString(" Status: Authenticated\n") + } else { + output.WriteString(" API Key: Configured\n") + } + + output.WriteString("\n") + } + } + + output.WriteString("================================\n") + + return output.String() +} + +// DetectAllConfiguredProviders scans the state to find all providers that have API keys configured. +// This allows switching between multiple providers even when only one is currently active. +func DetectAllConfiguredProviders(ctx context.Context, manager *task.Manager) ([]cline.ApiProvider, error) { + verboseLog("[DEBUG] Detecting all configured providers...") + + // Get latest state from Cline Core + state, err := manager.GetClient().State.GetLatestState(ctx, &cline.EmptyRequest{}) + if err != nil { + return nil, fmt.Errorf("failed to get state: %w", err) + } + + stateJSON := state.StateJson + + // Parse state_json as map[string]interface{} + var stateData map[string]interface{} + if err := json.Unmarshal([]byte(stateJSON), &stateData); err != nil { + return nil, fmt.Errorf("failed to parse state JSON: %w", err) + } + + // Extract apiConfiguration object from state + apiConfig, ok := stateData["apiConfiguration"].(map[string]interface{}) + if !ok { + verboseLog("[DEBUG] No apiConfiguration found in state") + verboseLog("[DEBUG] Available keys in stateData: %v", getMapKeys(stateData)) + return []cline.ApiProvider{}, nil + } + + verboseLog("[DEBUG] apiConfiguration keys: %v", getMapKeys(apiConfig)) + + var configuredProviders []cline.ApiProvider + + // Check for Cline provider (uses authentication instead of API key) + if IsAuthenticated(ctx) { + configuredProviders = append(configuredProviders, cline.ApiProvider_CLINE) + verboseLog("[DEBUG] Cline provider is authenticated") + } + + // Check each BYO provider for API key presence + providersToCheck := []struct { + provider cline.ApiProvider + keyField string + }{ + {cline.ApiProvider_ANTHROPIC, "apiKey"}, + {cline.ApiProvider_OPENAI, "openAiApiKey"}, + {cline.ApiProvider_OPENAI_NATIVE, "openAiNativeApiKey"}, + {cline.ApiProvider_OPENROUTER, "openRouterApiKey"}, + {cline.ApiProvider_XAI, "xaiApiKey"}, + {cline.ApiProvider_BEDROCK, "awsAccessKey"}, + {cline.ApiProvider_GEMINI, "geminiApiKey"}, + {cline.ApiProvider_OLLAMA, "ollamaBaseUrl"}, // Ollama uses baseUrl instead of API key + } + + for _, providerCheck := range providersToCheck { + verboseLog("[DEBUG] Checking for %s key: %s", getProviderDisplayName(providerCheck.provider), providerCheck.keyField) + if value, ok := apiConfig[providerCheck.keyField]; ok { + verboseLog("[DEBUG] Found key, value type: %T, is empty: %v", value, value == "") + if str, ok := value.(string); ok && str != "" { + configuredProviders = append(configuredProviders, providerCheck.provider) + verboseLog("[DEBUG] ✓ Provider %s is configured", getProviderDisplayName(providerCheck.provider)) + } + } else { + verboseLog("[DEBUG] Key %s not found", providerCheck.keyField) + } + } + + verboseLog("[DEBUG] Total configured providers: %d", len(configuredProviders)) + for _, p := range configuredProviders { + verboseLog("[DEBUG] - %s", getProviderDisplayName(p)) + } + + return configuredProviders, nil +} + +// getMapKeys returns the keys of a map for debugging +func getMapKeys(m map[string]interface{}) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + return keys +} diff --git a/cli/pkg/cli/auth/update_api_configurations.go b/cli/pkg/cli/auth/update_api_configurations.go new file mode 100644 index 00000000..78892542 --- /dev/null +++ b/cli/pkg/cli/auth/update_api_configurations.go @@ -0,0 +1,500 @@ +package auth + +import ( + "context" + "fmt" + + "github.com/cline/cli/pkg/cli/global" + "github.com/cline/cli/pkg/cli/task" + "github.com/cline/grpc-go/cline" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/fieldmaskpb" +) + +// updateApiConfigurationPartial is a helper that calls the gRPC method with optional verbose logging. +// This replaces the Manager.UpdateApiConfigurationPartial method to keep auth-specific code in the auth package. +func updateApiConfigurationPartial(ctx context.Context, manager *task.Manager, request *cline.UpdateApiConfigurationPartialRequest) error { + if global.Config.Verbose { + fmt.Println("[DEBUG] Updating API configuration (partial)") + if request.UpdateMask != nil && len(request.UpdateMask.Paths) > 0 { + fmt.Printf("[DEBUG] Field mask paths: %v\n", request.UpdateMask.Paths) + } + if request.ApiConfiguration != nil { + apiConfig := request.ApiConfiguration + if apiConfig.PlanModeApiProvider != nil { + fmt.Printf("[DEBUG] Plan mode provider: %s\n", *apiConfig.PlanModeApiProvider) + } + if apiConfig.ActModeApiProvider != nil { + fmt.Printf("[DEBUG] Act mode provider: %s\n", *apiConfig.ActModeApiProvider) + } + } + } + + // Call the Models service to update API configuration + _, err := manager.GetClient().Models.UpdateApiConfigurationPartial(ctx, request) + if err != nil { + return fmt.Errorf("failed to update API configuration (partial): %w", err) + } + + if global.Config.Verbose { + fmt.Println("[DEBUG] API configuration updated successfully (partial)") + } + + return nil +} + +// ProviderFields defines all the field names associated with a specific provider +type ProviderFields struct { + APIKeyField string // API key field name (e.g., "apiKey", "openAiApiKey") + PlanModeModelIDField string // Plan mode model ID field (e.g., "planModeApiModelId") + ActModeModelIDField string // Act mode model ID field (e.g., "actModeApiModelId") + PlanModeModelInfoField string // Plan mode model info field (optional, empty if not applicable) + ActModeModelInfoField string // Act mode model info field (optional, empty if not applicable) + // Provider-specific additional model ID fields + PlanModeProviderSpecificModelIDField string // e.g., "planModeOpenRouterModelId" + ActModeProviderSpecificModelIDField string // e.g., "actModeOpenRouterModelId" +} + +// GetProviderFields returns the field mapping for a given provider +func GetProviderFields(provider cline.ApiProvider) (ProviderFields, error) { + switch provider { + case cline.ApiProvider_ANTHROPIC: + return ProviderFields{ + APIKeyField: "apiKey", + PlanModeModelIDField: "planModeApiModelId", + ActModeModelIDField: "actModeApiModelId", + }, nil + + case cline.ApiProvider_OPENAI: + return ProviderFields{ + APIKeyField: "openAiApiKey", + PlanModeModelIDField: "planModeApiModelId", + ActModeModelIDField: "actModeApiModelId", + PlanModeProviderSpecificModelIDField: "planModeOpenAiModelId", + ActModeProviderSpecificModelIDField: "actModeOpenAiModelId", + }, nil + + case cline.ApiProvider_OPENROUTER: + return ProviderFields{ + APIKeyField: "openRouterApiKey", + PlanModeModelIDField: "planModeApiModelId", + ActModeModelIDField: "actModeApiModelId", + PlanModeModelInfoField: "planModeOpenRouterModelInfo", + ActModeModelInfoField: "actModeOpenRouterModelInfo", + PlanModeProviderSpecificModelIDField: "planModeOpenRouterModelId", + ActModeProviderSpecificModelIDField: "actModeOpenRouterModelId", + }, nil + + case cline.ApiProvider_XAI: + return ProviderFields{ + APIKeyField: "xaiApiKey", + PlanModeModelIDField: "planModeApiModelId", + ActModeModelIDField: "actModeApiModelId", + }, nil + + case cline.ApiProvider_BEDROCK: + return ProviderFields{ + APIKeyField: "awsAccessKey", + PlanModeModelIDField: "planModeApiModelId", + ActModeModelIDField: "actModeApiModelId", + PlanModeProviderSpecificModelIDField: "planModeAwsBedrockCustomModelBaseId", + ActModeProviderSpecificModelIDField: "actModeAwsBedrockCustomModelBaseId", + }, nil + + case cline.ApiProvider_GEMINI: + return ProviderFields{ + APIKeyField: "geminiApiKey", + PlanModeModelIDField: "planModeApiModelId", + ActModeModelIDField: "actModeApiModelId", + }, nil + + case cline.ApiProvider_OPENAI_NATIVE: + return ProviderFields{ + APIKeyField: "openAiNativeApiKey", + PlanModeModelIDField: "planModeApiModelId", + ActModeModelIDField: "actModeApiModelId", + }, nil + + case cline.ApiProvider_OLLAMA: + return ProviderFields{ + APIKeyField: "ollamaBaseUrl", + PlanModeModelIDField: "planModeApiModelId", + ActModeModelIDField: "actModeApiModelId", + PlanModeProviderSpecificModelIDField: "planModeOllamaModelId", + ActModeProviderSpecificModelIDField: "actModeOllamaModelId", + }, nil + + case cline.ApiProvider_CLINE: + return ProviderFields{ + APIKeyField: "clineApiKey", + PlanModeModelIDField: "planModeApiModelId", + ActModeModelIDField: "actModeApiModelId", + PlanModeModelInfoField: "planModeOpenRouterModelInfo", + ActModeModelInfoField: "actModeOpenRouterModelInfo", + PlanModeProviderSpecificModelIDField: "planModeOpenRouterModelId", + ActModeProviderSpecificModelIDField: "actModeOpenRouterModelId", + }, nil + + default: + return ProviderFields{}, fmt.Errorf("unsupported provider: %v", provider) + } +} + +// ProviderUpdatesPartial defines optional fields for partial provider updates +// Uses pointers to distinguish between "not provided" and "set to empty" +type ProviderUpdatesPartial struct { + ModelID *string // New model ID (optional) + APIKey *string // New API key (optional) + ModelInfo interface{} // New model info (optional, provider-specific) +} + +// GetModelIDFieldName returns the appropriate model ID field name for a provider and mode. +// This helper centralizes the logic for determining whether to use provider-specific +// or generic model ID fields. +func GetModelIDFieldName(provider cline.ApiProvider, mode string) (string, error) { + fields, err := GetProviderFields(provider) + if err != nil { + return "", err + } + + if mode == "plan" { + // Use provider-specific field if available, otherwise use generic field + if fields.PlanModeProviderSpecificModelIDField != "" { + return fields.PlanModeProviderSpecificModelIDField, nil + } + return fields.PlanModeModelIDField, nil + } + + // Act mode + if fields.ActModeProviderSpecificModelIDField != "" { + return fields.ActModeProviderSpecificModelIDField, nil + } + return fields.ActModeModelIDField, nil +} + +// buildProviderFieldMask builds a list of camelCase field paths for the field mask. +// When includeProviderEnums is true, the provider enum fields are included (for setting active provider). +// When false, only the data fields are included (for configuring without activating). +func buildProviderFieldMask(fields ProviderFields, includeAPIKey bool, includeModelID bool, includeModelInfo bool, includeProviderEnums bool) []string { + var fieldPaths []string + + // Include provider enums if requested (used when setting active provider) + if includeProviderEnums { + fieldPaths = append(fieldPaths, "planModeApiProvider", "actModeApiProvider") + } + + // Add API key field if requested + if includeAPIKey { + fieldPaths = append(fieldPaths, fields.APIKeyField) + // Special case: Bedrock also needs secret key + if fields.APIKeyField == "awsAccessKey" { + fieldPaths = append(fieldPaths, "awsSecretKey") + } + } + + // Add model ID fields if requested + if includeModelID { + // Only include provider-specific fields if they exist, otherwise use generic fields + if fields.PlanModeProviderSpecificModelIDField != "" { + // Provider has specific fields - use ONLY those + fieldPaths = append(fieldPaths, fields.PlanModeProviderSpecificModelIDField) + fieldPaths = append(fieldPaths, fields.ActModeProviderSpecificModelIDField) + } else { + // Provider uses generic fields - update those + fieldPaths = append(fieldPaths, fields.PlanModeModelIDField) + fieldPaths = append(fieldPaths, fields.ActModeModelIDField) + } + } + + // Add model info fields if requested and applicable + if includeModelInfo && fields.PlanModeModelInfoField != "" { + fieldPaths = append(fieldPaths, fields.PlanModeModelInfoField) + fieldPaths = append(fieldPaths, fields.ActModeModelInfoField) + } + + return fieldPaths +} + +// setAPIKeyField sets the appropriate API key field in the config based on the field name +func setAPIKeyField(apiConfig *cline.ModelsApiConfiguration, fieldName string, value *string) { + switch fieldName { + case "apiKey": + apiConfig.ApiKey = value + case "openAiApiKey": + apiConfig.OpenAiApiKey = value + case "openAiNativeApiKey": + apiConfig.OpenAiNativeApiKey = value + case "openRouterApiKey": + apiConfig.OpenRouterApiKey = value + case "xaiApiKey": + apiConfig.XaiApiKey = value + case "awsAccessKey": + apiConfig.AwsAccessKey = value + case "geminiApiKey": + apiConfig.GeminiApiKey = value + case "ollamaBaseUrl": + apiConfig.OllamaBaseUrl = value + case "clineApiKey": + apiConfig.ClineApiKey = value + } +} + +// setProviderSpecificModelID sets the appropriate provider-specific model ID fields when possible +func setProviderSpecificModelID(apiConfig *cline.ModelsApiConfiguration, fieldName string, value *string) { + switch fieldName { + case "planModeOpenAiModelId": + apiConfig.PlanModeOpenAiModelId = value + apiConfig.ActModeOpenAiModelId = value + case "planModeOpenRouterModelId": + apiConfig.PlanModeOpenRouterModelId = value + apiConfig.ActModeOpenRouterModelId = value + case "planModeOllamaModelId": + apiConfig.PlanModeOllamaModelId = value + apiConfig.ActModeOllamaModelId = value + case "planModeAwsBedrockCustomModelBaseId": + apiConfig.PlanModeAwsBedrockCustomModelBaseId = value + apiConfig.ActModeAwsBedrockCustomModelBaseId = value + } +} + +// AddProviderPartial configures a new provider with all necessary fields using partial updates. +func AddProviderPartial(ctx context.Context, manager *task.Manager, provider cline.ApiProvider, modelID string, apiKey string, modelInfo interface{}) error { + // Get field mapping for this provider + fields, err := GetProviderFields(provider) + if err != nil { + return err + } + + // Build a ModelsApiConfiguration with only the relevant provider fields set + apiConfig := &cline.ModelsApiConfiguration{} + + // Set API key field + if apiKey != "" || fields.APIKeyField != "ollamaBaseUrl" { + setAPIKeyField(apiConfig, fields.APIKeyField, proto.String(apiKey)) + } + + // Set model ID fields + apiConfig.PlanModeApiModelId = proto.String(modelID) + apiConfig.ActModeApiModelId = proto.String(modelID) + + // Set provider-specific model ID fields if applicable + if fields.PlanModeProviderSpecificModelIDField != "" { + setProviderSpecificModelID(apiConfig, fields.PlanModeProviderSpecificModelIDField, proto.String(modelID)) + } + + // Set model info if applicable and provided + if fields.PlanModeModelInfoField != "" && modelInfo != nil { + if openRouterInfo, ok := modelInfo.(*cline.OpenRouterModelInfo); ok { + apiConfig.PlanModeOpenRouterModelInfo = openRouterInfo + apiConfig.ActModeOpenRouterModelInfo = openRouterInfo + } + } + + // Build field mask including all fields we're setting (without provider enums) + includeModelInfo := fields.PlanModeModelInfoField != "" && modelInfo != nil + fieldPaths := buildProviderFieldMask(fields, true, true, includeModelInfo, false) + + // Create field mask + fieldMask := &fieldmaskpb.FieldMask{Paths: fieldPaths} + + // Apply the partial update + request := &cline.UpdateApiConfigurationPartialRequest{ + ApiConfiguration: apiConfig, + UpdateMask: fieldMask, + } + + if err := updateApiConfigurationPartial(ctx, manager, request); err != nil { + return fmt.Errorf("failed to update API configuration: %w", err) + } + + return nil +} + +// UpdateProviderPartial updates specific fields for an existing provider using partial updates. +// If setAsActive is true, this will also set the provider as the active provider for both Plan and Act modes. +func UpdateProviderPartial(ctx context.Context, manager *task.Manager, provider cline.ApiProvider, updates ProviderUpdatesPartial, setAsActive bool) error { + // Get field mapping for this provider + fields, err := GetProviderFields(provider) + if err != nil { + return err + } + + // Build a ModelsApiConfiguration with only the fields being updated + apiConfig := &cline.ModelsApiConfiguration{} + + // Set provider enum for BOTH Plan and Act modes if setAsActive is true + if setAsActive { + apiConfig.PlanModeApiProvider = &provider + apiConfig.ActModeApiProvider = &provider + } + + // Track what we're updating for field mask + includeAPIKey := updates.APIKey != nil + includeModelID := updates.ModelID != nil + includeModelInfo := updates.ModelInfo != nil && fields.PlanModeModelInfoField != "" + + // Update API key if provided + if updates.APIKey != nil { + setAPIKeyField(apiConfig, fields.APIKeyField, updates.APIKey) + } + + // Update model ID if provided + if updates.ModelID != nil { + // Only set provider-specific fields if they exist, otherwise use generic fields + if fields.PlanModeProviderSpecificModelIDField != "" { + setProviderSpecificModelID(apiConfig, fields.PlanModeProviderSpecificModelIDField, updates.ModelID) + } else { + // Provider uses generic fields - set those + apiConfig.PlanModeApiModelId = updates.ModelID + apiConfig.ActModeApiModelId = updates.ModelID + } + } + + // Update model info if provided + if updates.ModelInfo != nil && fields.PlanModeModelInfoField != "" { + if openRouterInfo, ok := updates.ModelInfo.(*cline.OpenRouterModelInfo); ok { + apiConfig.PlanModeOpenRouterModelInfo = openRouterInfo + apiConfig.ActModeOpenRouterModelInfo = openRouterInfo + } + } + + // Build field mask for only the fields being updated + fieldPaths := buildProviderFieldMask(fields, includeAPIKey, includeModelID, includeModelInfo, setAsActive) + + // Create field mask + fieldMask := &fieldmaskpb.FieldMask{Paths: fieldPaths} + + // Apply the partial update + request := &cline.UpdateApiConfigurationPartialRequest{ + ApiConfiguration: apiConfig, + UpdateMask: fieldMask, + } + + if err := updateApiConfigurationPartial(ctx, manager, request); err != nil { + return fmt.Errorf("failed to update API configuration: %w", err) + } + + return nil +} + +// RemoveProviderPartial removes a provider by clearing its API key using partial updates +func RemoveProviderPartial(ctx context.Context, manager *task.Manager, provider cline.ApiProvider) error { + // Get field mapping for this provider + fields, err := GetProviderFields(provider) + if err != nil { + return err + } + + // Build an EMPTY ModelsApiConfiguration (or one with empty API key field) + // Fields in the mask without values will be cleared + apiConfig := &cline.ModelsApiConfiguration{} + + // Build field mask with only the API key field(s) + // For Bedrock, include both access key and secret key + fieldPaths := []string{fields.APIKeyField} + if provider == cline.ApiProvider_BEDROCK { + fieldPaths = append(fieldPaths, "awsSecretKey") + } + + // Create field mask + fieldMask := &fieldmaskpb.FieldMask{Paths: fieldPaths} + + // Apply the partial update (clearing API key by including in mask without value) + request := &cline.UpdateApiConfigurationPartialRequest{ + ApiConfiguration: apiConfig, + UpdateMask: fieldMask, + } + + if err := updateApiConfigurationPartial(ctx, manager, request); err != nil { + return fmt.Errorf("failed to update API configuration: %w", err) + } + + return nil +} + +// BedrockOptionalFields holds optional configuration fields for AWS Bedrock +type BedrockOptionalFields struct { + SessionToken *string // Optional: AWS session token for temporary credentials + Region *string // Optional: AWS region + UseCrossRegionInference *bool // Optional: Enable cross-region inference + UseGlobalInference *bool // Optional: Use global inference endpoint + UsePromptCache *bool // Optional: Enable prompt caching + Authentication *string // Optional: Authentication method + UseProfile *bool // Optional: Use AWS profile + Profile *string // Optional: AWS profile name + Endpoint *string // Optional: Custom endpoint URL +} + +// setBedrockOptionalFields sets optional Bedrock-specific fields in the API configuration +func setBedrockOptionalFields(apiConfig *cline.ModelsApiConfiguration, fields *BedrockOptionalFields) { + if fields == nil { + return + } + + if fields.SessionToken != nil { + apiConfig.AwsSessionToken = fields.SessionToken + } + if fields.Region != nil { + apiConfig.AwsRegion = fields.Region + } + if fields.UseCrossRegionInference != nil { + apiConfig.AwsUseCrossRegionInference = fields.UseCrossRegionInference + } + if fields.UseGlobalInference != nil { + apiConfig.AwsUseGlobalInference = fields.UseGlobalInference + } + if fields.UsePromptCache != nil { + apiConfig.AwsBedrockUsePromptCache = fields.UsePromptCache + } + if fields.Authentication != nil { + apiConfig.AwsAuthentication = fields.Authentication + } + if fields.UseProfile != nil { + apiConfig.AwsUseProfile = fields.UseProfile + } + if fields.Profile != nil { + apiConfig.AwsProfile = fields.Profile + } + if fields.Endpoint != nil { + apiConfig.AwsBedrockEndpoint = fields.Endpoint + } +} + +// buildBedrockOptionalFieldMask builds field mask paths for Bedrock optional fields that have values +func buildBedrockOptionalFieldMask(fields *BedrockOptionalFields) []string { + if fields == nil { + return nil + } + + var fieldPaths []string + + if fields.SessionToken != nil { + fieldPaths = append(fieldPaths, "awsSessionToken") + } + if fields.Region != nil { + fieldPaths = append(fieldPaths, "awsRegion") + } + if fields.UseCrossRegionInference != nil { + fieldPaths = append(fieldPaths, "awsUseCrossRegionInference") + } + if fields.UseGlobalInference != nil { + fieldPaths = append(fieldPaths, "awsUseGlobalInference") + } + if fields.UsePromptCache != nil { + fieldPaths = append(fieldPaths, "awsBedrockUsePromptCache") + } + if fields.Authentication != nil { + fieldPaths = append(fieldPaths, "awsAuthentication") + } + if fields.UseProfile != nil { + fieldPaths = append(fieldPaths, "awsUseProfile") + } + if fields.Profile != nil { + fieldPaths = append(fieldPaths, "awsProfile") + } + if fields.Endpoint != nil { + fieldPaths = append(fieldPaths, "awsBedrockEndpoint") + } + + return fieldPaths +} diff --git a/cli/pkg/cli/auth/wizard_byo.go b/cli/pkg/cli/auth/wizard_byo.go new file mode 100644 index 00000000..d3551334 --- /dev/null +++ b/cli/pkg/cli/auth/wizard_byo.go @@ -0,0 +1,666 @@ +package auth + +import ( + "context" + "encoding/json" + "fmt" + "strings" + + "github.com/charmbracelet/huh" + "github.com/cline/cli/pkg/cli/global" + "github.com/cline/cli/pkg/cli/task" + "github.com/cline/grpc-go/cline" +) + +// ProviderWizard handles the interactive provider configuration process +type ProviderWizard struct { + ctx context.Context + manager *task.Manager +} + +// NewProviderWizard prepares a new provider configuration wizard +func NewProviderWizard(ctx context.Context) (*ProviderWizard, error) { + if err := global.EnsureDefaultInstance(ctx); err != nil { + return nil, fmt.Errorf("failed to ensure Cline Core instance: %w", err) + } + + manager, err := task.NewManagerForDefault(ctx) + if err != nil { + return nil, fmt.Errorf("failed to create task manager: %w", err) + } + + return &ProviderWizard{ + ctx: ctx, + manager: manager, + }, nil +} + +// showMainMenu displays the main provider configuration menu +func (pw *ProviderWizard) showMainMenu() (string, error) { + var action string + form := huh.NewForm( + huh.NewGroup( + huh.NewSelect[string](). + Title("What would you like to do?"). + Options( + huh.NewOption("Configure a new provider", "add"), + huh.NewOption("Change model for API provider", "change-model"), + huh.NewOption("Remove a provider", "remove"), + huh.NewOption("List configured providers", "list"), + huh.NewOption("Return to main auth menu", "back"), + ). + Value(&action), + ), + ) + + if err := form.Run(); err != nil { + return "", fmt.Errorf("failed to get menu choice: %w", err) + } + + return action, nil +} + +// Run runs the provider configuration wizard +func (pw *ProviderWizard) Run() error { + + for { + action, err := pw.showMainMenu() + if err != nil { + return err + } + + switch action { + case "add": + if err := pw.handleAddProvider(); err != nil { + return err + } + case "change-model": + if err := pw.handleChangeModel(); err != nil { + return err + } + case "remove": + if err := pw.handleRemoveProvider(); err != nil { + return err + } + case "list": + if err := pw.handleListProviders(); err != nil { + return err + } + case "back": + // Return to main auth menu + return HandleAuthMenuNoArgs(pw.ctx) + } + fmt.Println() + } +} + +// "Add a new provider" > handleAddProvider +func (pw *ProviderWizard) handleAddProvider() error { + // Step 1: Select provider + provider, err := SelectBYOProvider() + if err != nil { + if strings.Contains(err.Error(), "cancelled") { + return nil + } + return fmt.Errorf("provider selection failed: %w", err) + } + + // Step 2: Special handling for Bedrock provider + if provider == cline.ApiProvider_BEDROCK { + return pw.handleAddBedrockProvider() + } + + // Step 3: Get API key first (for non-Bedrock providers) + apiKey, err := PromptForAPIKey(provider) + if err != nil { + return fmt.Errorf("failed to get API key: %w", err) + } + + // Step 4: Try to fetch models and let user select (with fallback to manual entry for providers that don't support fetch) + modelID, modelInfo, err := pw.selectModel(provider, apiKey) + if err != nil { + return fmt.Errorf("model selection failed: %w", err) + } + + // Step 5: Apply configuration using AddProviderPartial + if err := AddProviderPartial(pw.ctx, pw.manager, provider, modelID, apiKey, modelInfo); err != nil { + return fmt.Errorf("failed to save configuration: %w", err) + } + + fmt.Println("✓ Provider configured successfully!") + return nil +} + +// handleAddBedrockProvider handles the special case of adding Bedrock provider with its multi-field form +func (pw *ProviderWizard) handleAddBedrockProvider() error { + // Step 1: Get Bedrock configuration (all credentials and optional fields) + config, err := PromptForBedrockConfig(pw.ctx, pw.manager) + if err != nil { + if strings.Contains(err.Error(), "user declined profile authentication") { + return nil + } + return fmt.Errorf("failed to get Bedrock configuration: %w", err) + } + + // Step 2: Select model + modelID, modelInfo, err := pw.selectModel(cline.ApiProvider_BEDROCK, "") + if err != nil { + return fmt.Errorf("model selection failed: %w", err) + } + + // Step 3: Apply Bedrock configuration + if err := ApplyBedrockConfig(pw.ctx, pw.manager, config, modelID, modelInfo); err != nil { + return fmt.Errorf("failed to save Bedrock configuration: %w", err) + } + + fmt.Println("✓ Bedrock provider configured successfully!") + return nil +} + +// handleListProviders retrieves and displays configured providers +func (pw *ProviderWizard) handleListProviders() error { + result, err := GetProviderConfigurations(pw.ctx, pw.manager) + if err != nil { + return fmt.Errorf("failed to retrieve provider configurations: %w", err) + } + + output := FormatProviderList(result) + fmt.Println(output) + + return nil +} + +// selectModel attempts to fetch available models and let user select, or falls back to manual entry +func (pw *ProviderWizard) selectModel(provider cline.ApiProvider, apiKey string) (string, interface{}, error) { + // For providers that support model fetching, try to fetch and display models + canFetchModels := pw.supportsModelFetching(provider) + + if canFetchModels { + fmt.Println("Fetching available models...") + models, modelInfoMap, err := pw.fetchModelsForProvider(provider, apiKey) + + if err != nil { + fmt.Println("\n⚠ Unable to fetch model list from the provider. Please enter the model ID manually instead.") + if global.Config.Verbose { + fmt.Printf(" Error details: %v\n", err) + } + return pw.manualModelEntry(provider) + } + + if len(models) == 0 { + fmt.Println("\n⚠ No models found from the provider. Please enter the model ID manually instead.") + return pw.manualModelEntry(provider) + } + + // Let user select from available models (includes manual entry option) + modelID, err := pw.selectFromAvailableModels(models) + if err != nil { + return "", nil, fmt.Errorf("model selection failed: %w", err) + } + + // Check if user chose manual entry + const manualEntryKey = "__MANUAL_ENTRY__" + if modelID == manualEntryKey { + return pw.manualModelEntry(provider) + } + + // Get the model info for the selected model + var modelInfo interface{} + if modelInfoMap != nil { + modelInfo = modelInfoMap[modelID] + } + + return modelID, modelInfo, nil + } + + // For providers without model fetching support, use manual entry + return pw.manualModelEntry(provider) +} + +// supportsModelFetching returns true if the provider supports fetching models +func (pw *ProviderWizard) supportsModelFetching(provider cline.ApiProvider) bool { + return SupportsBYOModelFetching(provider) +} + +// fetchModelsForProvider fetches models for a given provider +// Supports both dynamic API fetching (OpenRouter, OpenAI, Ollama) and static model lists (Anthropic, Bedrock, Gemini, X AI) +func (pw *ProviderWizard) fetchModelsForProvider(provider cline.ApiProvider, apiKey string) ([]string, map[string]interface{}, error) { + // Try dynamic/remote model fetching first + switch provider { + case cline.ApiProvider_OPENROUTER: + models, err := FetchOpenRouterModels(pw.ctx, pw.manager) + if err != nil { + return nil, nil, err + } + interfaceMap := ConvertOpenRouterModelsToInterface(models) + return ConvertModelsMapToSlice(interfaceMap), interfaceMap, nil + + case cline.ApiProvider_OPENAI: + // For OpenAI, we need to pass the base URL and API key + baseURL := "https://api.openai.com/v1" // Default OpenAI API base URL + modelIDs, err := FetchOpenAiModels(pw.ctx, pw.manager, baseURL, apiKey) + if err != nil { + return nil, nil, err + } + // OpenAI returns just model IDs without additional info, so modelInfo map is nil + return modelIDs, nil, nil + + case cline.ApiProvider_OLLAMA: + // For Ollama, apiKey actually contains the base URL (or empty for default) + baseURL := apiKey // The "API key" field for Ollama is actually the base URL + modelIDs, err := FetchOllamaModels(pw.ctx, pw.manager, baseURL) + if err != nil { + return nil, nil, err + } + // Ollama returns just model IDs without additional info, so modelInfo map is nil + return modelIDs, nil, nil + } + + // Fall back to static models for providers that don't support dynamic fetching + if SupportsStaticModelList(provider) { + modelIDs, _, err := FetchStaticModels(provider) + if err != nil { + return nil, nil, err + } + // Static models don't have detailed info maps for now, so modelInfo map is nil + return modelIDs, nil, nil + } + + return nil, nil, fmt.Errorf("model fetching not supported for provider: %v", provider) +} + +// selectFromAvailableModels displays available models and lets user select one. +// Includes an option to enter a model ID manually in case the desired model isn't listed. +func (pw *ProviderWizard) selectFromAvailableModels(models []string) (string, error) { + if len(models) == 0 { + return "", fmt.Errorf("no models available") + } + + // Add a special "manual entry" option at the end + const manualEntryKey = "__MANUAL_ENTRY__" + + // Use model ID as the value (not index) + var selectedModel string + options := make([]huh.Option[string], len(models)+1) + for i, model := range models { + options[i] = huh.NewOption(model, model) + } + // Add manual entry option at the end + options[len(models)] = huh.NewOption("Enter model ID manually...", manualEntryKey) + + form := huh.NewForm( + huh.NewGroup( + huh.NewSelect[string](). + Title("Select a model"). + Options(options...). + Height(calculateSelectHeight()). + Filtering(true). + Value(&selectedModel), + ), + ) + + if err := form.Run(); err != nil { + return "", fmt.Errorf("failed to select model: %w", err) + } + + // If user selected manual entry, return special key to trigger manual input + if selectedModel == manualEntryKey { + return manualEntryKey, nil + } + + return selectedModel, nil +} + +// manualModelEntry prompts user to manually enter a model ID. +// Returns the model ID and an error. The modelInfo is always nil for manual entry. +func (pw *ProviderWizard) manualModelEntry(provider cline.ApiProvider) (string, interface{}, error) { + var modelID string + modelPlaceholder := GetBYOProviderPlaceholder(provider) + + form := huh.NewForm( + huh.NewGroup( + huh.NewInput(). + Title("Model ID"). + Placeholder(modelPlaceholder). + Value(&modelID). + Validate(func(s string) error { + // Trim whitespace and validate + trimmed := strings.TrimSpace(s) + if trimmed == "" { + return fmt.Errorf("model ID cannot be empty") + } + return nil + }), + ), + ) + + if err := form.Run(); err != nil { + return "", nil, fmt.Errorf("failed to get model ID: %w", err) + } + + // Trim whitespace from the final value + modelID = strings.TrimSpace(modelID) + + // modelInfo is always nil for manual entry + return modelID, nil, nil +} + +// handleChangeModel allows changing the model for any configured provider +func (pw *ProviderWizard) handleChangeModel() error { + // Step 1: Get current provider configurations + result, err := GetProviderConfigurations(pw.ctx, pw.manager) + if err != nil { + return fmt.Errorf("failed to retrieve provider configurations: %w", err) + } + + // Step 2: Get all configured providers with models + readyProviders := result.GetAllReadyProviders() + + // Filter out Cline provider (it has its own model changer in the main menu) + var configurableProviders []*ProviderDisplay + for _, provider := range readyProviders { + if provider.Provider != cline.ApiProvider_CLINE { + configurableProviders = append(configurableProviders, provider) + } + } + + // Step 3: Check if there are any configurable providers + if len(configurableProviders) == 0 { + fmt.Println("\nNo configurable providers found.") + fmt.Println("Note: Cline provider has its own model selection in the main menu.") + return nil + } + + // Step 4: Let user select which provider to change the model for + var selectedIndex int + options := make([]huh.Option[int], len(configurableProviders)+1) + for i, providerDisplay := range configurableProviders { + displayName := fmt.Sprintf("%s (current: %s)", + getProviderDisplayName(providerDisplay.Provider), + providerDisplay.ModelID) + options[i] = huh.NewOption(displayName, i) + } + options[len(configurableProviders)] = huh.NewOption("(Cancel)", -1) + + form := huh.NewForm( + huh.NewGroup( + huh.NewSelect[int](). + Title("Select provider to change model for"). + Options(options...). + Value(&selectedIndex), + ), + ) + + if err := form.Run(); err != nil { + return fmt.Errorf("failed to select provider: %w", err) + } + + if selectedIndex == -1 { + return nil + } + + selectedProvider := configurableProviders[selectedIndex] + provider := selectedProvider.Provider + + fmt.Printf("\nChanging model for %s\n", getProviderDisplayName(provider)) + fmt.Printf("Current model: %s\n\n", selectedProvider.ModelID) + + // Step 5: Retrieve API key if needed for model fetching + var apiKey string + if pw.supportsModelFetching(provider) { + // For providers that support fetching, we need to retrieve the API key from state + state, err := pw.manager.GetClient().State.GetLatestState(pw.ctx, &cline.EmptyRequest{}) + if err != nil { + return fmt.Errorf("failed to get state: %w", err) + } + + var stateData map[string]interface{} + if err := json.Unmarshal([]byte(state.StateJson), &stateData); err != nil { + return fmt.Errorf("failed to parse state JSON: %w", err) + } + + apiConfig, ok := stateData["apiConfiguration"].(map[string]interface{}) + if !ok { + return fmt.Errorf("no API configuration found in state") + } + + apiKey = getProviderAPIKeyFromState(apiConfig, provider) + if apiKey == "" { + return fmt.Errorf("no API key found for provider %s", getProviderDisplayName(provider)) + } + } + + modelID, modelInfo, err := pw.selectModel(provider, apiKey) + if err != nil { + return fmt.Errorf("model selection failed: %w", err) + } + + // Step 6: Apply the model change (for both Plan and Act modes) + if err := pw.applyModelChange(provider, modelID, modelInfo); err != nil { + return fmt.Errorf("failed to apply model change: %w", err) + } + + fmt.Printf("✓ Model changed successfully to: %s\n", modelID) + fmt.Println(" (Applied to both Plan and Act modes)") + return nil +} + +// applyModelChange applies a model change for both Plan and Act modes using UpdateProviderPartial +func (pw *ProviderWizard) applyModelChange(provider cline.ApiProvider, modelID string, modelInfo interface{}) error { + updates := ProviderUpdatesPartial{ + ModelID: &modelID, + ModelInfo: modelInfo, + } + + return UpdateProviderPartial(pw.ctx, pw.manager, provider, updates, false) +} + +// SwitchToBYOProvider switches to a BYO provider that's already configured. +// It retrieves the existing model configuration and sets it as the active provider for both Plan and Act modes. +func SwitchToBYOProvider(ctx context.Context, manager *task.Manager, provider cline.ApiProvider) error { + // Get the current state to retrieve the model ID and model info for this provider + state, err := manager.GetClient().State.GetLatestState(ctx, &cline.EmptyRequest{}) + if err != nil { + return fmt.Errorf("failed to get state: %w", err) + } + + // Parse state JSON + var stateData map[string]interface{} + if err := json.Unmarshal([]byte(state.StateJson), &stateData); err != nil { + return fmt.Errorf("failed to parse state JSON: %w", err) + } + + // Extract apiConfiguration + apiConfig, ok := stateData["apiConfiguration"].(map[string]interface{}) + if !ok { + return fmt.Errorf("no API configuration found in state") + } + + // Get the model ID for the selected provider + modelID := getProviderModelIDFromState(apiConfig, provider) + if modelID == "" { + return fmt.Errorf("no model configured for provider %s", getProviderDisplayName(provider)) + } + + // Get model info if available (for OpenRouter/Cline) + var modelInfo interface{} + if provider == cline.ApiProvider_OPENROUTER || provider == cline.ApiProvider_CLINE { + if modelInfoData, ok := apiConfig["planModeOpenRouterModelInfo"].(map[string]interface{}); ok { + modelInfo = convertMapToOpenRouterModelInfo(modelInfoData) + } + } + + // Use UpdateProviderPartial to switch to this provider + updates := ProviderUpdatesPartial{ + ModelID: &modelID, + ModelInfo: modelInfo, + } + + if err := UpdateProviderPartial(ctx, manager, provider, updates, true); err != nil { + return fmt.Errorf("failed to switch provider: %w", err) + } + + verboseLog("✓ Switched to %s\n", getProviderDisplayName(provider)) + verboseLog(" Using model: %s\n", modelID) + + return HandleAuthMenuNoArgs(ctx) +} + +// getProviderModelIDFromState retrieves the model ID for a specific provider from state +func getProviderModelIDFromState(stateData map[string]interface{}, provider cline.ApiProvider) string { + modelKey, err := GetModelIDFieldName(provider, "plan") + if err != nil { + return "" + } + + if modelID, ok := stateData[modelKey].(string); ok { + return modelID + } + + return "" +} + +// getProviderAPIKeyFromState retrieves the API key for a specific provider from state +func getProviderAPIKeyFromState(stateData map[string]interface{}, provider cline.ApiProvider) string { + fields, err := GetProviderFields(provider) + if err != nil { + return "" + } + + if apiKey, ok := stateData[fields.APIKeyField].(string); ok { + return apiKey + } + + return "" +} + +// convertMapToOpenRouterModelInfo converts a map to OpenRouterModelInfo +func convertMapToOpenRouterModelInfo(data map[string]interface{}) *cline.OpenRouterModelInfo { + info := &cline.OpenRouterModelInfo{} + + if val, ok := data["description"].(string); ok { + info.Description = &val + } + if val, ok := data["contextWindow"].(float64); ok { + contextWindow := int64(val) + info.ContextWindow = &contextWindow + } + if val, ok := data["maxTokens"].(float64); ok { + maxTokens := int64(val) + info.MaxTokens = &maxTokens + } + if val, ok := data["inputPrice"].(float64); ok { + info.InputPrice = &val + } + if val, ok := data["outputPrice"].(float64); ok { + info.OutputPrice = &val + } + if val, ok := data["cacheWritesPrice"].(float64); ok { + info.CacheWritesPrice = &val + } + if val, ok := data["cacheReadsPrice"].(float64); ok { + info.CacheReadsPrice = &val + } + if val, ok := data["supportsImages"].(bool); ok { + info.SupportsImages = &val + } + if val, ok := data["supportsPromptCache"].(bool); ok { + info.SupportsPromptCache = val + } + + return info +} + +// handleRemoveProvider allows removing a configured provider by clearing its API key +func (pw *ProviderWizard) handleRemoveProvider() error { + // Step 1: Get current provider configurations + result, err := GetProviderConfigurations(pw.ctx, pw.manager) + if err != nil { + return fmt.Errorf("failed to retrieve provider configurations: %w", err) + } + + // Step 2: Get all ready providers + readyProviders := result.GetAllReadyProviders() + + // Filter out Cline provider (uses account auth, not API keys) + var removableProviders []*ProviderDisplay + for _, provider := range readyProviders { + if provider.Provider != cline.ApiProvider_CLINE { + removableProviders = append(removableProviders, provider) + } + } + + // Step 3: Check if there are providers to remove + if len(removableProviders) == 0 { + fmt.Println("\nNo providers available to remove.") + fmt.Println("Note: Cline provider cannot be removed via this menu.") + return nil + } + + // Step 4: Display selection menu + var selectedIndex int + options := make([]huh.Option[int], len(removableProviders)) + for i, provider := range removableProviders { + // Mark active provider + displayName := getProviderDisplayName(provider.Provider) + if result.ActProvider != nil && provider.Provider == result.ActProvider.Provider { + displayName += " (ACTIVE)" + } + options[i] = huh.NewOption(displayName, i) + } + + form := huh.NewForm( + huh.NewGroup( + huh.NewSelect[int](). + Title("Select provider to remove"). + Options(options...). + Value(&selectedIndex), + ), + ) + + if err := form.Run(); err != nil { + return fmt.Errorf("failed to select provider: %w", err) + } + + selectedProvider := removableProviders[selectedIndex] + + // Step 5: Check if trying to remove the active provider + if result.ActProvider != nil && selectedProvider.Provider == result.ActProvider.Provider { + fmt.Printf("\nCannot remove %s because it is currently active.\n", getProviderDisplayName(selectedProvider.Provider)) + fmt.Println("Please switch to a different provider first, then try again.") + return nil + } + + // Step 6: Confirm removal + var confirm bool + confirmForm := huh.NewForm( + huh.NewGroup( + huh.NewConfirm(). + Title(fmt.Sprintf("Are you sure you want to remove %s?", getProviderDisplayName(selectedProvider.Provider))). + Description("This will clear the API key but preserve the model configuration."). + Value(&confirm), + ), + ) + + if err := confirmForm.Run(); err != nil { + return fmt.Errorf("failed to get confirmation: %w", err) + } + + if !confirm { + fmt.Println("Removal cancelled.") + return nil + } + + // Step 7: Clear the API key for the selected provider + if err := pw.clearProviderAPIKey(selectedProvider.Provider); err != nil { + return fmt.Errorf("failed to remove provider: %w", err) + } + + fmt.Printf("\n✓ %s removed successfully\n", getProviderDisplayName(selectedProvider.Provider)) + return nil +} + +// clearProviderAPIKey clears the API key field for a specific provider using RemoveProviderPartial +func (pw *ProviderWizard) clearProviderAPIKey(provider cline.ApiProvider) error { + return RemoveProviderPartial(pw.ctx, pw.manager, provider) +} diff --git a/cli/pkg/cli/auth/wizard_byo_bedrock.go b/cli/pkg/cli/auth/wizard_byo_bedrock.go new file mode 100644 index 00000000..38ae9f0f --- /dev/null +++ b/cli/pkg/cli/auth/wizard_byo_bedrock.go @@ -0,0 +1,193 @@ +package auth + +import ( + "context" + "fmt" + "strings" + + "github.com/charmbracelet/huh" + "github.com/cline/cli/pkg/cli/task" + "github.com/cline/grpc-go/cline" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/fieldmaskpb" +) + +// BedrockConfig holds all AWS Bedrock-specific configuration fields +type BedrockConfig struct { + // Profile authentication fields + UseProfile bool // Always true for successful config + Profile string // Optional: AWS profile name (empty = default) + Region string // Required: AWS region + Endpoint string // Optional: Custom VPC endpoint URL + + // Optional features + UseCrossRegionInference bool // Optional: Enable cross-region inference + UseGlobalInference bool // Optional: Use global inference endpoint + UsePromptCache bool // Optional: Enable prompt caching + + // Authentication method (always "profile") + Authentication string // Always set to "profile" + + // Legacy fields (no longer used in profile-only flow) + AccessKey string // No longer used + SecretKey string // No longer used + SessionToken string // No longer used +} + +// PromptForBedrockConfig displays a profile-first authentication form for Bedrock configuration +func PromptForBedrockConfig(ctx context.Context, manager *task.Manager) (*BedrockConfig, error) { + config := &BedrockConfig{} + + // First, ask if user wants to use AWS profile authentication + var useProfile bool + profileQuestion := huh.NewForm( + huh.NewGroup( + huh.NewConfirm(). + Title("Do you want to use an AWS profile for authentication?"). + Description("AWS profiles are managed via 'aws configure'"). + Value(&useProfile). + Affirmative("Yes"). + Negative("No"). + Inline(true), + ), + ) + + if err := profileQuestion.Run(); err != nil { + return nil, fmt.Errorf("failed to get authentication method: %w", err) + } + + // If user declines profile authentication, show message and return error + if !useProfile { + fmt.Println("\nAWS profile authentication is currently the only supported method in the CLI.") + fmt.Println("Please configure an AWS profile using 'aws configure' and try again.") + return nil, fmt.Errorf("user declined profile authentication") + } + + // User wants profile auth - collect profile configuration + config.UseProfile = true + config.Authentication = "profile" + + // Collect profile name, region, and optional settings + configForm := huh.NewForm( + huh.NewGroup( + huh.NewInput(). + Title("AWS Profile Name (optional, press Enter for default profile)"). + Value(&config.Profile). + Description("Leave empty to use default AWS profile"), + + huh.NewInput(). + Title("AWS Region (required, e.g., us-east-1)"). + Value(&config.Region). + Validate(func(s string) error { + if strings.TrimSpace(s) == "" { + return fmt.Errorf("AWS Region is required") + } + return nil + }), + + huh.NewInput(). + Title("Custom VPC Endpoint URL (optional)"). + Value(&config.Endpoint). + Description("Press Enter to skip"), + + huh.NewConfirm(). + Title("Enable Prompt Cache? "). + Value(&config.UsePromptCache). + Affirmative("Yes"). + Negative("No"). + Inline(true), + + huh.NewConfirm(). + Title("Enable Cross-Region Inference? "). + Value(&config.UseCrossRegionInference). + Affirmative("Yes"). + Negative("No"). + Inline(true), + + huh.NewConfirm(). + Title("Use Global Inference Endpoint? "). + Value(&config.UseGlobalInference). + Affirmative("Yes"). + Negative("No"). + Inline(true), + ), + ) + + if err := configForm.Run(); err != nil { + return nil, fmt.Errorf("failed to get Bedrock configuration: %w", err) + } + + // Trim whitespace from string fields + config.Profile = strings.TrimSpace(config.Profile) + config.Region = strings.TrimSpace(config.Region) + config.Endpoint = strings.TrimSpace(config.Endpoint) + + return config, nil +} + +// ApplyBedrockConfig applies Bedrock configuration using partial updates (profile-only) +func ApplyBedrockConfig(ctx context.Context, manager *task.Manager, config *BedrockConfig, modelID string, modelInfo interface{}) error { + // Build the API configuration with all Bedrock fields + apiConfig := &cline.ModelsApiConfiguration{} + + // Set model ID fields + apiConfig.PlanModeApiModelId = proto.String(modelID) + apiConfig.ActModeApiModelId = proto.String(modelID) + apiConfig.PlanModeAwsBedrockCustomModelBaseId = proto.String(modelID) + apiConfig.ActModeAwsBedrockCustomModelBaseId = proto.String(modelID) + + // Set profile authentication fields (always required) + optionalFields := &BedrockOptionalFields{} + optionalFields.Authentication = proto.String("profile") + optionalFields.UseProfile = proto.Bool(true) + optionalFields.Region = proto.String(config.Region) + + // Set profile name (can be empty for default profile) + if config.Profile != "" { + optionalFields.Profile = proto.String(config.Profile) + } + + // Set optional fields if provided + if config.Endpoint != "" { + optionalFields.Endpoint = proto.String(config.Endpoint) + } + if config.UseCrossRegionInference { + optionalFields.UseCrossRegionInference = proto.Bool(true) + } + if config.UseGlobalInference { + optionalFields.UseGlobalInference = proto.Bool(true) + } + if config.UsePromptCache { + optionalFields.UsePromptCache = proto.Bool(true) + } + + // Apply all fields to the config + setBedrockOptionalFields(apiConfig, optionalFields) + + // Build field mask including all fields we're setting (excluding access keys) + fieldPaths := []string{ + "planModeApiModelId", + "actModeApiModelId", + "planModeAwsBedrockCustomModelBaseId", + "actModeAwsBedrockCustomModelBaseId", + } + + // Add profile authentication field paths + optionalPaths := buildBedrockOptionalFieldMask(optionalFields) + fieldPaths = append(fieldPaths, optionalPaths...) + + // Create field mask + fieldMask := &fieldmaskpb.FieldMask{Paths: fieldPaths} + + // Apply the partial update + request := &cline.UpdateApiConfigurationPartialRequest{ + ApiConfiguration: apiConfig, + UpdateMask: fieldMask, + } + + if err := updateApiConfigurationPartial(ctx, manager, request); err != nil { + return fmt.Errorf("failed to apply Bedrock configuration: %w", err) + } + + return nil +} diff --git a/cli/pkg/cli/task/manager.go b/cli/pkg/cli/task/manager.go index 32dfe8d5..a98db611 100644 --- a/cli/pkg/cli/task/manager.go +++ b/cli/pkg/cli/task/manager.go @@ -1102,6 +1102,13 @@ func (m *Manager) GetState() *types.ConversationState { return m.state } +// GetClient returns the underlying ClineClient for direct gRPC calls +func (m *Manager) GetClient() *client.ClineClient { + m.mu.RLock() + defer m.mu.RUnlock() + return m.client +} + // Cleanup cleans up resources func (m *Manager) Cleanup() { // Clean up streaming display resources if needed diff --git a/cli/pkg/generated/field_overrides.go b/cli/pkg/generated/field_overrides.go new file mode 100644 index 00000000..9031b260 --- /dev/null +++ b/cli/pkg/generated/field_overrides.go @@ -0,0 +1,39 @@ +package generated + +// FieldOverrides allows manual control over field relevance per provider +// This file is NOT auto-generated and can be edited manually to override +// the automatic field filtering logic. +// +// Usage: +// - Add provider-specific overrides to force include/exclude fields +// - true = force include this field for this provider +// - false = force exclude this field for this provider +// - If no override exists, automatic filtering logic applies +var FieldOverrides = map[string]map[string]bool{ + // Format: "provider_id": {"field_name": shouldInclude} + + // Example overrides (uncomment and modify as needed): + + // "anthropic": { + // "requestTimeoutMs": true, // explicitly include + // "ollamaBaseUrl": false, // explicitly exclude + // }, + + // "bedrock": { + // "awsSessionToken": true, // include even if marked optional + // "azureApiVersion": false, // exclude even if general + // }, + + // Add more provider-specific overrides as needed +} + +// GetFieldOverride returns the override setting for a field, if one exists +// Returns (shouldInclude, hasOverride) +func GetFieldOverride(providerID, fieldName string) (bool, bool) { + if providerOverrides, exists := FieldOverrides[providerID]; exists { + if override, hasOverride := providerOverrides[fieldName]; hasOverride { + return override, true + } + } + return false, false +} diff --git a/cli/pkg/generated/providers.go b/cli/pkg/generated/providers.go index 10746c59..b02992a5 100644 --- a/cli/pkg/generated/providers.go +++ b/cli/pkg/generated/providers.go @@ -421,6 +421,15 @@ var rawConfigFields = ` [ "required": false, "fieldType": "url", "placeholder": "https://api.example.com" + }, + { + "name": "ocaMode", + "type": "string", + "comment": "", + "category": "general", + "required": false, + "fieldType": "string", + "placeholder": "" } ]` diff --git a/go.work.sum b/go.work.sum index 34d46bd0..9d368ae2 100644 --- a/go.work.sum +++ b/go.work.sum @@ -2,6 +2,7 @@ cel.dev/expr v0.24.0/go.mod h1:hLPLo1W4QUmuYdA72RBX06QTs6MXw941piREPl3Yfiw= cloud.google.com/go/compute/metadata v0.7.0/go.mod h1:j5MvL9PprKL39t166CoB1uVHfQMs4tFQZZcKwksXUjo= github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.29.0/go.mod h1:Cz6ft6Dkn3Et6l2v2a9/RpN7epQ1GtDlO6lj8bEcOvw= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/charmbracelet/harmonica v0.2.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao= github.com/cncf/xds/go v0.0.0-20250501225837-2ac532fd4443/go.mod h1:W+zGtBO5Y1IgJhy4+A9GOqVhqLpfZi+vwmdNXUehLA8= github.com/envoyproxy/go-control-plane v0.13.4/go.mod h1:kDfuBlDVsSj2MjrLEtRWtHlsWIFcGyB2RMO44Dc5GZA= github.com/envoyproxy/go-control-plane/envoy v1.32.4/go.mod h1:Gzjc5k8JcJswLjAx1Zm+wSYE20UrLtt7JZMWiWQXQEw= @@ -9,9 +10,9 @@ github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJP github.com/envoyproxy/protoc-gen-validate v1.2.1/go.mod h1:d/C80l/jxXLdfEIhX1W2TmLfsJ31lvEjwamM4DxlWXU= github.com/go-jose/go-jose/v4 v4.1.1/go.mod h1:BdsZGqgdO3b6tTc6LSE56wcDbMMLuPsw5d4ZD5f94kA= github.com/golang/glog v1.2.5/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w= -github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8= +github.com/sahilm/fuzzy v0.1.1/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y= github.com/spiffe/go-spiffe/v2 v2.5.0/go.mod h1:P+NxobPc6wXhVtINNtFjNWGBTreew1GBUCwT2wPmb7g= github.com/zeebo/errs v1.4.0/go.mod h1:sgbWHsvVuTPHcqJJGQ1WhI5KbWlHYz+2+2C/LSEtCw4= go.opentelemetry.io/contrib/detectors/gcp v1.36.0/go.mod h1:IbBN8uAIIx734PTonTPxAxnjc2pQTxWNkwfstZ+6H2k=