Elffuss BraidHub

kikocis/continue public

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