Elffuss BraidHub

kikocis/continue public

dfc814e4318e · 9.1 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";
8import * as readlineSync from "readline-sync";
9
10import { processPromptOrRule } from "./args.js";
11import { AuthConfig, isAuthenticated, login } from "./auth/workos.js";
12import { initialize } from "./config.js";
13import { env } from "./env.js";
14import { MCPService } from "./services/MCPService.js";
15import {
16 getApiKeyValidationError,
17 isValidAnthropicApiKey,
18} from "./util/apiKeyValidation.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 = readlineSync.question(chalk.yellow("\nEnter choice (1): "), {
101 limit: ["1", "2", ""],
102 limitMessage: chalk.dim("Please enter 1 or 2"),
103 });
104
105 if (choice === "1" || choice === "") {
106 const newAuthConfig = await login();
107
108 const result = await initialize(newAuthConfig, undefined);
109 return { ...result, wasOnboarded: true };
110 } else if (choice === "2") {
111 const apiKey = readlineSync.question(
112 chalk.white("\nEnter your Anthropic API key: "),
113 {
114 hideEchoBack: true,
115 },
116 );
117
118 if (!isValidAnthropicApiKey(apiKey)) {
119 throw new Error(getApiKeyValidationError(apiKey));
120 }
121
122 await createOrUpdateConfig(apiKey);
123 console.log(
124 chalk.green(`✓ Config file updated successfully at ${CONFIG_PATH}`),
125 );
126
127 const result = await initialize(authConfig, CONFIG_PATH);
128 return { ...result, wasOnboarded: true };
129 } else {
130 throw new Error("Invalid choice. Please select 1 or 2.");
131 }
132}
133
134export async function runNormalFlow(
135 authConfig: AuthConfig,
136 configPath?: string,
137 rules?: string[],
138): Promise<OnboardingResult> {
139 // Step 1: Check if --config flag is provided
140 if (configPath !== undefined) {
141 // Empty string is invalid and should be treated as an error
142 if (configPath === "") {
143 throw new Error(
144 `Failed to load config from "": Config path cannot be empty`,
145 );
146 }
147
148 try {
149 const result = await initialize(authConfig, configPath);
150 // Inject rules into the config if provided
151 if (rules && rules.length > 0) {
152 result.config = await injectRulesIntoConfig(result.config, rules);
153 }
154 return { ...result, wasOnboarded: false };
155 } catch (error) {
156 // If user explicitly provided --config flag, fail loudly instead of falling back
157 const errorMessage =
158 error instanceof Error ? error.message : String(error);
159 throw new Error(
160 `Failed to load config from "${configPath}": ${errorMessage}`,
161 );
162 }
163 }
164
165 // Step 2: If user is logged in, look for first assistant in selected org
166 if (isAuthenticated()) {
167 try {
168 const result = await initialize(authConfig, undefined);
169 // Inject rules into the config if provided
170 if (rules && rules.length > 0) {
171 result.config = await injectRulesIntoConfig(result.config, rules);
172 }
173 return { ...result, wasOnboarded: false };
174 } catch {
175 // Silently ignore errors when loading default assistant
176 }
177 }
178
179 // Step 3: Look for local ~/.continue/config.yaml
180 if (fs.existsSync(CONFIG_PATH)) {
181 try {
182 const result = await initialize(authConfig, CONFIG_PATH);
183 // Inject rules into the config if provided
184 if (rules && rules.length > 0) {
185 result.config = await injectRulesIntoConfig(result.config, rules);
186 }
187 return { ...result, wasOnboarded: false };
188 } catch {
189 console.log(chalk.yellow("⚠ Invalid config file found"));
190 }
191 }
192
193 // Step 4: Look for ANTHROPIC_API_KEY in environment
194 if (process.env.ANTHROPIC_API_KEY) {
195 console.log(chalk.blue("✓ Using ANTHROPIC_API_KEY from environment"));
196 await createOrUpdateConfig(process.env.ANTHROPIC_API_KEY);
197 console.log(chalk.gray(` Config saved to: ${CONFIG_PATH}`));
198 const result = await initialize(authConfig, CONFIG_PATH);
199 // Inject rules into the config if provided
200 if (rules && rules.length > 0) {
201 result.config = await injectRulesIntoConfig(result.config, rules);
202 }
203 return { ...result, wasOnboarded: false };
204 }
205
206 // Step 5: Fall back to onboarding flow
207 return runOnboardingFlow(configPath, authConfig);
208}
209
210export async function isFirstTime(): Promise<boolean> {
211 return !fs.existsSync(path.join(env.continueHome, ".onboarding_complete"));
212}
213
214export async function markOnboardingComplete(): Promise<void> {
215 const flagPath = path.join(env.continueHome, ".onboarding_complete");
216 const flagDir = path.dirname(flagPath);
217
218 if (!fs.existsSync(flagDir)) {
219 fs.mkdirSync(flagDir, { recursive: true });
220 }
221
222 fs.writeFileSync(flagPath, new Date().toISOString());
223}
224
225/**
226 * Process rules and inject them into the assistant config
227 * @param config - The assistant config to modify
228 * @param rules - Array of rule specifications to process and inject
229 * @returns The modified config with injected rules
230 */
231async function injectRulesIntoConfig(
232 config: AssistantUnrolled,
233 rules: string[],
234): Promise<AssistantUnrolled> {
235 if (!rules || rules.length === 0) {
236 return config;
237 }
238
239 const processedRules: string[] = [];
240 for (const ruleSpec of rules) {
241 try {
242 const processedRule = await processPromptOrRule(ruleSpec);
243 processedRules.push(processedRule);
244 } catch (error: any) {
245 console.warn(
246 chalk.yellow(
247 `Warning: Failed to process rule "${ruleSpec}": ${error.message}`,
248 ),
249 );
250 }
251 }
252
253 if (processedRules.length === 0) {
254 return config;
255 }
256
257 // Clone the config to avoid mutating the original
258 const modifiedConfig = { ...config };
259
260 // Add processed rules to the config's rules array
261 // Each processed rule is a string, which is a valid Rule type
262 const existingRules = modifiedConfig.rules || [];
263 modifiedConfig.rules = [...existingRules, ...processedRules];
264
265 return modifiedConfig;
266}
267
268export async function initializeWithOnboarding(
269 authConfig: AuthConfig,
270 configPath: string | undefined,
271 rules?: string[],
272): Promise<OnboardingResult> {
273 const firstTime = await isFirstTime();
274
275 let result: OnboardingResult;
276
277 if (firstTime) {
278 result = await runOnboardingFlow(configPath, authConfig);
279 if (result.wasOnboarded) {
280 await markOnboardingComplete();
281 }
282 } else {
283 result = await runNormalFlow(authConfig, configPath, rules);
284 }
285
286 // Inject rules into the config if provided (for onboarding flow which doesn't handle rules directly)
287 if (rules && rules.length > 0 && !result.wasOnboarded) {
288 result.config = await injectRulesIntoConfig(result.config, rules);
289 }
290
291 return result;
292}