Elffuss BraidHub

kikocis/continue public

b4ebb5b5ebbb · 6.8 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 { handleInfoSlashCommand } from "./infoScreen.js";
11import { reloadService, SERVICE_NAMES, services } from "./services/index.js";
12import { getCurrentSession } from "./session.js";
13import { posthogService } from "./telemetry/posthogService.js";
14import { SlashCommandResult } from "./ui/hooks/useChat.types.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 handleFork() {
119 posthogService.capture("useSlashCommand", { name: "fork" });
120
121 try {
122 const currentSession = getCurrentSession();
123 const forkCommand = `cn --fork ${currentSession.sessionId}`;
124 // Try to copy to clipboard dynamically to avoid hard dependency in tests
125 try {
126 const clipboardy = await import("clipboardy");
127 await clipboardy.default.write(forkCommand);
128 return {
129 exit: false,
130 output: chalk.gray(`${forkCommand} (copied to clipboard)`),
131 };
132 } catch {
133 return {
134 exit: false,
135 output: chalk.gray(`${forkCommand}`),
136 };
137 }
138 } catch (error: any) {
139 return {
140 exit: false,
141 output: chalk.red(`Failed to create fork command: ${error.message}`),
142 };
143 }
144}
145
146const commandHandlers: Record<string, CommandHandler> = {
147 help: handleHelp,
148 clear: () => {
149 posthogService.capture("useSlashCommand", { name: "clear" });
150 return { clear: true, output: "Chat history cleared" };
151 },
152 exit: () => {
153 posthogService.capture("useSlashCommand", { name: "exit" });
154 return { exit: true, output: "Goodbye!" };
155 },
156 config: () => {
157 posthogService.capture("useSlashCommand", { name: "config" });
158 return { openConfigSelector: true };
159 },
160 login: handleLogin,
161 logout: handleLogout,
162 whoami: handleWhoami,
163 info: handleInfoSlashCommand,
164 model: () => ({ openModelSelector: true }),
165 compact: () => {
166 posthogService.capture("useSlashCommand", { name: "compact" });
167 return { compact: true };
168 },
169 mcp: () => {
170 posthogService.capture("useSlashCommand", { name: "mcp" });
171 return { openMcpSelector: true };
172 },
173 resume: () => {
174 posthogService.capture("useSlashCommand", { name: "resume" });
175 return { openSessionSelector: true };
176 },
177 fork: handleFork,
178};
179
180export async function handleSlashCommands(
181 input: string,
182 assistant: AssistantConfig,
183): Promise<{
184 output?: string;
185 exit?: boolean;
186 newInput?: string;
187 clear?: boolean;
188 openConfigSelector?: boolean;
189 openModelSelector?: boolean;
190 openMCPSelector?: boolean;
191 openSessionSelector?: boolean;
192 compact?: boolean;
193} | null> {
194 // Only trigger slash commands if slash is the very first character
195 if (!input.startsWith("/") || !input.trim().startsWith("/")) {
196 return null;
197 }
198
199 const [command, ...args] = input.slice(1).split(" ");
200
201 const handler = commandHandlers[command];
202 if (handler) {
203 return await handler(args, assistant);
204 }
205
206 // Check for custom assistant prompts
207 const assistantPrompt = assistant.prompts?.find(
208 (prompt) => prompt?.name === command,
209 );
210 if (assistantPrompt) {
211 const newInput = assistantPrompt.prompt + args.join(" ");
212 return { newInput };
213 }
214
215 // Check if this command would match any available commands (same logic as UI)
216 const allCommands = getAllSlashCommands(assistant);
217 const hasMatches = allCommands.some((cmd) =>
218 cmd.name.toLowerCase().includes(command.toLowerCase()),
219 );
220
221 // If no commands match, treat this as regular text instead of an unknown command
222 if (!hasMatches) {
223 return null;
224 }
225
226 return { output: `Unknown command: ${command}` };
227}