| 1 | import * as fs from "fs"; |
| 2 | import * as path from "path"; |
| 3 | |
| 4 | import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; |
| 5 | import { BaseLlmApi } from "@continuedev/openai-adapters"; |
| 6 | import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; |
| 7 | import chalk from "chalk"; |
| 8 | |
| 9 | import { processPromptOrRule } from "./args.js"; |
| 10 | import { AuthConfig, isAuthenticated, login } from "./auth/workos.js"; |
| 11 | import { initialize } from "./config.js"; |
| 12 | import { env } from "./env.js"; |
| 13 | import { MCPService } from "./services/MCPService.js"; |
| 14 | import { |
| 15 | getApiKeyValidationError, |
| 16 | isValidAnthropicApiKey, |
| 17 | } from "./util/apiKeyValidation.js"; |
| 18 | import { question, questionWithChoices } from "./util/prompt.js"; |
| 19 | import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js"; |
| 20 | |
| 21 | const CONFIG_PATH = path.join(env.continueHome, "config.yaml"); |
| 22 | |
| 23 | export interface OnboardingResult { |
| 24 | config: AssistantUnrolled; |
| 25 | llmApi: BaseLlmApi; |
| 26 | model: ModelConfig; |
| 27 | mcpService: MCPService; |
| 28 | apiClient: DefaultApiInterface; |
| 29 | wasOnboarded: boolean; |
| 30 | } |
| 31 | |
| 32 | export async function checkHasAcceptableModel( |
| 33 | configPath: string, |
| 34 | ): Promise<boolean> { |
| 35 | try { |
| 36 | if (!fs.existsSync(configPath)) { |
| 37 | return false; |
| 38 | } |
| 39 | |
| 40 | const content = fs.readFileSync(configPath, "utf8"); |
| 41 | return content.includes("claude"); |
| 42 | } catch { |
| 43 | return false; |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | export async function createOrUpdateConfig(apiKey: string): Promise<void> { |
| 48 | const configDir = path.dirname(CONFIG_PATH); |
| 49 | |
| 50 | if (!fs.existsSync(configDir)) { |
| 51 | fs.mkdirSync(configDir, { recursive: true }); |
| 52 | } |
| 53 | |
| 54 | const existingContent = fs.existsSync(CONFIG_PATH) |
| 55 | ? fs.readFileSync(CONFIG_PATH, "utf8") |
| 56 | : ""; |
| 57 | |
| 58 | const updatedContent = updateAnthropicModelInYaml(existingContent, apiKey); |
| 59 | fs.writeFileSync(CONFIG_PATH, updatedContent); |
| 60 | } |
| 61 | |
| 62 | export async function runOnboardingFlow( |
| 63 | configPath: string | undefined, |
| 64 | authConfig: AuthConfig, |
| 65 | ): Promise<OnboardingResult> { |
| 66 | // Step 1: Check if --config flag is provided |
| 67 | if (configPath !== undefined) { |
| 68 | const result = await initialize(authConfig, configPath); |
| 69 | return { ...result, wasOnboarded: false }; |
| 70 | } |
| 71 | |
| 72 | // Step 2: Check for CONTINUE_USE_BEDROCK environment variable first (before test env check) |
| 73 | if (process.env.CONTINUE_USE_BEDROCK === "1") { |
| 74 | console.log( |
| 75 | chalk.blue("✓ Using AWS Bedrock (CONTINUE_USE_BEDROCK detected)"), |
| 76 | ); |
| 77 | const result = await initialize(authConfig, CONFIG_PATH); |
| 78 | return { ...result, wasOnboarded: true }; |
| 79 | } |
| 80 | |
| 81 | // Step 3: Check if we're in a test/CI environment - if so, skip interactive prompts |
| 82 | const isTestEnv = |
| 83 | process.env.NODE_ENV === "test" || |
| 84 | process.env.CI === "true" || |
| 85 | process.env.VITEST === "true" || |
| 86 | process.env.GITHUB_ACTIONS === "true" || |
| 87 | !process.stdin.isTTY; |
| 88 | |
| 89 | if (isTestEnv) { |
| 90 | // In test/CI environment, check for ANTHROPIC_API_KEY first |
| 91 | if (process.env.ANTHROPIC_API_KEY) { |
| 92 | console.log(chalk.blue("✓ Using ANTHROPIC_API_KEY from environment")); |
| 93 | await createOrUpdateConfig(process.env.ANTHROPIC_API_KEY); |
| 94 | console.log(chalk.gray(` Config saved to: ${CONFIG_PATH}`)); |
| 95 | const result = await initialize(authConfig, CONFIG_PATH); |
| 96 | return { ...result, wasOnboarded: false }; |
| 97 | } |
| 98 | |
| 99 | // Otherwise return a minimal working configuration |
| 100 | const result = await initialize(authConfig, undefined); |
| 101 | return { ...result, wasOnboarded: false }; |
| 102 | } |
| 103 | |
| 104 | // Step 4: Present user with two options |
| 105 | console.log(chalk.yellow("How do you want to get started?")); |
| 106 | console.log(chalk.white("1. ⏩ Log in with Continue")); |
| 107 | console.log(chalk.white("2. 🔑 Enter your Anthropic API key")); |
| 108 | |
| 109 | const choice = await questionWithChoices( |
| 110 | chalk.yellow("\nEnter choice (1): "), |
| 111 | ["1", "2", ""], |
| 112 | "1", |
| 113 | chalk.dim("Please enter 1 or 2"), |
| 114 | ); |
| 115 | |
| 116 | if (choice === "1" || choice === "") { |
| 117 | const newAuthConfig = await login(); |
| 118 | |
| 119 | const { ensureOrganization } = await import("./auth/workos.js"); |
| 120 | const finalAuthConfig = await ensureOrganization(newAuthConfig); |
| 121 | |
| 122 | const result = await initialize(finalAuthConfig, undefined); |
| 123 | return { ...result, wasOnboarded: true }; |
| 124 | } else if (choice === "2") { |
| 125 | const apiKey = await question( |
| 126 | chalk.white("\nEnter your Anthropic API key: "), |
| 127 | ); |
| 128 | |
| 129 | if (!isValidAnthropicApiKey(apiKey)) { |
| 130 | throw new Error(getApiKeyValidationError(apiKey)); |
| 131 | } |
| 132 | |
| 133 | await createOrUpdateConfig(apiKey); |
| 134 | console.log( |
| 135 | chalk.green(`✓ Config file updated successfully at ${CONFIG_PATH}`), |
| 136 | ); |
| 137 | |
| 138 | const result = await initialize(authConfig, CONFIG_PATH); |
| 139 | return { ...result, wasOnboarded: true }; |
| 140 | } else { |
| 141 | throw new Error(`Invalid choice. Please select "1" or "2"`); |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | export async function runNormalFlow( |
| 146 | authConfig: AuthConfig, |
| 147 | configPath?: string, |
| 148 | rules?: string[], |
| 149 | ): Promise<OnboardingResult> { |
| 150 | // Step 1: Check if --config flag is provided |
| 151 | if (configPath !== undefined) { |
| 152 | // Empty string is invalid and should be treated as an error |
| 153 | if (configPath === "") { |
| 154 | throw new Error( |
| 155 | `Failed to load config from "": Config path cannot be empty`, |
| 156 | ); |
| 157 | } |
| 158 | |
| 159 | try { |
| 160 | const result = await initialize(authConfig, configPath); |
| 161 | // Inject rules into the config if provided |
| 162 | if (rules && rules.length > 0) { |
| 163 | result.config = await injectRulesIntoConfig(result.config, rules); |
| 164 | } |
| 165 | return { ...result, wasOnboarded: false }; |
| 166 | } catch (error) { |
| 167 | // If user explicitly provided --config flag, fail loudly instead of falling back |
| 168 | const errorMessage = |
| 169 | error instanceof Error ? error.message : String(error); |
| 170 | throw new Error( |
| 171 | `Failed to load config from "${configPath}": ${errorMessage}`, |
| 172 | ); |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | // Step 2: If user is logged in, look for first assistant in selected org |
| 177 | if (isAuthenticated()) { |
| 178 | try { |
| 179 | const result = await initialize(authConfig, undefined); |
| 180 | // Inject rules into the config if provided |
| 181 | if (rules && rules.length > 0) { |
| 182 | result.config = await injectRulesIntoConfig(result.config, rules); |
| 183 | } |
| 184 | return { ...result, wasOnboarded: false }; |
| 185 | } catch { |
| 186 | // Silently ignore errors when loading default assistant |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | // Step 3: Look for local ~/.continue/config.yaml |
| 191 | if (fs.existsSync(CONFIG_PATH)) { |
| 192 | try { |
| 193 | const result = await initialize(authConfig, CONFIG_PATH); |
| 194 | // Inject rules into the config if provided |
| 195 | if (rules && rules.length > 0) { |
| 196 | result.config = await injectRulesIntoConfig(result.config, rules); |
| 197 | } |
| 198 | return { ...result, wasOnboarded: false }; |
| 199 | } catch { |
| 200 | console.log(chalk.yellow("⚠ Invalid config file found")); |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | // Step 4: Look for ANTHROPIC_API_KEY in environment |
| 205 | if (process.env.ANTHROPIC_API_KEY) { |
| 206 | console.log(chalk.blue("✓ Using ANTHROPIC_API_KEY from environment")); |
| 207 | await createOrUpdateConfig(process.env.ANTHROPIC_API_KEY); |
| 208 | console.log(chalk.gray(` Config saved to: ${CONFIG_PATH}`)); |
| 209 | const result = await initialize(authConfig, CONFIG_PATH); |
| 210 | // Inject rules into the config if provided |
| 211 | if (rules && rules.length > 0) { |
| 212 | result.config = await injectRulesIntoConfig(result.config, rules); |
| 213 | } |
| 214 | return { ...result, wasOnboarded: false }; |
| 215 | } |
| 216 | |
| 217 | // Step 5: Fall back to onboarding flow |
| 218 | return runOnboardingFlow(configPath, authConfig); |
| 219 | } |
| 220 | |
| 221 | export async function isFirstTime(): Promise<boolean> { |
| 222 | return !fs.existsSync(path.join(env.continueHome, ".onboarding_complete")); |
| 223 | } |
| 224 | |
| 225 | export async function markOnboardingComplete(): Promise<void> { |
| 226 | const flagPath = path.join(env.continueHome, ".onboarding_complete"); |
| 227 | const flagDir = path.dirname(flagPath); |
| 228 | |
| 229 | if (!fs.existsSync(flagDir)) { |
| 230 | fs.mkdirSync(flagDir, { recursive: true }); |
| 231 | } |
| 232 | |
| 233 | fs.writeFileSync(flagPath, new Date().toISOString()); |
| 234 | } |
| 235 | |
| 236 | /** |
| 237 | * Process rules and inject them into the assistant config |
| 238 | * @param config - The assistant config to modify |
| 239 | * @param rules - Array of rule specifications to process and inject |
| 240 | * @returns The modified config with injected rules |
| 241 | */ |
| 242 | async function injectRulesIntoConfig( |
| 243 | config: AssistantUnrolled, |
| 244 | rules: string[], |
| 245 | ): Promise<AssistantUnrolled> { |
| 246 | if (!rules || rules.length === 0) { |
| 247 | return config; |
| 248 | } |
| 249 | |
| 250 | const processedRules: string[] = []; |
| 251 | for (const ruleSpec of rules) { |
| 252 | try { |
| 253 | const processedRule = await processPromptOrRule(ruleSpec); |
| 254 | processedRules.push(processedRule); |
| 255 | } catch (error: any) { |
| 256 | console.warn( |
| 257 | chalk.yellow( |
| 258 | `Warning: Failed to process rule "${ruleSpec}": ${error.message}`, |
| 259 | ), |
| 260 | ); |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | if (processedRules.length === 0) { |
| 265 | return config; |
| 266 | } |
| 267 | |
| 268 | // Clone the config to avoid mutating the original |
| 269 | const modifiedConfig = { ...config }; |
| 270 | |
| 271 | // Add processed rules to the config's rules array |
| 272 | // Each processed rule is a string, which is a valid Rule type |
| 273 | const existingRules = modifiedConfig.rules || []; |
| 274 | modifiedConfig.rules = [...existingRules, ...processedRules]; |
| 275 | |
| 276 | return modifiedConfig; |
| 277 | } |
| 278 | |
| 279 | export async function initializeWithOnboarding( |
| 280 | authConfig: AuthConfig, |
| 281 | configPath: string | undefined, |
| 282 | rules?: string[], |
| 283 | ): Promise<OnboardingResult> { |
| 284 | const firstTime = await isFirstTime(); |
| 285 | |
| 286 | let result: OnboardingResult; |
| 287 | |
| 288 | if (firstTime) { |
| 289 | result = await runOnboardingFlow(configPath, authConfig); |
| 290 | if (result.wasOnboarded) { |
| 291 | await markOnboardingComplete(); |
| 292 | } |
| 293 | } else { |
| 294 | result = await runNormalFlow(authConfig, configPath, rules); |
| 295 | } |
| 296 | |
| 297 | // Inject rules into the config if provided (for onboarding flow which doesn't handle rules directly) |
| 298 | if (rules && rules.length > 0 && !result.wasOnboarded) { |
| 299 | result.config = await injectRulesIntoConfig(result.config, rules); |
| 300 | } |
| 301 | |
| 302 | return result; |
| 303 | } |