Elffuss BraidHub

kikocis/continue public

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