Elffuss BraidHub

kikocis/continue public

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