Elffuss BraidHub

kikocis/continue public

4e7d29ea58e1 · 7.4 KiBRawPermalink
1import { type AssistantConfig } from "@continuedev/sdk";
2import chalk from "chalk";
3
4import {
5 isAuthenticated,
6 isAuthenticatedConfig,
7 loadAuthConfig,
8} from "./auth/workos.js";
9import { getAllSlashCommands } from "./commands/commands.js";
10import { reloadService, SERVICE_NAMES, services } from "./services/index.js";
11import { getSessionFilePath } from "./session.js";
12import { posthogService } from "./telemetry/posthogService.js";
13import { SlashCommandResult } from "./ui/hooks/useChat.types.js";
14import { getVersion } from "./version.js";
15
16type CommandHandler = (
17 args: string[],
18 assistant: AssistantConfig,
19) => Promise<SlashCommandResult> | SlashCommandResult;
20
21async function handleHelp(args: string[], assistant: AssistantConfig) {
22 const allCommands = getAllSlashCommands(assistant);
23 const helpMessage = [
24 "Slash commands:",
25 ...allCommands
26 .sort((a, b) => a.name.localeCompare(b.name))
27 .map(
28 (cmd) =>
29 `- ${chalk.white(`/${cmd.name}:`)} ${chalk.gray(cmd.description)}`,
30 ),
31 ].join("\n");
32 posthogService.capture("useSlashCommand", { name: "help" });
33 return { output: helpMessage };
34}
35
36async function handleLogin() {
37 posthogService.capture("useSlashCommand", { name: "login" });
38 try {
39 const newAuthState = await services.auth.login();
40 await reloadService(SERVICE_NAMES.AUTH);
41
42 const userInfo =
43 newAuthState.authConfig && isAuthenticatedConfig(newAuthState.authConfig)
44 ? newAuthState.authConfig.userEmail || newAuthState.authConfig.userId
45 : "user";
46
47 console.info(chalk.green(`\nLogged in as ${userInfo}`));
48
49 return {
50 exit: false,
51 output: "Login successful! All services updated automatically.",
52 };
53 } catch (error: any) {
54 console.error(chalk.red(`\nLogin failed: ${error.message}`));
55 return {
56 exit: false,
57 output: `Login failed: ${error.message}`,
58 };
59 }
60}
61
62async function handleLogout() {
63 posthogService.capture("useSlashCommand", { name: "logout" });
64 try {
65 await services.auth.logout();
66 return {
67 exit: true,
68 output: "Logged out successfully",
69 };
70 } catch {
71 return {
72 exit: true,
73 output: "Logged out successfully",
74 };
75 }
76}
77
78function handleWhoami() {
79 posthogService.capture("useSlashCommand", { name: "whoami" });
80 if (isAuthenticated()) {
81 const config = loadAuthConfig();
82 if (config && isAuthenticatedConfig(config)) {
83 return {
84 exit: false,
85 output: `Logged in as ${config.userEmail || config.userId}`,
86 };
87 } else {
88 return {
89 exit: false,
90 output: "Authenticated via environment variable",
91 };
92 }
93 } else {
94 return {
95 exit: false,
96 output: "Not logged in. Use /login to authenticate.",
97 };
98 }
99}
100
101async function handleInfo() {
102 posthogService.capture("useSlashCommand", { name: "info" });
103
104 const infoLines = [];
105
106 // Version and working directory info
107 const version = getVersion();
108 const cwd = process.cwd();
109
110 infoLines.push(chalk.white("CLI Information:"));
111 infoLines.push(` Version: ${chalk.green(version)}`);
112 infoLines.push(` Working Directory: ${chalk.blue(cwd)}`);
113
114 // Auth info
115 if (isAuthenticated()) {
116 const config = loadAuthConfig();
117 if (config && isAuthenticatedConfig(config)) {
118 const email = config.userEmail || config.userId;
119 const org = "(no org)"; // Organization info not available in AuthenticatedConfig
120 infoLines.push("");
121 infoLines.push(chalk.white("Authentication:"));
122 infoLines.push(` Email: ${chalk.green(email)}`);
123 infoLines.push(` Organization: ${chalk.cyan(org)}`);
124 } else {
125 infoLines.push("");
126 infoLines.push(chalk.white("Authentication:"));
127 infoLines.push(
128 ` ${chalk.yellow("Authenticated via environment variable")}`,
129 );
130 }
131 } else {
132 infoLines.push("");
133 infoLines.push(chalk.white("Authentication:"));
134 infoLines.push(` ${chalk.red("Not logged in")}`);
135 }
136
137 // Config info
138 try {
139 const configState = services.config.getState();
140 infoLines.push("");
141 infoLines.push(chalk.white("Configuration:"));
142 if (configState.config) {
143 infoLines.push(` ${chalk.gray(`Using ${configState.config?.name}`)}`);
144 } else {
145 infoLines.push(` ${chalk.red(`Config not found`)}`);
146 }
147 if (configState.configPath) {
148 infoLines.push(` Path: ${chalk.blue(configState.configPath)}`);
149 }
150
151 // Add current model info
152 try {
153 const modelInfo = services.model?.getModelInfo();
154 if (modelInfo) {
155 infoLines.push(` Model: ${chalk.cyan(modelInfo.name)}`);
156 } else {
157 infoLines.push(` Model: ${chalk.red("Not available")}`);
158 }
159 } catch {
160 infoLines.push(` Model: ${chalk.red("Error retrieving model info")}`);
161 }
162 } catch {
163 infoLines.push("");
164 infoLines.push(chalk.white("Configuration:"));
165 infoLines.push(` ${chalk.red("Configuration service not available")}`);
166 }
167
168 // Session history path
169 infoLines.push("");
170 infoLines.push(chalk.white("Session History:"));
171 const sessionFilePath = getSessionFilePath();
172
173 infoLines.push(` File: ${chalk.blue(sessionFilePath)}`);
174
175 return {
176 exit: false,
177 output: infoLines.join("\n"),
178 };
179}
180
181const commandHandlers: Record<string, CommandHandler> = {
182 help: handleHelp,
183 clear: () => {
184 posthogService.capture("useSlashCommand", { name: "clear" });
185 return { clear: true, output: "Chat history cleared" };
186 },
187 exit: () => {
188 posthogService.capture("useSlashCommand", { name: "exit" });
189 return { exit: true, output: "Goodbye!" };
190 },
191 config: () => {
192 posthogService.capture("useSlashCommand", { name: "config" });
193 return { openConfigSelector: true };
194 },
195 login: handleLogin,
196 logout: handleLogout,
197 whoami: handleWhoami,
198 info: handleInfo,
199 model: () => ({ openModelSelector: true }),
200 compact: () => {
201 posthogService.capture("useSlashCommand", { name: "compact" });
202 return { compact: true };
203 },
204 mcp: () => {
205 posthogService.capture("useSlashCommand", { name: "mcp" });
206 return { openMcpSelector: true };
207 },
208 resume: () => {
209 posthogService.capture("useSlashCommand", { name: "resume" });
210 return { openSessionSelector: true };
211 },
212};
213
214export async function handleSlashCommands(
215 input: string,
216 assistant: AssistantConfig,
217): Promise<{
218 output?: string;
219 exit?: boolean;
220 newInput?: string;
221 clear?: boolean;
222 openConfigSelector?: boolean;
223 openModelSelector?: boolean;
224 openMCPSelector?: boolean;
225 openSessionSelector?: boolean;
226 compact?: boolean;
227} | null> {
228 // Only trigger slash commands if slash is the very first character
229 if (!input.startsWith("/") || !input.trim().startsWith("/")) {
230 return null;
231 }
232
233 const [command, ...args] = input.slice(1).split(" ");
234
235 const handler = commandHandlers[command];
236 if (handler) {
237 return await handler(args, assistant);
238 }
239
240 // Check for custom assistant prompts
241 const assistantPrompt = assistant.prompts?.find(
242 (prompt) => prompt?.name === command,
243 );
244 if (assistantPrompt) {
245 const newInput = assistantPrompt.prompt + args.join(" ");
246 return { newInput };
247 }
248
249 // Check if this command would match any available commands (same logic as UI)
250 const allCommands = getAllSlashCommands(assistant);
251 const hasMatches = allCommands.some((cmd) =>
252 cmd.name.toLowerCase().includes(command.toLowerCase()),
253 );
254
255 // If no commands match, treat this as regular text instead of an unknown command
256 if (!hasMatches) {
257 return null;
258 }
259
260 return { output: `Unknown command: ${command}` };
261}