Elffuss BraidHub

kikocis/continue public

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