Elffuss BraidHub

kikocis/continue public

7a512fed920f Ā· 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 { updateAnthropicModelInYaml } from "./util/yamlConfigUpdater.js";
15
16const CONFIG_PATH = path.join(env.continueHome, "config.yaml");
17
18/**
19 * Creates or updates the local config with Anthropic API key
20 */
21async function createOrUpdateConfig(apiKey: string): Promise<void> {
22 const configDir = path.dirname(CONFIG_PATH);
23
24 if (!fs.existsSync(configDir)) {
25 fs.mkdirSync(configDir, { recursive: true });
26 }
27
28 const existingContent = fs.existsSync(CONFIG_PATH)
29 ? fs.readFileSync(CONFIG_PATH, "utf8")
30 : "";
31
32 const updatedContent = updateAnthropicModelInYaml(existingContent, apiKey);
33 fs.writeFileSync(CONFIG_PATH, updatedContent);
34}
35
36/**
37 * Handles the free trial transition flow for users who have maxed out their free trial
38 * This function provides a specialized flow that:
39 * 1. Assumes the user is already authenticated
40 * 2. Provides two specific options for continuing
41 * 3. Returns to the chat without restarting the entire CLI
42 */
43export async function handleMaxedOutFreeTrial(
44 onReload?: () => Promise<void>,
45): Promise<void> {
46 // Clear the screen but don't show ASCII art - keep it minimal since we're resuming a conversation
47 console.clear();
48
49 console.log(chalk.yellow("šŸš€ Free trial limit reached!\n"));
50 console.log("Choose how you'd like to Continue:");
51 console.log(chalk.white("1. šŸ’³ Sign up for models add-on"));
52 console.log(chalk.white("2. šŸ”‘ Enter your Anthropic API key"));
53
54 const choice = readlineSync.question(chalk.yellow("\nEnter choice (1): "), {
55 limit: ["1", "2", ""],
56 limitMessage: chalk.dim("Please enter 1 or 2"),
57 });
58
59 if (choice === "1" || choice === "") {
60 // Option 1: Open models setup page
61 const modelsUrl = new URL("setup-models", env.appUrl).toString();
62 console.log(chalk.blue(`Opening ${modelsUrl}...`));
63
64 try {
65 await open(modelsUrl);
66 console.log(chalk.green("\nāœ“ Browser opened successfully!"));
67 console.log(
68 chalk.dim(
69 "After setting up your models subscription, restart the CLI to continue.",
70 ),
71 );
72 } catch {
73 console.log(chalk.yellow("\n⚠ Could not open browser automatically"));
74 console.log(chalk.white(`Please visit: ${modelsUrl}`));
75 console.log(
76 chalk.dim(
77 "After setting up your models subscription, restart the CLI to continue.",
78 ),
79 );
80 }
81
82 // Wait for user to acknowledge
83 readlineSync.question(chalk.dim("\nPress Enter to exit..."));
84 process.exit(0);
85 } else if (choice === "2") {
86 // Option 2: Enter Anthropic API key
87 const apiKey = readlineSync.question(
88 chalk.white("\nEnter your Anthropic API key: "),
89 {
90 hideEchoBack: true,
91 },
92 );
93
94 if (!isValidAnthropicApiKey(apiKey)) {
95 console.log(chalk.red(`āŒ ${getApiKeyValidationError(apiKey)}`));
96 process.exit(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 process.exit(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 process.exit(0);
141}