Elffuss BraidHub

kikocis/continue public

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