Elffuss BraidHub

kikocis/continue public

main Ā· 4.3 KiBRawPermalink
1import { spawn } from "child_process";
2import * as fs from "fs";
3import * as path from "path";
4
5import chalk from "chalk";
6import open from "open";
7
8import { env } from "./env.js";
9import {
10 getApiKeyValidationError,
11 isValidAnthropicApiKey,
12} from "./util/apiKeyValidation.js";
13import { gracefulExit } from "./util/exit.js";
14import { question, questionWithChoices } from "./util/prompt.js";
15import { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js";
16
17const CONFIG_PATH = path.join(env.continueHome, "config.yaml");
18
19/**
20 * Creates or updates the local config with Anthropic API key
21 */
22async function createOrUpdateConfig(apiKey: string): Promise<void> {
23 const configDir = path.dirname(CONFIG_PATH);
24
25 if (!fs.existsSync(configDir)) {
26 fs.mkdirSync(configDir, { recursive: true });
27 }
28
29 const existingContent = fs.existsSync(CONFIG_PATH)
30 ? fs.readFileSync(CONFIG_PATH, "utf8")
31 : "";
32
33 const updatedContent = updateAnthropicModelInYaml(existingContent, apiKey);
34 fs.writeFileSync(CONFIG_PATH, updatedContent);
35}
36
37/**
38 * Handles the free trial transition flow for users who have maxed out their free trial
39 * This function provides a specialized flow that:
40 * 1. Assumes the user is already authenticated
41 * 2. Provides two specific options for continuing
42 * 3. Returns to the chat without restarting the entire CLI
43 */
44export async function handleMaxedOutFreeTrial(
45 onReload?: () => Promise<void>,
46): Promise<void> {
47 // Clear the screen but don't show ASCII art - keep it minimal since we're resuming a conversation
48 console.clear();
49
50 console.log(chalk.yellow("šŸš€ Free trial limit reached!\n"));
51 console.log("Choose how you'd like to Continue:");
52 console.log(chalk.white("1. šŸ’³ Sign up for models add-on"));
53 console.log(chalk.white("2. šŸ”‘ Enter your Anthropic API key"));
54
55 const choice = await questionWithChoices(
56 chalk.yellow("\nEnter choice (1): "),
57 ["1", "2", ""],
58 "1",
59 chalk.dim("Please enter 1 or 2"),
60 );
61
62 if (choice === "1" || choice === "") {
63 // Option 1: Open models setup page
64 const modelsUrl = new URL("setup-models", env.appUrl).toString();
65 console.log(chalk.blue(`Opening ${modelsUrl}...`));
66
67 try {
68 await open(modelsUrl);
69 console.log(chalk.green("\nāœ“ Browser opened successfully!"));
70 console.log(
71 chalk.dim(
72 "After setting up your models subscription, restart the CLI to continue.",
73 ),
74 );
75 } catch {
76 console.log(chalk.yellow("\n⚠ Could not open browser automatically"));
77 console.log(chalk.white(`Please visit: ${modelsUrl}`));
78 console.log(
79 chalk.dim(
80 "After setting up your models subscription, restart the CLI to continue.",
81 ),
82 );
83 }
84
85 // Wait for user to acknowledge
86 await question(chalk.dim("\nPress Enter to exit..."));
87 await gracefulExit(0);
88 } else if (choice === "2") {
89 // Option 2: Enter Anthropic API key
90 const apiKey = await question(
91 chalk.white("\nEnter your Anthropic API key: "),
92 );
93
94 if (!isValidAnthropicApiKey(apiKey)) {
95 console.log(chalk.red(`āŒ ${getApiKeyValidationError(apiKey)}`));
96 await gracefulExit(1);
97 }
98
99 try {
100 await createOrUpdateConfig(apiKey);
101 console.log(chalk.green(`āœ“ API key saved successfully!`));
102 console.log(chalk.green("āœ“ Switching to local configuration..."));
103
104 // If a reload callback is provided, use it instead of restarting
105 if (onReload) {
106 await onReload();
107 return;
108 }
109 } catch (error) {
110 console.log(chalk.red(`āŒ Error saving API key: ${error}`));
111 await gracefulExit(1);
112 }
113 }
114
115 // Fallback: restart the CLI if no reload callback was provided
116 console.log(
117 chalk.green(
118 "\nšŸ”„ Restarting Continue CLI to resume your conversation...\n",
119 ),
120 );
121
122 // Get the path to the current script
123 const scriptPath = path.resolve(process.argv[1]);
124
125 // Restart the CLI with the same arguments, except for the first two (node and script path)
126 // Use spawn instead of spawnSync, since we want to exit this process
127 const child = spawn(
128 process.execPath,
129 [scriptPath, ...process.argv.slice(2)],
130 {
131 stdio: "inherit",
132 detached: true,
133 },
134 );
135
136 // Unref the child to allow the parent process to exit
137 child.unref();
138
139 // Exit the current process
140 await gracefulExit(0);
141}