Elffuss BraidHub

kikocis/continue public

d84bb435539f · 7.0 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 { telemetryService } from "./telemetry/telemetryService.js";
15import { SlashCommandResult } from "./ui/hooks/useChat.types.js";
16
17type CommandHandler = (
18 args: string[],
19 assistant: AssistantConfig,
20) => Promise<SlashCommandResult> | SlashCommandResult;
21
22async function handleHelp(_args: string[], _assistant: AssistantConfig) {
23 const helpMessage = [
24 chalk.bold("Keyboard Shortcuts:"),
25 "",
26 chalk.white("Navigation:"),
27 ` ${chalk.cyan("↑/↓")} Navigate command/file suggestions or history`,
28 ` ${chalk.cyan("Tab")} Complete command or file selection`,
29 ` ${chalk.cyan("Enter")} Submit message`,
30 ` ${chalk.cyan("Shift+Enter")} New line`,
31 ` ${chalk.cyan("\\")} Line continuation (at end of line)`,
32 ` ${chalk.cyan("!")} Shell mode - run shell commands`,
33 "",
34 chalk.white("Controls:"),
35 ` ${chalk.cyan("Ctrl+C")} Clear input`,
36 ` ${chalk.cyan("Ctrl+D")} Exit application`,
37 ` ${chalk.cyan("Ctrl+L")} Clear screen`,
38 ` ${chalk.cyan("Shift+Tab")} Cycle permission modes (normal/plan/auto)`,
39 ` ${chalk.cyan("Esc")} Cancel streaming or close suggestions`,
40 "",
41 chalk.white("Special Characters:"),
42 ` ${chalk.cyan("@")} Search and attach files for context`,
43 ` ${chalk.cyan("/")} Access slash commands`,
44 ` ${chalk.cyan("!")} Execute bash commands directly`,
45 "",
46 chalk.white("Available Commands:"),
47 ` Type ${chalk.cyan("/")} to see available slash commands`,
48 ` Type ${chalk.cyan("!")} followed by a command to execute bash directly`,
49 ].join("\n");
50 posthogService.capture("useSlashCommand", { name: "help" });
51 return { output: helpMessage };
52}
53
54async function handleLogin() {
55 posthogService.capture("useSlashCommand", { name: "login" });
56 try {
57 const newAuthState = await services.auth.login();
58 await reloadService(SERVICE_NAMES.AUTH);
59
60 const userInfo =
61 newAuthState.authConfig && isAuthenticatedConfig(newAuthState.authConfig)
62 ? newAuthState.authConfig.userEmail || newAuthState.authConfig.userId
63 : "user";
64
65 console.info(chalk.green(`\nLogged in as ${userInfo}`));
66
67 return {
68 exit: false,
69 output: "Login successful! All services updated automatically.",
70 };
71 } catch (error: any) {
72 console.error(chalk.red(`\nLogin failed: ${error.message}`));
73 return {
74 exit: false,
75 output: `Login failed: ${error.message}`,
76 };
77 }
78}
79
80async function handleLogout() {
81 posthogService.capture("useSlashCommand", { name: "logout" });
82 try {
83 await services.auth.logout();
84 return {
85 exit: true,
86 output: "Logged out successfully",
87 };
88 } catch {
89 return {
90 exit: true,
91 output: "Logged out successfully",
92 };
93 }
94}
95
96function handleWhoami() {
97 posthogService.capture("useSlashCommand", { name: "whoami" });
98 if (isAuthenticated()) {
99 const config = loadAuthConfig();
100 if (config && isAuthenticatedConfig(config)) {
101 return {
102 exit: false,
103 output: `Logged in as ${config.userEmail || config.userId}`,
104 };
105 } else {
106 return {
107 exit: false,
108 output: "Authenticated via environment variable",
109 };
110 }
111 } else {
112 return {
113 exit: false,
114 output: "Not logged in. Use /login to authenticate.",
115 };
116 }
117}
118
119async function handleFork() {
120 posthogService.capture("useSlashCommand", { name: "fork" });
121
122 try {
123 const currentSession = getCurrentSession();
124 const forkCommand = `cn --fork ${currentSession.sessionId}`;
125 // Try to copy to clipboard dynamically to avoid hard dependency in tests
126 try {
127 const clipboardy = await import("clipboardy");
128 await clipboardy.default.write(forkCommand);
129 return {
130 exit: false,
131 output: chalk.gray(`${forkCommand} (copied to clipboard)`),
132 };
133 } catch {
134 return {
135 exit: false,
136 output: chalk.gray(`${forkCommand}`),
137 };
138 }
139 } catch (error: any) {
140 return {
141 exit: false,
142 output: chalk.red(`Failed to create fork command: ${error.message}`),
143 };
144 }
145}
146
147const commandHandlers: Record<string, CommandHandler> = {
148 help: handleHelp,
149 clear: () => {
150 posthogService.capture("useSlashCommand", { name: "clear" });
151 return { clear: true, output: "Chat history cleared" };
152 },
153 exit: () => {
154 posthogService.capture("useSlashCommand", { name: "exit" });
155 return { exit: true, output: "Goodbye!" };
156 },
157 config: () => {
158 posthogService.capture("useSlashCommand", { name: "config" });
159 return { openConfigSelector: true };
160 },
161 login: handleLogin,
162 logout: handleLogout,
163 whoami: handleWhoami,
164 info: handleInfoSlashCommand,
165 model: () => ({ openModelSelector: true }),
166 compact: () => {
167 posthogService.capture("useSlashCommand", { name: "compact" });
168 return { compact: true };
169 },
170 mcp: () => {
171 posthogService.capture("useSlashCommand", { name: "mcp" });
172 return { openMcpSelector: true };
173 },
174 resume: () => {
175 posthogService.capture("useSlashCommand", { name: "resume" });
176 return { openSessionSelector: true };
177 },
178 fork: handleFork,
179};
180
181export async function handleSlashCommands(
182 input: string,
183 assistant: AssistantConfig,
184): Promise<{
185 output?: string;
186 exit?: boolean;
187 newInput?: string;
188 clear?: boolean;
189 openConfigSelector?: boolean;
190 openModelSelector?: boolean;
191 openMCPSelector?: boolean;
192 openSessionSelector?: boolean;
193 compact?: boolean;
194} | null> {
195 // Only trigger slash commands if slash is the very first character
196 if (!input.startsWith("/") || !input.trim().startsWith("/")) {
197 return null;
198 }
199
200 const [command, ...args] = input.slice(1).split(" ");
201
202 telemetryService.recordSlashCommand(command);
203 posthogService.capture("useSlashCommand", { name: command });
204
205 const handler = commandHandlers[command];
206 if (handler) {
207 return await handler(args, assistant);
208 }
209
210 // Check for custom assistant prompts
211 const assistantPrompt = assistant.prompts?.find(
212 (prompt) => prompt?.name === command,
213 );
214 if (assistantPrompt) {
215 const newInput = assistantPrompt.prompt + args.join(" ");
216 return { newInput };
217 }
218
219 // Check if this command would match any available commands (same logic as UI)
220 const allCommands = getAllSlashCommands(assistant);
221 const hasMatches = allCommands.some((cmd) =>
222 cmd.name.toLowerCase().includes(command.toLowerCase()),
223 );
224
225 // If no commands match, treat this as regular text instead of an unknown command
226 if (!hasMatches) {
227 return null;
228 }
229
230 return { output: `Unknown command: ${command}` };
231}