Elffuss BraidHub

kikocis/continue public

fb08fd5cc0fe Ā· 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";
7import * as readlineSync from "readline-sync";
8
9import { env } from "./env.js";
10import {
11 isValidAnthropicApiKey,
12 getApiKeyValidationError,
13} from "./util/apiKeyValidation.js";
14import { gracefulExit } from "./util/exit.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 = readlineSync.question(chalk.yellow("\nEnter choice (1): "), {
56 limit: ["1", "2", ""],
57 limitMessage: chalk.dim("Please enter 1 or 2"),
58 });
59
60 if (choice === "1" || choice === "") {
61 // Option 1: Open models setup page
62 const modelsUrl = new URL("setup-models", env.appUrl).toString();
63 console.log(chalk.blue(`Opening ${modelsUrl}...`));
64
65 try {
66 await open(modelsUrl);
67 console.log(chalk.green("\nāœ“ Browser opened successfully!"));
68 console.log(
69 chalk.dim(
70 "After setting up your models subscription, restart the CLI to continue.",
71 ),
72 );
73 } catch {
74 console.log(chalk.yellow("\n⚠ Could not open browser automatically"));
75 console.log(chalk.white(`Please visit: ${modelsUrl}`));
76 console.log(
77 chalk.dim(
78 "After setting up your models subscription, restart the CLI to continue.",
79 ),
80 );
81 }
82
83 // Wait for user to acknowledge
84 readlineSync.question(chalk.dim("\nPress Enter to exit..."));
85 await gracefulExit(0);
86 } else if (choice === "2") {
87 // Option 2: Enter Anthropic API key
88 const apiKey = readlineSync.question(
89 chalk.white("\nEnter your Anthropic API key: "),
90 {
91 hideEchoBack: true,
92 },
93 );
94
95 if (!isValidAnthropicApiKey(apiKey)) {
96 console.log(chalk.red(`āŒ ${getApiKeyValidationError(apiKey)}`));
97 await gracefulExit(1);
98 }
99
100 try {
101 await createOrUpdateConfig(apiKey);
102 console.log(chalk.green(`āœ“ API key saved successfully!`));
103 console.log(chalk.green("āœ“ Switching to local configuration..."));
104
105 // If a reload callback is provided, use it instead of restarting
106 if (onReload) {
107 await onReload();
108 return;
109 }
110 } catch (error) {
111 console.log(chalk.red(`āŒ Error saving API key: ${error}`));
112 await gracefulExit(1);
113 }
114 }
115
116 // Fallback: restart the CLI if no reload callback was provided
117 console.log(
118 chalk.green(
119 "\nšŸ”„ Restarting Continue CLI to resume your conversation...\n",
120 ),
121 );
122
123 // Get the path to the current script
124 const scriptPath = path.resolve(process.argv[1]);
125
126 // Restart the CLI with the same arguments, except for the first two (node and script path)
127 // Use spawn instead of spawnSync, since we want to exit this process
128 const child = spawn(
129 process.execPath,
130 [scriptPath, ...process.argv.slice(2)],
131 {
132 stdio: "inherit",
133 detached: true,
134 },
135 );
136
137 // Unref the child to allow the parent process to exit
138 child.unref();
139
140 // Exit the current process
141 await gracefulExit(0);
142}